slatedb-estimates 0.1.0-alpha.2

Approximate range statistics built on SlateDB metadata
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use std::cmp::Ordering;
use std::ops::Bound::{Excluded, Included, Unbounded};
use std::ops::{Bound, RangeBounds};
use std::sync::Arc;

use slatedb::bytes::Bytes;
use slatedb::manifest::SsTableView;
use slatedb::object_store::ObjectStore;
use slatedb::object_store::path::Path;
use slatedb::{BlockTransformer, DbMetadataOps, SstIndex, SstReader, VersionedManifest};

use crate::SizeApproximationOptions;

type OwnedRange = (Bound<Bytes>, Bound<Bytes>);

/// Computes best-effort range statistics from a SlateDB manifest and SST metadata.
///
/// Estimates cover on-disk SSTs only. Memtable-backed estimation is not supported (yet).
pub struct RangeStats<D: DbMetadataOps + Send + Sync + ?Sized = slatedb::Db> {
    db: Arc<D>,
    sst_reader: SstReader,
}

impl<D: DbMetadataOps + Send + Sync + ?Sized> RangeStats<D> {
    /// Creates an estimator from a database and its SST storage configuration.
    ///
    /// `path`, `object_store`, and `block_transformer` must describe the same
    /// storage used by `db`. `cache` controls index and statistics block caching;
    /// it is not obtained from `db`.
    pub fn new<P: Into<Path>>(
        db: Arc<D>,
        path: P,
        object_store: Arc<dyn ObjectStore>,
        cache: Option<Arc<dyn slatedb::db_cache::DbCache>>,
        block_transformer: Option<Arc<dyn BlockTransformer>>,
    ) -> Self {
        let sst_reader = SstReader::new(path, object_store, cache, block_transformer);
        Self::from_db_parts(db, sst_reader)
    }

    /// Creates an estimator from a database and a preconfigured SST reader.
    pub fn from_db_parts(db: Arc<D>, sst_reader: SstReader) -> Self {
        Self { db, sst_reader }
    }

    /// Estimates the on-disk size of all keys beginning with `prefix`.
    ///
    /// An empty prefix covers the full keyspace.
    ///
    /// # Errors
    ///
    /// Returns an error when `opts` is invalid or SlateDB metadata cannot be read.
    pub async fn get_approximate_size_with_prefix<P: AsRef<[u8]> + Send>(
        &self,
        prefix: P,
        opts: &SizeApproximationOptions,
    ) -> Result<u64, slatedb::Error> {
        let range = prefix_to_range(prefix.as_ref());
        self.get_approximate_size::<Bytes, _>(range, opts).await
    }

    /// Estimates key entries beginning with `prefix` from SST-level statistics.
    ///
    /// An empty prefix covers the full keyspace. The estimate has the same
    /// storage-level limitations as [`Self::estimate_key_count`].
    ///
    /// # Errors
    ///
    /// Returns an error when SlateDB SST metadata cannot be read.
    pub async fn estimate_key_count_with_prefix<P: AsRef<[u8]> + Send>(
        &self,
        prefix: P,
    ) -> Result<u64, slatedb::Error> {
        let range = prefix_to_range(prefix.as_ref());
        self.estimate_key_count::<Bytes, _>(range).await
    }

