bstack_raii 0.1.0

Typed, RAII-style ownership and lifetime layer over the bstack allocation primitives
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
//! [`BStackCountingBloomFilter<K>`]: an owned counting Bloom filter.
//!
//! A probabilistic set: [`contains`](BStackCountingBloomFilter::contains) never
//! yields a false negative (a key that was inserted always reports present) but
//! may yield a false positive (report present for a key that was not). The
//! **counting** variant uses small integer counters instead of single bits, so it
//! also supports [`remove`](BStackCountingBloomFilter::remove) — the classic use
//! being a cheap in-memory-ish guard *in front of* an expensive
//! [`crate::BStackHashMap`] / [`crate::BStackBTreeMap`] lookup, to skip the disk
//! probe for keys that are definitely absent.
//!
//! # Layout — one contiguous block, no pointers
//!
//! The fixed handle ([`BloomOnDisk`]) records the counter-array pointer, the
//! counter count `m`, the number of hash functions `k`, and the inserted-item
//! count `n`. The counters themselves are one contiguous `[u8; m]` block (byte
//! counters — trivially addressable and saturating at 255; ~8× a bit filter, a
//! deliberate simplicity-for-space trade). The `k` indices come from **double
//! hashing** ([`super::hash::double_hash`]) so a single key yields `k`
//! well-distributed positions with no per-`k` hashing cost. Keys are `Pod`,
//! hashed by their raw bytes.
//!
//! # Atomicity
//!
//! `insert` / `remove` read every touched counter and `n`, then write the
//! adjusted values, all inside one [`bstack::BStack::inplace_gen`] — so each is
//! atomic per call and external-lock-free (a concurrent writer never loses an
//! increment, which would otherwise let a `remove` wrongly zero a shared
//! counter). The filter is fixed-size (no growth), so `data`/`m`/`k` never change
//! after construction and need no synchronization. `contains` is a plain read.
//!
//! **Caveat (inherent to counting Bloom filters):** only `remove` keys that were
//! actually inserted. Removing an absent key may decrement counters shared with
//! present keys and introduce false negatives.

use core::marker::PhantomData;
use core::mem::size_of;
use std::io;

use crate::BStackRaiiAllocator;
use bstack::{BStack, BStackGenOp, BStackRange};
use bytemuck::{Pod, Zeroable};

use super::hash::double_hash;
use super::util::{alloc_image, read_fields, w8};
use crate::io_core::{ClonePlan, TryCloneIn, dealloc_range};
use crate::primitives::EightCC;
use crate::types::compiled::{BStackOwned, BlockHeader, HEADER_SIZE};
use crate::types::traits::{BStackBlock, BStackCast};
use crate::util::{SmallBuf, io_error, read_u64};

/// The on-disk image of a [`BStackCountingBloomFilter`]: header, counter-array
/// pointer (`0` = none), counter count `m`, hash count `k`, and inserted-item
/// count `n`. `#[repr(C)]`, `u64` fields only — fixed-size, non-generic.
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
pub struct BloomOnDisk {
    /// The 16-byte block header (size + type tag).
    pub header: BlockHeader,
    /// Offset of the `[u8; m]` counter block, or `0` when unallocated.
    pub data: u64,
    /// Number of counters.
    pub m: u64,
    /// Number of hash functions.
    pub k: u64,
    /// Number of items inserted (minus removed).
    pub n: u64,
}

const DATA_OFF: u64 = HEADER_SIZE; // 16
const M_OFF: u64 = HEADER_SIZE + 8; // 24
const N_OFF: u64 = HEADER_SIZE + 24; // 40
const BLOOM_SIZE: u64 = size_of::<BloomOnDisk>() as u64;

/// An owned counting Bloom filter over `Pod` keys.
///
/// A typed handle (a newtype over a [`BStackRange`]); [`new`](Self::new) /
/// [`with_capacity`](Self::with_capacity) return a bare
/// [`BStackOwned<BStackCountingBloomFilter<K>>`] that frees nothing on scope exit
/// — free it with `bstack_drop` or wrap it
/// (`AutoDrop` / [`crate::BStackCow`]).
pub struct BStackCountingBloomFilter<K: Pod> {
    range: BStackRange,
    _marker: PhantomData<fn() -> K>,
}

