Skip to main content

ifc_lite_core/
columnar_index.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//! Columnar entity index — a compact, binary-searched alternative to the
6//! [`EntityIndex`](crate::EntityIndex) `FxHashMap<u32, (usize, usize)>`.
7//!
8//! # Why
9//!
10//! The streaming pre-pass hands every wasm worker (N geometry workers plus the
11//! prepass and parser workers) the same pre-scanned entity index as three
12//! parallel `u32` columns
13//! via `setEntityIndex`. Each worker used to materialize a private
14//! `FxHashMap<u32, (usize, usize)>` from those columns. hashbrown rounds the
15//! bucket count up to the next power of two, so for a 19.1 M-entity model it
16//! allocates `2^25` buckets × ~13 B ≈ **436 MB per worker**, rebuilt in every
17//! realm. Three sorted `Vec<u32>` columns for the same model are
18//! `3 × 19.1 M × 4 B ≈ 229 MB` — no power-of-two rounding, no per-bucket control
19//! byte, no `(usize, usize)` widening. The lookup becomes a `binary_search`
20//! (≈24 probes at 19 M rows) instead of an O(1) hash probe; see the PR for the
21//! measured wall-time delta on the full geometry pipeline.
22//!
23//! # `u32` offsets
24//!
25//! `starts`/`lengths` are `u32`, which is only sound while the source file is
26//! < 4 GiB. WASM ingestion (`setEntityIndex` and `cached_entity_index`) already
27//! lives in that linear address space and delivers `&[u32]` columns. The native
28//! processor also uses this representation for large sources with sparse ids,
29//! after checking their byte length fits `u32`; dense ids may use
30//! [`crate::DenseEntityIndex`]. Wider native sources keep the `usize`-carrying
31//! [`EntityIndex`](crate::EntityIndex) hashmap.
32//!
33//! # Duplicate express ids
34//!
35//! [`crate::build_entity_index`] inserts scanned spans into an `FxHashMap` in
36//! file order, so a repeated express id resolves to its **last** occurrence in
37//! the file (`HashMap::insert` overwrites). Express ids are unique per the STEP
38//! spec and duplicates essentially never occur, but this type replicates the
39//! last-in-file-order-wins behaviour deliberately (see `from_unsorted` and the
40//! `duplicate_id_last_wins` test) so a malformed file cannot diverge between the
41//! hashmap and columnar paths.
42
43use crate::decoder::EntityIndex;
44use crate::parser::EntityScanner;
45use std::sync::Arc;
46
47/// Compact, sorted, binary-searched entity index. Columns are kept sorted by
48/// `ids` (strictly ascending, unique) so [`Self::lookup`] can `binary_search`.
49///
50/// Invariants (upheld by every constructor):
51/// - `ids.len() == starts.len() == lengths.len()`
52/// - `ids` is strictly ascending (hence unique)
53/// - `starts[i]` / `lengths[i]` are the byte offset / byte length of `ids[i]`,
54///   so `lookup` returns `(start, start + length)` to match the `(start, end)`
55///   tuple layout of [`EntityIndex`](crate::EntityIndex).
56pub struct ColumnarEntityIndex {
57    ids: Vec<u32>,
58    starts: Vec<u32>,
59    lengths: Vec<u32>,
60}
61
62impl ColumnarEntityIndex {
63    /// Build from the three delivered columns (`setEntityIndex` ingestion).
64    ///
65    /// Verifies the id column's ordering **once**, O(n): the pre-pass emits in
66    /// whatever order it iterates (its own `FxHashMap` iteration order is
67    /// arbitrary), so this cannot assume ascending. If the ids are already
68    /// strictly ascending the columns are used as-is (no sort); otherwise a
69    /// single stable argsort permutation is applied and duplicate ids are
70    /// collapsed last-in-input-order-wins.
71    ///
72    /// Mismatched column lengths yield an empty index (the wasm caller guards
73    /// this too), so a malformed payload never panics a worker.
74    pub fn from_columns(ids: &[u32], starts: &[u32], lengths: &[u32]) -> Self {
75        let n = ids.len();
76        if n == 0 || starts.len() != n || lengths.len() != n {
77            return Self {
78                ids: Vec::new(),
79                starts: Vec::new(),
80                lengths: Vec::new(),
81            };
82        }
83        if is_strictly_ascending(ids) {
84            // Already sorted AND unique — the common case once the producer
85            // emits sorted columns. No permutation, no dedup: just adopt them.
86            return Self {
87                ids: ids.to_vec(),
88                starts: starts.to_vec(),
89                lengths: lengths.to_vec(),
90            };
91        }
92        Self::from_unsorted(ids.to_vec(), starts.to_vec(), lengths.to_vec())
93    }
94
95    /// Build from an already-scanned [`EntityIndex`](crate::EntityIndex)
96    /// hashmap, CONSUMING it. On the wasm prepass path the map is ~436 MB at
97    /// 19.1 M entities and the conversion runs while the whole source file is
98    /// resident in the same <4 GiB heap; borrowing (`from_hashmap`) keeps the
99    /// map alive across the copy AND the sort, spiking ~970 MB of transients.
100    ///
101    /// Consuming drains into one interleaved `Vec<(id, start, len)>` (~229 MB)
102    /// then sorts in place (`sort_unstable`; map keys are unique, so no
103    /// stability/permutation buffer). Peak during the drain is map + rows
104    /// capacity (~665 MB) until the map drops at end-of-loop; after that the
105    /// sort is in-place and the final column split briefly overlaps rows +
106    /// outputs (~458 MB) before rows drop. Still far below the borrowing path,
107    /// and the steady-state index is ~229 MB.
108    pub fn from_hashmap_consuming(map: EntityIndex) -> Self {
109        let n = map.len();
110        // Reserve while the map is still alive: peak ≈ map + rows (~665 MB at
111        // 19.1 M). Draining without reserve would thrash reallocs for the same
112        // asymptotic peak once the vec fills.
113        let mut rows: Vec<(u32, u32, u32)> = Vec::with_capacity(n);
114        for (id, (start, end)) in map {
115            // Offsets must fit u32, as required by the module contract;
116            // see `from_hashmap`.
117            debug_assert!(end <= u32::MAX as usize, "entity offset exceeds the u32 column ceiling");
118            rows.push((id, start as u32, (end - start) as u32));
119        }
120        // `map` dropped with the loop; sort is in-place on `rows` alone.
121        rows.sort_unstable_by_key(|r| r.0);
122        let mut ids = Vec::with_capacity(rows.len());
123        let mut starts = Vec::with_capacity(rows.len());
124        let mut lengths = Vec::with_capacity(rows.len());
125        for (id, start, len) in rows {
126            ids.push(id);
127            starts.push(start);
128            lengths.push(len);
129        }
130        Self { ids, starts, lengths }
131    }
132
133    /// Build from an already-scanned [`EntityIndex`](crate::EntityIndex)
134    /// hashmap. The map is unique by construction (last-in-file-order-wins was
135    /// applied by `HashMap::insert`), so this only sorts the entries. Prefer
136    /// [`Self::from_hashmap_consuming`] when the map is no longer needed - it
137    /// avoids holding map + copies concurrently (P1 review finding on #1689).
138    pub fn from_hashmap(map: &EntityIndex) -> Self {
139        let n = map.len();
140        let mut ids = Vec::with_capacity(n);
141        let mut starts = Vec::with_capacity(n);
142        let mut lengths = Vec::with_capacity(n);
143        for (&id, &(start, end)) in map.iter() {
144            // u32 offsets are sound only under the wasm32 <4GiB address space
145            // (module docs). Catch a future native caller in debug builds
146            // before a silent truncation decodes the wrong bytes.
147            debug_assert!(end <= u32::MAX as usize, "entity offset exceeds the u32 column ceiling");
148            ids.push(id);
149            starts.push(start as u32);
150            lengths.push((end - start) as u32);
151        }
152        // Entries are unique; `from_unsorted`'s dedup is a no-op but keeps one
153        // sort/build code path.
154        Self::from_unsorted(ids, starts, lengths)
155    }
156
157    /// Scan `content` and build the columns directly, replicating
158    /// [`crate::build_entity_index`]'s HEADER-skipping / quoted-string scan and
159    /// its last-in-file-order-wins duplicate handling — without ever
160    /// materializing the intermediate `FxHashMap`. Used by the wasm lazy
161    /// fallback when `setEntityIndex` was never called.
162    ///
163    /// Reports the scanner's #3395 refusals for the same reason
164    /// [`crate::build_entity_index`] does: this is a whole-file index build, so
165    /// a refused record is a record the model will not contain.
166    pub fn from_scan<T>(content: &T) -> Self
167    where
168        T: AsRef<[u8]> + ?Sized,
169    {
170        let content = content.as_ref();
171        let estimated = content.len() / 50;
172        let mut ids = Vec::with_capacity(estimated);
173        let mut starts = Vec::with_capacity(estimated);
174        let mut lengths = Vec::with_capacity(estimated);
175        let mut scanner = EntityScanner::new(content);
176        while let Some((id, _type_name, start, end)) = scanner.next_entity() {
177            debug_assert!(end <= u32::MAX as usize, "entity offset exceeds the u32 column ceiling");
178            ids.push(id);
179            starts.push(start as u32);
180            lengths.push((end - start) as u32);
181        }
182        crate::parser::report_scan_diagnostics(
183            scanner.skipped_oversized_ids(),
184            scanner.malformed_record_start().is_some(),
185        );
186        Self::from_unsorted(ids, starts, lengths)
187    }
188
189    /// Sort the (id, start, length) triples by id and collapse duplicate ids
190    /// keeping the one that appeared **last** in the input order (matching
191    /// `FxHashMap::insert`). The input `Vec`s are in original (file / delivery)
192    /// order.
193    fn from_unsorted(ids: Vec<u32>, starts: Vec<u32>, lengths: Vec<u32>) -> Self {
194        let n = ids.len();
195        // Argsort a permutation, ordering by (id, original_index). Ties break by
196        // original index ascending, so within an equal-id run the last element
197        // has the greatest original index == last-in-input-order.
198        let mut perm: Vec<u32> = (0..n as u32).collect();
199        perm.sort_unstable_by(|&a, &b| {
200            let ka = ids[a as usize];
201            let kb = ids[b as usize];
202            ka.cmp(&kb).then_with(|| a.cmp(&b))
203        });
204
205        let mut out_ids: Vec<u32> = Vec::with_capacity(n);
206        let mut out_starts: Vec<u32> = Vec::with_capacity(n);
207        let mut out_lengths: Vec<u32> = Vec::with_capacity(n);
208        for &p in &perm {
209            let p = p as usize;
210            let id = ids[p];
211            if out_ids.last() == Some(&id) {
212                // Duplicate id: overwrite the tail so the LAST occurrence wins.
213                let li = out_ids.len() - 1;
214                out_starts[li] = starts[p];
215                out_lengths[li] = lengths[p];
216            } else {
217                out_ids.push(id);
218                out_starts.push(starts[p]);
219                out_lengths.push(lengths[p]);
220            }
221        }
222        out_ids.shrink_to_fit();
223        out_starts.shrink_to_fit();
224        out_lengths.shrink_to_fit();
225        Self {
226            ids: out_ids,
227            starts: out_starts,
228            lengths: out_lengths,
229        }
230    }
231
232    /// Binary-search the byte span of `id`. Returns `(start, end)` where
233    /// `end = start + length`, exactly matching [`EntityIndex`](crate::EntityIndex)'s
234    /// tuple, or `None` if the id is absent.
235    #[inline]
236    pub fn lookup(&self, id: u32) -> Option<(usize, usize)> {
237        match self.ids.binary_search(&id) {
238            Ok(i) => {
239                let start = self.starts[i] as usize;
240                Some((start, start + self.lengths[i] as usize))
241            }
242            Err(_) => None,
243        }
244    }
245
246    /// Sorted, unique id column (for re-emitting the entity-index event).
247    #[inline]
248    pub fn ids(&self) -> &[u32] {
249        &self.ids
250    }
251
252    /// Byte-start column, parallel to [`Self::ids`].
253    #[inline]
254    pub fn starts(&self) -> &[u32] {
255        &self.starts
256    }
257
258    /// Byte-length column, parallel to [`Self::ids`].
259    #[inline]
260    pub fn lengths(&self) -> &[u32] {
261        &self.lengths
262    }
263
264    /// Number of indexed entities.
265    #[inline]
266    pub fn len(&self) -> usize {
267        self.ids.len()
268    }
269
270    /// Whether the index is empty.
271    #[inline]
272    pub fn is_empty(&self) -> bool {
273        self.ids.is_empty()
274    }
275}
276
277/// True iff `ids` is strictly ascending (which also proves uniqueness). O(n).
278#[inline]
279fn is_strictly_ascending(ids: &[u32]) -> bool {
280    ids.windows(2).all(|w| w[0] < w[1])
281}
282
283/// The index representation an [`EntityDecoder`](crate::EntityDecoder) holds:
284/// either the legacy `FxHashMap` (native / lazily-built paths) or the compact
285/// columnar index (wasm shared-index ingestion). A thin dispatch keeps the
286/// decoder hot path (`decode_by_id`) agnostic to which one is installed.
287pub(crate) enum EntityIndexStore {
288    Hash(Arc<EntityIndex>),
289    Columnar(Arc<ColumnarEntityIndex>),
290    Dense(Arc<crate::DenseEntityIndex>),
291}
292
293impl EntityIndexStore {
294    /// Resolve `id` to its `(start, end)` byte span.
295    #[inline]
296    pub(crate) fn lookup(&self, id: u32) -> Option<(usize, usize)> {
297        match self {
298            EntityIndexStore::Hash(m) => m.get(&id).copied(),
299            EntityIndexStore::Columnar(c) => c.lookup(id),
300            EntityIndexStore::Dense(d) => d.lookup(id),
301        }
302    }
303}
304
305impl<'a> crate::EntityDecoder<'a> {
306    /// Create a decoder backed by a shared columnar index (wasm shared-index
307    /// path). Mirrors [`EntityDecoder::with_arc_index`](crate::EntityDecoder::with_arc_index)
308    /// but installs the compact representation.
309    pub fn with_arc_columnar_index<T>(content: &'a T, index: Arc<ColumnarEntityIndex>) -> Self
310    where
311        T: AsRef<[u8]> + ?Sized,
312    {
313        let mut decoder = Self::new(content);
314        decoder.set_columnar_index(index);
315        decoder
316    }
317
318    /// Install a shared columnar index into an existing decoder. Like
319    /// [`EntityDecoder::set_entity_index`](crate::EntityDecoder::set_entity_index)
320    /// but for the compact representation; afterwards `build_index` no-ops.
321    pub fn set_columnar_index(&mut self, index: Arc<ColumnarEntityIndex>) {
322        self.entity_index = Some(EntityIndexStore::Columnar(index));
323    }
324}
325
326#[cfg(test)]
327#[path = "columnar_index_tests.rs"]
328mod columnar_index_tests;