    /// Estimates the on-disk byte size of `range` from SST-level metadata.
    ///
    /// Fully covered SSTs use their whole-file estimates. Partial SSTs are
    /// refined using block offsets unless `opts.error_margin` permits their
    /// coarse estimate to be used.
    ///
    /// # Errors
    ///
    /// Returns an error when `opts` is invalid or SlateDB metadata cannot be read.
    pub async fn get_approximate_size<K, T>(
        &self,
        range: T,
        opts: &SizeApproximationOptions,
    ) -> Result<u64, slatedb::Error>
    where
        K: AsRef<[u8]> + Send,
        T: RangeBounds<K> + Send,
    {
        validate_size_options(opts)?;

        let query = owned_range_from_range(&range);
        if range_is_empty(&query) {
            return Ok(0);
        }

        let manifest = self.db.manifest();
        let candidates = collect_candidates(&manifest, &query);
        if candidates.is_empty() {
            return Ok(0);
        }

        let coarse_total: u64 = candidates
            .iter()
            .map(|candidate| candidate.view.estimate_size())
            .sum();
        if coarse_total == 0 {
            return Ok(0);
        }

        let mut total = 0u64;
        for candidate in candidates {
            let coarse = candidate.view.estimate_size();
            if !candidate.requires_refinement {
                total = total.saturating_add(coarse);
                continue;
            }

            let candidate_fraction = coarse as f64 / coarse_total as f64;
            if candidate_fraction < opts.error_margin {
                total = total.saturating_add(coarse);
                continue;
            }

            let refined = self
                .estimate_view_size(&candidate.view, &candidate.overlap)
                .await?;
            total = total.saturating_add(refined);
        }

        Ok(total)
    }

    /// Estimates key entries in `range` from SST-level statistics.
    ///
    /// This is a storage-level best-effort estimate. It sums per-SST net
    /// `puts + merges - deletes` for the touched files or blocks and does not
    /// reconcile overlapping L0 files the way a SlateDB scan does. A range that
    /// covers un-compacted updates or tombstones can count obsolete versions or
    /// deleted keys.
    ///
    /// # Errors
    ///
    /// Returns an error when SlateDB SST metadata cannot be read.
    pub async fn estimate_key_count<K, T>(&self, range: T) -> Result<u64, slatedb::Error>
    where
        K: AsRef<[u8]> + Send,
        T: RangeBounds<K> + Send,
    {
        let query = owned_range_from_range(&range);
        if range_is_empty(&query) {
            return Ok(0);
        }

        let manifest = self.db.manifest();
        let candidates = collect_candidates(&manifest, &query);
        if candidates.is_empty() {
            return Ok(0);
        }

        let mut total = 0u64;
        for candidate in candidates {
            let sst_file = self
                .sst_reader
                .open_with_handle(candidate.view.sst.clone())?;
            let stats = sst_file
                .stats()
                .await?
                .ok_or_else(|| missing_sst_stats_error(&candidate.view))?;

            if !candidate.requires_refinement {
                total = total.saturating_add(net_count(
                    stats.num_puts,
                    stats.num_deletes,
                    stats.num_merges,
                ));
                continue;
            }

            let index = sst_file.index().await?;
            if index.is_empty() || stats.block_stats.is_empty() {
                continue;
            }

            let Some((start_idx, end_idx)) = touched_block_span(&index, &candidate.overlap) else {
                continue;
            };
            let end_idx = end_idx.min(stats.block_stats.len().saturating_sub(1));
            let start_idx = start_idx.min(end_idx);

            let mut count = 0u64;
            for block_stats in &stats.block_stats[start_idx..=end_idx] {
                count = count.saturating_add(net_count(
                    u64::from(block_stats.num_puts),
                    u64::from(block_stats.num_deletes),
                    u64::from(block_stats.num_merges),
                ));
            }
            total = total.saturating_add(count);
        }

        Ok(total)
    }

    async fn estimate_view_size(
        &self,
        view: &SsTableView,
        overlap: &OwnedRange,
    ) -> Result<u64, slatedb::Error> {
        let sst_file = self.sst_reader.open_with_handle(view.sst.clone())?;
        let index = sst_file.index().await?;
        if index.is_empty() {
            return Ok(view.estimate_size());
        }

        let Some((start_idx, end_idx)) = touched_block_span(&index, overlap) else {
            return Ok(0);
        };

        let total_size = view.estimate_size();
        let start_offset = index
            .get(start_idx)
            .expect("touched block start should be in range")
            .0;
        let end_offset = if end_idx + 1 < index.len() {
            index
                .get(end_idx + 1)
                .expect("block after touched span should be in range")
                .0
        } else {
            total_size
        };

        Ok(end_offset.saturating_sub(start_offset).min(total_size))
    }
}

#[derive(Clone, Debug)]
struct Candidate {
    view: SsTableView,
    overlap: OwnedRange,
    requires_refinement: bool,
}

