Skip to main content

waratah_storage/
registry.rs

1//! Partition-hashed string registry shards (`StrHash` → raw string).
2
3use std::fmt;
4use std::io::Cursor;
5use std::path::{Path, PathBuf};
6use std::sync::OnceLock;
7
8use crate::encode::{EncodedQuad, StrHash, StrHashMap, new_str_hash_map, strings_entries_for_term};
9use crate::rocksdb::split_slices;
10use crate::rocksdb_db::{
11    ColumnFamily, ColumnFamilyDefinition, Db, SstFileWriter, WarmBlockCacheStats, env_flag,
12    warm_walk,
13};
14use crate::worker_pool;
15use crate::{
16    GraphName, Quad, REGISTRY_BLOCK_SIZE_BYTES, RocksDbOptionsHooks, RocksDbTuning, StorageError,
17    Term,
18};
19
20/// Column family holding `StrHash` → UTF-8 entries in [`RocksDbRegistry`].
21pub const REGISTRY_CF: &str = "entries";
22/// Subdirectory name under `{data_dir}/{repository}` for the disk registry.
23pub const REGISTRY_DIR_NAME: &str = "registry";
24
25/// Route a hash to a shard index with Murmur3-32.
26pub fn shard_id_for_hash(hash: StrHash, shard_count: usize) -> usize {
27    assert!(shard_count > 0, "shard_count must be > 0");
28    let mut cursor = Cursor::new(hash.to_be_bytes());
29    let h = murmur3::murmur3_32(&mut cursor, 0).expect("fixed-size input");
30    h as usize % shard_count
31}
32
33/// Single shard of the distributed string registry.
34pub trait RegistryShard {
35    /// Register `raw` under `hash` (overwrites on duplicate).
36    fn register(&mut self, hash: StrHash, raw: String) -> Result<(), StorageError>;
37
38    /// Look up the raw string for `hash`.
39    fn lookup(&self, hash: StrHash) -> Result<Option<String>, StorageError>;
40}
41
42/// In-memory registry shard keyed by [`StrHash`].
43#[derive(Debug, Default, Clone)]
44pub struct InMemoryRegistryShard {
45    entries: StrHashMap,
46}
47
48impl InMemoryRegistryShard {
49    /// Empty shard.
50    pub fn new() -> Self {
51        Self {
52            entries: new_str_hash_map(),
53        }
54    }
55}
56
57impl RegistryShard for InMemoryRegistryShard {
58    fn register(&mut self, hash: StrHash, raw: String) -> Result<(), StorageError> {
59        self.entries.insert(hash, raw);
60        Ok(())
61    }
62
63    fn lookup(&self, hash: StrHash) -> Result<Option<String>, StorageError> {
64        Ok(self.entries.get(&hash).cloned())
65    }
66}
67
68/// Partition-hashed multi-shard registry (MVP: in-memory).
69#[derive(Debug, Clone)]
70pub struct ShardedRegistry {
71    shards: Vec<InMemoryRegistryShard>,
72}
73
74impl ShardedRegistry {
75    /// Create `shard_count` empty shards.
76    pub fn new(shard_count: usize) -> Self {
77        assert!(shard_count > 0, "shard_count must be > 0");
78        Self {
79            shards: (0..shard_count)
80                .map(|_| InMemoryRegistryShard::new())
81                .collect(),
82        }
83    }
84
85    /// Number of shards.
86    pub fn shard_count(&self) -> usize {
87        self.shards.len()
88    }
89
90    /// Total `StrHash → raw` entries across in-memory shards.
91    pub fn entry_count(&self) -> u64 {
92        self.shards
93            .iter()
94            .map(|shard| shard.entries.len() as u64)
95            .sum()
96    }
97
98    /// Register a raw string on the shard selected by `hash`.
99    pub fn register(&mut self, hash: StrHash, raw: impl Into<String>) -> Result<(), StorageError> {
100        let shard = shard_id_for_hash(hash, self.shards.len());
101        self.shards[shard].register(hash, raw.into())
102    }
103
104    /// Look up a hash on the owning shard.
105    pub fn lookup(&self, hash: StrHash) -> Result<Option<String>, StorageError> {
106        let shard = shard_id_for_hash(hash, self.shards.len());
107        self.shards[shard].lookup(hash)
108    }
109
110    /// Positional bulk lookup (one HashMap get per hash).
111    pub fn lookup_many(&self, hashes: &[StrHash]) -> Result<Vec<Option<String>>, StorageError> {
112        hashes.iter().map(|hash| self.lookup(*hash)).collect()
113    }
114
115    /// Register all hash-referenced strings required by an encoded quad.
116    ///
117    /// `encoded` must be the same encoding the hexastore write path uses, so a
118    /// single insert encodes the quad once and shares it with the registry.
119    pub fn register_quad(
120        &mut self,
121        quad: &Quad,
122        encoded: &EncodedQuad,
123    ) -> Result<(), StorageError> {
124        for (hash, raw) in registry_entries_for_quad(quad, encoded) {
125            self.register(hash, raw)?;
126        }
127        Ok(())
128    }
129}
130
131/// RocksDB-backed inverse dictionary: 16-byte [`StrHash`] key → raw UTF-8 value.
132pub struct RocksDbRegistry {
133    db: Db,
134    cf: ColumnFamily,
135}
136
137impl fmt::Debug for RocksDbRegistry {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        f.debug_struct("RocksDbRegistry").finish_non_exhaustive()
140    }
141}
142
143/// Gate: resolve-path lookup strategy, process-wide
144/// (`WARATAH_RESOLVE_MULTIGET=1`; off by default).
145///
146/// Off (default): bulk resolve walks sorted seeks
147/// ([`RocksDbRegistry::lookup_many_seek`]) with the registry's fixed
148/// readahead — serial I/O, but streaming. On: batched point reads
149/// ([`RocksDbRegistry::lookup_many_multiget`]) — per-key blocks with no
150/// readahead, issued as one batch whose misses RocksDB can read
151/// independently. The A/B question is cold-cache misses, where the seek
152/// walk's serial per-key cost dominates (the warm pass only ever covers a
153/// fraction of a large dictionary).
154pub fn resolve_multiget_env_enabled() -> bool {
155    static GATE: OnceLock<bool> = OnceLock::new();
156    *GATE.get_or_init(|| {
157        env_flag(
158            "WARATAH_RESOLVE_MULTIGET",
159            std::env::var("WARATAH_RESOLVE_MULTIGET").ok().as_deref(),
160            false,
161        )
162    })
163}
164
165/// Parallel worker slice count for the registry seek walk
166/// (`WARATAH_REGISTRY_WALKS=<K>`, `K ≥ 2`).
167pub(crate) const REGISTRY_WALKS_ENV: &str = "WARATAH_REGISTRY_WALKS";
168/// `WARATAH_REGISTRY_WALKS` minimum (below it the knob is the serial walk) ...
169pub(crate) const REGISTRY_WALKS_MIN: usize = 2;
170/// ... and maximum per call (values above clamp to it).
171pub(crate) const REGISTRY_WALKS_MAX: usize = 64;
172/// Cap on the slice count the UNSET knob derives from the storage worker
173/// pool's width.
174///
175/// The registry resolve is a point-lookup walk: it is latency-bound, not
176/// CPU-bound, so it stops scaling before the pool width does. Eight is the
177/// largest count measured — a cold 312k-hash resolve cost 10.7 µs per hash
178/// at K=1 and 1.9 µs at K=8 on a 16-thread serve box, so a default at that
179/// box's pool width would put 16 seek threads on 8 physical cores. An
180/// explicit `WARATAH_REGISTRY_WALKS` is not bound by this cap; it exists
181/// only to keep the DERIVED default inside the measured range.
182const REGISTRY_WALKS_DEFAULT_MAX: usize = 8;
183/// Minimum sorted hash groups per parallel slice. Slices smaller than this
184/// cannot amortize the per-walker fixed costs (thread spawn/join, iterator
185/// construction, first-seek index/filter/readahead) against one seek of
186/// work each — a walker per single seek is strictly worse than the serial
187/// walk on a warm cache and marginal cold. Hardcoded (not an env): an
188/// amortization policy, not an operational knob — the precedent is
189/// `PUSHDOWN_TERMS_LIMIT`. Tune here once measurements justify it.
190const REGISTRY_WALKS_MIN_GROUPS_PER_SLICE: usize = 16;
191
192/// Resolved seek-walk worker count for this process (children inherit the
193/// env). `1` = the legacy single-iterator walk.
194///
195/// Precedence mirrors `WARATAH_DOMAIN_WALKS` / `WARATAH_COUNT_WALKS`, with
196/// one difference: the derived default is capped at
197/// [`REGISTRY_WALKS_DEFAULT_MAX`] because a point-lookup walk stops scaling
198/// before the pool width does. Unset → `min(cap, pool width)` (parallel on
199/// every machine with at least two cores); a valid `K` in `2..=64` → that
200/// count (values above clamp); `0` / `1` / junk warn and force the single
201/// walk — the serial opt-out, so a typo'd disable is never silent.
202pub(crate) fn registry_walks() -> usize {
203    static WALKS: OnceLock<usize> = OnceLock::new();
204    *WALKS.get_or_init(|| match std::env::var(REGISTRY_WALKS_ENV).ok() {
205        // Unset: enabled at min(cap, the storage pool's width) slices,
206        // resolved once here at first use. Serving processes install their
207        // pool at startup, before any walk can resolve this; a process with
208        // no pool (tests, batch tools) reports the machine's parallelism.
209        None => registry_walks_default(worker_pool::default_walk_width()),
210        // Explicit value: 0 / 1 / junk = the serial opt-out (warned);
211        // K >= 2 = that slice count.
212        Some(raw) => registry_walks_from_env(Some(raw.as_str())).unwrap_or(1),
213    })
214}
215
216/// The unset-knob slice count for a given pool width.
217fn registry_walks_default(pool_width: usize) -> usize {
218    pool_width.min(REGISTRY_WALKS_DEFAULT_MAX)
219}
220
221// The seek walk used to gate its slices with a process-wide permit pool
222// (`WARATAH_REGISTRY_WALKS_MAX`): each parallel call try-acquired one permit
223// per slice and degraded to fewer slices when the pool was exhausted. The
224// fixed-resident storage worker pool (`crate::worker_pool`) replaces that
225// mechanism: the pool width is the concurrency bound and its FIFO queues are
226// the backpressure, so a call waits for a worker instead of shrinking its
227// slice count. `WARATAH_REGISTRY_WALKS` still selects the requested slice
228// count per call.
229
230/// Slice count for one seek walk: `min(workers, groups / MIN)`, parallel
231/// only when that yields at least two slices of [`REGISTRY_WALKS_MIN_GROUPS_PER_SLICE`]
232/// groups; `0` means run the single walk.
233fn parallel_slice_count(groups: usize, workers: usize) -> usize {
234    if workers < 2 || groups < 2 {
235        return 0;
236    }
237    let ideal = workers.min(groups / REGISTRY_WALKS_MIN_GROUPS_PER_SLICE);
238    if ideal < 2 { 0 } else { ideal }
239}
240
241/// Parse one EXPLICIT `WARATAH_REGISTRY_WALKS` value into a worker count.
242///
243/// `0` / `1` / junk warn and return `None` (the serial opt-out — registry
244/// seeks are otherwise enabled by default at `min(8, pool width)`); values
245/// above [`REGISTRY_WALKS_MAX`] clamp to it. The unset case never reaches
246/// here — [`registry_walks`] derives the default.
247fn registry_walks_from_env(raw: Option<&str>) -> Option<usize> {
248    let raw = raw?;
249    match raw.trim().parse::<usize>() {
250        Ok(workers) if (REGISTRY_WALKS_MIN..=REGISTRY_WALKS_MAX).contains(&workers) => {
251            Some(workers)
252        }
253        Ok(workers) if workers > REGISTRY_WALKS_MAX => {
254            eprintln!(
255                "waratah-storage: clamping WARATAH_REGISTRY_WALKS={raw} to {REGISTRY_WALKS_MAX} \
256                 workers"
257            );
258            Some(REGISTRY_WALKS_MAX)
259        }
260        Ok(_) => {
261            eprintln!(
262                "waratah-storage: WARATAH_REGISTRY_WALKS={raw}: parallel registry seeks \
263                 disabled (0/1 is the serial opt-out; the default is \
264                 min({REGISTRY_WALKS_DEFAULT_MAX}, pool width))"
265            );
266            None
267        }
268        Err(_) => {
269            eprintln!(
270                "waratah-storage: ignoring invalid WARATAH_REGISTRY_WALKS {raw:?} (expected a \
271                 worker count >= {REGISTRY_WALKS_MIN}); using single-threaded registry seeks"
272            );
273            None
274        }
275    }
276}
277
278/// Self-attestation for benchmark discipline: once per process, the first
279/// parallel seek walk prints its effective slice count on stderr. Callers
280/// pass the dispatched count (after the pool-width clamp), not the requested
281/// worker count, so the receipt states what actually ran.
282fn attest_registry_walks(workers: usize) {
283    static ATTESTED: OnceLock<()> = OnceLock::new();
284    if ATTESTED.set(()).is_ok() {
285        eprintln!("storage-trace registry walk: parallel K={workers}");
286    }
287}
288
289/// Self-attestation for benchmark discipline: once per process, the first
290/// parallel pinned-multi-get resolve prints its effective slice count on
291/// stderr.
292fn attest_registry_multiget(workers: usize) {
293    static ATTESTED: OnceLock<()> = OnceLock::new();
294    if ATTESTED.set(()).is_ok() {
295        eprintln!("storage-trace registry multiget: parallel K={workers}");
296    }
297}
298
299impl RocksDbRegistry {
300    /// Open (or create) a registry DB at `path` with `tuning`.
301    pub fn open(path: impl AsRef<Path>, tuning: RocksDbTuning) -> Result<Self, StorageError> {
302        let path = path.as_ref();
303        if let Some(parent) = path.parent() {
304            std::fs::create_dir_all(parent).map_err(|e| StorageError::Backend(e.to_string()))?;
305        }
306        std::fs::create_dir_all(path).map_err(|e| StorageError::Backend(e.to_string()))?;
307        let db = Db::open_read_write_with_hooks(
308            path,
309            vec![ColumnFamilyDefinition {
310                name: REGISTRY_CF,
311                min_prefix_size: 0,
312                prefix_filter: false,
313                permutation: None,
314            }],
315            RocksDbOptionsHooks {
316                tuning,
317                ..Default::default()
318            },
319        )?;
320        let cf = db.column_family(REGISTRY_CF)?;
321        let registry = Self { db, cf };
322        // A killed offline import leaves finished `run-*.sst` files beside this
323        // directory. Ingest them before the registry is served. A failed ingest
324        // leaves the files in place; the next open tries again.
325        registry.recover_staged_sst_runs(&crate::layout::registry_sst_staging_dir(path))?;
326        Ok(registry)
327    }
328
329    /// Put `hash` → `raw` (overwrites on duplicate).
330    pub fn register(&self, hash: StrHash, raw: impl AsRef<[u8]>) -> Result<(), StorageError> {
331        self.db.insert(&self.cf, &hash.to_be_bytes(), raw.as_ref())
332    }
333
334    /// Look up the raw UTF-8 string for `hash`.
335    pub fn lookup(&self, hash: StrHash) -> Result<Option<String>, StorageError> {
336        match self.db.get(&self.cf, &hash.to_be_bytes())? {
337            None => Ok(None),
338            Some(bytes) => Ok(Some(registry_utf8(bytes)?)),
339        }
340    }
341
342    /// Bulk resolve, positional like [`Self::lookup`].
343    ///
344    /// The lookup strategy is gated process-wide by `WARATAH_RESOLVE_MULTIGET`
345    /// (see [`resolve_multiget_env_enabled`]): off (default) walks sorted
346    /// seeks ([`Self::lookup_many_seek`]); on uses batched point reads
347    /// ([`Self::lookup_many_multiget`]). Both are positional and return
348    /// identical results — `rocksdb_lookup_many_seek_matches_get_and_multiget`
349    /// holds all three equal — differing only in I/O shape on a cold cache.
350    pub fn lookup_many(&self, hashes: &[StrHash]) -> Result<Vec<Option<String>>, StorageError> {
351        if resolve_multiget_env_enabled() {
352            self.lookup_many_multiget(hashes)
353        } else {
354            self.lookup_many_seek(hashes)
355        }
356    }
357
358    /// Sorted unique keys, then monotonic `Seek` over one iterator per slice.
359    ///
360    /// Default resolve path (`WARATAH_RESOLVE_MULTIGET` off): the registry's
361    /// fixed readahead and streaming per-key I/O, on one iterator or — the
362    /// process default — several key-disjoint slices of the sorted groups.
363    ///
364    /// Execution is gated process-wide by `WARATAH_REGISTRY_WALKS` (see
365    /// [`registry_walks`]): unset splits into `min(8, pool width)` slices,
366    /// `K ≥ 2` sets that count, and `0` / `1` keeps the legacy single walk.
367    /// Each slice is one storage worker with its own iterator (see
368    /// [`Self::lookup_many_seek_with_workers`]).
369    pub fn lookup_many_seek(
370        &self,
371        hashes: &[StrHash],
372    ) -> Result<Vec<Option<String>>, StorageError> {
373        self.lookup_many_seek_with_workers(hashes, registry_walks())
374    }
375
376    /// [`Self::lookup_many_seek`] with an explicit worker count (tests pin
377    /// per-mode behavior without process-global env).
378    ///
379    /// With `workers < 2` (or fewer than two hash groups) this is the legacy
380    /// single-iterator walk. Otherwise the sorted unique hash groups split
381    /// into `min(workers, groups / MIN, pool width)` contiguous key-disjoint
382    /// slices — `MIN` is [`REGISTRY_WALKS_MIN_GROUPS_PER_SLICE`], so no
383    /// worker is used for a slice too small to amortize its fixed costs, and
384    /// requests below the two-slice threshold run serially. The groups are
385    /// unique and sorted, so slices are ascending key ranges and the ordered
386    /// concatenation is exactly the single walk's visit order.
387    ///
388    /// Slices run as units of the process-wide storage worker pool
389    /// ([`crate::worker_pool`]; a scoped-thread spawn before any pool is
390    /// installed). The pool width bounds concurrency and its FIFO queues are
391    /// the backpressure, so this call waits for workers instead of shrinking
392    /// its slice count under load. Every group costs one exact-match seek,
393    /// and a seek target below the iterator's current key (possible only
394    /// across a slice boundary, which workers never cross) would simply not
395    /// match — each worker's result depends only on its own slice's keys, so
396    /// any slice count returns identical positional results. Errors
397    /// propagate in slice order, first worker `Err` wins; a panicking worker
398    /// is caught by the pool and surfaces as a `StorageError` in that same
399    /// first-`Err` position.
400    pub(crate) fn lookup_many_seek_with_workers(
401        &self,
402        hashes: &[StrHash],
403        workers: usize,
404    ) -> Result<Vec<Option<String>>, StorageError> {
405        if hashes.is_empty() {
406            return Ok(Vec::new());
407        }
408        let groups = sorted_hash_groups(hashes);
409        let mut out = vec![None; hashes.len()];
410        let count = parallel_slice_count(groups.len(), workers).min(worker_pool::effective_width());
411        if count < 2 {
412            let values = seek_groups_on(&self.db, &self.cf, &groups)?;
413            for ((_, indexes), value) in groups.iter().zip(values) {
414                scatter_value(&mut out, indexes, value);
415            }
416            return Ok(out);
417        }
418        attest_registry_walks(count);
419        let slices = split_slices(groups.len(), count);
420        // One shared, immutable group list: a unit carries the range of its
421        // own key-disjoint slice instead of copying the (potentially large)
422        // index vectors, and still owns everything it touches.
423        let groups = std::sync::Arc::new(groups);
424        let units: Vec<RegistrySeekUnit> = slices
425            .iter()
426            .map(|slice| RegistrySeekUnit {
427                db: self.db.clone(),
428                cf: self.cf,
429                groups: std::sync::Arc::clone(&groups),
430                range: slice.clone(),
431            })
432            .collect();
433        let outcomes = worker_pool::run_units(units);
434        for (slice, outcome) in slices.iter().zip(outcomes) {
435            // First worker `Err` wins; slice order keeps the merge ordered.
436            let values = match outcome {
437                worker_pool::UnitOutcome::Ok(result) => result?,
438                worker_pool::UnitOutcome::Panicked(message) => {
439                    return Err(StorageError::Backend(format!(
440                        "registry seek walk worker panicked: {message}"
441                    )));
442                }
443            };
444            for ((_, indexes), value) in groups[slice.clone()].iter().zip(values) {
445                scatter_value(&mut out, indexes, value);
446            }
447        }
448        Ok(out)
449    }
450
451    /// Sorted unique keys, then one pinned batched `MultiGet`
452    /// (`WARATAH_RESOLVE_MULTIGET=1`): point reads whose misses can be
453    /// served independently instead of the walk's serial span. Values are
454    /// pinned in RocksDB until the batch drops, so the classic C API's
455    /// per-value malloc/copy/free is gone. Sorted batches pass
456    /// `sorted_input=true`, skipping RocksDB's internal copy-and-sort of
457    /// the key array.
458    ///
459    /// Parallelism follows [`registry_walks`]: the unset default (and any
460    /// explicit `WARATAH_REGISTRY_WALKS=K`) splits the sorted hash groups
461    /// into contiguous slices, each resolved by its own storage worker (see
462    /// [`Self::lookup_many_multiget_with_workers`]). Sharing the knob with
463    /// the seek walk keeps the gate A/B fair by construction: both arms run
464    /// the same K against the same pool width.
465    pub fn lookup_many_multiget(
466        &self,
467        hashes: &[StrHash],
468    ) -> Result<Vec<Option<String>>, StorageError> {
469        self.lookup_many_multiget_with_workers(hashes, registry_walks())
470    }
471
472    /// [`Self::lookup_many_multiget`] with an explicit worker count (tests
473    /// pin per-mode behavior without process-global env).
474    ///
475    /// Mirrors [`Self::lookup_many_seek_with_workers`]: `workers < 2` (or
476    /// fewer than two hash groups) runs the single batch; otherwise the
477    /// sorted unique hash groups split into
478    /// `min(workers, groups / MIN, pool width)` contiguous key-disjoint
479    /// slices — `MIN` is [`REGISTRY_WALKS_MIN_GROUPS_PER_SLICE`], so no
480    /// worker is used for a slice too small to amortize its fixed costs,
481    /// and requests below the two-slice threshold run serially. The groups
482    /// are unique and sorted, so slices are ascending key ranges and the
483    /// ordered scatter of slice results is exactly the single batch's
484    /// positions.
485    ///
486    /// Slices run as units of the process-wide storage worker pool
487    /// ([`crate::worker_pool`]; a scoped-thread spawn before any pool is
488    /// installed). The pool width bounds concurrency and its FIFO queues
489    /// are the backpressure. Each slice is one sorted pinned MultiGet —
490    /// `sorted_input=true` holds per slice, skipping the internal
491    /// copy-and-sort. Errors propagate in slice order, first worker `Err`
492    /// wins; a panicking worker is caught by the pool and surfaces as a
493    /// `StorageError` in that same first-`Err` position.
494    pub(crate) fn lookup_many_multiget_with_workers(
495        &self,
496        hashes: &[StrHash],
497        workers: usize,
498    ) -> Result<Vec<Option<String>>, StorageError> {
499        if hashes.is_empty() {
500            return Ok(Vec::new());
501        }
502        let groups = sorted_hash_groups(hashes);
503        let mut out = vec![None; hashes.len()];
504        let count = parallel_slice_count(groups.len(), workers).min(worker_pool::effective_width());
505        if count < 2 {
506            let values = multiget_groups_on(&self.db, &self.cf, &groups)?;
507            for ((_, indexes), value) in groups.iter().zip(values) {
508                scatter_value(&mut out, indexes, value);
509            }
510            return Ok(out);
511        }
512        attest_registry_multiget(count);
513        let slices = split_slices(groups.len(), count);
514        // One shared, immutable group list: a unit carries the range of its
515        // own key-disjoint slice instead of copying the (potentially large)
516        // index vectors, and still owns everything it touches.
517        let groups = std::sync::Arc::new(groups);
518        let units: Vec<RegistryMultiGetUnit> = slices
519            .iter()
520            .map(|slice| RegistryMultiGetUnit {
521                db: self.db.clone(),
522                cf: self.cf,
523                groups: std::sync::Arc::clone(&groups),
524                range: slice.clone(),
525            })
526            .collect();
527        let outcomes = worker_pool::run_units(units);
528        for (slice, outcome) in slices.iter().zip(outcomes) {
529            // First worker `Err` wins; slice order keeps the merge ordered.
530            let values = match outcome {
531                worker_pool::UnitOutcome::Ok(result) => result?,
532                worker_pool::UnitOutcome::Panicked(message) => {
533                    return Err(StorageError::Backend(format!(
534                        "registry multiget worker panicked: {message}"
535                    )));
536                }
537            };
538            for ((_, indexes), value) in groups[slice.clone()].iter().zip(values) {
539                scatter_value(&mut out, indexes, value);
540            }
541        }
542        Ok(out)
543    }
544
545    /// Point-Get loop (test oracle vs Seek / MultiGet).
546    pub fn lookup_many_get(&self, hashes: &[StrHash]) -> Result<Vec<Option<String>>, StorageError> {
547        hashes.iter().map(|hash| self.lookup(*hash)).collect()
548    }
549
550    /// Write `entries` in one `WriteBatch`. Empty `entries` is a no-op.
551    pub fn apply_puts(&self, entries: &[(StrHash, String)]) -> Result<u64, StorageError> {
552        if entries.is_empty() {
553            return Ok(0);
554        }
555        let mut batch = self.db.write_batch();
556        for (hash, raw) in entries {
557            batch.insert(&self.cf, &hash.to_be_bytes(), raw.as_bytes());
558        }
559        batch.commit()?;
560        Ok(entries.len() as u64)
561    }
562
563    /// Write `entries` as one sorted SST run file at `path` (bulk-ingest input).
564    ///
565    /// `entries` must be sorted ascending by [`StrHash`] with no duplicates —
566    /// the `SstFileWriter` contract (a `BTreeMap<StrHash, _>` iteration order
567    /// satisfies it). The file uses the registry's own SST layout (32 KiB
568    /// blocks, LZ4), so it needs no rewrite after ingest.
569    pub fn write_sorted_sst_run(
570        &self,
571        path: &Path,
572        entries: &[(StrHash, String)],
573    ) -> Result<(), StorageError> {
574        if entries.is_empty() {
575            return Ok(());
576        }
577        debug_assert!(
578            entries.windows(2).all(|pair| pair[0].0 < pair[1].0),
579            "SST run entries must be sorted ascending by hash with no duplicates"
580        );
581        let mut writer = SstFileWriter::new(REGISTRY_BLOCK_SIZE_BYTES)?;
582        writer.open(path)?;
583        for (hash, raw) in entries {
584            writer.add(&hash.to_be_bytes(), raw.as_bytes())?;
585        }
586        writer.finish()
587    }
588
589    /// Bulk-ingest sorted SST run files ([`Self::write_sorted_sst_run`] output)
590    /// into the registry CF. Empty `files` is a no-op.
591    ///
592    /// Runs may overlap each other's key ranges: a [`StrHash`] is a pure hash
593    /// of its raw string, so the same hash in two runs always carries the same
594    /// value and whichever run wins is equivalent. No memtable flush is
595    /// required and none is performed.
596    pub fn ingest_sst_runs(&self, files: &[PathBuf]) -> Result<(), StorageError> {
597        self.db.ingest_external_file_cf(&self.cf, files, true)
598    }
599
600    /// Warm the registry's block cache: one sequential walk over `entries`,
601    /// stopping once usage reaches `fill_fraction` of capacity.
602    ///
603    /// See [`warm_walk`]; the walk is what matters, values are dropped.
604    /// A `fill_fraction` of `0` (or below) disables the walk.
605    pub fn warm_block_cache(
606        &self,
607        fill_fraction: f64,
608    ) -> Result<WarmBlockCacheStats, StorageError> {
609        let capacity = self.db.block_cache_capacity();
610        let target = (capacity as f64 * fill_fraction.max(0.0)) as usize;
611        let usage_before = self.db.block_cache_usage();
612        let entries_touched = if target == 0 {
613            0
614        } else {
615            warm_walk(&self.db, &[&self.cf], target)?
616        };
617        Ok(WarmBlockCacheStats {
618            entries_touched,
619            usage_before,
620            usage_after: self.db.block_cache_usage(),
621            capacity,
622        })
623    }
624
625    /// Ingest finished offline-import SST runs and delete `staging_dir`.
626    ///
627    /// `run-*.sst` files are ingested in name order. `run-*.sst.partial` is an
628    /// in-progress chunk and is deleted without being ingested. A missing
629    /// directory is a no-op. If the ingest fails, the finished runs stay on
630    /// disk so the next open can try again.
631    pub fn recover_staged_sst_runs(&self, staging_dir: &Path) -> Result<(), StorageError> {
632        if !staging_dir.exists() {
633            return Ok(());
634        }
635        delete_partial_registry_sst_runs(staging_dir)?;
636        let runs = finished_registry_sst_runs(staging_dir)?;
637        if runs.is_empty() {
638            if staging_dir_is_empty(staging_dir)? {
639                std::fs::remove_dir(staging_dir).map_err(io_backend)?;
640            }
641            return Ok(());
642        }
643        self.ingest_sst_runs(&runs)?;
644        // The runs are in the registry CF now (`move_files` unlinks them on
645        // the way in). Drop the directory only after that ingest succeeds.
646        std::fs::remove_dir_all(staging_dir).map_err(io_backend)?;
647        Ok(())
648    }
649
650    /// Flush the registry column family to SST files.
651    pub fn flush_memtables(&self) -> Result<(), StorageError> {
652        self.db.flush_cfs(&[&self.cf])
653    }
654
655    /// Compact the full key range of the registry column family.
656    pub fn compact_range(&self) {
657        self.db.compact_cf(&self.cf);
658    }
659
660    /// Approximate key count from RocksDB (`rocksdb.estimate-num-keys` on the registry CF).
661    pub fn estimate_num_keys(&self) -> Option<u64> {
662        self.db
663            .int_property_cf(&self.cf, "rocksdb.estimate-num-keys")
664    }
665
666    /// RocksDB LSM size / compaction counters (registry CF, not `default`).
667    pub fn lsm_metrics(&self) -> crate::LsmMetrics {
668        self.db.lsm_metrics_for_cfs(&[&self.cf])
669    }
670
671    /// Process-wide block cache bytes: `(capacity, charged usage)`.
672    pub fn block_cache_bytes(&self) -> Option<(u64, u64)> {
673        Some((
674            self.db.block_cache_capacity() as u64,
675            self.db.block_cache_usage() as u64,
676        ))
677    }
678}
679
680fn io_backend(err: std::io::Error) -> StorageError {
681    StorageError::Backend(err.to_string())
682}
683
684fn staging_dir_is_empty(dir: &Path) -> Result<bool, StorageError> {
685    let mut entries = std::fs::read_dir(dir).map_err(io_backend)?;
686    match entries.next() {
687        None => Ok(true),
688        Some(Ok(_)) => Ok(false),
689        Some(Err(err)) => Err(io_backend(err)),
690    }
691}
692
693fn staging_file_name(path: &Path) -> Option<&str> {
694    path.file_name().and_then(|name| name.to_str())
695}
696
697/// Finished offline-import runs in `staging_dir` (`run-NNNNNN.sst`), sorted by name.
698///
699/// A missing directory is an empty list. `run-*.sst.partial` is an in-progress
700/// chunk and is not included.
701pub fn finished_registry_sst_runs(staging_dir: &Path) -> Result<Vec<PathBuf>, StorageError> {
702    if !staging_dir.exists() {
703        return Ok(Vec::new());
704    }
705    let mut runs = Vec::new();
706    for entry in std::fs::read_dir(staging_dir).map_err(io_backend)? {
707        let path = entry.map_err(io_backend)?.path();
708        let Some(name) = staging_file_name(&path) else {
709            continue;
710        };
711        if name.starts_with("run-") && name.ends_with(".sst") {
712            runs.push(path);
713        }
714    }
715    runs.sort();
716    Ok(runs)
717}
718
719/// Delete in-progress `run-*.sst.partial` files. A missing directory is a no-op.
720///
721/// These files are an offline chunk whose hexastore apply and SST write had
722/// not both finished. They are not a dictionary.
723pub fn delete_partial_registry_sst_runs(staging_dir: &Path) -> Result<(), StorageError> {
724    if !staging_dir.exists() {
725        return Ok(());
726    }
727    for entry in std::fs::read_dir(staging_dir).map_err(io_backend)? {
728        let path = entry.map_err(io_backend)?.path();
729        let Some(name) = staging_file_name(&path) else {
730            continue;
731        };
732        if name.starts_with("run-") && name.ends_with(".sst.partial") {
733            std::fs::remove_file(&path).map_err(io_backend)?;
734        }
735    }
736    Ok(())
737}
738
739/// In-memory or RocksDB string registry used by compute and the registry process.
740pub enum Registry {
741    /// Partition-hashed in-memory shards.
742    Memory(ShardedRegistry),
743    /// Disk-backed dictionary at `{data_dir}/{repository}/registry`.
744    RocksDb(RocksDbRegistry),
745}
746
747impl fmt::Debug for Registry {
748    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
749        match self {
750            Self::Memory(inner) => f.debug_tuple("Memory").field(inner).finish(),
751            Self::RocksDb(inner) => f.debug_tuple("RocksDb").field(inner).finish(),
752        }
753    }
754}
755
756impl Registry {
757    /// In-memory registry with `shard_count` shards.
758    pub fn memory(shard_count: usize) -> Self {
759        Self::Memory(ShardedRegistry::new(shard_count))
760    }
761
762    /// Open a RocksDB registry at `path` (created if missing).
763    pub fn open_rocksdb(
764        path: impl AsRef<Path>,
765        tuning: RocksDbTuning,
766    ) -> Result<Self, StorageError> {
767        Ok(Self::RocksDb(RocksDbRegistry::open(path, tuning)?))
768    }
769
770    /// Number of in-process shards (always `1` for RocksDB).
771    pub fn shard_count(&self) -> usize {
772        match self {
773            Self::Memory(inner) => inner.shard_count(),
774            Self::RocksDb(_) => 1,
775        }
776    }
777
778    /// Exact in-memory count, or RocksDB `estimate-num-keys`.
779    pub fn entry_count(&self) -> Option<u64> {
780        match self {
781            Self::Memory(inner) => Some(inner.entry_count()),
782            Self::RocksDb(inner) => inner.estimate_num_keys(),
783        }
784    }
785
786    /// RocksDB LSM counters (`None` on the memory backend).
787    pub fn lsm_metrics(&self) -> Option<crate::LsmMetrics> {
788        match self {
789            Self::Memory(_) => None,
790            Self::RocksDb(inner) => Some(inner.lsm_metrics()),
791        }
792    }
793
794    /// Process-wide block cache bytes (`None` on the memory backend).
795    pub fn block_cache_bytes(&self) -> Option<(u64, u64)> {
796        match self {
797            Self::Memory(_) => None,
798            Self::RocksDb(inner) => inner.block_cache_bytes(),
799        }
800    }
801
802    /// Register `raw` under `hash` (overwrites on duplicate).
803    pub fn register(&mut self, hash: StrHash, raw: impl Into<String>) -> Result<(), StorageError> {
804        match self {
805            Self::Memory(inner) => inner.register(hash, raw),
806            Self::RocksDb(inner) => inner.register(hash, raw.into()),
807        }
808    }
809
810    /// Look up the raw string for `hash`.
811    pub fn lookup(&self, hash: StrHash) -> Result<Option<String>, StorageError> {
812        match self {
813            Self::Memory(inner) => inner.lookup(hash),
814            Self::RocksDb(inner) => inner.lookup(hash),
815        }
816    }
817
818    /// Positional bulk lookup. RocksDB uses sorted `MultiGet`.
819    pub fn lookup_many(&self, hashes: &[StrHash]) -> Result<Vec<Option<String>>, StorageError> {
820        match self {
821            Self::Memory(inner) => inner.lookup_many(hashes),
822            Self::RocksDb(inner) => inner.lookup_many(hashes),
823        }
824    }
825
826    /// Register many entries; RocksDB uses one `WriteBatch`.
827    pub fn register_entries(&mut self, entries: &[(StrHash, String)]) -> Result<u64, StorageError> {
828        match self {
829            Self::Memory(inner) => {
830                for (hash, raw) in entries {
831                    inner.register(*hash, raw.clone())?;
832                }
833                Ok(entries.len() as u64)
834            }
835            Self::RocksDb(inner) => inner.apply_puts(entries),
836        }
837    }
838
839    /// Write hash-sorted `entries` as one SST run file at `path` (see
840    /// [`RocksDbRegistry::write_sorted_sst_run`]). RocksDB-only: the
841    /// in-memory registry has no SST layout to write.
842    pub fn write_sorted_sst_run(
843        &self,
844        path: &Path,
845        entries: &[(StrHash, String)],
846    ) -> Result<(), StorageError> {
847        match self {
848            Self::Memory(_) => Err(StorageError::Backend(
849                "SST runs are only supported by the RocksDB registry".to_owned(),
850            )),
851            Self::RocksDb(inner) => inner.write_sorted_sst_run(path, entries),
852        }
853    }
854
855    /// Bulk-ingest sorted SST run files (see
856    /// [`RocksDbRegistry::ingest_sst_runs`]). RocksDB-only.
857    pub fn ingest_sst_runs(&self, files: &[PathBuf]) -> Result<(), StorageError> {
858        match self {
859            Self::Memory(_) => Err(StorageError::Backend(
860                "SST runs are only supported by the RocksDB registry".to_owned(),
861            )),
862            Self::RocksDb(inner) => inner.ingest_sst_runs(files),
863        }
864    }
865
866    /// Warm this registry's block cache (see
867    /// [`RocksDbRegistry::warm_block_cache`]). No-op on the in-memory
868    /// backend: there is no block cache to warm, so the stats come back
869    /// zeroed rather than erroring.
870    pub fn warm_block_cache(
871        &self,
872        fill_fraction: f64,
873    ) -> Result<WarmBlockCacheStats, StorageError> {
874        match self {
875            Self::Memory(_) => Ok(WarmBlockCacheStats::noop()),
876            Self::RocksDb(inner) => inner.warm_block_cache(fill_fraction),
877        }
878    }
879
880    /// Ingest finished offline-import SST runs in `staging_dir` (see
881    /// [`RocksDbRegistry::recover_staged_sst_runs`]). RocksDB-only.
882    pub fn recover_staged_sst_runs(&self, staging_dir: &Path) -> Result<(), StorageError> {
883        match self {
884            Self::Memory(_) => Err(StorageError::Backend(
885                "SST runs are only supported by the RocksDB registry".to_owned(),
886            )),
887            Self::RocksDb(inner) => inner.recover_staged_sst_runs(staging_dir),
888        }
889    }
890
891    /// Flush MemTables (no-op for memory).
892    pub fn flush_memtables(&self) -> Result<(), StorageError> {
893        match self {
894            Self::Memory(_) => Ok(()),
895            Self::RocksDb(inner) => inner.flush_memtables(),
896        }
897    }
898
899    /// Compact the registry CF (no-op for memory).
900    pub fn compact_range(&self) {
901        match self {
902            Self::Memory(_) => {}
903            Self::RocksDb(inner) => inner.compact_range(),
904        }
905    }
906}
907
908/// Collect `(StrHash, raw)` pairs that must be registered for an encoded quad.
909///
910/// Used by the local [`ShardedRegistry`] and by compute's `RegisterStrings`
911/// fan-out so hexastore writes and dictionary writes share one encoding.
912pub fn registry_entries_for_quad(quad: &Quad, encoded: &EncodedQuad) -> Vec<(StrHash, String)> {
913    let graph_term = match &quad.graph_name {
914        GraphName::NamedNode(node) => Some(Term::from(node.clone())),
915        GraphName::BlankNode(node) => Some(Term::from(node.clone())),
916        GraphName::DefaultGraph => None,
917    };
918    let slots = [
919        (Some(Term::from(quad.subject.clone())), &encoded.subject),
920        (Some(Term::from(quad.predicate.clone())), &encoded.predicate),
921        (Some(quad.object.clone()), &encoded.object),
922        (graph_term, &encoded.graph_name),
923    ];
924    let mut entries = Vec::new();
925    for (term, encoded_term) in slots {
926        let Some(term) = term else { continue };
927        entries.extend(strings_entries_for_term(&term, encoded_term));
928    }
929    entries
930}
931
932fn registry_utf8(bytes: Vec<u8>) -> Result<String, StorageError> {
933    String::from_utf8(bytes)
934        .map_err(|_| StorageError::Corrupt("registry value is not valid UTF-8".to_owned()))
935}
936
937/// One registry seek-walk slice: a storage worker's exact-match seek
938/// iterator over an owned, sorted, key-disjoint run of hash groups.
939///
940/// Units own their inputs because the worker pool outlives individual
941/// calls; the shared group list is behind an `Arc` so a slice carries only
942/// its index range.
943struct RegistrySeekUnit {
944    db: Db,
945    cf: ColumnFamily,
946    groups: std::sync::Arc<Vec<(StrHash, Vec<usize>)>>,
947    range: std::ops::Range<usize>,
948}
949
950impl crate::worker_pool::PoolUnit for RegistrySeekUnit {
951    type Output = Result<Vec<Option<String>>, StorageError>;
952
953    fn execute(self) -> Self::Output {
954        seek_groups_on(&self.db, &self.cf, &self.groups[self.range.clone()])
955    }
956}
957
958/// Walk `groups` (sorted ascending by key bytes) with **one** iterator,
959/// one exact-match seek per hash. Returns values parallel to `groups`.
960///
961/// No iterate upper bound is needed: matching is exact-key equality on
962/// ascending seek targets, so any key a seek lands on that is not the
963/// requested hash is simply a miss — the walk is correct on the whole CF
964/// and therefore on any contiguous sub-range of it.
965fn seek_groups_on(
966    db: &Db,
967    cf: &ColumnFamily,
968    groups: &[(StrHash, Vec<usize>)],
969) -> Result<Vec<Option<String>>, StorageError> {
970    let mut values = Vec::with_capacity(groups.len());
971    // Empty prefix: no iterate upper bound, whole `entries` CF.
972    let mut iter = db.scan_prefix(cf, &[]);
973    for (hash, _) in groups {
974        let key = hash.to_be_bytes();
975        iter.seek(&key);
976        let value = if iter.is_valid() && iter.key() == Some(key.as_slice()) {
977            let bytes = iter
978                .value()
979                .ok_or_else(|| StorageError::Corrupt("iterator key without value".to_owned()))?;
980            Some(registry_utf8(bytes.to_vec())?)
981        } else {
982            None
983        };
984        values.push(value);
985    }
986    iter.status()?;
987    Ok(values)
988}
989
990/// One registry multi-get batch: pinned point reads over an owned, sorted,
991/// key-disjoint run of hash groups (same unit shape as the seek walk).
992struct RegistryMultiGetUnit {
993    db: Db,
994    cf: ColumnFamily,
995    groups: std::sync::Arc<Vec<(StrHash, Vec<usize>)>>,
996    range: std::ops::Range<usize>,
997}
998
999impl crate::worker_pool::PoolUnit for RegistryMultiGetUnit {
1000    type Output = Result<Vec<Option<String>>, StorageError>;
1001
1002    fn execute(self) -> Self::Output {
1003        multiget_groups_on(&self.db, &self.cf, &self.groups[self.range.clone()])
1004    }
1005}
1006
1007/// Resolve `groups` with one pinned batched MultiGet, values parallel to
1008/// `groups`. `groups` must be sorted ascending by key bytes — the sorted
1009/// hash groups always are, and so is any contiguous slice of them —
1010/// which is what makes `sorted_input=true` valid per batch.
1011fn multiget_groups_on(
1012    db: &Db,
1013    cf: &ColumnFamily,
1014    groups: &[(StrHash, Vec<usize>)],
1015) -> Result<Vec<Option<String>>, StorageError> {
1016    let key_bufs: Vec<[u8; 16]> = groups.iter().map(|(hash, _)| hash.to_be_bytes()).collect();
1017    let key_refs: Vec<&[u8]> = key_bufs.iter().map(|buf| buf.as_slice()).collect();
1018    let fetched = db.multi_get_pinned(cf, &key_refs, true)?;
1019    let mut values = Vec::with_capacity(groups.len());
1020    for bytes in fetched {
1021        values.push(match bytes {
1022            None => None,
1023            Some(raw) => Some(registry_utf8(raw)?),
1024        });
1025    }
1026    Ok(values)
1027}
1028
1029/// Groups of equal hashes in 16-byte CF key order, with original indexes.
1030fn sorted_hash_groups(hashes: &[StrHash]) -> Vec<(StrHash, Vec<usize>)> {
1031    let mut order: Vec<usize> = (0..hashes.len()).collect();
1032    order.sort_by_key(|&index| hashes[index]);
1033    let mut groups = Vec::new();
1034    let mut i = 0;
1035    while i < order.len() {
1036        let hash = hashes[order[i]];
1037        let mut indexes = vec![order[i]];
1038        i += 1;
1039        while i < order.len() && hashes[order[i]] == hash {
1040            indexes.push(order[i]);
1041            i += 1;
1042        }
1043        groups.push((hash, indexes));
1044    }
1045    groups
1046}
1047
1048fn scatter_value(out: &mut [Option<String>], indexes: &[usize], value: Option<String>) {
1049    let Some(raw) = value else {
1050        return;
1051    };
1052    if let Some((last, rest)) = indexes.split_last() {
1053        for &index in rest {
1054            out[index] = Some(raw.clone());
1055        }
1056        out[*last] = Some(raw);
1057    }
1058}
1059
1060/// Resolve only the requested `hashes` to raw strings (late materialization).
1061pub fn resolve_bindings(
1062    registry: &ShardedRegistry,
1063    hashes: &[Option<StrHash>],
1064) -> Result<Vec<Option<String>>, StorageError> {
1065    hashes
1066        .iter()
1067        .map(|hash| match hash {
1068            Some(h) => registry
1069                .lookup(*h)?
1070                .ok_or(StorageError::RegistryMiss(h.as_u128()))
1071                .map(Some),
1072            None => Ok(None),
1073        })
1074        .collect()
1075}
1076
1077#[cfg(test)]
1078mod tests {
1079    use super::*;
1080    use crate::encode::{EncodedTerm, encode_term};
1081    use crate::{Literal, NamedNode, WARM_CACHE_FILL_FRACTION, WARM_CACHE_PROBE_INTERVAL};
1082
1083    #[test]
1084    fn shard_routing_is_stable() {
1085        let h = StrHash::new("http://example.org/long-iri-for-sharding-test");
1086        let a = shard_id_for_hash(h, 8);
1087        let b = shard_id_for_hash(h, 8);
1088        assert_eq!(a, b);
1089        assert!(a < 8);
1090    }
1091
1092    #[test]
1093    fn register_lookup_hit_miss_overwrite() {
1094        let mut shard = InMemoryRegistryShard::new();
1095        let h = StrHash::new("foo");
1096        assert_eq!(shard.lookup(h).unwrap(), None);
1097
1098        shard.register(h, "foo".to_owned()).unwrap();
1099        assert_eq!(shard.lookup(h).unwrap().as_deref(), Some("foo"));
1100
1101        shard.register(h, "bar".to_owned()).unwrap();
1102        assert_eq!(shard.lookup(h).unwrap().as_deref(), Some("bar"));
1103    }
1104
1105    #[test]
1106    fn resolve_bindings_only_requested_hashes() {
1107        let mut registry = ShardedRegistry::new(4);
1108        let h1 = StrHash::new("alpha");
1109        let h2 = StrHash::new("beta");
1110        registry.register(h1, "alpha").unwrap();
1111        registry.register(h2, "beta").unwrap();
1112
1113        let resolved = resolve_bindings(&registry, &[Some(h1), None, Some(h2)]).unwrap();
1114        assert_eq!(resolved[0].as_deref(), Some("alpha"));
1115        assert_eq!(resolved[1], None);
1116        assert_eq!(resolved[2].as_deref(), Some("beta"));
1117
1118        // No eager full-dict scan: miss returns error only for requested Some slots.
1119        let err = resolve_bindings(&registry, &[Some(StrHash::new("missing"))]).unwrap_err();
1120        assert!(matches!(err, StorageError::RegistryMiss(_)));
1121    }
1122
1123    #[test]
1124    fn encode_named_node_registers_iri() {
1125        let mut registry = ShardedRegistry::new(2);
1126        let iri = NamedNode::new("http://example.org/p").unwrap();
1127        let term = Term::from(iri.clone());
1128        let encoded = encode_term(&term).unwrap();
1129        if let EncodedTerm::NamedNode { iri_id } = encoded {
1130            registry.register(iri_id, iri.as_str().to_owned()).unwrap();
1131            assert_eq!(
1132                registry.lookup(iri_id).unwrap().as_deref(),
1133                Some("http://example.org/p")
1134            );
1135        } else {
1136            panic!("expected named node encoding");
1137        }
1138    }
1139
1140    #[test]
1141    fn register_quad_covers_every_slot_of_the_shared_encoding() {
1142        use crate::encode::encode_quad;
1143        use crate::{GraphName, Quad};
1144
1145        let quad = Quad::new(
1146            NamedNode::new("http://example.org/s").unwrap(),
1147            NamedNode::new("http://example.org/p").unwrap(),
1148            NamedNode::new("http://example.org/o").unwrap(),
1149            GraphName::NamedNode(NamedNode::new("http://example.org/g").unwrap()),
1150        );
1151
1152        let mut registry = ShardedRegistry::new(4);
1153        registry
1154            .register_quad(&quad, &encode_quad(&quad).unwrap())
1155            .unwrap();
1156
1157        for slot in ["s", "p", "o", "g"] {
1158            let iri = format!("http://example.org/{slot}");
1159            assert_eq!(
1160                registry.lookup(StrHash::new(&iri)).unwrap().as_deref(),
1161                Some(iri.as_str())
1162            );
1163        }
1164    }
1165
1166    #[test]
1167    fn small_literal_does_not_need_registry() {
1168        let lit = Literal::from("hi");
1169        let encoded = encode_term(&Term::from(lit)).unwrap();
1170        assert!(matches!(encoded, EncodedTerm::SmallStringLiteral(_)));
1171    }
1172
1173    #[test]
1174    fn rocksdb_registry_register_lookup_flush() {
1175        let dir = tempfile::tempdir().unwrap();
1176        let path = crate::registry_data_dir(dir.path(), crate::MAIN_REPOSITORY_ID);
1177        let mut registry = Registry::open_rocksdb(&path, RocksDbTuning::registry_node()).unwrap();
1178        let h = StrHash::new("http://example.org/long-iri-for-disk-registry");
1179        assert_eq!(registry.lookup(h).unwrap(), None);
1180
1181        registry
1182            .register(h, "http://example.org/long-iri-for-disk-registry")
1183            .unwrap();
1184        assert_eq!(
1185            registry.lookup(h).unwrap().as_deref(),
1186            Some("http://example.org/long-iri-for-disk-registry")
1187        );
1188
1189        let h2 = StrHash::new("http://example.org/second-entry");
1190        let written = registry
1191            .register_entries(&[(h2, "http://example.org/second-entry".to_owned())])
1192            .unwrap();
1193        assert_eq!(written, 1);
1194        registry.flush_memtables().unwrap();
1195        registry.compact_range();
1196
1197        drop(registry);
1198        let reopened = Registry::open_rocksdb(&path, RocksDbTuning::registry_node()).unwrap();
1199        assert_eq!(
1200            reopened.lookup(h).unwrap().as_deref(),
1201            Some("http://example.org/long-iri-for-disk-registry")
1202        );
1203        assert_eq!(
1204            reopened.lookup(h2).unwrap().as_deref(),
1205            Some("http://example.org/second-entry")
1206        );
1207    }
1208
1209    #[test]
1210    fn rocksdb_lookup_many_seek_matches_get_and_multiget() {
1211        let dir = tempfile::tempdir().unwrap();
1212        let path = crate::registry_data_dir(dir.path(), crate::MAIN_REPOSITORY_ID);
1213        let registry = RocksDbRegistry::open(&path, RocksDbTuning::registry_node()).unwrap();
1214
1215        let a = StrHash::new("http://example.org/alpha-label");
1216        let b = StrHash::new("http://example.org/bravo-label");
1217        let c = StrHash::new("http://example.org/charlie-label");
1218        let hole = StrHash::new("http://example.org/missing-in-the-middle");
1219        let after = StrHash::new("http://example.org/zzz-past-last");
1220        registry.register(a, "alpha").unwrap();
1221        registry.register(b, "bravo").unwrap();
1222        registry.register(c, "charlie").unwrap();
1223
1224        // Unsorted request: hits, a hole, a miss past the last key, a duplicate.
1225        let query = [c, hole, a, after, a, b];
1226        let via_seek = registry.lookup_many_seek(&query).unwrap();
1227        let via_multi = registry.lookup_many_multiget(&query).unwrap();
1228        let via_get = registry.lookup_many_get(&query).unwrap();
1229        assert_eq!(via_seek, via_get);
1230        assert_eq!(via_multi, via_get);
1231        assert_eq!(via_seek[0].as_deref(), Some("charlie"));
1232        assert_eq!(via_seek[1], None);
1233        assert_eq!(via_seek[2].as_deref(), Some("alpha"));
1234        assert_eq!(via_seek[3], None);
1235        assert_eq!(via_seek[4].as_deref(), Some("alpha"));
1236        assert_eq!(via_seek[5].as_deref(), Some("bravo"));
1237
1238        assert!(registry.lookup_many(&[]).unwrap().is_empty());
1239        assert!(registry.lookup_many_multiget(&[]).unwrap().is_empty());
1240        assert_eq!(
1241            registry.lookup_many(&[b]).unwrap()[0].as_deref(),
1242            Some("bravo")
1243        );
1244    }
1245
1246    #[test]
1247    fn registry_walks_env_parser_junk_and_clamps() {
1248        use super::{REGISTRY_WALKS_MAX, REGISTRY_WALKS_MIN, registry_walks_from_env};
1249        // 0 / 1 / junk are the serial opt-out (None); 2..=MAX pass; above
1250        // clamps to MAX. The UNSET case never reaches the parser:
1251        // registry_walks() derives its default from the pool width.
1252        assert_eq!(registry_walks_from_env(None), None);
1253        assert_eq!(registry_walks_from_env(Some("0")), None);
1254        assert_eq!(registry_walks_from_env(Some("1")), None);
1255        assert_eq!(registry_walks_from_env(Some("junk")), None);
1256        assert_eq!(registry_walks_from_env(Some("")), None);
1257        assert_eq!(registry_walks_from_env(Some("2")), Some(2));
1258        assert_eq!(registry_walks_from_env(Some("8")), Some(8));
1259        assert_eq!(
1260            registry_walks_from_env(Some(REGISTRY_WALKS_MAX.to_string().as_str())),
1261            Some(REGISTRY_WALKS_MAX)
1262        );
1263        assert_eq!(
1264            registry_walks_from_env(Some(&(REGISTRY_WALKS_MAX + 1).to_string())),
1265            Some(REGISTRY_WALKS_MAX)
1266        );
1267        assert_eq!(
1268            registry_walks_from_env(Some("1000")),
1269            Some(REGISTRY_WALKS_MAX)
1270        );
1271        assert_eq!(REGISTRY_WALKS_MIN, 2);
1272    }
1273
1274    #[test]
1275    fn unset_default_is_capped_by_pool_width() {
1276        use super::{REGISTRY_WALKS_DEFAULT_MAX, registry_walks_default};
1277        assert_eq!(REGISTRY_WALKS_DEFAULT_MAX, 8);
1278        // A narrow pool is the binding constraint; a wide one hits the cap.
1279        assert_eq!(registry_walks_default(1), 1);
1280        assert_eq!(registry_walks_default(2), 2);
1281        assert_eq!(registry_walks_default(4), 4);
1282        assert_eq!(registry_walks_default(8), 8);
1283        assert_eq!(registry_walks_default(16), 8);
1284        assert_eq!(registry_walks_default(64), 8);
1285    }
1286
1287    #[test]
1288    fn registry_parallel_slice_count_rule() {
1289        use super::{REGISTRY_WALKS_MIN_GROUPS_PER_SLICE, parallel_slice_count};
1290        assert_eq!(REGISTRY_WALKS_MIN_GROUPS_PER_SLICE, 16);
1291        // Below the two-slice threshold: never split.
1292        assert_eq!(parallel_slice_count(0, 8), 0);
1293        assert_eq!(parallel_slice_count(1, 8), 0);
1294        assert_eq!(parallel_slice_count(8, 8), 0);
1295        assert_eq!(parallel_slice_count(16, 8), 0);
1296        assert_eq!(parallel_slice_count(17, 8), 0);
1297        // Two slices of exactly MIN groups is the first split point.
1298        assert_eq!(parallel_slice_count(32, 8), 2);
1299        assert_eq!(parallel_slice_count(33, 8), 2);
1300        // K clamps the count; groups / MIN can exceed it. (Production
1301        // worker counts are pre-clamped to 2..=64 by the env parser —
1302        // `parallel_slice_count` itself applies only the MIN rule.)
1303        assert_eq!(parallel_slice_count(500, 8), 8);
1304        assert_eq!(parallel_slice_count(2000, 64), 64);
1305        assert_eq!(parallel_slice_count(2000, 200), 125);
1306        // Single-worker and single-group degenerate cases.
1307        assert_eq!(parallel_slice_count(2000, 1), 0);
1308        assert_eq!(parallel_slice_count(1, 64), 0);
1309    }
1310
1311    /// Register 16 named terms and build an above-threshold resolve query
1312    /// (1101 hashes): registered hits sprinkled through mostly-miss holes,
1313    /// plus a duplicate of the first hit.
1314    fn build_parallel_query(registry: &RocksDbRegistry) -> Vec<StrHash> {
1315        let names: Vec<String> = (0..16)
1316            .map(|i| format!("http://example.org/parallel-term-{i}"))
1317            .collect();
1318        for name in &names {
1319            registry
1320                .register(StrHash::new(name), name.as_str())
1321                .unwrap();
1322        }
1323        let mut query = Vec::with_capacity(1101);
1324        for i in 0..1100 {
1325            if i % 41 == 0 {
1326                query.push(StrHash::new(&names[i % names.len()]));
1327            } else {
1328                query.push(StrHash::new(&format!(
1329                    "http://example.org/parallel-miss-{i}"
1330                )));
1331            }
1332        }
1333        query.push(StrHash::new(&names[0]));
1334        query
1335    }
1336
1337    /// Oracle: parallel seek walks and parallel pinned-multiget resolves
1338    /// are positionally identical to the single walk/batch, MultiGet, and
1339    /// Get — above the split threshold at several worker counts, below it
1340    /// (serial), on empty input, and on a single hash.
1341    fn assert_parallel_seek_oracle(registry: &RocksDbRegistry) {
1342        let query = build_parallel_query(registry);
1343        let via_get = registry.lookup_many_get(&query).unwrap();
1344        let via_multi = registry.lookup_many_multiget(&query).unwrap();
1345        assert_eq!(via_get.len(), query.len());
1346
1347        for workers in [1usize, 2, 3, 8, 64] {
1348            let got = registry
1349                .lookup_many_seek_with_workers(&query, workers)
1350                .unwrap();
1351            assert_eq!(got, via_get, "workers {workers}");
1352            assert_eq!(got, via_multi, "workers {workers}");
1353            let got_multi = registry
1354                .lookup_many_multiget_with_workers(&query, workers)
1355                .unwrap();
1356            assert_eq!(got_multi, via_get, "multiget workers {workers}");
1357        }
1358        // Duplicates resolve to the same value in every position.
1359        assert_eq!(via_get[0], via_get[via_get.len() - 1]);
1360
1361        // Below the split threshold (6 groups < 2 × MIN): always serial, and
1362        // still identical to the reference modes.
1363        let hole_a = StrHash::new("http://example.org/parallel-hole-a");
1364        let small: Vec<StrHash> = vec![
1365            StrHash::new("http://example.org/parallel-term-4"),
1366            hole_a,
1367            StrHash::new("http://example.org/parallel-term-0"),
1368            StrHash::new("http://example.org/parallel-term-2"),
1369            StrHash::new("http://example.org/parallel-term-1"),
1370            StrHash::new("http://example.org/parallel-term-3"),
1371        ];
1372        let small_get = registry.lookup_many_get(&small).unwrap();
1373        for workers in [1usize, 2, 3, 64] {
1374            assert_eq!(
1375                registry
1376                    .lookup_many_seek_with_workers(&small, workers)
1377                    .unwrap(),
1378                small_get,
1379                "below-threshold workers {workers}"
1380            );
1381            assert_eq!(
1382                registry
1383                    .lookup_many_multiget_with_workers(&small, workers)
1384                    .unwrap(),
1385                small_get,
1386                "below-threshold multiget workers {workers}"
1387            );
1388        }
1389
1390        // Empty input and a single hash on every worker count.
1391        for workers in [1usize, 2, 64] {
1392            assert!(
1393                registry
1394                    .lookup_many_seek_with_workers(&[], workers)
1395                    .unwrap()
1396                    .is_empty()
1397            );
1398            let one = [StrHash::new("http://example.org/parallel-term-3")];
1399            assert_eq!(
1400                registry
1401                    .lookup_many_seek_with_workers(&one, workers)
1402                    .unwrap()[0]
1403                    .as_deref(),
1404                Some("http://example.org/parallel-term-3")
1405            );
1406            // A single hash group never splits.
1407            assert_eq!(
1408                registry
1409                    .lookup_many_seek_with_workers(std::slice::from_ref(&hole_a), workers)
1410                    .unwrap(),
1411                vec![None]
1412            );
1413            assert!(
1414                registry
1415                    .lookup_many_multiget_with_workers(&[], workers)
1416                    .unwrap()
1417                    .is_empty()
1418            );
1419            assert_eq!(
1420                registry
1421                    .lookup_many_multiget_with_workers(&one, workers)
1422                    .unwrap()[0]
1423                    .as_deref(),
1424                Some("http://example.org/parallel-term-3")
1425            );
1426            assert_eq!(
1427                registry
1428                    .lookup_many_multiget_with_workers(std::slice::from_ref(&hole_a), workers)
1429                    .unwrap(),
1430                vec![None]
1431            );
1432        }
1433    }
1434
1435    fn open_parallel_registry(tag: &str) -> (tempfile::TempDir, RocksDbRegistry) {
1436        let dir = tempfile::Builder::new()
1437            .prefix(tag)
1438            .tempdir()
1439            .expect("temp dir");
1440        let path = crate::registry_data_dir(dir.path(), crate::MAIN_REPOSITORY_ID);
1441        let registry = RocksDbRegistry::open(&path, RocksDbTuning::registry_node()).unwrap();
1442        (dir, registry)
1443    }
1444
1445    /// Oracle: parallel seek-walk results equal the serial walk's at every
1446    /// worker count.
1447    ///
1448    /// This exercises whichever dispatch arm `run_units` picks at the moment
1449    /// it runs. It only sees the scoped-thread fallback when no test in this
1450    /// binary has yet installed the process-global worker pool — libtest
1451    /// gives no execution-order guarantee, so that is scheduling-dependent
1452    /// and accepted: the assertions hold through either arm, and the
1453    /// fallback arm is covered directly (bypassing the global install) by
1454    /// `scoped_fallback_runs_units_in_order_without_a_pool` in
1455    /// `worker_pool.rs`.
1456    #[test]
1457    fn rocksdb_lookup_many_seek_parallel_matches_other_modes() {
1458        let (_dir, registry) = open_parallel_registry("seek-oracle");
1459        assert_parallel_seek_oracle(&registry);
1460    }
1461
1462    /// The same oracle through the installed process-wide worker pool: the
1463    /// production dispatch path, where each slice runs on a pool worker
1464    /// instead of a scoped thread.
1465    ///
1466    /// The install is process-global and first call wins: from here on, every
1467    /// later test in this binary dispatches to the pool, and slice counts
1468    /// above the installed width clamp to it (no assertion depends on a
1469    /// specific width, so this is accepted — see the oracle test above).
1470    #[test]
1471    fn rocksdb_lookup_many_seek_parallel_matches_other_modes_through_the_pool() {
1472        crate::worker_pool::init_worker_pool(None, 4);
1473        let (_dir, registry) = open_parallel_registry("seek-oracle-pool");
1474        assert_parallel_seek_oracle(&registry);
1475    }
1476
1477    /// Walk-scaling diagnosis (manual, ignored by default): does the
1478    /// K-worker seek walk's wall time shrink with K on a warm store?
1479    ///
1480    /// Requires `WARATAH_WALK_DIAG_DATA_DIR` pointing at a waratah data dir
1481    /// with a populated RocksDB registry; the store must not be open by a
1482    /// server (this opens it read-write). Samples ~250k hashes spanning the
1483    /// whole dictionary, then times `lookup_many_seek_with_workers` at
1484    /// K ∈ {1, 2, 4, 8} (5 runs each) against a serial seek-only floor that
1485    /// skips string conversion and scatter, reporting the value bytes the
1486    /// floor touches so the per-byte cost can be compared against
1487    /// page-cache copy bandwidth.
1488    ///
1489    /// Run:
1490    /// `WARATAH_WALK_DIAG_DATA_DIR=/path/to/store cargo test -p waratah_storage \
1491    ///  --lib walk_scaling_diagnosis -- --ignored --nocapture`
1492    #[test]
1493    #[ignore = "manual diagnosis; needs WARATAH_WALK_DIAG_DATA_DIR"]
1494    fn walk_scaling_diagnosis() {
1495        let Ok(data_dir) = std::env::var("WARATAH_WALK_DIAG_DATA_DIR") else {
1496            eprintln!("diag: skipping (WARATAH_WALK_DIAG_DATA_DIR unset)");
1497            return;
1498        };
1499        let path =
1500            crate::registry_data_dir(std::path::Path::new(&data_dir), crate::MAIN_REPOSITORY_ID);
1501        let registry = RocksDbRegistry::open(&path, RocksDbTuning::registry_node()).unwrap();
1502
1503        // Sample the dictionary. Registry keys are the 16-byte hashes in
1504        // big-endian order, so scan order is ascending hash order; a fixed
1505        // stride lands near 250k hashes spanning the whole key range.
1506        let mut total = 0usize;
1507        {
1508            let mut iter = registry.db.scan_prefix(&registry.cf, &[]);
1509            iter.seek(&[]);
1510            while iter.is_valid() {
1511                if iter.key().is_some() {
1512                    total += 1;
1513                }
1514                iter.next();
1515            }
1516        }
1517        let stride = total.div_ceil(250_000).max(1);
1518        let mut sampled: Vec<StrHash> = Vec::new();
1519        {
1520            let mut iter = registry.db.scan_prefix(&registry.cf, &[]);
1521            iter.seek(&[]);
1522            let mut index = 0usize;
1523            while iter.is_valid() {
1524                if let Some(key) = iter.key() {
1525                    if index.is_multiple_of(stride)
1526                        && let Ok(bytes) = <[u8; 16]>::try_from(key)
1527                    {
1528                        sampled.push(StrHash::from_be_bytes(bytes));
1529                    }
1530                    index += 1;
1531                }
1532                iter.next();
1533            }
1534        }
1535        eprintln!(
1536            "diag: dictionary={total} stride={stride} sampled={}",
1537            sampled.len()
1538        );
1539        assert!(sampled.len() >= 32, "dictionary too small to split");
1540
1541        // K-scaling of the full walk (grouping + workers + utf8 + scatter).
1542        for k in [1usize, 2, 4, 8] {
1543            let mut runs: Vec<f64> = Vec::new();
1544            for _ in 0..5 {
1545                let started = std::time::Instant::now();
1546                let values = registry.lookup_many_seek_with_workers(&sampled, k).unwrap();
1547                let elapsed = started.elapsed().as_secs_f64() * 1e3;
1548                assert_eq!(values.len(), sampled.len());
1549                runs.push(elapsed);
1550            }
1551            runs.sort_by(|a, b| a.total_cmp(b));
1552            eprintln!(
1553                "diag: K={k} median={:.1} ms min={:.1} max={:.1}",
1554                runs[2], runs[0], runs[4]
1555            );
1556        }
1557
1558        // Serial seek-only floor: one iterator, one exact-match seek per
1559        // hash, no string conversion, no scatter. Counts hits and the value
1560        // bytes actually touched.
1561        let started = std::time::Instant::now();
1562        let mut iter = registry.db.scan_prefix(&registry.cf, &[]);
1563        let mut hits = 0u64;
1564        let mut value_bytes = 0u64;
1565        for hash in &sampled {
1566            let key = hash.to_be_bytes();
1567            iter.seek(&key);
1568            if iter.is_valid() && iter.key() == Some(key.as_slice()) {
1569                hits += 1;
1570                value_bytes += iter.value().map(|v| v.len() as u64).unwrap_or(0);
1571            }
1572        }
1573        if let Err(error) = iter.status() {
1574            panic!("floor walk iterator error: {error}");
1575        }
1576        let floor_ms = started.elapsed().as_secs_f64() * 1e3;
1577        eprintln!(
1578            "diag: seek-only floor {:.1} ms hits={hits} value_bytes={value_bytes} \
1579             ({:.1} MB) -> {:.0} ns/hash, {:.2} ns/byte",
1580            floor_ms,
1581            value_bytes as f64 / 1048576.0,
1582            floor_ms * 1e6 / sampled.len() as f64,
1583            floor_ms * 1e6 / value_bytes.max(1) as f64,
1584        );
1585
1586        // The server calls the walk in sequential chunks of
1587        // RESOLVE_STRING_CHUNK (20k) hashes. Does per-chunk K4 still scale
1588        // when the batch is chunk-sized, or does the effect only exist at
1589        // full-batch sizes?
1590        let groups = sorted_hash_groups(&sampled);
1591        let chunk = 20_000usize;
1592        let mut chunked_k1 = 0.0f64;
1593        let mut chunked_k4 = 0.0f64;
1594        for start in (0..sampled.len()).step_by(chunk) {
1595            let end = (start + chunk).min(sampled.len());
1596            let piece = &sampled[start..end];
1597            let started = std::time::Instant::now();
1598            registry.lookup_many_seek_with_workers(piece, 1).unwrap();
1599            chunked_k1 += started.elapsed().as_secs_f64() * 1e3;
1600            let started = std::time::Instant::now();
1601            registry.lookup_many_seek_with_workers(piece, 4).unwrap();
1602            chunked_k4 += started.elapsed().as_secs_f64() * 1e3;
1603        }
1604        eprintln!(
1605            "diag: chunked(20k) total K1={chunked_k1:.1} ms K4={chunked_k4:.1} ms \
1606             ratio={:.3}x",
1607            chunked_k4 / chunked_k1
1608        );
1609
1610        // Direct 4-thread seek_groups, bypassing the wrapper entirely:
1611        // per-slice walls show whether the workers actually overlap.
1612        let mut direct_slices = Vec::new();
1613        {
1614            let slices = crate::rocksdb::split_slices(groups.len(), 4);
1615            let registry_ref = &registry;
1616            let started = std::time::Instant::now();
1617            std::thread::scope(|scope| {
1618                let mut handles = Vec::new();
1619                for range in &slices {
1620                    let piece = &groups[range.clone()];
1621                    handles.push(scope.spawn(move || {
1622                        let started = std::time::Instant::now();
1623                        let out =
1624                            seek_groups_on(&registry_ref.db, &registry_ref.cf, piece).unwrap();
1625                        (started.elapsed().as_secs_f64() * 1e3, out.len())
1626                    }));
1627                }
1628                for handle in handles {
1629                    direct_slices.push(handle.join().unwrap());
1630                }
1631            });
1632            let wall = started.elapsed().as_secs_f64() * 1e3;
1633            let slice_walls: Vec<String> = direct_slices
1634                .iter()
1635                .map(|(ms, _)| format!("{ms:.1}"))
1636                .collect();
1637            eprintln!(
1638                "diag: direct 4-thread seek_groups wall={wall:.1} ms slices=[{}] \
1639                 rows={}",
1640                slice_walls.join(", "),
1641                direct_slices.iter().map(|(_, n)| n).sum::<usize>()
1642            );
1643        }
1644
1645        // Iterator creation cost: seek_groups makes one full-CF iterator per
1646        // worker per call; if creation is expensive it taxes K4 four times
1647        // more than K1.
1648        let started = std::time::Instant::now();
1649        let creations = 200usize;
1650        for _ in 0..creations {
1651            let iter = registry.db.scan_prefix(&registry.cf, &[]);
1652            drop(iter);
1653        }
1654        eprintln!(
1655            "diag: iterator create+drop {:.0} us each ({} creations)",
1656            started.elapsed().as_secs_f64() * 1e6 / creations as f64,
1657            creations
1658        );
1659    }
1660
1661    /// A corrupt (non-UTF-8) value under one hash fails the seek walk and
1662    /// the multiget batch in every worker configuration; parallel workers
1663    /// surface the first `Err`.
1664    ///
1665    /// Installs the process-global worker pool (idempotent, first call wins
1666    /// for the whole binary); see the seek-oracle tests above for the
1667    /// accepted test-order dependence.
1668    #[test]
1669    fn rocksdb_lookup_many_seek_parallel_propagates_corrupt_values() {
1670        crate::worker_pool::init_worker_pool(None, 4);
1671        let (_dir, registry) = open_parallel_registry("seek-corrupt");
1672
1673        // 40 groups clears the split threshold at every worker count.
1674        let names: Vec<String> = (0..40)
1675            .map(|i| format!("http://example.org/corrupt-term-{i}"))
1676            .collect();
1677        for name in &names {
1678            registry
1679                .register(StrHash::new(name), name.as_str())
1680                .unwrap();
1681        }
1682        // Rewrite one entry's value as invalid UTF-8 through the raw handle.
1683        let victim = StrHash::new(&names[1]);
1684        registry
1685            .db
1686            .insert(&registry.cf, &victim.to_be_bytes(), &[0xFF, 0xFE])
1687            .unwrap();
1688
1689        let query: Vec<StrHash> = names.iter().map(|n| StrHash::new(n)).collect();
1690        for workers in [1usize, 2, 3, 64] {
1691            let result = registry.lookup_many_seek_with_workers(&query, workers);
1692            assert!(
1693                matches!(&result, Err(StorageError::Corrupt(_))),
1694                "workers {workers} must propagate the corrupt value: {result:?}"
1695            );
1696            let multi = registry.lookup_many_multiget_with_workers(&query, workers);
1697            assert!(
1698                matches!(&multi, Err(StorageError::Corrupt(_))),
1699                "multiget workers {workers} must propagate the corrupt value: {multi:?}"
1700            );
1701        }
1702    }
1703
1704    /// The pinned block-cache path: resolve *after* `flush_memtables`, so
1705    /// values come from SST data blocks (pinned slices into the block
1706    /// cache) instead of the memtable. Covers hits, a hole, a duplicate,
1707    /// and an empty value through the multiget arm, positionally identical
1708    /// to the per-key Get oracle.
1709    #[test]
1710    fn rocksdb_lookup_many_multiget_matches_get_after_flush() {
1711        let dir = tempfile::tempdir().unwrap();
1712        let path = crate::registry_data_dir(dir.path(), crate::MAIN_REPOSITORY_ID);
1713        let registry = RocksDbRegistry::open(&path, RocksDbTuning::registry_node()).unwrap();
1714
1715        // An empty value is legal and exercises the zero-length pinned slice.
1716        let names = ["alpha", "", "charlie"];
1717        let hashes: Vec<StrHash> = names
1718            .iter()
1719            .map(|n| StrHash::new(&format!("http://example.org/flushed-{n}")))
1720            .collect();
1721        for (name, hash) in names.iter().zip(&hashes) {
1722            registry.register(*hash, name).unwrap();
1723        }
1724        registry.flush_memtables().unwrap();
1725
1726        let hole = StrHash::new("http://example.org/flushed-hole");
1727        let query = vec![hashes[0], hashes[2], hole, hashes[0], hashes[1]];
1728        let via_multi = registry.lookup_many_multiget(&query).unwrap();
1729        let via_get = registry.lookup_many_get(&query).unwrap();
1730        assert_eq!(via_multi, via_get);
1731        assert_eq!(via_multi[0].as_deref(), Some("alpha"));
1732        assert_eq!(via_multi[1].as_deref(), Some("charlie"));
1733        assert_eq!(via_multi[2], None);
1734        assert_eq!(via_multi[3], via_multi[0]);
1735        assert_eq!(via_multi[4].as_deref(), Some(""));
1736    }
1737
1738    #[test]
1739    fn sst_runs_ingest_roundtrips_and_handles_overlap() {
1740        let dir = tempfile::tempdir().unwrap();
1741        let path = crate::registry_data_dir(dir.path(), crate::MAIN_REPOSITORY_ID);
1742        let registry = RocksDbRegistry::open(&path, RocksDbTuning::registry_node()).unwrap();
1743
1744        let a = StrHash::new("http://example.org/run-alpha");
1745        let b = StrHash::new("http://example.org/run-bravo");
1746        let c = StrHash::new("http://example.org/run-charlie");
1747        let mut entries_ab: Vec<(StrHash, String)> = vec![(a, "alpha".into()), (b, "bravo".into())];
1748        entries_ab.sort_by_key(|(hash, _)| *hash);
1749        let mut entries_bc: Vec<(StrHash, String)> =
1750            vec![(b, "bravo".into()), (c, "charlie".into())];
1751        entries_bc.sort_by_key(|(hash, _)| *hash);
1752
1753        let runs_dir = dir.path().join("runs");
1754        std::fs::create_dir_all(&runs_dir).unwrap();
1755        let run1 = runs_dir.join("run-000000.sst");
1756        let run2 = runs_dir.join("run-000001.sst");
1757        registry.write_sorted_sst_run(&run1, &entries_ab).unwrap();
1758        registry.write_sorted_sst_run(&run2, &entries_bc).unwrap();
1759        registry.ingest_sst_runs(&[run1, run2]).unwrap();
1760
1761        assert_eq!(registry.lookup(a).unwrap().as_deref(), Some("alpha"));
1762        // The overlapping key `b` appears in both runs with the same value
1763        // (StrHash is a pure hash), so run precedence cannot change it.
1764        assert_eq!(registry.lookup(b).unwrap().as_deref(), Some("bravo"));
1765        assert_eq!(registry.lookup(c).unwrap().as_deref(), Some("charlie"));
1766
1767        // Re-ingest overlapping the already-ingested (L6) files, then compact.
1768        let mut entries_d: Vec<(StrHash, String)> =
1769            vec![(a, "alpha".into()), (c, "charlie".into())];
1770        entries_d.sort_by_key(|(hash, _)| *hash);
1771        let run3 = runs_dir.join("run-000002.sst");
1772        registry.write_sorted_sst_run(&run3, &entries_d).unwrap();
1773        registry.ingest_sst_runs(&[run3]).unwrap();
1774        registry.compact_range();
1775        assert_eq!(registry.lookup(a).unwrap().as_deref(), Some("alpha"));
1776        assert_eq!(registry.lookup(b).unwrap().as_deref(), Some("bravo"));
1777        assert_eq!(registry.lookup(c).unwrap().as_deref(), Some("charlie"));
1778
1779        // Empty file list is a no-op.
1780        registry.ingest_sst_runs(&[]).unwrap();
1781    }
1782
1783    #[test]
1784    fn reopen_ingests_finished_staging_runs_and_drops_partials() {
1785        let dir = tempfile::tempdir().unwrap();
1786        let path = crate::registry_data_dir(dir.path(), crate::MAIN_REPOSITORY_ID);
1787        let registry = RocksDbRegistry::open(&path, RocksDbTuning::registry_node()).unwrap();
1788        let kept = StrHash::new("http://example.org/kept");
1789        let mut entries = vec![(kept, "http://example.org/kept".to_owned())];
1790        entries.sort_by_key(|(hash, _)| *hash);
1791        let staging = crate::layout::registry_sst_staging_dir(&path);
1792        std::fs::create_dir_all(&staging).unwrap();
1793        let partial = staging.join("run-000000.sst.partial");
1794        std::fs::write(&partial, b"in-progress").unwrap();
1795        registry
1796            .write_sorted_sst_run(&staging.join("run-000000.sst"), &entries)
1797            .unwrap();
1798        drop(registry);
1799
1800        let registry = RocksDbRegistry::open(&path, RocksDbTuning::registry_node()).unwrap();
1801        assert_eq!(
1802            registry.lookup(kept).unwrap().as_deref(),
1803            Some("http://example.org/kept")
1804        );
1805        assert!(!partial.exists());
1806        assert!(!staging.exists());
1807    }
1808
1809    #[test]
1810    fn reopen_leaves_finished_runs_when_ingest_fails() {
1811        let dir = tempfile::tempdir().unwrap();
1812        let path = crate::registry_data_dir(dir.path(), crate::MAIN_REPOSITORY_ID);
1813        let registry = RocksDbRegistry::open(&path, RocksDbTuning::registry_node()).unwrap();
1814        drop(registry);
1815        let staging = crate::layout::registry_sst_staging_dir(&path);
1816        std::fs::create_dir_all(&staging).unwrap();
1817        let run = staging.join("run-000000.sst");
1818        std::fs::write(&run, b"not-an-sst").unwrap();
1819
1820        let err = RocksDbRegistry::open(&path, RocksDbTuning::registry_node()).unwrap_err();
1821        assert!(
1822            run.exists(),
1823            "a failed ingest must leave the finished run on disk ({err})"
1824        );
1825    }
1826
1827    #[test]
1828    fn warm_block_cache_walks_everything_when_target_far_above_data() {
1829        let dir = tempfile::tempdir().unwrap();
1830        let path = crate::registry_data_dir(dir.path(), crate::MAIN_REPOSITORY_ID);
1831        // Run the sequential warm walk under the scan-async gate (`scan_async_io: true`):
1832        // same results, exercises the io_uring read-options path end to end.
1833        let registry = RocksDbRegistry::open(
1834            &path,
1835            RocksDbTuning {
1836                scan_async_io: true,
1837                ..RocksDbTuning::registry_node()
1838            },
1839        )
1840        .unwrap();
1841        for i in 0..10_000u64 {
1842            registry
1843                .register(
1844                    StrHash::new(&format!("http://example.org/warm-{i}")),
1845                    format!("value-{i}"),
1846                )
1847                .unwrap();
1848        }
1849        registry.flush_memtables().unwrap();
1850
1851        // Half of the 256 MiB registry cache is far above ~0.7 MiB of data:
1852        // the walk covers every entry.
1853        let stats = registry.warm_block_cache(WARM_CACHE_FILL_FRACTION).unwrap();
1854        assert_eq!(stats.entries_touched, 10_000);
1855        assert!(
1856            stats.usage_after > stats.usage_before,
1857            "warm must fill data blocks into the cache"
1858        );
1859        assert!(
1860            registry
1861                .lookup(StrHash::new("http://example.org/warm-9999"))
1862                .unwrap()
1863                .is_some()
1864        );
1865    }
1866
1867    #[test]
1868    fn warm_block_cache_stops_at_first_probe_when_target_is_tiny() {
1869        let dir = tempfile::tempdir().unwrap();
1870        let path = crate::registry_data_dir(dir.path(), crate::MAIN_REPOSITORY_ID);
1871        let registry = RocksDbRegistry::open(&path, RocksDbTuning::registry_node()).unwrap();
1872        for i in 0..10_000u64 {
1873            registry
1874                .register(
1875                    StrHash::new(&format!("http://example.org/warm-{i}")),
1876                    format!("value-{i}"),
1877                )
1878                .unwrap();
1879        }
1880        registry.flush_memtables().unwrap();
1881
1882        // Target ≈ 2.6 KiB: the first data block read (32 KiB) crosses it, so
1883        // the walk stops at the first probe instead of covering all entries.
1884        let stats = registry.warm_block_cache(1e-5).unwrap();
1885        assert_eq!(stats.entries_touched, WARM_CACHE_PROBE_INTERVAL);
1886        assert!(stats.usage_after > 0);
1887    }
1888
1889    #[test]
1890    fn warm_block_cache_is_a_noop_on_memory() {
1891        let registry = Registry::memory(4);
1892        let stats = registry.warm_block_cache(0.5).unwrap();
1893        assert!(stats.is_noop());
1894    }
1895}