136 lines · 7.7 KB · RustRaw
//! One keep-free policy per device, shared by media, jobs and cache trimming.use cotton_store::driver::Row;/// A device keeps 15% of its volume by default. A person's byte setting can/// lower that reserve to 10% of the volume, or raise it.pub fn keep_free_bytes(total_bytes: u64, raised_bytes: Option<u64>) -> u64 { let default = (u128::from(total_bytes) * 15).div_ceil(100) as u64; match raised_bytes { Some(bytes) => bytes.max((u128::from(total_bytes) * 10).div_ceil(100) as u64), None => default, }}/// The same policy in the GiB units used by machine samples and schedulers.pub fn keep_free_gb(total_gb: f64, raised_bytes: Option<u64>) -> f64 { keep_free_bytes((total_gb * 1_073_741_824.0) as u64, raised_bytes) as f64 / 1_073_741_824.0}/// Read the device row rather than giving each consumer another default./// A NULL setting uses the volume default.pub fn read_keep_free_bytes(row: &Row, total_bytes: u64) -> u64 { let raised = row.int("keep_free_bytes").and_then(|n| u64::try_from(n).ok()); keep_free_bytes(total_bytes, raised)}/// Capacity is a device fact even when only one database row reports it.pub fn device_disk_total_gb(rows: &[Row]) -> Option<f64> { rows.iter().filter_map(|row| row.real("disk_total_gb")) .filter(|total| total.is_finite() && *total > 0.0) .max_by(f64::total_cmp)}/// Read live rows and the receipt time of the setting itself. Device telemetry/// also edits updated_at, so it must never make an old floor look newly chosen.pub fn device_disk_rows(db: &cotton_store::Driver, device: &str) -> cotton_store::Result<Vec<Row>> { let rows = db.all( "SELECT id, workspace_id, disk_total_gb, keep_free_bytes, updated_at FROM cotton_devices WHERE device_id = ? AND revoked_at IS NULL", &[device.to_string().into()], )?; rows.into_iter().map(|row| { let id = row.text("id").unwrap_or_default(); let receipts = cotton_store::receipts::of_row(db, "cotton_devices", id)?; let retract = cotton_store::receipts::retract_stamp(db, "cotton_devices", id)?; let life = cotton_store::receipts::assemble("cotton_devices", &receipts, retract.as_deref()); let stamp = life.fields.get("keep_free_bytes").map(|field| field.stamp.clone()) .unwrap_or_else(|| { // Rows predating receipts still have the original edited time. let millis = row.text("updated_at").and_then(|at| chrono::DateTime::parse_from_rfc3339(at).ok()) .map_or(0, |at| at.timestamp_millis()); format!("{millis:013}:0000:") }); let mut columns = row.columns().to_vec(); columns.push(("keep_free_written_at".into(), stamp.into())); Ok(Row::new(columns)) }).collect()}/// The resolved number and its evidence, shared by the card and publisher.pub struct DeviceDiskFloor<'a> { pub bytes: u64, pub source: Option<&'a Row>, pub disagreeing_rows: usize,}pub fn resolve_device_floor(rows: &[Row], total_bytes: u64) -> DeviceDiskFloor<'_> { let source = rows.iter() .filter(|row| row.int("keep_free_bytes").is_some_and(|bytes| bytes >= 0)) .max_by_key(|row| (row.text("keep_free_written_at").unwrap_or_default(), row.text("workspace_id").unwrap_or_default(), row.text("id").unwrap_or_default())); let setting = source.and_then(|row| row.int("keep_free_bytes")).map(|bytes| bytes as u64); let disagreeing_rows = source.map_or(0, |source| rows.iter() .filter(|row| row.int("keep_free_bytes") != source.int("keep_free_bytes")).count()); DeviceDiskFloor { bytes: keep_free_bytes(total_bytes, setting), source, disagreeing_rows }}/// One physical disk has one floor: the newest non-NULL setting wins,/// irrespective of its size or the database order.pub fn read_device_keep_free_bytes(rows: &[Row], total_bytes: u64) -> u64 { resolve_device_floor(rows, total_bytes).bytes}#[cfg(test)]mod tests { use super::*; /// RULE: The most recently written non-NULL floor wins across database rows; an older explicit default cannot outrank a newer lower setting. #[test] fn device_floor_uses_the_latest_setting_in_either_row_order() { use rusqlite::types::Value; let row = |bytes, at: &str| Row::new(vec![("keep_free_bytes".into(), Value::Integer(bytes)), ("keep_free_written_at".into(), Value::Text(at.into()))]); let mut rows = vec![row(150, "0000000000100:0000:old"), row(100, "0000000000200:0000:new")]; assert_eq!(read_device_keep_free_bytes(&rows, 1000), 100); rows.reverse(); assert_eq!(read_device_keep_free_bytes(&rows, 1000), 100); } /// RULE: A later telemetry sample cannot outrank a newer floor edit; resolve the setting's own receipt time, with updated_at only for rows that predate receipts. #[test] fn device_floor_receipt_time_ignores_newer_telemetry() { use cotton_store::canonical::{self, Kind, Receipt}; use rusqlite::types::Value; let db = cotton_store::Driver::open_in_memory().unwrap(); db.exec("CREATE TABLE cotton_devices(id TEXT, workspace_id TEXT,device_id TEXT,revoked_at TEXT,disk_total_gb REAL,keep_free_bytes INTEGER,updated_at TEXT); CREATE TABLE _writes(tbl TEXT,row_id TEXT,hlc TEXT,op_id TEXT,held INTEGER,bytes BLOB); CREATE TABLE _tombstones(tbl TEXT,row_id TEXT,hlc TEXT); INSERT INTO cotton_devices VALUES('old','personal','mac',NULL,1000,150,'2030-01-01T00:00:00Z'),('new','project','mac',NULL,NULL,100,'2026-01-01T00:00:00Z'),('unset','other','mac',NULL,NULL,NULL,'2030-01-01T00:00:00Z');").unwrap(); for (id, at, key, value) in [("old", 100, "keep_free_bytes", 150), ("new", 200, "keep_free_bytes", 100), ("old", 300, "disk_total_gb", 1000)] { let receipt = Receipt { table: "cotton_devices".into(), row_id: id.into(), kind: Kind::Change, stamp: format!("{at:013}:0000:synthetic"), author: "synthetic".into(), actor: "job:synthetic".into(), schema: cotton_store::schema::ddl::SCHEMA_VERSION, fields: [(key.into(), serde_json::json!(value))].into(), restamps: None, erase: None, undo: None }; db.run("INSERT INTO _writes VALUES('cotton_devices',?,?,?,0,?)", &[ Value::Text(id.into()), Value::Text(receipt.stamp.clone()), Value::Text(format!("receipt-{at}")), Value::Blob(canonical::encode(&receipt).unwrap()), ]).unwrap(); } let rows = device_disk_rows(&db, "mac").unwrap(); let resolved = resolve_device_floor(&rows, 1000); assert_eq!(resolved.bytes, 100); assert_eq!(resolved.source.unwrap().text("workspace_id"), Some("project")); assert_eq!(resolved.disagreeing_rows, 2); } /// RULE: Every consumer uses one device floor: 15% by default, adjustable down to 10%, so background media cannot fill a disk while jobs and caches protect different numbers. #[test] fn a_device_floor_is_proportional_and_can_be_lowered_to_ten_percent() { assert_eq!(keep_free_bytes(1000, None), 150); assert_eq!(keep_free_bytes(1000, Some(100)), 100); assert_eq!(keep_free_bytes(1000, Some(99)), 100); assert_eq!(keep_free_bytes(101, Some(0)), 11); assert_eq!(keep_free_bytes(1000, Some(300)), 300); assert_eq!(keep_free_bytes(101, None), 16); assert_eq!(keep_free_bytes(u64::MAX, None), 2_767_011_611_056_432_743); assert_eq!(keep_free_gb(1000.0, Some(200 * 1_073_741_824)), 200.0); let row = Row::new(vec![("keep_free_bytes".into(), rusqlite::types::Value::Integer(300))]); assert_eq!(read_keep_free_bytes(&row, 1000), 300); let row = Row::new(vec![("keep_free_bytes".into(), rusqlite::types::Value::Integer(100))]); assert_eq!(read_keep_free_bytes(&row, 1000), 100); }}