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    // One source-scoped inverse lookup shared by native jobs and WASM batches.
61    pub(crate) styled_item_index: std::sync::OnceLock<crate::decoder::StyledItemIndexResult>,
62}
63
64impl ColumnarEntityIndex {
65    /// Build from the three delivered columns (`setEntityIndex` ingestion).
66    ///
67    /// Verifies the id column's ordering **once**, O(n): the pre-pass emits in
68    /// whatever order it iterates (its own `FxHashMap` iteration order is
69    /// arbitrary), so this cannot assume ascending. If the ids are already
70    /// strictly ascending the columns are used as-is (no sort); otherwise a
71    /// single stable argsort permutation is applied and duplicate ids are
72    /// collapsed last-in-input-order-wins.
73    ///
74    /// Mismatched column lengths yield an empty index (the wasm caller guards
75    /// this too), so a malformed payload never panics a worker.
76    pub fn from_columns(ids: &[u32], starts: &[u32], lengths: &[u32]) -> Self {
77        let n = ids.len();
78        if n == 0 || starts.len() != n || lengths.len() != n {
79            return Self {
80                ids: Vec::new(),
81                starts: Vec::new(),
82                lengths: Vec::new(),
83                styled_item_index: std::sync::OnceLock::new(),
84            };
85        }
86        Self::from_owned_columns(ids.to_vec(), starts.to_vec(), lengths.to_vec())
87    }
88
89    /// Consume binding-owned columns without another full allocation (#3989).
90    /// Validation and last-in-input-order duplicate precedence match `from_columns`.
91    pub fn from_owned_columns(ids: Vec<u32>, starts: Vec<u32>, lengths: Vec<u32>) -> Self {
92        if ids.is_empty() || starts.len() != ids.len() || lengths.len() != ids.len() {
93            return Self { ids: Vec::new(), starts: Vec::new(), lengths: Vec::new(), styled_item_index: std::sync::OnceLock::new() };
94        }
95        if is_strictly_ascending(&ids) {
96            return Self { ids, starts, lengths, styled_item_index: std::sync::OnceLock::new() };
97        }
98        Self::from_unsorted(ids, starts, lengths)
99    }
100
101    /// Build from an already-scanned [`EntityIndex`](crate::EntityIndex)
102    /// hashmap, CONSUMING it. On the wasm prepass path the map is ~436 MB at
103    /// 19.1 M entities and the conversion runs while the whole source file is
104    /// resident in the same <4 GiB heap; borrowing (`from_hashmap`) keeps the
105    /// map alive across the copy AND the sort, spiking ~970 MB of transients.
106    ///
107    /// Consuming drains into one interleaved `Vec<(id, start, len)>` (~229 MB)
108    /// then sorts in place (`sort_unstable`; map keys are unique, so no
109    /// stability/permutation buffer). Peak during the drain is map + rows
110    /// capacity (~665 MB) until the map drops at end-of-loop; after that the
111    /// sort is in-place and the final column split briefly overlaps rows +
112    /// outputs (~458 MB) before rows drop. Still far below the borrowing path,
113    /// and the steady-state index is ~229 MB.
114    pub fn from_hashmap_consuming(map: EntityIndex) -> Self {
115        let n = map.len();
116        // Reserve while the map is still alive: peak ≈ map + rows (~665 MB at
117        // 19.1 M). Draining without reserve would thrash reallocs for the same
118        // asymptotic peak once the vec fills.
119        let mut rows: Vec<(u32, u32, u32)> = Vec::with_capacity(n);
120        for (id, (start, end)) in map {
121            // Offsets must fit u32, as required by the module contract;
122            // see `from_hashmap`.
123            debug_assert!(end <= u32::MAX as usize, "entity offset exceeds the u32 column ceiling");
124            rows.push((id, start as u32, (end - start) as u32));
125        }
126        // `map` dropped with the loop; sort is in-place on `rows` alone.
127        rows.sort_unstable_by_key(|r| r.0);
128        let mut ids = Vec::with_capacity(rows.len());
129        let mut starts = Vec::with_capacity(rows.len());
130        let mut lengths = Vec::with_capacity(rows.len());
131        for (id, start, len) in rows {
132            ids.push(id);
133            starts.push(start);
134            lengths.push(len);
135        }
136        Self { ids, starts, lengths, styled_item_index: std::sync::OnceLock::new() }
137    }
138
139    /// Build from an already-scanned [`EntityIndex`](crate::EntityIndex)
140    /// hashmap. The map is unique by construction (last-in-file-order-wins was
141    /// applied by `HashMap::insert`), so this only sorts the entries. Prefer
142    /// [`Self::from_hashmap_consuming`] when the map is no longer needed - it
143    /// avoids holding map + copies concurrently (P1 review finding on #1689).
144    pub fn from_hashmap(map: &EntityIndex) -> Self {
145        let n = map.len();
146        let mut ids = Vec::with_capacity(n);
147        let mut starts = Vec::with_capacity(n);
148        let mut lengths = Vec::with_capacity(n);
149        for (&id, &(start, end)) in map.iter() {
150            // u32 offsets are sound only under the wasm32 <4GiB address space
151            // (module docs). Catch a future native caller in debug builds
152            // before a silent truncation decodes the wrong bytes.
153            debug_assert!(end <= u32::MAX as usize, "entity offset exceeds the u32 column ceiling");
154            ids.push(id);
155            starts.push(start as u32);
156            lengths.push((end - start) as u32);
157        }
158        // Entries are unique; `from_unsorted`'s dedup is a no-op but keeps one
159        // sort/build code path.
160        Self::from_unsorted(ids, starts, lengths)
161    }
162
163    /// Scan `content` and build the columns directly, replicating
164    /// [`crate::build_entity_index`]'s HEADER-skipping / quoted-string scan and
165    /// its last-in-file-order-wins duplicate handling — without ever
166    /// materializing the intermediate `FxHashMap`. Used by the wasm lazy
167    /// fallback when `setEntityIndex` was never called.
168    ///
169    /// Reports the scanner's #3395 refusals for the same reason
170    /// [`crate::build_entity_index`] does: this is a whole-file index build, so
171    /// a refused record is a record the model will not contain.
172    pub fn from_scan<T>(content: &T) -> Self
173    where
174        T: AsRef<[u8]> + ?Sized,
175    {
176        let content = content.as_ref();
177        let estimated = content.len() / 50;
178        let mut ids = Vec::with_capacity(estimated);
179        let mut starts = Vec::with_capacity(estimated);
180        let mut lengths = Vec::with_capacity(estimated);
181        let mut scanner = EntityScanner::new(content);
182        while let Some((id, _type_name, start, end)) = scanner.next_entity() {
183            debug_assert!(end <= u32::MAX as usize, "entity offset exceeds the u32 column ceiling");
184            ids.push(id);
185            starts.push(start as u32);
186            lengths.push((end - start) as u32);
187        }
188        crate::parser::report_scan_diagnostics(
189            scanner.skipped_oversized_ids(),
190            scanner.malformed_record_start().is_some(),
191        );
192        Self::from_unsorted(ids, starts, lengths)
193    }
194
195    /// Sort the (id, start, length) triples by id and collapse duplicate ids
196    /// keeping the one that appeared **last** in the input order (matching
197    /// `FxHashMap::insert`). The input `Vec`s are in original (file / delivery)
198    /// order.
199    fn from_unsorted(ids: Vec<u32>, starts: Vec<u32>, lengths: Vec<u32>) -> Self {
200        let n = ids.len();
201        // Argsort a permutation, ordering by (id, original_index). Ties break by
202        // original index ascending, so within an equal-id run the last element
203        // has the greatest original index == last-in-input-order.
204        let mut perm: Vec<u32> = (0..n as u32).collect();
205        perm.sort_unstable_by(|&a, &b| {
206            let ka = ids[a as usize];
207            let kb = ids[b as usize];
208            ka.cmp(&kb).then_with(|| a.cmp(&b))
209        });
210
211        let mut out_ids: Vec<u32> = Vec::with_capacity(n);
212        let mut out_starts: Vec<u32> = Vec::with_capacity(n);
213        let mut out_lengths: Vec<u32> = Vec::with_capacity(n);
214        for &p in &perm {
215            let p = p as usize;
216            let id = ids[p];
217            if out_ids.last() == Some(&id) {
218                // Duplicate id: overwrite the tail so the LAST occurrence wins.
219                let li = out_ids.len() - 1;
220                out_starts[li] = starts[p];
221                out_lengths[li] = lengths[p];
222            } else {
223                out_ids.push(id);
224                out_starts.push(starts[p]);
225                out_lengths.push(lengths[p]);
226            }
227        }
228        out_ids.shrink_to_fit();
229        out_starts.shrink_to_fit();
230        out_lengths.shrink_to_fit();
231        Self {
232            ids: out_ids,
233            starts: out_starts,
234            lengths: out_lengths,
235            styled_item_index: std::sync::OnceLock::new(),
236        }
237    }
238
239    /// Binary-search the byte span of `id`. Returns `(start, end)` where
240    /// `end = start + length`, exactly matching [`EntityIndex`](crate::EntityIndex)'s
241    /// tuple, or `None` if the id is absent.
242    #[inline]
243    pub fn lookup(&self, id: u32) -> Option<(usize, usize)> {
244        match self.ids.binary_search(&id) {
245            Ok(i) => {
246                let start = self.starts[i] as usize;
247                Some((start, start + self.lengths[i] as usize))
248            }
249            Err(_) => None,
250        }
251    }
252
253    /// Sorted, unique id column (for re-emitting the entity-index event).
254    #[inline]
255    pub fn ids(&self) -> &[u32] {
256        &self.ids
257    }
258
259    /// Byte-start column, parallel to [`Self::ids`].
260    #[inline]
261    pub fn starts(&self) -> &[u32] {
262        &self.starts
263    }
264
265    /// Byte-length column, parallel to [`Self::ids`].
266    #[inline]
267    pub fn lengths(&self) -> &[u32] {
268        &self.lengths
269    }
270
271    /// Number of indexed entities.
272    #[inline]
273    pub fn len(&self) -> usize {
274        self.ids.len()
275    }
276
277    /// Whether the index is empty.
278    #[inline]
279    pub fn is_empty(&self) -> bool {
280        self.ids.is_empty()
281    }
282}
283
284/// True iff `ids` is strictly ascending (which also proves uniqueness). O(n).
285#[inline]
286fn is_strictly_ascending(ids: &[u32]) -> bool {
287    ids.windows(2).all(|w| w[0] < w[1])
288}
289
290/// The index representation an [`EntityDecoder`](crate::EntityDecoder) holds:
291/// either the legacy `FxHashMap` (native / lazily-built paths) or the compact
292/// columnar index (wasm shared-index ingestion). A thin dispatch keeps the
293/// decoder hot path (`decode_by_id`) agnostic to which one is installed.
294pub(crate) enum EntityIndexStore {
295    Hash(Arc<EntityIndex>),
296    Columnar(Arc<ColumnarEntityIndex>),
297    Dense(Arc<crate::DenseEntityIndex>),
298}
299
300impl EntityIndexStore {
301    /// Resolve `id` to its `(start, end)` byte span.
302    #[inline]
303    pub(crate) fn lookup(&self, id: u32) -> Option<(usize, usize)> {
304        match self {
305            EntityIndexStore::Hash(m) => m.get(&id).copied(),
306            EntityIndexStore::Columnar(c) => c.lookup(id),
307            EntityIndexStore::Dense(d) => d.lookup(id),
308        }
309    }
310}
311
312impl<'a> crate::EntityDecoder<'a> {
313    /// Create a decoder backed by a shared columnar index (wasm shared-index
314    /// path). Mirrors [`EntityDecoder::with_arc_index`](crate::EntityDecoder::with_arc_index)
315    /// but installs the compact representation.
316    pub fn with_arc_columnar_index<T>(content: &'a T, index: Arc<ColumnarEntityIndex>) -> Self
317    where
318        T: AsRef<[u8]> + ?Sized,
319    {
320        let mut decoder = Self::new(content);
321        decoder.set_columnar_index(index);
322        decoder
323    }
324
325    /// Install a shared columnar index into an existing decoder. Like
326    /// [`EntityDecoder::set_entity_index`](crate::EntityDecoder::set_entity_index)
327    /// but for the compact representation; afterwards `build_index` no-ops.
328    pub fn set_columnar_index(&mut self, index: Arc<ColumnarEntityIndex>) {
329        self.entity_index = Some(EntityIndexStore::Columnar(index));
330    }
331}
332
333#[cfg(test)]
334#[path = "columnar_index_tests.rs"]
335mod columnar_index_tests;