fn validate_size_options(opts: &SizeApproximationOptions) -> Result<(), slatedb::Error> {
    if !opts.include_memtables && !opts.include_files {
        return Err(slatedb::Error::invalid(
            "at least one of include_memtables or include_files must be true".to_string(),
        ));
    }
    if !opts.error_margin.is_finite() || !(0.0..=1.0).contains(&opts.error_margin) {
        return Err(slatedb::Error::invalid(format!(
            "error_margin must be in the range [0.0, 1.0], got {}",
            opts.error_margin
        )));
    }
    if opts.include_memtables {
        return Err(slatedb::Error::invalid(
            "include_memtables is not supported yet".to_string(),
        ));
    }
    Ok(())
}

fn collect_candidates(manifest: &VersionedManifest, query: &OwnedRange) -> Vec<Candidate> {
    let mut candidates = Vec::new();

    for view in manifest.l0() {
        if let Some(candidate) = build_candidate(view.clone(), query) {
            candidates.push(candidate);
        }
    }

    for sorted_run in manifest.compacted() {
        for view in sorted_run.tables_covering_range::<OwnedRange>(query.clone()) {
            if let Some(candidate) = build_candidate(view.clone(), query) {
                candidates.push(candidate);
            }
        }
    }

    candidates
}

fn build_candidate(view: SsTableView, query: &OwnedRange) -> Option<Candidate> {
    let logical = logical_view_range(&view)?;
    let overlap = range_intersection(&logical, query)?;
    let projected = view.visible_range().is_some();
    let requires_refinement = projected || !range_contains(query, &logical);
    Some(Candidate {
        view,
        overlap,
        requires_refinement,
    })
}

fn logical_view_range(view: &SsTableView) -> Option<OwnedRange> {
    let start = Included(view.sst.info.first_entry.clone()?);
    let end = match &view.sst.info.last_entry {
        Some(last) => Included(last.clone()),
        None => Unbounded,
    };

    let physical = (start, end);
    if let Some(visible) = view.visible_range() {
        let visible = (visible.start_bound().cloned(), visible.end_bound().cloned());
        range_intersection(&physical, &visible)
    } else {
        Some(physical)
    }
}

fn touched_block_span(index: &SstIndex, range: &OwnedRange) -> Option<(usize, usize)> {
    if index.is_empty() {
        return None;
    }

    let start_idx = start_block_index(index, &range.0);
    let end_idx = end_block_index(index, &range.1)?;
    if start_idx > end_idx || start_idx >= index.len() {
        return None;
    }
    Some((start_idx, end_idx.min(index.len() - 1)))
}

fn start_block_index(index: &SstIndex, start: &Bound<Bytes>) -> usize {
    match start {
        Unbounded => 0,
        Included(key) | Excluded(key) => {
            let idx = index.partition_point(|candidate| candidate <= key.as_ref());
            idx.saturating_sub(1)
        }
    }
}

fn end_block_index(index: &SstIndex, end: &Bound<Bytes>) -> Option<usize> {
    match end {
        Unbounded => Some(index.len().saturating_sub(1)),
        Included(key) => {
            let idx = index.partition_point(|candidate| candidate <= key.as_ref());
            idx.checked_sub(1)
        }
        Excluded(key) => {
            let idx = index.partition_point(|candidate| candidate < key.as_ref());
            idx.checked_sub(1)
        }
    }
}

fn net_count(puts: u64, deletes: u64, merges: u64) -> u64 {
    puts.saturating_add(merges).saturating_sub(deletes)
}

fn format_sst_id(view: &SsTableView) -> String {
    format!("compacted-{}", view.sst.id.value())
}

fn missing_sst_stats_error(view: &SsTableView) -> slatedb::Error {
    slatedb::Error::data(format!(
        "cannot estimate key count because SST {} has no stats block",
        format_sst_id(view)
    ))
}

fn owned_range_from_range<K, T>(range: &T) -> OwnedRange
where
    K: AsRef<[u8]> + Send,
    T: RangeBounds<K> + Send,
{
    (
        clone_bound(range.start_bound()),
        clone_bound(range.end_bound()),
    )
}

