oxidd-cache 0.13.0

Apply cache for OxiDD
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! Fixed-size direct mapped apply cache

use std::cell::UnsafeCell;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::mem::MaybeUninit;

use parking_lot::lock_api::RawMutex;

use oxidd_core::util::{DropWith, Own, Ref};
use oxidd_core::{ApplyCache, Manager, ManagerEventSubscriber};

#[cfg(feature = "hugealloc")]
type Box<T> = allocator_api2::boxed::Box<T, hugealloc::HugeAlloc>;
#[cfg(feature = "hugealloc")]
type Vec<T> = allocator_api2::vec::Vec<T, hugealloc::HugeAlloc>;

/// Fixed-size direct mapped apply cache
pub struct DMApplyCache<M: Manager, O, H, const ENTRY_CAP: usize = 3>(
    Box<[Entry<M, O, ENTRY_CAP>]>,
    PhantomData<H>,
);

impl<M: Manager, O, H, const ENTRY_CAP: usize> DropWith<M::Edge>
    for DMApplyCache<M, O, H, ENTRY_CAP>
where
    O: Copy + Eq + Hash,
{
    fn drop_with(self, _drop_edge: impl Fn(Own<M::Edge>)) {
        // The plain drop impl suffices
    }
}

union Datum<E: Copy> {
    edge: E,
    numeric: u32,
    uninit: (),
}

impl<E: Copy> Datum<E> {
    const UNINIT: Self = Self { uninit: () };
}

const KIND_BITS: u32 = 4;
const KIND_COUNT: usize = 1 << KIND_BITS;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct CountPair(u8);

impl CountPair {
    const NULL: Self = CountPair(0);

    #[inline]
    const fn new(edge: usize, numeric: usize) -> Self {
        debug_assert!(edge < KIND_COUNT);
        debug_assert!(numeric < KIND_COUNT);
        Self((numeric << 4 | edge) as u8)
    }

    #[inline]
    const fn edge(self) -> usize {
        self.0 as usize & (KIND_COUNT - 1)
    }

    #[inline]
    const fn numeric(self) -> usize {
        (self.0 >> KIND_BITS) as usize
    }
}

/// Entry containing key and value
struct Entry<M: Manager, O, const ENTRY_CAP: usize> {
    /// Mutex for all the `UnsafeCell`s in here
    mutex: crate::util::RawMutex,
    /// Count of operands. If 0, this entry is not occupied.
    operands: UnsafeCell<CountPair>,
    /// Count of values
    values: UnsafeCell<CountPair>,
    /// Operator of the key. Initialized if `operands != 0`.
    operator: UnsafeCell<MaybeUninit<O>>,
    /// Operands and values. The first `operands.edge()` elements are edges, the
    /// following `operands.numeric()` elements are numeric. Then follow
    /// `values.edge()` edges and `values.numeric()` numeric elements.
    data: UnsafeCell<[Datum<M::Edge>; ENTRY_CAP]>,
}

struct EntryGuard<'a, M: Manager, O, const ENTRY_CAP: usize>(&'a Entry<M, O, ENTRY_CAP>);

// SAFETY: `Entry` is like a `Mutex`
unsafe impl<M: Manager, O: Send, const ENTRY_CAP: usize> Send for Entry<M, O, ENTRY_CAP> where
    M::Edge: Send
{
}
unsafe impl<M: Manager, O: Send, const ENTRY_CAP: usize> Sync for Entry<M, O, ENTRY_CAP> where
    M::Edge: Send
{
}

impl<M: Manager, O: Copy + Eq, const ENTRY_CAP: usize> Entry<M, O, ENTRY_CAP> {
    // Regarding the lint: the intent here is not to modify the `AtomicBool` in
    // a const context but to create the `RawMutex` in a const context.
    #[allow(clippy::declare_interior_mutable_const)]
    const INIT: Self = Self {
        mutex: crate::util::RawMutex::INIT,
        operands: UnsafeCell::new(CountPair::NULL),
        values: UnsafeCell::new(CountPair::NULL),
        operator: UnsafeCell::new(MaybeUninit::uninit()),
        data: UnsafeCell::new([Datum::UNINIT; ENTRY_CAP]),
    };

    #[inline]
    fn lock(&self) -> EntryGuard<'_, M, O, ENTRY_CAP> {
        self.mutex.lock();
        EntryGuard(self)
    }

    #[inline]
    fn try_lock(&self) -> Option<EntryGuard<'_, M, O, ENTRY_CAP>> {
        if self.mutex.try_lock() {
            Some(EntryGuard(self))
        } else {
            None
        }
    }
}

impl<M: Manager, O, const ENTRY_CAP: usize> Drop for EntryGuard<'_, M, O, ENTRY_CAP> {
    #[inline]
    fn drop(&mut self) {
        // SAFETY: The entry is locked.
        unsafe { self.0.mutex.unlock() }
    }
}

