Skip to main content

waratah_registry/
blobs.rs

1//! Content-addressed blob store on the registry process, in two variants:
2//! index-backed (RocksDB / data-dir modes) and in-memory (the default
3//! in-memory registry mode, so geo writes work without a data dir).
4//!
5//! The index-backed variant keeps a RocksDB DB at `blobs/index/` mapping a
6//! 16-byte content hash to a tagged value:
7//!
8//! - tag 0: the payload bytes inline (`[0][payload]`);
9//! - tag 1: a segment locator (`[1][segment_id u32][offset u64][len u32]`,
10//!   little-endian).
11//!
12//! Payloads at or below [`INLINE_THRESHOLD_BYTES`] take the inline tag;
13//! larger payloads append to immutable segment files at
14//! `blobs/segments/seg-{id:010}.bin` as `[len u32][crc32 u32][payload]`
15//! records (little-endian header), and the index holds the locator.
16//!
17//! **Durability invariant: a durable locator implies durable bytes.** A
18//! batch's records are appended and `fdatasync`ed BEFORE the index
19//! `WriteBatch` (locators + per-segment durable lengths) commits — and the
20//! commit itself is synchronous (the index DB fsyncs its WAL entry inside
21//! the commit), so a returning put really does mean "on disk". The
22//! only crash windows leave orphan segment bytes with no locator —
23//! harmless. A failed append cuts its partial bytes back; a failed commit
24//! additionally triggers a best-effort truncate back to the batch's
25//! pre-append length (skipped when another writer appended in between;
26//! those bytes stay as bounded orphans). A failed `fdatasync` or segment
27//! roll after a successful append also leaves the batch's bytes in place
28//! — no locator committed, and the next batch's durable length simply
29//! covers them, so they remain as bounded orphan records. Open-time
30//! recovery truncates a torn tail only when a committed durable length
31//! exists for the segment; a segment with no entry keeps its bytes (an
32//! absent entry also means the index DB itself may have been lost, and
33//! recovery must not destroy payloads in that case — see
34//! [`SegmentSet::open`]).
35//!
36//! **Why a separate RocksDB DB.** The string dictionary is read by bulk
37//! sorted walks and uses 32 KiB blocks. The blob index is a point lookup:
38//! 4 KiB blocks, a dedicated 64 MiB cache, and a Bloom filter
39//! ([`waratah_storage::BlobIndex`]). Keeping it separate also keeps
40//! `FlushMemtables`/`CompactRange` on the dictionary from rewriting the
41//! index.
42//!
43//! **Integrity layers.** The CRC32 in each segment record is a cheap
44//! storage check ("are these the bytes that were physically written?"),
45//! verified on every segment read; the content hash (`StrHash`) is the
46//! identity check ("is this the blob the caller asked for?"), re-verified
47//! by the client on reassembly. Inline values rely on RocksDB block
48//! checksums plus the client re-hash.
49//!
50//! **Legacy layout.** The previous store kept one file per payload at
51//! `blobs/{xx}/{hash}.bin|.meta`. If that layout exists and `blobs/index/`
52//! does not, [`BlobStore::open`] fails with
53//! [`RegistryError::LegacyBlobLayout`]; there is no dual-read path and no
54//! migration command — the layout was written by an unreleased build, so
55//! the remedy is re-importing into a fresh data dir.
56
57use std::collections::{BTreeMap, HashMap, HashSet};
58use std::fmt;
59use std::fs::{File, OpenOptions};
60use std::os::unix::fs::FileExt;
61use std::path::{Path, PathBuf};
62use std::sync::atomic::{AtomicUsize, Ordering};
63use std::sync::{Arc, Mutex};
64
65use waratah_storage::{BlobIndex, StrHash, blob_index_dir, blob_segments_dir};
66
67use crate::RegistryError;
68
69/// Maximum size of one stored blob (64 MiB).
70///
71/// Independent of the 4 MiB gRPC frame (chunked RPC) and of
72/// [`MAX_REGISTERED_STRING_BYTES`](crate::MAX_REGISTERED_STRING_BYTES)
73/// (1 MiB UTF-8 terms).
74pub const MAX_BLOB_BYTES: usize = 64 * 1024 * 1024;
75
76/// Largest payload stored inline in the blob index.
77///
78/// Payloads above this threshold go to the segment tier. 4 KiB is the block
79/// size of the blob index: an inline value stays within one data block, and
80/// the geometry payloads in the Bellendena corpora are 100-400 bytes, so the
81/// segment tier holds only genuinely large geometries.
82pub const INLINE_THRESHOLD_BYTES: usize = 4 * 1024;
83
84/// A segment rolls to the next file once its length reaches this target
85/// after an append.
86///
87/// Bounds the number of open segment handles (10 GiB of large payloads ≈ 80
88/// segments) and matches the immutable-object granularity the target
89/// architecture's Fast layer wants for object storage.
90pub const SEGMENT_TARGET_BYTES: usize = 128 * 1024 * 1024;
91
92/// Default number of segment files kept open for reads.
93///
94/// Covers every segment up to ~32 GiB of large payloads; trivial in file
95/// descriptors against the process limit, and the read path already groups
96/// a batch by segment, so misses are rare above a handful of segments.
97pub const SEGMENT_HANDLE_CACHE: usize = 256;
98
99/// Hard maximum for the segment handle cache (a test override can never
100/// push past this).
101pub const SEGMENT_HANDLE_CACHE_MAX: usize = 512;
102
103/// Segment record header: `len u32 | crc32 u32` (little-endian).
104const RECORD_HEADER_BYTES: usize = 8;
105
106/// Index value tag: the payload bytes follow the tag.
107const INLINE_TAG: u8 = 0;
108/// Index value tag: a segment locator follows the tag.
109const SEGMENT_TAG: u8 = 1;
110
111static SEGMENT_TARGET_SETTING: AtomicUsize = AtomicUsize::new(0);
112static SEGMENT_HANDLE_CACHE_SETTING: AtomicUsize = AtomicUsize::new(0);
113
114/// Restores one process-wide tuning slot to its default (`0`) when
115/// dropped — including when the test panics, which a trailing reset call
116/// cannot cover. Two guards over different slots compose.
117pub struct TuningOverride {
118    slot: &'static AtomicUsize,
119}
120
121impl Drop for TuningOverride {
122    fn drop(&mut self) {
123        self.slot.store(0, Ordering::Relaxed);
124    }
125}
126
127/// Override the segment roll target for tests (rollover tests need a
128/// shrinkable segment). Process-wide; the returned guard restores the
129/// default when dropped. Serialize against other tuning-sensitive tests
130/// (the test module's mutex) while an override is live. The slot treats
131/// `0` as "use the default" (the same value the guard stores), so passing
132/// `0` is equivalent to no override.
133pub fn set_segment_target_bytes(bytes: usize) -> TuningOverride {
134    SEGMENT_TARGET_SETTING.store(bytes, Ordering::Relaxed);
135    TuningOverride {
136        slot: &SEGMENT_TARGET_SETTING,
137    }
138}
139
140fn segment_target_bytes() -> usize {
141    match SEGMENT_TARGET_SETTING.load(Ordering::Relaxed) {
142        0 => SEGMENT_TARGET_BYTES,
143        bytes => bytes,
144    }
145}
146
147/// Override the segment handle-cache capacity for tests (eviction tests
148/// need a tiny cache). Clamped to [`SEGMENT_HANDLE_CACHE_MAX`]. The
149/// capacity is read once at [`BlobStore::open`], so set it before opening.
150/// Process-wide; the returned guard restores the default when dropped.
151/// The slot treats `0` as "use the default" (the same value the guard
152/// stores), so passing `0` yields [`SEGMENT_HANDLE_CACHE`], not an empty
153/// cache.
154pub fn set_segment_handle_cache(capacity: usize) -> TuningOverride {
155    SEGMENT_HANDLE_CACHE_SETTING.store(capacity, Ordering::Relaxed);
156    TuningOverride {
157        slot: &SEGMENT_HANDLE_CACHE_SETTING,
158    }
159}
160
161fn segment_handle_cache_capacity() -> usize {
162    match SEGMENT_HANDLE_CACHE_SETTING.load(Ordering::Relaxed) {
163        0 => SEGMENT_HANDLE_CACHE,
164        capacity => capacity.min(SEGMENT_HANDLE_CACHE_MAX),
165    }
166}
167
168/// Content-addressed blob store: index-backed or in-memory behind one
169/// surface, so `RegistryService` and callers are unaffected by the variant.
170pub struct BlobStore {
171    inner: BlobStoreInner,
172}
173
174impl fmt::Debug for BlobStore {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        match &self.inner {
177            BlobStoreInner::Index { root, .. } => f
178                .debug_struct("BlobStore")
179                .field("root", root)
180                .finish_non_exhaustive(),
181            BlobStoreInner::Memory(_) => f
182                .debug_struct("BlobStore")
183                .field("backend", &"memory")
184                .finish(),
185        }
186    }
187}
188
189enum BlobStoreInner {
190    /// RocksDB index under `{root}/index`; segment files under
191    /// `{root}/segments`.
192    Index {
193        root: PathBuf,
194        index: BlobIndex,
195        segments: SegmentSet,
196        handles: SegmentHandles,
197    },
198    /// RAM-backed payloads; data lives until process shutdown, consistent
199    /// with in-memory storage semantics. No inline threshold — every
200    /// payload up to [`MAX_BLOB_BYTES`] lives in the map, mirroring the
201    /// old in-memory store's behavior.
202    Memory(Mutex<HashMap<StrHash, Vec<u8>>>),
203}
204
205impl BlobStore {
206    /// Open (creating if missing) the blob store rooted at `blobs_root`.
207    ///
208    /// Recovery runs before the store is returned: a segment WITH a
209    /// committed durable length is truncated to it (a torn tail from a
210    /// mid-append crash never becomes readable), a segment shorter than
211    /// its committed length is reported as corruption, and a segment
212    /// WITHOUT an entry is left untouched (nothing references its bytes —
213    /// and an absent entry is also the signature of a lost index DB, which
214    /// must not be answered by destroying payloads).
215    ///
216    /// A legacy `blobs/{xx}/{hash}.bin` layout without a `blobs/index/`
217    /// directory is rejected rather than served as an empty store.
218    pub fn open(blobs_root: impl Into<PathBuf>) -> Result<Self, RegistryError> {
219        let root = blobs_root.into();
220        std::fs::create_dir_all(&root).map_err(|error| RegistryError::BlobIo(error.to_string()))?;
221        let index_dir = blob_index_dir(&root);
222        if !index_dir.exists() && legacy_layout_present(&root)? {
223            return Err(RegistryError::LegacyBlobLayout { path: root });
224        }
225        let index = BlobIndex::open(index_dir)?;
226        let segments = SegmentSet::open(&root, &index)?;
227        let handles = SegmentHandles::new(&root);
228        Ok(Self {
229            inner: BlobStoreInner::Index {
230                root,
231                index,
232                segments,
233                handles,
234            },
235        })
236    }
237
238    /// Create an in-memory blob store.
239    ///
240    /// Exists so the default in-memory registry supports geo writes: data
241    /// lives until process shutdown, consistent with in-memory storage
242    /// semantics.
243    pub fn memory() -> Self {
244        Self {
245            inner: BlobStoreInner::Memory(Mutex::new(HashMap::new())),
246        }
247    }
248
249    /// Store `payload` under `blob_id` (content-address validated here).
250    /// Returns the bytes written; a put of an id that already has a payload
251    /// is a no-op and returns 0 — the address is the commitment.
252    pub fn put(&self, blob_id: StrHash, payload: &[u8]) -> Result<u64, RegistryError> {
253        self.put_entries(&[(blob_id, payload)])
254    }
255
256    /// Batched, all-or-nothing blob write.
257    ///
258    /// Every payload must be non-empty, is size-checked against
259    /// [`MAX_BLOB_BYTES`], and is content-hash-validated before any
260    /// index write. Blobs already present are skipped; new blobs are
261    /// committed in one atomic index batch (a RocksDB `WriteBatch` in the
262    /// index-backed variant; the in-memory variant locks its map once), so a
263    /// failure leaves no partial entries. Content addressing makes a
264    /// whole-batch retry idempotent.
265    pub fn put_blobs(&self, blobs: &[(StrHash, Arc<[u8]>)]) -> Result<(), RegistryError> {
266        let entries: Vec<(StrHash, &[u8])> = blobs
267            .iter()
268            .map(|(id, payload)| (*id, payload.as_ref()))
269            .collect();
270        self.put_entries(&entries).map(|_| ())
271    }
272
273    fn put_entries(&self, entries: &[(StrHash, &[u8])]) -> Result<u64, RegistryError> {
274        if entries.is_empty() {
275            return Err(RegistryError::EmptyBlobBatch);
276        }
277        for (id, payload) in entries {
278            if payload.is_empty() {
279                // The streamed read path frames a payload as its chunks,
280                // and an empty payload chunks to zero frames — which a
281                // client reads back as a miss, never as an empty hit. Real
282                // payloads (e.g. EWKB geometry bytes) always have at least
283                // a header, so an empty one is a producer bug; reject it
284                // at the boundary instead of storing an entry that cannot
285                // round-trip.
286                return Err(RegistryError::BlobEmpty { id: *id });
287            }
288            if payload.len() > MAX_BLOB_BYTES {
289                return Err(RegistryError::BlobTooLarge {
290                    len: payload.len(),
291                    max: MAX_BLOB_BYTES,
292                });
293            }
294            if StrHash::from_bytes(payload) != *id {
295                return Err(RegistryError::BlobHashMismatch { id: *id });
296            }
297        }
298        match &self.inner {
299            BlobStoreInner::Index {
300                index, segments, ..
301            } => {
302                let keys: Vec<[u8; 16]> = entries.iter().map(|(id, _)| id.to_be_bytes()).collect();
303                let key_refs: Vec<&[u8]> = keys.iter().map(|key| key.as_slice()).collect();
304                let existing = index.multi_get(&key_refs)?;
305                // First occurrence of each new id, partitioned by tier.
306                let mut fresh_inline: Vec<(StrHash, &[u8])> = Vec::new();
307                let mut fresh_large: Vec<(StrHash, &[u8])> = Vec::new();
308                let mut seen: HashSet<StrHash> = HashSet::new();
309                for ((id, payload), present) in entries.iter().zip(existing) {
310                    if present.is_some() || !seen.insert(*id) {
311                        continue;
312                    }
313                    if payload.len() <= INLINE_THRESHOLD_BYTES {
314                        fresh_inline.push((*id, payload));
315                    } else {
316                        fresh_large.push((*id, payload));
317                    }
318                }
319                if fresh_inline.is_empty() && fresh_large.is_empty() {
320                    return Ok(0);
321                }
322                let mut written = 0u64;
323                if fresh_large.is_empty() {
324                    // Inline-only batch: no segment I/O, no append mutex.
325                    let mut batch = index.write_batch();
326                    for (id, payload) in fresh_inline {
327                        batch.insert(&id.to_be_bytes(), &encode_inline(payload));
328                        written += payload.len() as u64;
329                    }
330                    batch.commit()?;
331                    return Ok(written);
332                }
333                // Mixed or segment-only batch. The append mutex is held
334                // across re-probe + append + fdatasync + commit so a
335                // concurrent batch can neither interleave its bytes between
336                // this batch's appends and its locator commit nor defeat
337                // the failure-path truncate. Inline-only batches skip this
338                // serialization entirely (the common geometry case).
339                let mut writer = segments.lock()?;
340                // Re-probe the segment-tier ids under the mutex: the probe
341                // above ran unlocked, and a concurrent batch may have
342                // committed the same payload in between. Content addressing
343                // makes a double append harmless (identical bytes; the
344                // loser's record becomes a bounded orphan), but skipping it
345                // here keeps the segment compact when duplicate payloads
346                // race. Inline ids need no re-probe: two racing puts of the
347                // same id write identical index values atomically, and the
348                // second commit is a same-value overwrite.
349                if !fresh_large.is_empty() {
350                    let keys: Vec<[u8; 16]> =
351                        fresh_large.iter().map(|(id, _)| id.to_be_bytes()).collect();
352                    let key_refs: Vec<&[u8]> = keys.iter().map(|key| key.as_slice()).collect();
353                    let now_present = index.multi_get(&key_refs)?;
354                    let mut still_fresh = Vec::with_capacity(fresh_large.len());
355                    for ((id, payload), present) in fresh_large.drain(..).zip(now_present) {
356                        if present.is_none() {
357                            still_fresh.push((id, payload));
358                        }
359                    }
360                    fresh_large = still_fresh;
361                    if fresh_inline.is_empty() && fresh_large.is_empty() {
362                        return Ok(0);
363                    }
364                }
365                let mut batch = index.write_batch();
366                for (id, payload) in fresh_inline {
367                    batch.insert(&id.to_be_bytes(), &encode_inline(payload));
368                    written += payload.len() as u64;
369                }
370                // Per-segment (pre-append length, post-append length)
371                // bookkeeping for the durable-length commit and the
372                // failure-path truncate. The pre length is the offset of
373                // this batch's FIRST record in that segment; appends are
374                // contiguous per segment within one batch.
375                let mut touched: HashMap<u32, (u64, u64)> = HashMap::new();
376                for (id, payload) in fresh_large {
377                    let (segment_id, offset, len, length_after) = writer.append(payload)?;
378                    let entry = touched.entry(segment_id).or_insert((offset, length_after));
379                    entry.1 = length_after;
380                    batch.insert(&id.to_be_bytes(), &encode_locator(segment_id, offset, len));
381                    written += payload.len() as u64;
382                }
383                // Durable bytes BEFORE durable locators: the one-way
384                // invariant that makes a crash between these steps leave
385                // orphans instead of dangling references. Segments rolled
386                // mid-batch were already fdatasynced at their seal; the
387                // active segment is synced here, once per batch.
388                writer.sync_active()?;
389                for (segment_id, (_, length_after)) in &touched {
390                    batch.insert_meta(&durable_len_key(*segment_id), &length_after.to_le_bytes());
391                }
392                if let Err(error) = batch.commit() {
393                    // Best-effort truncate: the batch's bytes are orphans
394                    // (no locator committed). Truncating keeps the common
395                    // single-writer failure path clean; if the length check
396                    // fails (another writer appended, or the mutex scope
397                    // is ever split), the bytes simply stay as bounded
398                    // orphans.
399                    writer.truncate_touched(&touched);
400                    return Err(error.into());
401                }
402                Ok(written)
403            }
404            BlobStoreInner::Memory(map) => {
405                let mut map = map.lock().map_err(|_| RegistryError::LockPoisoned)?;
406                let mut written = 0u64;
407                let mut seen: HashSet<StrHash> = HashSet::new();
408                for (id, payload) in entries {
409                    if map.contains_key(id) || !seen.insert(*id) {
410                        continue;
411                    }
412                    map.insert(*id, payload.to_vec());
413                    written += payload.len() as u64;
414                }
415                Ok(written)
416            }
417        }
418    }
419
420    /// Fetch `ids` positionally; `None` marks a blob this store lacks.
421    ///
422    /// Segment hits are grouped by segment and read in ascending offset
423    /// order so a batch touching many records in one file reads with disk
424    /// locality. Every segment record's CRC32 is verified on read.
425    pub fn get(&self, ids: &[StrHash]) -> Result<Vec<Option<Vec<u8>>>, RegistryError> {
426        match &self.inner {
427            BlobStoreInner::Index { index, handles, .. } => {
428                let keys: Vec<[u8; 16]> = ids.iter().map(|id| id.to_be_bytes()).collect();
429                let key_refs: Vec<&[u8]> = keys.iter().map(|key| key.as_slice()).collect();
430                let values = index.multi_get(&key_refs)?;
431                let mut out: Vec<Option<Vec<u8>>> = Vec::with_capacity(ids.len());
432                let mut segment_reads: Vec<(usize, StrHash, Locator)> = Vec::new();
433                for (position, (value, id)) in values.into_iter().zip(ids.iter()).enumerate() {
434                    match value {
435                        None => out.push(None),
436                        Some(value) => match decode_entry(*id, &value)? {
437                            DecodedEntry::Inline(payload) => out.push(Some(payload)),
438                            DecodedEntry::Segment(locator) => {
439                                out.push(None);
440                                segment_reads.push((position, *id, locator));
441                            }
442                        },
443                    }
444                }
445                if !segment_reads.is_empty() {
446                    segment_reads.sort_by_key(|(_, _, locator)| (locator.segment, locator.offset));
447                    for (position, id, locator) in segment_reads {
448                        out[position] = Some(read_record(handles, id, &locator)?);
449                    }
450                }
451                Ok(out)
452            }
453            BlobStoreInner::Memory(map) => {
454                let map = map.lock().map_err(|_| RegistryError::LockPoisoned)?;
455                Ok(ids.iter().map(|id| map.get(id).cloned()).collect())
456            }
457        }
458    }
459
460    /// Flush the index MemTable to an SST file (no-op in memory).
461    pub fn flush(&self) -> Result<(), RegistryError> {
462        match &self.inner {
463            BlobStoreInner::Index { index, .. } => Ok(index.flush()?),
464            BlobStoreInner::Memory(_) => Ok(()),
465        }
466    }
467
468    /// Full-range compaction of the index column family (no-op in memory).
469    pub fn compact_range(&self) -> Result<(), RegistryError> {
470        match &self.inner {
471            BlobStoreInner::Index { index, .. } => {
472                index.compact();
473                Ok(())
474            }
475            BlobStoreInner::Memory(_) => Ok(()),
476        }
477    }
478
479    /// Offline integrity scan of the whole store (`waratah blob verify`).
480    ///
481    /// Checks, per index entry, that the value decodes and that an inline
482    /// payload hashes to its own key (identity), and per segment locator,
483    /// that the record exists with a matching header length (the read path
484    /// treats a disagreement as fatal — so must the scan), CRC32, AND
485    /// payload identity — a locator pointing at another blob's record has
486    /// a valid CRC and only the identity check catches it. Two locators
487    /// resolving to the same (segment, offset) are flagged separately.
488    /// Then walks every segment file sequentially, reporting records no
489    /// locator references as orphans and any undecodable tail as
490    /// corruption. A walk that hits an undecodable record aborts at that
491    /// offset (record framing is self-describing, so nothing past it can
492    /// be located without guessing); locators at or past the abort offset
493    /// are reported as unverified rather than dangling, because the
494    /// classic shape — preserved torn bytes below a committed durable
495    /// length, valid records appended after them — reads back fine. An
496    /// empty index over non-empty segments is flagged as the
497    /// lost-or-never-committed-index signature. `verify` itself
498    /// performs no writes; the store's `open` (which the caller already
499    /// ran, and which may truncate torn tails past committed durable
500    /// lengths) is where recovery happens. Returns the report; the caller
501    /// decides severity from [`BlobVerifyReport::problems`] and
502    /// [`BlobVerifyReport::orphan_records`].
503    pub fn verify(&self) -> Result<BlobVerifyReport, RegistryError> {
504        let BlobStoreInner::Index { root, index, .. } = &self.inner else {
505            return Err(RegistryError::BlobStoreMissing);
506        };
507        let mut report = BlobVerifyReport::default();
508        // Locator positions by (segment, offset) so the sequential walk can
509        // mark live records. The locator's declared length rides along so
510        // the walk can compare it against the record header — the read
511        // path treats a disagreement as fatal corruption, and verify must
512        // report the same condition rather than pass it.
513        let mut live: HashMap<(u32, u64), (StrHash, u32)> = HashMap::new();
514        // Segments whose sequential walk aborted at an undecodable record,
515        // with the abort offset: locators at or past that offset were never
516        // walked and must be reported as unverified, not as dangling (the
517        // classic shape is preserved torn bytes below a committed durable
518        // length, with valid records appended after them).
519        let mut aborted_at: HashMap<u32, u64> = HashMap::new();
520        let mut iter = index.iter_entries();
521        while iter.is_valid() {
522            report.index_entries += 1;
523            // Copy out before advancing: the iterator lends key/value only
524            // until the next `next()`.
525            let key = iter.key().expect("valid iterator yields a key").to_vec();
526            let value = iter
527                .value()
528                .expect("valid iterator yields a value")
529                .to_vec();
530            iter.next();
531            let Some(id) = hash_from_key(&key) else {
532                report.problems.push(format!(
533                    "index key of {} bytes is not a 16-byte hash",
534                    key.len()
535                ));
536                continue;
537            };
538            match decode_entry(id, &value) {
539                Ok(DecodedEntry::Inline(payload)) => {
540                    report.inline_entries += 1;
541                    if StrHash::from_bytes(&payload) != id {
542                        report.problems.push(format!(
543                            "inline payload of {id} does not hash to its own key"
544                        ));
545                    }
546                }
547                Ok(DecodedEntry::Segment(locator)) => {
548                    report.segment_entries += 1;
549                    // A second locator at an already-live position means
550                    // one of the two ids is wrong by construction; report
551                    // it here because the map can only keep one of them
552                    // for the walk's checks.
553                    if let Some((previous, _)) =
554                        live.insert((locator.segment, locator.offset), (id, locator.len))
555                    {
556                        report.problems.push(format!(
557                            "locators of {previous} and {id} both point at segment {} offset {}",
558                            locator.segment, locator.offset
559                        ));
560                    }
561                }
562                Err(error) => report.problems.push(format!("index entry {id}: {error}")),
563            }
564        }
565        iter.status()?;
566        // Sequential walk of every segment file.
567        let segments_dir = blob_segments_dir(root);
568        for segment_id in segment_ids(&segments_dir)? {
569            let path = segment_path(&segments_dir, segment_id);
570            let file =
571                File::open(&path).map_err(|error| RegistryError::BlobIo(error.to_string()))?;
572            let length = file
573                .metadata()
574                .map_err(|error| RegistryError::BlobIo(error.to_string()))?
575                .len();
576            let mut offset = 0u64;
577            let mut scan_aborted_at: Option<u64> = None;
578            while offset + RECORD_HEADER_BYTES as u64 <= length {
579                let mut header = [0u8; RECORD_HEADER_BYTES];
580                file.read_exact_at(&mut header, offset)
581                    .map_err(|error| RegistryError::BlobIo(error.to_string()))?;
582                let payload_len = u32::from_le_bytes(header[0..4].try_into().unwrap()) as u64;
583                let crc = u32::from_le_bytes(header[4..8].try_into().unwrap());
584                // Every legitimately written record is within the blob
585                // size limit; a header beyond it (even one that still fits
586                // in the file) is corruption — reject before the
587                // allocation. Aborting rather than skipping is deliberate:
588                // record framing is self-describing, so nothing past an
589                // undecodable record can be located without guessing.
590                if payload_len > MAX_BLOB_BYTES as u64 {
591                    report.problems.push(format!(
592                        "segment {segment_id}: record at {offset} declares {payload_len} bytes, \
593                         over the {} byte blob limit",
594                        MAX_BLOB_BYTES
595                    ));
596                    scan_aborted_at = Some(offset);
597                    break;
598                }
599                let record_end = offset + RECORD_HEADER_BYTES as u64 + payload_len;
600                if record_end > length {
601                    report.problems.push(format!(
602                        "segment {segment_id}: record at {offset} runs past the end of the file"
603                    ));
604                    scan_aborted_at = Some(offset);
605                    break;
606                }
607                let mut payload = vec![0u8; payload_len as usize];
608                file.read_exact_at(&mut payload, offset + RECORD_HEADER_BYTES as u64)
609                    .map_err(|error| RegistryError::BlobIo(error.to_string()))?;
610                report.segment_bytes_scanned += record_end - offset;
611                match live.remove(&(segment_id, offset)) {
612                    Some((id, locator_len)) => {
613                        // The read path rejects this mismatch outright
614                        // ("declares N bytes, its locator says M"), so a
615                        // store verify passes while a blob read fails must
616                        // be impossible.
617                        if payload_len != locator_len as u64 {
618                            report.problems.push(format!(
619                                "segment {segment_id} record at {offset} declares {payload_len} \
620                                 bytes, the locator of {id} says {locator_len}"
621                            ));
622                        }
623                        if crc32(&payload) != crc {
624                            report.problems.push(format!(
625                                "segment {segment_id} record at {offset} ({id}): CRC mismatch"
626                            ));
627                        }
628                        // The CRC proves the bytes are what was written;
629                        // identity proves they are the blob the locator
630                        // claims. A locator redirected at another blob's
631                        // record passes the CRC and fails only here.
632                        let actual = StrHash::from_bytes(&payload);
633                        if actual != id {
634                            report.problems.push(format!(
635                                "segment {segment_id} record at {offset} hashes to {actual}; its locator says {id}"
636                            ));
637                        }
638                    }
639                    None => report.orphan_records += 1,
640                }
641                offset = record_end;
642            }
643            if let Some(abort_offset) = scan_aborted_at {
644                // The aborting problem line already described the bytes at
645                // the abort offset; a trailing-bytes line on top would
646                // double-report the same region.
647                aborted_at.insert(segment_id, abort_offset);
648            } else if offset != length {
649                report.problems.push(format!(
650                    "segment {segment_id}: {} trailing byte(s) below the durable length are not a complete record",
651                    length - offset
652                ));
653            }
654        }
655        for ((segment_id, offset), (id, _)) in live {
656            if let Some(&abort_offset) = aborted_at.get(&segment_id)
657                && offset >= abort_offset
658            {
659                // The walk never reached this record (the scan aborted at
660                // or before it). It may be perfectly readable — reporting
661                // it as dangling would be false.
662                report.problems.push(format!(
663                    "locator of {id} points at segment {segment_id} offset {offset}, past the \
664                     point where the sequential scan aborted ({abort_offset}); the record was \
665                     not verified"
666                ));
667            } else {
668                report.problems.push(format!(
669                    "locator of {id} points at segment {segment_id} offset {offset}, which holds no record"
670                ));
671            }
672        }
673        // The index-loss signature: bytes exist, nothing references them,
674        // and the index has never (or no longer) committed an entry. Also
675        // matches an interrupted first append into a fresh store — either
676        // way every segment byte is unreachable and the operator should
677        // look, hence a problem rather than a census line.
678        if report.index_entries == 0 && report.segment_bytes_scanned > 0 {
679            report.problems.push(format!(
680                "index is empty but segments hold {} orphan record(s) over {} byte(s) — a lost or never-committed index DB",
681                report.orphan_records, report.segment_bytes_scanned
682            ));
683        }
684        Ok(report)
685    }
686}
687
688/// Result of [`BlobStore::verify`].
689#[derive(Debug, Default)]
690pub struct BlobVerifyReport {
691    /// Total blob entries in the index.
692    pub index_entries: u64,
693    /// Entries whose payload is inline in the index.
694    pub inline_entries: u64,
695    /// Entries pointing at segment records.
696    pub segment_entries: u64,
697    /// Segment bytes walked during the sequential scan.
698    pub segment_bytes_scanned: u64,
699    /// Segment records no locator references (bounded space leak).
700    pub orphan_records: u64,
701    /// Every integrity problem found, one line each.
702    pub problems: Vec<String>,
703}
704
705/// A parsed segment locator.
706#[derive(Debug, Clone, Copy, PartialEq, Eq)]
707struct Locator {
708    segment: u32,
709    offset: u64,
710    len: u32,
711}
712
713/// One segment set's append-side state; the single mutex serializes
714/// appends per store.
715struct SegmentSet {
716    writer: Mutex<SegmentWriter>,
717}
718
719impl SegmentSet {
720    /// Open the segments directory, run recovery, and position the active
721    /// segment for appends.
722    fn open(root: &Path, index: &BlobIndex) -> Result<Self, RegistryError> {
723        let dir = blob_segments_dir(root);
724        std::fs::create_dir_all(&dir).map_err(|error| RegistryError::BlobIo(error.to_string()))?;
725        let ids = segment_ids(&dir)?;
726        let writer = match ids.iter().copied().max() {
727            None => {
728                let active = create_segment_file(&dir, 0)?;
729                SegmentWriter {
730                    dir,
731                    active,
732                    active_id: 0,
733                    active_len: 0,
734                }
735            }
736            Some(active_id) => {
737                // Recovery, gated on the committed durable length:
738                //
739                // - A segment WITH a durable-length entry may carry a torn
740                //   tail past it (a crash between append/fdatasync and the
741                //   index commit). Truncate to the entry — it always covers
742                //   every committed locator's end, so this can never cut a
743                //   referenced record.
744                // - A segment WITHOUT an entry has never had a locator
745                //   committed into it (the entry commits in the same
746                //   WriteBatch as the locators), so nothing references its
747                //   bytes and they are never truncated. That is deliberate:
748                //   the entry is also absent when the whole index DB was
749                //   lost or rebuilt, and destroying the payload store must
750                //   not be the open path's decision — the bytes stay as
751                //   orphans (`waratah blob verify` reports them) and the
752                //   active segment simply appends past them.
753                let mut active_len = None;
754                for segment_id in ids {
755                    let path = segment_path(&dir, segment_id);
756                    let file_len = std::fs::metadata(&path)
757                        .map_err(|error| RegistryError::BlobIo(error.to_string()))?
758                        .len();
759                    match durable_len(index, segment_id)? {
760                        Some(durable) => {
761                            if file_len > durable {
762                                let file = OpenOptions::new()
763                                    .write(true)
764                                    .open(&path)
765                                    .map_err(|error| RegistryError::BlobIo(error.to_string()))?;
766                                file.set_len(durable)
767                                    .and_then(|()| file.sync_all())
768                                    .map_err(|error| RegistryError::BlobIo(error.to_string()))?;
769                            } else if file_len < durable {
770                                // One way this branch can fire without a
771                                // torn device: durable lengths are keyed
772                                // by bare numeric segment id with no
773                                // generation. If a segment file is deleted
774                                // out-of-band while its durable-length
775                                // entry survives, a later roll reuses the
776                                // id, and a crash before that segment's
777                                // first commit reopens here with a fresh
778                                // short file under the old entry.
779                                return Err(RegistryError::BlobCorrupt {
780                                    reason: format!(
781                                        "segment {segment_id} is {file_len} bytes, shorter than \
782                                         its committed durable length {durable}"
783                                    ),
784                                });
785                            }
786                            if segment_id == active_id {
787                                active_len = Some(durable);
788                            }
789                        }
790                        None => {
791                            if segment_id == active_id {
792                                // No committed length: append past whatever
793                                // bytes are there rather than judging them.
794                                active_len = Some(file_len);
795                            }
796                        }
797                    }
798                }
799                // Both match arms above assign a length when the loop
800                // visits the active segment, and the active id is the
801                // maximum of the walked ids, so it is always visited —
802                // the expect can only fire if that invariant is broken.
803                let active_len =
804                    active_len.expect("the active segment is always among the walked ids");
805                let file = OpenOptions::new()
806                    .read(true)
807                    .write(true)
808                    .open(segment_path(&dir, active_id))
809                    .map_err(|error| RegistryError::BlobIo(error.to_string()))?;
810                SegmentWriter {
811                    dir,
812                    active: file,
813                    active_id,
814                    active_len,
815                }
816            }
817        };
818        Ok(Self {
819            writer: Mutex::new(writer),
820        })
821    }
822
823    fn lock(&self) -> Result<std::sync::MutexGuard<'_, SegmentWriter>, RegistryError> {
824        // A panicking writer poisons this mutex; the store answers with the
825        // same error the in-memory variant uses rather than taking the
826        // process down.
827        self.writer.lock().map_err(|_| RegistryError::LockPoisoned)
828    }
829}
830
831/// The active append target plus its tracked length. The handle is opened
832/// for explicit-offset writes rather than append mode: on Linux, pwrite on
833/// an O_APPEND descriptor ignores the offset and lands at end-of-file, so
834/// a file left longer than `active_len` by a torn write would silently
835/// desync every later record from its locator. With the offset honored, a
836/// later append overwrites the torn bytes at the tracked offset instead.
837struct SegmentWriter {
838    dir: PathBuf,
839    active: File,
840    active_id: u32,
841    active_len: u64,
842}
843
844impl SegmentWriter {
845    /// Append one record and return `(segment_id, offset, payload_len,
846    /// segment_length_after)`. Rolls to the next segment once the target
847    /// length is reached after the append (the sealed segment is fdatasynced
848    /// and the new file's directory entry fsynced). On a write error, the
849    /// partial bytes are cut back to `offset` best-effort so the file
850    /// length and the tracked length stay equal; if that truncate also
851    /// fails, the next append still writes at the tracked offset and
852    /// overwrites whatever torn bytes remain.
853    fn append(&mut self, payload: &[u8]) -> Result<(u32, u64, u32, u64), RegistryError> {
854        let segment_id = self.active_id;
855        let offset = self.active_len;
856        let len = payload.len() as u32;
857        let mut record = Vec::with_capacity(RECORD_HEADER_BYTES + payload.len());
858        record.extend_from_slice(&len.to_le_bytes());
859        record.extend_from_slice(&crc32(payload).to_le_bytes());
860        record.extend_from_slice(payload);
861        if let Err(error) = self.active.write_all_at(&record, offset) {
862            // A torn write (ENOSPC, EIO) can leave the file longer than
863            // the tracked length — and the tracked length is what the next
864            // record's locator offset comes from, so the two must not
865            // diverge. Cut back to `offset`. Best-effort only: the caller
866            // is already on a failure path, and any surviving tail is
867            // overwritten by the next append at the same offset.
868            let _ = self
869                .active
870                .set_len(offset)
871                .and_then(|()| self.active.sync_all());
872            return Err(RegistryError::BlobIo(error.to_string()));
873        }
874        self.active_len += record.len() as u64;
875        let length_after = self.active_len;
876        if self.active_len >= segment_target_bytes() as u64 {
877            self.roll()?;
878        }
879        Ok((segment_id, offset, len, length_after))
880    }
881
882    /// Seal the active segment and create the next one.
883    fn roll(&mut self) -> Result<(), RegistryError> {
884        self.active
885            .sync_data()
886            .map_err(|error| RegistryError::BlobIo(error.to_string()))?;
887        let next_id = self.active_id + 1;
888        self.active = create_segment_file(&self.dir, next_id)?;
889        self.active_id = next_id;
890        self.active_len = 0;
891        Ok(())
892    }
893
894    /// `fdatasync` the active segment — once per batch, after its last
895    /// append, before the locator commit.
896    fn sync_active(&self) -> Result<(), RegistryError> {
897        self.active
898            .sync_data()
899            .map_err(|error| RegistryError::BlobIo(error.to_string()))
900    }
901
902    /// Best-effort truncate of a failed batch's bytes: for every touched
903    /// segment still ending at its post-append length, cut back to the
904    /// pre-append length and fsync. A segment whose length moved on belongs
905    /// to a concurrent (or later) writer; its bytes stay as bounded
906    /// orphans. Errors are swallowed by design — the caller is already on
907    /// a failure path and the leak is acceptable.
908    fn truncate_touched(&mut self, touched: &HashMap<u32, (u64, u64)>) {
909        for (segment_id, (pre_len, post_len)) in touched {
910            if *segment_id == self.active_id {
911                if self.active_len == *post_len
912                    && self
913                        .active
914                        .set_len(*pre_len)
915                        // The truncate is complete the moment set_len
916                        // returns; the tracked length must advance on
917                        // set_len alone. Keying it on the fsync too would
918                        // leave the tracking at the post-append value
919                        // while the file is already cut back — the next
920                        // append would then pwrite at a past-EOF offset
921                        // and extend the file with a zero hole that parses
922                        // as a phantom record.
923                        .is_ok()
924                {
925                    self.active_len = *pre_len;
926                    let _ = self.active.sync_all();
927                }
928            } else {
929                // A segment sealed mid-batch: its bytes were fsynced at the
930                // seal, so truncate through a fresh handle.
931                let path = segment_path(&self.dir, *segment_id);
932                let ends_where_left = std::fs::metadata(&path)
933                    .map(|metadata| metadata.len() == *post_len)
934                    .unwrap_or(false);
935                if !ends_where_left {
936                    continue;
937                }
938                if let Ok(file) = OpenOptions::new().write(true).open(&path) {
939                    let _ = file.set_len(*pre_len).and_then(|()| file.sync_all());
940                }
941            }
942        }
943    }
944}
945
946/// Read-only handle cache over segment files: approximate LRU (probe
947/// recency is per-open, insert stamps a fresh clock), mirroring the
948/// compute-side blob cache's granularity. The capacity is fixed at
949/// construction; an eviction never closes a handle an outstanding read still
950/// holds (reads carry their own `Arc`).
951struct SegmentHandles {
952    dir: PathBuf,
953    inner: Mutex<HandleCacheInner>,
954}
955
956struct HandleCacheInner {
957    map: HashMap<u32, (Arc<File>, u64)>,
958    /// Recency index mirroring `map`: stamp → segment id. Every touch
959    /// assigns the next clock value, so stamps are unique and the first
960    /// entry is always the single least-recently-used victim — eviction
961    /// is a `pop_first`, not a scan for the minimum.
962    stamps: BTreeMap<u64, u32>,
963    clock: u64,
964    capacity: usize,
965}
966
967impl SegmentHandles {
968    fn new(root: &Path) -> Self {
969        Self {
970            dir: blob_segments_dir(root),
971            inner: Mutex::new(HandleCacheInner {
972                map: HashMap::new(),
973                stamps: BTreeMap::new(),
974                clock: 0,
975                capacity: segment_handle_cache_capacity(),
976            }),
977        }
978    }
979
980    /// A read handle for `segment_id`, from the cache when warm. A missing
981    /// segment file is corruption — recovery truncates or errors at open,
982    /// so a referenced segment that cannot be opened was deleted or
983    /// renamed underneath the store.
984    fn open(&self, segment_id: u32) -> Result<Arc<File>, RegistryError> {
985        let mut guard = match self.inner.lock() {
986            Ok(guard) => guard,
987            Err(_) => return Err(RegistryError::LockPoisoned),
988        };
989        // Warm hit: restamp with the next clock value so the recency index
990        // has no ties, and hand out a clone of the handle. The Arc clone
991        // and stamp copy end the map borrow before the stamps index is
992        // touched (both live behind the same MutexGuard deref).
993        if let Some((file, old_stamp)) = guard
994            .map
995            .get_mut(&segment_id)
996            .map(|(file, stamp)| (Arc::clone(file), *stamp))
997        {
998            guard.stamps.remove(&old_stamp);
999            guard.clock += 1;
1000            let now = guard.clock;
1001            guard.stamps.insert(now, segment_id);
1002            guard
1003                .map
1004                .get_mut(&segment_id)
1005                .expect("entry was present under the cache lock")
1006                .1 = now;
1007            return Ok(file);
1008        }
1009        let file = File::open(segment_path(&self.dir, segment_id)).map_err(|error| match error
1010            .kind()
1011        {
1012            std::io::ErrorKind::NotFound => RegistryError::BlobCorrupt {
1013                reason: format!("segment file {segment_id:010} is missing"),
1014            },
1015            _ => RegistryError::BlobIo(error.to_string()),
1016        })?;
1017        guard.clock += 1;
1018        let stamp = guard.clock;
1019        let file = Arc::new(file);
1020        guard.map.insert(segment_id, (Arc::clone(&file), stamp));
1021        guard.stamps.insert(stamp, segment_id);
1022        // Evict least-recently-stamped handles until the cache fits.
1023        while guard.map.len() > guard.capacity {
1024            let (_, victim) = guard.stamps.pop_first().expect(
1025                "the recency index mirrors the map, so it is non-empty whenever the map is",
1026            );
1027            guard.map.remove(&victim);
1028        }
1029        Ok(file)
1030    }
1031
1032    /// Cached-handle count (tests).
1033    #[cfg(test)]
1034    fn len(&self) -> usize {
1035        match self.inner.lock() {
1036            Ok(guard) => guard.map.len(),
1037            Err(_) => 0,
1038        }
1039    }
1040}
1041
1042/// Read one segment record and verify its header and CRC.
1043fn read_record(
1044    handles: &SegmentHandles,
1045    id: StrHash,
1046    locator: &Locator,
1047) -> Result<Vec<u8>, RegistryError> {
1048    let file = handles.open(locator.segment)?;
1049    let mut header = [0u8; RECORD_HEADER_BYTES];
1050    file.read_exact_at(&mut header, locator.offset)
1051        .map_err(|error| record_io_error(id, locator, error))?;
1052    let record_len = u32::from_le_bytes(header[0..4].try_into().unwrap());
1053    let crc = u32::from_le_bytes(header[4..8].try_into().unwrap());
1054    if record_len != locator.len {
1055        return Err(RegistryError::BlobCorrupt {
1056            reason: format!(
1057                "blob {id}: segment {} record at {} declares {record_len} bytes, its locator \
1058                 says {}",
1059                locator.segment, locator.offset, locator.len
1060            ),
1061        });
1062    }
1063    // Puts enforce the store-wide blob size limit, so a locator (or a
1064    // header agreeing with it) beyond it is index corruption — reject
1065    // before the allocation rather than attempting a multi-gigabyte read
1066    // that would fail at EOF anyway.
1067    if locator.len as usize > MAX_BLOB_BYTES {
1068        return Err(RegistryError::BlobCorrupt {
1069            reason: format!(
1070                "blob {id}: segment {} locator length {} exceeds the {} byte blob limit",
1071                locator.segment, locator.len, MAX_BLOB_BYTES
1072            ),
1073        });
1074    }
1075    let mut payload = vec![0u8; locator.len as usize];
1076    file.read_exact_at(&mut payload, locator.offset + RECORD_HEADER_BYTES as u64)
1077        .map_err(|error| record_io_error(id, locator, error))?;
1078    if crc32(&payload) != crc {
1079        return Err(RegistryError::BlobCorrupt {
1080            reason: format!(
1081                "blob {id}: segment {} record at {} fails its CRC (storage corruption)",
1082                locator.segment, locator.offset
1083            ),
1084        });
1085    }
1086    Ok(payload)
1087}
1088
1089/// A record read that hit EOF or I/O failure is corruption of that record,
1090/// not a store-level I/O configuration problem.
1091fn record_io_error(id: StrHash, locator: &Locator, error: std::io::Error) -> RegistryError {
1092    match error.kind() {
1093        std::io::ErrorKind::UnexpectedEof => RegistryError::BlobCorrupt {
1094            reason: format!(
1095                "blob {id}: segment {} record at {} runs past the end of the file",
1096                locator.segment, locator.offset
1097            ),
1098        },
1099        _ => RegistryError::BlobIo(error.to_string()),
1100    }
1101}
1102
1103/// Create `seg-{id:010}.bin` and fsync its directory entry. The handle is
1104/// the writer's: opened for explicit-offset writes, not append mode,
1105/// because pwrite on an O_APPEND descriptor ignores the offset on Linux
1106/// (see [`SegmentWriter`]). Creation never truncates: segment ids only
1107/// advance past every existing file, and an unexplained file at the next
1108/// id must not be zeroed on open.
1109fn create_segment_file(dir: &Path, segment_id: u32) -> Result<File, RegistryError> {
1110    let file = OpenOptions::new()
1111        .create(true)
1112        .read(true)
1113        .write(true)
1114        .truncate(false)
1115        .open(segment_path(dir, segment_id))
1116        .map_err(|error| RegistryError::BlobIo(error.to_string()))?;
1117    File::open(dir)
1118        .and_then(|dir_handle| dir_handle.sync_all())
1119        .map_err(|error| RegistryError::BlobIo(error.to_string()))?;
1120    Ok(file)
1121}
1122
1123/// `seg-{id:010}.bin` under `dir`.
1124fn segment_path(dir: &Path, segment_id: u32) -> PathBuf {
1125    dir.join(format!("seg-{segment_id:010}.bin"))
1126}
1127
1128/// Sorted segment ids present in `dir`.
1129fn segment_ids(dir: &Path) -> Result<Vec<u32>, RegistryError> {
1130    let entries =
1131        std::fs::read_dir(dir).map_err(|error| RegistryError::BlobIo(error.to_string()))?;
1132    let mut ids = Vec::new();
1133    for entry in entries {
1134        let entry = entry.map_err(|error| RegistryError::BlobIo(error.to_string()))?;
1135        let file_name = entry.file_name();
1136        let Some(digits) = file_name
1137            .to_str()
1138            .and_then(|name| name.strip_prefix("seg-"))
1139            .and_then(|rest| rest.strip_suffix(".bin"))
1140        else {
1141            continue;
1142        };
1143        if let Ok(id) = digits.parse::<u32>() {
1144            ids.push(id);
1145        }
1146    }
1147    ids.sort_unstable();
1148    Ok(ids)
1149}
1150
1151/// Meta key for a segment's committed durable length (`default` CF).
1152fn durable_len_key(segment_id: u32) -> [u8; 10] {
1153    let mut key = [0u8; 10];
1154    key[0..6].copy_from_slice(b"seglen");
1155    key[6..10].copy_from_slice(&segment_id.to_le_bytes());
1156    key
1157}
1158
1159/// A segment's committed durable length; `None` when no entry exists
1160/// (nothing was ever committed into that segment — see the recovery notes
1161/// on [`SegmentSet::open`] for why absent and zero must stay distinct).
1162fn durable_len(index: &BlobIndex, segment_id: u32) -> Result<Option<u64>, RegistryError> {
1163    let value = index
1164        .get_meta(&durable_len_key(segment_id))
1165        .map_err(RegistryError::from)?;
1166    match value {
1167        None => Ok(None),
1168        Some(bytes) => match <[u8; 8]>::try_from(bytes.as_slice()) {
1169            Ok(bytes) => Ok(Some(u64::from_le_bytes(bytes))),
1170            Err(_) => Err(RegistryError::BlobCorrupt {
1171                reason: format!(
1172                    "durable-length entry of segment {segment_id} is {} bytes, expected 8",
1173                    bytes.len()
1174                ),
1175            }),
1176        },
1177    }
1178}
1179
1180fn crc32(payload: &[u8]) -> u32 {
1181    let mut hasher = crc32fast::Hasher::new();
1182    hasher.update(payload);
1183    hasher.finalize()
1184}
1185
1186/// Encode an inline index value: tag followed by the payload bytes.
1187fn encode_inline(payload: &[u8]) -> Vec<u8> {
1188    let mut value = Vec::with_capacity(1 + payload.len());
1189    value.push(INLINE_TAG);
1190    value.extend_from_slice(payload);
1191    value
1192}
1193
1194/// Encode a segment locator index value.
1195fn encode_locator(segment_id: u32, offset: u64, len: u32) -> Vec<u8> {
1196    let mut value = Vec::with_capacity(1 + 16);
1197    value.push(SEGMENT_TAG);
1198    value.extend_from_slice(&segment_id.to_le_bytes());
1199    value.extend_from_slice(&offset.to_le_bytes());
1200    value.extend_from_slice(&len.to_le_bytes());
1201    value
1202}
1203
1204/// Decode one index value into its tier.
1205fn decode_entry(id: StrHash, value: &[u8]) -> Result<DecodedEntry, RegistryError> {
1206    let Some((&tag, rest)) = value.split_first() else {
1207        return Err(RegistryError::BlobCorrupt {
1208            reason: format!("blob {id}: empty index value"),
1209        });
1210    };
1211    match tag {
1212        INLINE_TAG => Ok(DecodedEntry::Inline(rest.to_vec())),
1213        SEGMENT_TAG => match decode_locator(rest) {
1214            Some(locator) => Ok(DecodedEntry::Segment(locator)),
1215            None => Err(RegistryError::BlobCorrupt {
1216                reason: format!("blob {id}: malformed segment locator"),
1217            }),
1218        },
1219        other => Err(RegistryError::BlobCorrupt {
1220            reason: format!("blob {id}: unknown index tag {other}"),
1221        }),
1222    }
1223}
1224
1225/// The tier an index value decodes to.
1226enum DecodedEntry {
1227    Inline(Vec<u8>),
1228    Segment(Locator),
1229}
1230
1231/// Parse `segment_id u32 | offset u64 | len u32` (little-endian).
1232fn decode_locator(bytes: &[u8]) -> Option<Locator> {
1233    Some(Locator {
1234        segment: u32::from_le_bytes(bytes.get(0..4)?.try_into().ok()?),
1235        offset: u64::from_le_bytes(bytes.get(4..12)?.try_into().ok()?),
1236        len: u32::from_le_bytes(bytes.get(12..16)?.try_into().ok()?),
1237    })
1238}
1239
1240/// Parse a 16-byte index key back into a [`StrHash`].
1241fn hash_from_key(key: &[u8]) -> Option<StrHash> {
1242    Some(StrHash::from_be_bytes(key.try_into().ok()?))
1243}
1244
1245/// Whether `root` still contains the old `blobs/{xx}/*.bin` layout.
1246fn legacy_layout_present(root: &Path) -> Result<bool, RegistryError> {
1247    let entries =
1248        std::fs::read_dir(root).map_err(|error| RegistryError::BlobIo(error.to_string()))?;
1249    for entry in entries {
1250        let entry = entry.map_err(|error| RegistryError::BlobIo(error.to_string()))?;
1251        let name = entry.file_name();
1252        let Some(name) = name.to_str() else {
1253            continue;
1254        };
1255        if name.len() != 2 || !name.bytes().all(|byte| byte.is_ascii_hexdigit()) {
1256            continue;
1257        }
1258        let file_type = entry
1259            .file_type()
1260            .map_err(|error| RegistryError::BlobIo(error.to_string()))?;
1261        if !file_type.is_dir() {
1262            continue;
1263        }
1264        let shard = entry.path();
1265        for file in
1266            std::fs::read_dir(&shard).map_err(|error| RegistryError::BlobIo(error.to_string()))?
1267        {
1268            let file = file.map_err(|error| RegistryError::BlobIo(error.to_string()))?;
1269            if file.file_name().to_string_lossy().ends_with(".bin") {
1270                return Ok(true);
1271            }
1272        }
1273    }
1274    Ok(false)
1275}
1276
1277#[cfg(test)]
1278mod tests {
1279    use super::*;
1280    use pretty_assertions::assert_eq;
1281
1282    /// The segment-target and handle-cache overrides are process-wide, so
1283    /// tests that set them serialize against each other (parallel test
1284    /// threads would otherwise reset one another's override mid-test).
1285    static TUNING: std::sync::Mutex<()> = std::sync::Mutex::new(());
1286
1287    fn tuning_guard() -> std::sync::MutexGuard<'static, ()> {
1288        match TUNING.lock() {
1289            Ok(guard) => guard,
1290            Err(poisoned) => poisoned.into_inner(),
1291        }
1292    }
1293
1294    fn store() -> (tempfile::TempDir, BlobStore) {
1295        let dir = tempfile::tempdir().unwrap();
1296        let store = BlobStore::open(dir.path().join("blobs")).unwrap();
1297        (dir, store)
1298    }
1299
1300    /// The raw index value of one id (tier assertions need the tag byte).
1301    fn index_value(store: &BlobStore, id: StrHash) -> Vec<u8> {
1302        let BlobStoreInner::Index { index, .. } = &store.inner else {
1303            panic!("index-backed store required");
1304        };
1305        index.get(&id.to_be_bytes()).unwrap().expect("present")
1306    }
1307
1308    #[test]
1309    fn empty_payload_is_rejected() {
1310        // An empty payload chunks to zero frames on the streamed read
1311        // path, so it would read back as a miss, never as an empty hit —
1312        // the store rejects it at the boundary instead, on both variants.
1313        let (_dir, store) = store();
1314        let id = StrHash::from_bytes(b"");
1315        assert!(matches!(
1316            store.put(id, b"").unwrap_err(),
1317            RegistryError::BlobEmpty { id: rejected } if rejected == id
1318        ));
1319        assert_eq!(store.get(&[id]).unwrap(), vec![None]);
1320        let memory = BlobStore::memory();
1321        assert!(matches!(
1322            memory.put(id, b"").unwrap_err(),
1323            RegistryError::BlobEmpty { .. }
1324        ));
1325    }
1326
1327    #[test]
1328    fn put_then_get_round_trip() {
1329        let (_dir, store) = store();
1330        let payload = b"POINT EWKB bytes".to_vec();
1331        let id = StrHash::from_bytes(&payload);
1332        store.put(id, &payload).unwrap();
1333        assert_eq!(store.get(&[id]).unwrap(), vec![Some(payload.clone())]);
1334        let missing = StrHash::new("http://ex/not-a-blob");
1335        assert_eq!(store.get(&[id, missing]).unwrap()[1], None);
1336    }
1337
1338    #[test]
1339    fn put_is_idempotent_and_never_rewrites() {
1340        let (_dir, store) = store();
1341        let payload = b"payload-A".to_vec();
1342        let id = StrHash::from_bytes(&payload);
1343        assert_eq!(store.put(id, &payload).unwrap(), payload.len() as u64);
1344        assert_eq!(store.put(id, &payload).unwrap(), 0);
1345        assert_eq!(store.get(&[id]).unwrap(), vec![Some(payload)]);
1346    }
1347
1348    #[test]
1349    fn inline_threshold_boundary_places_tiers() {
1350        let (_dir, store) = store();
1351        let inline = vec![7u8; INLINE_THRESHOLD_BYTES];
1352        let segment = vec![7u8; INLINE_THRESHOLD_BYTES + 1];
1353        let inline_id = StrHash::from_bytes(&inline);
1354        let segment_id = StrHash::from_bytes(&segment);
1355        store.put(inline_id, &inline).unwrap();
1356        store.put(segment_id, &segment).unwrap();
1357        assert_eq!(index_value(&store, inline_id)[0], INLINE_TAG);
1358        assert_eq!(index_value(&store, segment_id)[0], SEGMENT_TAG);
1359        assert_eq!(
1360            store.get(&[inline_id, segment_id]).unwrap(),
1361            vec![Some(inline), Some(segment)]
1362        );
1363    }
1364
1365    #[test]
1366    fn mixed_batch_round_trips_both_tiers() {
1367        let (_dir, store) = store();
1368        let small = b"inline payload".to_vec();
1369        let large = vec![9u8; INLINE_THRESHOLD_BYTES * 3];
1370        let small_id = StrHash::from_bytes(&small);
1371        let large_id = StrHash::from_bytes(&large);
1372        store
1373            .put_blobs(&[
1374                (small_id, Arc::from(small.clone())),
1375                (large_id, Arc::from(large.clone())),
1376            ])
1377            .unwrap();
1378        assert_eq!(
1379            store.get(&[small_id, large_id]).unwrap(),
1380            vec![Some(small), Some(large)]
1381        );
1382    }
1383
1384    #[test]
1385    fn segment_tier_survives_reopen() {
1386        let (dir, store) = store();
1387        let payloads: Vec<Vec<u8>> = (0..4)
1388            .map(|index| {
1389                let mut payload = vec![index as u8; INLINE_THRESHOLD_BYTES + 64 + index * 32];
1390                payload[0] = index as u8;
1391                payload
1392            })
1393            .collect();
1394        let ids: Vec<StrHash> = payloads.iter().map(|p| StrHash::from_bytes(p)).collect();
1395        store
1396            .put_blobs(
1397                &ids.iter()
1398                    .zip(&payloads)
1399                    .map(|(id, payload)| (*id, Arc::from(payload.as_slice())))
1400                    .collect::<Vec<_>>(),
1401            )
1402            .unwrap();
1403        drop(store);
1404        // Reopen: recovery reads the durable lengths, and every locator
1405        // must still resolve to its payload.
1406        let reopened = BlobStore::open(dir.path().join("blobs")).unwrap();
1407        let got = reopened.get(&ids).unwrap();
1408        for (got, payload) in got.into_iter().zip(&payloads) {
1409            assert_eq!(got.as_deref(), Some(payload.as_slice()));
1410        }
1411    }
1412
1413    #[test]
1414    fn rollover_creates_segments_and_keeps_reads_correct() {
1415        let _tuning = tuning_guard();
1416        // Two large payloads with a roll target that fits only the first:
1417        // the first append must land in segment 0, the second in segment 1.
1418        let _target = set_segment_target_bytes(INLINE_THRESHOLD_BYTES + 128);
1419        let (dir, store) = store();
1420        let a = vec![1u8; INLINE_THRESHOLD_BYTES + 32];
1421        let b = vec![2u8; INLINE_THRESHOLD_BYTES + 32];
1422        let a_id = StrHash::from_bytes(&a);
1423        let b_id = StrHash::from_bytes(&b);
1424        store.put(a_id, &a).unwrap();
1425        store.put(b_id, &b).unwrap();
1426        let segments = segment_ids(&blob_segments_dir(dir.path().join("blobs"))).unwrap();
1427        assert_eq!(segments, vec![0, 1], "the second append must roll");
1428        assert_eq!(
1429            store.get(&[a_id, b_id]).unwrap(),
1430            vec![Some(a.clone()), Some(b.clone())]
1431        );
1432        drop(store);
1433        let reopened = BlobStore::open(dir.path().join("blobs")).unwrap();
1434        assert_eq!(reopened.get(&[a_id, b_id]).unwrap(), vec![Some(a), Some(b)]);
1435    }
1436
1437    #[test]
1438    fn torn_tail_is_truncated_on_reopen() {
1439        // Asserts on segment 0's file length: serialize against the
1440        // process-wide roll-target overrides other tests install.
1441        let _tuning = tuning_guard();
1442        let (dir, store) = store();
1443        let payload = vec![5u8; INLINE_THRESHOLD_BYTES + 48];
1444        let id = StrHash::from_bytes(&payload);
1445        store.put(id, &payload).unwrap();
1446        drop(store);
1447        // Simulate a crash mid-append: append garbage past the committed
1448        // durable length of the active segment.
1449        let segments_dir = blob_segments_dir(dir.path().join("blobs"));
1450        let segment_file = segment_path(&segments_dir, 0);
1451        let length = std::fs::metadata(&segment_file).unwrap().len();
1452        let file = OpenOptions::new().append(true).open(&segment_file).unwrap();
1453        file.write_all_at(b"torn bytes", length).unwrap();
1454        drop(file);
1455        let reopened = BlobStore::open(dir.path().join("blobs")).unwrap();
1456        assert_eq!(
1457            reopened.get(&[id]).unwrap(),
1458            vec![Some(payload)],
1459            "the committed record survives; the torn tail is gone"
1460        );
1461        assert_eq!(
1462            std::fs::metadata(&segment_file).unwrap().len(),
1463            length,
1464            "recovery truncated the file back to its durable length"
1465        );
1466    }
1467
1468    #[test]
1469    fn index_loss_leaves_segments_intact() {
1470        // The segment-file length assertions below assume the default roll
1471        // target, so this test also serializes against the tuning overrides.
1472        let _tuning = tuning_guard();
1473        // Losing or rebuilding the index DB must not destroy the segment
1474        // tier: every durable-length entry disappears with it, and a
1475        // segment with no entry is never truncated. The bytes become
1476        // unreachable (no locators) but survive for inspection/vacuum.
1477        let (dir, store) = store();
1478        let payload = vec![5u8; INLINE_THRESHOLD_BYTES + 64];
1479        let id = StrHash::from_bytes(&payload);
1480        store.put(id, &payload).unwrap();
1481        drop(store);
1482        let segments_dir = blob_segments_dir(dir.path().join("blobs"));
1483        let intact_len = std::fs::metadata(segment_path(&segments_dir, 0))
1484            .unwrap()
1485            .len();
1486        assert!(intact_len > 0);
1487
1488        std::fs::remove_dir_all(blob_index_dir(dir.path().join("blobs"))).unwrap();
1489        let reopened = BlobStore::open(dir.path().join("blobs")).unwrap();
1490        assert_eq!(
1491            std::fs::metadata(segment_path(&segments_dir, 0))
1492                .unwrap()
1493                .len(),
1494            intact_len,
1495            "recovery must not truncate a segment with no durable-length entry"
1496        );
1497        // No locators exist in the fresh index, so the blob reads as a
1498        // miss — unreachable, not destroyed.
1499        assert_eq!(reopened.get(&[id]).unwrap(), vec![None]);
1500        // Verify names this state explicitly instead of counting every
1501        // record as a plain orphan.
1502        let report = reopened.verify().unwrap();
1503        assert!(
1504            report
1505                .problems
1506                .iter()
1507                .any(|problem| problem.contains("index is empty but segments hold")),
1508            "{:?}",
1509            report.problems
1510        );
1511        // The store still works: a new put appends past the surviving
1512        // bytes and commits its own durable length.
1513        let fresh = vec![6u8; INLINE_THRESHOLD_BYTES + 32];
1514        let fresh_id = StrHash::from_bytes(&fresh);
1515        reopened.put(fresh_id, &fresh).unwrap();
1516        assert_eq!(reopened.get(&[fresh_id]).unwrap(), vec![Some(fresh)]);
1517        assert!(
1518            std::fs::metadata(segment_path(&segments_dir, 0))
1519                .unwrap()
1520                .len()
1521                > intact_len
1522        );
1523    }
1524
1525    #[test]
1526    fn segment_without_meta_keeps_bytes_and_appends_past() {
1527        // The crash-during-first-batch shape: a segment file holds bytes,
1528        // but no batch ever committed (no durable-length entry, empty
1529        // index). Open must neither judge nor truncate those bytes; the
1530        // next append lands past them.
1531        let dir = tempfile::tempdir().unwrap();
1532        let root = dir.path().join("blobs");
1533        let segments_dir = blob_segments_dir(&root);
1534        std::fs::create_dir_all(&segments_dir).unwrap();
1535        let orphan_tail = b"orphan bytes from an interrupted first batch";
1536        std::fs::write(segment_path(&segments_dir, 0), orphan_tail).unwrap();
1537
1538        let store = BlobStore::open(&root).unwrap();
1539        assert_eq!(
1540            std::fs::metadata(segment_path(&segments_dir, 0))
1541                .unwrap()
1542                .len(),
1543            orphan_tail.len() as u64,
1544            "no committed durable length means no truncation"
1545        );
1546        let payload = vec![7u8; INLINE_THRESHOLD_BYTES + 48];
1547        let id = StrHash::from_bytes(&payload);
1548        store.put(id, &payload).unwrap();
1549        let file_len = std::fs::metadata(segment_path(&segments_dir, 0))
1550            .unwrap()
1551            .len();
1552        assert!(
1553            file_len > orphan_tail.len() as u64,
1554            "the new record appends past the surviving bytes"
1555        );
1556        assert_eq!(store.get(&[id]).unwrap(), vec![Some(payload.clone())]);
1557
1558        // Reopen: the committed durable length now exists and covers the
1559        // real record; the leading orphan bytes sit below it and stay.
1560        drop(store);
1561        let reopened = BlobStore::open(&root).unwrap();
1562        assert_eq!(
1563            std::fs::metadata(segment_path(&segments_dir, 0))
1564                .unwrap()
1565                .len(),
1566            file_len
1567        );
1568        assert_eq!(reopened.get(&[id]).unwrap(), vec![Some(payload)]);
1569    }
1570
1571    #[test]
1572    fn segment_shorter_than_durable_length_is_corruption() {
1573        let (dir, store) = store();
1574        let payload = vec![5u8; INLINE_THRESHOLD_BYTES + 48];
1575        store.put(StrHash::from_bytes(&payload), &payload).unwrap();
1576        drop(store);
1577        // Shrink the segment below its committed durable length (hardware
1578        // failure class): open must refuse.
1579        let segment_file = segment_path(&blob_segments_dir(dir.path().join("blobs")), 0);
1580        let file = OpenOptions::new().write(true).open(&segment_file).unwrap();
1581        file.set_len(8).unwrap();
1582        drop(file);
1583        let error = BlobStore::open(dir.path().join("blobs")).unwrap_err();
1584        assert!(
1585            matches!(error, RegistryError::BlobCorrupt { .. }),
1586            "expected BlobCorrupt, got {error:?}"
1587        );
1588    }
1589
1590    #[test]
1591    fn crc_mismatch_is_corrupt_not_a_miss() {
1592        // Patches bytes inside segment 0: serialize against the
1593        // process-wide roll-target overrides other tests install.
1594        let _tuning = tuning_guard();
1595        let (dir, store) = store();
1596        let payload = vec![3u8; INLINE_THRESHOLD_BYTES + 16];
1597        let id = StrHash::from_bytes(&payload);
1598        store.put(id, &payload).unwrap();
1599        drop(store);
1600        // Flip one payload byte inside the committed record (header is 8
1601        // bytes; hit the middle of the payload region).
1602        let segment_file = segment_path(&blob_segments_dir(dir.path().join("blobs")), 0);
1603        let length = std::fs::metadata(&segment_file).unwrap().len();
1604        let mut bytes = vec![0u8; length as usize];
1605        File::open(&segment_file)
1606            .unwrap()
1607            .read_exact_at(&mut bytes, 0)
1608            .unwrap();
1609        let flip_at = 8 + payload.len() / 2;
1610        bytes[flip_at] ^= 0xff;
1611        let file = OpenOptions::new().write(true).open(&segment_file).unwrap();
1612        file.write_all_at(&bytes, 0).unwrap();
1613        drop(file);
1614        let reopened = BlobStore::open(dir.path().join("blobs")).unwrap();
1615        let error = reopened.get(&[id]).unwrap_err();
1616        assert!(
1617            matches!(error, RegistryError::BlobCorrupt { .. }),
1618            "expected BlobCorrupt, got {error:?}"
1619        );
1620    }
1621
1622    #[test]
1623    fn missing_segment_file_is_corrupt() {
1624        // Deletes segment 0: serialize against the process-wide
1625        // roll-target overrides other tests install.
1626        let _tuning = tuning_guard();
1627        let (dir, store) = store();
1628        let payload = vec![4u8; INLINE_THRESHOLD_BYTES + 16];
1629        let id = StrHash::from_bytes(&payload);
1630        store.put(id, &payload).unwrap();
1631        drop(store);
1632        std::fs::remove_file(segment_path(
1633            &blob_segments_dir(dir.path().join("blobs")),
1634            0,
1635        ))
1636        .unwrap();
1637        let reopened = BlobStore::open(dir.path().join("blobs")).unwrap();
1638        let error = reopened.get(&[id]).unwrap_err();
1639        assert!(
1640            matches!(error, RegistryError::BlobCorrupt { .. }),
1641            "expected BlobCorrupt, got {error:?}"
1642        );
1643    }
1644
1645    #[test]
1646    fn handle_cache_evicts_and_still_serves_reads() {
1647        let _tuning = tuning_guard();
1648        let _cache = set_segment_handle_cache(1);
1649        let (_dir, store) = store();
1650        let _target = set_segment_target_bytes(INLINE_THRESHOLD_BYTES + 64);
1651        let a = vec![1u8; INLINE_THRESHOLD_BYTES + 16];
1652        let b = vec![2u8; INLINE_THRESHOLD_BYTES + 16];
1653        let a_id = StrHash::from_bytes(&a);
1654        let b_id = StrHash::from_bytes(&b);
1655        store.put(a_id, &a).unwrap();
1656        store.put(b_id, &b).unwrap();
1657        let BlobStoreInner::Index { handles, .. } = &store.inner else {
1658            panic!("index-backed store required");
1659        };
1660        // Alternate reads: each open of the cold segment evicts the other.
1661        for _ in 0..3 {
1662            assert_eq!(
1663                store.get(&[a_id, b_id]).unwrap(),
1664                vec![Some(a.clone()), Some(b.clone())]
1665            );
1666            assert!(
1667                handles.len() <= 1,
1668                "capacity 1 must hold at most one handle"
1669            );
1670        }
1671    }
1672
1673    #[test]
1674    fn partial_write_does_not_desync_the_next_append() {
1675        // A torn append (ENOSPC or EIO partway through a record) leaves the
1676        // segment file longer than the writer's tracked length. Reproduce
1677        // that state by appending junk bytes behind the writer's back, then
1678        // verify the NEXT record lands at the tracked offset — overwriting
1679        // the junk — rather than at end-of-file. With an append-mode
1680        // handle, pwrite ignores the offset on Linux, the next record
1681        // appends past the junk, and its locator commits a stale offset:
1682        // the blob reads back garbage and every later durable length
1683        // freezes the misalignment in place.
1684        let _tuning = tuning_guard();
1685        let (dir, store) = store();
1686        let first = vec![1u8; INLINE_THRESHOLD_BYTES + 64];
1687        let first_id = StrHash::from_bytes(&first);
1688        store.put(first_id, &first).unwrap();
1689        let segments_dir = blob_segments_dir(dir.path().join("blobs"));
1690        let seg0 = segment_path(&segments_dir, 0);
1691        let committed_len = std::fs::metadata(&seg0).unwrap().len();
1692
1693        // The torn tail: bytes past the committed durable length, exactly
1694        // what a partially written next record would leave behind.
1695        let torn = b"torn partial record bytes";
1696        let tail = OpenOptions::new().append(true).open(&seg0).unwrap();
1697        tail.write_all_at(torn, committed_len).unwrap();
1698        drop(tail);
1699        assert_eq!(
1700            std::fs::metadata(&seg0).unwrap().len(),
1701            committed_len + torn.len() as u64
1702        );
1703
1704        // The next put must write AT the tracked offset, not past the junk.
1705        let second = vec![2u8; INLINE_THRESHOLD_BYTES + 48];
1706        let second_id = StrHash::from_bytes(&second);
1707        store.put(second_id, &second).unwrap();
1708        assert_eq!(store.get(&[first_id]).unwrap(), vec![Some(first.clone())]);
1709        assert_eq!(store.get(&[second_id]).unwrap(), vec![Some(second.clone())]);
1710
1711        // Exact length proves the overwrite: committed bytes plus the
1712        // second record, with the torn tail gone — not pushed past the end.
1713        let second_record = (RECORD_HEADER_BYTES + second.len()) as u64;
1714        assert_eq!(
1715            std::fs::metadata(&seg0).unwrap().len(),
1716            committed_len + second_record
1717        );
1718
1719        // Reopen: the committed durable length equals the file length, so
1720        // recovery has nothing to truncate and both records stay readable.
1721        drop(store);
1722        let reopened = BlobStore::open(dir.path().join("blobs")).unwrap();
1723        assert_eq!(
1724            std::fs::metadata(&seg0).unwrap().len(),
1725            committed_len + second_record
1726        );
1727        assert_eq!(
1728            reopened.get(&[first_id, second_id]).unwrap(),
1729            vec![Some(first), Some(second)]
1730        );
1731    }
1732
1733    #[test]
1734    fn truncate_touched_cuts_a_failed_batch_back() {
1735        let _tuning = tuning_guard();
1736        let (dir, store) = store();
1737        let payload = vec![6u8; INLINE_THRESHOLD_BYTES + 32];
1738        let id = StrHash::from_bytes(&payload);
1739        store.put(id, &payload).unwrap();
1740        let BlobStoreInner::Index { segments, .. } = &store.inner else {
1741            panic!("index-backed store required");
1742        };
1743        let mut writer = segments.lock().unwrap();
1744        let before = writer.active_len;
1745        // Simulate the append side of a batch that then fails to commit.
1746        let orphan = vec![8u8; INLINE_THRESHOLD_BYTES + 8];
1747        let (segment, offset, _len, after) = writer.append(&orphan).unwrap();
1748        assert_eq!(segment, writer.active_id);
1749        let mut touched = HashMap::new();
1750        touched.insert(segment, (offset, after));
1751        writer.truncate_touched(&touched);
1752        assert_eq!(
1753            writer.active_len, before,
1754            "the truncate restores the length"
1755        );
1756        drop(writer);
1757        // The store never learned the orphan; the committed record is intact
1758        // and no locator references the removed bytes.
1759        assert_eq!(store.get(&[id]).unwrap(), vec![Some(payload)]);
1760        drop(store);
1761        let reopened = BlobStore::open(dir.path().join("blobs")).unwrap();
1762        let expected = vec![6u8; INLINE_THRESHOLD_BYTES + 32];
1763        assert_eq!(reopened.get(&[id]).unwrap(), vec![Some(expected)]);
1764    }
1765
1766    #[test]
1767    fn verify_flags_a_locator_pointing_at_another_blobs_record() {
1768        // Redirecting one blob's index entry at another blob's record is
1769        // invisible to the CRC (the bytes are exactly what was written);
1770        // only the payload-identity check can catch it.
1771        let _tuning = tuning_guard();
1772        let (_dir, store) = store();
1773        let a = vec![1u8; INLINE_THRESHOLD_BYTES + 16];
1774        let b = vec![2u8; INLINE_THRESHOLD_BYTES + 32];
1775        let a_id = StrHash::from_bytes(&a);
1776        let b_id = StrHash::from_bytes(&b);
1777        store.put(a_id, &a).unwrap();
1778        store.put(b_id, &b).unwrap();
1779
1780        // Replace b's entry with a's raw value (a's locator) and drop a's
1781        // own entry, so exactly one locator points at a's record — the
1782        // clean statement of "locator says b, record holds a".
1783        let BlobStoreInner::Index { index, .. } = &store.inner else {
1784            unreachable!("store() opens an index-backed store");
1785        };
1786        let a_value = index.get(&a_id.to_be_bytes()).unwrap().unwrap();
1787        let mut batch = index.write_batch();
1788        batch.delete(&a_id.to_be_bytes());
1789        batch.insert(&b_id.to_be_bytes(), &a_value);
1790        batch.commit().unwrap();
1791
1792        let report = store.verify().unwrap();
1793        let joined = report.problems.join("\n");
1794        assert!(
1795            joined.contains(&format!("hashes to {a_id}; its locator says {b_id}")),
1796            "{joined}"
1797        );
1798        assert!(
1799            !joined.contains("CRC"),
1800            "the redirected record's bytes are intact; the CRC must pass: {joined}"
1801        );
1802        // b's real record is now unreferenced.
1803        assert_eq!(report.orphan_records, 1);
1804    }
1805
1806    #[test]
1807    fn verify_flags_two_locators_at_one_offset() {
1808        let _tuning = tuning_guard();
1809        let (_dir, store) = store();
1810        let a = vec![3u8; INLINE_THRESHOLD_BYTES + 16];
1811        let b = vec![4u8; INLINE_THRESHOLD_BYTES + 32];
1812        let a_id = StrHash::from_bytes(&a);
1813        let b_id = StrHash::from_bytes(&b);
1814        store.put(a_id, &a).unwrap();
1815        store.put(b_id, &b).unwrap();
1816
1817        // Copy a's locator under b's key without removing a's entry: two
1818        // index entries now resolve to the same record position.
1819        let BlobStoreInner::Index { index, .. } = &store.inner else {
1820            unreachable!("store() opens an index-backed store");
1821        };
1822        let a_value = index.get(&a_id.to_be_bytes()).unwrap().unwrap();
1823        let mut batch = index.write_batch();
1824        batch.insert(&b_id.to_be_bytes(), &a_value);
1825        batch.commit().unwrap();
1826
1827        let report = store.verify().unwrap();
1828        assert!(
1829            report
1830                .problems
1831                .iter()
1832                .any(|problem| problem.contains("both point at segment")),
1833            "{:?}",
1834            report.problems
1835        );
1836    }
1837
1838    #[test]
1839    fn verify_flags_a_locator_length_disagreeing_with_the_record_header() {
1840        // The read path rejects a header/locator length disagreement as
1841        // fatal; the scan must report the same condition instead of
1842        // passing a store whose blob cannot be read.
1843        let _tuning = tuning_guard();
1844        let (_dir, store) = store();
1845        let payload = vec![5u8; INLINE_THRESHOLD_BYTES + 64];
1846        let id = StrHash::from_bytes(&payload);
1847        store.put(id, &payload).unwrap();
1848
1849        // Rewrite the locator with a wrong length (segment and offset
1850        // unchanged) — exactly the corruption the walk must catch.
1851        let BlobStoreInner::Index { index, .. } = &store.inner else {
1852            unreachable!("store() opens an index-backed store");
1853        };
1854        let value = index.get(&id.to_be_bytes()).unwrap().unwrap();
1855        let DecodedEntry::Segment(locator) = decode_entry(id, &value).unwrap() else {
1856            unreachable!("payload above the inline threshold lands in a segment");
1857        };
1858        let wrong_len = locator.len - 8;
1859        let mut batch = index.write_batch();
1860        batch.insert(
1861            &id.to_be_bytes(),
1862            &encode_locator(locator.segment, locator.offset, wrong_len),
1863        );
1864        batch.commit().unwrap();
1865
1866        let report = store.verify().unwrap();
1867        assert_eq!(report.problems.len(), 1, "{:?}", report.problems);
1868        assert!(
1869            report.problems[0].contains(&format!(
1870                "record at {} declares {} bytes, the locator of {id} says {wrong_len}",
1871                locator.offset,
1872                payload.len()
1873            )),
1874            "{:?}",
1875            report.problems
1876        );
1877        // The read path fails on the same store: the scan's verdict and
1878        // the read's verdict must agree.
1879        assert!(matches!(
1880            store.get(&[id]).unwrap_err(),
1881            RegistryError::BlobCorrupt { .. }
1882        ));
1883    }
1884
1885    #[test]
1886    fn verify_reports_unverified_rather_than_dangling_when_the_scan_aborts() {
1887        // The preserved-torn-bytes shape: junk at the head of a segment
1888        // with no durable-length entry is kept, and a later put appends
1889        // past it. The store reads back fine, so the walk aborting at the
1890        // junk header must NOT call the valid record dangling — it must
1891        // report the undecodable header and the unverified locator, and
1892        // nothing else.
1893        let _tuning = tuning_guard();
1894        let dir = tempfile::tempdir().unwrap();
1895        let root = dir.path().join("blobs");
1896        let segments_dir = blob_segments_dir(&root);
1897        std::fs::create_dir_all(&segments_dir).unwrap();
1898        // 16 junk head bytes: "torn" parses as a huge little-endian
1899        // length, so the walk aborts at offset 0.
1900        std::fs::write(segment_path(&segments_dir, 0), b"torn junk bytes!").unwrap();
1901
1902        let store = BlobStore::open(&root).unwrap();
1903        let payload = vec![9u8; INLINE_THRESHOLD_BYTES + 48];
1904        let id = StrHash::from_bytes(&payload);
1905        store.put(id, &payload).unwrap();
1906        // The store is healthy: the blob reads back.
1907        assert_eq!(store.get(&[id]).unwrap(), vec![Some(payload.clone())]);
1908
1909        let report = store.verify().unwrap();
1910        let joined = report.problems.join("\n");
1911        assert!(
1912            joined.contains("byte blob limit"),
1913            "the aborting header problem must be reported: {joined}"
1914        );
1915        assert!(
1916            joined.contains(&format!(
1917                "locator of {id} points at segment 0 offset 16, past the point where the \
1918                 sequential scan aborted (0); the record was not verified"
1919            )),
1920            "{joined}"
1921        );
1922        assert!(
1923            !joined.contains("holds no record"),
1924            "a readable record past the abort point must not be called dangling: {joined}"
1925        );
1926        assert!(
1927            !joined.contains("trailing byte"),
1928            "the abort problem already covers the unparsed region: {joined}"
1929        );
1930        // Exactly the two problems above — no double reporting.
1931        assert_eq!(report.problems.len(), 2, "{joined}");
1932    }
1933
1934    #[test]
1935    fn verify_reports_a_healthy_store_and_finds_corruption() {
1936        // Flips a byte inside segment 0: serialize against the
1937        // process-wide roll-target overrides other tests install.
1938        let _tuning = tuning_guard();
1939        let (dir, store) = store();
1940        let small = b"inline payload".to_vec();
1941        let large = vec![9u8; INLINE_THRESHOLD_BYTES + 24];
1942        let small_id = StrHash::from_bytes(&small);
1943        let large_id = StrHash::from_bytes(&large);
1944        store.put(small_id, &small).unwrap();
1945        store.put(large_id, &large).unwrap();
1946        let report = store.verify().unwrap();
1947        assert_eq!(report.index_entries, 2);
1948        assert_eq!(report.inline_entries, 1);
1949        assert_eq!(report.segment_entries, 1);
1950        assert_eq!(report.orphan_records, 0);
1951        assert!(report.problems.is_empty(), "{:?}", report.problems);
1952        drop(store);
1953        // Corrupt the segment record's payload: verify must name it.
1954        let segment_file = segment_path(&blob_segments_dir(dir.path().join("blobs")), 0);
1955        let length = std::fs::metadata(&segment_file).unwrap().len();
1956        let mut bytes = vec![0u8; length as usize];
1957        File::open(&segment_file)
1958            .unwrap()
1959            .read_exact_at(&mut bytes, 0)
1960            .unwrap();
1961        bytes[8 + 4] ^= 0xff;
1962        let file = OpenOptions::new().write(true).open(&segment_file).unwrap();
1963        file.write_all_at(&bytes, 0).unwrap();
1964        drop(file);
1965        let reopened = BlobStore::open(dir.path().join("blobs")).unwrap();
1966        let report = reopened.verify().unwrap();
1967        assert!(
1968            report
1969                .problems
1970                .iter()
1971                .any(|problem| problem.contains("CRC")),
1972            "{:?}",
1973            report.problems
1974        );
1975    }
1976
1977    #[test]
1978    fn batch_put_is_all_or_nothing_on_hash_mismatch() {
1979        let (_dir, store) = store();
1980        let a = b"alpha".to_vec();
1981        let a_id = StrHash::from_bytes(&a);
1982        let (bad_id, bad) = (StrHash::new("http://ex/bad"), b"mismatched".to_vec());
1983        let error = store
1984            .put_blobs(&[
1985                (a_id, Arc::from(a.clone())),
1986                (bad_id, Arc::from(bad.clone())),
1987            ])
1988            .unwrap_err();
1989        assert!(
1990            matches!(error, RegistryError::BlobHashMismatch { id } if id == bad_id),
1991            "{error:?}"
1992        );
1993        assert_eq!(store.get(&[a_id]).unwrap(), vec![None]);
1994    }
1995
1996    #[test]
1997    fn batch_put_skips_existing_and_duplicate_ids() {
1998        let (_dir, store) = store();
1999        let a = b"alpha".to_vec();
2000        let a_id = StrHash::from_bytes(&a);
2001        let b = vec![1u8; INLINE_THRESHOLD_BYTES + 16];
2002        let b_id = StrHash::from_bytes(&b);
2003        store.put(a_id, &a).unwrap();
2004        store
2005            .put_blobs(&[
2006                (a_id, Arc::from(a.clone())),
2007                (b_id, Arc::from(b.clone())),
2008                (b_id, Arc::from(b.clone())),
2009            ])
2010            .unwrap();
2011        assert_eq!(store.get(&[a_id, b_id]).unwrap(), vec![Some(a), Some(b)]);
2012    }
2013
2014    #[test]
2015    fn batch_put_rejects_empty() {
2016        let (_dir, store) = store();
2017        assert!(matches!(
2018            store.put_blobs(&[]).unwrap_err(),
2019            RegistryError::EmptyBlobBatch
2020        ));
2021    }
2022
2023    #[test]
2024    fn reject_above_the_64mib_limit() {
2025        let (_dir, store) = store();
2026        let oversized = vec![0u8; MAX_BLOB_BYTES + 1];
2027        let error = store
2028            .put(StrHash::from_bytes(&oversized), &oversized)
2029            .unwrap_err();
2030        assert!(matches!(error, RegistryError::BlobTooLarge { .. }));
2031    }
2032
2033    #[test]
2034    fn legacy_layout_fails_fast() {
2035        let dir = tempfile::tempdir().unwrap();
2036        let root = dir.path().join("blobs");
2037        let shard = root.join("ab");
2038        std::fs::create_dir_all(&shard).unwrap();
2039        std::fs::write(shard.join("deadbeef.bin"), b"old payload").unwrap();
2040        let error = BlobStore::open(&root).unwrap_err();
2041        assert!(matches!(error, RegistryError::LegacyBlobLayout { .. }));
2042    }
2043
2044    #[test]
2045    fn memory_store_round_trip_and_miss() {
2046        let store = BlobStore::memory();
2047        let payload = b"POINT EWKB bytes".to_vec();
2048        let id = StrHash::from_bytes(&payload);
2049        assert_eq!(store.put(id, &payload).unwrap(), payload.len() as u64);
2050        let missing = StrHash::new("http://ex/not-a-blob");
2051        assert_eq!(
2052            store.get(&[id, missing]).unwrap(),
2053            vec![Some(payload.clone()), None]
2054        );
2055    }
2056
2057    #[test]
2058    fn memory_store_put_is_idempotent() {
2059        let store = BlobStore::memory();
2060        let payload = b"payload-A".to_vec();
2061        let id = StrHash::from_bytes(&payload);
2062        assert_eq!(store.put(id, &payload).unwrap(), payload.len() as u64);
2063        assert_eq!(store.put(id, &payload).unwrap(), 0);
2064        assert_eq!(store.get(&[id]).unwrap(), vec![Some(payload)]);
2065    }
2066
2067    #[test]
2068    fn memory_store_stores_large_payloads_without_segments() {
2069        // The in-memory variant mirrors the old store: every payload up to
2070        // the 64 MiB limit lives in the map (geo writes in memory mode must
2071        // not depend on the segment tier).
2072        let store = BlobStore::memory();
2073        let payload = vec![7u8; INLINE_THRESHOLD_BYTES * 4];
2074        let id = StrHash::from_bytes(&payload);
2075        store.put(id, &payload).unwrap();
2076        assert_eq!(store.get(&[id]).unwrap(), vec![Some(payload)]);
2077    }
2078
2079    #[test]
2080    fn memory_store_rejects_above_the_64mib_limit() {
2081        let store = BlobStore::memory();
2082        let oversized = vec![0u8; MAX_BLOB_BYTES + 1];
2083        let error = store
2084            .put(StrHash::from_bytes(&oversized), &oversized)
2085            .unwrap_err();
2086        assert!(matches!(error, RegistryError::BlobTooLarge { .. }));
2087    }
2088
2089    #[test]
2090    fn memory_batch_is_all_or_nothing() {
2091        let store = BlobStore::memory();
2092        let a = b"alpha".to_vec();
2093        let a_id = StrHash::from_bytes(&a);
2094        let (bad_id, bad) = (StrHash::new("http://ex/bad"), b"mismatched".to_vec());
2095        let error = store
2096            .put_blobs(&[(a_id, Arc::from(a.clone())), (bad_id, Arc::from(bad))])
2097            .unwrap_err();
2098        assert!(
2099            matches!(error, RegistryError::BlobHashMismatch { id } if id == bad_id),
2100            "{error:?}"
2101        );
2102        assert_eq!(store.get(&[a_id]).unwrap(), vec![None]);
2103    }
2104
2105    #[test]
2106    fn memory_flush_and_compact_are_noops() {
2107        let store = BlobStore::memory();
2108        store.flush().unwrap();
2109        store.compact_range().unwrap();
2110    }
2111}