impl<K: Pod> BStackCountingBloomFilter<K> {
    /// The `k` counter indices for `key_bytes` (with possible repeats).
    ///
    /// `m`/`k` come straight from the on-disk handle; `new`/`with_capacity`
    /// force `m >= 1` at construction, but a corrupted `m` field would
    /// otherwise divide by zero here on every subsequent `contains`/`insert`/
    /// `remove` — including through `BStackHashSet`/`BStackBTreeSet`'s
    /// embedded filter.
    fn indices(m: u64, k: u64, key_bytes: &[u8]) -> io::Result<Vec<u64>> {
        if m == 0 {
            return Err(io_error!("corrupt bloom filter: zero counter count"));
        }
        let (h1, h2) = double_hash(key_bytes);
        Ok((0..k)
            .map(|i| h1.wrapping_add(i.wrapping_mul(h2)) % m)
            .collect())
    }

    /// Collapse indices to distinct `(index, multiplicity)`, so a counter hit by
    /// two of the `k` hashes is adjusted by two in one write.
    fn aggregate(mut idxs: Vec<u64>) -> Vec<(u64, u32)> {
        idxs.sort_unstable();
        let mut out: Vec<(u64, u32)> = Vec::new();
        for x in idxs {
            match out.last_mut() {
                Some(last) if last.0 == x => last.1 += 1,
                _ => out.push((x, 1)),
            }
        }
        out
    }

    /// Allocate a filter with `m` counters and `k` hash functions (both forced to
    /// at least 1). Prefer [`with_capacity`](Self::with_capacity) to size these.
    pub fn new<A: BStackRaiiAllocator>(
        allocator: &A,
        m: u64,
        k: u64,
    ) -> io::Result<BStackOwned<Self>> {
        let m = m.max(1);
        let k = k.max(1);
        // Allocate and zero the counter block (an orphan until the handle links it).
        let data = {
            let mut slice = allocator.alloc(m)?;
            if let Err(e) = slice.write_range(0, vec![0u8; m as usize]) {
                let _ = allocator.dealloc(slice);
                return Err(e);
            }
            slice.as_range().start()
        };
        let od = BloomOnDisk {
            header: BlockHeader {
                size: BLOOM_SIZE,
                tag: Self::eightcc(),
            },
            data,
            m,
            k,
            n: 0,
        };
        match alloc_image(allocator, bytemuck::bytes_of(&od)) {
            // SAFETY: a freshly allocated block owned by no other handle.
            Ok(range) => Ok(unsafe { BStackOwned::from_raw(Self::from_range(range)) }),
            Err(e) => {
                // SAFETY: the counter block was just allocated, referenced by nobody.
                let _ = unsafe { dealloc_range(allocator, BStackRange::new(data, m)) };
                Err(e)
            }
        }
    }

    /// Allocate a filter sized for `expected_items` at target false-positive rate
    /// `fp_rate`, using the standard optimal `m = -n·ln p / (ln 2)²` and
    /// `k = (m/n)·ln 2`.
    pub fn with_capacity<A: BStackRaiiAllocator>(
        allocator: &A,
        expected_items: u64,
        fp_rate: f64,
    ) -> io::Result<BStackOwned<Self>> {
        let n = expected_items.max(1) as f64;
        let p = fp_rate.clamp(1e-9, 0.5);
        let ln2 = core::f64::consts::LN_2;
        let m = (-(n * p.ln()) / (ln2 * ln2)).ceil().max(1.0) as u64;
        let k = ((m as f64 / n) * ln2).round().clamp(1.0, 32.0) as u64;
        Self::new(allocator, m, k)
    }

    /// Number of items inserted (minus removed).
    pub fn count(&self, stack: &BStack) -> io::Result<u64> {
        read_u64(stack, self.range.start() + N_OFF)
    }

    /// Whether no items are currently present.
    pub fn is_empty(&self, stack: &BStack) -> io::Result<bool> {
        Ok(self.count(stack)? == 0)
    }

    /// The current estimated false-positive probability, `(1 - e^{-k n / m})^k`.
    pub fn estimated_fp_rate(&self, stack: &BStack) -> io::Result<f64> {
        let handle = self.range.start();
        let [m, k, n] = read_fields::<3>(stack, handle + M_OFF)?;
        let (m, k, n) = (m as f64, k as f64, n as f64);
        Ok((1.0 - (-k * n / m).exp()).powf(k))
    }

    /// Insert `key`, bumping each of its `k` counters (saturating at 255).
    pub fn insert<A: BStackRaiiAllocator>(&self, allocator: &A, key: &K) -> io::Result<()> {
        self.adjust(allocator, key, true)
    }