impl<M: Manager, O, const ENTRY_CAP: usize> EntryGuard<'_, M, O, ENTRY_CAP>
where
    O: Copy + Eq,
{
    /// Is this entry occupied?
    #[inline]
    fn is_occupied(&self) -> bool {
        // SAFETY: The entry is locked.
        unsafe { *self.0.operands.get() != CountPair::NULL }
    }

    /// Get the value of this entry if it is occupied and the key (`operator`
    /// and `operands`) matches
    ///
    /// Assumes that
    /// - there is at least one operand,
    /// - there are at most `KIND_COUNT` operands and values of each kind, and
    /// - the count of operands and values is at most `ENTRY_CAP`.
    #[inline(always)]
    #[allow(clippy::type_complexity)]
    fn get<const E: usize, const N: usize>(
        &self,
        manager: &M,
        operator: O,
        operands: (&[Ref<'_, M::Edge>], &[u32]),
    ) -> Option<([Own<M::Edge>; E], [u32; N])> {
        // These conditions are ensured when called by
        // `DMApplyCache::get_extended()`
        debug_assert_ne!(operands.0.len() + operands.1.len(), 0);
        debug_assert!(operands.0.len() <= KIND_COUNT);
        debug_assert!(operands.1.len() <= KIND_COUNT);
        debug_assert!(E <= KIND_COUNT);
        debug_assert!(N <= KIND_COUNT);
        debug_assert!(operands.0.len() + operands.1.len() + E + N <= ENTRY_CAP);

        #[cfg(feature = "statistics")]
        STAT_ACCESSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);

        let num_operands = CountPair::new(operands.0.len(), operands.1.len());
        // SAFETY: The entry is locked.
        if unsafe { *self.0.operands.get() } != num_operands {
            return None;
        }

        // SAFETY: The entry is locked.
        let mut data = unsafe { &*self.0.data.get() }.iter();
        for (o1, o2) in operands.0.iter().zip(data.by_ref()) {
            // SAFETY: The first `operands.len()` operands are edges
            if o1.raw() != unsafe { o2.edge } {
                return None;
            }
        }
        for (&o1, o2) in operands.1.iter().zip(data.by_ref()) {
            // SAFETY: The next `num_numeric_operands` operands are numeric
            if o1 != unsafe { o2.numeric } {
                return None;
            }
        }

        // SAFETY: The entry is (1,2) locked and (2) occupied.
        if unsafe { (*self.0.operator.get()).assume_init() } != operator
            || unsafe { *self.0.values.get() } != const { CountPair::new(E, N) }
        {
            return None;
        }

        #[cfg(feature = "statistics")]
        STAT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);

        let (edge_values, remaining) = data.as_slice().split_at(E);
        let numeric_values = &remaining[..N];

        // `std::array::from_fn` is not always inlined properly, so we use a
        // hand-rolled implementation
        let mut edges = MaybeUninit::uninit();
        // SAFETY: essentially the `AsMut` impl stabilized in Rust 1.95
        let edges_mut = unsafe { &mut *(&raw mut edges as *mut [MaybeUninit<Own<M::Edge>>; E]) };
        for (dst, src) in edges_mut.iter_mut().zip(edge_values) {
            // SAFETY: The next `E` values in `data` are edges. We still have
            // permission to recreate the `Ref`s from "weak" edges.
            dst.write(manager.clone_edge(unsafe { Ref::from_raw(src.edge) }));
        }

        Some((
            // SAFETY: `edges` is fully initialized above
            unsafe { edges.assume_init() },
            // SAFETY: The final `N` values in `data` are numeric
            std::array::from_fn(|i| unsafe { numeric_values[i].numeric }),
        ))
    }

    /// Set the key/value of this entry
    ///
    /// If `self` is already occupied and the key matches, the entry is not
    /// updated (`operands` and `value` are not cloned).
    ///
    /// Assumes that
    /// - there is at least one operand,
    /// - there are at most `KIND_COUNT` operands and values of each kind, and
    /// - the count of operands and values is at most `ENTRY_CAP`.
    #[inline(always)]
    fn set(
        &mut self,
        operator: O,
        operands: (&[Ref<'_, M::Edge>], &[u32]),
        values: (&[Ref<'_, M::Edge>], &[u32]),
    ) {
        debug_assert_ne!(operands.0.len() + operands.1.len(), 0);
        debug_assert!(operands.0.len() <= KIND_COUNT);
        debug_assert!(operands.1.len() <= KIND_COUNT);
        debug_assert!(values.0.len() <= KIND_COUNT);
        debug_assert!(values.1.len() <= KIND_COUNT);
        debug_assert!(
            operands.0.len() + operands.1.len() + values.0.len() + values.1.len() <= ENTRY_CAP
        );

        self.clear();

        #[cfg(feature = "statistics")]
        STAT_INSERTIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);

        // SAFETY (next 2 dereference ops): The entry is locked.
        unsafe { &mut *self.0.operator.get() }.write(operator);
        let mut data = unsafe { &mut *self.0.data.get() }.iter_mut();
        for (src, dst) in operands.0.iter().zip(data.by_ref()) {
            dst.edge = src.raw();
        }
        for (&src, dst) in operands.1.iter().zip(data.by_ref()) {
            dst.numeric = src;
        }
        for (src, dst) in values.0.iter().zip(data.by_ref()) {
            dst.edge = src.raw();
        }
        for (&src, dst) in values.1.iter().zip(data) {
            dst.numeric = src;
        }

        // Important: Set the counts last for exception safety (the functions
        // above might panic).
        unsafe { *self.0.values.get() = CountPair::new(values.0.len(), values.1.len()) };
        unsafe { *self.0.operands.get() = CountPair::new(operands.0.len(), operands.1.len()) };
    }

    /// Clear this entry
    #[inline(always)]
    fn clear(&mut self) {
        // SAFETY: The entry is locked.
        unsafe { *self.0.operands.get() = CountPair::NULL };
        // `Edge`s are just borrowed, so nothing else to do.
    }
}

impl<M, O, H, const ENTRY_CAP: usize> DMApplyCache<M, O, H, ENTRY_CAP>
where
    M: Manager,
    O: Copy + Eq + Hash,
    H: Hasher + Default,
{
    const CHECK_ENTRY_CAP: () = {
        assert!(
            0 < ENTRY_CAP && ENTRY_CAP <= KIND_COUNT * 4,
            "ENTRY_CAP must be in range [1, 64]"
        );
    };

    /// Create a new `ApplyCache` with the given capacity (entries).
    ///
    /// # Safety
    ///
    /// The apply cache must only be used inside a manager that guarantees all
    /// node deletions to be wrapped inside an
    /// [`ManagerEventSubscriber::pre_gc()`] /
    /// [`ManagerEventSubscriber::post_gc()`] pair.
    pub unsafe fn with_capacity(capacity: usize) -> Self {
        let () = Self::CHECK_ENTRY_CAP;
        let buckets = capacity
            .checked_next_power_of_two()
            .expect("capacity is too large");
        #[cfg(not(feature = "hugealloc"))]
        let mut vec = Vec::with_capacity(buckets);
        #[cfg(feature = "hugealloc")]
        let mut vec = Vec::with_capacity_in(buckets, hugealloc::HugeAlloc);

        vec.resize_with(buckets, || Entry::INIT);
        DMApplyCache(vec.into_boxed_slice(), PhantomData)
    }

    /// Get the bucket for the given operator and operands
    #[inline(always)]
    fn bucket(
        &self,
        operator: O,
        operands: (&[Ref<'_, M::Edge>], &[u32]),
    ) -> &Entry<M, O, ENTRY_CAP> {
        let mut hasher = H::default();
        operator.hash(&mut hasher);
        for o in operands.0 {
            o.hash(&mut hasher);
        }
        for o in operands.1 {
            o.hash(&mut hasher);
        }
        let mask = (self.0.len() - 1) as u64; // bucket count is a power of two
        let index = (hasher.finish() & mask) as usize;
        debug_assert!(index < self.0.len());
        // SAFETY: access is guaranteed to be in bounds
        unsafe { self.0.get_unchecked(index) }
    }
}

#[cfg(feature = "statistics")]
static STAT_ACCESSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

#[cfg(feature = "statistics")]
static STAT_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

#[cfg(feature = "statistics")]
static STAT_INSERTIONS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

impl<M, O, H, const ENTRY_CAP: usize> crate::StatisticsGenerator
    for DMApplyCache<M, O, H, ENTRY_CAP>
where
    M: Manager,
    O: Copy + Eq,
{
    #[cfg(not(feature = "statistics"))]
    fn print_stats(&self) {}

    #[cfg(feature = "statistics")]
    fn print_stats(&self) {
        let count = self.0.len();
        debug_assert_ne!(count, 0);
        let occupied = self.0.iter().filter(|e| e.lock().is_occupied()).count();

        let accesses = STAT_ACCESSES.swap(0, std::sync::atomic::Ordering::Relaxed);
        let hits = STAT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed);
        let insertions = STAT_INSERTIONS.swap(0, std::sync::atomic::Ordering::Relaxed);
        println!(
            "[DMApplyCache] fill level: {:.2} %, accesses: {accesses}, hits: {hits}, insertions: {insertions}, hit ratio ~{:.2} %",
            100.0 * occupied as f32 / count as f32,
            100.0 * hits as f32 / accesses as f32,
        );
    }
}

impl<M, O, H, const ENTRY_CAP: usize> ApplyCache<M, O> for DMApplyCache<M, O, H, ENTRY_CAP>
where
    M: Manager,
    O: Copy + Hash + Ord,
    H: Hasher + Default,
{
    #[inline(always)]
    fn get_extended<const E: usize, const N: usize>(
        &self,
        manager: &M,
        operator: O,
        operands: (&[Ref<'_, M::Edge>], &[u32]),
    ) -> Option<([Own<M::Edge>; E], [u32; N])> {
        let total_operands = operands.0.len() + operands.1.len();
        if total_operands == 0
            || total_operands + (N + E) > ENTRY_CAP
            || operands.0.len() > KIND_COUNT
            || operands.1.len() > KIND_COUNT
            || const { N > KIND_COUNT || E > KIND_COUNT }
        {
            return None;
        }
        self.bucket(operator, operands)
            .try_lock()?
            .get(manager, operator, operands)
    }

    #[inline(always)]
    fn add_extended(
        &self,
        _manager: &M,
        operator: O,
        operands: (&[Ref<'_, M::Edge>], &[u32]),
        values: (&[Ref<'_, M::Edge>], &[u32]),
    ) {
        let total_operands = operands.0.len() + operands.1.len();
        if total_operands == 0
            || total_operands + (values.0.len() + values.1.len()) > ENTRY_CAP
            || operands.0.len() > KIND_COUNT
            || operands.1.len() > KIND_COUNT
            || values.0.len() > KIND_COUNT
            || values.1.len() > KIND_COUNT
        {
            return;
        }
        if let Some(mut entry) = self.bucket(operator, operands).try_lock() {
            entry.set(operator, operands, values);
        }
    }

    fn clear(&self, _manager: &M) {
        for entry in &*self.0 {
            entry.lock().clear();
        }
    }
}

impl<M, O, H, const ENTRY_CAP: usize> ManagerEventSubscriber<M> for DMApplyCache<M, O, H, ENTRY_CAP>
where
    M: Manager,
    O: Copy + Hash + Ord,
    H: Hasher + Default,
{
    fn pre_gc(&self, _manager: &M) {
        // FIXME: We should probably do something smarter than clearing the
        // entire cache.
        for entry in &*self.0 {
            let mut entry = entry.lock();
            entry.clear();
            // Don't unlock!
            std::mem::forget(entry);
        }
    }

    unsafe fn post_gc(&self, _manager: &M) {
        for entry in &*self.0 {
            // SAFETY: `post_gc()` is called at most once after `pre_gc()` and
            // reordering. Hence, the mutex is locked. The cache is empty, so
            // we don't risk that a call to `get()` returns an invalid edge.
            unsafe { entry.mutex.unlock() };
        }
    }
}

impl<M, O, H, const ENTRY_CAP: usize> fmt::Debug for DMApplyCache<M, O, H, ENTRY_CAP>
where
    M: Manager,
    M::Edge: fmt::Debug,
    O: Copy + Eq + fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_map()
            .entries(
                self.0
                    .iter()
                    .enumerate()
                    .map(|(i, e)| (i, e.lock()))
                    .filter(|(_, e)| e.is_occupied()),
            )
            .finish()
    }
}

impl<M, O, const ENTRY_CAP: usize> fmt::Debug for EntryGuard<'_, M, O, ENTRY_CAP>
where
    M: Manager,
    M::Edge: fmt::Debug,
    O: Copy + Eq + fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // SAFETY: The entry is locked.
        let operands = unsafe { *self.0.operands.get() };
        if operands == CountPair::NULL {
            return f.write_str("None");
        }

        // SAFETY: The entry is (1-3) locked and (1) occupied.
        let operator = unsafe { (*self.0.operator.get()).assume_init() };
        let values = unsafe { *self.0.operands.get() };
        let mut data = unsafe { &*self.0.data.get() }.iter();

        f.write_str("{{ ")?;
        operator.fmt(f)?;

        let mut tuple = f.debug_tuple("");
        for operand in data.by_ref().take(operands.edge()) {
            tuple.field(&unsafe { operand.edge });
        }
        for operand in data.by_ref().take(operands.numeric()) {
            tuple.field(&unsafe { operand.numeric });
        }
        tuple.finish()?;

        f.write_str(" = ")?;

        let mut tuple = f.debug_tuple("");
        for value in data.by_ref().take(values.edge()) {
            tuple.field(&unsafe { value.edge });
        }
        for value in data.by_ref().take(values.numeric()) {
            tuple.field(&unsafe { value.numeric });
        }
        tuple.finish()?;

        f.write_str(" }}")
    }
}