ifc_lite_core/
sparse_source.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//! Out-of-core source: a decoder's `content` that holds only the
6//! records a worker has needed so far, instead of the whole file.
7//!
8//! The arena is itself a valid STEP file: the original HEADER, then a subset
9//! of the DATA records in the order they were installed. Every reader that
10//! takes `content: &[u8]` therefore works on it unchanged, and a reader that
11//! scans by type sees the subset that was installed. The host fetches records
12//! by byte range (a `File` slice, an OPFS handle, a shared buffer) and installs
13//! them here; [`SparseSource::expand`] names the records a set of roots still
14//! needs by walking `#id` references through what is already present.
15//!
16//! A lookup of an id that is not installed is recorded
17//! ([`SparseIndex::take_misses`]), so a reference the forward walk cannot see
18//! (an inverse relation the caller did not declare) is detected rather than
19//! silently read as "entity not found".
20
21use crate::decoder::EntityIndex;
22use crate::parser::EntityScanner;
23use rustc_hash::{FxHashMap, FxHashSet};
24use std::sync::{Arc, Mutex, PoisonError};
25
26/// Id to arena span, with a record of every id asked for and not found.
27#[derive(Default)]
28pub struct SparseIndex {
29    /// Shared with the decoder, which reads it as an ordinary hash index.
30    map: Arc<EntityIndex>,
31    misses: Mutex<FxHashSet<u32>>,
32}
33
34impl SparseIndex {
35    /// Resolve `id` to its arena span; an absent id is recorded as a miss.
36    #[inline]
37    pub fn lookup(&self, id: u32) -> Option<(usize, usize)> {
38        let hit = self.map.get(&id).copied();
39        if hit.is_none() {
40            self.record_miss(id);
41        }
42        hit
43    }
44
45    /// Record an id a decoder looked up and did not find (the host fetches it and runs the batch again).
46    #[cold]
47    #[inline(never)]
48    pub fn record_miss(&self, id: u32) {
49        self.misses.lock().unwrap_or_else(PoisonError::into_inner).insert(id);
50    }
51
52    /// Resolve without recording a miss (the reference walk's own probe).
53    #[inline]
54    pub fn peek(&self, id: u32) -> Option<(usize, usize)> {
55        self.map.get(&id).copied()
56    }
57
58    /// Drain the ids looked up and not found since the last drain.
59    pub fn take_misses(&self) -> Vec<u32> {
60        let mut misses = self.misses.lock().unwrap_or_else(PoisonError::into_inner);
61        let mut ids: Vec<u32> = misses.drain().collect();
62        ids.sort_unstable();
63        ids
64    }
65
66    pub fn len(&self) -> usize {
67        self.map.len()
68    }
69
70    pub fn is_empty(&self) -> bool {
71        self.map.is_empty()
72    }
73}
74
75/// Call `visit` with every `#id` reference in one STEP record's attribute
76/// list. Quoted strings and `/* */` comments are skipped; the record's own
77/// `#id=` is not reported.
78/// A reference wider than `u32` is ignored, as the decoder refuses it anyway.
79pub fn for_each_record_ref(record: &[u8], mut visit: impl FnMut(u32)) {
80    // Skip the instance name: everything up to and including the first `=` outside a comment.
81    let len = record.len();
82    let mut i = 0;
83    loop {
84        let Some(rel) = memchr::memchr2(b'=', b'/', &record[i..]) else { return };
85        i += rel + 1;
86        if record[i - 1] == b'=' {
87            break;
88        }
89        if record.get(i) == Some(&b'*') {
90            match memchr::memmem::find(&record[i + 1..], b"*/") {
91                Some(close) => i += close + 3,
92                None => return,
93            }
94        }
95    }
96    while i < len {
97        let Some(rel) = memchr::memchr3(b'#', b'\'', b'/', &record[i..]) else { return };
98        i += rel;
99        if record[i] == b'/' {
100            // A comment may hold a quote or a `#`: neither means anything inside it.
101            if record.get(i + 1) != Some(&b'*') {
102                i += 1;
103                continue;
104            }
105            match memchr::memmem::find(&record[i + 2..], b"*/") {
106                Some(close) => i += close + 4,
107                None => return,
108            }
109            continue;
110        }
111        if record[i] == b'\'' {
112            // A doubled quote inside a string closes and reopens it, which
113            // skips the same bytes as treating it as an escape.
114            match memchr::memchr(b'\'', &record[i + 1..]) {
115                Some(close) => i += close + 2,
116                None => return,
117            }
118            continue;
119        }
120        i += 1;
121        let digits_start = i;
122        let mut value: u64 = 0;
123        while i < len && record[i].is_ascii_digit() {
124            value = value.saturating_mul(10).saturating_add(u64::from(record[i] - b'0'));
125            i += 1;
126        }
127        if i > digits_start {
128            if let Ok(id) = u32::try_from(value) {
129                visit(id);
130            }
131        }
132    }
133}
134
135/// Counters for the host's budget decision and for the report.
136#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
137pub struct SparseStats {
138    pub arena_bytes: usize,
139    pub base_bytes: usize,
140    pub records: usize,
141    pub installed_bytes_total: u64,
142    pub installed_records_total: u64,
143    pub resets: u32,
144    /// Bumped whenever a declared inverse referrer is installed (or dropped by
145    /// a reset): an index built by scanning the arena for those records is
146    /// stale once this moves.
147    pub referrer_generation: u32,
148}
149
150/// The sparse arena, its index and the reference-walk state.
151pub struct SparseSource {
152    bytes: Arc<Vec<u8>>,
153    index: Arc<SparseIndex>,
154    /// Length and record ids of the preamble, restored by [`Self::reset`].
155    base_len: usize,
156    base: EntityIndex,
157    /// Ids whose references have been walked, or that the file does not hold.
158    walked: FxHashSet<u32>,
159    /// Records that reference a target the forward walk starts from, and must
160    /// travel with it: target id to referrer ids, in file order.
161    inverse: FxHashMap<u32, Vec<u32>>,
162    referrers: FxHashSet<u32>,
163    stats: SparseStats,
164}
165
166impl SparseSource {
167    /// Start from a preamble: the file's HEADER followed by the records every
168    /// worker needs (see `build_sparse_preamble`).
169    pub fn new(preamble: Vec<u8>) -> Self {
170        Self::with_reserve(preamble, 0)
171    }
172
173    /// [`Self::new`], reserving `reserve_bytes` of arena up front.
174    ///
175    /// Without a reservation the arena grows by doubling, and each growth
176    /// holds the old and the new block at once: measured on a single worker,
177    /// the wasm heap high-water was 2 to 5 times the arena. Reserved once, the
178    /// arena never moves until it outgrows the reservation, and a reset keeps
179    /// the block. Pages that are never written cost address space only.
180    pub fn with_reserve(mut preamble: Vec<u8>, reserve_bytes: usize) -> Self {
181        preamble.reserve_exact(reserve_bytes.saturating_sub(preamble.len()));
182        let mut base = EntityIndex::default();
183        let mut scanner = EntityScanner::new(&preamble);
184        while let Some((id, _kw, start, end)) = scanner.next_entity() {
185            base.insert(id, (start, end));
186        }
187        let stats = SparseStats {
188            arena_bytes: preamble.len(),
189            base_bytes: preamble.len(),
190            records: base.len(),
191            ..Default::default()
192        };
193        Self {
194            base_len: preamble.len(),
195            index: Arc::new(SparseIndex { map: Arc::new(base.clone()), misses: Mutex::default() }),
196            base,
197            bytes: Arc::new(preamble),
198            walked: FxHashSet::default(),
199            inverse: FxHashMap::default(),
200            referrers: FxHashSet::default(),
201            stats,
202        }
203    }
204
205    /// Declare inverse edges: `referrers[i]` references `targets[i]` and must
206    /// be installed whenever the target is walked. Order is preserved per
207    /// target, so file-order precedence among referrers survives.
208    pub fn set_inverse_edges(&mut self, targets: &[u32], referrers: &[u32]) {
209        self.inverse.clear();
210        self.referrers.clear();
211        for (&target, &referrer) in targets.iter().zip(referrers) {
212            self.inverse.entry(target).or_default().push(referrer);
213            self.referrers.insert(referrer);
214        }
215    }
216
217    pub fn bytes(&self) -> Arc<Vec<u8>> {
218        Arc::clone(&self.bytes)
219    }
220
221    pub fn index(&self) -> Arc<SparseIndex> {
222        Arc::clone(&self.index)
223    }
224
225    pub fn stats(&self) -> SparseStats {
226        self.stats
227    }
228
229    pub fn contains(&self, id: u32) -> bool {
230        self.index.peek(id).is_some()
231    }
232
233    /// Walk references from `ids` through the installed records and append
234    /// every id that is needed and not installed to `missing` (deduplicated,
235    /// ascending). After installing them, walk again from those ids.
236    ///
237    /// A full walk (`max_depth == u32::MAX`) expands each record once per
238    /// arena lifetime, so later calls only pay for what was installed since.
239    /// A depth-limited walk follows at most `max_depth` reference hops and
240    /// keeps no state, so it never hides a record from a later full walk.
241    pub fn expand(&mut self, ids: &[u32], max_depth: u32, missing: &mut Vec<u32>) {
242        let full = max_depth == u32::MAX;
243        let mut seen: FxHashSet<u32> = FxHashSet::default();
244        let mut absent: FxHashSet<u32> = FxHashSet::default();
245        let mut frontier: Vec<u32> = ids.to_vec();
246        let mut next: Vec<u32> = Vec::new();
247        let mut depth = 0u32;
248        while !frontier.is_empty() {
249            for &id in &frontier {
250                if self.walked.contains(&id) || (!full && !seen.insert(id)) {
251                    continue;
252                }
253                let Some((start, end)) = self.index.peek(id) else {
254                    absent.insert(id);
255                    continue;
256                };
257                if depth >= max_depth {
258                    continue;
259                }
260                if full {
261                    self.walked.insert(id);
262                }
263                for_each_record_ref(&self.bytes[start..end], |reference| next.push(reference));
264                if let Some(referrers) = self.inverse.get(&id) {
265                    next.extend_from_slice(referrers);
266                }
267            }
268            frontier.clear();
269            std::mem::swap(&mut frontier, &mut next);
270            depth = depth.saturating_add(1);
271        }
272        let from = missing.len();
273        missing.extend(absent);
274        missing[from..].sort_unstable();
275    }
276
277    /// Append records. `spans` holds `(id, offset, length)` into `chunk`; each
278    /// record is copied with a trailing newline. An id already installed is
279    /// skipped (the first copy stays authoritative).
280    pub fn install(&mut self, spans: &[(u32, usize, usize)], chunk: &[u8]) {
281        let bytes = Arc::make_mut(&mut self.bytes);
282        let index = match Arc::get_mut(&mut self.index) {
283            Some(index) => index,
284            None => {
285                // A decoder from an earlier batch still holds the index: copy it.
286                let copy = SparseIndex { map: Arc::clone(&self.index.map), misses: Mutex::default() };
287                self.index = Arc::new(copy);
288                Arc::get_mut(&mut self.index).expect("freshly created index is unshared")
289            }
290        };
291        // Copied only if a decoder from an earlier batch still reads it.
292        let map = Arc::make_mut(&mut index.map);
293        for &(id, offset, length) in spans {
294            let Some(record) = chunk.get(offset..offset.saturating_add(length)) else { continue };
295            if record.is_empty() || map.contains_key(&id) {
296                continue;
297            }
298            let start = bytes.len();
299            bytes.extend_from_slice(record);
300            bytes.push(b'\n');
301            map.insert(id, (start, start + record.len()));
302            if self.referrers.contains(&id) {
303                self.stats.referrer_generation = self.stats.referrer_generation.wrapping_add(1);
304            }
305            self.stats.installed_bytes_total += record.len() as u64;
306            self.stats.installed_records_total += 1;
307        }
308        self.stats.arena_bytes = bytes.len();
309        self.stats.records = map.len();
310    }
311
312    /// Ids the file does not hold (dangling references): never reported again.
313    pub fn mark_absent(&mut self, ids: &[u32]) {
314        self.walked.extend(ids.iter().copied());
315    }
316
317    /// Lookups that missed since the last call, without the ids already known
318    /// to be absent from the file.
319    pub fn take_misses(&self) -> Vec<u32> {
320        let mut misses = self.index.take_misses();
321        misses.retain(|id| !self.walked.contains(id) && self.index.peek(*id).is_none());
322        misses
323    }
324
325    /// Drop everything but the preamble. Spans change, so the caller must not
326    /// hold a decoder or a span across this call.
327    pub fn reset(&mut self) {
328        // Truncate in place: the reserved block is kept for the next period.
329        Arc::make_mut(&mut self.bytes).truncate(self.base_len);
330        self.index = Arc::new(SparseIndex { map: Arc::new(self.base.clone()), misses: Mutex::default() });
331        self.walked.clear();
332        self.stats.arena_bytes = self.base_len;
333        self.stats.records = self.base.len();
334        self.stats.resets += 1;
335        self.stats.referrer_generation = self.stats.referrer_generation.wrapping_add(1);
336    }
337}
338
339/// Build the preamble every sparse worker starts from: the bytes before the
340/// first DATA record (the HEADER, which declares the schema), the `closure`
341/// roots with every record they reference, and the `records` roots alone, all
342/// in file order. `lookup` resolves an id to its span in `content`.
343pub fn build_sparse_preamble(
344    content: &[u8],
345    lookup: impl Fn(u32) -> Option<(usize, usize)>,
346    closure_roots: &[u32],
347    record_roots: &[u32],
348) -> Vec<u8> {
349    let header_end = EntityScanner::new(content)
350        .next_entity()
351        .map_or(content.len(), |(_, _, start, _)| start);
352    let mut spans: FxHashMap<u32, (usize, usize)> = FxHashMap::default();
353    let mut stack: Vec<u32> = closure_roots.to_vec();
354    while let Some(id) = stack.pop() {
355        if spans.contains_key(&id) {
356            continue;
357        }
358        let Some((start, end)) = lookup(id) else { continue };
359        let Some(record) = content.get(start..end) else { continue };
360        spans.insert(id, (start, end));
361        for_each_record_ref(record, |reference| stack.push(reference));
362    }
363    for &id in record_roots {
364        if let Some((start, end)) = lookup(id).filter(|&(s, e)| content.get(s..e).is_some()) {
365            spans.entry(id).or_insert((start, end));
366        }
367    }
368    let mut ordered: Vec<(usize, usize)> = spans.into_values().collect();
369    ordered.sort_unstable();
370    let body: usize = ordered.iter().map(|(start, end)| end - start + 1).sum();
371    let mut preamble = Vec::with_capacity(header_end + body);
372    preamble.extend_from_slice(&content[..header_end]);
373    for (start, end) in ordered {
374        preamble.extend_from_slice(&content[start..end]);
375        preamble.push(b'\n');
376    }
377    preamble
378}
379
380impl<'a> crate::EntityDecoder<'a> {
381    /// Create a decoder over a sparse arena. `content` must be the arena that
382    /// `index` spans point into.
383    pub fn with_sparse_index<T>(content: &'a T, index: Arc<SparseIndex>) -> Self
384    where
385        T: AsRef<[u8]> + ?Sized,
386    {
387        // The arena's index is read as an ordinary hash index, so a decoder's lookups run the same code
388        // with or without an arena. What differs is the miss path: it tells the arena's host.
389        let mut decoder = Self::new(content);
390        decoder.entity_index = Some(crate::columnar_index::EntityIndexStore::Hash(Arc::clone(&index.map)));
391        decoder.sparse_misses = Some(index);
392        decoder
393    }
394}
395
396#[cfg(test)]
397#[path = "sparse_source_tests.rs"]
398mod tests;