    /// Remove `key`, decrementing each of its `k` counters (saturating at 0).
    ///
    /// Only call this for a key that was actually inserted (see the module docs) —
    /// removing an absent key can introduce false negatives.
    pub fn remove<A: BStackRaiiAllocator>(&self, allocator: &A, key: &K) -> io::Result<()> {
        self.adjust(allocator, key, false)
    }

    /// Whether `key` is *possibly* present: `true` if all `k` counters are
    /// non-zero (may be a false positive), `false` if any is zero (definitely
    /// absent). A plain read.
    pub fn contains(&self, stack: &BStack, key: &K) -> io::Result<bool> {
        let handle = self.range.start();
        let [data, m, k] = read_fields::<3>(stack, handle + DATA_OFF)?;
        let key_bytes = bytemuck::bytes_of(key);
        for idx in Self::indices(m, k, key_bytes)? {
            let mut b = [0u8; 1];
            let off = data
                .checked_add(idx)
                .ok_or_else(|| io_error!("bloom filter offset overflow"))?;
            stack.get_into(off, &mut b)?;
            if b[0] == 0 {
                return Ok(false);
            }
        }
        Ok(true)
    }

    /// Reset every counter and the item count to zero.
    pub fn clear<A: BStackRaiiAllocator>(&self, allocator: &A) -> io::Result<()> {
        let handle = self.range.start();
        let [data, m] = read_fields::<2>(allocator.stack(), handle + DATA_OFF)?;
        // `m` (the counter-array byte length) is an untrusted on-disk field: bound it by
        // the stack size before allocating, so a forged huge `m` cannot drive an
        // unbounded allocation (an abort), mirroring the sibling containers.
        if m > allocator.len()? {
            return Err(io_error!(
                "bloom filter counter array larger than the stack"
            ));
        }
        allocator.stack().set_batched([
            (
                data,
                SmallBuf::Heap(vec![0u8; m as usize].into_boxed_slice()),
            ),
            w8(handle + N_OFF, 0u64),
        ])
    }

    /// Atomically adjust the counters for `key` (and `n`) up or down, reading and
    /// writing every touched counter in one `inplace_gen` (external-lock-free).
    fn adjust<A: BStackRaiiAllocator>(&self, allocator: &A, key: &K, add: bool) -> io::Result<()> {
        let handle = self.range.start();
        let [data, m, k] = read_fields::<3>(allocator.stack(), handle + DATA_OFF)?;
        let agg = Self::aggregate(Self::indices(m, k, bytemuck::bytes_of(key))?);
        let cn = agg.len();
        // Precompute every counter's absolute offset up front (checked): `data`
        // is an on-disk pointer that can be corrupted, and the generator
        // closure below can't itself return `Result`.
        let offs: Vec<u64> = agg
            .iter()
            .map(|&(idx, _)| {
                data.checked_add(idx)
                    .ok_or_else(|| io_error!("bloom filter offset overflow"))
            })
            .collect::<io::Result<Vec<u64>>>()?;

        // Buffers that must outlive the whole `inplace_gen` call.
        let mut read_c = vec![0u8; cn];
        let mut n_buf = [0u8; 8];
        let mut new_c = vec![0u8; cn];
        let mut new_n = [0u8; 8];

        let mut rc = 0usize;
        let mut n_read = false;
        let mut computed = false;
        let mut wc = 0usize;
        let mut n_written = false;
        // A failed `Read` is reported here as the previous op's result. The adjusted
        // counters are computed from `read_c`/`n_buf`, so a swallowed read error
        // would write back values derived from stale/zero bytes (or return a false
        // `Ok` for an adjustment that never happened). Capture it in the read phase —
        // nothing is staged yet — and surface it after `inplace_gen` returns.
        let mut read_err: Option<io::Error> = None;

        let result = allocator.stack().inplace_gen(|feedback| {
            if let Err(e) = feedback {
                read_err = Some(e);
                return None; // read phase, nothing staged → commits nothing
            }
            // Read each distinct counter (one byte).
            if rc < cn {
                let i = rc;
                rc += 1;
                // SAFETY: `read_c` outlives the call; each byte read once.
                let b: &mut [u8] =
                    unsafe { core::mem::transmute::<&mut [u8], _>(&mut read_c[i..i + 1]) };
                return Some(BStackGenOp::Read {
                    offset: offs[i],
                    buf: b,
                });
            }
            // Read `n`.
            if !n_read {
                n_read = true;
                // SAFETY: `n_buf` outlives the call.
                let b: &mut [u8] = unsafe { core::mem::transmute::<&mut [u8], _>(&mut n_buf[..]) };
                return Some(BStackGenOp::Read {
                    offset: handle + N_OFF,
                    buf: b,
                });
            }
            // Compute the adjusted counters and item count.
            if !computed {
                computed = true;
                for i in 0..cn {
                    let mult = agg[i].1.min(255) as u8;
                    new_c[i] = if !add && read_c[i] == 255 {
                        // A counter that ever saturated has lost its true count, so it is
                        // **pinned** at 255 forever — decrementing it could reach 0 while
                        // members still map to it, causing a false negative (a present key
                        // reported absent). The standard counting-bloom saturation rule.
                        255
                    } else if add {
                        read_c[i].saturating_add(mult)
                    } else {
                        read_c[i].saturating_sub(mult)
                    };
                }
                let n = u64::from_le_bytes(n_buf);
                let nn = if add {
                    n.saturating_add(1)
                } else {
                    n.saturating_sub(1)
                };
                new_n = nn.to_le_bytes();
            }
            // Write the adjusted counters.
            if wc < cn {
                let i = wc;
                wc += 1;
                // SAFETY: `new_c` outlives the call and is not mutated after compute.
                let d: &[u8] = unsafe { core::mem::transmute::<&[u8], _>(&new_c[i..i + 1]) };
                return Some(BStackGenOp::Write {
                    offset: offs[i],
                    data: d,
                });
            }
            // Write `n`.
            if !n_written {
                n_written = true;
                // SAFETY: `new_n` outlives the call.
                let d: &[u8] = unsafe { core::mem::transmute::<&[u8], _>(&new_n[..]) };
                return Some(BStackGenOp::Write {
                    offset: handle + N_OFF,
                    data: d,
                });
            }
            None
        });
        match read_err {
            Some(e) => Err(e),
            None => result,
        }
    }
}

