Skip to main content

waratah_exec/
term_dict.rs

1//! Query-local intern table: [`EncodedTerm`] ↔ [`TermId`].
2//!
3//! One [`TermDict`] is shared by every operator in a SPARQL execution.
4//! [`TermId::UNBOUND`] (`0`) is SPARQL unbound and is not returned from
5//! [`TermDict::get`]. Shelf position `0` holds [`EncodedTerm::Placeholder`]
6//! (internal sentinel only). Reserved ids 1–3 are DefaultGraph, [`RDF_TYPE`], and
7//! [`TermId::COUNTED_PRESENCE`] (XSD `true` for domain-count placeholders).
8
9use std::hash::{BuildHasher, Hash, Hasher};
10#[cfg(feature = "intern-replay")]
11use std::io::Write as _;
12#[cfg(feature = "intern-replay")]
13use std::sync::OnceLock;
14use std::sync::{Arc, Mutex};
15
16use rustc_hash::FxBuildHasher;
17#[cfg(feature = "intern-replay")]
18use waratah_storage::encode_term_bytes;
19use waratah_storage::{ENCODED_TERM_TRUE, EncodedTerm, RDF_TYPE};
20
21use crate::ExecError;
22
23/// Capture hooks for the `intern-replay` feature: stream the exact intern
24/// access sequence (`WARATAH_DUMP_ACCESS`) and the final dict contents
25/// (`WARATAH_DUMP_DICT`) to disk so the `replay_corpus_access` test can run
26/// its census on real corpus terms. Compiled only with
27/// `--features intern-replay`; without it no dump code exists in the build.
28#[cfg(feature = "intern-replay")]
29static ACCESS_DUMP: OnceLock<Option<Mutex<std::io::BufWriter<std::fs::File>>>> = OnceLock::new();
30
31/// Open the access-sequence dump writer when `WARATAH_DUMP_ACCESS` is set.
32#[cfg(feature = "intern-replay")]
33fn access_dump() -> Option<&'static Mutex<std::io::BufWriter<std::fs::File>>> {
34    ACCESS_DUMP
35        .get_or_init(|| {
36            std::env::var_os("WARATAH_DUMP_ACCESS").map(|path| {
37                let file = std::fs::File::create(&path).expect("WARATAH_DUMP_ACCESS file");
38                Mutex::new(std::io::BufWriter::with_capacity(1 << 20, file))
39            })
40        })
41        .as_ref()
42}
43
44/// Append one term to an access or dict dump: 4-byte big-endian length,
45/// then the encoded term bytes.
46#[cfg(feature = "intern-replay")]
47fn write_dump_term(w: &mut impl std::io::Write, term: &EncodedTerm) {
48    let bytes = encode_term_bytes(term);
49    let _ = w.write_all(&(bytes.len() as u32).to_be_bytes());
50    let _ = w.write_all(&bytes);
51}
52
53/// Dense intern id for one RDF term in a query.
54///
55/// `0` is SPARQL unbound (not an [`EncodedTerm`] returned from [`TermDict::get`]).
56/// Other ids equal the term's dense position on the intern shelf.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
58#[repr(transparent)]
59pub struct TermId(pub u32);
60
61impl TermId {
62    /// Unbound / UNDEF. Never returned from [`TermDict::get`].
63    pub const UNBOUND: Self = Self(0);
64    /// [`EncodedTerm::DefaultGraph`].
65    pub const DEFAULT_GRAPH: Self = Self(1);
66    /// [`RDF_TYPE`] (`rdf:type`).
67    pub const RDF_TYPE: Self = Self(2);
68    /// Reserved XSD `true` slot for counted-dead placeholder columns (not RDF
69    /// data semantics — see domain-count materialization in compute).
70    pub const COUNTED_PRESENCE: Self = Self(3);
71
72    /// Whether this id is SPARQL-unbound.
73    #[inline]
74    pub fn is_unbound(self) -> bool {
75        self.0 == 0
76    }
77
78    /// Raw `u32` stored in [`crate::TermColumn`] buffers.
79    #[inline]
80    pub const fn as_u32(self) -> u32 {
81        self.0
82    }
83}
84
85/// One 16-byte catalog entry (Large mode): the term's full 64-bit hash and
86/// its shelf position, stored as `position + 1` — 4 per 64-byte cache line.
87/// Storing the hash lets a resize re-slot every entry without re-hashing
88/// terms, and lets a probe walk skip another term's entry by comparing 8
89/// bytes in the line it already holds. A stored-tag match is only a
90/// candidate; the shelf verify (bit-identity of the term) decides, and with
91/// 64-bit tags a collision between distinct terms is ~n/2^64 — effectively
92/// never — so that verify is never wasted. `stored == 0` marks the slot
93/// vacant; see [`Slot8`] for why the field is offset by one.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95#[repr(C, align(16))]
96struct Slot16 {
97    hash: u64,
98    stored: u32,
99    _pad: u32,
100}
101
102/// 8-byte catalog entry (Small mode): a 32-bit tag — the FxHash **high**
103/// half, which for multiply-based hashing is the better-mixed half (the low
104/// k bits of a product depend only on the low k bits of the inputs) — plus
105/// the shelf position, stored as `position + 1`. 8 per 64-byte cache line,
106/// and the tag is the complete placement key, so a resize re-places from
107/// stored tags without re-hashing. The tag match is only a candidate:
108/// distinct terms share a 32-bit tag at rate n/2^32, and each collision costs
109/// one wasted shelf verify on the later-inserted member's lookups. Crossing
110/// [`SLOTS8_MAX_TERMS`] upgrades to [`Slot16`], recovering the low hash half
111/// by re-hashing the shelf once.
112///
113/// **Why `position + 1` and not the position.** `stored == 0` is the vacant
114/// marker, so an all-zero slot is a valid empty entry. That is what lets
115/// [`zeroed_slots`] allocate the catalog through `alloc_zeroed`: the reserve
116/// path then costs address space instead of a write over every slot. Storing
117/// the position directly would also leave `0` vacant — the catalog never
118/// holds positions 0–3, which live only on the shelf — but it would make a
119/// vacant slot's field numerically equal to `TermId::UNBOUND`, separating
120/// the two meanings only by that non-local "never holds 0–3" rule. The
121/// offset makes the stored field its own encoding, so the `stored != 0` test
122/// alone decides liveness. The last usable shelf position is `u32::MAX - 1`
123/// (enforced by [`has_room_for_one_more`]), so `position + 1` cannot
124/// overflow. A real term whose hash is `0` is still distinguishable because
125/// only `stored` signals emptiness.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127#[repr(C)]
128struct Slot8 {
129    tag: u32,
130    stored: u32,
131}
132
133/// Whether the shelf can take one more term.
134///
135/// The last usable position is `u32::MAX - 1`. The catalog stores
136/// `position + 1` in a `u32` (see [`Slot8`]), so a position of `u32::MAX`
137/// would make its stored form wrap to `0` and read as a vacant slot. That is
138/// the whole reason for the ceiling: it is not about the sentinel value, it
139/// is about the offset encoding and the `u32` field width.
140#[inline]
141fn has_room_for_one_more(terms_len: usize) -> bool {
142    terms_len < u32::MAX as usize
143}
144
145/// `n` empty slots, allocated zero-filled rather than written.
146///
147/// `alloc_zeroed` lets the allocator satisfy a large request with fresh
148/// anonymous pages, which read as zero without a write; a recycled block is
149/// zeroed by the allocator instead. Either way this function issues no
150/// per-slot write, so a plan-driven reserve of hundreds of thousands of slots
151/// costs roughly a page fault per page actually probed, not one write per
152/// slot.
153///
154/// # Safety contract
155///
156/// `T` must satisfy all of:
157///
158/// - an all-zero bit pattern is a valid value of `T`, and means "vacant";
159/// - `T` is not zero-sized (a zero-size allocation is not a valid
160///   `alloc_zeroed` request);
161/// - `T` does not implement `Drop` (the returned `Vec` reports `n`
162///   initialized elements, so its destructor would drop values that were
163///   never constructed).
164///
165/// Every field an integer satisfies all three. [`Slot8`] and [`Slot16`] do,
166/// and [`slot_layout_pins_the_zeroed_empty_encoding`] pins the layout those
167/// two rely on.
168fn zeroed_slots<T>(n: usize) -> Vec<T> {
169    if n == 0 {
170        return Vec::new();
171    }
172    // Offsets are compile-time constants for any concrete `T`, so these fold
173    // away; they exist to fail loudly on a misuse the compiler cannot see.
174    assert!(
175        std::mem::size_of::<T>() != 0,
176        "zeroed_slots requires a non-zero-sized element type"
177    );
178    let layout = std::alloc::Layout::array::<T>(n).expect("catalog slot array layout");
179    // SAFETY: the layout is exactly `n` slots; `alloc_zeroed` returns null or
180    // a block owned by the global allocator, aligned for `T` and long enough
181    // for `n` elements. It is never read before write except as an empty
182    // slot, which the safety contract above makes valid, so the `Vec` below
183    // may treat every element as initialised.
184    unsafe {
185        let ptr = std::alloc::alloc_zeroed(layout) as *mut T;
186        if ptr.is_null() {
187            std::alloc::handle_alloc_error(layout);
188        }
189        Vec::from_raw_parts(ptr, n, n)
190    }
191}
192
193/// Load-factor guard: the catalog doubles when occupied slots pass this
194/// fraction, keeping linear-probe chains short. The same 7/8 policy the
195/// hashbrown table inside the previous IndexMap enforced.
196const SLOTS_LOAD_NUM: usize = 7;
197const SLOTS_LOAD_DEN: usize = 8;
198const SLOTS_MIN: usize = 8;
199
200/// Shelf length where the catalog upgrades Small → Large (see [`Slot8`]).
201/// Below it the 32-bit tag's wasted-verify rate is statistically invisible
202/// (n/2^32 of lookups: measured 0.071% at a 10.3M-term working set, 0.75%
203/// modeled at 32M) and the halved catalog footprint is the win — on a
204/// 100M-triple corpus, pure slot8 through 10.3M terms beat the
205/// upgrade-at-2M path by 5.5-6.8% wall with identical results. Above it
206/// the wasted verifies grow linearly (~4.7% of lookups at 200M terms) and
207/// the full hash pays for itself; revisit the threshold if working sets
208/// approach that zone.
209///
210/// 32M is kept deliberately, not derived from the collision math (which
211/// stays negligible to ~60M): it sits above the only measured working set,
212/// so measured workloads never pay the upgrade. The reason it is not
213/// raised further is the upgrade stall itself — a crossing re-places every
214/// interned term under the dict mutex in one step, and a ~60M-term dict
215/// upgrading from 8-byte slots (32-bit tag) to 16-byte slots (full 64-bit
216/// hash) would stall too noticeably to accept casually. Any revisit weighs
217/// the collision zone against that stall, which grows with the shelf
218/// length at the crossing.
219const SLOTS8_MAX_TERMS: usize = 32_000_000;
220
221/// The reserved shelf ids (Placeholder, DefaultGraph, RDF_TYPE,
222/// counted-presence). They live only on the shelf — the well-known fast
223/// paths answer them before any probe — so the catalog holds
224/// `terms.len() - RESERVED_TERMS` entries.
225const RESERVED_TERMS: usize = 4;
226
227/// Ceiling for the *advisory* plan-driven reserve. `reserve` is a hint, not
228/// a promise — the dict grows on demand regardless — so a plan estimate is
229/// clamped to a size whose shelf + catalog allocations are actually
230/// satisfiable instead of the full `u32::MAX - 1` id ceiling (whose shelf
231/// reserve alone is ~171 GB and aborts via `handle_alloc_error`).
232const MAX_RESERVE_TERMS: usize = 1 << 26;
233
234/// How many upcoming cells' start-slot lines the intern loop prefetches
235/// while inserting the current cell. Pure-latency tuning: prefetch is a
236/// hint, so a wrong guess costs bandwidth only.
237const PREFETCH_AHEAD: usize = 8;
238
239impl Slot16 {
240    /// The all-zero slot: the reference value a vacant entry compares equal
241    /// to. Allocations are zero-filled rather than filled with this
242    /// constant; it exists for the constructor assertion and the layout
243    /// test. `stored == 0` is the vacant marker.
244    const EMPTY: Self = Self {
245        hash: 0,
246        stored: 0,
247        _pad: 0,
248    };
249}
250
251impl Slot8 {
252    /// The all-zero slot: the reference value a vacant entry compares equal
253    /// to. Allocations are zero-filled rather than filled with this
254    /// constant; it exists for the constructor assertion and the layout
255    /// test. `stored == 0` is the vacant marker.
256    const EMPTY: Self = Self { tag: 0, stored: 0 };
257}
258
259/// The catalog in one of two slot widths, selected by shelf size (see
260/// [`SLOTS8_MAX_TERMS`]). Both are open-addressing with linear probing,
261/// power-of-two length, and place from the hash's high 32 bits — in Small
262/// mode those bits are the whole stored tag, so a resize re-places from
263/// stored tags without re-hashing in either mode.
264#[derive(Debug)]
265enum Catalog {
266    Small(Vec<Slot8>),
267    Large(Vec<Slot16>),
268}
269
270impl Catalog {
271    #[inline]
272    fn slot_count(&self) -> usize {
273        match self {
274            Catalog::Small(slots) => slots.len(),
275            Catalog::Large(slots) => slots.len(),
276        }
277    }
278}
279
280#[derive(Debug)]
281struct TermDictInner {
282    /// The shelf: id → term. `id` is the position, assigned once on insert
283    /// and never renumbered — identical semantics to the previous IndexMap's
284    /// insertion index. The first four entries are the reserved ids 0–3
285    /// (Placeholder, DefaultGraph, RDF_TYPE, counted-presence).
286    terms: Vec<EncodedTerm>,
287    /// The catalog: term → id, in one of two slot widths. The four reserved
288    /// ids live only on the shelf — the well-known fast paths answer them
289    /// before any probe.
290    catalog: Catalog,
291    /// `catalog.slot_count() - 1`: power-of-two mask for start-slot
292    /// selection.
293    mask: u64,
294    /// Occupied catalog slots (== `terms.len() - RESERVED_TERMS`).
295    occupied: usize,
296    /// Shelf length at which the catalog upgrades Small → Large. A field
297    /// rather than a const so tests can drive the transition cheaply.
298    small_mode_max: usize,
299}
300
301/// Bidirectional intern table for one SPARQL query.
302///
303/// The dense shelf owns each term once: catalog hash-lookup for intern, shelf
304/// position for `TermId → EncodedTerm`. A [`Mutex`] allows parallel UNION arms
305/// to intern on `&TermDict` across `.await`.
306#[derive(Debug)]
307pub struct TermDict {
308    inner: Mutex<TermDictInner>,
309}
310
311/// XSD `true` interned at [`TermId::COUNTED_PRESENCE`] in every query dict.
312#[inline]
313pub fn counted_presence_encoded_term() -> EncodedTerm {
314    ENCODED_TERM_TRUE
315}
316
317impl TermDict {
318    /// Empty dict with Placeholder @0 and reserved ids 1–3.
319    pub fn new() -> Self {
320        // Shelf order fixes the reserved ids: 0 Placeholder (SPARQL unbound,
321        // never returned from `get`), 1 DefaultGraph, 2 rdf:type, 3
322        // counted-presence. The reserved terms live only on the shelf; the
323        // catalog answers them through the well-known fast paths.
324        let inner = TermDictInner {
325            terms: vec![
326                EncodedTerm::Placeholder,
327                EncodedTerm::DefaultGraph,
328                RDF_TYPE,
329                ENCODED_TERM_TRUE,
330            ],
331            catalog: Catalog::Small(zeroed_slots(SLOTS_MIN)),
332            mask: (SLOTS_MIN - 1) as u64,
333            occupied: 0,
334            small_mode_max: SLOTS8_MAX_TERMS,
335        };
336        // Constructor invariants: shelf order pins the reserved ids, and a
337        // fresh catalog holds nothing.
338        debug_assert_eq!(inner.terms[0], EncodedTerm::Placeholder);
339        debug_assert_eq!(inner.terms[1], EncodedTerm::DefaultGraph);
340        debug_assert_eq!(inner.terms[2], RDF_TYPE);
341        debug_assert_eq!(inner.terms[3], ENCODED_TERM_TRUE);
342        debug_assert_eq!(inner.occupied, 0);
343        debug_assert!(match &inner.catalog {
344            Catalog::Small(slots) => slots.iter().all(|s| *s == Slot8::EMPTY),
345            Catalog::Large(slots) => slots.iter().all(|s| *s == Slot16::EMPTY),
346        });
347        Self {
348            inner: Mutex::new(inner),
349        }
350    }
351
352    /// Shared dict for a [`crate`]-external [`std::sync::Arc`] holder (compute).
353    pub fn new_shared() -> Arc<Self> {
354        Arc::new(Self::new())
355    }
356
357    /// Distinct terms interned so far — instrumentation for spotting
358    /// hash-table doubling boundaries (a rehash shows up as a one-time
359    /// materialization spike at a power of two). Never empty: the dict
360    /// starts with 4 reserved terms.
361    #[allow(clippy::len_without_is_empty)]
362    pub fn len(&self) -> usize {
363        self.inner.lock().expect("term dict mutex").terms.len()
364    }
365
366    /// Reserve capacity for `additional` more terms beyond the current
367    /// length, so a plan-estimated interning burst cannot trigger a
368    /// mid-execution hash-doubling rehash — a one-time full-table
369    /// relocation under the dict mutex (profiled as a 38–196ms stall when
370    /// a query crossed the 458,752-entry boundary mid-driver-page).
371    pub fn reserve(&self, additional: usize) {
372        self.inner
373            .lock()
374            .expect("term dict mutex")
375            .reserve_for(additional);
376    }
377
378    /// Intern `term`. Well-known DefaultGraph / `rdf:type` skip the map lock
379    /// after a cheap match. Other terms: existing index or sequential insert
380    /// from 4. Hitting the id ceiling ([`has_room_for_one_more`]) is
381    /// [`ExecError::TooManyTerms`].
382    pub fn intern(&self, term: EncodedTerm) -> Result<TermId, ExecError> {
383        if matches!(term, EncodedTerm::Placeholder) {
384            return Err(ExecError::LengthMismatch(
385                "EncodedTerm::Placeholder is not internable".into(),
386            ));
387        }
388        // Well-known fast path for DefaultGraph / RDF_TYPE; else catalog
389        // lookup or insert. TermId == shelf position.
390        if matches!(term, EncodedTerm::DefaultGraph) {
391            return Ok(TermId::DEFAULT_GRAPH);
392        }
393        if term == RDF_TYPE {
394            return Ok(TermId::RDF_TYPE);
395        }
396        if term == ENCODED_TERM_TRUE {
397            return Ok(TermId::COUNTED_PRESENCE);
398        }
399        let mut inner = self.inner.lock().expect("term dict mutex");
400        let hash = fx_hash_term(&term);
401        let vacant = match inner.find_existing(hash, &term) {
402            Ok(id) => return Ok(TermId(id)),
403            Err(vacant) => vacant,
404        };
405        // The catalog stores `position + 1`; a position of `u32::MAX` would
406        // wrap to the vacant marker, so the last usable id is `u32::MAX - 1`.
407        if !has_room_for_one_more(inner.terms.len()) {
408            return Err(ExecError::TooManyTerms);
409        }
410        Ok(inner.insert_new(hash, term, vacant))
411    }
412
413    /// Intern a borrowed term (clones on insert).
414    pub fn intern_ref(&self, term: &EncodedTerm) -> Result<TermId, ExecError> {
415        if matches!(term, EncodedTerm::Placeholder) {
416            return Err(ExecError::LengthMismatch(
417                "EncodedTerm::Placeholder is not internable".into(),
418            ));
419        }
420        if matches!(term, EncodedTerm::DefaultGraph) {
421            return Ok(TermId::DEFAULT_GRAPH);
422        }
423        if *term == RDF_TYPE {
424            return Ok(TermId::RDF_TYPE);
425        }
426        if *term == ENCODED_TERM_TRUE {
427            return Ok(TermId::COUNTED_PRESENCE);
428        }
429        let mut inner = self.inner.lock().expect("term dict mutex");
430        let hash = fx_hash_term(term);
431        let vacant = match inner.find_existing(hash, term) {
432            Ok(id) => return Ok(TermId(id)),
433            Err(vacant) => vacant,
434        };
435        if !has_room_for_one_more(inner.terms.len()) {
436            return Err(ExecError::TooManyTerms);
437        }
438        Ok(inner.insert_new(hash, term.clone(), vacant))
439    }
440
441    /// Pure lookup: the id `term` already has, or `None` if it was never
442    /// interned. Never mutates the dict — the read-side counterpart of
443    /// [`Self::intern_ref`]. Use it when a pushed term list may name terms
444    /// that exist elsewhere in the query (an ancestor's correlation
445    /// values, for one) and interning absent entries would grow the dict
446    /// without any column ever referencing them.
447    ///
448    /// Unlike [`Self::intern_ref`], a `Placeholder` maps to
449    /// `Some(TermId::UNBOUND)` instead of erroring — this is a lookup,
450    /// not an intern, and there is a well-defined id for "unbound".
451    /// Callers that partition rows by id already guard unbound cells
452    /// (`TermColumn::is_bound`), so id 0 is never consulted downstream.
453    pub fn peek(&self, term: &EncodedTerm) -> Option<TermId> {
454        if matches!(term, EncodedTerm::Placeholder) {
455            return Some(TermId::UNBOUND);
456        }
457        if matches!(term, EncodedTerm::DefaultGraph) {
458            return Some(TermId::DEFAULT_GRAPH);
459        }
460        if *term == RDF_TYPE {
461            return Some(TermId::RDF_TYPE);
462        }
463        if *term == ENCODED_TERM_TRUE {
464            return Some(TermId::COUNTED_PRESENCE);
465        }
466        let inner = self.inner.lock().expect("term dict mutex");
467        inner
468            .find_existing(fx_hash_term(term), term)
469            .ok()
470            .map(TermId)
471    }
472
473    /// Intern a column under one mutex.
474    ///
475    /// `None` cells become [`TermId::UNBOUND`] (`0`). Reserves `cells.len()`
476    /// extra catalog slots so inserts do not geometrically rehash, then lookup /
477    /// insert each cell. Drop the guard before I/O — this function is sync.
478    /// Bound columns should pass `values.into_iter().map(Some)` rather than
479    /// allocating a `Vec<Option<EncodedTerm>>`.
480    pub fn intern_column(
481        &self,
482        cells: impl ExactSizeIterator<Item = Option<EncodedTerm>>,
483    ) -> Result<Vec<u32>, ExecError> {
484        let n = cells.len();
485        let mut ids = Vec::with_capacity(n);
486        if n == 0 {
487            return Ok(ids);
488        }
489        // Materialize and pre-hash OUTSIDE the mutex: hashing touches only
490        // the terms, never the dict, and the precomputed hashes are what
491        // make the prefetch pass possible — the start-slot line of every
492        // upcoming cell is known before the intern loop reaches it.
493        let owned: Vec<Option<EncodedTerm>> = cells.collect();
494        let mut hashes: Vec<Option<u64>> = Vec::with_capacity(n);
495        for cell in &owned {
496            hashes.push(cell.as_ref().map(fx_hash_term));
497        }
498        let mut inner = self.inner.lock().expect("term dict mutex");
499        inner.reserve_for(n);
500        intern_prehashed_locked(&mut inner, owned, &hashes, &mut ids)?;
501        Ok(ids)
502    }
503
504    /// Intern N columns under ONE mutex acquisition.
505    ///
506    /// Semantically identical to calling [`Self::intern_column`] on each
507    /// column in order — ids are assigned in exactly the same sequence
508    /// (column after column, first cell to last), so a term appearing in
509    /// several columns gets one id everywhere — but the dict lock is taken
510    /// once and the catalog reserved once for the whole batch. A
511    /// multi-column page absorb (the path walker's S/O/G slots) then
512    /// serializes against concurrent interning on one acquisition instead
513    /// of N. Columns are moved in, never cloned; every cell is a bound
514    /// term (unbound cells do not exist at this boundary — callers omit
515    /// the row instead).
516    pub fn intern_columns<const N: usize>(
517        &self,
518        columns: [Vec<EncodedTerm>; N],
519    ) -> Result<[Vec<u32>; N], ExecError> {
520        // Pre-hash every column outside the mutex — the same discipline as
521        // [`Self::intern_column`], hoisted over all columns so the single
522        // locked pass pays no hashing at all.
523        let prehashed: [Vec<Option<EncodedTerm>>; N] =
524            columns.map(|column| column.into_iter().map(Some).collect());
525        let total: usize = prehashed.iter().map(Vec::len).sum();
526        if total == 0 {
527            return Ok(std::array::from_fn(|_| Vec::new()));
528        }
529        let hashes: [Vec<Option<u64>>; N] = std::array::from_fn(|slot| {
530            prehashed[slot]
531                .iter()
532                .map(|cell| cell.as_ref().map(fx_hash_term))
533                .collect()
534        });
535        let mut inner = self.inner.lock().expect("term dict mutex");
536        inner.reserve_for(total);
537        let mut out: [Vec<u32>; N] = std::array::from_fn(|_| Vec::new());
538        for (slot, (owned, column_hashes)) in prehashed.into_iter().zip(hashes.iter()).enumerate() {
539            intern_prehashed_locked(&mut inner, owned, column_hashes, &mut out[slot])?;
540        }
541        Ok(out)
542    }
543
544    /// Reverse lookup. Id `0` is always `None` (unbound, not the Placeholder slot).
545    pub fn get(&self, id: TermId) -> Option<EncodedTerm> {
546        self.inner.lock().expect("term dict mutex").lookup_id(id.0)
547    }
548
549    /// Reverse-lookup many TermIds under one mutex.
550    ///
551    /// `ids` is the raw `u32` buffer from [`crate::TermColumn::ids`] (`0` =
552    /// unbound → `None`). `ids.len()` must equal `out.len()` (caller bug).
553    /// Whole-row / column / frame materialize must use this instead of looping
554    /// [`Self::get`]. Clone terms out and drop the guard — do not hold the
555    /// lock across `decode_term`, SPARQL eval, or I/O.
556    pub fn get_many(&self, ids: &[u32], out: &mut [Option<EncodedTerm>]) {
557        assert_eq!(ids.len(), out.len());
558        if ids.is_empty() {
559            return;
560        }
561        let inner = self.inner.lock().expect("term dict mutex");
562        for (id, slot) in ids.iter().zip(out.iter_mut()) {
563            *slot = inner.lookup_id(*id);
564        }
565    }
566}
567
568/// FxHash of one term — the same hash function the previous IndexMap used.
569/// Computed once per intern call and reused by the probe walk, the insert,
570/// and any catalog rebuild the insert triggers.
571fn fx_hash_term(term: &EncodedTerm) -> u64 {
572    let mut h = <FxBuildHasher as BuildHasher>::build_hasher(&FxBuildHasher);
573    term.hash(&mut h);
574    h.finish()
575}
576
577/// Prefetch the cache line containing `ptr`. Pure hint — safe for any
578/// address, no correctness effect, ignored on non-x86_64 targets.
579#[inline]
580fn prefetch(ptr: *const ()) {
581    #[cfg(target_arch = "x86_64")]
582    // SAFETY: _mm_prefetch is a pure performance hint; any address is fine.
583    unsafe {
584        std::arch::x86_64::_mm_prefetch(ptr as *const i8, std::arch::x86_64::_MM_HINT_T0);
585    }
586    #[cfg(not(target_arch = "x86_64"))]
587    let _ = ptr;
588}
589
590/// The locked probe/insert loop shared by [`TermDict::intern_column`] and
591/// [`TermDict::intern_columns`]: pre-hashed cells in, ids appended to `ids`.
592/// The caller holds the dict lock and has already reserved catalog space for
593/// the batch; `hashes[idx]` must be the hash of `owned[idx]` (`None` cells
594/// hash to `None` and become id `0`).
595///
596/// Prefetch uses the precomputed hashes to put the start-slot line of each
597/// upcoming cell in flight while the current insert completes — a pure hint,
598/// no correctness effect. The access dump (`intern-replay` feature) writes
599/// one record per interned cell and flushes per call: statics are not
600/// dropped at process exit, so the BufWriter's tail would otherwise be lost.
601/// Dump runs only; not on timing runs.
602fn intern_prehashed_locked(
603    inner: &mut TermDictInner,
604    owned: Vec<Option<EncodedTerm>>,
605    hashes: &[Option<u64>],
606    ids: &mut Vec<u32>,
607) -> Result<(), ExecError> {
608    let n = owned.len();
609    #[cfg(feature = "intern-replay")]
610    let dump = access_dump();
611    for (idx, cell) in owned.into_iter().enumerate() {
612        match cell {
613            None => ids.push(0),
614            Some(term) => {
615                // Prefetch the start-slot lines of the next
616                // PREFETCH_AHEAD cells so their first probe line is in
617                // flight while this insert completes. Prefetch is a pure
618                // hint — no correctness effect.
619                for k in 1..=PREFETCH_AHEAD {
620                    if idx + k >= n {
621                        break;
622                    }
623                    if let Some(h) = hashes[idx + k] {
624                        inner.prefetch_home(h);
625                    }
626                }
627                #[cfg(feature = "intern-replay")]
628                if let Some(w) = dump {
629                    let mut w = w.lock().expect("dump mutex");
630                    write_dump_term(&mut *w, &term);
631                }
632                ids.push(intern_with_hash(inner, term, hashes[idx].unwrap())?.as_u32());
633            }
634        }
635    }
636    #[cfg(feature = "intern-replay")]
637    if let Some(w) = dump {
638        let _ = w.lock().map(|mut w| w.flush());
639    }
640    Ok(())
641}
642
643/// Lookup or insert `term` in an already-locked dict.
644///
645/// Well-known DefaultGraph / `rdf:type` / XSD `true` skip the catalog.
646/// Placeholder is not internable. Hitting the id ceiling is
647/// [`ExecError::TooManyTerms`] — see [`has_room_for_one_more`] for why the
648/// last usable id is `u32::MAX - 1`.
649/// Lookup or insert `term` in an already-locked dict. The hash is passed in
650/// by [`TermDict::intern_column`], which pre-hashes columns outside the
651/// mutex so the intern loop can prefetch from the precomputed hashes (see
652/// `PREFETCH_AHEAD`).
653fn intern_with_hash(
654    inner: &mut TermDictInner,
655    term: EncodedTerm,
656    hash: u64,
657) -> Result<TermId, ExecError> {
658    if matches!(term, EncodedTerm::Placeholder) {
659        return Err(ExecError::LengthMismatch(
660            "EncodedTerm::Placeholder is not internable".into(),
661        ));
662    }
663    if matches!(term, EncodedTerm::DefaultGraph) {
664        return Ok(TermId::DEFAULT_GRAPH);
665    }
666    if term == RDF_TYPE {
667        return Ok(TermId::RDF_TYPE);
668    }
669    if term == ENCODED_TERM_TRUE {
670        return Ok(TermId::COUNTED_PRESENCE);
671    }
672    let vacant = match inner.find_existing(hash, &term) {
673        Ok(id) => return Ok(TermId(id)),
674        Err(vacant) => vacant,
675    };
676    if !has_room_for_one_more(inner.terms.len()) {
677        return Err(ExecError::TooManyTerms);
678    }
679    Ok(inner.insert_new(hash, term, vacant))
680}
681
682impl TermDictInner {
683    /// Catalog probe for `term`. Linear-probes from the hash's start slot;
684    /// the stored tag filters candidates inside the cache line the walk
685    /// already holds, and only a tag match pays the shelf fetch for the real
686    /// term comparison — the tag alone never decides correctness (a 32-bit
687    /// tag collides between distinct terms at rate n/2^32, so the walk
688    /// *continues past* a tag match whose shelf verify fails). Returns the
689    /// shelf id when the term is present, or `Err(vacant index)` — the first
690    /// vacant slot of the probe chain — so the caller places without
691    /// re-walking (fused find-or-place: the miss path previously probed the
692    /// chain twice, census-measured at 12.19 probes/insert). The Err index
693    /// is valid only while the catalog is unchanged: callers place
694    /// immediately under the same mutex hold; growth re-probes (see
695    /// insert_new). The load-factor guard keeps at least one vacant slot,
696    /// so the walk always terminates.
697    ///
698    /// `stored` holds the shelf position plus one (see [`Slot8`]), so the
699    /// position is decoded only once a live slot's tag or hash has matched —
700    /// a vacant slot and a probe-skipped slot cost no arithmetic at all.
701    #[inline]
702    fn find_existing(&self, hash: u64, term: &EncodedTerm) -> Result<u32, usize> {
703        let mask = self.mask as usize;
704        let mut i = ((hash >> 32) as usize) & mask;
705        match &self.catalog {
706            Catalog::Small(slots) => {
707                let tag = (hash >> 32) as u32;
708                loop {
709                    let slot = &slots[i];
710                    if slot.stored == 0 {
711                        return Err(i);
712                    }
713                    if slot.tag == tag {
714                        let id = slot.stored - 1;
715                        if self.terms[id as usize] == *term {
716                            return Ok(id);
717                        }
718                    }
719                    i = (i + 1) & mask;
720                }
721            }
722            Catalog::Large(slots) => loop {
723                let slot = &slots[i];
724                if slot.stored == 0 {
725                    return Err(i);
726                }
727                if slot.hash == hash {
728                    let id = slot.stored - 1;
729                    if self.terms[id as usize] == *term {
730                        return Ok(id);
731                    }
732                }
733                i = (i + 1) & mask;
734            },
735        }
736    }
737
738    /// Linear-probe to the first vacant slot and claim it for `(hash, id)`.
739    /// Requires at least one vacant slot, which the load-factor guard in
740    /// [`Self::insert_new`] guarantees before this runs. Placement comes
741    /// from the hash's high 32 bits in both modes, so Small-mode slots hold
742    /// the complete placement key. The slot stores `id + 1`, keeping `0` for
743    /// a vacant slot (see [`Slot8`]).
744    fn place(&mut self, hash: u64, id: u32) {
745        let mask = self.mask as usize;
746        let mut i = ((hash >> 32) as usize) & mask;
747        match &mut self.catalog {
748            Catalog::Small(slots) => {
749                let tag = (hash >> 32) as u32;
750                while slots[i].stored != 0 {
751                    i = (i + 1) & mask;
752                }
753                slots[i] = Slot8 {
754                    tag,
755                    stored: id + 1,
756                };
757            }
758            Catalog::Large(slots) => {
759                while slots[i].stored != 0 {
760                    i = (i + 1) & mask;
761                }
762                slots[i] = Slot16 {
763                    hash,
764                    stored: id + 1,
765                    _pad: 0,
766                };
767            }
768        }
769    }
770
771    /// Append `term` to the shelf (its position is the new id), grow the
772    /// catalog when the 7/8 load guard would be crossed, then claim a
773    /// slot. The caller has already checked the id ceiling. Crossing the
774    /// Small-mode threshold upgrades the catalog in place — the rebuild
775    /// walks the shelf, which already contains the just-pushed term, so no
776    /// separate placement is needed for it.
777    fn insert_new(&mut self, hash: u64, term: EncodedTerm, vacant: usize) -> TermId {
778        self.terms.push(term);
779        let id = (self.terms.len() - 1) as u32;
780        // The ceiling is enforced by every caller (`has_room_for_one_more`).
781        // It is re-pinned here because the offset encoding turns a missed
782        // check into a live slot that reads as vacant — a silent "term not
783        // found" rather than an out-of-range value.
784        debug_assert!(id < u32::MAX, "a position of u32::MAX cannot be stored");
785        if self.terms.len() > self.small_mode_max && matches!(self.catalog, Catalog::Small(_)) {
786            let min_slots = (self.terms.len() * SLOTS_LOAD_DEN)
787                .div_ceil(SLOTS_LOAD_NUM)
788                .next_power_of_two()
789                .max(SLOTS_MIN);
790            self.upgrade_to_large(min_slots);
791            self.occupied += 1;
792            return TermId(id);
793        }
794        if (self.occupied + 1) * SLOTS_LOAD_DEN > self.catalog.slot_count() * SLOTS_LOAD_NUM {
795            // Growth invalidates the pre-found vacant index (new mask,
796            // re-placed entries) — probe once in the fresh table instead;
797            // the rehash dominates this rare path, so the extra walk is
798            // noise.
799            self.rehash_slots(self.catalog.slot_count() * 2);
800            self.place(hash, id);
801        } else {
802            // Fused placement: the probe already located the first vacant
803            // slot of this chain; claiming it directly skips the redundant
804            // second walk (census: the miss path previously spent 12.19
805            // probes/insert, half of them the re-walk). The index is valid —
806            // the catalog cannot have changed between the probe and here
807            // (same mutex hold, no growth taken).
808            debug_assert!(vacant < self.catalog.slot_count());
809            match &mut self.catalog {
810                Catalog::Small(slots) => {
811                    slots[vacant] = Slot8 {
812                        tag: (hash >> 32) as u32,
813                        stored: id + 1,
814                    };
815                }
816                Catalog::Large(slots) => {
817                    slots[vacant] = Slot16 {
818                        hash,
819                        stored: id + 1,
820                        _pad: 0,
821                    };
822                }
823            }
824        }
825        self.occupied += 1;
826        TermId(id)
827    }
828
829    /// Reserve shelf + catalog capacity for `additional` more terms beyond
830    /// the current length, so a plan-estimated interning burst cannot
831    /// trigger a mid-execution catalog doubling — a one-time full-catalog
832    /// relocation under the dict mutex. The target is clamped to
833    /// [`MAX_RESERVE_TERMS`]: the reserve is advisory (growth continues
834    /// organically past it), and a larger clamp only risks an unsatisfiable
835    /// allocation. A target past the Small-mode threshold pre-selects Large
836    /// mode here, so the upgrade never fires mid-query; the catalog is then
837    /// sized for the estimate in the same rebuild.
838    ///
839    /// The shelf's own growth policy is `Vec::reserve`'s amortized doubling,
840    /// and its overshoot is accepted by design. When a page-burst crossing
841    /// lands near the end of a query's intern sequence, shelf capacity can
842    /// end at roughly twice the live term count — measured once at ~33 MB
843    /// of untouched shelf with ~0.8M live terms, freed when the dict drops.
844    /// The only in-tree signal for "growth has ended" is the plan estimate
845    /// this function is already fed (`reserve_term_dict_from_plan`), and it
846    /// undershot by hypothesis in exactly the case where the tail overshoot
847    /// appears — so doubling stays the correct bet under the uncertainty
848    /// that exists at each crossing. Growing the page path exactly instead
849    /// (`reserve_exact`) would re-copy the whole shelf on every crossing,
850    /// trading measured CPU for transient memory. Revisit only if shelf
851    /// overshoot shows up as resident-memory pressure under concurrent
852    /// queries; the fix shape there is exact growth toward a remembered
853    /// target with doubling past it, not per-page exact reserves.
854    fn reserve_for(&mut self, additional: usize) {
855        if additional == 0 {
856            return;
857        }
858        let target = self
859            .terms
860            .len()
861            .saturating_add(additional)
862            .min(MAX_RESERVE_TERMS);
863        // Once the shelf is past the clamp, `target` sits below the current
864        // length — growth past an advisory ceiling stays organic — so
865        // reserve nothing instead of underflowing.
866        self.terms.reserve(target.saturating_sub(self.terms.len()));
867        let crossing = target > self.small_mode_max && matches!(self.catalog, Catalog::Small(_));
868        // Catalog sized so the 7/8 guard never fires at or below `target`
869        // entries, rounded up to the next power of two (the mask requires
870        // it). One rebuild here replaces the whole doubling cascade the
871        // growth path would otherwise run mid-query.
872        let min_slots = (target * SLOTS_LOAD_DEN)
873            .div_ceil(SLOTS_LOAD_NUM)
874            .next_power_of_two()
875            .max(SLOTS_MIN);
876        if crossing {
877            self.upgrade_to_large(min_slots);
878            return;
879        }
880        if min_slots > self.catalog.slot_count() {
881            self.rehash_slots(min_slots);
882        }
883    }
884
885    /// Rebuild the catalog at `new_len` (a larger power of two),
886    /// re-placing every occupied entry from its stored tag — no term
887    /// re-hashing (both modes store the complete placement key), no shelf
888    /// moves, ids unchanged.
889    ///
890    /// The replacement array is allocated zero-filled (see [`zeroed_slots`]),
891    /// so a rebuild costs one write per *occupied* slot rather than one per
892    /// slot in the new table.
893    fn rehash_slots(&mut self, new_len: usize) {
894        debug_assert!(new_len.is_power_of_two());
895        debug_assert!(new_len > self.occupied);
896        self.mask = (new_len - 1) as u64;
897        match &mut self.catalog {
898            Catalog::Small(old) => {
899                let old = std::mem::replace(old, zeroed_slots(new_len));
900                for slot in old {
901                    if slot.stored != 0 {
902                        // The low 32 bits never participate in placement, so
903                        // a reconstructed hash with zero low bits places
904                        // identically to the original.
905                        self.place((slot.tag as u64) << 32, slot.stored - 1);
906                    }
907                }
908            }
909            Catalog::Large(old) => {
910                let old = std::mem::replace(old, zeroed_slots(new_len));
911                for slot in old {
912                    if slot.stored != 0 {
913                        self.place(slot.hash, slot.stored - 1);
914                    }
915                }
916            }
917        }
918    }
919
920    /// Re-select the catalog into 16-byte slots with full 64-bit tags by
921    /// re-hashing every interned term from the shelf — Small-mode slots
922    /// store only the hash's high half, so the low half must be recovered
923    /// from the terms themselves. Sequential shelf walk in id order (the
924    /// bandwidth-friendly direction); ids 0–3 are the reserved entries the
925    /// well-known fast paths answer before any probe, so they stay
926    /// catalog-less and `occupied` keeps meaning `len - RESERVED_TERMS`.
927    /// Ids never move; the transition is one-way.
928    fn upgrade_to_large(&mut self, min_slots: usize) {
929        debug_assert!(min_slots.is_power_of_two());
930        debug_assert!(min_slots > self.occupied);
931        let mut slots: Vec<Slot16> = zeroed_slots(min_slots);
932        let mask = min_slots - 1;
933        for (id, term) in self.terms.iter().enumerate().skip(RESERVED_TERMS) {
934            let hash = fx_hash_term(term);
935            let mut i = ((hash >> 32) as usize) & mask;
936            while slots[i].stored != 0 {
937                i = (i + 1) & mask;
938            }
939            slots[i] = Slot16 {
940                hash,
941                stored: id as u32 + 1,
942                _pad: 0,
943            };
944        }
945        self.catalog = Catalog::Large(slots);
946        self.mask = mask as u64;
947    }
948
949    /// Prefetch the cache line holding the start slot of `hash`'s probe
950    /// chain. Pure hint.
951    #[inline]
952    fn prefetch_home(&self, hash: u64) {
953        let i = ((hash >> 32) as usize) & (self.mask as usize);
954        match &self.catalog {
955            Catalog::Small(slots) => prefetch(slots.as_ptr().wrapping_add(i) as *const ()),
956            Catalog::Large(slots) => prefetch(slots.as_ptr().wrapping_add(i) as *const ()),
957        }
958    }
959
960    /// Reverse lookup: shelf position → term. Id `0` is always `None`
961    /// (unbound, never the Placeholder shelf entry).
962    #[inline]
963    fn lookup_id(&self, id: u32) -> Option<EncodedTerm> {
964        if id == 0 {
965            return None;
966        }
967        self.terms.get(id as usize).cloned()
968    }
969}
970
971impl Default for TermDict {
972    fn default() -> Self {
973        Self::new()
974    }
975}
976
977/// Teardown hooks for the `intern-replay` feature: write the dict dump
978/// (`WARATAH_DUMP_DICT`) when the last `Arc<TermDict>` drops, and report
979/// resident structure sizes (`WARATAH_DICT_SIZES`) for footprint analysis.
980/// Compiled only with `--features intern-replay`.
981///
982/// Only a dict with more than the 4 reserved ids writes its dump, so a late
983/// empty utility dict cannot truncate a real dump; write errors are
984/// reported, not swallowed. The size report runs after the timed region of
985/// a measurement, so timing runs are not perturbed.
986#[cfg(feature = "intern-replay")]
987impl Drop for TermDict {
988    fn drop(&mut self) {
989        // Size report (WARATAH_DICT_SIZES): the actual resident structure
990        // sizes at dict teardown.
991        if std::env::var_os("WARATAH_DICT_SIZES").is_some()
992            && let Ok(inner) = self.inner.lock()
993        {
994            let (mode, slots_len, slot_bytes) = match &inner.catalog {
995                Catalog::Small(slots) => ("slot8", slots.len(), std::mem::size_of::<Slot8>()),
996                Catalog::Large(slots) => ("slot16", slots.len(), std::mem::size_of::<Slot16>()),
997            };
998            eprintln!(
999                "dict-sizes variant=dense terms={} terms_cap={} mode={} slots={} slot_bytes={} term_bytes={} shelf_cap_bytes={}",
1000                inner.terms.len(),
1001                inner.terms.capacity(),
1002                mode,
1003                slots_len,
1004                slot_bytes,
1005                std::mem::size_of::<EncodedTerm>(),
1006                inner.terms.capacity() * std::mem::size_of::<EncodedTerm>(),
1007            );
1008        }
1009        if let Some(path) = std::env::var_os("WARATAH_DUMP_DICT") {
1010            let inner = match self.inner.lock() {
1011                Ok(inner) if inner.terms.len() > 4 => inner,
1012                _ => return,
1013            };
1014            let file = match std::fs::File::create(&path) {
1015                Ok(file) => std::io::BufWriter::with_capacity(1 << 20, file),
1016                Err(e) => {
1017                    eprintln!("dict-dump create {path:?} failed: {e}");
1018                    return;
1019                }
1020            };
1021            let mut w = file;
1022            for term in &inner.terms {
1023                // Shelf position 0 holds the Placeholder sentinel, which
1024                // write_dump_term's encoding refuses — and it is not a term
1025                // any consumer interned, so the replay does not need it.
1026                if matches!(term, EncodedTerm::Placeholder) {
1027                    continue;
1028                }
1029                write_dump_term(&mut w, term);
1030            }
1031            if let Err(e) = w.flush() {
1032                eprintln!("dict-dump flush {path:?} failed: {e}");
1033            }
1034        }
1035    }
1036}
1037
1038#[cfg(test)]
1039mod tests {
1040    use super::*;
1041    use waratah_storage::{Literal, NamedNode};
1042
1043    /// Term identity is bit identity, so the dict's catalog
1044    /// (Fx hash + Eq) must intern two equal NaN literals to ONE id — the
1045    /// pre-fix double-intern gave a join two ids for one term, and the
1046    /// join then missed the term against itself. The two zeros stay
1047    /// distinct terms.
1048    #[test]
1049    fn nan_literal_interns_once_and_the_zeros_stay_distinct() {
1050        let dict = TermDict::new();
1051        let first = dict
1052            .intern(EncodedTerm::DoubleLiteral(f64::NAN.into()))
1053            .unwrap();
1054        let second = dict
1055            .intern(EncodedTerm::DoubleLiteral(f64::NAN.into()))
1056            .unwrap();
1057        assert_eq!(first, second, "one NaN term = one id");
1058        let pos = dict.intern(EncodedTerm::DoubleLiteral(0.0.into())).unwrap();
1059        let neg = dict
1060            .intern(EncodedTerm::DoubleLiteral((-0.0).into()))
1061            .unwrap();
1062        assert_ne!(pos, neg, "+0.0 and -0.0 are two terms");
1063    }
1064
1065    fn iri(local: &str) -> EncodedTerm {
1066        EncodedTerm::from(&NamedNode::new(format!("http://ex/{local}")).unwrap())
1067    }
1068
1069    /// The vacant catalog encoding is the all-zero slot, which is what makes
1070    /// [`zeroed_slots`] sound and cheap. The size asserts and the zeroed
1071    /// transmute catch field-count and size drift — the cases a future edit
1072    /// is most likely to introduce. They cannot catch a same-size niche type
1073    /// (`NonZeroU32` in place of a `u32`), which has to be caught in review;
1074    /// that is the one slot-layout change this test does not guard.
1075    #[test]
1076    fn slot_layout_pins_the_zeroed_empty_encoding() {
1077        assert_eq!(std::mem::size_of::<Slot8>(), 8);
1078        assert_eq!(std::mem::size_of::<Slot16>(), 16);
1079        // SAFETY: both slot types are plain integer fields with no padding
1080        // that is ever read, so an all-zero byte pattern is a valid value.
1081        // The sizes are asserted above and re-checked by the transmute.
1082        let zero8: Slot8 = unsafe { std::mem::transmute([0u8; 8]) };
1083        let zero16: Slot16 = unsafe { std::mem::transmute([0u8; 16]) };
1084        assert_eq!(zero8, Slot8::EMPTY);
1085        assert_eq!(zero16, Slot16::EMPTY);
1086        assert_eq!(zero8.stored, 0);
1087        assert_eq!(zero16.stored, 0);
1088    }
1089
1090    /// The lazy allocation produces a catalog that already reads as vacant.
1091    #[test]
1092    fn zeroed_slots_read_as_empty() {
1093        let small: Vec<Slot8> = zeroed_slots(64);
1094        assert_eq!(small.len(), 64);
1095        assert!(small.iter().all(|slot| *slot == Slot8::EMPTY));
1096        let large: Vec<Slot16> = zeroed_slots(64);
1097        assert_eq!(large.len(), 64);
1098        assert!(large.iter().all(|slot| *slot == Slot16::EMPTY));
1099        assert!(zeroed_slots::<Slot8>(0).is_empty());
1100    }
1101
1102    /// Every live catalog entry stores its shelf position plus one, and
1103    /// decodes back to a real term. The vacant marker is never a live
1104    /// entry's value, and the reserved ids stay catalog-less.
1105    #[test]
1106    fn catalog_stores_position_plus_one() {
1107        let dict = TermDict::new();
1108        let a = dict.intern(iri("a")).unwrap().as_u32();
1109        let b = dict.intern(iri("b")).unwrap().as_u32();
1110        let c = dict.intern(iri("c")).unwrap().as_u32();
1111        let inner = dict.inner.lock().expect("term dict mutex");
1112        let mut stored: Vec<u32> = match &inner.catalog {
1113            Catalog::Small(slots) => slots.iter().map(|slot| slot.stored).collect(),
1114            Catalog::Large(slots) => slots.iter().map(|slot| slot.stored).collect(),
1115        };
1116        stored.retain(|value| *value != 0);
1117        stored.sort_unstable();
1118        assert_eq!(stored, vec![a + 1, b + 1, c + 1]);
1119        for &value in &stored {
1120            let term = inner
1121                .lookup_id(value - 1)
1122                .expect("a live slot decodes to a live id");
1123            assert_ne!(term, EncodedTerm::Placeholder);
1124        }
1125    }
1126
1127    /// The id ceiling belongs to the offset encoding: the last usable shelf
1128    /// position is `u32::MAX - 1`, so `position + 1` fits in the slot's u32.
1129    #[test]
1130    fn intern_gate_keeps_position_plus_one_in_range() {
1131        assert!(has_room_for_one_more(0));
1132        assert!(has_room_for_one_more(u32::MAX as usize - 1));
1133        assert!(!has_room_for_one_more(u32::MAX as usize));
1134    }
1135
1136    #[test]
1137    fn reserved_ids_are_stable() {
1138        let dict = TermDict::new();
1139        assert_eq!(
1140            dict.intern(EncodedTerm::DefaultGraph).unwrap(),
1141            TermId::DEFAULT_GRAPH
1142        );
1143        assert_eq!(dict.intern(RDF_TYPE).unwrap(), TermId::RDF_TYPE);
1144        assert_eq!(
1145            dict.intern(ENCODED_TERM_TRUE).unwrap(),
1146            TermId::COUNTED_PRESENCE
1147        );
1148        assert_eq!(
1149            dict.get(TermId::DEFAULT_GRAPH),
1150            Some(EncodedTerm::DefaultGraph)
1151        );
1152        assert_eq!(dict.get(TermId::RDF_TYPE), Some(RDF_TYPE));
1153        assert_eq!(dict.get(TermId::COUNTED_PRESENCE), Some(ENCODED_TERM_TRUE));
1154        assert_eq!(dict.get(TermId::UNBOUND), None);
1155    }
1156
1157    #[test]
1158    fn intern_is_stable_and_sequential() {
1159        let dict = TermDict::new();
1160        let a = dict.intern(iri("alice")).unwrap();
1161        let b = dict.intern(iri("bob")).unwrap();
1162        assert_eq!(a, TermId(4));
1163        assert_eq!(b, TermId(5));
1164        assert_eq!(dict.intern(iri("alice")).unwrap(), a);
1165        let lit = EncodedTerm::from(&Literal::from("Sunny"));
1166        let c = dict.intern(lit.clone()).unwrap();
1167        assert_eq!(c, TermId(6));
1168        assert_eq!(dict.get(c), Some(lit));
1169    }
1170
1171    #[test]
1172    fn unbound_is_never_an_intern_slot() {
1173        let dict = TermDict::new();
1174        let _ = dict.intern(iri("a")).unwrap();
1175        assert!(dict.get(TermId::UNBOUND).is_none());
1176    }
1177
1178    #[test]
1179    fn placeholder_is_not_internable() {
1180        let dict = TermDict::new();
1181        assert!(dict.intern(EncodedTerm::Placeholder).is_err());
1182    }
1183
1184    /// The dense layout must reproduce the previous implementation's id
1185    /// semantics exactly: id = insertion position, well-known terms pinned
1186    /// to ids 1–3, Placeholder never internable. The reference model is a
1187    /// plain insertion-ordered map (Vec + HashMap) driven by the same
1188    /// deterministic term stream. Ids and reverse lookups must agree after
1189    /// every step, across many catalog doublings from the 8-slot start and
1190    /// interleaved reserve calls that exercise `reserve_for` +
1191    /// `rehash_slots` with entries present.
1192    #[test]
1193    fn dense_layout_matches_reference_model() {
1194        // xorshift64* — deterministic, no rand dependency.
1195        let mut seed: u64 = 0x9E37_79B9_7F4A_7C15;
1196        let mut next = move || {
1197            seed ^= seed >> 12;
1198            seed ^= seed << 25;
1199            seed ^= seed >> 27;
1200            seed.wrapping_mul(0x2545_F491_4F6C_DD1D)
1201        };
1202
1203        let dict = TermDict::new();
1204
1205        // Reference model: insertion-ordered term → id.
1206        let mut ref_terms: Vec<EncodedTerm> = vec![
1207            EncodedTerm::Placeholder,
1208            EncodedTerm::DefaultGraph,
1209            RDF_TYPE,
1210            ENCODED_TERM_TRUE,
1211        ];
1212        let mut ref_index: std::collections::HashMap<EncodedTerm, u32> =
1213            std::collections::HashMap::new();
1214
1215        let mk_term =
1216            |i: u64| EncodedTerm::from(&NamedNode::new(format!("http://ex/t{i}")).unwrap());
1217
1218        let mut made = 0u64;
1219        for step in 0..20_000u64 {
1220            // 40% brand-new terms, 60% re-interns of an existing term
1221            // (catalog hits).
1222            let term = if made == 0 || next() % 100 < 40 {
1223                let t = mk_term(made);
1224                made += 1;
1225                t
1226            } else {
1227                mk_term(next() % made)
1228            };
1229
1230            // Periodic reserve: exercises reserve_for + rehash_slots with
1231            // entries present.
1232            if step % 1_000 == 999 {
1233                dict.reserve((next() % 2_000) as usize);
1234            }
1235
1236            let got = dict.intern(term.clone()).unwrap();
1237            let want = match &term {
1238                EncodedTerm::DefaultGraph => TermId::DEFAULT_GRAPH,
1239                t if *t == RDF_TYPE => TermId::RDF_TYPE,
1240                t if *t == ENCODED_TERM_TRUE => TermId::COUNTED_PRESENCE,
1241                t => match ref_index.get(t) {
1242                    Some(id) => TermId(*id),
1243                    None => {
1244                        ref_terms.push(term.clone());
1245                        let id = (ref_terms.len() - 1) as u32;
1246                        ref_index.insert(term.clone(), id);
1247                        TermId(id)
1248                    }
1249                },
1250            };
1251            assert_eq!(got, want, "id mismatch at step {step} for {term:?}");
1252
1253            // Reverse lookups agree, sampled.
1254            if step % 97 == 0 {
1255                assert_eq!(dict.get(got).as_ref(), Some(&term));
1256                assert_eq!(dict.peek(&term), Some(got));
1257            }
1258        }
1259
1260        // Whole-shelf equality at the end: same insertion order ⇒ same
1261        // id → term map. Id 0 is unbound and never returned from `get`,
1262        // so it is excluded here (the Placeholder shelf entry is not
1263        // observable through the public API).
1264        assert_eq!(dict.len(), ref_terms.len());
1265        for id in 1..ref_terms.len() as u32 {
1266            assert_eq!(dict.get(TermId(id)).as_ref(), Some(&ref_terms[id as usize]));
1267        }
1268        let all_ids: Vec<u32> = (1..ref_terms.len() as u32).collect();
1269        let mut out = vec![None; all_ids.len()];
1270        dict.get_many(&all_ids, &mut out);
1271        for (got, want) in out.iter().zip(ref_terms[1..].iter()) {
1272            assert_eq!(got.as_ref(), Some(want));
1273        }
1274    }
1275
1276    /// Real 32-bit tag collision, brute-forced: with 32-bit tags, distinct
1277    /// terms share a tag at ~n²/2³³ pairs, so ~300k probe terms reliably
1278    /// contain several genuine pairs (P(none) ≈ 3e-5). Interning a colliding
1279    /// pair must give distinct ids and correct reverse lookups in both walk
1280    /// orders — this exercises the verify-and-continue path with a collision
1281    /// no test could manufacture at 64-bit width.
1282    #[test]
1283    fn slot8_real_tag_collision_keeps_terms_distinct() {
1284        let mk =
1285            |i: u64| EncodedTerm::from(&NamedNode::new(format!("http://ex/collide/{i}")).unwrap());
1286        let mut first_by_tag: std::collections::HashMap<u32, u64> =
1287            std::collections::HashMap::new();
1288        let mut pair = None;
1289        for i in 0..300_000u64 {
1290            let tag = (fx_hash_term(&mk(i)) >> 32) as u32;
1291            match first_by_tag.get(&tag) {
1292                Some(&j) => {
1293                    pair = Some((j, i));
1294                    break;
1295                }
1296                None => {
1297                    first_by_tag.insert(tag, i);
1298                }
1299            }
1300        }
1301        let (ia, ib) = pair.expect("birthday bound guarantees a colliding pair below 300k");
1302
1303        let term_a = mk(ia);
1304        let term_b = mk(ib);
1305        assert_ne!(term_a, term_b, "distinct terms, identical 32-bit tag");
1306
1307        let dict = TermDict::new();
1308        let id_a = dict.intern(term_a.clone()).unwrap();
1309        let id_b = dict.intern(term_b.clone()).unwrap();
1310        assert_ne!(id_a, id_b, "same-tag terms must get distinct ids");
1311        assert_eq!(dict.get(id_a).as_ref(), Some(&term_a));
1312        assert_eq!(dict.get(id_b).as_ref(), Some(&term_b));
1313        assert_eq!(dict.peek(&term_a), Some(id_a));
1314        assert_eq!(dict.peek(&term_b), Some(id_b));
1315        // Re-intern in the reverse order: the walk must still resolve both.
1316        assert_eq!(dict.intern(term_b.clone()).unwrap(), id_b);
1317        assert_eq!(dict.intern(term_a.clone()).unwrap(), id_a);
1318    }
1319
1320    /// Large-mode verify-and-continue: 64-bit tags cannot be collided by
1321    /// brute force, so this manufactures one — two shelf entries whose
1322    /// stored hashes are identical but whose terms differ. `find_existing`
1323    /// must step past the first hash match (its shelf verify fails) and
1324    /// resolve the second; a third term with the same hash must miss.
1325    #[test]
1326    fn large_mode_hash_match_still_verifies_the_term() {
1327        let term_a = EncodedTerm::from(&NamedNode::new("http://ex/whitebox-a").unwrap());
1328        let term_b = EncodedTerm::from(&NamedNode::new("http://ex/whitebox-b").unwrap());
1329        let term_c = EncodedTerm::from(&NamedNode::new("http://ex/whitebox-c").unwrap());
1330        let hash = fx_hash_term(&term_a);
1331
1332        let mut slots: Vec<Slot16> = zeroed_slots(SLOTS_MIN);
1333        let mask = (SLOTS_MIN - 1) as u64;
1334        let i = ((hash >> 32) as usize) & (mask as usize);
1335        slots[i] = Slot16 {
1336            hash,
1337            stored: 5,
1338            _pad: 0,
1339        };
1340        slots[(i + 1) & (mask as usize)] = Slot16 {
1341            hash,
1342            stored: 6,
1343            _pad: 0,
1344        };
1345
1346        let inner = TermDictInner {
1347            terms: vec![
1348                EncodedTerm::Placeholder,
1349                EncodedTerm::DefaultGraph,
1350                RDF_TYPE,
1351                ENCODED_TERM_TRUE,
1352                term_a.clone(),
1353                term_b.clone(),
1354            ],
1355            catalog: Catalog::Large(slots),
1356            mask,
1357            occupied: 2,
1358            small_mode_max: usize::MAX,
1359        };
1360        assert_eq!(inner.find_existing(hash, &term_a), Ok(4));
1361        assert_eq!(inner.find_existing(hash, &term_b), Ok(5));
1362        assert!(inner.find_existing(hash, &term_c).is_err());
1363    }
1364
1365    /// The Small → Large transition must preserve id semantics: the upgrade
1366    /// re-hashes the shelf in place, so every id before and after the
1367    /// crossing must match the same insertion-order reference model. The
1368    /// threshold is lowered so the crossing happens early, and interleaved
1369    /// reserve calls exercise `reserve_for`'s threshold-aware sizing
1370    /// (a reserve past the threshold upgrades during the reserve).
1371    #[test]
1372    fn dense_layout_crosses_threshold_and_matches_reference() {
1373        // xorshift64* — deterministic, no rand dependency.
1374        let mut seed: u64 = 0x9E37_79B9_7F4A_7C15;
1375        let mut next = move || {
1376            seed ^= seed >> 12;
1377            seed ^= seed << 25;
1378            seed ^= seed >> 27;
1379            seed.wrapping_mul(0x2545_F491_4F6C_DD1D)
1380        };
1381
1382        let dict = TermDict::new();
1383        dict.inner.lock().unwrap().small_mode_max = 500;
1384
1385        let mut ref_terms: Vec<EncodedTerm> = vec![
1386            EncodedTerm::Placeholder,
1387            EncodedTerm::DefaultGraph,
1388            RDF_TYPE,
1389            ENCODED_TERM_TRUE,
1390        ];
1391        let mut ref_index: std::collections::HashMap<EncodedTerm, u32> =
1392            std::collections::HashMap::new();
1393        let mut seen_large = false;
1394
1395        let mk_term =
1396            |i: u64| EncodedTerm::from(&NamedNode::new(format!("http://ex/t{i}")).unwrap());
1397        let mut made = 0u64;
1398        for step in 0..8_000u64 {
1399            let term = if made == 0 || next() % 100 < 40 {
1400                let t = mk_term(made);
1401                made += 1;
1402                t
1403            } else {
1404                mk_term(next() % made)
1405            };
1406            if step % 500 == 499 {
1407                dict.reserve((next() % 1_500) as usize);
1408            }
1409            let got = dict.intern(term.clone()).unwrap();
1410            seen_large |= matches!(dict.inner.lock().unwrap().catalog, Catalog::Large(_));
1411            let want = match &term {
1412                EncodedTerm::DefaultGraph => TermId::DEFAULT_GRAPH,
1413                t if *t == RDF_TYPE => TermId::RDF_TYPE,
1414                t if *t == ENCODED_TERM_TRUE => TermId::COUNTED_PRESENCE,
1415                t => match ref_index.get(t) {
1416                    Some(id) => TermId(*id),
1417                    None => {
1418                        ref_terms.push(term.clone());
1419                        let id = (ref_terms.len() - 1) as u32;
1420                        ref_index.insert(term.clone(), id);
1421                        TermId(id)
1422                    }
1423                },
1424            };
1425            assert_eq!(got, want, "id mismatch at step {step}");
1426        }
1427        assert!(seen_large, "run must cross the threshold into Large mode");
1428        assert_eq!(dict.len(), ref_terms.len());
1429        for id in 1..ref_terms.len() as u32 {
1430            assert_eq!(dict.get(TermId(id)).as_ref(), Some(&ref_terms[id as usize]));
1431        }
1432    }
1433
1434    #[test]
1435    fn intern_column_matches_scalar_intern() {
1436        let dict = TermDict::new();
1437        let cells = vec![
1438            Some(EncodedTerm::DefaultGraph),
1439            None,
1440            Some(iri("alice")),
1441            Some(RDF_TYPE),
1442            Some(iri("alice")),
1443        ];
1444        let ids = dict.intern_column(cells.into_iter()).unwrap();
1445        assert_eq!(ids[0], TermId::DEFAULT_GRAPH.as_u32());
1446        assert_eq!(ids[1], 0);
1447        assert_eq!(ids[2], TermId(4).as_u32());
1448        assert_eq!(ids[3], TermId::RDF_TYPE.as_u32());
1449        assert_eq!(ids[4], ids[2]);
1450        assert_eq!(dict.get(TermId(ids[2])), Some(iri("alice")));
1451    }
1452
1453    #[test]
1454    fn intern_column_rejects_placeholder() {
1455        let dict = TermDict::new();
1456        assert!(
1457            dict.intern_column(std::iter::once(Some(EncodedTerm::Placeholder)))
1458                .is_err()
1459        );
1460    }
1461
1462    #[test]
1463    fn intern_columns_matches_sequential_intern_column() {
1464        // The batched multi-column intern must be interchangeable with
1465        // sequential single-column calls on a fresh dict: same ids in the
1466        // same order, including a term shared across columns (one id
1467        // everywhere), reserved ids, and an empty column staying empty.
1468        let shared = iri("shared");
1469        let columns = [
1470            vec![iri("a1"), shared.clone(), iri("a3")],
1471            Vec::new(),
1472            vec![shared.clone(), iri("c2"), EncodedTerm::DefaultGraph],
1473        ];
1474        let batched = TermDict::new();
1475        let sequential = TermDict::new();
1476        let got = batched.intern_columns(columns.clone()).unwrap();
1477        for (column, got) in columns.iter().zip(got.iter()) {
1478            let want = sequential
1479                .intern_column(column.iter().cloned().map(Some))
1480                .unwrap();
1481            assert_eq!(got, &want);
1482        }
1483        assert_eq!(got[0][1], got[2][0], "shared term must share one id");
1484        assert_eq!(got[2][2], TermId::DEFAULT_GRAPH.as_u32());
1485        assert_eq!(batched.len(), sequential.len());
1486    }
1487
1488    #[test]
1489    fn intern_columns_two_columns_dedup_across_columns() {
1490        let dict = TermDict::new();
1491        let [left, right] = dict
1492            .intern_columns([vec![iri("x"), iri("y")], vec![iri("y"), iri("z")]])
1493            .unwrap();
1494        assert_eq!(left[1], right[0], "y appears in both columns: one id");
1495        assert_eq!(dict.get(TermId(left[1])), Some(iri("y")));
1496        assert_eq!(left.len(), 2);
1497        assert_eq!(right.len(), 2);
1498    }
1499
1500    #[test]
1501    fn get_many_matches_get() {
1502        let dict = TermDict::new();
1503        let a = dict.intern(iri("alice")).unwrap();
1504        let b = dict.intern(iri("bob")).unwrap();
1505        let ids = [
1506            TermId::UNBOUND.as_u32(),
1507            TermId::DEFAULT_GRAPH.as_u32(),
1508            TermId::RDF_TYPE.as_u32(),
1509            a.as_u32(),
1510            b.as_u32(),
1511        ];
1512        let mut out = vec![None; ids.len()];
1513        dict.get_many(&ids, &mut out);
1514        assert_eq!(out[0], dict.get(TermId::UNBOUND));
1515        assert_eq!(out[1], dict.get(TermId::DEFAULT_GRAPH));
1516        assert_eq!(out[2], dict.get(TermId::RDF_TYPE));
1517        assert_eq!(out[3], dict.get(a));
1518        assert_eq!(out[4], dict.get(b));
1519    }
1520}
1521
1522/// Replay instrument (`intern-replay` feature): rebuild the dictionary from
1523/// a dumped corpus term list, replay the dumped access sequence, and print
1524/// per-lookup timings plus the probe census (slot inspections, cache lines
1525/// touched, shelf verifies) and the miss-path census (probes per insert).
1526/// Asserts id equivalence between the rebuilt shelf and the dump.
1527///
1528/// Run with:
1529/// `WARATAH_REPLAY=1 WARATAH_ACCESS_DUMP=<file> WARATAH_DICT_DUMP=<file>
1530/// cargo test -p waratah_exec --features intern-replay replay_corpus_access
1531/// -- --nocapture`.
1532#[cfg(all(test, feature = "intern-replay"))]
1533mod replay_probe {
1534    use super::*;
1535    use std::hint::black_box;
1536    use std::time::Instant;
1537    use waratah_storage::TermReader;
1538
1539    fn read_terms(path: &str) -> Vec<EncodedTerm> {
1540        let raw = std::fs::read(path).expect("dump file");
1541        let mut out = Vec::new();
1542        let mut pos = 0usize;
1543        while pos + 4 <= raw.len() {
1544            let len = u32::from_be_bytes(raw[pos..pos + 4].try_into().unwrap()) as usize;
1545            pos += 4;
1546            // DefaultGraph writes zero bytes (the empty record); read_term
1547            // cannot read an empty cursor.
1548            if len == 0 {
1549                out.push(EncodedTerm::DefaultGraph);
1550                continue;
1551            }
1552            let mut cursor = &raw[pos..pos + len];
1553            out.push(cursor.read_term().unwrap());
1554            pos += len;
1555        }
1556        out
1557    }
1558
1559    #[test]
1560    fn replay_corpus_access() {
1561        if std::env::var_os("WARATAH_REPLAY").is_none() {
1562            return;
1563        }
1564        let access = read_terms(&std::env::var("WARATAH_ACCESS_DUMP").unwrap());
1565        let dict_terms = read_terms(&std::env::var("WARATAH_DICT_DUMP").unwrap());
1566        println!(
1567            "access cells={} dict terms={}",
1568            access.len(),
1569            dict_terms.len()
1570        );
1571
1572        // Variant census over the real dict contents.
1573        let (mut nodes, mut bnodes, mut other) = (0u64, 0u64, 0u64);
1574        for t in &dict_terms {
1575            match t {
1576                EncodedTerm::NamedNode { .. } => nodes += 1,
1577                EncodedTerm::NumericalBlankNode { .. }
1578                | EncodedTerm::SmallBlankNode(_)
1579                | EncodedTerm::BigBlankNode { .. } => bnodes += 1,
1580                _ => other += 1,
1581            }
1582        }
1583        println!("dict mix: nodes={nodes} bnodes={bnodes} other(literals/graph)={other}");
1584
1585        let time = |name: &str, f: &mut dyn FnMut()| {
1586            f();
1587            let mut best = f64::MAX;
1588            for _ in 0..3 {
1589                let t = Instant::now();
1590                f();
1591                best = best.min(t.elapsed().as_secs_f64());
1592            }
1593            println!(
1594                "{name:<38} {best:>8.1} s  ({:.1} ns/cell)",
1595                best * 1e9 / access.len() as f64
1596            );
1597        };
1598
1599        // Same shelf seeding as TermDict::new: the reserved ids live only
1600        // on the shelf, never in the catalog. The threshold parameter
1601        // selects the catalog mode the run exercises (0 upgrades on the
1602        // first insert; usize::MAX never upgrades).
1603        let mk = |small_mode_max: usize| TermDictInner {
1604            terms: vec![
1605                EncodedTerm::Placeholder,
1606                EncodedTerm::DefaultGraph,
1607                RDF_TYPE,
1608                ENCODED_TERM_TRUE,
1609            ],
1610            catalog: Catalog::Small(zeroed_slots(SLOTS_MIN)),
1611            mask: (SLOTS_MIN - 1) as u64,
1612            occupied: 0,
1613            small_mode_max,
1614        };
1615
1616        // Calibration: the fused production path over the real access
1617        // sequence, in the mode production uses at this dict size (1.02M
1618        // terms < the 32M threshold → 8-byte slots).
1619        time("replay fused intern_locked (slot8)", &mut || {
1620            let mut inner = mk(SLOTS8_MAX_TERMS);
1621            for t in access.iter().cloned() {
1622                let h = fx_hash_term(&t);
1623                intern_with_hash(&mut inner, t, h).unwrap();
1624            }
1625            black_box(inner.terms.len());
1626        });
1627
1628        // Same stream with the catalog forced to 16-byte slots from the
1629        // first insert (threshold 0) — the slot-width comparison the corpus
1630        // A/B cannot isolate at this dict size.
1631        time("replay fused intern_locked (slot16)", &mut || {
1632            let mut inner = mk(0);
1633            for t in access.iter().cloned() {
1634                let h = fx_hash_term(&t);
1635                intern_with_hash(&mut inner, t, h).unwrap();
1636            }
1637            black_box(inner.terms.len());
1638        });
1639
1640        // Id equivalence against the dump, on the same input: the dump
1641        // recorded the previous implementation's insertion order minus the
1642        // Placeholder shelf entry, and the dense shelf must preserve that
1643        // order exactly — element-wise equality pins id-for-id
1644        // compatibility on real corpus data (production Small mode).
1645        {
1646            let mut inner = mk(SLOTS8_MAX_TERMS);
1647            for t in access.iter().cloned() {
1648                let h = fx_hash_term(&t);
1649                intern_with_hash(&mut inner, t, h).unwrap();
1650            }
1651            let replayed = &inner.terms[1..];
1652            assert_eq!(
1653                replayed.len(),
1654                dict_terms.len(),
1655                "replayed shelf length != dumped dict length"
1656            );
1657            let mut mismatches = 0usize;
1658            for (i, (a, b)) in replayed.iter().zip(dict_terms.iter()).enumerate() {
1659                if a != b {
1660                    mismatches += 1;
1661                    if mismatches <= 5 {
1662                        println!("  id mismatch @{}: replayed={a:?} dumped={b:?}", i + 1);
1663                    }
1664                }
1665            }
1666            assert_eq!(mismatches, 0, "{mismatches} id-order mismatches vs dump");
1667            println!("id equivalence vs dump: OK ({} terms)", replayed.len());
1668        }
1669
1670        // Component: hash only.
1671        time("hash-only (FxHash of term)", &mut || {
1672            let mut acc = 0u64;
1673            for t in &access {
1674                acc ^= fx_hash_term(t);
1675            }
1676            black_box(acc);
1677        });
1678
1679        // Component: full lookup (hash + probe walk + shelf verify) on the
1680        // final dict. Reserved terms stay catalog-less (the well-known fast
1681        // paths answer them), so they are skipped when warming.
1682        let mut warm = mk(SLOTS8_MAX_TERMS);
1683        for t in &dict_terms {
1684            if matches!(t, EncodedTerm::DefaultGraph) || *t == RDF_TYPE || *t == ENCODED_TERM_TRUE {
1685                continue;
1686            }
1687            let h = fx_hash_term(t);
1688            if let Err(vacant) = warm.find_existing(h, t) {
1689                warm.insert_new(h, t.clone(), vacant);
1690            }
1691        }
1692        time("find_existing only (real mix)", &mut || {
1693            let mut hits = 0u64;
1694            for t in &access {
1695                hits += warm.find_existing(fx_hash_term(t), t).is_ok() as u64;
1696            }
1697            println!(
1698                "  (hit rate on final dict: {:.1}%)",
1699                hits as f64 / access.len() as f64 * 100.0
1700            );
1701        });
1702
1703        // Component: pure miss path. The dump order is exactly the stream of
1704        // first occurrences, so replaying it into an empty dict never hits —
1705        // this isolates the insert-side cost, per catalog mode.
1706        for (label, threshold) in [("slot8", SLOTS8_MAX_TERMS), ("slot16", 0usize)] {
1707            time(
1708                &format!("insert-only [{label}] (first occurrences)"),
1709                &mut || {
1710                    let mut inner = mk(threshold);
1711                    for t in &dict_terms {
1712                        if matches!(t, EncodedTerm::DefaultGraph)
1713                            || *t == RDF_TYPE
1714                            || *t == ENCODED_TERM_TRUE
1715                        {
1716                            continue;
1717                        }
1718                        let h = fx_hash_term(t);
1719                        if let Err(vacant) = inner.find_existing(h, t) {
1720                            black_box(vacant);
1721                            inner.insert_new(h, t.clone(), vacant);
1722                        }
1723                    }
1724                    black_box(inner.terms.len());
1725                },
1726            );
1727        }
1728
1729        // Probe-economy census per catalog mode on the final dict (hit
1730        // path): slot inspections, distinct 64-byte cache lines, and shelf
1731        // verifies per lookup. The verify count is what a 32-bit tag adds —
1732        // a real tag collision makes the walk fetch a term it could
1733        // otherwise have skipped from the line it already holds. The walk
1734        // mirrors find_existing exactly (small: 8 slots/line → line =
1735        // i >> 3; large: 4 → i >> 2). Discriminates "more misses per
1736        // access" (footprint) from "more lines per access" (probe economy).
1737        fn census_walk(
1738            inner: &TermDictInner,
1739            hash: u64,
1740            term: &EncodedTerm,
1741            inspections: &mut u64,
1742            lines: &mut u64,
1743            verifies: &mut u64,
1744        ) {
1745            let mask = inner.mask as usize;
1746            let mut i = ((hash >> 32) as usize) & mask;
1747            let mut last_line = usize::MAX;
1748            match &inner.catalog {
1749                Catalog::Small(slots) => {
1750                    let tag = (hash >> 32) as u32;
1751                    loop {
1752                        let slot = &slots[i];
1753                        *inspections += 1;
1754                        let line = i >> 3;
1755                        if line != last_line {
1756                            *lines += 1;
1757                            last_line = line;
1758                        }
1759                        if slot.stored == 0 {
1760                            return;
1761                        }
1762                        if slot.tag == tag {
1763                            *verifies += 1;
1764                            if inner.terms[(slot.stored - 1) as usize] == *term {
1765                                return;
1766                            }
1767                        }
1768                        i = (i + 1) & mask;
1769                    }
1770                }
1771                Catalog::Large(slots) => loop {
1772                    let slot = &slots[i];
1773                    *inspections += 1;
1774                    let line = i >> 2;
1775                    if line != last_line {
1776                        *lines += 1;
1777                        last_line = line;
1778                    }
1779                    if slot.stored == 0 {
1780                        return;
1781                    }
1782                    if slot.hash == hash {
1783                        *verifies += 1;
1784                        if inner.terms[(slot.stored - 1) as usize] == *term {
1785                            return;
1786                        }
1787                    }
1788                    i = (i + 1) & mask;
1789                },
1790            }
1791        }
1792
1793        for (label, threshold) in [("slot8", SLOTS8_MAX_TERMS), ("slot16", 0usize)] {
1794            let mut warm = mk(threshold);
1795            for t in &dict_terms {
1796                if matches!(t, EncodedTerm::DefaultGraph)
1797                    || *t == RDF_TYPE
1798                    || *t == ENCODED_TERM_TRUE
1799                {
1800                    continue;
1801                }
1802                let h = fx_hash_term(t);
1803                if let Err(vacant) = warm.find_existing(h, t) {
1804                    warm.insert_new(h, t.clone(), vacant);
1805                }
1806            }
1807            let (mut inspections, mut lines, mut verifies, mut calls) = (0u64, 0u64, 0u64, 0u64);
1808            for t in &access {
1809                if matches!(t, EncodedTerm::DefaultGraph)
1810                    || *t == RDF_TYPE
1811                    || *t == ENCODED_TERM_TRUE
1812                {
1813                    continue;
1814                }
1815                calls += 1;
1816                census_walk(
1817                    &warm,
1818                    fx_hash_term(t),
1819                    t,
1820                    &mut inspections,
1821                    &mut lines,
1822                    &mut verifies,
1823                );
1824            }
1825            println!(
1826                "probe census [{label}]: calls={calls} inspections/call={:.2} lines/call={:.2} shelf_verifies/call={:.5} (verifies={verifies})",
1827                inspections as f64 / calls as f64,
1828                lines as f64 / calls as f64,
1829                verifies as f64 / calls as f64
1830            );
1831        }
1832
1833        // Miss-path census per mode: with fused find-or-place the insert
1834        // probes ONCE — the walk that discovers the first vacant slot is the
1835        // same walk that places (before the fusion this census counted a
1836        // second identical place walk: 12.19 probes/insert). Fresh dict +
1837        // distinct dumped terms means every walk is a pure miss.
1838        for (label, threshold) in [("slot8", SLOTS8_MAX_TERMS), ("slot16", 0usize)] {
1839            let mut inner = mk(threshold);
1840            let (mut probes, mut inserts) = (0u64, 0u64);
1841            for t in &dict_terms {
1842                if matches!(t, EncodedTerm::DefaultGraph)
1843                    || *t == RDF_TYPE
1844                    || *t == ENCODED_TERM_TRUE
1845                {
1846                    continue;
1847                }
1848                let h = fx_hash_term(t);
1849                inserts += 1;
1850                let mask = inner.mask as usize;
1851                let mut i = ((h >> 32) as usize) & mask;
1852                match &inner.catalog {
1853                    Catalog::Small(slots) => {
1854                        while slots[i].stored != 0 {
1855                            probes += 1;
1856                            i = (i + 1) & mask;
1857                        }
1858                    }
1859                    Catalog::Large(slots) => {
1860                        while slots[i].stored != 0 {
1861                            probes += 1;
1862                            i = (i + 1) & mask;
1863                        }
1864                    }
1865                }
1866                inner.insert_new(h, t.clone(), i);
1867            }
1868            println!(
1869                "miss census [{label}]: inserts={inserts} probes/insert={:.2} (fused find-or-place)",
1870                probes as f64 / inserts as f64
1871            );
1872        }
1873
1874        // Component: well-known fast-path checks alone.
1875        time("well-known checks alone", &mut || {
1876            let mut n = 0u64;
1877            for t in &access {
1878                n += matches!(t, EncodedTerm::DefaultGraph) as u64;
1879                n += (*t == RDF_TYPE) as u64;
1880                n += (*t == ENCODED_TERM_TRUE) as u64;
1881            }
1882            black_box(n);
1883        });
1884    }
1885}