fn range_is_empty(range: &OwnedRange) -> bool {
    match (&range.0, &range.1) {
        (Unbounded, _) | (_, Unbounded) => false,
        (Included(start), Included(end)) => start > end,
        (Included(start), Excluded(end))
        | (Excluded(start), Included(end))
        | (Excluded(start), Excluded(end)) => start >= end,
    }
}

fn range_intersection(left: &OwnedRange, right: &OwnedRange) -> Option<OwnedRange> {
    let range = (
        max_start_bound(&left.0, &right.0),
        min_end_bound(&left.1, &right.1),
    );
    (!range_is_empty(&range)).then_some(range)
}

fn range_contains(container: &OwnedRange, contained: &OwnedRange) -> bool {
    range_intersection(container, contained).as_ref() == Some(contained)
}

fn clone_bound<K: AsRef<[u8]>>(bound: Bound<&K>) -> Bound<Bytes> {
    match bound {
        Included(key) => Included(Bytes::copy_from_slice(key.as_ref())),
        Excluded(key) => Excluded(Bytes::copy_from_slice(key.as_ref())),
        Unbounded => Unbounded,
    }
}

fn max_start_bound(left: &Bound<Bytes>, right: &Bound<Bytes>) -> Bound<Bytes> {
    match compare_start_bounds(left, right) {
        Ordering::Less => right.clone(),
        _ => left.clone(),
    }
}

fn min_end_bound(left: &Bound<Bytes>, right: &Bound<Bytes>) -> Bound<Bytes> {
    match compare_end_bounds(left, right) {
        Ordering::Greater => right.clone(),
        _ => left.clone(),
    }
}

fn compare_start_bounds(left: &Bound<Bytes>, right: &Bound<Bytes>) -> Ordering {
    match (left, right) {
        (Unbounded, Unbounded) => Ordering::Equal,
        (Unbounded, _) => Ordering::Less,
        (_, Unbounded) => Ordering::Greater,
        (Included(left), Included(right)) | (Excluded(left), Excluded(right)) => left.cmp(right),
        (Included(left), Excluded(right)) => match left.cmp(right) {
            Ordering::Equal => Ordering::Less,
            ordering => ordering,
        },
        (Excluded(left), Included(right)) => match left.cmp(right) {
            Ordering::Equal => Ordering::Greater,
            ordering => ordering,
        },
    }
}

fn prefix_to_range(prefix: &[u8]) -> OwnedRange {
    if prefix.is_empty() {
        return (Unbounded, Unbounded);
    }
    let start = Included(Bytes::copy_from_slice(prefix));
    let end = increment_prefix(prefix).map(Excluded).unwrap_or(Unbounded);
    (start, end)
}

// Returns the smallest byte string lexicographically greater than any key
// starting with `prefix`. Returns `None` when `prefix` is all `0xff`.
fn increment_prefix(prefix: &[u8]) -> Option<Bytes> {
    let mut upper_bound = prefix.to_vec();
    for i in (0..upper_bound.len()).rev() {
        if upper_bound[i] != u8::MAX {
            upper_bound[i] += 1;
            upper_bound.truncate(i + 1);
            return Some(Bytes::from(upper_bound));
        }
    }
    None
}

fn compare_end_bounds(left: &Bound<Bytes>, right: &Bound<Bytes>) -> Ordering {
    match (left, right) {
        (Unbounded, Unbounded) => Ordering::Equal,
        (Unbounded, _) => Ordering::Greater,
        (_, Unbounded) => Ordering::Less,
        (Included(left), Included(right)) | (Excluded(left), Excluded(right)) => left.cmp(right),
        (Included(left), Excluded(right)) => match left.cmp(right) {
            Ordering::Equal => Ordering::Greater,
            ordering => ordering,
        },
        (Excluded(left), Included(right)) => match left.cmp(right) {
            Ordering::Equal => Ordering::Less,
            ordering => ordering,
        },
    }
}