//! Metadata-only GPU memory admission for an experimental KAR archive. //! This is not a scheduler, payload verification, or a model quality gate. use std::path::Path; use serde::Serialize; use crate::{kar, kar_overlay}; #[derive(Serialize)] pub struct RecordMemory { pub name: String, pub compressed_bytes: u64, pub decode_bytes: u64, pub single_record_peak_bytes: u64, /// Geometric lower bound for kar_decode_rows, not a model execution plan. pub one_row_peak_bytes: Option, } #[derive(Serialize)] pub struct Report { pub schema: &'static str, pub level: u8, pub budget_bytes: u64, pub record_count: usize, pub all_compressed_resident_bytes: u64, pub largest_decode_scratch_bytes: u64, pub all_resident_plus_scratch_bytes: u64, pub largest_single_record_peak_bytes: u64, pub records_exceeding_budget: usize, pub full_decode_exceeds_but_one_row_fits: usize, pub largest_records: Vec, pub verification: &'static str, } #[derive(Serialize)] pub struct SelectedRecordMemory { pub archive: &'static str, pub level: u8, #[serde(flatten)] pub memory: RecordMemory, } #[derive(Serialize)] pub struct SelectedReport { pub schema: &'static str, pub base_archive_sha256: String, pub overlay_archive_sha256: String, pub base_level: u8, pub overlay_level: u8, pub budget_bytes: u64, pub record_count: usize, pub replacement_count: usize, pub selected_base_compressed_bytes: u64, pub selected_overlay_compressed_bytes: u64, pub selected_compressed_bytes: u64, pub largest_decode_scratch_bytes: u64, pub all_selected_plus_scratch_bytes: u64, pub largest_single_record_peak_bytes: u64, pub records_exceeding_budget: usize, pub full_decode_exceeds_but_one_row_fits: usize, pub largest_records: Vec, pub verification: &'static str, } const SELECTED_VERIFICATION: &str = concat!( "complete base and overlay hashes, payload CRCs, provenance, and replacement mappings verified before ", "metadata planning; keep archives immutable; no GPU execution or model quality check" ); const BOUNDED_VERIFICATION: &str = concat!( "bounded KAR metadata only; payload CRCs, archive SHA-256, model quality, ", "and GPU execution not checked" ); /// Per-record GPU byte arithmetic shared by both planners. struct Measured { compressed: u64, scratch: u64, peak: u64, one_row_peak: Option, } impl Measured { fn of( source: &kar::TensorSource, level: u8, peak_overflow: &'static str, ) -> Result { let compressed = source.gpu_resident_bytes(level)?; let scratch = source.gpu_decode_bytes()?; let peak = compressed.checked_add(scratch).ok_or(peak_overflow)?; let one_row_peak = source .gpu_one_row_decode_bytes() .and_then(|row_bytes| compressed.checked_add(row_bytes)); Ok(Self { compressed, scratch, peak, one_row_peak, }) } fn record(&self, name: String) -> RecordMemory { RecordMemory { name, compressed_bytes: self.compressed, decode_bytes: self.scratch, single_record_peak_bytes: self.peak, one_row_peak_bytes: self.one_row_peak, } } } /// Running maxima and budget counters over the measured records. struct Tally { budget: u64, scratch_max: u64, peak_max: u64, exceeding: usize, row_fits: usize, } impl Tally { fn new(budget: u64) -> Self { Self { budget, scratch_max: 0, peak_max: 0, exceeding: 0, row_fits: 0, } } fn observe(&mut self, measured: &Measured) { self.scratch_max = self.scratch_max.max(measured.scratch); self.peak_max = self.peak_max.max(measured.peak); if measured.peak > self.budget { self.exceeding += 1; } if measured.peak > self.budget && measured .one_row_peak .is_some_and(|bytes| bytes <= self.budget) { self.row_fits += 1; } } } fn by_peak_then_name(a: &RecordMemory, b: &RecordMemory) -> std::cmp::Ordering { b.single_record_peak_bytes .cmp(&a.single_record_peak_bytes) .then_with(|| a.name.cmp(&b.name)) } fn keep_largest(list: &mut Vec, memory: impl Fn(&T) -> &RecordMemory) { list.sort_unstable_by(|a, b| by_peak_then_name(memory(a), memory(b))); list.truncate(10); } /// The verified base and overlay record lists with the level each is planned at. struct SelectedSources { base: Vec, overlay: Vec, base_level: u8, overlay_level: u8, } impl SelectedSources { fn lookup( &self, selected: &kar_overlay::ResolvedRecord, ) -> Result<(&kar::TensorSource, u8), String> { let (list, level) = match selected.archive { "base" => (&self.base, self.base_level), "overlay" => (&self.overlay, self.overlay_level), _ => return Err("unknown KAR selection archive".into()), }; let source = list .get(selected.archive_index) .ok_or("selected KAR record index is out of bounds")?; Ok((source, level)) } } fn check_selected_unchanged( source: &kar::TensorSource, selected: &kar_overlay::ResolvedRecord, ) -> Result<(), String> { if source.name != selected.name || source.offset != selected.source_offset || source.dimensions != selected.dimensions || hex::encode(source.digest) != selected.source_sha256 { return Err(format!("{}: selected KAR record changed", selected.name)); } Ok(()) } /// Totals of one walk over the resolved base/overlay selection. struct SelectedTotals { base_bytes: u64, overlay_bytes: u64, tally: Tally, largest: Vec, } impl SelectedTotals { fn add_compressed(&mut self, from_base: bool, compressed: u64) -> Result<(), String> { let total = if from_base { &mut self.base_bytes } else { &mut self.overlay_bytes }; *total = total .checked_add(compressed) .ok_or("selected KAR compressed total overflow")?; Ok(()) } fn selected_bytes(&self) -> Result { self.base_bytes .checked_add(self.overlay_bytes) .ok_or_else(|| "selected KAR compressed total overflow".into()) } fn all_plus_scratch(&self, selected_bytes: u64) -> Result { selected_bytes .checked_add(self.tally.scratch_max) .ok_or_else(|| "selected KAR all-resident peak overflow".into()) } } fn walk_selected( selection: &kar_overlay::Resolution, sources: &SelectedSources, budget_bytes: u64, ) -> Result { let mut totals = SelectedTotals { base_bytes: 0, overlay_bytes: 0, tally: Tally::new(budget_bytes), largest: Vec::with_capacity(selection.records.len()), }; for selected in &selection.records { let (source, level) = sources.lookup(selected)?; check_selected_unchanged(source, selected)?; let measured = Measured::of(source, level, "selected KAR single-record peak overflow")?; totals.add_compressed(selected.archive == "base", measured.compressed)?; totals.tally.observe(&measured); totals.largest.push(SelectedRecordMemory { archive: selected.archive, level, memory: measured.record(selected.name.clone()), }); } keep_largest(&mut totals.largest, |entry| &entry.memory); Ok(totals) } /// Plan the exact base/overlay record selection after full archive and /// provenance verification. This is metadata arithmetic, not GPU admission. pub fn plan_selected( base_path: &Path, overlay_path: &Path, base_level: u8, overlay_level: u8, budget_bytes: u64, ) -> Result { if !(1..=8).contains(&base_level) || !(1..=8).contains(&overlay_level) || budget_bytes == 0 { return Err("KAR levels must be 1..8 and GPU budget must be positive".into()); } let selection = kar_overlay::resolve_verified(base_path, overlay_path)?; let (_, base) = kar::inspect_with_sources(base_path)?; let (_, overlay) = kar::inspect_with_sources(overlay_path)?; let sources = SelectedSources { base, overlay, base_level, overlay_level, }; let totals = walk_selected(&selection, &sources, budget_bytes)?; selected_report(selection, totals, &sources, budget_bytes) } #[rustfmt::skip] fn selected_report( selection: kar_overlay::Resolution, totals: SelectedTotals, sources: &SelectedSources, budget_bytes: u64, ) -> Result { let selected_bytes = totals.selected_bytes()?; let all_plus_scratch = totals.all_plus_scratch(selected_bytes)?; Ok(SelectedReport { schema: "strata-next/selected-kar-gpu-memory-plan-v1", base_archive_sha256: selection.base_archive_sha256, overlay_archive_sha256: selection.overlay_archive_sha256, base_level: sources.base_level, overlay_level: sources.overlay_level, budget_bytes, record_count: selection.records.len(), replacement_count: selection.replacement_count, selected_base_compressed_bytes: totals.base_bytes, selected_overlay_compressed_bytes: totals.overlay_bytes, selected_compressed_bytes: selected_bytes, largest_decode_scratch_bytes: totals.tally.scratch_max, all_selected_plus_scratch_bytes: all_plus_scratch, largest_single_record_peak_bytes: totals.tally.peak_max, records_exceeding_budget: totals.tally.exceeding, full_decode_exceeds_but_one_row_fits: totals.tally.row_fits, largest_records: totals.largest, verification: SELECTED_VERIFICATION, }) } /// Totals of one walk over every record of a single archive. struct ArchiveTotals { compressed_total: u64, tally: Tally, largest: Vec, } fn walk_archive( records: Vec, level: u8, budget_bytes: u64, ) -> Result { let mut totals = ArchiveTotals { compressed_total: 0, tally: Tally::new(budget_bytes), largest: Vec::with_capacity(records.len()), }; for record in records { let measured = Measured::of(&record, level, "KAR single-record GPU peak overflow")?; totals.compressed_total = totals .compressed_total .checked_add(measured.compressed) .ok_or("KAR total GPU residency overflow")?; totals.tally.observe(&measured); totals.largest.push(measured.record(record.name)); } keep_largest(&mut totals.largest, |entry| entry); Ok(totals) } pub fn plan(path: &Path, level: u8, budget_bytes: u64) -> Result { if !(1..=8).contains(&level) || budget_bytes == 0 { return Err("KAR level must be 1..8 and GPU budget must be positive".into()); } let (summary, records) = kar::inspect_with_sources(path)?; let totals = walk_archive(records, level, budget_bytes)?; let all_plus_scratch = totals .compressed_total .checked_add(totals.tally.scratch_max) .ok_or("KAR all-resident GPU peak overflow")?; Ok(Report { schema: "strata-next/kar-gpu-memory-plan-v1", level, budget_bytes, record_count: summary.tensor_count as usize, all_compressed_resident_bytes: totals.compressed_total, largest_decode_scratch_bytes: totals.tally.scratch_max, all_resident_plus_scratch_bytes: all_plus_scratch, largest_single_record_peak_bytes: totals.tally.peak_max, records_exceeding_budget: totals.tally.exceeding, full_decode_exceeds_but_one_row_fits: totals.tally.row_fits, largest_records: totals.largest, verification: BOUNDED_VERIFICATION, }) } #[cfg(test)] mod tests { use super::*; use std::time::{SystemTime, UNIX_EPOCH}; #[test] fn smoke_fixture_has_bounded_single_record_peak() { let nonce = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); let path = std::env::temp_dir().join(format!( "strata-kar-memory-{}-{nonce}.kar", std::process::id() )); crate::kar_fixture::write(&path).unwrap(); let report = plan(&path, 2, 1 << 20).unwrap(); assert_eq!(report.record_count, 1); assert_eq!(report.records_exceeding_budget, 0); assert!(report.largest_single_record_peak_bytes <= 1 << 20); assert_eq!(plan(&path, 2, 1).unwrap().records_exceeding_budget, 1); std::fs::remove_file(path).unwrap(); } }