ifc_lite_processing/data_model/rooted.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Which rows the data model's entities table carries (issue #6034).
6//!
7//! Its own module because it is a WIRE CONTRACT as much as a filter: the parse
8//! routes read it off the query, the data-model cache key is built from it, the
9//! fetch route selects by it, and the client sends it. One definition keeps
10//! those four in step, the same shape as `parquet_layout.rs`.
11
12use super::slots::RootSlots;
13use super::types::{
14 ClassificationAssociation, DataModel, DocumentAssociation, EntityJob, MaterialAssociation,
15 PropertySet, QuantitySet, Relationship, SpatialHierarchyData,
16};
17use rustc_hash::{FxHashMap, FxHashSet};
18use std::borrow::Cow;
19
20/// Which STEP instances the data model's entities table carries.
21///
22/// OPT-IN, defaulting to [`Self::All`], because the default table is a public
23/// payload: a client that looks up a non-rooted instance by id (an
24/// `IfcCartesianPoint`, an `IfcPropertySingleValue`) keeps working, and a
25/// default request writes and reads exactly the bytes it did before #6034.
26///
27/// [`Self::Rooted`] is for the clients that only ever look up objects. On a
28/// large architectural model about five in six entity rows are geometry and
29/// property plumbing with no GlobalId (`IfcPolyLoop`, `IfcFace`,
30/// `IfcCartesianPoint`, `IfcPropertySingleValue`, ...), none of which another
31/// table of the data model points at: property values are already flattened
32/// into the properties table, quantities into the quantities table.
33///
34/// The two variants are cached under separate keys (see
35/// `routes::parse::cache_keys::data_model_cache_key`), so a warm cache can
36/// never answer one with the other.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize)]
38pub enum DataModelEntities {
39 /// Every STEP instance in the file. The only behaviour before #6034.
40 #[default]
41 #[serde(rename = "all")]
42 All,
43 /// Only rooted entities (`IfcRoot` subtypes, the ones carrying a
44 /// GlobalId), plus every non-rooted instance another table of the same
45 /// data model references by id, so no relation dangles. See
46 /// [`retain_rooted_entities`].
47 #[serde(rename = "rooted")]
48 Rooted,
49}
50
51impl DataModelEntities {
52 /// The data-model cache-key infix naming this variant. Empty for
53 /// [`Self::All`], so a default request keeps hitting the entries already
54 /// on disk.
55 pub fn cache_infix(self) -> &'static str {
56 match self {
57 Self::All => "",
58 Self::Rooted => "-rooted",
59 }
60 }
61
62 /// Narrow `data_model`'s entities table to this variant. A no-op for
63 /// [`Self::All`]; every other table is left untouched either way.
64 pub fn apply(self, data_model: &mut DataModel) {
65 if self == Self::Rooted {
66 retain_rooted_entities(data_model);
67 }
68 }
69}
70
71/// Keep the entity rows a rooted-only client can need, dropping the rest.
72///
73/// A row is kept when EITHER
74/// - it is rooted: it carries a GlobalId, or its type is one the schema
75/// registry says declares one (an `IfcRoot` subtype whose GlobalId the file
76/// left empty is still an object); or
77/// - another table of this data model references its id: a material, a
78/// material layer set or usage (`materials.definition_id` /
79/// `material_id`), the `RelatingMaterial` / `RelatingClassification` /
80/// `RelatingDocument` of an `IfcRelAssociates*` row, and so on.
81///
82/// The second rule is what keeps every relation resolvable. Without it the
83/// relationships table would name `IfcMaterial` and `IfcClassificationReference`
84/// ids the entities table no longer describes, and a client resolving a
85/// relation's endpoint to its type or name through the entities table would
86/// find nothing. They are few, so keeping them costs nothing measurable; the
87/// rows this drops are the ones nothing points at.
88///
89/// `entity_id`s are untouched, and the kept rows stay in file order.
90pub(crate) fn retain_rooted_entities(data_model: &mut DataModel) {
91 let referenced = referenced_ids(data_model);
92 // Types are few (hundreds) and rows are many (millions), so the registry
93 // lookup runs once per type.
94 let mut rooted_type: FxHashMap<String, bool> = FxHashMap::default();
95 let keep: Vec<bool> = data_model
96 .entities
97 .iter()
98 .map(|entity| {
99 if entity.global_id.is_some() || referenced.contains(&entity.entity_id) {
100 return true;
101 }
102 if let Some(&rooted) = rooted_type.get(entity.type_name.as_str()) {
103 return rooted;
104 }
105 let rooted = declares_global_id(&entity.type_name);
106 rooted_type.insert(entity.type_name.clone(), rooted);
107 rooted
108 })
109 .collect();
110 let mut keep = keep.into_iter();
111 // `retain` visits every element exactly once, in order.
112 data_model
113 .entities
114 .retain(|_| keep.next().unwrap_or(true));
115}
116
117/// Whether the schema registry lists `type_name` as declaring a GlobalId,
118/// i.e. as an `IfcRoot` subtype. A type the registry does not know answers
119/// `false`: for those the extracted `global_id` (read at the `IfcRoot`
120/// position by the metadata fallback) is the only evidence there is.
121fn declares_global_id(type_name: &str) -> bool {
122 RootSlots::declares_global_id(type_name)
123}
124
125/// Every entity id another table of `data_model` points at. `0` is the
126/// tables' "none" (a root spatial node's parent, a synthetic relationship's
127/// `rel_id`), never an instance, so it is skipped.
128fn referenced_ids(data_model: &DataModel) -> FxHashSet<u32> {
129 let mut ids = FxHashSet::default();
130 collect_table_refs(TableRefs::of(data_model), &mut ids);
131 collect_spatial_refs(&data_model.spatial_hierarchy, &mut ids);
132 ids
133}
134
135/// The tables that can name a non-rooted instance, borrowed together.
136///
137/// Borrowed rather than read off a [`DataModel`] because the pre-filter
138/// ([`metadata_jobs`]) has to consult them BEFORE a `DataModel` exists -- the
139/// entities table it is deciding is the one that would go into it. One type
140/// and one collector serve both callers, so the rule for "which non-rooted
141/// rows must survive" cannot drift between them.
142#[derive(Clone, Copy)]
143pub(crate) struct TableRefs<'a> {
144 pub(crate) property_sets: &'a [PropertySet],
145 pub(crate) quantity_sets: &'a [QuantitySet],
146 pub(crate) relationships: &'a [Relationship],
147 pub(crate) classifications: &'a [ClassificationAssociation],
148 pub(crate) materials: &'a [MaterialAssociation],
149 pub(crate) documents: &'a [DocumentAssociation],
150}
151
152impl<'a> TableRefs<'a> {
153 fn of(data_model: &'a DataModel) -> Self {
154 Self {
155 property_sets: &data_model.property_sets,
156 quantity_sets: &data_model.quantity_sets,
157 relationships: &data_model.relationships,
158 classifications: &data_model.classifications,
159 materials: &data_model.materials,
160 documents: &data_model.documents,
161 }
162 }
163}
164
165/// Every id `tables` names. THE one policy; both filters call it.
166fn collect_table_refs(tables: TableRefs<'_>, ids: &mut FxHashSet<u32>) {
167 let mut add = |id: u32| {
168 if id != 0 {
169 ids.insert(id);
170 }
171 };
172 for rel in tables.relationships {
173 add(rel.rel_id);
174 add(rel.relating_id);
175 add(rel.related_id);
176 }
177 for pset in tables.property_sets {
178 add(pset.pset_id);
179 }
180 for qset in tables.quantity_sets {
181 add(qset.qset_id);
182 }
183 for row in tables.classifications {
184 add(row.element_id);
185 }
186 // `definition_id` and `material_id` are the non-rooted ones: an
187 // `IfcMaterial` or an `IfcMaterialLayerSet` carries no GlobalId, and no
188 // other table names it.
189 for row in tables.materials {
190 add(row.element_id);
191 add(row.association_id);
192 add(row.definition_id);
193 if let Some(material_id) = row.material_id {
194 add(material_id);
195 }
196 }
197 for row in tables.documents {
198 add(row.element_id);
199 }
200}
201
202/// Every id the spatial hierarchy names.
203///
204/// The pre-filter does NOT call this, and cannot: the hierarchy is built from
205/// the entities table it is deciding. It does not have to, because every id
206/// reachable here is already kept for another reason -- see the proof on
207/// [`metadata_jobs`], and `rooted_tests.rs`, which asserts the whole
208/// `SpatialHierarchyData` is identical on both paths.
209fn collect_spatial_refs(spatial: &SpatialHierarchyData, ids: &mut FxHashSet<u32>) {
210 let mut add = |id: u32| {
211 if id != 0 {
212 ids.insert(id);
213 }
214 };
215 add(spatial.project_id);
216 for node in &spatial.nodes {
217 add(node.entity_id);
218 add(node.parent_id);
219 node.children_ids.iter().for_each(|&id| add(id));
220 node.element_ids.iter().for_each(|&id| add(id));
221 }
222 for lookup in [
223 &spatial.element_to_storey,
224 &spatial.element_to_building,
225 &spatial.element_to_site,
226 &spatial.element_to_space,
227 ] {
228 for &(element, container) in lookup {
229 add(element);
230 add(container);
231 }
232 }
233}
234
235/// The jobs whose metadata a narrowed extraction still has to build, so the
236/// rest are never materialised. [`DataModelEntities::All`] borrows the full
237/// list: the default path does not copy a job.
238///
239/// # What this decides, and with what
240///
241/// [`retain_rooted_entities`] decides per EXTRACTED ROW, which knows whether a
242/// GlobalId was actually present. Here only the type name is known, so the
243/// test is deliberately WIDER in one place: a type the IFC4 registry does not
244/// list is kept, because for those the extracted GlobalId is the only evidence
245/// there is (`RootSlots::UNKNOWN_TYPE_FALLBACK` reads slot 0) and dropping
246/// them here would lose rows the post-filter keeps. Vendor extensions are the
247/// realistic unknown type and they are rare; a file made entirely of them
248/// simply costs what the unfiltered path costs today.
249///
250/// `retain_rooted_entities` then runs on the much smaller table and applies
251/// the exact rule, so the two paths agree row for row.
252///
253/// # Why this is safe without the spatial tables
254///
255/// [`referenced_ids`] -- the post-filter's retained set -- also includes
256/// `spatial_hierarchy`, which does not exist yet here. It does not need to,
257/// because the hierarchy can only name ids this filter already keeps:
258///
259/// - `project_id`, and every id in `spatial_entity_ids`, is an entity whose
260/// type is in `spatial.rs`'s spatial-type list. Every one of those is an
261/// `IfcRoot` subtype, so it is kept by type (or, for the IFC4X3 ones the
262/// IFC4 registry does not list, kept as an unknown type).
263/// - every other id the builder touches -- a node's `parent_id`, its
264/// `children_ids`, its `element_ids`, and both halves of every
265/// `element_to_*` pair -- is read from `IfcRelAggregates` /
266/// `IfcRelContainedInSpatialStructure` rows, so it is a `relating_id` or a
267/// `related_id` of the relationships table, which `collect_table_refs`
268/// keeps.
269///
270/// So the spatial build also sees the same answers from the narrowed table it
271/// saw from the full one: every id it looks up in its `entity_map` is a
272/// relationship endpoint or a spatial-typed row. `rooted_tests.rs` asserts
273/// that empirically on real models and on disconnected and malformed spatial
274/// fixtures, rather than resting on this argument.
275///
276/// # The ordering condition
277///
278/// The caller must have built EVERY other table in `tables` first,
279/// associations included. That is not hypothetical: while the association
280/// pass still ran after this one, the catalogued models lost every non-rooted
281/// `IfcMaterial` the materials table points at -- 24 rows on
282/// `ara3d/AC20-FZK-Haus.ifc`, 88 on `ara3d/ISSUE_068_ARK_NUS_skolebygg.ifc` --
283/// because nothing had yet recorded that they were referenced.
284pub(crate) fn metadata_jobs<'j, 'a>(
285 entities: DataModelEntities,
286 all_entities: &'j [EntityJob<'a>],
287 tables: TableRefs<'_>,
288) -> Cow<'j, [EntityJob<'a>]> {
289 if entities == DataModelEntities::All {
290 return Cow::Borrowed(all_entities);
291 }
292
293 let mut referenced = FxHashSet::default();
294 collect_table_refs(tables, &mut referenced);
295 // Types are few (hundreds) and rows are many (millions), so the registry
296 // lookup runs once per type rather than once per row.
297 let mut keep_type: FxHashMap<&str, bool> = FxHashMap::default();
298 Cow::Owned(
299 all_entities
300 .iter()
301 .filter(|job| {
302 if referenced.contains(&job.id) {
303 return true;
304 }
305 *keep_type
306 .entry(job.type_name)
307 .or_insert_with(|| may_carry_global_id(job.type_name))
308 })
309 .copied()
310 .collect(),
311 )
312}
313
314/// Whether a row of this type could survive [`retain_rooted_entities`] on its
315/// GlobalId alone.
316///
317/// Derived from [`declares_global_id`], the post-filter's own predicate,
318/// rather than restating it: that one answers `false` for BOTH "known to IFC4
319/// and declares no GlobalId" and "not in the registry at all", and only the
320/// first of those is a reason to drop a row before it exists. For the second,
321/// the metadata pass falls back to `RootSlots::UNKNOWN_TYPE_FALLBACK` and
322/// reads slot 0, so only the extracted row can say.
323fn may_carry_global_id(type_name: &str) -> bool {
324 declares_global_id(type_name) || RootSlots::for_type(type_name).is_none()
325}
326
327#[cfg(test)]
328#[path = "rooted_tests.rs"]
329mod tests;