impl<K: Pod> BStackCast for BStackCountingBloomFilter<K> {
    /// A `"Blm"` prefix perturbed by the key size.
    fn eightcc() -> EightCC {
        const BASE: EightCC = EightCC::new([b'B', b'l', b'm', 0x80, 0x81, 0x82, 0x83, 0x84]);
        BASE.mix(EightCC::new((size_of::<K>() as u64).to_le_bytes()))
    }
}

// Self-contained (no separate control block): may be `#[embed]`ded.
impl<K: Pod> crate::types::traits::BStackEmbeddable for BStackCountingBloomFilter<K> {}

impl<K: Pod> BStackBlock for BStackCountingBloomFilter<K> {
    type OnDisk = BloomOnDisk;

    unsafe fn from_range(range: BStackRange) -> Self {
        BStackCountingBloomFilter {
            range,
            _marker: PhantomData,
        }
    }

    fn range(&self) -> BStackRange {
        self.range
    }

    /// Free the counter block, **without** freeing the handle block itself.
    fn __bstack_drop_children<A: BStackRaiiAllocator>(
        allocator: &A,
        range: BStackRange,
    ) -> io::Result<()> {
        let [data, m] = read_fields::<2>(allocator.stack(), range.start() + DATA_OFF)?;
        if data != 0 {
            // SAFETY: the filter solely owns its counter block.
            unsafe { dealloc_range(allocator, BStackRange::new(data, m))? };
        }
        Ok(())
    }

    /// Deep-clone: copy the counter block and stage the handle, in the parent
    /// plan's single atomic commit.
    fn __bstack_clone_children_inplace<A: BStackRaiiAllocator>(
        &self,
        allocator: &A,
        plan: &mut ClonePlan,
    ) -> io::Result<Self::OnDisk> {
        let handle = self.range.start();
        let [data, m, k, n] = read_fields::<4>(allocator.stack(), handle + DATA_OFF)?;

        let new_data = if m != 0 {
            // Untrusted `m`: bound by the stack size before allocating (mirrors the
            // sibling containers), so a forged huge `m` can't drive an unbounded alloc.
            if m > allocator.len()? {
                return Err(io_error!(
                    "bloom filter counter array larger than the stack"
                ));
            }
            let mut bytes = vec![0u8; m as usize];
            allocator.stack().get_into(data, &mut bytes)?;
            let dst = plan.alloc_raw(allocator, m)?;
            plan.write(dst.start(), bytes);
            dst.start()
        } else {
            0
        };

        let od = BloomOnDisk {
            header: BlockHeader {
                size: BLOOM_SIZE,
                tag: Self::eightcc(),
            },
            data: new_data,
            m,
            k,
            n,
        };
        Ok(od)
    }
}

impl<K: Pod> TryCloneIn for BStackCountingBloomFilter<K> {}