Skip to main content

edgestore_tier/
lib.rs

1//! `edgestore-tier` — Tiered storage for EdgeStore.
2//!
3//! Wraps a local `Engine` with a `RemoteStore` (S3, filesystem, etc.) to provide
4//! transparent read-through from local SSD to cold archive.
5//!
6//! ## Usage
7//!
8//! ```rust,no_run
9//! use edgestore::{EdgestoreConfig, Engine};
10//! use edgestore_repl::S3RemoteStore;
11//! use edgestore_tier::TieredEngine;
12//!
13//! let local = Engine::open(EdgestoreConfig::new("/tmp/db")).unwrap();
14//! let remote = S3RemoteStore::new("my-bucket", Some("mydb/"), None).unwrap();
15//! let mut tiered = TieredEngine::new(local, Box::new(remote));
16//!
17//! // write goes to local
18//! tiered.put(b"users", b"alice", b"data").unwrap();
19//!
20//! // read tries local first; on miss checks remote segments
21//! let val = tiered.get(b"users", b"alice").unwrap();
22//! ```
23//!
24//! ## How it works
25//!
26//! 1. **Writes** go to the local `Engine` only. The hot path is unchanged.
27//! 2. **Archiving** (`archive_segments`) uploads local segments to the remote
28//!    store and records them in an archived-segment list.
29//! 3. **`get()`** tries local first. On miss, scans archived segments by key
30//!    bounds, downloads the matching segment, imports it via
31//!    `Engine::import_segment` (LWW merge), then retries.
32//! 4. **`range()` and `prefix()`** merge local results with any archived
33//!    segments whose key bounds overlap the query range. Archived segments are
34//!    downloaded **ephemerally** (no local import, no disk growth) and merged
35//!    in-memory via `ImmutableEngine`. Local data wins for any key present in
36//!    both local and archived segments.
37//! 5. **Text-index stripping** (`with_text_stripping(true)`) removes embedded
38//!    BM25 index records from local segment copies after successful archival,
39//!    reclaiming disk space without touching the remote copy.
40//! 6. **No background tasks.** Everything is synchronous and caller-driven.
41//!    The application decides when to archive, how much to keep local, and
42//!    whether to prefetch.
43//!
44//! ## Monitor-and-archive pattern
45//!
46//! ```rust,no_run
47//! use edgestore::{EdgestoreConfig, Engine};
48//! use edgestore_repl::FilesystemRemoteStore;
49//! use edgestore_tier::TieredEngine;
50//!
51//! let local = Engine::open(EdgestoreConfig::new("/var/db/hot")).unwrap();
52//! let remote = FilesystemRemoteStore::new("/mnt/cold".into()).unwrap();
53//! let mut tiered = TieredEngine::new(local, Box::new(remote))
54//!     .with_text_stripping(true)
55//!     .with_segment_cache_bytes(32 * 1024 * 1024);
56//!
57//! loop {
58//!     let metas = tiered.local().list_segment_metas();
59//!     if metas.len() > 8 {
60//!         let to_archive = &metas[..metas.len() - 4];
61//!         tiered.archive_segments(to_archive).unwrap();
62//!     }
63//! # break;
64//! }
65//! ```
66
67use std::collections::HashMap;
68
69use edgestore::error::EdgestoreError;
70use edgestore::types::encode_key;
71use edgestore::{Engine, ImmutableEngine, ImportResult, RemoteStore};
72use lru::LruCache;
73use std::num::NonZeroUsize;
74
75type KvPairs = Vec<(Vec<u8>, Vec<u8>)>;
76
77/// Metadata for a segment that lives in remote storage.
78#[derive(Debug, Clone)]
79pub struct ArchivedSegment {
80    /// BLAKE3 content hash (also the remote object key).
81    pub hash: [u8; 32],
82    /// Min key in this segment (inclusive).
83    pub min_key: Vec<u8>,
84    /// Max key in this segment (inclusive).
85    pub max_key: Vec<u8>,
86}
87
88/// Default maximum bytes for the ephemeral segment byte cache (32 MB).
89const DEFAULT_SEGMENT_CACHE_MAX_BYTES: usize = 32 * 1024 * 1024;
90
91/// Item cap for the LRU segment cache. High enough that byte-based eviction
92/// always fires first, preventing a silent second eviction path.
93const SEGMENT_CACHE_MAX_ENTRIES: NonZeroUsize =
94    // SAFETY: 65536 is non-zero.
95    unsafe { NonZeroUsize::new_unchecked(65536) };
96
97/// Maximum retry attempts for transient remote errors (throttle, timeout, 503).
98const MAX_RETRIES: u32 = 3;
99
100/// Base delay for exponential backoff: delay_ms = BASE_DELAY_MS * 2^attempt.
101const BASE_DELAY_MS: u64 = 10;
102
103/// Tiered engine: local hot cache + remote cold archive.
104///
105/// Writes go to local. Reads fall back to remote on miss.
106/// Segment import uses the existing `Engine::import_segment` path (LWW merge).
107pub struct TieredEngine {
108    pub(crate) local: Engine,
109    pub(crate) remote: Box<dyn RemoteStore>,
110    /// Segments uploaded to remote (optionally removed locally).
111    archived: Vec<ArchivedSegment>,
112    /// Segments already fetched this session — avoid re-download.
113    fetched: HashMap<[u8; 32], ()>,
114    /// When true, `archive_segments` uploads `.idx`, `.xf`, `.meta` sidecars.
115    upload_sidecars: bool,
116    /// When true, strips BM25 index records from local copy after archive.
117    strip_text_after_archive: bool,
118    /// When true, strips vector index records from local copy after archive.
119    strip_vector_after_archive: bool,
120    /// LRU cache of raw segment bytes for ephemeral range/prefix reads.
121    segment_cache: LruCache<[u8; 32], Vec<u8>>,
122    /// Current total bytes resident in `segment_cache`.
123    pub(crate) segment_cache_bytes: usize,
124    /// Maximum total bytes allowed in `segment_cache` before LRU eviction.
125    segment_cache_max_bytes: usize,
126}
127
128impl TieredEngine {
129    /// Create a new `TieredEngine` from a local `Engine` and a `RemoteStore` backend.
130    pub fn new(local: Engine, remote: Box<dyn RemoteStore>) -> Self {
131        Self {
132            local,
133            remote,
134            archived: Vec::new(),
135            fetched: HashMap::new(),
136            upload_sidecars: false,
137            strip_text_after_archive: false,
138            strip_vector_after_archive: false,
139            // Item cap is high enough that byte-based eviction always fires first.
140            // Prevents a silent second eviction path from drifting segment_cache_bytes.
141            segment_cache: LruCache::new(SEGMENT_CACHE_MAX_ENTRIES),
142            segment_cache_bytes: 0,
143            segment_cache_max_bytes: DEFAULT_SEGMENT_CACHE_MAX_BYTES,
144        }
145    }
146
147    /// Set the maximum total bytes for the ephemeral segment byte cache.
148    /// Default: 32 MB. Set to 0 to disable caching.
149    pub fn with_segment_cache_bytes(mut self, max_bytes: usize) -> Self {
150        self.segment_cache_max_bytes = max_bytes;
151        self
152    }
153
154    /// Enable or disable sidecar upload during `archive_segments`.
155    pub fn with_sidecars(mut self, enabled: bool) -> Self {
156        self.upload_sidecars = enabled;
157        self
158    }
159
160    /// Enable or disable automatic text-index stripping after archiving.
161    pub fn with_text_stripping(mut self, enabled: bool) -> Self {
162        self.strip_text_after_archive = enabled;
163        self
164    }
165
166    /// Enable or disable automatic vector-index stripping after archiving.
167    pub fn with_vector_stripping(mut self, enabled: bool) -> Self {
168        self.strip_vector_after_archive = enabled;
169        self
170    }
171
172    /// Access the underlying local engine.
173    pub fn local(&self) -> &Engine {
174        &self.local
175    }
176
177    /// Mutable access to the underlying local engine.
178    pub fn local_mut(&mut self) -> &mut Engine {
179        &mut self.local
180    }
181
182    /// Return a clone of the archived segment list.
183    pub fn archived_segments(&self) -> Vec<ArchivedSegment> {
184        self.archived.clone()
185    }
186
187    /// Register segments as archived without uploading them.
188    ///
189    /// Use this after restart to restore the archived list from persistent
190    /// storage (e.g. a JSON file written after a previous `archive_segments`).
191    pub fn register_archived(&mut self, segments: Vec<ArchivedSegment>) {
192        for seg in segments {
193            if !self.archived.iter().any(|s| s.hash == seg.hash) {
194                self.archived.push(seg);
195            }
196        }
197    }
198
199    // ── Pass-through KV API ─────────────────────────────────────────────────
200
201    /// Single-record put. Goes to local engine only.
202    pub fn put(&mut self, ns: &[u8], key: &[u8], val: &[u8]) -> Result<u64, EdgestoreError> {
203        self.local.put(ns, key, val)
204    }
205
206    /// Single-record put with TTL.
207    pub fn put_with_ttl(
208        &mut self,
209        ns: &[u8],
210        key: &[u8],
211        val: &[u8],
212        ttl_secs: u32,
213    ) -> Result<u64, EdgestoreError> {
214        self.local.put_with_ttl(ns, key, val, ttl_secs)
215    }
216
217    /// Delete a record.
218    pub fn delete(&mut self, ns: &[u8], key: &[u8]) -> Result<u64, EdgestoreError> {
219        self.local.delete(ns, key)
220    }
221
222    // ── Read-through API ────────────────────────────────────────────────────
223
224    /// Get a value. Local first; on miss checks archived segments and fetches from remote.
225    pub fn get(&mut self, ns: &[u8], key: &[u8]) -> Result<Option<Vec<u8>>, EdgestoreError> {
226        if let Some(val) = self.local.get(ns, key)? {
227            return Ok(Some(val));
228        }
229
230        let encoded_key = edgestore::types::encode_key(ns, key);
231        let to_fetch: Vec<[u8; 32]> = self
232            .archived
233            .iter()
234            .filter(|seg| encoded_key >= seg.min_key && encoded_key <= seg.max_key)
235            .filter(|seg| !self.fetched.contains_key(&seg.hash))
236            .map(|seg| seg.hash)
237            .collect();
238
239        for hash in to_fetch {
240            if let Err(e) = self.fetch_and_import(&hash) {
241                eprintln!(
242                    "[edgestore-tier] failed to fetch segment {}: {}",
243                    hex_hash(&hash),
244                    e
245                );
246            }
247        }
248
249        self.local.get(ns, key)
250    }
251
252    /// Range scan across local data and any archived segments whose key bounds
253    /// overlap `[start, end)`. Local data wins on key conflict.
254    #[allow(clippy::type_complexity)]
255    pub fn range(
256        &mut self,
257        ns: &[u8],
258        start: &[u8],
259        end: &[u8],
260    ) -> Result<KvPairs, EdgestoreError> {
261        let local = self.local.range(ns, start, end)?;
262        let archived = self.range_archived(ns, start, end)?;
263        Ok(merge_local_wins(local, archived))
264    }
265
266    /// Prefix scan across local data and any archived segments whose key bounds
267    /// overlap the prefix range. Local data wins on key conflict.
268    #[allow(clippy::type_complexity)]
269    pub fn prefix(&mut self, ns: &[u8], prefix: &[u8]) -> Result<KvPairs, EdgestoreError> {
270        let local = self.local.prefix(ns, prefix)?;
271        let archived = self.prefix_archived(ns, prefix)?;
272        Ok(merge_local_wins(local, archived))
273    }
274
275    // ── Archiving ───────────────────────────────────────────────────────────
276
277    /// Upload local segments to remote storage and register them as archived.
278    ///
279    /// When `with_sidecars(true)`: also uploads `.idx`, `.xf`, `.meta` files.
280    /// Sidecar upload errors are logged but do not fail the archive.
281    pub fn archive_segments(
282        &mut self,
283        metas: &[edgestore::types::SegmentMeta],
284    ) -> Result<(), EdgestoreError> {
285        assert!(!metas.is_empty() || true, "metas slice accepted (may be empty)");
286        let base = self.local.db_path().to_path_buf();
287
288        for meta in metas {
289            let hash: [u8; 32] = meta.segment_hash.as_slice().try_into().map_err(|_| {
290                EdgestoreError::ReplicationError(format!(
291                    "segment {} hash is not 32 bytes",
292                    meta.segment_id
293                ))
294            })?;
295
296            let dat_path = base.join(format!("segment-{:08}.dat", meta.segment_id));
297            if !dat_path.exists() {
298                continue; // already archived / deleted
299            }
300
301            let data = std::fs::read(&dat_path).map_err(EdgestoreError::Io)?;
302            assert!(!data.is_empty(), "segment .dat file must not be empty");
303            self.upload_with_retry(&hash, &data)?;
304
305            if self.upload_sidecars {
306                for ext in &["idx", "xf", "meta"] {
307                    let sidecar_path =
308                        base.join(format!("segment-{:08}.{}", meta.segment_id, ext));
309                    if let Ok(bytes) = std::fs::read(&sidecar_path) {
310                        if let Err(e) = self.remote.upload_aux(&hash, ext, &bytes) {
311                            eprintln!(
312                                "[edgestore-tier] sidecar upload skipped for {}.{}: {}",
313                                hex_hash(&hash),
314                                ext,
315                                e
316                            );
317                        }
318                    }
319                }
320            }
321
322            self.archived.push(ArchivedSegment {
323                hash,
324                min_key: meta.min_key.clone(),
325                max_key: meta.max_key.clone(),
326            });
327
328            if self.strip_text_after_archive {
329                if let Err(e) = self.local.strip_text_index(meta.segment_id) {
330                    eprintln!(
331                        "[edgestore-tier] strip_text_index skipped for segment {}: {}",
332                        meta.segment_id, e
333                    );
334                }
335            }
336
337            if self.strip_vector_after_archive {
338                if let Err(e) = self.local.strip_vector_index(meta.segment_id) {
339                    eprintln!(
340                        "[edgestore-tier] strip_vector_index skipped for segment {}: {}",
341                        meta.segment_id, e
342                    );
343                }
344            }
345        }
346
347        Ok(())
348    }
349
350    /// Download and import one specific archived segment by hash.
351    pub fn fetch_segment(&mut self, hash: &[u8; 32]) -> Result<(), EdgestoreError> {
352        self.fetch_and_import(hash)
353    }
354
355    /// Download a segment's raw bytes without importing into local storage.
356    ///
357    /// Use this to build an ephemeral `ImmutableEngine` without growing local
358    /// storage. Does not touch `self.local` or `self.fetched`.
359    pub fn download_segment(&self, hash: &[u8; 32]) -> Result<Vec<u8>, EdgestoreError> {
360        assert!(hash.len() == 32, "hash must be 32 bytes");
361        self.remote.download(hash).map_err(|e| {
362            EdgestoreError::ReplicationError(format!("download segment {}: {}", hex_hash(hash), e))
363        })
364    }
365
366    /// Download and import only the archived segments whose key bounds overlap
367    /// the given namespace key range.
368    pub fn fetch_archived_overlapping(
369        &mut self,
370        ns: &[u8],
371        start: &[u8],
372        end: &[u8],
373    ) -> Result<(), EdgestoreError> {
374        let start = edgestore::types::encode_key(ns, start);
375        let end = edgestore::types::encode_key(ns, end);
376
377        let overlapping: Vec<[u8; 32]> = self
378            .archived
379            .iter()
380            .filter(|seg| seg.max_key >= start && seg.min_key < end)
381            .map(|seg| seg.hash)
382            .collect();
383
384        for hash in overlapping {
385            self.fetch_and_import(&hash)?;
386        }
387        Ok(())
388    }
389
390    /// Fetch every archived segment into local storage.
391    pub fn fetch_all_archived(&mut self) -> Result<(), EdgestoreError> {
392        let archived = self.archived.clone();
393        for seg in &archived {
394            if !self.fetched.contains_key(&seg.hash) {
395                self.fetch_and_import(&seg.hash)?;
396            }
397        }
398        Ok(())
399    }
400
401    // ── Read-only fast-path helpers ──────────────────────────────────────────
402    //
403    // These `&self` methods let a caller (e.g. `AsyncTieredEngine`) check whether
404    // a read needs a write lock, cutting contention between concurrent readers and
405    // the single writer for the common local-hit case.
406
407    /// Local-only get, no archived read-through.
408    /// `None` does not mean absent — caller must fall back to `get()`.
409    pub fn local_only_get(&self, ns: &[u8], key: &[u8]) -> Result<Option<Vec<u8>>, EdgestoreError> {
410        self.local.get(ns, key)
411    }
412
413    fn has_unfetched_archived_overlap(&self, enc_start: &[u8], enc_end: &[u8]) -> bool {
414        self.archived.iter().any(|seg| {
415            seg.max_key.as_slice() >= enc_start
416                && seg.min_key.as_slice() < enc_end
417                && !self.fetched.contains_key(&seg.hash)
418        })
419    }
420
421    fn has_unfetched_archived_point(&self, enc_key: &[u8]) -> bool {
422        self.archived.iter().any(|seg| {
423            seg.min_key.as_slice() <= enc_key
424                && seg.max_key.as_slice() >= enc_key
425                && !self.fetched.contains_key(&seg.hash)
426        })
427    }
428
429    /// True if answering `get(ns, key)` might require fetching an archived segment.
430    pub fn get_needs_archived_fetch(&self, ns: &[u8], key: &[u8]) -> bool {
431        let enc_key = encode_key(ns, key);
432        self.has_unfetched_archived_point(&enc_key)
433    }
434
435    /// True if answering `range(ns, start, end)` would need to fetch an archived segment.
436    pub fn range_needs_archived_fetch(&self, ns: &[u8], start: &[u8], end: &[u8]) -> bool {
437        let enc_start = encode_key(ns, start);
438        let enc_end = encode_key(ns, end);
439        self.has_unfetched_archived_overlap(&enc_start, &enc_end)
440    }
441
442    /// Local-only range scan, no archived read-through.
443    pub fn local_only_range(
444        &self,
445        ns: &[u8],
446        start: &[u8],
447        end: &[u8],
448    ) -> Result<KvPairs, EdgestoreError> {
449        self.local.range(ns, start, end)
450    }
451
452    /// True if answering `prefix(ns, prefix)` would need to fetch an archived segment.
453    pub fn prefix_needs_archived_fetch(&self, ns: &[u8], prefix: &[u8]) -> bool {
454        let enc_prefix = encode_key(ns, prefix);
455        let enc_end = edgestore::types::prefix_upper_bound(&enc_prefix)
456            .unwrap_or_else(|| vec![0xFF; enc_prefix.len() + 1]);
457        self.has_unfetched_archived_overlap(&enc_prefix, &enc_end)
458    }
459
460    /// Local-only prefix scan, no archived read-through.
461    pub fn local_only_prefix(&self, ns: &[u8], prefix: &[u8]) -> Result<KvPairs, EdgestoreError> {
462        self.local.prefix(ns, prefix)
463    }
464
465    // ── Ephemeral archived-segment reads ────────────────────────────────────
466
467    /// Build an ephemeral `ImmutableEngine` from archived segments overlapping
468    /// `[enc_start, enc_end)`. Serves from the LRU byte cache when available.
469    fn ephemeral_engine_for_range(
470        &mut self,
471        enc_start: &[u8],
472        enc_end: &[u8],
473    ) -> Result<Option<ImmutableEngine>, EdgestoreError> {
474        let to_load: Vec<[u8; 32]> = self
475            .archived
476            .iter()
477            .filter(|seg| seg.max_key.as_slice() >= enc_start && seg.min_key.as_slice() < enc_end)
478            .filter(|seg| !self.fetched.contains_key(&seg.hash))
479            .map(|seg| seg.hash)
480            .collect();
481
482        if to_load.is_empty() {
483            return Ok(None);
484        }
485
486        let mut pairs: Vec<(edgestore::types::SegmentMeta, Vec<u8>)> =
487            Vec::with_capacity(to_load.len());
488
489        for hash in to_load {
490            let data = if let Some(cached) = self.segment_cache.get(&hash) {
491                cached.clone()
492            } else {
493                match self.remote.download(&hash) {
494                    Ok(data) => {
495                        self.cache_segment(hash, data.clone());
496                        data
497                    }
498                    Err(e) => {
499                        eprintln!(
500                            "[edgestore-tier] ephemeral download skipped for {}: {}",
501                            hex_hash(&hash),
502                            e
503                        );
504                        continue;
505                    }
506                }
507            };
508            pairs.push((synthetic_meta(&hash), data));
509        }
510
511        if pairs.is_empty() {
512            return Ok(None);
513        }
514
515        Ok(Some(ImmutableEngine::from_segment_bytes(pairs)?))
516    }
517
518    fn range_archived(
519        &mut self,
520        ns: &[u8],
521        start: &[u8],
522        end: &[u8],
523    ) -> Result<KvPairs, EdgestoreError> {
524        let enc_start = encode_key(ns, start);
525        let enc_end = encode_key(ns, end);
526        match self.ephemeral_engine_for_range(&enc_start, &enc_end)? {
527            Some(engine) => engine.range(ns, start, end),
528            None => Ok(Vec::new()),
529        }
530    }
531
532    fn prefix_archived(&mut self, ns: &[u8], prefix: &[u8]) -> Result<KvPairs, EdgestoreError> {
533        let enc_prefix = encode_key(ns, prefix);
534        let enc_end = edgestore::types::prefix_upper_bound(&enc_prefix)
535            .unwrap_or_else(|| vec![0xFF; enc_prefix.len() + 1]);
536        match self.ephemeral_engine_for_range(&enc_prefix, &enc_end)? {
537            Some(engine) => engine.prefix(ns, prefix),
538            None => Ok(Vec::new()),
539        }
540    }
541
542    /// Upload a segment with exponential backoff retry on transient errors.
543    fn upload_with_retry(&self, hash: &[u8; 32], data: &[u8]) -> Result<(), EdgestoreError> {
544        assert!(!data.is_empty(), "upload data must not be empty");
545        let label = format!("upload segment {}", hex_hash(hash));
546        retry_transient(&label, || {
547            self.remote.upload_if_absent(hash, data).map(|_| ())
548        })
549    }
550
551    /// Download and import a segment by hash with exponential backoff retry.
552    fn fetch_and_import(&mut self, hash: &[u8; 32]) -> Result<(), EdgestoreError> {
553        assert!(hash.len() == 32, "hash must be 32 bytes");
554        let label = format!("download segment {}", hex_hash(hash));
555        let data = retry_transient(&label, || self.remote.download(hash))?;
556
557        assert!(!data.is_empty(), "downloaded segment must not be empty");
558
559        match self.local.import_segment(&data, hash)? {
560            ImportResult::Applied {
561                keys_written,
562                keys_skipped,
563            } => {
564                eprintln!(
565                    "[edgestore-tier] imported {} ({} written, {} skipped)",
566                    hex_hash(hash),
567                    keys_written,
568                    keys_skipped
569                );
570            }
571            ImportResult::Skipped => {
572                eprintln!("[edgestore-tier] segment {} already local", hex_hash(hash));
573            }
574            ImportResult::HashMismatch => {
575                return Err(EdgestoreError::ReplicationError(format!(
576                    "hash mismatch for segment {}",
577                    hex_hash(hash)
578                )));
579            }
580            ImportResult::Rejected { reason } => {
581                return Err(EdgestoreError::ReplicationError(format!(
582                    "segment {} permanently rejected: {}",
583                    hex_hash(hash),
584                    reason
585                )));
586            }
587        }
588        self.fetched.insert(*hash, ());
589        Ok(())
590    }
591
592    /// Insert segment bytes into the LRU byte cache, evicting LRU entries
593    /// until total resident bytes is within `segment_cache_max_bytes`.
594    fn cache_segment(&mut self, hash: [u8; 32], data: Vec<u8>) {
595        if self.segment_cache_max_bytes == 0 {
596            return;
597        }
598        let incoming = data.len();
599        while self.segment_cache_bytes + incoming > self.segment_cache_max_bytes {
600            match self.segment_cache.pop_lru() {
601                Some((_, evicted)) => {
602                    self.segment_cache_bytes =
603                        self.segment_cache_bytes.saturating_sub(evicted.len())
604                }
605                None => break,
606            }
607        }
608        self.segment_cache_bytes += incoming;
609        self.segment_cache.put(hash, data);
610    }
611
612    /// Flush local memtable to segment.
613    pub fn flush(&mut self) -> Result<(), EdgestoreError> {
614        self.local.flush()
615    }
616
617    /// Compact local segments.
618    pub fn compact_once(&mut self) -> Result<edgestore::CompactionStats, EdgestoreError> {
619        self.local.compact_once()
620    }
621
622    /// Remove one segment from local storage only.
623    ///
624    /// Caller must have confirmed (via `archived_segments()`) that the segment
625    /// is durably archived before pruning.
626    pub fn prune_local_segment(
627        &mut self,
628        segment_id: edgestore::types::SegmentId,
629    ) -> Result<(), EdgestoreError> {
630        self.local.prune_local_segment(segment_id)
631    }
632}
633
634// ── Free functions ──────────────────────────────────────────────────────────
635
636fn hex_hash(hash: &[u8; 32]) -> String {
637    assert!(hash.len() == 32, "hash must be 32 bytes");
638    let mut s = String::with_capacity(64);
639    for b in hash {
640        s.push_str(&format!("{b:02x}"));
641    }
642    assert!(s.len() == 64, "hex_hash must produce 64 chars");
643    s
644}
645
646/// Build a minimal `SegmentMeta` from an archived segment hash for use with
647/// `ImmutableEngine::from_segment_bytes`. Non-critical fields are placeholders;
648/// the engine rebuilds its index from the raw `.dat` bytes.
649fn synthetic_meta(hash: &[u8; 32]) -> edgestore::types::SegmentMeta {
650    assert!(hash.len() == 32, "hash must be 32 bytes");
651    edgestore::types::SegmentMeta {
652        segment_id: 0,
653        segment_hash: hash.to_vec(),
654        min_key: vec![],
655        max_key: vec![0xFF; 2],
656        min_lsn: 0,
657        max_lsn: u64::MAX,
658        record_count: 0,
659        compressed_bytes: 0,
660        uncompressed_bytes: 0,
661        compression: "zstd:1".to_string(),
662        cohort_bucket: 0,
663        death_time: i64::MAX,
664        merkle_root: vec![0u8; 32],
665        created_at: 0,
666        text_index_stripped: false,
667        vector_index_stripped: false,
668    }
669}
670
671/// Merge local and archived results with local winning for any key in both.
672/// Result is sorted by key.
673fn merge_local_wins(local: KvPairs, archived: KvPairs) -> KvPairs {
674    if archived.is_empty() {
675        return local;
676    }
677    let local_keys: std::collections::HashSet<Vec<u8>> =
678        local.iter().map(|(k, _)| k.clone()).collect();
679    let mut result = local;
680    for (k, v) in archived {
681        if !local_keys.contains(&k) {
682            result.push((k, v));
683        }
684    }
685    result.sort_by(|(a, _), (b, _)| a.cmp(b));
686    result
687}
688
689/// Retry `f` up to `MAX_RETRIES` times on transient errors (throttle/timeout/503).
690/// Returns the first successful result, or the last error after all retries.
691fn retry_transient<T, F>(label: &str, mut f: F) -> Result<T, EdgestoreError>
692where
693    F: FnMut() -> Result<T, EdgestoreError>,
694{
695    assert!(!label.is_empty(), "retry label must not be empty");
696    let mut last_err = None;
697
698    for attempt in 0..=MAX_RETRIES {
699        match f() {
700            Ok(v) => return Ok(v),
701            Err(e) => {
702                let msg = e.to_string();
703                last_err = Some(e);
704                let is_transient = msg.contains("throttled")
705                    || msg.contains("timeout")
706                    || msg.contains("503");
707                if is_transient && attempt < MAX_RETRIES {
708                    let delay_ms = BASE_DELAY_MS * (1u64 << attempt);
709                    eprintln!(
710                        "[edgestore-tier] retry {} for {} after {} ms",
711                        attempt + 1,
712                        label,
713                        delay_ms
714                    );
715                    std::thread::sleep(std::time::Duration::from_millis(delay_ms));
716                } else if !is_transient {
717                    break;
718                }
719            }
720        }
721    }
722
723    assert!(last_err.is_some(), "last_err must be set after all retries");
724    Err(EdgestoreError::ReplicationError(format!(
725        "{label} failed after {MAX_RETRIES} retries: {}",
726        last_err.map(|e| e.to_string()).unwrap_or_default()
727    )))
728}
729
730#[cfg(test)]
731mod tests;