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