1 //! inf3r-ledger — byte reservations per device.2 //!3 //! The ledger is the only reason the core unloads a model (core.md section 3).4 //! It counts bytes because a byte is what a driver refuses to allocate: a5 //! percentage of device memory is not a number that any allocator can use.6 //!7 //! One reservation covers every device of a target, and it is all or nothing.8 //! A target that needs 8 GiB on each of two devices either holds both or holds9 //! nothing; a half reservation would leave a model that cannot start holding10 //! memory that another model could have used.11 12 use std::collections::BTreeMap;13 use std::fmt;14 15 /// A device as the host reports it.16 #[derive(Clone, PartialEq, Eq, Debug)]17 pub struct Device {18 /// The identifier that the catalogue and the operator use.19 pub id: String,20 /// Bytes that a process may allocate on this device.21 pub bytes: u64,22 }23 24 /// The reason a reservation failed.25 #[derive(Clone, PartialEq, Eq, Debug)]26 pub enum LedgerError {27 /// The device is not in the ledger.28 Unknown {29 /// The device that a caller named.30 device: String,31 },32 /// The device does not have the bytes.33 NoRoom {34 /// The device that is short.35 device: String,36 /// Bytes that the device has now.37 free: u64,38 /// Bytes that the caller asked for.39 want: u64,40 },41 /// A reservation that the ledger did not issue, or issued once before.42 Spent {43 /// The reservation identifier.44 id: u64,45 },46 }47 48 impl fmt::Display for LedgerError {49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {50 match self {51 LedgerError::Unknown { device } => write!(f, "unknown device {device}"),52 LedgerError::NoRoom { device, free, want } => {53 write!(f, "{device} has {free} bytes free, {want} are wanted")54 }55 LedgerError::Spent { id } => write!(f, "reservation {id} is not held"),56 }57 }58 }59 60 impl std::error::Error for LedgerError {}61 62 /// The right to hold bytes on a set of devices until it is released.63 ///64 /// A reservation is not cloneable: a copy would release the same bytes twice.65 /// Dropping one without a release is a bug, so the value asserts that the66 /// caller gave it back (core.md section 4 rule 4).67 #[derive(PartialEq, Eq, Debug)]68 pub struct Reservation {69 id: u64,70 held: BTreeMap<String, u64>,71 released: bool,72 }73 74 impl Drop for Reservation {75 fn drop(&mut self) {76 assert!(77 self.released || self.held.is_empty(),78 "reservation {} was dropped without a release",79 self.id80 );81 }82 }83 84 impl Reservation {85 /// The identifier that this reservation had in the ledger.86 pub fn id(&self) -> u64 {87 self.id88 }89 90 /// Bytes held on each device.91 pub fn held(&self) -> &BTreeMap<String, u64> {92 &self.held93 }94 95 /// Bytes held on the whole target: the sum of every device.96 pub fn total(&self) -> u64 {97 self.held.values().sum()98 }99 }100 101 /// Bytes per device, held and free.102 #[derive(Clone, PartialEq, Eq, Debug, Default)]103 pub struct Ledger {104 devices: BTreeMap<String, DeviceState>,105 next: u64,106 }107 108 #[derive(Clone, PartialEq, Eq, Debug)]109 struct DeviceState {110 bytes: u64,111 held: BTreeMap<u64, u64>,112 }113 114 impl DeviceState {115 fn held(&self) -> u64 {116 self.held.values().sum()117 }118 119 fn free(&self) -> u64 {120 self.bytes.saturating_sub(self.held())121 }122 }123 124 impl Ledger {125 /// A ledger with no reservation and the devices that the host reports.126 pub fn new(devices: impl IntoIterator<Item = Device>) -> Ledger {127 let devices = devices128 .into_iter()129 .map(|device| {130 (131 device.id,132 DeviceState {133 bytes: device.bytes,134 held: BTreeMap::new(),135 },136 )137 })138 .collect();139 Ledger { devices, next: 1 }140 }141 142 /// Adds a device to the ledger if it is not already there.143 ///144 /// The first declaration wins. A second declaration would silently change145 /// the capacity under reservations that are already held, so it is146 /// refused. Adding devices one at a time keeps every existing reservation147 /// in place.148 pub fn add_device(&mut self, device: &str, bytes: u64) -> bool {149 if self.devices.contains_key(device) {150 return false;151 }152 self.devices.insert(153 device.to_string(),154 DeviceState {155 bytes,156 held: BTreeMap::new(),157 },158 );159 true160 }161 162 /// Bytes that a device has in total.163 pub fn total(&self, device: &str) -> Option<u64> {164 self.devices.get(device).map(|state| state.bytes)165 }166 167 /// Bytes that a device holds now.168 pub fn held(&self, device: &str) -> u64 {169 self.devices.get(device).map(DeviceState::held).unwrap_or(0)170 }171 172 /// Bytes that a device can still reserve.173 pub fn free(&self, device: &str) -> u64 {174 self.devices.get(device).map(DeviceState::free).unwrap_or(0)175 }176 177 /// Bytes held on the whole machine.178 pub fn held_total(&self) -> u64 {179 self.devices.values().map(DeviceState::held).sum()180 }181 182 /// Records bytes on every device, or on none.183 ///184 /// The check and the record happen in one step, so two callers that fit185 /// alone cannot both succeed.186 pub fn reserve(&mut self, wants: &BTreeMap<String, u64>) -> Result<Reservation, LedgerError> {187 for (device, want) in wants {188 let state = self189 .devices190 .get(device)191 .ok_or_else(|| LedgerError::Unknown {192 device: device.clone(),193 })?;194 if *want > state.free() {195 return Err(LedgerError::NoRoom {196 device: device.clone(),197 free: state.free(),198 want: *want,199 });200 }201 }202 203 let id = self.next;204 self.next += 1;205 for (device, want) in wants {206 if *want == 0 {207 continue;208 }209 if let Some(state) = self.devices.get_mut(device) {210 state.held.insert(id, *want);211 }212 }213 214 let held = wants215 .iter()216 .filter(|(_, want)| **want > 0)217 .map(|(device, want)| (device.clone(), *want))218 .collect();219 Ok(Reservation {220 id,221 held,222 released: false,223 })224 }225 226 /// Gives back exactly the bytes that the reservation holds.227 ///228 /// A reservation that was released, or one that this ledger did not issue,229 /// is a bug in the caller and is reported as such.230 pub fn release(&mut self, mut reservation: Reservation) -> Result<(), LedgerError> {231 // The value is consumed by this call, so no later drop may complain232 // about it even when the identifier is not one that this ledger issued.233 reservation.released = true;234 // A reservation of zero bytes holds nothing, so giving it back is235 // already done.236 if reservation.held.is_empty() {237 return Ok(());238 }239 let mut found = false;240 for (device, want) in &reservation.held {241 let Some(state) = self.devices.get_mut(device) else {242 continue;243 };244 if state.held.get(&reservation.id) == Some(want) {245 state.held.remove(&reservation.id);246 found = true;247 }248 }249 if found {250 Ok(())251 } else {252 Err(LedgerError::Spent { id: reservation.id })253 }254 }255 256 /// The devices of the machine, in identifier order.257 pub fn devices(&self) -> impl Iterator<Item = (&str, u64, u64)> {258 self.devices259 .iter()260 .map(|(id, state)| (id.as_str(), state.bytes, state.free()))261 }262 }