Skip to main content

qualia_core_db/net/qdnf/harness/
allocation.rs

1//! Thread-local hot-path allocation counter. Parallel tests need no serial flag.
2
3use core::cell::Cell;
4
5use crate::net::qdnf::errors::QdnfError;
6use crate::net::qdnf::types::Generation;
7
8thread_local! {
9    static HOT_ALLOCS: Cell<u64> = const { Cell::new(0) };
10}
11
12/// Record one hot-path heap touch on the calling thread.
13#[inline]
14pub fn record_alloc() {
15    HOT_ALLOCS.with(|c| c.set(c.get().wrapping_add(1)));
16}
17
18/// Take and reset this thread's hot-path allocation count.
19#[inline]
20pub fn take_alloc() -> u64 {
21    HOT_ALLOCS.with(|c| c.replace(0))
22}
23
24/// Peek without reset. Tests on other threads do not observe this value.
25#[inline]
26pub fn peek_alloc() -> u64 {
27    HOT_ALLOCS.with(|c| c.get())
28}
29
30const POOL_SLOTS: usize = 8;
31
32#[derive(Clone, Copy, Debug)]
33struct PoolSlot {
34    occupied: bool,
35    owner: u8,
36    bytes: u32,
37    generation: Generation,
38}
39
40impl PoolSlot {
41    const EMPTY: Self = Self {
42        occupied: false,
43        owner: 0,
44        bytes: 0,
45        generation: Generation::ZERO,
46    };
47}
48
49/// Harness lease handle. Not the product `LeaseTable`.
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub struct HarnessLease {
52    pub slot: u8,
53    pub owner: u8,
54    pub bytes: u32,
55    pub generation: Generation,
56}
57
58/// Bounded reservation tracker: conservation, ownership, generation, peak bytes.
59pub struct ReservationTracker {
60    slots: [PoolSlot; POOL_SLOTS],
61    live_bytes: u64,
62    peak_bytes: u64,
63    live_leases: u8,
64}
65
66impl ReservationTracker {
67    /// Creates a default `ReservationTracker`.
68    pub const fn new() -> Self {
69        Self {
70            slots: [PoolSlot::EMPTY; POOL_SLOTS],
71            live_bytes: 0,
72            peak_bytes: 0,
73            live_leases: 0,
74        }
75    }
76
77    /// `ReservationTracker::live_bytes`.
78    pub const fn live_bytes(&self) -> u64 {
79        self.live_bytes
80    }
81
82    /// `ReservationTracker::peak_bytes`.
83    pub const fn peak_bytes(&self) -> u64 {
84        self.peak_bytes
85    }
86
87    /// `ReservationTracker::live_leases`.
88    pub const fn live_leases(&self) -> u8 {
89        self.live_leases
90    }
91
92    /// Live allocation generation.
93    pub fn live_generation(&self, slot: u8) -> Result<Generation, QdnfError> {
94        let i = slot as usize;
95        if i >= POOL_SLOTS {
96            return Err(QdnfError::Range);
97        }
98        if !self.slots[i].occupied {
99            return Err(QdnfError::Incomplete);
100        }
101        Ok(self.slots[i].generation)
102    }
103
104    /// Reserves capacity.
105    pub fn reserve(&mut self, owner: u8, bytes: u32) -> Result<HarnessLease, QdnfError> {
106        let mut i = 0;
107        while i < POOL_SLOTS {
108            if !self.slots[i].occupied {
109                let generation = self.slots[i].generation.next()?;
110                self.slots[i] = PoolSlot {
111                    occupied: true,
112                    owner,
113                    bytes,
114                    generation,
115                };
116                self.live_leases = self.live_leases.saturating_add(1);
117                self.live_bytes = self
118                    .live_bytes
119                    .checked_add(bytes as u64)
120                    .ok_or(QdnfError::Range)?;
121                if self.live_bytes > self.peak_bytes {
122                    self.peak_bytes = self.live_bytes;
123                }
124                return Ok(HarnessLease {
125                    slot: i as u8,
126                    owner,
127                    bytes,
128                    generation,
129                });
130            }
131            i += 1;
132        }
133        Err(QdnfError::Capacity)
134    }
135
136    /// Releases the resource.
137    pub fn release(&mut self, lease: HarnessLease) -> Result<(), QdnfError> {
138        let i = lease.slot as usize;
139        if i >= POOL_SLOTS {
140            return Err(QdnfError::Range);
141        }
142        let slot = &mut self.slots[i];
143        if !slot.occupied {
144            return Err(QdnfError::DoubleRelease);
145        }
146        if slot.generation != lease.generation {
147            return Err(QdnfError::StaleGeneration);
148        }
149        if slot.owner != lease.owner {
150            return Err(QdnfError::Denied);
151        }
152        self.live_bytes = self.live_bytes.saturating_sub(slot.bytes as u64);
153        self.live_leases = self.live_leases.saturating_sub(1);
154        slot.occupied = false;
155        slot.bytes = 0;
156        slot.owner = 0;
157        Ok(())
158    }
159
160    /// Occupied-slot sum. Must equal `live_bytes` after every mutating call.
161    pub fn occupied_bytes(&self) -> u64 {
162        let mut sum = 0u64;
163        let mut i = 0;
164        while i < POOL_SLOTS {
165            if self.slots[i].occupied {
166                sum = sum.saturating_add(self.slots[i].bytes as u64);
167            }
168            i += 1;
169        }
170        sum
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    #[test]
179    fn take_alloc_is_thread_local() {
180        let _ = take_alloc();
181        record_alloc();
182        record_alloc();
183        assert_eq!(take_alloc(), 2);
184        assert_eq!(take_alloc(), 0);
185
186        let child = std::thread::spawn(|| {
187            record_alloc();
188            take_alloc()
189        });
190        assert_eq!(child.join().unwrap(), 1);
191        assert_eq!(peek_alloc(), 0);
192    }
193
194    #[test]
195    fn hot_alloc_covers_success_error_cancel() {
196        let _ = take_alloc();
197        assert_eq!(take_alloc(), 0);
198
199        record_alloc();
200        let err = QdnfError::Capacity;
201        assert_eq!(err, QdnfError::Capacity);
202        assert_eq!(take_alloc(), 1);
203
204        record_alloc();
205        let cancel = QdnfError::Cancelled;
206        assert_eq!(cancel, QdnfError::Cancelled);
207        assert_eq!(take_alloc(), 1);
208    }
209
210    #[test]
211    fn reservation_conservation_and_peak() {
212        let mut pool = ReservationTracker::new();
213        let a = pool.reserve(1, 100).unwrap();
214        let b = pool.reserve(2, 50).unwrap();
215        assert_eq!(pool.live_bytes(), 150);
216        assert_eq!(pool.occupied_bytes(), 150);
217        assert_eq!(pool.peak_bytes(), 150);
218        assert_eq!(pool.live_leases(), 2);
219        assert_eq!(pool.live_generation(a.slot).unwrap(), a.generation);
220
221        pool.release(a).unwrap();
222        assert_eq!(pool.live_bytes(), 50);
223        assert_eq!(pool.occupied_bytes(), 50);
224        assert_eq!(pool.peak_bytes(), 150);
225
226        assert_eq!(pool.release(a), Err(QdnfError::DoubleRelease));
227        let mut stolen = b;
228        stolen.owner = 9;
229        assert_eq!(pool.release(stolen), Err(QdnfError::Denied));
230        pool.release(b).unwrap();
231        assert_eq!(pool.live_bytes(), 0);
232        assert_eq!(pool.live_leases(), 0);
233    }
234}