pub const MAX_DOC_BYTES: usize = 1024 * 1024;
pub const DOC_SIZE_WARN_BYTES: usize = 768 * 1024;
pub const COMPACT_MIN_DELTA_LOG_BYTES: usize = 64 * 1024;
pub const COMPACT_DELTA_LOG_RATIO: usize = 4;
pub const COMPACT_MAX_COMMITS: u32 = 1024;
pub fn should_compact(
delta_log_bytes: usize,
compacted_doc_bytes: usize,
commits_since_compaction: u32,
) -> bool {
if commits_since_compaction >= COMPACT_MAX_COMMITS {
return true;
}
let ratio_threshold = compacted_doc_bytes.saturating_mul(COMPACT_DELTA_LOG_RATIO);
delta_log_bytes > ratio_threshold.max(COMPACT_MIN_DELTA_LOG_BYTES)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SizeVerdict {
Ok,
Warn,
TooLarge,
}
pub fn size_verdict(compacted_bytes: usize) -> SizeVerdict {
if compacted_bytes > MAX_DOC_BYTES {
SizeVerdict::TooLarge
} else if compacted_bytes >= DOC_SIZE_WARN_BYTES {
SizeVerdict::Warn
} else {
SizeVerdict::Ok
}
}
pub fn needs_size_check(last_measured_bytes: usize, delta_bytes_since: usize) -> bool {
last_measured_bytes.saturating_add(delta_bytes_since) >= DOC_SIZE_WARN_BYTES
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn small_documents_do_not_compact_on_every_commit() {
assert!(!should_compact(8 * 1024, 900, 3));
}
#[test]
fn the_floor_is_not_a_ceiling_for_large_documents() {
assert!(!should_compact(100 * 1024, 200 * 1024, 10));
assert!(should_compact(900 * 1024, 200 * 1024, 10));
}
#[test]
fn a_never_compacted_document_uses_the_floor() {
assert!(!should_compact(COMPACT_MIN_DELTA_LOG_BYTES, 0, 1));
assert!(should_compact(COMPACT_MIN_DELTA_LOG_BYTES + 1, 0, 1));
}
#[test]
fn commit_count_forces_compaction_regardless_of_size() {
assert!(should_compact(1, 10 * 1024 * 1024, COMPACT_MAX_COMMITS));
}
#[test]
fn size_verdict_boundaries() {
assert_eq!(size_verdict(0), SizeVerdict::Ok);
assert_eq!(size_verdict(DOC_SIZE_WARN_BYTES - 1), SizeVerdict::Ok);
assert_eq!(size_verdict(DOC_SIZE_WARN_BYTES), SizeVerdict::Warn);
assert_eq!(size_verdict(MAX_DOC_BYTES), SizeVerdict::Warn);
assert_eq!(size_verdict(MAX_DOC_BYTES + 1), SizeVerdict::TooLarge);
}
#[test]
fn the_cap_leaves_room_under_the_record_ceiling() {
assert!(MAX_DOC_BYTES * 4 <= 4 * 1024 * 1024);
assert!(DOC_SIZE_WARN_BYTES < MAX_DOC_BYTES);
}
#[test]
fn size_checks_engage_before_the_cap_can_be_crossed() {
assert!(!needs_size_check(DOC_SIZE_WARN_BYTES - 1, 0));
assert!(needs_size_check(DOC_SIZE_WARN_BYTES - 1, 1));
assert!(needs_size_check(1024, DOC_SIZE_WARN_BYTES));
}
}