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