Skip to main content

ifc_geometry/lower/
session.rs

1//! One recursive lowering session over one shared graph builder.
2//!
3//! # Why a session exists
4//!
5//! Recursive lowering appends to a single session-owned builder, and family
6//! lowerers return [`NodeId`] instead of freezing isolated child graphs
7//! (`tests/lower_session.rs` pins this). That is not a style preference: a [`NodeId`]
8//! is owned by the graph that minted it, so handles from two independently
9//! finished graphs are mutually foreign. Every composite IFC family needs two
10//! children in one graph:
11//!
12//! - `IfcBooleanResult` references two operands,
13//! - `IfcMappedItem` reuses one source under many transforms,
14//! - a B-rep face set shares one surface across many faces,
15//! - `IfcCsgSolid` nests operations arbitrarily deep.
16//!
17//! The session also carries the model and resolved unit scale that every
18//! lowerer needs. Approximation policy is deliberately absent: lowering emits
19//! exact neutral geometry, while execution providers own tessellation tolerance.
20//!
21//! # What it guarantees
22//!
23//! - **One graph.** All nodes land in one builder, so any two lowered results
24//!   are composable.
25//! - **Memoization.** A shared IFC entity lowered under the same frame yields
26//!   the same node instead of a duplicate subtree.
27//! - **Bounded recursion.** Cyclic and over-deep chains produce typed errors
28//!   rather than a stack overflow.
29//! - **Located failures.** Graph construction faults are translated into
30//!   [`GeometryError`] values that name the offending IFC entity.
31
32use std::collections::BTreeMap;
33
34use axiolid_model::{GeometryGraphBuilder, GeometryNode, GraphError, NodeId};
35use ifc_model::{EntityId, Model};
36
37#[cfg(feature = "compile")]
38use crate::constraint::placement::CachedPositionPolicy;
39use crate::constraint::placement::LinearResolution;
40use crate::error::{GeometryError, GeometryResult};
41use crate::lower::{LoweredGeometry, ProvenanceMap};
42use crate::slots::Slots;
43use crate::transform::Transform;
44use crate::units::UnitScale;
45
46/// Recursion budget for chained IFC references.
47///
48/// IFC places no normative limit on placement or mapped-item nesting, so a
49/// budget is the only way to terminate on malformed input that is deep rather
50/// than strictly cyclic.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct SessionLimits {
53    /// Maximum simultaneously active entities in one chain.
54    pub max_depth: usize,
55    /// Maximum elements one file-declared aggregate may materialize.
56    pub max_aggregate_elements: usize,
57}
58
59impl SessionLimits {
60    /// Depth budget used when a caller states no preference.
61    ///
62    /// Real exporter output nests placements a few levels deep; 64 is far
63    /// above observed depth while still terminating quickly on bad input.
64    pub const DEFAULT_MAX_DEPTH: usize = 64;
65
66    /// Aggregate-element budget used when a caller states no preference.
67    ///
68    /// Sized against the largest thing a legitimate file plausibly declares:
69    /// a dense triangulated face set of ~5.5M triangles expands to 16M
70    /// indices, and the largest observed knot vectors are four orders of
71    /// magnitude smaller. 16M `f64` is ~128 MiB, which bounds a single
72    /// aggregate to something a workstation survives while still refusing the
73    /// billion-element declarations that motivate this budget.
74    ///
75    /// This is a refusal threshold, never a truncation point: an aggregate
76    /// over the limit produces [`crate::GeometryError::AggregateTooLarge`]
77    /// naming the entity, and no geometry is emitted for it.
78    pub const DEFAULT_MAX_AGGREGATE_ELEMENTS: usize = 16_777_216;
79}
80
81impl Default for SessionLimits {
82    fn default() -> Self {
83        Self {
84            max_depth: Self::DEFAULT_MAX_DEPTH,
85            max_aggregate_elements: Self::DEFAULT_MAX_AGGREGATE_ELEMENTS,
86        }
87    }
88}
89
90/// What lowering does with an `IfcPolyLoop` face bound that collapses (#46).
91///
92/// A poly loop "collapses" when fewer than three of its implied edges join
93/// two different points, e.g. `(A, A, B, B)`: it encloses no area, so it
94/// cannot bound a face. Authoring tools emit such sliver faces routinely.
95///
96/// The test is exactly the one the refusal applies, so
97/// [`DropAndReport`](Self::DropAndReport) drops precisely the faces that
98/// [`Refuse`](Self::Refuse) would have refused over, and nothing else.
99#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
100#[non_exhaustive]
101pub enum DegenerateFacePolicy {
102    /// Refuse the whole representation item with
103    /// [`GeometryError::Degenerate`] naming
104    /// the loop. The default: a file that says a face exists is not silently
105    /// contradicted.
106    #[default]
107    Refuse,
108    /// Leave the face out and record it in
109    /// [`ProvenanceMap::dropped_faces`](crate::lower::ProvenanceMap::dropped_faces).
110    ///
111    /// Only a face whose OUTER bound (or only bound) collapses is dropped:
112    /// that face covers no area, so omitting it removes no surface. A
113    /// collapsed inner bound of a face that still has a valid outer bound is
114    /// still refused, because dropping the face there would remove real area.
115    ///
116    /// Dropping a face can leave a shell open; the backend's own closure
117    /// check still decides whether the result is a solid.
118    DropAndReport,
119}
120
121/// Identity of one lowering result, used to deduplicate shared entities.
122///
123/// The frame is part of the key. Two `IfcMappedItem`s reusing one source under
124/// different transforms are different results, and collapsing them would place
125/// geometry at one location only. Floats are keyed by bit pattern so the key is
126/// totally ordered without imposing a tolerance policy: memoization must be an
127/// exact-identity optimization, never a geometric approximation.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
129struct MemoKey {
130    entity: u64,
131    family: &'static str,
132    basis: [[u64; 3]; 3],
133    origin: [u64; 3],
134}
135
136impl MemoKey {
137    fn new(entity: EntityId, family: &'static str, frame: Transform) -> Self {
138        Self {
139            entity: entity.0,
140            family,
141            basis: frame.basis.map(|axis| axis.map(f64::to_bits)),
142            origin: frame.origin.map(f64::to_bits),
143        }
144    }
145}
146
147/// A single recursive lowering pass over one shared graph builder.
148///
149/// Family lowerers take `&mut LoweringSession` and return [`NodeId`]. Only the
150/// public entry point calls [`LoweringSession::finish`].
151#[derive(Debug)]
152pub struct LoweringSession<'a> {
153    model: &'a Model,
154    units: &'a UnitScale,
155    limits: SessionLimits,
156    builder: GeometryGraphBuilder,
157    nodes: usize,
158    memo: BTreeMap<MemoKey, NodeId>,
159    active: Vec<EntityId>,
160    provenance: ProvenanceMap,
161    /// `MappedTo` face set -> its `IfcIndexedTriangleTextureMap`s, built on
162    /// first use. Maps point at face sets, not the other way round, so
163    /// finding a face set's map means a scan; doing it once per session
164    /// keeps lowering linear in the file.
165    texture_maps: Option<BTreeMap<EntityId, Vec<EntityId>>>,
166    /// What each appended node is, structurally, for net lowering (#44).
167    ///
168    /// A boolean operand must be a solid, and the graph validator rejects a
169    /// `Collection` (or an `Instance` of one) there. Net lowering therefore
170    /// has to split a multi-item body into its solid parts, which needs to
171    /// see node kinds before the graph is frozen. Recording them at push time
172    /// costs one small entry per node and avoids re-walking the builder.
173    shapes: BTreeMap<NodeId, NodeShape>,
174    /// Every atomic curve appended, kept for station lowering (#307).
175    ///
176    /// A station names a distance along its basis, and IFC gives a station
177    /// on a tangent discontinuity the PREVIOUS segment's tangent while the
178    /// neutral evaluators read the next one. Seeing where the basis's seams
179    /// are, and its stated length, needs the curve's stored data, which the
180    /// append-only builder does not hand back.
181    curves: BTreeMap<NodeId, AtomicCurve>,
182    /// Every curve relation and node placed at a station appended, kept
183    /// for station lowering along a relation basis (#346): the seams of a
184    /// composite are its joints, at running sums of its pieces' lengths,
185    /// which only the stored relation states.
186    relations: BTreeMap<NodeId, GeometryNode>,
187    /// What to do with a collapsed poly-loop face (#46).
188    face_policy: DegenerateFacePolicy,
189    /// How a product's `IfcLinearPlacement` is resolved (#353).
190    linear: LinearResolution<'a>,
191    /// What to do with a cached `CartesianPosition` once an evaluator is
192    /// supplied (#354).
193    #[cfg(feature = "compile")]
194    cached_positions: CachedPositionPolicy,
195}
196
197/// The structural kind of a node, as net lowering needs it.
198#[derive(Debug, Clone, PartialEq)]
199pub(crate) enum NodeShape {
200    /// Merges its members; not itself a boolean operand.
201    Collection(Vec<NodeId>),
202    /// Reuses `source` under `transform`.
203    Instance {
204        /// The reused node.
205        source: NodeId,
206        /// Local-to-parent transform.
207        transform: axiolid_core::Transform3,
208    },
209    /// A family the graph validator admits as a boolean operand.
210    Solid,
211    /// A curve, a curve relation or an open profile: compiled to a
212    /// polyline, never to a mesh (#458).
213    Curve,
214    /// Anything else: surfaces, closed profiles, points.
215    Other,
216}
217
218/// An appended atomic curve, 2D or 3D, as stored.
219#[derive(Debug, Clone, PartialEq)]
220pub(crate) enum AtomicCurve {
221    /// A `GeometryNode::Curve2`.
222    Two(axiolid_curve::Curve2),
223    /// A `GeometryNode::Curve3`.
224    Three(axiolid_curve::Curve3),
225}
226
227impl AtomicCurve {
228    fn of(node: &GeometryNode) -> Option<Self> {
229        match node {
230            GeometryNode::Curve2(curve) => Some(Self::Two(curve.clone())),
231            GeometryNode::Curve3(curve) => Some(Self::Three(curve.clone())),
232            _ => None,
233        }
234    }
235}
236
237/// A copy of `node` when it is a curve relation or a node placed at a
238/// station, the relations a station basis is flattened through (#346).
239fn relation_of(node: &GeometryNode) -> Option<GeometryNode> {
240    matches!(
241        node,
242        GeometryNode::CurveRelation(_) | GeometryNode::InstanceAtStation(_)
243    )
244    .then(|| node.clone())
245}
246
247impl NodeShape {
248    fn of(node: &GeometryNode) -> Self {
249        match node {
250            GeometryNode::Collection(members) => Self::Collection(members.clone()),
251            GeometryNode::Instance(instance) => Self::Instance {
252                source: instance.source,
253                transform: instance.transform,
254            },
255            // Mirrors axiolid-model's `ExpectedReference::Solid`.
256            GeometryNode::Primitive(_)
257            | GeometryNode::HalfSpace(_)
258            | GeometryNode::SolidOperation(_)
259            | GeometryNode::BRep(_)
260            | GeometryNode::PolygonMesh(_)
261            | GeometryNode::TriMesh(_) => Self::Solid,
262            GeometryNode::Curve2(_)
263            | GeometryNode::Curve3(_)
264            | GeometryNode::CurveRelation(_)
265            | GeometryNode::OpenProfile(_) => Self::Curve,
266            _ => Self::Other,
267        }
268    }
269}
270
271impl<'a> LoweringSession<'a> {
272    /// Open a session with the default recursion budget.
273    pub fn new(model: &'a Model, units: &'a UnitScale) -> Self {
274        Self::with_limits(model, units, SessionLimits::default())
275    }
276
277    /// Open a session with an explicit recursion budget.
278    pub fn with_limits(model: &'a Model, units: &'a UnitScale, limits: SessionLimits) -> Self {
279        Self {
280            model,
281            units,
282            limits,
283            builder: GeometryGraphBuilder::new(),
284            nodes: 0,
285            memo: BTreeMap::new(),
286            active: Vec::new(),
287            provenance: ProvenanceMap::default(),
288            texture_maps: None,
289            shapes: BTreeMap::new(),
290            curves: BTreeMap::new(),
291            relations: BTreeMap::new(),
292            face_policy: DegenerateFacePolicy::default(),
293            linear: LinearResolution::cache_only(),
294            #[cfg(feature = "compile")]
295            cached_positions: CachedPositionPolicy::default(),
296        }
297    }
298
299    /// Derive an uncached `IfcLinearPlacement` through `evaluator` (#353).
300    ///
301    /// Builder-style, like [`Self::with_face_policy`], so every product
302    /// entry point that takes the session -- `lower_product_items`,
303    /// `lower_product_representation`, `lower_product_net` and its openings'
304    /// own placements -- places products along an alignment the same way.
305    /// Without it, a session reads only the cached `CartesianPosition` and
306    /// refuses a placement without one, as before. The evaluator is the
307    /// caller's: this crate links no implementation (ADR 0004, ADR 0012).
308    ///
309    /// A cached position is then checked against the derived one unless
310    /// [`Self::with_cached_position_policy`] says to trust it (#354).
311    #[cfg(feature = "compile")]
312    #[must_use]
313    pub fn with_curve_evaluator(
314        mut self,
315        evaluator: &'a dyn axiolid_curve_evaluate_contract::CurveEvaluator,
316    ) -> Self {
317        self.linear = LinearResolution::derive(evaluator, self.cached_positions);
318        self
319    }
320
321    /// Set what an evaluator-taking session does with a cached
322    /// `CartesianPosition` (#354). Without an evaluator it has no effect.
323    #[cfg(feature = "compile")]
324    #[must_use]
325    pub fn with_cached_position_policy(mut self, policy: CachedPositionPolicy) -> Self {
326        self.cached_positions = policy;
327        if let Some(derivation) = &mut self.linear.derivation {
328            derivation.cached = policy;
329        }
330        self
331    }
332
333    /// Whether this session derives linear placements through an evaluator.
334    pub fn derives_linear_placements(&self) -> bool {
335        #[cfg(feature = "compile")]
336        return self.linear.derivation.is_some();
337        #[cfg(not(feature = "compile"))]
338        false
339    }
340
341    /// How this session resolves a product's `IfcLinearPlacement`.
342    pub(crate) fn linear_resolution(&self) -> LinearResolution<'a> {
343        self.linear
344    }
345
346    /// Set what lowering does with a collapsed poly-loop face (#46).
347    ///
348    /// Builder-style so the default constructors stay unchanged:
349    /// `LoweringSession::new(model, units).with_face_policy(policy)`.
350    #[must_use]
351    pub fn with_face_policy(mut self, policy: DegenerateFacePolicy) -> Self {
352        self.face_policy = policy;
353        self
354    }
355
356    /// The degenerate-face policy in force.
357    pub fn face_policy(&self) -> DegenerateFacePolicy {
358        self.face_policy
359    }
360
361    /// Record a face left out under [`DegenerateFacePolicy::DropAndReport`].
362    pub(crate) fn report_dropped_face(&mut self, face: EntityId) {
363        self.provenance.record_dropped_face(face);
364    }
365
366    /// Record a station lowered with the kernel's seam-snapping window
367    /// (#423): its `IfcPointByDistanceExpression` or
368    /// `IfcAxis2PlacementLinear`.
369    pub(crate) fn record_seam_window(&mut self, station: EntityId) {
370        self.provenance.record_seam_window(station);
371    }
372
373    /// Record that the run `run`'s stations carry the kernel's
374    /// seam-snapping window (#429) or stand at a basis end it measures
375    /// (#433).
376    pub(crate) fn record_seam_window_run(&mut self, run: EntityId) {
377        self.provenance.record_seam_window_run(run);
378    }
379
380    /// The `IfcIndexedTriangleTextureMap`s whose `MappedTo` is `face_set`, in
381    /// file order. Empty for an untextured face set.
382    pub(crate) fn triangle_texture_maps(&mut self, face_set: EntityId) -> &[EntityId] {
383        let model = self.model;
384        let index = self.texture_maps.get_or_insert_with(|| {
385            let mut index: BTreeMap<EntityId, Vec<EntityId>> = BTreeMap::new();
386            // `ids_of_type` yields file order, so each list stays in it.
387            for &map in model.ids_of_type("IFCINDEXEDTRIANGLETEXTUREMAP") {
388                // `MappedTo` is slot 1 in IFC4 and IFC4X3 alike.
389                let target = model
390                    .get(map)
391                    .and_then(|entity| entity.attributes.get(1))
392                    .and_then(ifc_model::Value::as_ref_id);
393                if let Some(target) = target {
394                    index.entry(target).or_default().push(map);
395                }
396            }
397            index
398        });
399        index.get(&face_set).map_or(&[], Vec::as_slice)
400    }
401
402    /// The model being lowered.
403    pub fn model(&self) -> &'a Model {
404        self.model
405    }
406
407    /// The resolved unit scale for this model.
408    pub fn units(&self) -> &'a UnitScale {
409        self.units
410    }
411
412    /// Number of nodes appended so far.
413    ///
414    /// Exposed so tests can assert that a memoized hit appends nothing.
415    pub fn node_count(&self) -> usize {
416        self.nodes
417    }
418
419    /// Append one node, attributing any graph fault to the current entity.
420    pub fn node(&mut self, node: GeometryNode) -> GeometryResult<NodeId> {
421        let source = self.active.last().copied();
422        let shape = NodeShape::of(&node);
423        let curve = AtomicCurve::of(&node);
424        let relation = relation_of(&node);
425        let id = self
426            .builder
427            .push(node)
428            .map_err(|error| graph_error(source.unwrap_or(EntityId(0)), error))?;
429        self.nodes += 1;
430        self.shapes.insert(id, shape);
431        if let Some(curve) = curve {
432            self.curves.insert(id, curve);
433        }
434        if let Some(relation) = relation {
435            self.relations.insert(id, relation);
436        }
437        if let Some(source) = source {
438            self.provenance.record(id, source);
439        }
440        Ok(id)
441    }
442
443    /// Append one node, attributing any graph fault to `entity`.
444    pub fn node_for(&mut self, entity: EntityId, node: GeometryNode) -> GeometryResult<NodeId> {
445        let shape = NodeShape::of(&node);
446        let curve = AtomicCurve::of(&node);
447        let relation = relation_of(&node);
448        let id = self
449            .builder
450            .push(node)
451            .map_err(|error| graph_error(entity, error))?;
452        self.nodes += 1;
453        self.shapes.insert(id, shape);
454        if let Some(curve) = curve {
455            self.curves.insert(id, curve);
456        }
457        if let Some(relation) = relation {
458            self.relations.insert(id, relation);
459        }
460        self.provenance.record(id, entity);
461        Ok(id)
462    }
463
464    /// The structural kind of an appended node; `None` for a foreign id.
465    pub(crate) fn shape(&self, node: NodeId) -> Option<&NodeShape> {
466        self.shapes.get(&node)
467    }
468
469    /// The stored data of an appended atomic curve; `None` for any other
470    /// node, a curve relation included.
471    pub(crate) fn atomic_curve(&self, node: NodeId) -> Option<&AtomicCurve> {
472        self.curves.get(&node)
473    }
474
475    /// The stored data of an appended curve relation or node placed at a
476    /// station; `None` for any other node.
477    pub(crate) fn relation(&self, node: NodeId) -> Option<&GeometryNode> {
478        self.relations.get(&node)
479    }
480
481    /// Source attribution accumulated so far.
482    pub fn provenance(&self) -> &ProvenanceMap {
483        &self.provenance
484    }
485
486    /// Resolve an entity or report the dangling reference against `referrer`.
487    pub fn entity(
488        &self,
489        referrer: EntityId,
490        id: EntityId,
491    ) -> GeometryResult<&'a ifc_model::Entity> {
492        self.model.get(id).ok_or(GeometryError::MissingEntity {
493            referrer,
494            missing: id,
495        })
496    }
497
498    /// Look up a previously lowered result for `entity` under `frame`.
499    pub fn memoized(
500        &self,
501        entity: EntityId,
502        family: &'static str,
503        frame: Transform,
504    ) -> Option<NodeId> {
505        self.memo.get(&MemoKey::new(entity, family, frame)).copied()
506    }
507
508    /// Record the lowered result for `entity` under `frame`.
509    pub fn memoize(
510        &mut self,
511        entity: EntityId,
512        family: &'static str,
513        frame: Transform,
514        node: NodeId,
515    ) {
516        self.memo.insert(MemoKey::new(entity, family, frame), node);
517    }
518
519    /// Mark `entity` as active in the current chain.
520    ///
521    /// Returns [`GeometryError::CyclicChain`] if the entity is already active
522    /// and [`GeometryError::ChainTooDeep`] once the depth budget is exhausted.
523    /// Every successful call must be paired with [`LoweringSession::exit`].
524    pub fn enter(&mut self, entity: EntityId, kind: &'static str) -> GeometryResult<()> {
525        if self.active.contains(&entity) {
526            return Err(GeometryError::CyclicChain { entity, kind });
527        }
528        if self.active.len() >= self.limits.max_depth {
529            return Err(GeometryError::ChainTooDeep {
530                entity,
531                kind,
532                limit: self.limits.max_depth,
533            });
534        }
535        self.active.push(entity);
536        Ok(())
537    }
538
539    /// Release `entity` from the active chain.
540    ///
541    /// Sharing is not recursion: once a subtree is complete the entity must be
542    /// reachable again from a sibling branch.
543    pub fn exit(&mut self, entity: EntityId) {
544        if self.active.last() == Some(&entity) {
545            self.active.pop();
546            return;
547        }
548        debug_assert!(false, "lowering scopes must exit in LIFO order");
549        if let Some(index) = self.active.iter().rposition(|&active| active == entity) {
550            self.active.remove(index);
551        }
552    }
553
554    /// Borrowed attribute view for `entity`.
555    pub fn slots(&self, entity: EntityId) -> GeometryResult<Slots<'a>> {
556        let resolved = self.entity(entity, entity)?;
557        Ok(Slots::new(entity, resolved))
558    }
559
560    /// Upper-cased IFC type name for `entity`.
561    ///
562    /// Dispatch compares against canonical upper-case names because STEP files
563    /// are case-insensitive in practice and exporters disagree.
564    pub fn type_name(&self, entity: EntityId) -> GeometryResult<String> {
565        Ok(self.entity(entity, entity)?.type_name.to_ascii_uppercase())
566    }
567
568    /// Build a typed `Unsupported` error naming the offending entity.
569    pub fn unsupported(
570        &self,
571        entity: EntityId,
572        type_name: &str,
573        detail: &'static str,
574    ) -> GeometryError {
575        GeometryError::Unsupported {
576            entity,
577            type_name: type_name.to_string(),
578            detail,
579        }
580    }
581
582    /// Build a typed `Degenerate` error naming the offending entity.
583    ///
584    /// Structurally impossible geometry is distinct from an unimplemented
585    /// family: the file is understood and the shape does not exist.
586    pub fn degenerate(
587        &self,
588        entity: EntityId,
589        type_name: &str,
590        detail: impl Into<String>,
591    ) -> GeometryError {
592        GeometryError::Degenerate {
593            entity,
594            type_name: type_name.to_string(),
595            detail: detail.into(),
596        }
597    }
598
599    /// Check a file-declared aggregate size against the element budget.
600    ///
601    /// Takes `u128` so an overflowing product (`triangles * 3`) can be
602    /// computed in a wider type and reported honestly instead of wrapping to a
603    /// small number that passes the check. Returns the size as `usize` only
604    /// once it is known to fit.
605    ///
606    /// Call this *before* reserving, not after: the point is to refuse the
607    /// declaration, not to survive the allocation.
608    pub fn check_aggregate(
609        &self,
610        entity: EntityId,
611        type_name: &str,
612        what: &'static str,
613        requested: u128,
614    ) -> GeometryResult<usize> {
615        let limit = self.limits.max_aggregate_elements;
616        if requested > limit as u128 {
617            return Err(GeometryError::AggregateTooLarge {
618                entity,
619                type_name: type_name.to_string(),
620                what,
621                requested,
622                limit,
623            });
624        }
625        Ok(requested as usize)
626    }
627
628    /// Lower a nested operand through the total dispatcher.
629    ///
630    /// Kept on the session so recursive families do not each re-import the
631    /// dispatcher and risk diverging on cycle/limit handling.
632    pub fn lower_operand(&mut self, entity: EntityId, frame: Transform) -> GeometryResult<NodeId> {
633        crate::lower::dispatch::lower_representation_item(self, entity, frame)
634    }
635
636    /// Freeze the graph with `root` as its single output root.
637    pub fn finish(self, root: NodeId) -> GeometryResult<LoweredGeometry> {
638        let entity = self.current_entity();
639        let graph = self
640            .builder
641            .finish(vec![root])
642            .map_err(|error| graph_error(entity, error))?;
643        Ok(LoweredGeometry {
644            graph,
645            root,
646            provenance: self.provenance,
647        })
648    }
649
650    /// Best-effort attribution target for graph faults raised outside a family.
651    fn current_entity(&self) -> EntityId {
652        self.active.last().copied().unwrap_or(EntityId(0))
653    }
654}
655
656/// Translate a graph construction fault into a located IFC error.
657///
658/// A bare [`GraphError`] names a `NodeId`, which is meaningless when debugging
659/// a 500k-entity file; the IFC entity is the addressable unit.
660pub(crate) fn graph_error(entity: EntityId, error: GraphError) -> GeometryError {
661    GeometryError::Degenerate {
662        entity,
663        type_name: "geometry graph".to_string(),
664        detail: error.to_string(),
665    }
666}
667
668#[cfg(test)]
669mod tests {
670    use super::*;
671
672    #[test]
673    fn the_memo_key_separates_entity_family_and_frame() {
674        let frame = Transform::identity();
675        let mut moved = Transform::identity();
676        moved.origin = [1.0, 0.0, 0.0];
677
678        let base = MemoKey::new(EntityId(1), "solid", frame);
679        assert_eq!(base, MemoKey::new(EntityId(1), "solid", frame));
680        assert_ne!(base, MemoKey::new(EntityId(2), "solid", frame));
681        assert_ne!(base, MemoKey::new(EntityId(1), "profile", frame));
682        assert_ne!(base, MemoKey::new(EntityId(1), "solid", moved));
683    }
684
685    #[test]
686    fn signed_zero_does_not_alias_positive_zero_in_the_key() {
687        // -0.0 == 0.0 numerically but has a distinct bit pattern. Keying on
688        // bits keeps memoization an exact-identity optimization.
689        let mut negative = Transform::identity();
690        negative.origin = [-0.0, 0.0, 0.0];
691        assert_ne!(
692            MemoKey::new(EntityId(1), "solid", Transform::identity()),
693            MemoKey::new(EntityId(1), "solid", negative)
694        );
695    }
696
697    #[test]
698    fn the_default_aggregate_budget_is_documented() {
699        assert_eq!(
700            SessionLimits::default().max_aggregate_elements,
701            SessionLimits::DEFAULT_MAX_AGGREGATE_ELEMENTS
702        );
703        assert_eq!(SessionLimits::DEFAULT_MAX_AGGREGATE_ELEMENTS, 16_777_216);
704    }
705
706    #[test]
707    fn the_default_depth_budget_is_documented() {
708        assert_eq!(
709            SessionLimits::default().max_depth,
710            SessionLimits::DEFAULT_MAX_DEPTH
711        );
712    }
713}