Skip to main content

waratah_storage/
rocksdb_db.rs

1//! Minimal RocksDB FFI wrapper over `waratah-rocksdb-sys` (our fork of
2//! Oxigraph's oxrocksdb-sys).
3//!
4//! Bounded defaults (documented here for operators):
5//! - write buffer: 64 MiB (`rocksdb_options_set_write_buffer_size`); bulk ingest uses 256 MiB
6//! - `max_write_buffer_number`: 2 (RocksDB default); bulk ingest uses 8
7//! - block cache: 64 MiB LRU (`rocksdb_cache_create_lru`)
8//! - LZ4 compression; create DB + missing column families on open
9//!
10//! Env-gated read-path tuning (process-wide, inherited by spawned
11//! storage children):
12//! - `WARATAH_PIN_INDEX` — cache SST index/filter blocks and pin them
13//!   (`cache_index_and_filter_blocks` + `unpartitioned_pinning = kAll`);
14//!   **on by default**, `WARATAH_PIN_INDEX=0` disables
15//! - `WARATAH_SST_FILTER=1` — build per-SST prefix bloom filters on the
16//!   column families marked `prefix_filter` (hexastore `spog` / `sopg` /
17//!   `tsg`; see [`sst_filter_env_enabled`] and
18//!   [`PREFIX_FILTER_BITS_PER_KEY`]); **off by default after the
19//!   2026-11-08 A/B showed costs with no win at the measurable tier** —
20//!   see [`sst_filter_env_enabled`] for the measurements and revisit
21//!   condition
22//! - `WARATAH_WARM_CACHE` — each storage process warms its block cache at
23//!   startup to [`WARM_CACHE_FILL_FRACTION`] of capacity ([`warm_walk`]);
24//!   **on by default**, `WARATAH_WARM_CACHE=0` disables
25//! - `WARATAH_SCAN_ASYNC_IO=1` — submit scan-iterator block reads via
26//!   io_uring (`ReadOptions::async_io`); sequential prefetch only
27//!   (requires `ROCKSDB_IOURING_PRESENT` in the vendored build)
28//! - `WARATAH_MEMTABLE_BATCH_LOOKUP=1` — batch sorted MultiGet memtable
29//!   lookups through one skiplist traversal (immutable; set at open)
30//! - `TEST_HEXASTORE_READAHEAD_SIZE=<KiB>` — **temporary A/B knob**: force an
31//!   explicit iterator readahead window on hexastore stores (whose tuning is
32//!   otherwise `0` = engine auto-readahead), for benchmarking the
33//!   explicit-window + async-prefetch combination. Remove once the
34//!   readahead experiment concludes.
35
36#![allow(
37    unsafe_code,
38    clippy::undocumented_unsafe_blocks,
39    clippy::unwrap_used,
40    clippy::expect_used
41)]
42
43use std::ffi::{CStr, CString, c_void};
44use std::path::{Path, PathBuf};
45use std::ptr;
46use std::slice;
47use std::sync::Arc;
48use std::sync::OnceLock;
49#[cfg(test)]
50use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
51
52use waratah_rocksdb_sys::*;
53
54use crate::StorageError;
55use crate::encode::{IndexPermutation, NAMED_GRAPHS_CATALOG_CF};
56
57/// Default MemTable write-buffer size (bytes).
58pub const DEFAULT_WRITE_BUFFER_BYTES: usize = 64 * 1024 * 1024;
59/// Default `max_write_buffer_number` (RocksDB default is 2).
60pub const DEFAULT_MAX_WRITE_BUFFER_NUMBER: i32 = 2;
61/// Bulk-ingest MemTable write-buffer size (bytes).
62pub const BULK_WRITE_BUFFER_BYTES: usize = 256 * 1024 * 1024;
63/// Bulk-ingest `max_write_buffer_number`.
64pub const BULK_MAX_WRITE_BUFFER_NUMBER: i32 = 8;
65/// Default block-cache capacity (bytes). (our default is 128MB)
66///
67/// FUTURE WORK (very large single-partition stores): index pinning
68/// ([`pin_index_env_enabled`], on by default) places SST index blocks in
69/// this cache outside LRU eviction, and the per-SST prefix filters
70/// ([`sst_filter_env_enabled`], on by default) add their filter blocks to
71/// the same pinned volume. The open path adapts the budget upward when
72/// filters are active — capacity is raised to at least
73/// `2 × estimated filter bytes` (estimate from `estimate-num-keys`; see
74/// `PREFIX_FILTER_BUDGET_FUDGE`) — but it never starts above this
75/// default, so the cold-start path (open, warm pass, first query) always
76/// fits this footprint per store. Measured on the 78 GB yago store
77/// (2026-11-06): open-state RSS is identical with pinning on/off — index
78/// blocks are resident either way — so the budget matters only under
79/// cache PRESSURE: pinned index blocks (~150–270 MB on a 19–27 GB
80/// partition) shrink the data-block working set this budget can hold. If
81/// scan-heavy serving on such partitions shows data-block re-read
82/// pressure, scale this budget to
83/// `max(128 MiB, 2 × (estimated index + filter volume))` at table open
84/// (tracked in `scratch/open_todo.md`).
85pub const DEFAULT_BLOCK_CACHE_BYTES: usize = 128 * 1024 * 1024;
86/// Default SST data-block size (bytes; uncompressed, the RocksDB default).
87///
88/// The read unit, cache unit, compression unit, and checksum unit are all one
89/// block. 4 KiB suits random point lookups; scan-heavy stores (the registry
90/// dictionary) want bigger blocks — see [`REGISTRY_BLOCK_SIZE_BYTES`].
91pub const DEFAULT_BLOCK_SIZE_BYTES: usize = 4 * 1024;
92/// Registry SST data-block size (bytes).
93///
94/// The registry's only real reader is `lookup_many_seek`'s bulk sorted walk:
95/// larger blocks mean ~8× fewer block reads per walk and correspondingly
96/// larger disk requests, which is worth far more than the extra bytes a point
97/// lookup would fetch (the RocksDB registry has no hot point-lookup path).
98/// Applies to SSTs written after the setting is in effect — run a full-range
99/// compaction to rewrite existing files.
100pub const REGISTRY_BLOCK_SIZE_BYTES: usize = 32 * 1024;
101/// Default fixed readahead (bytes) for stores that opt in via
102/// [`RocksDbTuning::iterator_readahead_bytes`] — the registry dictionary,
103/// whose only reader is an unbounded sorted walk.
104///
105/// SST files are opened `POSIX_FADV_RANDOM` (RocksDB `advise_random_on_open`
106/// default), so the kernel never merges the per-block reads of a scan walk —
107/// on spinning disk every 4 KiB block was an individual ~0.45 ms SATA command.
108/// Iterator-level readahead makes RocksDB itself pre-read a window per miss
109/// (its own buffer, unaffected by the fadvise), which the sorted walks then
110/// consume. Hexastore stores keep `0`: their scans carry an iterate upper
111/// bound, so they get the engine's auto-readahead (8 KiB ramping to
112/// `max_auto_readahead_size`, trimmed against the scan range) without a fixed
113/// window. Overridable per process with `WARATAH_ITERATOR_READAHEAD_SIZE`
114/// (KiB); `0` there restores the engine default.
115pub const DEFAULT_ITERATOR_READAHEAD_BYTES: usize = 128 * 1024;
116/// Compaction readahead (bytes).
117///
118/// `rocksdb_options_compaction_readahead_size`: compaction reads its input
119/// SSTs sequentially; 2 MiB matches the RocksDB ≥ 8.7 default (older releases
120/// defaulted to 0, which post-8.6 means almost no readahead). Keep this at or
121/// below the device's `max_sectors_kb` — reads larger than that are split by
122/// the block layer, which measurably hurt application throughput in
123/// smalldatum's 8.6+ benchmarks (github.com/facebook/rocksdb/issues/12038).
124/// The benchmark box's spinners report `max_sectors_kb` 4096, so 2 MiB reads
125/// go out unsplit.
126pub const COMPACTION_READAHEAD_BYTES: usize = 2 * 1024 * 1024;
127
128/// Resolved iterator readahead for this process.
129///
130/// Defaults to [`DEFAULT_ITERATOR_READAHEAD_BYTES`]; `WARATAH_ITERATOR_READAHEAD_SIZE`
131/// overrides it in KiB (`"4"` = 4 KiB, `"1024"` = 1 MiB, `"0"` = off). Child
132/// processes inherit the variable, so setting it before `waratah start`
133/// or `waratah import` tunes the whole cluster.
134pub fn iterator_readahead_bytes() -> usize {
135    static READAHEAD: OnceLock<usize> = OnceLock::new();
136    *READAHEAD.get_or_init(|| {
137        readahead_from_env(
138            std::env::var("WARATAH_ITERATOR_READAHEAD_SIZE")
139                .ok()
140                .as_deref(),
141        )
142    })
143}
144
145/// Parse one `WARATAH_ITERATOR_READAHEAD_SIZE` value (KiB) into bytes.
146fn readahead_from_env(raw: Option<&str>) -> usize {
147    match raw {
148        None => DEFAULT_ITERATOR_READAHEAD_BYTES,
149        Some(raw) => match raw.trim().parse::<usize>() {
150            Ok(kib) => kib.saturating_mul(1024),
151            Err(_) => {
152                eprintln!(
153                    "waratah-storage: ignoring invalid WARATAH_ITERATOR_READAHEAD_SIZE \
154                     {raw:?} (expected a KiB number); using {} KiB",
155                    DEFAULT_ITERATOR_READAHEAD_BYTES / 1024
156                );
157                DEFAULT_ITERATOR_READAHEAD_BYTES
158            }
159        },
160    }
161}
162
163/// Resolved hexastore iterator readahead from the temporary A/B knob
164/// `TEST_HEXASTORE_READAHEAD_SIZE` (KiB), or [`None`] when unset/invalid/zero.
165///
166/// Hexastore stores keep [`RocksDbTuning::iterator_readahead_bytes`] at `0`
167/// (engine auto-readahead: 8 KiB ramping to `max_auto_readahead_size`, and
168/// it only engages after 2 sequential misses). This knob forces an explicit
169/// window instead — which engages from the very first IO, runs the
170/// fixed-size two-buffer async prefetch when `WARATAH_SCAN_ASYNC_IO` is on,
171/// and is trimmed against the iterate upper bound. Applies only at the
172/// hexastore open path ([`crate::rocksdb::RocksDbStorage::open_with_hooks`]);
173/// the registry's readahead (`WARATAH_ITERATOR_READAHEAD_SIZE`) is
174/// unaffected. Temporary: remove with the readahead experiment.
175pub fn hexastore_readahead_env_bytes() -> Option<usize> {
176    hexastore_readahead_from_env(
177        std::env::var("TEST_HEXASTORE_READAHEAD_SIZE")
178            .ok()
179            .as_deref(),
180    )
181}
182
183/// Upper bound for the test knob (KiB): explicit readahead is a fixed
184/// window (no ramping) held in up to two buffers per iterator, so a typo
185/// like `=16000` (16 MiB) must not silently become a memory problem.
186const TEST_HEXASTORE_READAHEAD_MAX_KIB: usize = 8 * 1024;
187
188/// Parse one `TEST_HEXASTORE_READAHEAD_SIZE` value (KiB) into bytes.
189/// Unset and `0` are no-ops (the hexastore default is already the engine
190/// default); junk warns and disables; values above
191/// [`TEST_HEXASTORE_READAHEAD_MAX_KIB`] warn and clamp.
192fn hexastore_readahead_from_env(raw: Option<&str>) -> Option<usize> {
193    let kib = match raw.map(str::trim).filter(|value| !value.is_empty()) {
194        None => return None,
195        Some(raw) => match raw.parse::<usize>() {
196            Ok(0) => return None,
197            Ok(kib) => kib,
198            Err(_) => {
199                eprintln!(
200                    "waratah-storage: ignoring invalid TEST_HEXASTORE_READAHEAD_SIZE \
201                     {raw:?} (expected a KiB number); hexastore keeps engine \
202                     auto-readahead"
203                );
204                return None;
205            }
206        },
207    };
208    if kib > TEST_HEXASTORE_READAHEAD_MAX_KIB {
209        eprintln!(
210            "waratah-storage: clamping TEST_HEXASTORE_READAHEAD_SIZE {kib} KiB \
211             to {TEST_HEXASTORE_READAHEAD_MAX_KIB} KiB (fixed window, two \
212             buffers per iterator)"
213        );
214        Some(TEST_HEXASTORE_READAHEAD_MAX_KIB * 1024)
215    } else {
216        Some(kib * 1024)
217    }
218}
219
220/// Parse an on/off flag value; unset/empty falls back to `default`.
221/// Unrecognized non-empty values warn and fall back to `default` (a typo
222/// must not silently flip tuning).
223pub(crate) fn env_flag(var: &str, raw: Option<&str>, default: bool) -> bool {
224    match raw.map(str::trim).filter(|value| !value.is_empty()) {
225        None => default,
226        Some(value) => match value.to_ascii_lowercase().as_str() {
227            "1" | "true" | "on" | "yes" => true,
228            "0" | "false" | "off" | "no" => false,
229            other => {
230                eprintln!(
231                    "waratah-storage: ignoring invalid {var}={other:?} \
232                     (expected 1/true/on/yes or 0/false/off/no); using default {default}"
233                );
234                default
235            }
236        },
237    }
238}
239
240/// Gate A: cache + pin SST index/filter blocks, process-wide
241/// (**on by default**; `WARATAH_PIN_INDEX=0` disables). Child processes
242/// inherit the variable, so setting it before `waratah start` / `waratah
243/// import` covers the whole local cluster. See
244/// [`RocksDbTuning::pin_index_in_cache`] for the semantics.
245///
246/// Default on (measured 2026-11-06, lubm-100): the cold pass — the first
247/// query a fresh process serves — ran 4× faster with pinning (7.6 ms →
248/// 1.8 ms) because the startup warm walk's data-block fill no longer
249/// evicts the index blocks a point seek consults; steady state is
250/// unchanged. Pinned volume is index blocks plus, when
251/// [`sst_filter_env_enabled`] is on, the per-SST prefix-bloom filter
252/// blocks of the `prefix_filter` column families — roughly ~1% of
253/// partition bytes for indexes at the 4 KiB block size, plus
254/// `distinct-leading-terms × PREFIX_FILTER_BITS_PER_KEY / 8` for filters.
255/// The open path raises the cache budget to keep both inside it (see
256/// [`DEFAULT_BLOCK_CACHE_BYTES`]); that is the revisit condition if very
257/// large single-partition stores still show budget pressure.
258pub fn pin_index_env_enabled() -> bool {
259    static GATE: OnceLock<bool> = OnceLock::new();
260    *GATE.get_or_init(|| {
261        env_flag(
262            "WARATAH_PIN_INDEX",
263            std::env::var("WARATAH_PIN_INDEX").ok().as_deref(),
264            true,
265        )
266    })
267}
268
269/// Bloom bits per key for the per-SST prefix filters
270/// ([`sst_filter_env_enabled`]).
271///
272/// 10 bits gives ~1% false positives; a false positive costs one wasted
273/// index seek, so there is no reason to pay more bits. Entries are added
274/// per DISTINCT leading term, not per key: the filtered CFs set
275/// `whole_key_filtering = false`, so the filter holds one entry per
276/// distinct subject (spog/sopg) or class (tsg) — the numbers that decide
277/// filter bytes are the term cardinalities, not the quad count.
278pub const PREFIX_FILTER_BITS_PER_KEY: f64 = 10.0;
279
280/// Fudge factor over `num_keys × bits/8` when estimating filter bytes for
281/// the adaptive block-cache budget: `estimate-num-keys` counts quads, but
282/// the filter holds distinct leading terms — for spog/sopg that is the
283/// distinct-subject count, always ≤ quads. The over-estimate is safe (the
284/// budget is a bound, not an allocation) and errs toward keeping filters
285/// resident.
286pub const PREFIX_FILTER_BUDGET_FUDGE: f64 = 1.1;
287
288/// Test-only process-wide override for [`sst_filter_env_enabled`]: the
289/// filter tests force the gate on because the env var default is OFF, and
290/// setting the env from a test would race the OnceLock cache against
291/// unrelated `Db` opens in the same test binary. Harmless to leave set:
292/// only `prefix_filter` column families consult the gate, and within this
293/// module's tests none of the raw-`Db` fixtures mark one. The hexastore
294/// stores opened by the `rocksdb.rs` domain-scan tests do mark spog/sopg
295/// (their `confined_domain_scans_stay_correct_with_sst_filters_armed`
296/// test sets this flag deliberately); once set, later stores in the same
297/// test binary build filter blocks too — which is exactly the
298/// armed-correctness invariant those tests pin, so leaving it set is
299/// harmless there as well.
300#[cfg(test)]
301pub(crate) static TEST_SST_FILTER_FORCE_ON: AtomicBool = AtomicBool::new(false);
302
303/// Gate: build per-SST prefix bloom filters on every column family marked
304/// `prefix_filter` in its [`ColumnFamilyDefinition`] (hexastore `spog` /
305/// `sopg` / `tsg` today). **Off by default**; `WARATAH_SST_FILTER=1`
306/// enables. Child processes inherit the variable, so setting it before
307/// `waratah start` / `waratah import` covers the whole local cluster.
308///
309/// Default OFF (measured 2026-11-08, bellendena-sparql-100m, 13 GB store,
310/// compacted, 32 GB RAM / NVMe): the skip mechanism works (a disk-cold
311/// absent-subject probe ran 13 ms → 11 ms and `SEEK_FILTERED` moved) but
312/// nothing else improved — steady-state queries flat to +4%, a cold
313/// present-heavy broadcast join +28% (per-term consult CPU scales with
314/// driver terms × overlapping SSTs), cold start +1.2 s (filter prefetch +
315/// the enlarged warm pass), steady RSS +274 MB, S-axis disk +50 MB (+1%).
316/// Costs with no demonstrated win at that tier → default off.
317///
318/// The yago revisit (same day, 76 GB store) made the default off look
319/// generous: cold start 7.3 s → 19.9 s, warm start 7.6 s → 22.7 s,
320/// children RSS +2 GB, and — decisive — a CORRECTNESS failure: with the
321/// gate on, `SELECT DISTINCT ?c WHERE { ?s a ?c }` returned 2 rows
322/// instead of 10,098 in 7 ms. Mechanism: the axis-head walks'
323/// `byte_successor(bare term)` skips (skip, resume, allow-list per-head)
324/// seek keys whose 17-byte prefix belongs to no key; with a prefix
325/// extractor set and default (non-total-order) read options RocksDB
326/// treats the seek as prefix-mode, the bloom answers "prefix absent",
327/// and the whole SST is marked exhausted — silently truncating the walk.
328/// Pattern scans are immune (they seek real term prefixes and `Next()`
329/// never re-consults the bloom), which is why the storage tests and the
330/// bellendena corpus missed it.
331///
332/// Armed-seeking safety (2026-11-09, closed): the general rule is
333/// range ≡ seek prefix — a `Seek` consults the seek target's prefix and
334/// "absent here" marks the SST exhausted from that seek onward; the
335/// pruning is transient across seeks (each seek consults fresh) but
336/// permanent within one seek's walk, so the soundness condition is that
337/// every key the walk still needs is reachable via seeks whose targets
338/// are present in the SSTs holding them. Three violating or
339/// range-exceeding shapes carry `total_order_seek`:
340///
341/// - The axis-head walks via [`Db::scan_prefix_total_order`]:
342///   bare-term successor seeks (skip, resume, and the allow-list mode's
343///   per-head skips) — every consult target is malformed everywhere, so
344///   the pruning never lifts.
345/// - Sliced multi-constraint walks (one seek at slice start, `Next()`
346///   across a range spanning many prefixes; a real prefix absent in an
347///   SST prunes that SST's later-range rows for the whole slice — the
348///   shape that surfaced in the DomainScanCounts improvement work), and
349///   the pattern-count walkers for the same reason via
350///   [`Db::scan_prefix_from_total_order`]: a full-axis slice spans ~1/8
351///   of the CF's term space and a TSG hint slice spans several whole
352///   classes, while the slice's start probe and hint-aligned starts
353///   name only the first term visited — real, present prefixes, so no
354///   seek-shape fix exists (confinement would be the per-term
355///   seek-union shape the domain work deleted). Pinned by
356///   `count_walks_stay_exact_with_sst_filters_armed`, which failed 6 vs
357///   4 on armed full-axis Spog without the flag.
358/// - `max_commit_ts_under_prefixes` as hardening: its per-prefix
359///   re-seeks make it sound without the flag (each seek consults fresh
360///   with a real, present target), but it is a one-shot upgrade op
361///   whose contract is "must observe every matching key".
362///
363/// The domain walks (legacy + parallel) are otherwise filter-safe by
364/// key arithmetic: every seek (initial, resume successor, per-head
365/// successor) keeps the extractor window on the constraint's own
366/// prefix, and measured armed serving accelerated them (10k-constraint
367/// VALUES cell −15.7%, 1k-constraint −26.8%) with byte-identical
368/// results. Residual: the window stays on the constraint's own prefix
369/// only while the constraint encoding fills the extractor window —
370/// every validated-path shape does (node encodings and string literals
371/// are exactly 17 bytes), but a typed numeric/date literal class
372/// (9 bytes, reachable as a TSG class only through `waratah import
373/// --offline`, which skips the `validate_type_objects` IRI check in
374/// `waratah_compute/src/fanout.rs`) leaves the successor seek's window
375/// mid-head-term, and SSTs holding only later heads of the same
376/// constraint are then pruned. The pins exercise 17-byte constraints
377/// only; arming over offline-imported literal classes stays the
378/// recorded open verification. Armed regression tests pin the families
379/// (`axis_head_scans_stay_complete_with_sst_filters_armed`,
380/// `confined_domain_scans_stay_correct_with_sst_filters_armed`,
381/// `count_walks_stay_exact_with_sst_filters_armed`). Arming is a
382/// property of the OPENING process: blocks are only loaded when the
383/// gate is on at open — a gate-off server on an armed store neither
384/// benefits nor truncates.
385///
386/// Write side: flush and compaction attach filter blocks to new SSTs
387/// (existing SSTs gain them on rewrite — run `waratah compact` with the
388/// gate on to backfill, and again with it off to strip them). Read side:
389/// the table factory consults the prefix bloom on point `Get`/`MultiGet`
390/// and on iterator `Seek` (default read options: `total_order_seek` off),
391/// skipping whole SSTs whose filter says the leading term is absent.
392/// Seeks shorter than the fixed prefix stay outside the extractor domain
393/// and simply skip the check.
394///
395/// Interplay with `WARATAH_PIN_INDEX` (default on): filter blocks are
396/// cached AND pinned, so enabling this multiplies the pinned volume by
397/// the filter bytes; the open path compensates by raising the block-cache
398/// capacity to at least `2 ×` the estimated filter volume (see
399/// [`Db::open_read_write_with_hooks`]) so the warm pass and the
400/// data-block working set keep their room.
401pub fn sst_filter_env_enabled() -> bool {
402    #[cfg(test)]
403    if TEST_SST_FILTER_FORCE_ON.load(AtomicOrdering::Relaxed) {
404        return true;
405    }
406    static GATE: OnceLock<bool> = OnceLock::new();
407    *GATE.get_or_init(|| {
408        env_flag(
409            "WARATAH_SST_FILTER",
410            std::env::var("WARATAH_SST_FILTER").ok().as_deref(),
411            false,
412        )
413    })
414}
415
416/// RocksDB statistics ticker ids read through
417/// [`Db::ticker_count`].
418///
419/// The C API takes tickers as a raw `u32` — these mirror the numeric
420/// values of the C++ `Tickers` enum in `rocksdb/include/rocksdb/
421/// statistics.h` (sequential from `BLOCK_CACHE_MISS = 0`; re-verify the
422/// numbers on a RocksDB upgrade). Statistics are enabled only when the
423/// per-SST prefix-filter gate is on (see [`sst_filter_env_enabled`] —
424/// the tickers exist to verify filter consults), so the counts are live
425/// only for DBs opened under that gate and read 0 otherwise; they cover
426/// this DB only (per-process, per-store).
427pub const TICKER_BLOCK_CACHE_FILTER_MISS: u32 = 8;
428/// See [`TICKER_BLOCK_CACHE_FILTER_MISS`]: filter-block cache lookups
429/// served from cache (a consult on an already-resident filter block).
430pub const TICKER_BLOCK_CACHE_FILTER_HIT: u32 = 9;
431/// See [`TICKER_BLOCK_CACHE_FILTER_MISS`]: a prefix bloom was checked on
432/// the `Get`/`MultiGet` path (`BLOOM_FILTER_PREFIX_CHECKED`).
433pub const TICKER_BLOOM_FILTER_PREFIX_CHECKED: u32 = 38;
434/// See [`TICKER_BLOCK_CACHE_FILTER_MISS`]: a prefix bloom check came back
435/// negative and skipped work (`BLOOM_FILTER_PREFIX_USEFUL`). Note the
436/// iterator-`Seek` consult path records only perf counters upstream, so
437/// this ticker proves the point-lookup path; seek consults are observed
438/// via the filter-block cache tickers above instead.
439pub const TICKER_BLOOM_FILTER_PREFIX_USEFUL: u32 = 39;
440/// See [`TICKER_BLOCK_CACHE_FILTER_MISS`]: an iterator `Seek` consulted
441/// the prefix bloom and the negative verdict skipped the whole SST
442/// (`NON_LAST_LEVEL_SEEK_FILTERED`, recorded at the skip decision in
443/// `BlockBasedTableIterator::Seek`). This is the seek-side counterpart of
444/// [`TICKER_BLOOM_FILTER_PREFIX_USEFUL`] — the exact consult the
445/// broadcast-filter seek-union and bound-subject pattern scans pay for.
446pub const TICKER_SEEK_FILTERED: u32 = 210;
447/// See [`TICKER_SEEK_FILTERED`]: an iterator `Seek` consulted the prefix
448/// bloom and it did NOT skip (`NON_LAST_LEVEL_SEEK_FILTER_MATCH`).
449pub const TICKER_SEEK_FILTER_MATCH: u32 = 211;
450
451/// Gate: batch the sorted MultiGet key set through one memtable skiplist
452/// traversal instead of per-key lookups (`WARATAH_MEMTABLE_BATCH_LOOKUP=1`;
453/// off by default, matching the upstream default).
454///
455/// Skiplist-only by design: non-skip-list memtable reps fall back to
456/// per-key lookups, and Waratah uses the default rep. The option is
457/// immutable in RocksDB — set here at open, or never. The optimization
458/// exploits the fact that `MultiGet` keys are sorted: RocksDB prepares
459/// every batch's keys internally (copying and sorting them when the caller
460/// passes `sorted_input=false`), so the knob helps any `MultiGet`. In
461/// Waratah the tree's only `MultiGet` runs behind the
462/// `WARATAH_RESOLVE_MULTIGET` gate, whose callers always pass pre-sorted
463/// slices.
464pub fn memtable_batch_lookup_env_enabled() -> bool {
465    static GATE: OnceLock<bool> = OnceLock::new();
466    *GATE.get_or_init(|| {
467        env_flag(
468            "WARATAH_MEMTABLE_BATCH_LOOKUP",
469            std::env::var("WARATAH_MEMTABLE_BATCH_LOOKUP")
470                .ok()
471                .as_deref(),
472            false,
473        )
474    })
475}
476
477/// Gate B: run the occupancy-targeted block-cache warm pass at startup
478/// ([`warm_walk`]). **On by default**; `WARATAH_WARM_CACHE=0` (or
479/// `false`/`off`/`no`) disables it. Child processes inherit the variable,
480/// so setting it before `waratah start` / `waratah import` covers the
481/// whole local cluster.
482pub fn warm_cache_env_enabled() -> bool {
483    static GATE: OnceLock<bool> = OnceLock::new();
484    *GATE.get_or_init(|| {
485        env_flag(
486            "WARATAH_WARM_CACHE",
487            std::env::var("WARATAH_WARM_CACHE").ok().as_deref(),
488            true,
489        )
490    })
491}
492
493/// Gate: submit scan-iterator block reads asynchronously via io_uring
494/// (`ReadOptions::async_io`), process-wide (`WARATAH_SCAN_ASYNC_IO=1`;
495/// off by default). Engages for sequential iteration — forward hexastore
496/// scans, geo/temporal drains, and the registry warm pass; random seek
497/// patterns (the resolve path) are unaffected. Requires io_uring support
498/// compiled into the library (`ROCKSDB_IOURING_PRESENT`); silent
499/// synchronous fallback otherwise.
500pub fn scan_async_io_env_enabled() -> bool {
501    static GATE: OnceLock<bool> = OnceLock::new();
502    *GATE.get_or_init(|| {
503        env_flag(
504            "WARATAH_SCAN_ASYNC_IO",
505            std::env::var("WARATAH_SCAN_ASYNC_IO").ok().as_deref(),
506            false,
507        )
508    })
509}
510
511/// Fraction of block-cache capacity the warm pass fills before stopping
512/// ([`warm_walk`]).
513///
514/// Deliberately below 1.0: an LRU evicts from its tail, so warming to exact
515/// capacity would have the pass's own tail evict its head before the first
516/// query runs. Headroom also absorbs pinned index blocks (when
517/// `WARATAH_PIN_INDEX` is on) and the first queries' own misses.
518pub const WARM_CACHE_FILL_FRACTION: f64 = 0.667;
519
520/// Warm-pass cache-usage probe cadence (iterated entries).
521///
522/// `rocksdb_cache_get_usage` takes the cache's internal shard mutex, so
523/// probing per entry would throttle the walk itself; a few thousand entries
524/// between probes bounds overshoot to a block or two.
525pub const WARM_CACHE_PROBE_INTERVAL: u64 = 4096;
526
527/// Block-cache occupancy counters for one warm pass.
528#[derive(Debug, Clone, Copy, PartialEq, Eq)]
529pub struct WarmBlockCacheStats {
530    /// CF entries the pass visited (data + metadata CFs; a superset of what
531    /// landed in the cache, since the walk stops at the occupancy target).
532    pub entries_touched: u64,
533    /// Block-cache bytes before the pass.
534    pub usage_before: usize,
535    /// Block-cache bytes after the pass (includes pinned index blocks).
536    pub usage_after: usize,
537    /// Configured block-cache capacity for this DB.
538    pub capacity: usize,
539}
540
541impl WarmBlockCacheStats {
542    /// Stats for a backend with no block cache (memory) or a skipped pass.
543    pub fn noop() -> Self {
544        Self {
545            entries_touched: 0,
546            usage_before: 0,
547            usage_after: 0,
548            capacity: 0,
549        }
550    }
551
552    /// True when nothing was warmed (no-op backend, disabled, or target
553    /// already met before the walk started).
554    pub fn is_noop(&self) -> bool {
555        self.entries_touched == 0
556    }
557}
558
559/// Walk `column_families` front-to-back until block-cache usage reaches
560/// `target`, dropping values as they stream (the block fills are the point).
561///
562/// CFs must be ordered big-to-small: the occupancy target is shared, so once
563/// it is hit the remaining CFs are skipped entirely. A `target` of `0`
564/// (fill fraction ≤ 0) disables the walk.
565pub(crate) fn warm_walk(
566    db: &Db,
567    column_families: &[&ColumnFamily],
568    target: usize,
569) -> Result<u64, StorageError> {
570    if target == 0 {
571        return Ok(0);
572    }
573    let mut entries = 0u64;
574    'cfs: for cf in column_families {
575        let mut it = db.scan_prefix(cf, &[]);
576        while it.is_valid() {
577            it.next();
578            entries += 1;
579            if entries.is_multiple_of(WARM_CACHE_PROBE_INTERVAL) && db.block_cache_usage() >= target
580            {
581                it.status()?;
582                break 'cfs;
583            }
584        }
585        it.status()?;
586    }
587    Ok(entries)
588}
589
590/// RocksDB open knobs shared by hexastore partitions and the disk registry.
591#[derive(Debug, Clone, Copy, PartialEq, Eq)]
592pub struct RocksDbTuning {
593    /// MemTable write-buffer size (`rocksdb_options_set_write_buffer_size`).
594    pub write_buffer_bytes: usize,
595    /// Number of MemTables (`rocksdb_options_set_max_write_buffer_number`).
596    pub max_write_buffer_number: i32,
597    /// Block cache size (`rocksdb_cache_create_lru`).
598    pub block_cache_bytes: usize,
599    /// SST data-block size (`rocksdb_block_based_options_set_block_size`).
600    ///
601    /// Affects SSTs written after open (flush/compaction output); existing
602    /// files keep their original block size until rewritten.
603    pub block_size_bytes: usize,
604    /// Fixed per-iterator readahead in bytes
605    /// (`rocksdb_readoptions_set_readahead_size`); `0` keeps the engine
606    /// default, whose implicit auto-readahead engages only for iterators with
607    /// an iterate upper bound or `prefix_same_as_start` (hexastore scans) and
608    /// never for the registry's unbounded walk — which is why the registry
609    /// tuning sets an explicit value here.
610    pub iterator_readahead_bytes: usize,
611    /// Disable background compaction.
612    pub disable_auto_compactions: bool,
613    /// Skip the write-ahead log (`rocksdb_writeoptions_disable_WAL`).
614    pub disable_wal: bool,
615    /// Fsync the write-ahead log entry of every write before it returns
616    /// (`rocksdb_writeoptions_set_sync`).
617    ///
618    /// A `WriteBatch::commit` that returns is then durable: RocksDB flushes
619    /// and fsyncs the WAL entry inside `rocksdb_write`. Only meaningful with
620    /// the WAL enabled — with `disable_wal: true` there is nothing to sync
621    /// and the write returns after the MemTable insert. The blob index sets
622    /// this so a returning `PutBlobs` means the locators are on disk, which
623    /// is what the durability contract of the segment tier is written
624    /// against (segment records are fdatasynced before the commit, and the
625    /// commit must not silently lag them).
626    pub sync_writes: bool,
627    /// Submit scan-iterator block reads asynchronously via io_uring
628    /// (`ReadOptions::async_io`). Also enabled process-wide by
629    /// `WARATAH_SCAN_ASYNC_IO=1`. Engages for sequential iteration (forward
630    /// scans, the warm pass); random seek patterns are unaffected. Requires
631    /// the library built with io_uring support (`ROCKSDB_IOURING_PRESENT`);
632    /// silent synchronous fallback otherwise.
633    pub scan_async_io: bool,
634    /// Cache SST index/filter blocks in the block cache and pin them there
635    /// (`cache_index_and_filter_blocks` + `unpartitioned_pinning = kAll`).
636    ///
637    /// Also enabled process-wide by `WARATAH_PIN_INDEX=1`. Under the default
638    /// `false`, index blocks live in table-reader heap memory — resident for
639    /// immortal readers, but invisible to the block cache. Pinning is
640    /// read-path state: it applies to newly opened stores and needs no data
641    /// rewrite. `pin_top_level_index_and_filter` would be the wrong knob here:
642    /// it governs *partitioned* indexes only, and every waratah index is the
643    /// default binary-search (unpartitioned) kind.
644    pub pin_index_in_cache: bool,
645    /// Bloom-filter bits per key attached to the SST table factory (`None`
646    /// = no filter policy).
647    ///
648    /// The policy is created once at open and shared by every column family
649    /// in that DB. Point-lookup stores (the blob index) enable it; the
650    /// scan-heavy hexastore and registry dictionaries leave it off. Ten bits
651    /// per key is the standard false-positive / memory trade-off.
652    pub bloom_filter_bits_per_key: Option<u8>,
653}
654
655impl Default for RocksDbTuning {
656    fn default() -> Self {
657        Self {
658            write_buffer_bytes: DEFAULT_WRITE_BUFFER_BYTES,
659            max_write_buffer_number: DEFAULT_MAX_WRITE_BUFFER_NUMBER,
660            block_cache_bytes: DEFAULT_BLOCK_CACHE_BYTES,
661            block_size_bytes: DEFAULT_BLOCK_SIZE_BYTES,
662            iterator_readahead_bytes: 0,
663            disable_auto_compactions: false,
664            disable_wal: false,
665            sync_writes: false,
666            pin_index_in_cache: false,
667            scan_async_io: false,
668            bloom_filter_bits_per_key: None,
669        }
670    }
671}
672
673impl RocksDbTuning {
674    /// Offline ingest: large buffers, extra MemTables, no background compact.
675    pub fn bulk_ingest(disable_wal: bool) -> Self {
676        Self {
677            write_buffer_bytes: BULK_WRITE_BUFFER_BYTES,
678            max_write_buffer_number: BULK_MAX_WRITE_BUFFER_NUMBER,
679            block_cache_bytes: DEFAULT_BLOCK_CACHE_BYTES,
680            block_size_bytes: DEFAULT_BLOCK_SIZE_BYTES,
681            iterator_readahead_bytes: 0,
682            disable_auto_compactions: true,
683            disable_wal,
684            sync_writes: false,
685            pin_index_in_cache: false,
686            scan_async_io: false,
687            bloom_filter_bits_per_key: None,
688        }
689    }
690
691    /// Registry node: normal buffers, larger block cache to avoid evictions.
692    pub fn registry_node() -> Self {
693        Self {
694            write_buffer_bytes: DEFAULT_WRITE_BUFFER_BYTES,
695            max_write_buffer_number: DEFAULT_MAX_WRITE_BUFFER_NUMBER,
696            // Registry node always has a larger than normal
697            // block cache to avoid evictions.
698            block_cache_bytes: DEFAULT_BLOCK_CACHE_BYTES * 2,
699            // The registry is read by bulk sorted walks, not point lookups:
700            // bigger blocks mean fewer, larger disk requests per walk.
701            block_size_bytes: REGISTRY_BLOCK_SIZE_BYTES,
702            // The walk is unbounded (no iterate upper bound), so RocksDB's
703            // implicit auto-readahead never engages for it — an explicit
704            // window is the only readahead it will ever get.
705            iterator_readahead_bytes: iterator_readahead_bytes(),
706            disable_auto_compactions: false,
707            disable_wal: false,
708            sync_writes: false,
709            // Index pinning is gated process-wide by `WARATAH_PIN_INDEX`
710            // (checked at open, see [`pin_index_env_enabled`]), so the named
711            // tuning stays env-independent for tests.
712            pin_index_in_cache: false,
713            // Same treatment for scan async I/O: process gate is applied at
714            // open (see [`scan_async_io_env_enabled`]).
715            scan_async_io: false,
716            bloom_filter_bits_per_key: None,
717        }
718    }
719
720    /// Blob index: point lookups, not scans.
721    ///
722    /// The blob index maps a 16-byte content hash to either an inline payload
723    /// or a segment locator. Both are point lookups, so the tuning is the
724    /// opposite of the registry dictionary's: 4 KiB blocks (the value is
725    /// usually one block), a dedicated 64 MiB cache (the index is small but
726    /// the cache must be isolated from the dictionary's 256 MiB), and a
727    /// Bloom filter to skip SSTs that cannot contain the key. The default
728    /// level compaction applies; the index is append-only, so the write
729    /// amplification is a one-time import cost.
730    ///
731    /// Writes are synchronous: segment records are fdatasynced BEFORE the
732    /// locator commit, and the commit itself must not lag them in a crash —
733    /// an async-WAL commit that returns before its WAL entry reaches disk
734    /// would break "a durable locator implies durable bytes" from the other
735    /// side. One fsync per `PutBlobs` batch is also strictly cheaper than
736    /// the per-blob-file fsync this store replaced.
737    pub fn blob_index() -> Self {
738        Self {
739            write_buffer_bytes: DEFAULT_WRITE_BUFFER_BYTES,
740            max_write_buffer_number: DEFAULT_MAX_WRITE_BUFFER_NUMBER,
741            block_cache_bytes: 64 * 1024 * 1024,
742            block_size_bytes: DEFAULT_BLOCK_SIZE_BYTES,
743            iterator_readahead_bytes: 0,
744            disable_auto_compactions: false,
745            disable_wal: false,
746            sync_writes: true,
747            pin_index_in_cache: false,
748            scan_async_io: false,
749            bloom_filter_bits_per_key: Some(10),
750        }
751    }
752}
753
754macro_rules! ffi_result {
755    ( $($function:ident)::*( $arg1:expr $(, $arg:expr)* $(,)? ) ) => {{
756        let mut error: *mut ::std::ffi::c_char = ::std::ptr::null_mut();
757        let result = $($function)::*($arg1 $(, $arg)* , &mut error);
758        if error.is_null() {
759            Ok(result)
760        } else {
761            Err(error_from_ptr(error))
762        }
763    }};
764}
765
766fn error_from_ptr(error: *mut std::ffi::c_char) -> StorageError {
767    // SAFETY: RocksDB returns a malloc'd C string on error.
768    let msg = unsafe {
769        let cstr = CStr::from_ptr(error);
770        let owned = cstr.to_string_lossy().into_owned();
771        rocksdb_free(error.cast());
772        owned
773    };
774    StorageError::Backend(msg)
775}
776
777/// Owns a `rocksdb_pinnable_multi_get_t` until dropped: one destroy call
778/// frees every pinned value and error message in the batch, so results
779/// borrowed from it stay valid for the guard's whole lifetime.
780struct PinnableMultiGetGuard(*mut rocksdb_pinnable_multi_get_t);
781
782/// Result states of `rocksdb_pinnable_multi_get_result`, aliased because the
783/// generated constants are bindgen's lower-case renderings of the C enum.
784const PINNABLE_NOT_FOUND: u32 = rocksdb_pinnable_multi_get_not_found;
785const PINNABLE_FOUND: u32 = rocksdb_pinnable_multi_get_found;
786const PINNABLE_ERROR: u32 = rocksdb_pinnable_multi_get_error;
787const PINNABLE_OUT_OF_BOUNDS: u32 = rocksdb_pinnable_multi_get_out_of_bounds;
788
789impl Drop for PinnableMultiGetGuard {
790    fn drop(&mut self) {
791        if !self.0.is_null() {
792            // SAFETY: non-null pointer from `rocksdb_batched_multi_get_pinned_cf`.
793            unsafe { rocksdb_pinnable_multi_get_destroy(self.0) };
794        }
795    }
796}
797
798/// Optional RocksDB options hooks (stats collectors, event listeners).
799///
800/// Pointers are `*mut rocksdb_options_t` cast to [`c_void`]. Hooks run before
801/// `rocksdb_open_column_families`. The DB hook is applied to the top-level
802/// options **after** per-CF copies are made, so listeners registered there are
803/// not duplicated onto every column family.
804#[derive(Default)]
805pub struct RocksDbOptionsHooks<'a> {
806    /// Invoked with the DB-level options pointer.
807    pub configure_db: Option<&'a dyn Fn(*mut c_void)>,
808    /// Invoked for each hexastore CF (not the implicit `default` CF).
809    pub configure_cf: Option<&'a dyn Fn(IndexPermutation, *mut c_void)>,
810    /// Invoked for the S-axis `named_graphs_catalog` CF (stats collector).
811    pub configure_catalog_cf: Option<&'a dyn Fn(*mut c_void)>,
812    /// Invoked for the O-axis `temporal_index` CF (temporal histogram
813    /// collector).
814    pub configure_temporal_cf: Option<&'a dyn Fn(*mut c_void)>,
815    /// Invoked for the O-axis `geo_index` CF (geo cell-count collector).
816    pub configure_geo_cf: Option<&'a dyn Fn(*mut c_void)>,
817    /// Buffer / WAL / compaction knobs applied to the base options before CF copies.
818    pub tuning: RocksDbTuning,
819}
820
821/// Whether a manual compact rewrites the bottommost level.
822///
823/// Numeric values match RocksDB `BottommostLevelCompaction` (`kSkip` = 0,
824/// `kForce` = 2). The C API takes that discriminant as an `unsigned char`.
825#[derive(Clone, Copy, Debug, PartialEq, Eq)]
826#[repr(u8)]
827pub enum BottommostLevelCompaction {
828    /// Do not rewrite the bottommost level.
829    ///
830    /// A single flushed file can be trivial-moved. Properties already on it
831    /// stay, which is safe when the flush ran with the stats collectors attached.
832    Skip = 0,
833    /// Rewrite the bottommost level even when RocksDB would trivial-move.
834    ///
835    /// A move does not build a new SST, so a collector on the compact never
836    /// sees those keys. Files flushed without collectors need this to gain
837    /// `waratah.stats`.
838    Force = 2,
839}
840
841/// Disable RocksDB background compaction on DB or CF options (`*mut rocksdb_options_t`).
842pub fn disable_auto_compactions(options: *mut c_void) {
843    if options.is_null() {
844        return;
845    }
846    unsafe {
847        rocksdb_options_set_disable_auto_compactions(options.cast(), 1);
848    }
849}
850
851/// Column-family open parameters.
852#[derive(Debug, Clone, Copy)]
853pub struct ColumnFamilyDefinition {
854    /// CF name (static for handle lookup).
855    pub name: &'static str,
856    /// Minimum fixed prefix length for the prefix extractor (`0` = disabled).
857    pub min_prefix_size: usize,
858    /// Build per-SST prefix bloom filters for this CF (requires
859    /// `min_prefix_size > 0` and [`sst_filter_env_enabled`]). The filter
860    /// holds distinct `min_prefix_size`-byte prefixes, so it answers
861    /// "might this SST contain a row whose leading term hashes to this
862    /// prefix?" — worth it only when the leading term is fixed-width AND
863    /// high-cardinality (hexastore subject / class columns), pure
864    /// overhead when the leading term clusters (predicate columns).
865    pub prefix_filter: bool,
866    /// Hexastore permutation for this CF; [`None`] for the implicit `default` CF.
867    pub permutation: Option<IndexPermutation>,
868}
869
870#[derive(Clone)]
871pub struct Db {
872    inner: Arc<DbInner>,
873}
874
875struct DbInner {
876    db: *mut rocksdb_t,
877    options: *mut rocksdb_options_t,
878    read_options: *mut rocksdb_readoptions_t,
879    write_options: *mut rocksdb_writeoptions_t,
880    block_based_table_options: *mut rocksdb_block_based_table_options_t,
881    /// Second table-options set carrying the prefix-bloom filter policy,
882    /// applied per-CF on every `prefix_filter` column family (null when
883    /// no CF filters). Kept alive for the DB's lifetime because the
884    /// options copies that reference it only hold a snapshot taken at
885    /// `set_block_based_table_factory` time; destroyed in [`Drop`].
886    ///
887    /// Ownership note: `rocksdb_block_based_options_set_filter_policy`
888    /// transfers the `rocksdb_filterpolicy_t*` into these options (a
889    /// `shared_ptr` `.reset(raw)`) — the factories' shared_ptr copies keep
890    /// the policy alive after this handle is destroyed, and the handle
891    /// itself must NEVER be passed to `rocksdb_filterpolicy_destroy`
892    /// (that would double-free it).
893    filtered_table_options: *mut rocksdb_block_based_table_options_t,
894    cache: *mut rocksdb_cache_t,
895    iterator_readahead_bytes: usize,
896    /// Submit scan-iterator block reads via io_uring (see
897    /// [`RocksDbTuning::scan_async_io`]).
898    scan_async_io: bool,
899    column_family_names: Vec<&'static str>,
900    cf_handles: Vec<*mut rocksdb_column_family_handle_t>,
901    cf_options: Vec<*mut rocksdb_options_t>,
902}
903
904// SAFETY: RocksDB handles are internally synchronized for the operations we
905// use. Concurrent iterator creation from multiple threads is supported by
906// RocksDB (DB and CF handles are thread-safe for reads): the parallel domain
907// walks (`WARATAH_DOMAIN_WALKS`) and the registry seek walk
908// (`WARATAH_REGISTRY_WALKS`) create one `Iter` per worker slice inside the
909// fixed storage worker pool (`worker_pool`, or a scoped-thread spawn before
910// that pool is installed), and never share an iterator across threads.
911unsafe impl Send for DbInner {}
912unsafe impl Sync for DbInner {}
913
914impl Drop for DbInner {
915    fn drop(&mut self) {
916        unsafe {
917            for cf_handle in &self.cf_handles {
918                rocksdb_column_family_handle_destroy(*cf_handle);
919            }
920            rocksdb_close(self.db);
921            for cf_option in &self.cf_options {
922                rocksdb_options_destroy(*cf_option);
923            }
924            rocksdb_readoptions_destroy(self.read_options);
925            rocksdb_writeoptions_destroy(self.write_options);
926            rocksdb_options_destroy(self.options);
927            rocksdb_block_based_options_destroy(self.block_based_table_options);
928            if !self.filtered_table_options.is_null() {
929                rocksdb_block_based_options_destroy(self.filtered_table_options);
930            }
931            rocksdb_cache_destroy(self.cache);
932        }
933    }
934}
935
936/// Opaque column-family handle borrowed from an open [`Db`].
937#[derive(Clone, Copy)]
938pub struct ColumnFamily(*mut rocksdb_column_family_handle_t);
939
940// SAFETY: CF handles are owned by a `Db` and are only valid while a `Db`
941// owning them is alive (the handle is destroyed with its `Db` in `Drop`).
942// The parallel storage walks (registry seek walk, domain scans) copy this
943// `Copy` handle onto worker-pool threads or scoped walkers; every carrier
944// that does so also owns a `Db` clone of the db the handle came from,
945// which keeps the handle alive for the walk's lifetime. The type system
946// cannot enforce that pairing — `ColumnFamily` is a raw pointer and a
947// bare copy sent anywhere without a live `Db` dangles — so a new
948// cross-thread carrier must hold a `Db` clone too. Handles are read-only
949// once created: RocksDB synchronizes CF-handle use internally.
950unsafe impl Send for ColumnFamily {}
951unsafe impl Sync for ColumnFamily {}
952
953impl Db {
954    /// Open with optional DB/CF options hooks (collectors, event listeners).
955    pub fn open_read_write_with_hooks(
956        path: &Path,
957        column_families: Vec<ColumnFamilyDefinition>,
958        hooks: RocksDbOptionsHooks<'_>,
959    ) -> Result<Self, StorageError> {
960        let c_path = path_to_cstring(path)?;
961        unsafe {
962            let options = rocksdb_options_create();
963            assert!(!options.is_null(), "rocksdb_options_create returned null");
964            rocksdb_options_set_create_if_missing(options, 1);
965            rocksdb_options_set_create_missing_column_families(options, 1);
966            rocksdb_options_set_write_buffer_size(options, hooks.tuning.write_buffer_bytes);
967            rocksdb_options_set_max_write_buffer_number(
968                options,
969                hooks.tuning.max_write_buffer_number,
970            );
971            if hooks.tuning.disable_auto_compactions {
972                rocksdb_options_set_disable_auto_compactions(options, 1);
973            }
974            // Compaction scans its input SSTs front-to-back; batch those reads
975            // so spinning drives stream instead of issuing per-block commands.
976            rocksdb_options_compaction_readahead_size(options, COMPACTION_READAHEAD_BYTES);
977            rocksdb_options_set_compression(options, rocksdb_lz4_compression.try_into().unwrap());
978            rocksdb_options_set_info_log_level(options, 2);
979            // Immutable ColumnFamilyOptions knob (advanced_options.h): set on
980            // the base Options here so every CF's options copy inherits it.
981            // It must be decided at open — see
982            // `memtable_batch_lookup_env_enabled` for the semantics and the
983            // skiplist-only requirement.
984            if memtable_batch_lookup_env_enabled() {
985                rocksdb_options_set_memtable_batch_lookup_optimization(options, 1);
986            }
987
988            let cache = rocksdb_cache_create_lru(hooks.tuning.block_cache_bytes);
989            assert!(!cache.is_null(), "rocksdb_cache_create_lru returned null");
990
991            let block_based_table_options = rocksdb_block_based_options_create();
992            assert!(
993                !block_based_table_options.is_null(),
994                "rocksdb_block_based_options_create returned null"
995            );
996            rocksdb_block_based_options_set_format_version(block_based_table_options, 8);
997            rocksdb_block_based_options_set_block_size(
998                block_based_table_options,
999                hooks.tuning.block_size_bytes,
1000            );
1001            rocksdb_block_based_options_set_block_cache(block_based_table_options, cache);
1002            // Bloom filters for point-lookup stores (the blob index). The
1003            // block-based options take ownership of the policy
1004            // (`filter_policy.reset`), so it lives and dies with the table
1005            // factory — no separate destroy on the DbInner drop path.
1006            if let Some(bits) = hooks.tuning.bloom_filter_bits_per_key {
1007                let policy = rocksdb_filterpolicy_create_bloom(f64::from(bits));
1008                assert!(
1009                    !policy.is_null(),
1010                    "rocksdb_filterpolicy_create_bloom returned null"
1011                );
1012                rocksdb_block_based_options_set_filter_policy(block_based_table_options, policy);
1013            }
1014            // Gate A (`WARATAH_PIN_INDEX=1` or tuning): cache SST index/filter
1015            // blocks and pin them there for every table of this DB. The
1016            // registry's binary-search index is unpartitioned, so the tier
1017            // that governs it is `unpartitioned_pinning` — the
1018            // `pin_top_level_index_and_filter` flag only covers *partitioned*
1019            // indexes, of which waratah has none. Read-path state only: no
1020            // data rewrite, applies from the next open.
1021            if hooks.tuning.pin_index_in_cache || pin_index_env_enabled() {
1022                rocksdb_block_based_options_set_cache_index_and_filter_blocks(
1023                    block_based_table_options,
1024                    1,
1025                );
1026                rocksdb_block_based_options_set_unpartitioned_pinning_tier(
1027                    block_based_table_options,
1028                    rocksdb_block_based_k_all_pinning_tier as i32,
1029                );
1030            }
1031            rocksdb_options_set_block_based_table_factory(options, block_based_table_options);
1032
1033            // Per-SST prefix bloom filters. The base table options above
1034            // are shared by EVERY column family through the options copy,
1035            // so a filter set there would also reach CFs that must not
1036            // carry one (opsg, catalog, geo, temporal). Instead: one
1037            // policy + one filtered table-options set, applied per CF at
1038            // copy time below. `set_block_based_table_factory`
1039            // dereferences and copies the options at set time, so a single
1040            // handle safely serves every filtered CF copy.
1041            let filter_wanted = column_families.iter().any(|cf| cf.prefix_filter);
1042            let filters_active = filter_wanted && sst_filter_env_enabled();
1043            let filter_cf_names: Vec<&'static str> = column_families
1044                .iter()
1045                .filter(|cf| cf.prefix_filter)
1046                .map(|cf| cf.name)
1047                .collect();
1048            // RocksDB statistics ride the same gate as the prefix filters
1049            // they were added to observe. A StatisticsImpl keeps its ticker
1050            // counters in a per-core CoreLocalArray, so every RecordTick
1051            // call site in RocksDB (block-cache hit/miss, every seek, next,
1052            // and get) pays a PhysicalCoreID() lookup plus an atomic add
1053            // into the current core's private copy of the array — a flat
1054            // per-operation tax on every read path. Measured 2026-11-10 on
1055            // the 10m-triple bellendena-sparql store: ~+1.7 ms per storage
1056            // scan RPC with statistics unconditionally enabled, which was
1057            // the whole of the q-distinct-observed-taxa and
1058            // q-broadcast-critical 0.4.0 hot regressions (bisected to the
1059            // commit that introduced the unconditional enable; removing
1060            // only this enable restored the prior floor). Ticker counts are
1061            // read through the options handle (see [`Db::ticker_count`]);
1062            // enabling here — after the gate resolves, but before the
1063            // per-CF options copies are made below — lets the copies share
1064            // this one statistics object. With statistics off the
1065            // ticker-count getter returns 0. The filter verification tests
1066            // force the gate (and therefore statistics) on via
1067            // `TEST_SST_FILTER_FORCE_ON`.
1068            if filters_active {
1069                rocksdb_options_enable_statistics(options);
1070            }
1071            let filtered_table_options: *mut rocksdb_block_based_table_options_t = if filters_active
1072            {
1073                // `create_bloom_full` (not the legacy `create_bloom`):
1074                // with format_version 8 both write full filters, but
1075                // the "full" variant selects the modern builtin bloom
1076                // layout (the legacy one keeps the pre-6.x hash
1077                // layout). Both record the compatibility name
1078                // "bloomfilter" in the table properties.
1079                let policy = rocksdb_filterpolicy_create_bloom_full(PREFIX_FILTER_BITS_PER_KEY);
1080                assert!(
1081                    !policy.is_null(),
1082                    "rocksdb_filterpolicy_create_bloom returned null"
1083                );
1084                let filtered = rocksdb_block_based_options_create();
1085                assert!(
1086                    !filtered.is_null(),
1087                    "rocksdb_block_based_options_create returned null"
1088                );
1089                rocksdb_block_based_options_set_format_version(filtered, 8);
1090                rocksdb_block_based_options_set_block_size(filtered, hooks.tuning.block_size_bytes);
1091                rocksdb_block_based_options_set_block_cache(filtered, cache);
1092                if hooks.tuning.pin_index_in_cache || pin_index_env_enabled() {
1093                    rocksdb_block_based_options_set_cache_index_and_filter_blocks(filtered, 1);
1094                    rocksdb_block_based_options_set_unpartitioned_pinning_tier(
1095                        filtered,
1096                        rocksdb_block_based_k_all_pinning_tier as i32,
1097                    );
1098                }
1099                // Ownership: the set call moves the raw `policy`
1100                // pointer into these options (`shared_ptr::reset`), so
1101                // it must never be destroyed separately; the options
1102                // handle (and every factory copy of it) owns it from
1103                // here on.
1104                rocksdb_block_based_options_set_filter_policy(filtered, policy);
1105                // Whole-key filtering is deliberately OFF: with a prefix
1106                // extractor set, RocksDB would add BOTH whole keys and
1107                // prefixes to the filter. Nothing ever point-Gets a full
1108                // versioned hexastore key (they carry `|| commit_ts`
1109                // suffixes), so whole-key entries would multiply filter
1110                // bytes by ~quads for zero possible hit. With it off the
1111                // filter holds one entry per distinct leading term.
1112                rocksdb_block_based_options_set_whole_key_filtering(filtered, 0);
1113                filtered
1114            } else {
1115                ptr::null_mut()
1116            };
1117
1118            let (column_family_names, c_column_family_names, cf_options) =
1119                Self::column_families_names_and_options(
1120                    column_families,
1121                    options,
1122                    &hooks,
1123                    filtered_table_options,
1124                );
1125            if let Some(configure_db) = hooks.configure_db {
1126                configure_db(options.cast());
1127            }
1128            let mut cf_handles: Vec<*mut rocksdb_column_family_handle_t> =
1129                vec![ptr::null_mut(); column_family_names.len()];
1130            let c_num_column_families = c_column_family_names.len().try_into().unwrap();
1131
1132            let db = ffi_result!(rocksdb_open_column_families(
1133                options,
1134                c_path.as_ptr(),
1135                c_num_column_families,
1136                c_column_family_names
1137                    .iter()
1138                    .map(|cf| cf.as_ptr())
1139                    .collect::<Vec<_>>()
1140                    .as_ptr(),
1141                cf_options.as_ptr().cast(),
1142                cf_handles.as_mut_ptr(),
1143            ))
1144            .inspect_err(|_| {
1145                for cf_option in &cf_options {
1146                    rocksdb_options_destroy(*cf_option);
1147                }
1148                rocksdb_options_destroy(options);
1149                rocksdb_block_based_options_destroy(block_based_table_options);
1150                if !filtered_table_options.is_null() {
1151                    rocksdb_block_based_options_destroy(filtered_table_options);
1152                }
1153                rocksdb_cache_destroy(cache);
1154            })?;
1155            assert!(!db.is_null(), "rocksdb_open_column_families returned null");
1156            for handle in &cf_handles {
1157                assert!(!handle.is_null(), "null column family handle");
1158            }
1159
1160            let read_options = rocksdb_readoptions_create();
1161            assert!(
1162                !read_options.is_null(),
1163                "rocksdb_readoptions_create returned null"
1164            );
1165
1166            let write_options = rocksdb_writeoptions_create();
1167            assert!(
1168                !write_options.is_null(),
1169                "rocksdb_writeoptions_create returned null"
1170            );
1171            if hooks.tuning.disable_wal {
1172                rocksdb_writeoptions_disable_WAL(write_options, 1);
1173            }
1174            if hooks.tuning.sync_writes {
1175                rocksdb_writeoptions_set_sync(write_options, 1);
1176            }
1177
1178            Ok(Self {
1179                inner: Arc::new(DbInner {
1180                    db,
1181                    options,
1182                    read_options,
1183                    write_options,
1184                    block_based_table_options,
1185                    filtered_table_options,
1186                    cache,
1187                    iterator_readahead_bytes: hooks.tuning.iterator_readahead_bytes,
1188                    scan_async_io: hooks.tuning.scan_async_io || scan_async_io_env_enabled(),
1189                    column_family_names,
1190                    cf_handles,
1191                    cf_options,
1192                }),
1193            }
1194            // Filter blocks are cached AND pinned (pinning gate is on by
1195            // default), so raise the budget to keep the pinned filter
1196            // volume from evicting the data-block working set the warm
1197            // pass fills. Capacity is adjustable at runtime; the estimate
1198            // uses per-CF `estimate-num-keys`, an over-count of distinct
1199            // leading terms (see `PREFIX_FILTER_BUDGET_FUDGE`).
1200            .with_filter_budget(filters_active, &filter_cf_names))
1201        }
1202    }
1203
1204    /// Raise the block-cache capacity when prefix filters are active, to
1205    /// `max(current, 2 × estimated filter bytes)` — never lower it.
1206    ///
1207    /// Called at the end of [`Db::open_read_write_with_hooks`]; logs a
1208    /// storage-trace line when it raises the budget.
1209    fn with_filter_budget(self, filters_active: bool, filter_cf_names: &[&'static str]) -> Self {
1210        if !filters_active || filter_cf_names.is_empty() {
1211            return self;
1212        }
1213        let estimated: u64 = filter_cf_names
1214            .iter()
1215            .filter_map(|name| self.column_family(name).ok())
1216            .map(|cf| {
1217                self.int_property_cf(&cf, "rocksdb.estimate-num-keys")
1218                    .unwrap_or(0)
1219            })
1220            .map(|keys| {
1221                ((keys as f64) * PREFIX_FILTER_BITS_PER_KEY / 8.0 * PREFIX_FILTER_BUDGET_FUDGE)
1222                    as u64
1223            })
1224            .sum();
1225        if estimated == 0 {
1226            return self;
1227        }
1228        let target = (2 * estimated).max(self.block_cache_capacity() as u64) as usize;
1229        if target > self.block_cache_capacity() {
1230            eprintln!(
1231                "storage-trace sst filter: block cache {} KiB -> {} KiB \
1232                 (estimated filter bytes ~{} KiB, pinned with the index gate)",
1233                self.block_cache_capacity() / 1024,
1234                target / 1024,
1235                estimated / 1024
1236            );
1237            // SAFETY: `cache` is a valid handle created at open and freed
1238            // only in `DbInner::drop`; `set_capacity` is noexcept.
1239            unsafe { rocksdb_cache_set_capacity(self.inner.cache.cast(), target) };
1240        }
1241        self
1242    }
1243
1244    fn column_families_names_and_options(
1245        mut column_families: Vec<ColumnFamilyDefinition>,
1246        base_options: *mut rocksdb_options_t,
1247        hooks: &RocksDbOptionsHooks<'_>,
1248        filtered_table_options: *mut rocksdb_block_based_table_options_t,
1249    ) -> (Vec<&'static str>, Vec<CString>, Vec<*mut rocksdb_options_t>) {
1250        if !column_families.iter().any(|c| c.name == "default") {
1251            column_families.push(ColumnFamilyDefinition {
1252                name: "default",
1253                min_prefix_size: 0,
1254                prefix_filter: false,
1255                permutation: None,
1256            });
1257        }
1258        let column_family_names = column_families.iter().map(|c| c.name).collect::<Vec<_>>();
1259        let c_column_family_names = column_family_names
1260            .iter()
1261            .map(|name| CString::new(*name).unwrap())
1262            .collect();
1263
1264        let cf_options = column_families
1265            .into_iter()
1266            .map(|cf| unsafe {
1267                let options = rocksdb_options_create_copy(base_options);
1268                if cf.min_prefix_size > 0 {
1269                    rocksdb_options_set_prefix_extractor(
1270                        options,
1271                        rocksdb_slicetransform_create_fixed_prefix(cf.min_prefix_size),
1272                    );
1273                }
1274                // Swap the shared (filter-less) table factory for the
1275                // filtered one on exactly the CFs that asked for it. The
1276                // set call copies the table options, so all these CF
1277                // copies share the one `filtered_table_options` snapshot.
1278                if cf.prefix_filter && !filtered_table_options.is_null() {
1279                    rocksdb_options_set_block_based_table_factory(options, filtered_table_options);
1280                }
1281                if cf.name == NAMED_GRAPHS_CATALOG_CF {
1282                    if let Some(configure_catalog_cf) = hooks.configure_catalog_cf {
1283                        configure_catalog_cf(options.cast());
1284                    }
1285                } else if cf.name == crate::encode::TEMPORAL_INDEX_CF {
1286                    if let Some(configure_temporal_cf) = hooks.configure_temporal_cf {
1287                        configure_temporal_cf(options.cast());
1288                    }
1289                } else if cf.name == crate::encode::GEO_INDEX_CF {
1290                    if let Some(configure_geo_cf) = hooks.configure_geo_cf {
1291                        configure_geo_cf(options.cast());
1292                    }
1293                } else if let (Some(perm), Some(configure_cf)) =
1294                    (cf.permutation, hooks.configure_cf)
1295                {
1296                    configure_cf(perm, options.cast());
1297                }
1298                options
1299            })
1300            .collect::<Vec<_>>();
1301        (column_family_names, c_column_family_names, cf_options)
1302    }
1303
1304    /// Look up a column family by name.
1305    pub fn column_family(&self, name: &'static str) -> Result<ColumnFamily, StorageError> {
1306        for (cf, cf_handle) in self
1307            .inner
1308            .column_family_names
1309            .iter()
1310            .zip(&self.inner.cf_handles)
1311        {
1312            if *cf == name {
1313                return Ok(ColumnFamily(*cf_handle));
1314            }
1315        }
1316        Err(StorageError::Backend(format!(
1317            "missing column family `{name}`"
1318        )))
1319    }
1320
1321    /// Get `key` from `column_family`, or `None` if absent.
1322    pub fn get(
1323        &self,
1324        column_family: &ColumnFamily,
1325        key: &[u8],
1326    ) -> Result<Option<Vec<u8>>, StorageError> {
1327        unsafe {
1328            let mut vlen = 0usize;
1329            let val = ffi_result!(rocksdb_get_cf(
1330                self.inner.db,
1331                self.inner.read_options,
1332                column_family.0,
1333                key.as_ptr().cast(),
1334                key.len(),
1335                &raw mut vlen,
1336            ))?;
1337            if val.is_null() {
1338                return Ok(None);
1339            }
1340            let bytes = slice::from_raw_parts(val.cast::<u8>(), vlen).to_vec();
1341            rocksdb_free(val.cast());
1342            Ok(Some(bytes))
1343        }
1344    }
1345
1346    /// Point-get many keys in `column_family` via RocksDB's batched pinned
1347    /// `MultiGet` (`rocksdb_batched_multi_get_pinned_cf`).
1348    ///
1349    /// Results are positional (`None` is not-found). Values stay pinned in
1350    /// RocksDB (block cache where possible) until the batch is destroyed,
1351    /// so there is no per-value malloc/copy/free round trip — each found
1352    /// value is copied once, straight into the result `Vec`. All C entry
1353    /// points to `DB::MultiGet` share the same read path; this wrapper's
1354    /// win over per-value-materializing wrappers is API overhead and
1355    /// allocation count only.
1356    ///
1357    /// `sorted_input` must be `true` only when `keys` is ascending under the
1358    /// column family's comparator: it skips RocksDB's internal copy and sort
1359    /// of the key array. Error messages are borrowed from the batch and
1360    /// converted without a free — unlike [`error_from_ptr`], which owns its
1361    /// input.
1362    ///
1363    /// Pin cost scales with *blocks touched*, not value bytes: the batch
1364    /// holds a pin on every distinct data block any key touches until
1365    /// destroy, and pinned blocks are not evictable. On the registry's
1366    /// 32 KiB blocks a cold multi-thousand-key batch can pin on the order
1367    /// of 100 MiB against the 256 MiB registry block cache — measure cold
1368    /// resolve before enabling `WARATAH_RESOLVE_MULTIGET` in a serving
1369    /// process.
1370    pub(crate) fn multi_get_pinned(
1371        &self,
1372        column_family: &ColumnFamily,
1373        keys: &[&[u8]],
1374        sorted_input: bool,
1375    ) -> Result<Vec<Option<Vec<u8>>>, StorageError> {
1376        if keys.is_empty() {
1377            return Ok(Vec::new());
1378        }
1379        let n = keys.len();
1380        let slices: Vec<rocksdb_slice_t> = keys
1381            .iter()
1382            .map(|key| rocksdb_slice_t {
1383                data: key.as_ptr().cast(),
1384                size: key.len(),
1385            })
1386            .collect();
1387
1388        // SAFETY: `db`, `read_options`, and the column family handle live as
1389        // long as `&self`; the key slices borrow `keys`, which outlives the
1390        // call. The returned batch owns every value and error message until
1391        // `rocksdb_pinnable_multi_get_destroy` — `PinnableMultiGetGuard`
1392        // releases it on every exit path below, including panics.
1393        let batch = PinnableMultiGetGuard(unsafe {
1394            rocksdb_batched_multi_get_pinned_cf(
1395                self.inner.db,
1396                self.inner.read_options,
1397                column_family.0,
1398                n,
1399                slices.as_ptr(),
1400                sorted_input as std::os::raw::c_uchar,
1401            )
1402        });
1403        if batch.0.is_null() {
1404            return Err(StorageError::Corrupt(
1405                "pinned multi-get returned a null result batch".to_owned(),
1406            ));
1407        }
1408        let count = unsafe { rocksdb_pinnable_multi_get_count(batch.0) };
1409        if count != n {
1410            return Err(StorageError::Corrupt(format!(
1411                "pinned multi-get returned {count} results for {n} keys"
1412            )));
1413        }
1414
1415        let mut out: Vec<Option<Vec<u8>>> = Vec::with_capacity(n);
1416        let mut first_err: Option<StorageError> = None;
1417        for i in 0..n {
1418            let mut value: *const std::os::raw::c_char = ptr::null();
1419            let mut value_size: usize = 0;
1420            let mut error: *const std::os::raw::c_char = ptr::null();
1421            let mut error_size: usize = 0;
1422            let state = unsafe {
1423                rocksdb_pinnable_multi_get_result(
1424                    batch.0,
1425                    i,
1426                    &mut value,
1427                    &mut value_size,
1428                    &mut error,
1429                    &mut error_size,
1430                )
1431            };
1432            // The C accessor returns `int`; the generated state constants are
1433            // unsigned — normalize once here.
1434            match state as u32 {
1435                PINNABLE_FOUND => {
1436                    debug_assert!(
1437                        !value.is_null(),
1438                        "pinned multi-get found-state with null value pointer"
1439                    );
1440                    let bytes =
1441                        unsafe { slice::from_raw_parts(value.cast::<u8>(), value_size).to_vec() };
1442                    out.push(Some(bytes));
1443                }
1444                PINNABLE_NOT_FOUND => out.push(None),
1445                PINNABLE_ERROR => {
1446                    // Borrowed bytes: valid until the guard drops, never freed.
1447                    debug_assert!(
1448                        !error.is_null(),
1449                        "pinned multi-get error-state with null error pointer"
1450                    );
1451                    let msg = unsafe { CStr::from_ptr(error).to_string_lossy().into_owned() };
1452                    if first_err.is_none() {
1453                        first_err = Some(StorageError::Backend(msg));
1454                    }
1455                    out.push(None);
1456                }
1457                PINNABLE_OUT_OF_BOUNDS => {
1458                    // Unreachable: the accessor is indexed below `count`,
1459                    // which asserts equal to `n`. Treat as corruption rather
1460                    // than panic so the batch still reports a first error.
1461                    if first_err.is_none() {
1462                        first_err = Some(StorageError::Corrupt(format!(
1463                            "pinned multi-get returned out-of-range state at index {i}"
1464                        )));
1465                    }
1466                    out.push(None);
1467                }
1468                other => {
1469                    if first_err.is_none() {
1470                        first_err = Some(StorageError::Corrupt(format!(
1471                            "pinned multi-get returned unknown result state {other} at index {i}"
1472                        )));
1473                    }
1474                    out.push(None);
1475                }
1476            }
1477        }
1478        if let Some(err) = first_err {
1479            return Err(err);
1480        }
1481        Ok(out)
1482    }
1483
1484    /// Put `key` → `value` in `column_family`.
1485    pub fn insert(
1486        &self,
1487        column_family: &ColumnFamily,
1488        key: &[u8],
1489        value: &[u8],
1490    ) -> Result<(), StorageError> {
1491        unsafe {
1492            ffi_result!(rocksdb_put_cf(
1493                self.inner.db,
1494                self.inner.write_options,
1495                column_family.0,
1496                key.as_ptr().cast(),
1497                key.len(),
1498                value.as_ptr().cast(),
1499                value.len(),
1500            ))?;
1501        }
1502        Ok(())
1503    }
1504
1505    /// Allocate an empty RocksDB `WriteBatch` bound to this DB's write options.
1506    pub fn write_batch(&self) -> WriteBatch {
1507        let batch = unsafe { rocksdb_writebatch_create() };
1508        assert!(!batch.is_null(), "rocksdb_writebatch_create returned null");
1509        WriteBatch {
1510            db: self.clone(),
1511            batch,
1512        }
1513    }
1514
1515    /// Flush MemTables for `column_families` to SST files (waits for completion).
1516    pub fn flush_cfs(&self, column_families: &[&ColumnFamily]) -> Result<(), StorageError> {
1517        if column_families.is_empty() {
1518            return Ok(());
1519        }
1520        unsafe {
1521            let options = rocksdb_flushoptions_create();
1522            assert!(
1523                !options.is_null(),
1524                "rocksdb_flushoptions_create returned null"
1525            );
1526            rocksdb_flushoptions_set_wait(options, 1);
1527            let mut handles: Vec<*mut rocksdb_column_family_handle_t> =
1528                column_families.iter().map(|cf| cf.0).collect();
1529            let result = ffi_result!(rocksdb_flush_cfs(
1530                self.inner.db,
1531                options,
1532                handles.as_mut_ptr(),
1533                handles.len() as std::os::raw::c_int,
1534            ));
1535            rocksdb_flushoptions_destroy(options);
1536            result?;
1537        }
1538        Ok(())
1539    }
1540
1541    /// Bulk-ingest pre-built sorted SST files into `column_family`.
1542    ///
1543    /// Files may overlap each other's key ranges: RocksDB assigns a global
1544    /// sequence number to overlapping files in list order (`allow_global_seqno`),
1545    /// so within one call the last file in the list wins on duplicate keys.
1546    /// `move_files` hard-links the files into the DB (requires the same
1547    /// filesystem); otherwise they stay in place and are copied.
1548    pub fn ingest_external_file_cf(
1549        &self,
1550        column_family: &ColumnFamily,
1551        files: &[PathBuf],
1552        move_files: bool,
1553    ) -> Result<(), StorageError> {
1554        if files.is_empty() {
1555            return Ok(());
1556        }
1557        let c_files = files
1558            .iter()
1559            .map(|path| path_to_cstring(path))
1560            .collect::<Result<Vec<_>, _>>()?;
1561        let file_ptrs = c_files.iter().map(|f| f.as_ptr()).collect::<Vec<_>>();
1562        unsafe {
1563            let options = rocksdb_ingestexternalfileoptions_create();
1564            assert!(
1565                !options.is_null(),
1566                "rocksdb_ingestexternalfileoptions_create returned null"
1567            );
1568            rocksdb_ingestexternalfileoptions_set_move_files(options, u8::from(move_files));
1569            // No snapshot in the bulk-ingest path needs to see (or not see)
1570            // the ingested files; snapshot_consistency would only force a
1571            // higher global seqno per batch.
1572            rocksdb_ingestexternalfileoptions_set_snapshot_consistency(options, 0);
1573            rocksdb_ingestexternalfileoptions_set_allow_global_seqno(options, 1);
1574            let result = ffi_result!(rocksdb_ingest_external_file_cf(
1575                self.inner.db,
1576                column_family.0,
1577                file_ptrs.as_ptr(),
1578                file_ptrs.len(),
1579                options,
1580            ));
1581            rocksdb_ingestexternalfileoptions_destroy(options);
1582            result?;
1583        }
1584        Ok(())
1585    }
1586
1587    /// Compact the full key range of `column_family` (tests / explicit rewrite).
1588    ///
1589    /// Uses `BottommostLevelCompaction::kForce` so a tiny flushed L0 file is
1590    /// rewritten rather than trivially moved, which is required for table-
1591    /// properties collectors (`waratah.stats`) to run on compaction output.
1592    pub fn compact_cf(&self, column_family: &ColumnFamily) {
1593        self.compact_cf_bottommost(column_family, BottommostLevelCompaction::Force);
1594    }
1595
1596    /// Compact the full key range of `column_family` with an explicit
1597    /// bottommost-level policy.
1598    ///
1599    /// [`BottommostLevelCompaction::Skip`] leaves a trivial move in place, so
1600    /// `waratah.stats` written at flush time stays on that file. The L0 merge
1601    /// still builds new SSTs and runs whatever collectors are attached.
1602    pub fn compact_cf_bottommost(
1603        &self,
1604        column_family: &ColumnFamily,
1605        bottommost: BottommostLevelCompaction,
1606    ) {
1607        unsafe {
1608            let options = rocksdb_compactoptions_create();
1609            assert!(
1610                !options.is_null(),
1611                "rocksdb_compactoptions_create returned null"
1612            );
1613            rocksdb_compactoptions_set_bottommost_level_compaction(options, bottommost as u8);
1614            rocksdb_compact_range_cf_opt(
1615                self.inner.db,
1616                column_family.0,
1617                options,
1618                ptr::null(),
1619                0,
1620                ptr::null(),
1621                0,
1622            );
1623            rocksdb_compactoptions_destroy(options);
1624        }
1625    }
1626
1627    /// `user_collected_properties` values for `key` on every live SST in `column_family`.
1628    pub fn user_property_blobs(
1629        &self,
1630        column_family: &ColumnFamily,
1631        key: &[u8],
1632    ) -> Result<Vec<Vec<u8>>, StorageError> {
1633        unsafe {
1634            let collection = ffi_result!(oxrocksdb_get_properties_of_all_tables_cf(
1635                self.inner.db,
1636                column_family.0,
1637            ))?;
1638            if collection.is_null() {
1639                return Ok(Vec::new());
1640            }
1641            let mut out = Vec::new();
1642            let it = oxrocksdb_table_properties_collection_iter_create(collection);
1643            if !it.is_null() {
1644                while oxrocksdb_table_properties_collection_iter_valid(it) != 0 {
1645                    let table_props = oxrocksdb_table_properties_collection_iter_value(it);
1646                    if !table_props.is_null() {
1647                        let user_props =
1648                            oxrocksdb_table_properties_get_user_properties(table_props);
1649                        if !user_props.is_null() {
1650                            let mut vlen = 0usize;
1651                            let val = oxrocksdb_user_collected_properties_get(
1652                                user_props,
1653                                key.as_ptr().cast(),
1654                                key.len(),
1655                                &raw mut vlen,
1656                            );
1657                            if !val.is_null() && vlen > 0 {
1658                                out.push(slice::from_raw_parts(val.cast::<u8>(), vlen).to_vec());
1659                            }
1660                        }
1661                    }
1662                    oxrocksdb_table_properties_collection_iter_next(it);
1663                }
1664                oxrocksdb_table_properties_collection_iter_destroy(it);
1665            }
1666            oxrocksdb_table_properties_collection_destroy(collection);
1667            Ok(out)
1668        }
1669    }
1670
1671    /// RocksDB `GetProperty` string, or `None` when the name is unknown.
1672    pub fn property_value(&self, name: &str) -> Option<String> {
1673        let cname = CString::new(name).ok()?;
1674        unsafe {
1675            let ptr = rocksdb_property_value(self.inner.db, cname.as_ptr());
1676            if ptr.is_null() {
1677                return None;
1678            }
1679            let value = CStr::from_ptr(ptr).to_string_lossy().into_owned();
1680            rocksdb_free(ptr.cast());
1681            Some(value)
1682        }
1683    }
1684
1685    /// Parse [`Self::property_value`] as `u64`.
1686    pub fn int_property(&self, name: &str) -> Option<u64> {
1687        self.property_value(name)?.parse().ok()
1688    }
1689
1690    /// RocksDB `GetProperty` on `column_family`, or `None` when unknown.
1691    pub fn property_value_cf(&self, column_family: &ColumnFamily, name: &str) -> Option<String> {
1692        let cname = CString::new(name).ok()?;
1693        unsafe {
1694            let ptr = rocksdb_property_value_cf(self.inner.db, column_family.0, cname.as_ptr());
1695            if ptr.is_null() {
1696                return None;
1697            }
1698            let value = CStr::from_ptr(ptr).to_string_lossy().into_owned();
1699            rocksdb_free(ptr.cast());
1700            Some(value)
1701        }
1702    }
1703
1704    /// `DB::GetIntProperty` on `column_family` (`rocksdb_property_int_cf`).
1705    pub fn int_property_cf(&self, column_family: &ColumnFamily, name: &str) -> Option<u64> {
1706        let cname = CString::new(name).ok()?;
1707        let mut out = 0u64;
1708        unsafe {
1709            let rc =
1710                rocksdb_property_int_cf(self.inner.db, column_family.0, cname.as_ptr(), &mut out);
1711            (rc == 0).then_some(out)
1712        }
1713    }
1714
1715    /// Bytes currently held by this DB's block cache, across all column
1716    /// families. Includes pinned index blocks when index pinning is on
1717    /// (`WARATAH_PIN_INDEX` or [`RocksDbTuning::pin_index_in_cache`]).
1718    ///
1719    /// Takes the cache's internal shard mutex — cheap enough for periodic
1720    /// probing, not per-entry.
1721    pub fn block_cache_usage(&self) -> usize {
1722        // SAFETY: `cache` is a valid handle created at open and freed only in
1723        // `DbInner::drop`; `get_usage` is `noexcept` in the C API.
1724        unsafe { rocksdb_cache_get_usage(self.inner.cache.cast()) }
1725    }
1726
1727    /// Configured block-cache capacity (the LRU bound, not current usage).
1728    pub fn block_cache_capacity(&self) -> usize {
1729        // SAFETY: same handle lifetime contract as `block_cache_usage`.
1730        unsafe { rocksdb_cache_get_capacity(self.inner.cache.cast()) }
1731    }
1732
1733    /// Sum per-CF size/key properties; compaction/flush counters stay DB-wide.
1734    ///
1735    /// `rocksdb_property_value` without a CF handle reports the empty `default`
1736    /// family. Hexastore and registry data live on named CFs, so callers pass
1737    /// those handles and this sums `estimate-*` / SST / memtable sizes.
1738    pub fn lsm_metrics_for_cfs(&self, column_families: &[&ColumnFamily]) -> crate::LsmMetrics {
1739        crate::LsmMetrics {
1740            estimate_live_data_bytes: sum_cf_int(
1741                self,
1742                column_families,
1743                "rocksdb.estimate-live-data-size",
1744            ),
1745            estimate_num_keys: sum_cf_int(self, column_families, "rocksdb.estimate-num-keys"),
1746            total_sst_bytes: sum_cf_int(self, column_families, "rocksdb.total-sst-files-size"),
1747            memtable_bytes: sum_cf_int(self, column_families, "rocksdb.cur-size-all-mem-tables"),
1748            num_running_compactions: self.int_property("rocksdb.num-running-compactions"),
1749            num_running_flushes: self.int_property("rocksdb.num-running-flushes"),
1750            block_cache_capacity_bytes: Some(self.block_cache_capacity() as u64),
1751            block_cache_usage_bytes: Some(self.block_cache_usage() as u64),
1752        }
1753    }
1754
1755    /// Process-wide block cache bytes: `(capacity, charged usage)`. One cheap
1756    /// probe (shard-mutex counter read, no I/O) covering every CF — the same
1757    /// counters the warm pass targets. `None` on the memory backend.
1758    pub fn block_cache_bytes(&self) -> Option<(u64, u64)> {
1759        Some((
1760            self.block_cache_capacity() as u64,
1761            self.block_cache_usage() as u64,
1762        ))
1763    }
1764
1765    /// Current value of one RocksDB statistics ticker on this DB (see the
1766    /// `TICKER_*` constants). Statistics are enabled only when the
1767    /// per-SST prefix-filter gate is on (see [`sst_filter_env_enabled`]),
1768    /// so the counter is live only for DBs opened under that gate and
1769    /// reads 0 otherwise; it covers this DB only.
1770    ///
1771    /// Test/ops-support surface today: the filter tests read bloom
1772    /// tickers through it, and the before/after filter measurements will
1773    /// read the same counters.
1774    #[cfg(test)]
1775    pub fn ticker_count(&self, ticker: u32) -> u64 {
1776        // SAFETY: `options` is a valid handle created at open and freed
1777        // only in `DbInner::drop`; the getter is `noexcept` and returns 0
1778        // for an unknown ticker id.
1779        unsafe { rocksdb_options_statistics_get_ticker_count(self.inner.options, ticker) }
1780    }
1781
1782    /// Distinct `filter_policy_name` values across every live SST of
1783    /// `column_family`, one entry per table (empty string when a table
1784    /// has no filter block).
1785    ///
1786    /// Build-side evidence that the prefix-filter plumbing is (or is not)
1787    /// writing filter blocks: the filter policy's compatibility name
1788    /// (`"bloomfilter"` for the builtin bloom this wrapper configures) on
1789    /// SSTs flushed/compacted under an active [`sst_filter_env_enabled`]
1790    /// gate, `""` on CFs without a policy and on SSTs written before the
1791    /// gate was enabled (they gain a name only when rewritten).
1792    ///
1793    /// Test/ops-support surface today (the filter build-side test reads
1794    /// it); it is the natural probe for a future storage-health surface.
1795    #[cfg(test)]
1796    pub fn table_filter_policy_names(
1797        &self,
1798        column_family: &ColumnFamily,
1799    ) -> Result<Vec<String>, StorageError> {
1800        unsafe {
1801            let collection = ffi_result!(oxrocksdb_get_properties_of_all_tables_cf(
1802                self.inner.db,
1803                column_family.0,
1804            ))?;
1805            if collection.is_null() {
1806                return Ok(Vec::new());
1807            }
1808            let mut out = Vec::new();
1809            let it = oxrocksdb_table_properties_collection_iter_create(collection);
1810            if !it.is_null() {
1811                while oxrocksdb_table_properties_collection_iter_valid(it) != 0 {
1812                    let table_props = oxrocksdb_table_properties_collection_iter_value(it);
1813                    if !table_props.is_null() {
1814                        let mut len = 0usize;
1815                        // SAFETY: the getter returns a pointer into the
1816                        // properties object (no transfer, no free) with
1817                        // its length in `len`; `table_props` stays alive
1818                        // until the iterator advances or is destroyed.
1819                        let name = oxrocksdb_table_properties_filter_policy_name(
1820                            table_props,
1821                            &raw mut len,
1822                        );
1823                        if !name.is_null() {
1824                            out.push(
1825                                String::from_utf8_lossy(slice::from_raw_parts(
1826                                    name.cast::<u8>(),
1827                                    len,
1828                                ))
1829                                .into_owned(),
1830                            );
1831                        }
1832                    }
1833                    oxrocksdb_table_properties_collection_iter_next(it);
1834                }
1835                oxrocksdb_table_properties_collection_iter_destroy(it);
1836            }
1837            oxrocksdb_table_properties_collection_destroy(collection);
1838            Ok(out)
1839        }
1840    }
1841
1842    /// Prefix scan over `column_family`.
1843    pub fn scan_prefix<'a>(&'a self, column_family: &ColumnFamily, prefix: &[u8]) -> Iter<'a> {
1844        self.scan_prefix_from(column_family, prefix, prefix)
1845    }
1846
1847    /// Prefix scan with `total_order_seek` read options (unbounded start:
1848    /// positions at the first key of the prefix range).
1849    ///
1850    /// The range ≡ seek-prefix rule for filter CFs: a `Seek` consults the
1851    /// seek target's prefix, and "absent here" marks the SST exhausted
1852    /// from that seek onward. The pruning is transient across seeks (each
1853    /// seek consults fresh) but permanent within one seek's walk, so the
1854    /// soundness condition is: every key the walk still needs must be
1855    /// reachable by seeks whose targets are present in the SSTs holding
1856    /// them. Two shapes violate it and MUST use this constructor:
1857    /// (1) seeks whose key's 17-byte prefix belongs to no key at all —
1858    /// `byte_successor` of a bare encoded term (the axis-head skip,
1859    /// resume, and allow-list walks; every consult target is malformed
1860    /// everywhere, so the pruning never lifts); and (2) iterators that
1861    /// rely on one seek's positioning to reach keys past that seek's
1862    /// prefix — sliced multi-constraint walks (one seek at slice start,
1863    /// `Next()` across a range spanning many prefixes). A walk that
1864    /// re-seeks with a real target per range (e.g.
1865    /// `max_commit_ts_under_prefixes`) gets a fresh consult each time and
1866    /// is sound without the flag — it still carries it as hardening
1867    /// (one-shot upgrade op; contract is "must observe every matching
1868    /// key"). A confined per-constraint walk — range ≡ prefix for its
1869    /// whole life — must NOT use it: the flag would disarm its measured
1870    /// filter benefit.
1871    pub fn scan_prefix_total_order<'a>(
1872        &'a self,
1873        column_family: &ColumnFamily,
1874        prefix: &[u8],
1875    ) -> Iter<'a> {
1876        self.iter_between_opts(column_family, prefix, prefix, true)
1877    }
1878
1879    /// Prefix scan seeking at `start` (inclusive), still bounded by `prefix`.
1880    ///
1881    /// `start` should be `>= prefix`. Keys that sort before `prefix` are not
1882    /// visited; the iterate upper bound still ends the prefix range.
1883    pub fn scan_prefix_from<'a>(
1884        &'a self,
1885        column_family: &ColumnFamily,
1886        prefix: &[u8],
1887        start: &[u8],
1888    ) -> Iter<'a> {
1889        // A start below the prefix would re-visit nothing (the prefix range
1890        // begins at `prefix`), so clamp it up.
1891        let seek = if start > prefix { start } else { prefix };
1892        self.iter_between(column_family, prefix, seek)
1893    }
1894
1895    /// [`Self::scan_prefix_from`] with `total_order_seek` read options.
1896    ///
1897    /// For range walks whose iterator spans MANY leading terms while their
1898    /// seeks name only the first term visited — the pattern-count walkers:
1899    /// a full-axis slice spans ~1/8 of the column family, a hint slice
1900    /// spans several whole classes, but the slice's start/probe seeks name
1901    /// only the first term. Per-SST prefix pruning is correct only when
1902    /// the iterator's range equals the probed prefix (see
1903    /// [`Self::iter_between_opts`]); these walks must disarm the consult
1904    /// even though every seek key's 17-byte prefix is a real, present
1905    /// term, because the slice's range continues past it.
1906    pub fn scan_prefix_from_total_order<'a>(
1907        &'a self,
1908        column_family: &ColumnFamily,
1909        prefix: &[u8],
1910        start: &[u8],
1911    ) -> Iter<'a> {
1912        // A start below the prefix would re-visit nothing (the prefix range
1913        // begins at `prefix`), so clamp it up.
1914        let seek = if start > prefix { start } else { prefix };
1915        self.iter_between_opts(column_family, prefix, seek, true)
1916    }
1917
1918    /// Shared iterator constructor: upper bound = `byte_successor(bound_prefix)`,
1919    /// initial position = `seek`.
1920    fn iter_between<'a>(
1921        &'a self,
1922        column_family: &ColumnFamily,
1923        bound_prefix: &[u8],
1924        seek: &[u8],
1925    ) -> Iter<'a> {
1926        self.iter_between_opts(column_family, bound_prefix, seek, false)
1927    }
1928
1929    /// [`Self::iter_between`] with `total_order_seek` read options.
1930    ///
1931    /// Required by the axis-head walks: they skip past a head term with
1932    /// `byte_successor(bare term)`, whose 17-byte prefix belongs to no key.
1933    /// Under armed per-SST prefix filters (`WARATAH_SST_FILTER`), a seek in
1934    /// prefix mode consults the bloom, gets a confident "prefix absent",
1935    /// and marks the SST exhausted — truncating the walk at the first head
1936    /// (recorded on yago: `SELECT DISTINCT ?c` returned 2 of 10,097 rows).
1937    /// `total_order_seek` makes RocksDB skip the bloom consult for this
1938    /// iterator entirely, so the walk is the complete total-order scan in
1939    /// every configuration. With filters off the flag is a no-op (no
1940    /// filter blocks are loaded, and the store uses the default binary
1941    /// search index and no memtable prefix bloom, the flag's only other
1942    /// consumers).
1943    fn iter_between_opts<'a>(
1944        &'a self,
1945        column_family: &ColumnFamily,
1946        bound_prefix: &[u8],
1947        seek: &[u8],
1948        total_order_seek: bool,
1949    ) -> Iter<'a> {
1950        let upper_bound = {
1951            let mut bound = bound_prefix.to_vec();
1952            let mut found = false;
1953            for c in bound.iter_mut().rev() {
1954                if *c < u8::MAX {
1955                    *c += 1;
1956                    found = true;
1957                    break;
1958                }
1959            }
1960            found.then_some(bound)
1961        };
1962
1963        unsafe {
1964            let options = oxrocksdb_readoptions_create_copy(self.inner.read_options);
1965            assert!(
1966                !options.is_null(),
1967                "oxrocksdb_readoptions_create_copy returned null"
1968            );
1969            if total_order_seek {
1970                rocksdb_readoptions_set_total_order_seek(options, 1);
1971            }
1972            // `0` keeps the engine default (implicit auto-readahead, which
1973            // only engages for upper-bounded iterators like hexastore scans);
1974            // stores that opt in — the registry's unbounded walk — set a
1975            // fixed window, since auto never engages without a bound. Point
1976            // `get`s use the shared template and stay unaffected either way.
1977            rocksdb_readoptions_set_readahead_size(options, self.inner.iterator_readahead_bytes);
1978            // Gate (`WARATAH_SCAN_ASYNC_IO=1` / tuning): submit this
1979            // iterator's block reads via io_uring so sequential prefetch
1980            // overlaps consumption. Engages for forward scans; the resolve
1981            // path's random seek pattern is unaffected either way.
1982            if self.inner.scan_async_io {
1983                rocksdb_readoptions_set_async_io(options, 1);
1984            }
1985            if let Some(upper_bound) = &upper_bound {
1986                rocksdb_readoptions_set_iterate_upper_bound(
1987                    options,
1988                    upper_bound.as_ptr().cast(),
1989                    upper_bound.len(),
1990                );
1991            }
1992            let iter = rocksdb_create_iterator_cf(self.inner.db, options, column_family.0);
1993            assert!(!iter.is_null(), "rocksdb_create_iterator_cf returned null");
1994            if seek.is_empty() {
1995                rocksdb_iter_seek_to_first(iter);
1996            } else {
1997                rocksdb_iter_seek(iter, seek.as_ptr().cast(), seek.len());
1998            }
1999            let is_currently_valid = rocksdb_iter_valid(iter) != 0;
2000            Iter {
2001                inner: iter,
2002                options,
2003                _upper_bound: upper_bound,
2004                _db: self,
2005                is_currently_valid,
2006            }
2007        }
2008    }
2009}
2010
2011/// Prefix iterator over a column family.
2012pub struct Iter<'a> {
2013    inner: *mut rocksdb_iterator_t,
2014    is_currently_valid: bool,
2015    _upper_bound: Option<Vec<u8>>,
2016    _db: &'a Db,
2017    options: *mut rocksdb_readoptions_t,
2018}
2019
2020impl Drop for Iter<'_> {
2021    fn drop(&mut self) {
2022        unsafe {
2023            rocksdb_iter_destroy(self.inner);
2024            rocksdb_readoptions_destroy(self.options);
2025        }
2026    }
2027}
2028
2029// SAFETY: an iterator is owned by one thread; `seek`/`next` are never called
2030// concurrently on the same `Iter`. Workers of the parallel domain walks each
2031// create and drive their own iterator.
2032unsafe impl Send for Iter<'_> {}
2033
2034impl Iter<'_> {
2035    /// Whether the iterator is positioned at a valid entry.
2036    pub fn is_valid(&self) -> bool {
2037        self.is_currently_valid
2038    }
2039
2040    /// Propagate iterator status errors.
2041    pub fn status(&self) -> Result<(), StorageError> {
2042        unsafe {
2043            ffi_result!(rocksdb_iter_get_error(self.inner))?;
2044        }
2045        Ok(())
2046    }
2047
2048    /// Advance to the next key.
2049    pub fn next(&mut self) {
2050        unsafe {
2051            rocksdb_iter_next(self.inner);
2052            self.is_currently_valid = rocksdb_iter_valid(self.inner) != 0;
2053        }
2054    }
2055
2056    /// Jump to the first key `>= key` on this iterator (does not recreate it).
2057    ///
2058    /// The iterate upper bound from [`Db::scan_prefix_from`] still applies:
2059    /// seeking past that bound leaves the iterator invalid.
2060    pub fn seek(&mut self, key: &[u8]) {
2061        unsafe {
2062            if key.is_empty() {
2063                rocksdb_iter_seek_to_first(self.inner);
2064            } else {
2065                rocksdb_iter_seek(self.inner, key.as_ptr().cast(), key.len());
2066            }
2067            self.is_currently_valid = rocksdb_iter_valid(self.inner) != 0;
2068        }
2069    }
2070
2071    /// Current key bytes, if valid.
2072    pub fn key(&self) -> Option<&[u8]> {
2073        if self.is_valid() {
2074            unsafe {
2075                let key = oxrocksdb_iter_key_slice(self.inner);
2076                Some(slice::from_raw_parts(key.data.cast(), key.size))
2077            }
2078        } else {
2079            None
2080        }
2081    }
2082
2083    /// Current value bytes, if valid (same cursor — no second Get).
2084    pub fn value(&self) -> Option<&[u8]> {
2085        if self.is_valid() {
2086            unsafe {
2087                let value = rocksdb_iter_value_slice(self.inner);
2088                Some(slice::from_raw_parts(value.data.cast(), value.size))
2089            }
2090        } else {
2091            None
2092        }
2093    }
2094}
2095
2096/// Accumulates `Put`s and commits them with one `rocksdb_write`.
2097pub struct WriteBatch {
2098    db: Db,
2099    batch: *mut rocksdb_writebatch_t,
2100}
2101
2102impl Drop for WriteBatch {
2103    fn drop(&mut self) {
2104        unsafe {
2105            rocksdb_writebatch_destroy(self.batch);
2106        }
2107    }
2108}
2109
2110impl WriteBatch {
2111    /// Stage `key` → `value` in `column_family` (no I/O until [`Self::commit`]).
2112    pub fn insert(&mut self, column_family: &ColumnFamily, key: &[u8], value: &[u8]) {
2113        unsafe {
2114            rocksdb_writebatch_put_cf(
2115                self.batch,
2116                column_family.0,
2117                key.as_ptr().cast(),
2118                key.len(),
2119                value.as_ptr().cast(),
2120                value.len(),
2121            );
2122        }
2123    }
2124
2125    /// Stage a `Delete` of `key` in `column_family` (no I/O until [`Self::commit`]).
2126    pub fn delete(&mut self, column_family: &ColumnFamily, key: &[u8]) {
2127        unsafe {
2128            rocksdb_writebatch_delete_cf(
2129                self.batch,
2130                column_family.0,
2131                key.as_ptr().cast(),
2132                key.len(),
2133            );
2134        }
2135    }
2136
2137    /// Apply every staged put atomically using the DB's write options.
2138    ///
2139    /// Durability on return depends on the DB's tuning: with
2140    /// [`RocksDbTuning::sync_writes`] the WAL entry is flushed and fsynced
2141    /// inside this call; otherwise the write returns after the WAL buffer
2142    /// write (or the MemTable insert when the WAL is disabled).
2143    pub fn commit(self) -> Result<(), StorageError> {
2144        unsafe {
2145            ffi_result!(rocksdb_write(
2146                self.db.inner.db,
2147                self.db.inner.write_options,
2148                self.batch,
2149            ))?;
2150        }
2151        Ok(())
2152    }
2153}
2154
2155/// Sorted SST run writer over `rocksdb_sstfilewriter_*` (bulk `IngestExternalFile` input).
2156///
2157/// Writes one file of strictly ascending `(key, value)` pairs — the RocksDB
2158/// `SstFileWriter::Add` contract — which [`Db::ingest_external_file_cf`] then
2159/// links into a column family without a memtable round-trip. The file layout
2160/// matches [`Db`]'s own output: LZ4 compression, format-version-5 blocks at
2161/// the given block size, so ingested files need no rewrite to be read or
2162/// compacted later.
2163pub struct SstFileWriter {
2164    inner: *mut rocksdb_sstfilewriter_t,
2165}
2166
2167// SAFETY: RocksDB handles are internally synchronized; we use the writer from
2168// one thread at a time by construction (&mut self).
2169unsafe impl Send for SstFileWriter {}
2170
2171impl SstFileWriter {
2172    /// Create a writer with `block_size_bytes` data blocks (see
2173    /// [`REGISTRY_BLOCK_SIZE_BYTES`] for scan-heavy stores).
2174    pub fn new(block_size_bytes: usize) -> Result<Self, StorageError> {
2175        unsafe {
2176            let env = rocksdb_envoptions_create();
2177            assert!(!env.is_null(), "rocksdb_envoptions_create returned null");
2178            let options = rocksdb_options_create();
2179            assert!(!options.is_null(), "rocksdb_options_create returned null");
2180            rocksdb_options_set_compression(options, rocksdb_lz4_compression.try_into().unwrap());
2181            let table = rocksdb_block_based_options_create();
2182            assert!(
2183                !table.is_null(),
2184                "rocksdb_block_based_options_create returned null"
2185            );
2186            rocksdb_block_based_options_set_format_version(table, 8);
2187            rocksdb_block_based_options_set_block_size(table, block_size_bytes);
2188            rocksdb_options_set_block_based_table_factory(options, table);
2189            // `SstFileWriter` copies both option structs into its Rep, so the
2190            // FFI-owned originals can be destroyed immediately after create.
2191            // (`rocksdb_sstfilewriter_create` takes no errptr — it cannot fail.)
2192            let inner = rocksdb_sstfilewriter_create(env, options);
2193            rocksdb_block_based_options_destroy(table);
2194            rocksdb_options_destroy(options);
2195            rocksdb_envoptions_destroy(env);
2196            assert!(
2197                !inner.is_null(),
2198                "rocksdb_sstfilewriter_create returned null"
2199            );
2200            Ok(Self { inner })
2201        }
2202    }
2203
2204    /// Open the destination file; `path` must not already exist.
2205    pub fn open(&mut self, path: &Path) -> Result<(), StorageError> {
2206        let c_path = path_to_cstring(path)?;
2207        unsafe {
2208            ffi_result!(rocksdb_sstfilewriter_open(self.inner, c_path.as_ptr()))?;
2209        }
2210        Ok(())
2211    }
2212
2213    /// Append the next pair; keys must ascend strictly in bytewise order.
2214    pub fn add(&mut self, key: &[u8], value: &[u8]) -> Result<(), StorageError> {
2215        unsafe {
2216            ffi_result!(rocksdb_sstfilewriter_add(
2217                self.inner,
2218                key.as_ptr().cast(),
2219                key.len(),
2220                value.as_ptr().cast(),
2221                value.len(),
2222            ))?;
2223        }
2224        Ok(())
2225    }
2226
2227    /// Finish the file: flush the last data block and write the footer.
2228    ///
2229    /// Consumes the writer; a writer dropped without `finish` leaves no file.
2230    pub fn finish(self) -> Result<(), StorageError> {
2231        unsafe {
2232            ffi_result!(rocksdb_sstfilewriter_finish(self.inner))?;
2233        }
2234        Ok(())
2235    }
2236}
2237
2238impl Drop for SstFileWriter {
2239    fn drop(&mut self) {
2240        unsafe {
2241            rocksdb_sstfilewriter_destroy(self.inner);
2242        }
2243    }
2244}
2245
2246fn sum_cf_int(db: &Db, column_families: &[&ColumnFamily], name: &str) -> Option<u64> {
2247    let mut sum = 0u64;
2248    let mut any = false;
2249    for cf in column_families {
2250        if let Some(value) = db.int_property_cf(cf, name) {
2251            sum = sum.saturating_add(value);
2252            any = true;
2253        }
2254    }
2255    any.then_some(sum)
2256}
2257
2258fn path_to_cstring(path: &Path) -> Result<CString, StorageError> {
2259    let s = path
2260        .to_str()
2261        .ok_or_else(|| StorageError::Backend("The DB path is not valid UTF-8".to_owned()))?;
2262    CString::new(s).map_err(|e| StorageError::Backend(e.to_string()))
2263}
2264
2265#[cfg(test)]
2266mod tests {
2267    use super::*;
2268    use tempfile::TempDir;
2269
2270    #[test]
2271    fn readahead_env_values_map_to_bytes() {
2272        assert_eq!(readahead_from_env(None), DEFAULT_ITERATOR_READAHEAD_BYTES);
2273        assert_eq!(readahead_from_env(Some("256")), 256 * 1024);
2274        assert_eq!(readahead_from_env(Some("4")), 4 * 1024);
2275        assert_eq!(readahead_from_env(Some("1024")), 1024 * 1024);
2276        assert_eq!(
2277            readahead_from_env(Some("0")),
2278            0,
2279            "0 must reach RocksDB as 0 = engine default (auto readahead where eligible)"
2280        );
2281        assert_eq!(
2282            readahead_from_env(Some(" 512 ")),
2283            512 * 1024,
2284            "surrounding whitespace is tolerated"
2285        );
2286    }
2287
2288    #[test]
2289    fn hexastore_readahead_test_knob_parses_to_bytes() {
2290        // Unset and 0 are no-ops: the hexastore tuning default is already the
2291        // engine auto-readahead.
2292        assert_eq!(hexastore_readahead_from_env(None), None);
2293        assert_eq!(hexastore_readahead_from_env(Some("")), None);
2294        assert_eq!(hexastore_readahead_from_env(Some("0")), None);
2295        // The headline case from the experiment plan: `=16` means 16 KiB.
2296        assert_eq!(hexastore_readahead_from_env(Some("16")), Some(16 * 1024));
2297        assert_eq!(hexastore_readahead_from_env(Some(" 64 ")), Some(64 * 1024));
2298        assert_eq!(
2299            hexastore_readahead_from_env(Some("8192")),
2300            Some(8 * 1024 * 1024),
2301            "the clamp boundary itself is accepted verbatim"
2302        );
2303        assert_eq!(
2304            hexastore_readahead_from_env(Some("65536")),
2305            Some(TEST_HEXASTORE_READAHEAD_MAX_KIB * 1024),
2306            "above the clamp the window is capped, not rejected"
2307        );
2308    }
2309
2310    #[test]
2311    fn invalid_hexastore_readahead_test_knob_is_ignored() {
2312        // Junk disables the knob (hexastore keeps engine auto-readahead);
2313        // it must never fall through to the registry's default window.
2314        for junk in ["abc", "-4", "12.5", "1e3"] {
2315            assert_eq!(
2316                hexastore_readahead_from_env(Some(junk)),
2317                None,
2318                "junk value {junk:?} must leave the hexastore tuning untouched"
2319            );
2320        }
2321    }
2322
2323    #[test]
2324    fn invalid_readahead_env_falls_back_to_default() {
2325        for junk in ["", "abc", "-4", "12.5", "1e3"] {
2326            assert_eq!(
2327                readahead_from_env(Some(junk)),
2328                DEFAULT_ITERATOR_READAHEAD_BYTES,
2329                "junk value {junk:?} must fall back to the default"
2330            );
2331        }
2332    }
2333
2334    #[test]
2335    fn env_flag_parses_and_falls_back_to_default() {
2336        // Explicit values win over the default.
2337        assert!(env_flag("V", Some("1"), false));
2338        assert!(env_flag("V", Some(" true "), true));
2339        assert!(env_flag("V", Some("ON"), false));
2340        assert!(env_flag("V", Some("yes"), false));
2341        // Unset / empty fall back to the default.
2342        assert!(env_flag("V", None, true));
2343        assert!(!env_flag("V", None, false));
2344        assert!(env_flag("V", Some("  "), true));
2345        // Explicit off beats a true default.
2346        assert!(!env_flag("V", Some("0"), true));
2347        assert!(!env_flag("V", Some("False"), true));
2348        assert!(!env_flag("V", Some("off"), true));
2349        // Junk warns (to stderr) and falls back to the default: a typo must
2350        // not silently flip tuning either way.
2351        assert!(env_flag("WARATAH_PIN_INDEX", Some("ture"), true));
2352        assert!(!env_flag("WARATAH_PIN_INDEX", Some("ture"), false));
2353    }
2354
2355    #[test]
2356    fn experimental_tunings_default_off_everywhere() {
2357        // The named constructors must stay env-independent; the process-wide
2358        // gates are applied at open (see `open_read_write_with_hooks`).
2359        for tuning in [
2360            RocksDbTuning::default(),
2361            RocksDbTuning::registry_node(),
2362            RocksDbTuning::bulk_ingest(false),
2363        ] {
2364            assert!(!tuning.pin_index_in_cache);
2365            assert!(!tuning.scan_async_io);
2366        }
2367    }
2368
2369    #[test]
2370    fn block_cache_usage_and_capacity_flow_from_tuning() {
2371        let dir = TempDir::new().unwrap();
2372        let db = Db::open_read_write_with_hooks(
2373            dir.path(),
2374            vec![ColumnFamilyDefinition {
2375                name: "t",
2376                min_prefix_size: 0,
2377                prefix_filter: false,
2378                permutation: None,
2379            }],
2380            RocksDbOptionsHooks {
2381                tuning: RocksDbTuning {
2382                    block_cache_bytes: 8 * 1024 * 1024,
2383                    ..Default::default()
2384                },
2385                ..Default::default()
2386            },
2387        )
2388        .unwrap();
2389        assert_eq!(db.block_cache_capacity(), 8 * 1024 * 1024);
2390
2391        let cf = db.column_family("t").unwrap();
2392        let mut batch = db.write_batch();
2393        batch.insert(&cf, &[1u8, 2, 3], &[9u8; 64]);
2394        batch.commit().unwrap();
2395        db.flush_cfs(&[&cf]).unwrap();
2396        assert_eq!(
2397            db.get(&cf, &[1, 2, 3]).unwrap().as_deref(),
2398            Some(&[9u8; 64][..])
2399        );
2400        assert!(
2401            db.block_cache_usage() > 0,
2402            "a get after flush must pull the data block into the cache"
2403        );
2404    }
2405
2406    #[test]
2407    fn registry_tuning_uses_big_blocks_and_default_stays_small() {
2408        assert_eq!(
2409            RocksDbTuning::default().block_size_bytes,
2410            DEFAULT_BLOCK_SIZE_BYTES
2411        );
2412        assert_eq!(
2413            RocksDbTuning::bulk_ingest(false).block_size_bytes,
2414            DEFAULT_BLOCK_SIZE_BYTES
2415        );
2416        assert_eq!(
2417            RocksDbTuning::registry_node().block_size_bytes,
2418            REGISTRY_BLOCK_SIZE_BYTES
2419        );
2420    }
2421
2422    #[test]
2423    fn only_registry_tuning_sets_fixed_iterator_readahead() {
2424        // Hexastore scans must keep 0 = engine default: they are
2425        // upper-bound-eligible for the engine's auto-readahead, and a fixed
2426        // window would both over-read short scans and disable the trimming.
2427        assert_eq!(RocksDbTuning::default().iterator_readahead_bytes, 0);
2428        assert_eq!(
2429            RocksDbTuning::bulk_ingest(false).iterator_readahead_bytes,
2430            0
2431        );
2432        assert_eq!(
2433            RocksDbTuning::registry_node().iterator_readahead_bytes,
2434            iterator_readahead_bytes()
2435        );
2436    }
2437
2438    #[test]
2439    fn seek_reuses_iterator_and_skips_middle_prefix() {
2440        let dir = TempDir::new().unwrap();
2441        let db = Db::open_read_write_with_hooks(
2442            dir.path(),
2443            vec![ColumnFamilyDefinition {
2444                name: "t",
2445                min_prefix_size: 0,
2446                prefix_filter: false,
2447                permutation: None,
2448            }],
2449            RocksDbOptionsHooks::default(),
2450        )
2451        .unwrap();
2452        let cf = db.column_family("t").unwrap();
2453        let mut batch = db.write_batch();
2454        batch.insert(&cf, &[0x01, 0x10, 0x01], &[1]);
2455        batch.insert(&cf, &[0x01, 0x10, 0x02], &[1]);
2456        batch.insert(&cf, &[0x01, 0x20, 0x01], &[1]);
2457        batch.insert(&cf, &[0x01, 0x30, 0x01], &[1]);
2458        batch.commit().unwrap();
2459
2460        let mut iter = db.scan_prefix(&cf, &[0x01]);
2461        iter.seek(&[0x01, 0x10]);
2462        let mut first = Vec::new();
2463        while iter.is_valid() {
2464            let key = iter.key().unwrap();
2465            if !key.starts_with(&[0x01, 0x10]) {
2466                break;
2467            }
2468            first.push(key.to_vec());
2469            iter.next();
2470        }
2471        assert_eq!(first.len(), 2, "S1 slice has two keys");
2472
2473        iter.seek(&[0x01, 0x30]);
2474        let mut third = Vec::new();
2475        while iter.is_valid() {
2476            let key = iter.key().unwrap();
2477            if !key.starts_with(&[0x01, 0x30]) {
2478                break;
2479            }
2480            third.push(key.to_vec());
2481            iter.next();
2482        }
2483        assert_eq!(third, vec![vec![0x01, 0x30, 0x01]]);
2484        assert!(
2485            first.iter().all(|k| !k.starts_with(&[0x01, 0x20])),
2486            "S2 must not appear in the S1 slice"
2487        );
2488        iter.status().unwrap();
2489    }
2490
2491    /// Keys with distinct 17-byte prefixes (first byte varies) for the
2492    /// filter tests below: the fixed-prefix extractor stays in domain, and
2493    /// the prefix bytes ARE the leading term as far as the bloom is
2494    /// concerned.
2495    fn filter_test_definitions() -> Vec<ColumnFamilyDefinition> {
2496        vec![
2497            ColumnFamilyDefinition {
2498                name: "filtered",
2499                min_prefix_size: 17,
2500                prefix_filter: true,
2501                permutation: None,
2502            },
2503            ColumnFamilyDefinition {
2504                name: "plain",
2505                min_prefix_size: 17,
2506                prefix_filter: false,
2507                permutation: None,
2508            },
2509        ]
2510    }
2511
2512    #[test]
2513    fn prefix_filter_builds_filter_blocks_only_on_marked_cfs() {
2514        TEST_SST_FILTER_FORCE_ON.store(true, AtomicOrdering::Relaxed);
2515        let dir = TempDir::new().unwrap();
2516        let db = Db::open_read_write_with_hooks(
2517            dir.path(),
2518            filter_test_definitions(),
2519            RocksDbOptionsHooks::default(),
2520        )
2521        .unwrap();
2522        let filtered = db.column_family("filtered").unwrap();
2523        let plain = db.column_family("plain").unwrap();
2524        let mut batch = db.write_batch();
2525        for i in 0..4u8 {
2526            let mut key = [0u8; 17];
2527            key[0] = 0x01;
2528            key[16] = i;
2529            batch.insert(&filtered, &key, &[i]);
2530            batch.insert(&plain, &key, &[i]);
2531        }
2532        batch.commit().unwrap();
2533        db.flush_cfs(&[&filtered, &plain]).unwrap();
2534
2535        let names = db.table_filter_policy_names(&filtered).unwrap();
2536        assert_eq!(
2537            names,
2538            vec!["bloomfilter".to_owned()],
2539            "every SST of a prefix_filter CF must carry a bloom filter block \
2540             (table property filter_policy_name is the compatibility name)"
2541        );
2542        let plain_names = db.table_filter_policy_names(&plain).unwrap();
2543        assert!(
2544            plain_names.iter().all(String::is_empty),
2545            "unmarked CFs must stay filter-less, got {plain_names:?}"
2546        );
2547    }
2548
2549    #[test]
2550    fn absent_prefix_probes_consult_the_bloom_filter() {
2551        TEST_SST_FILTER_FORCE_ON.store(true, AtomicOrdering::Relaxed);
2552        let dir = TempDir::new().unwrap();
2553        let db = Db::open_read_write_with_hooks(
2554            dir.path(),
2555            filter_test_definitions(),
2556            RocksDbOptionsHooks::default(),
2557        )
2558        .unwrap();
2559        let filtered = db.column_family("filtered").unwrap();
2560        // Leading prefixes 0x01 / 0x02 / 0x05: the absent probe 0x03 sorts
2561        // INSIDE the SST's [smallest, largest] key range, so the file-range
2562        // check cannot skip the file — only the bloom can, which is exactly
2563        // the shape being asserted.
2564        let mut batch = db.write_batch();
2565        for first in [0x01u8, 0x02, 0x05] {
2566            let mut key = [0u8; 17];
2567            key[0] = first;
2568            batch.insert(&filtered, &key, &[first]);
2569        }
2570        batch.commit().unwrap();
2571        db.flush_cfs(&[&filtered]).unwrap();
2572
2573        let mut absent = vec![0x03u8; 18];
2574        absent[16] = 0xAA;
2575
2576        // Point path: MultiGet consults the prefix bloom and the negative
2577        // verdict skips the lookup — both facts are recorded as tickers.
2578        let checked_before = db.ticker_count(TICKER_BLOOM_FILTER_PREFIX_CHECKED);
2579        let useful_before = db.ticker_count(TICKER_BLOOM_FILTER_PREFIX_USEFUL);
2580        let results = db.multi_get_pinned(&filtered, &[&absent], true).unwrap();
2581        assert_eq!(results, vec![None]);
2582        assert!(
2583            db.ticker_count(TICKER_BLOOM_FILTER_PREFIX_CHECKED) > checked_before,
2584            "the prefix bloom must be checked on a point lookup"
2585        );
2586        assert!(
2587            db.ticker_count(TICKER_BLOOM_FILTER_PREFIX_USEFUL) > useful_before,
2588            "the absent prefix must produce a useful (negative) bloom verdict"
2589        );
2590
2591        // Seek path: the scan iterator consults the prefix bloom at the
2592        // per-SST Seek and a negative verdict skips the whole file —
2593        // recorded as a seek-filtered ticker at the skip decision. This
2594        // is the exact mechanism bound-subject pattern scans and the
2595        // broadcast-filter seek-union ride on.
2596        let filtered_before = db.ticker_count(TICKER_SEEK_FILTERED);
2597        let match_before = db.ticker_count(TICKER_SEEK_FILTER_MATCH);
2598        let iter = db.scan_prefix(&filtered, &absent);
2599        assert!(!iter.is_valid());
2600        iter.status().unwrap();
2601        assert!(
2602            db.ticker_count(TICKER_SEEK_FILTERED) > filtered_before,
2603            "a seek whose target is inside the file range but outside the \
2604             bloom must consult the filter and skip the SST \
2605             ({} -> {}), filter-match {} -> {}",
2606            filtered_before,
2607            db.ticker_count(TICKER_SEEK_FILTERED),
2608            match_before,
2609            db.ticker_count(TICKER_SEEK_FILTER_MATCH),
2610        );
2611    }
2612}