qualia_core_db/inference/
thermal_wal.rs1use bytemuck::{Pod, Zeroable};
2use memmap2::{MmapMut, MmapOptions};
3use std::fs::OpenOptions;
4use std::path::Path;
5
6#[repr(C)]
7#[derive(Copy, Clone, Debug, Pod, Zeroable)]
8pub struct ThermalEvictionRecord {
9 pub timestamp_ms: u64,
10 pub page_id: u32,
11 pub fast_entropy: f32,
12 pub top1_v: f32,
13 pub top2_v: f32,
14 pub reserved: [u8; 8], }
16
17#[repr(C)]
18#[derive(Copy, Clone, Debug, Pod, Zeroable)]
19pub struct ThermalWalHeader {
20 pub magic: [u8; 4], pub version: u32,
22 pub head: u32, pub capacity: u32, pub reserved: [u8; 48], }
26
27pub struct ThermalWal {
28 mmap: MmapMut,
29 capacity: usize,
30 head: usize,
31}
32
33impl ThermalWal {
34 pub fn open(path: &Path, capacity_records: usize) -> std::io::Result<Self> {
36 let file_size = 64 + (capacity_records * 32);
37 let file = OpenOptions::new()
38 .read(true)
39 .write(true)
40 .create(true)
41 .open(path)?;
42 file.set_len(file_size as u64)?;
43
44 let mut mmap = unsafe { MmapOptions::new().map_mut(&file)? };
45
46 let header_ptr = mmap.as_mut_ptr() as *mut ThermalWalHeader;
48 let mut head = 0;
49 unsafe {
50 if (*header_ptr).magic != *b"WAL\0" {
51 (*header_ptr).magic = *b"WAL\0";
52 (*header_ptr).version = 1;
53 (*header_ptr).head = 0;
54 (*header_ptr).capacity = capacity_records as u32;
55 } else {
56 head = (*header_ptr).head as usize;
57 }
58 }
59
60 Ok(Self {
61 mmap,
62 capacity: capacity_records,
63 head,
64 })
65 }
66
67 pub fn append(&mut self, record: ThermalEvictionRecord) {
69 let offset = 64 + (self.head * 32);
70 let record_bytes = bytemuck::bytes_of(&record);
71 self.mmap[offset..offset + 32].copy_from_slice(record_bytes);
72
73 self.head = (self.head + 1) % self.capacity;
74 let header_ptr = self.mmap.as_mut_ptr() as *mut ThermalWalHeader;
75 unsafe {
76 (*header_ptr).head = self.head as u32;
77 }
78 }
79}