ifc_lite_core/limits/
complex_property.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//! The `IfcComplexProperty` walk policy (#7675): its bounds, markers and
6//! every charge, re-exported as `ifc_lite_core::limits::*`.
7//!
8//! The walk has three copies that must write the same value for the same
9//! file: the server's data model
10//! (`rust/processing/src/data_model/property_value.rs`), the Rust STEP
11//! exporter's property base (`ifc_lite_export` `step_log/base_complex.rs`)
12//! and the browser's store pass (`packages/parser/src/complex-property-store.ts`
13//! over `property-complex-value.ts`). The two Rust copies take every bound,
14//! marker and charge from here; the TypeScript twin mirrors
15//! [`ComplexPropertyBudget`] method for method, and one shared vector
16//! (`packages/parser/test/fixtures/complex-property-budget-7675.json`) pins
17//! all three.
18//!
19//! A lean file, one with no geometry to dilute the input, cuts sooner than a
20//! typical model: at a 120-member shared property, or at 10 distinct
21//! 256-byte texts per element over 3 000 elements.
22
23use std::collections::HashMap;
24
25/// How deep an `IfcComplexProperty`'s `HasProperties` walk descends. A member
26/// past it is not read; its value says so with
27/// [`complex_property_depth_marker`].
28pub const MAX_COMPLEX_PROPERTY_DEPTH: usize = 8;
29
30/// Nested members one top-level complex property may read across all its
31/// levels. The depth cap bounds a path's LENGTH only: a member listing itself
32/// `k` times is `k^8` reads. Output accumulates (the same member down two
33/// branches is two real parts), so a visited set would drop real members; a
34/// work budget is the right bound (AGENTS.md "Bounding walks").
35pub const MAX_COMPLEX_PROPERTY_MEMBERS: usize = 1024;
36
37/// The floor of a model's complex-property output budget
38/// ([`complex_property_output_budget`]), so a small file can still carry
39/// ordinary complex properties in full.
40pub const COMPLEX_PROPERTY_OUTPUT_BYTES: usize = 1 << 20;
41
42/// Output bytes a model's complex properties may cost per input byte, above
43/// the [`COMPLEX_PROPERTY_OUTPUT_BYTES`] floor. The first listing of a
44/// complex property costs its walk: each member's entry
45/// ([`COMPLEX_PROPERTY_MEMBER_BYTES`]), name and value, its part, and the
46/// joined level, about three times what it keeps. A repeat listing costs
47/// only what it keeps ([`complex_property_listing_bytes`]). 16 is the
48/// server's material-row policy too, and keeps one 20-member property shared
49/// by 3 000 sets (the shape a de-duplicating optimiser writes, 664 KB in,
50/// about 2.5 MB charged) whole with room to spare. What it binds is reuse
51/// past that: one 1 KB value listed a thousand times by each of a thousand
52/// properties built 685 MB from 10.7 KB (#7675); that is now the floor.
53pub const COMPLEX_PROPERTY_BYTES_PER_INPUT_BYTE: usize = 16;
54
55/// What a read member costs before its text: its `members` / `values` entry.
56/// Without it a member with a name but no value would be free, and one walk
57/// could retain a member object per visit for every property in the model.
58pub const COMPLEX_PROPERTY_MEMBER_BYTES: usize = 16;
59
60/// The output budget of ONE model's complex properties: `input_bytes` times
61/// [`COMPLEX_PROPERTY_BYTES_PER_INPUT_BYTE`], at least
62/// [`COMPLEX_PROPERTY_OUTPUT_BYTES`].
63///
64/// Scope, identical in every copy: one budget per model (the server's
65/// extraction, the exporter's `BaseSets`, the browser's `IfcDataStore`),
66/// spent on every `IfcComplexProperty` listed by an `IfcPropertySet`, in file
67/// order of the sets and then `HasProperties` order. A set id is read once,
68/// at its LAST record in the file, the record core's entity index resolves
69/// the id to (keep-last, #7682); an earlier record with the id is not a set.
70/// A complex property id is walked once, at its first listing; every later
71/// listing reuses that value through [`ComplexPropertyBudget::listing`]. A
72/// value is therefore the same whichever entity asks for it first, and no
73/// number of entities sharing a set multiplies the output.
74pub fn complex_property_output_budget(input_bytes: usize) -> usize {
75    input_bytes
76        .saturating_mul(COMPLEX_PROPERTY_BYTES_PER_INPUT_BYTE)
77        .max(COMPLEX_PROPERTY_OUTPUT_BYTES)
78}
79
80/// What one listing of a resolved complex property keeps: its `value`, and
81/// per entry of its `values` list the entry ([`COMPLEX_PROPERTY_MEMBER_BYTES`])
82/// and its text. A repeat listing is charged exactly this.
83pub fn complex_property_listing_bytes<S: AsRef<str>>(value: &str, values: &[S]) -> usize {
84    values
85        .iter()
86        .fold(value.len(), |n, v| n.saturating_add(COMPLEX_PROPERTY_MEMBER_BYTES + v.as_ref().len()))
87}
88
89/// Appended to a complex property cut by [`MAX_COMPLEX_PROPERTY_DEPTH`].
90pub fn complex_property_depth_marker() -> String {
91    format!("(truncated: nesting deeper than {MAX_COMPLEX_PROPERTY_DEPTH} levels)")
92}
93
94/// The value of a level cut by [`ComplexPropertyBudget`]: its parts so far,
95/// then this marker. The usage name is not repeated, so a reference to a
96/// complex property past the budget costs the marker and nothing else. A walk
97/// that keeps a member list (`values`, the browser's `members`) ends a cut
98/// level's list with this marker too, so a member past the cut reads as
99/// truncated rather than absent. A repeat listing refused by
100/// [`ComplexPropertyBudget::listing`] reads as a cut level with no parts.
101pub const COMPLEX_PROPERTY_BUDGET_MARKER: &str = "(truncated: nested properties over the walk budget)";
102
103/// The walk state every `IfcComplexProperty` walker charges: member visits for
104/// the current top-level property, output bytes for the whole model
105/// ([`complex_property_output_budget`]), and how many levels it cut.
106///
107/// Check order, identical in every copy, and every charge is made HERE so the
108/// copies cannot drift: [`Self::listing`] for each listing a set makes;
109/// within a first listing's walk, [`Self::admit_member`] before reading a
110/// member, [`Self::member_part`] once the member is read (charges its entry,
111/// and its part when it has a display), and [`Self::level_value`] once the
112/// level's members are done (charges the joined value, and only a value that
113/// has parts).
114#[derive(Debug, Clone)]
115pub struct ComplexPropertyBudget {
116    visits: usize,
117    bytes_left: usize,
118    cuts: usize,
119}
120
121impl ComplexPropertyBudget {
122    /// A scope that may build `output_bytes` of text.
123    pub fn new(output_bytes: usize) -> Self {
124        Self { visits: 0, bytes_left: output_bytes, cuts: 0 }
125    }
126
127    /// The budget of one model whose source is `input_bytes` long.
128    pub fn for_input(input_bytes: usize) -> Self {
129        Self::new(complex_property_output_budget(input_bytes))
130    }
131
132    /// One listing of complex property `id` by a set. The first listing of an
133    /// id calls `resolve`, which starts the property and walks it against
134    /// this budget, and returns the value with its
135    /// [`complex_property_listing_bytes`]; `memo` keeps both. A later listing
136    /// reuses the value, charged its listing bytes, or reads `spent()` (a
137    /// counted cut) once the budget is spent. Memoised per id, not per
138    /// listing: a repeat costs what it keeps, not a fresh walk.
139    ///
140    /// A repeat listing is admitted while any budget is left and charged in
141    /// full, so one admitted with almost nothing left overshoots: the total
142    /// stays under the budget plus one listing.
143    pub fn listing<V: Clone>(
144        &mut self,
145        memo: &mut HashMap<u32, (V, usize)>,
146        id: u32,
147        resolve: impl FnOnce(&mut Self) -> (V, usize),
148        spent: impl FnOnce() -> V,
149    ) -> V {
150        if let Some((value, bytes)) = memo.get(&id) {
151            if self.bytes_left == 0 {
152                self.cuts += 1;
153                return spent();
154            }
155            self.charge(*bytes);
156            return value.clone();
157        }
158        let (value, bytes) = resolve(self);
159        memo.insert(id, (value.clone(), bytes));
160        value
161    }
162
163    /// Start a top-level property: its member visits start at zero, the byte
164    /// budget carries on.
165    pub fn start_property(&mut self) {
166        self.visits = 0;
167    }
168
169    /// Whether one more member may be read, counting it if so.
170    pub fn admit_member(&mut self) -> bool {
171        if self.visits >= MAX_COMPLEX_PROPERTY_MEMBERS || self.bytes_left == 0 {
172            return false;
173        }
174        self.visits += 1;
175        true
176    }
177
178    /// A member that was read, under `name` (empty without one) with
179    /// `display` (empty when it has no value): charge its entry, and return
180    /// the `"Name: value"` part (bare `value` without a name), charged too,
181    /// or `None` when there is no display to show. A member without a name is
182    /// still read for its value, in every copy.
183    pub fn member_part(&mut self, name: &str, display: &str) -> Option<String> {
184        self.charge(COMPLEX_PROPERTY_MEMBER_BYTES + name.len() + display.len());
185        if display.is_empty() {
186            return None;
187        }
188        let part = if name.is_empty() { display.to_string() } else { format!("{name}: {display}") };
189        self.charge(part.len());
190        Some(part)
191    }
192
193    /// A level's value from its parts, `cut` when [`Self::admit_member`]
194    /// refused one of its members: the parts joined with `", "` (then the
195    /// budget marker when cut), the bare marker when cut with no parts, or
196    /// `None` (the caller's bare `UsageName`) when nothing resolved. Only a
197    /// value with parts is charged; the bare marker is bounded by the members
198    /// admitted to reach it.
199    pub fn level_value(&mut self, parts: &[String], cut: bool) -> Option<String> {
200        if cut {
201            self.cuts += 1;
202        }
203        if parts.is_empty() {
204            return cut.then(|| COMPLEX_PROPERTY_BUDGET_MARKER.to_string());
205        }
206        let joined = parts.join(", ");
207        let value = if cut { format!("{joined} {COMPLEX_PROPERTY_BUDGET_MARKER}") } else { joined };
208        self.charge(value.len());
209        Some(value)
210    }
211
212    /// Levels and listings this budget has cut so far (D3: counted, and
213    /// logged by the walk's owner, never silent).
214    pub fn cuts(&self) -> usize {
215        self.cuts
216    }
217
218    fn charge(&mut self, bytes: usize) {
219        self.bytes_left = self.bytes_left.saturating_sub(bytes);
220    }
221}
222
223#[cfg(test)]
224#[path = "complex_property_tests.rs"]
225mod tests;