use crate::error::Result;
use crate::store::metadata::{MetadataStore, SqliteMetadataStore};
use crate::types::TenantId;
#[derive(Debug, Clone, Default)]
pub struct CompactionMetrics {
pub tombstone_ratio: f32,
pub active_chunks: usize,
pub deleted_chunks: usize,
pub segment_count: usize,
pub hnsw_staleness: f32,
pub hnsw_cache_size: usize,
pub hnsw_index_size: usize,
}
impl CompactionMetrics {
pub fn gather(
metadata: &SqliteMetadataStore,
hnsw_stats: (usize, usize),
segment_count: usize,
tenant_id: &TenantId,
) -> Result<Self> {
let (active, deleted, candidates) = metadata.count_by_status(tenant_id)?;
let total = active + deleted + candidates;
let tombstone_ratio = if total > 0 {
deleted as f32 / total as f32
} else {
0.0
};
let (hnsw_cache_size, hnsw_index_size) = hnsw_stats;
let hnsw_staleness = if hnsw_index_size > 0 {
let orphans = hnsw_index_size.saturating_sub(hnsw_cache_size);
orphans as f32 / hnsw_index_size as f32
} else {
0.0
};
Ok(Self {
tombstone_ratio,
active_chunks: active,
deleted_chunks: deleted,
segment_count,
hnsw_staleness,
hnsw_cache_size,
hnsw_index_size,
})
}
pub fn exceeds_tombstone_threshold(&self, threshold: f32) -> bool {
self.tombstone_ratio > threshold
}
pub fn exceeds_segment_threshold(&self, threshold: usize) -> bool {
self.segment_count > threshold
}
pub fn exceeds_hnsw_staleness_threshold(&self, threshold: f32) -> bool {
self.hnsw_staleness > threshold
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_metrics() {
let metrics = CompactionMetrics::default();
assert!((metrics.tombstone_ratio - 0.0).abs() < 0.001);
assert_eq!(metrics.active_chunks, 0);
assert_eq!(metrics.deleted_chunks, 0);
assert_eq!(metrics.segment_count, 0);
assert!((metrics.hnsw_staleness - 0.0).abs() < 0.001);
}
#[test]
fn exceeds_tombstone_threshold() {
let metrics = CompactionMetrics {
tombstone_ratio: 0.25,
..Default::default()
};
assert!(metrics.exceeds_tombstone_threshold(0.20));
assert!(!metrics.exceeds_tombstone_threshold(0.30));
}
#[test]
fn exceeds_segment_threshold() {
let metrics = CompactionMetrics {
segment_count: 15,
..Default::default()
};
assert!(metrics.exceeds_segment_threshold(10));
assert!(!metrics.exceeds_segment_threshold(20));
}
#[test]
fn exceeds_hnsw_staleness_threshold() {
let metrics = CompactionMetrics {
hnsw_staleness: 0.20,
..Default::default()
};
assert!(metrics.exceeds_hnsw_staleness_threshold(0.15));
assert!(!metrics.exceeds_hnsw_staleness_threshold(0.25));
}
}