diff --git a/core/continuum-dreaming/src/modules/training_trigger/on_engine.rs b/core/continuum-dreaming/src/modules/training_trigger/on_engine.rs index 54f87e2c7d..814ff1f313 100644 --- a/core/continuum-dreaming/src/modules/training_trigger/on_engine.rs +++ b/core/continuum-dreaming/src/modules/training_trigger/on_engine.rs @@ -22,10 +22,10 @@ use super::in_place::{bucket_stem, decide, start, Decided, Decision, Pending}; use super::seat_run::{Heard, NotTold, SeatRun}; use super::{BucketKey, TrainingTriggerState}; use crate::genome::learner::example::learn_messages; -use crate::genome::learner::seat::{lease_memory, Authority, LeasedMemory, SeatRefusal}; +use crate::genome::learner::seat::{lease_memory_within, Authority, LeasedMemory, SeatRefusal}; use crate::inference::learning::{leased, Fit, LearnPort, Lesson, Measure, MemoryRow, Optimizer, PersonaId, Said, SeatId, ShadowSource}; use crate::inference::training_admission::TrainingWait; -use crate::resources::{Free, ResourceKind}; +use crate::resources::{Ask, AskTicket, Free, LeaseGuard, ResourceKind}; use crate::inference::learning::FreshShadow; use continuum_kernel::system_resources::disk_reporters::ClassWriter; @@ -95,8 +95,10 @@ enum HeldOff { /// never memory to wait for. Seated again only on another node engine (the 5090, 2026-11-24: a /// fresh shadow measured at 428,581,700,665,600 VRAM bytes was measured again on every wake). Defect { engine: Weak }, - /// Short of memory: seated again once `needed` bytes of `kind` are free on the authority's board. - Memory { kind: ResourceKind, needed: u64 }, + /// Short of memory: the whole seat was asked of the authority, and the bucket is held until the + /// ask is granted. The grant becomes the bucket's reserve, and its seat's stages are carved from it + /// with no second ask (Codex's contract, 2026-11-26). Dropping the hold withdraws the ask. + Asked { ticket: AskTicket }, } /// The seats the trainer holds on the node engine, and the buckets it holds off. @@ -104,6 +106,9 @@ enum HeldOff { pub(crate) struct OnEngine { seats: parking_lot::Mutex>, held_off: parking_lot::Mutex>, + /// Each bucket's granted reserve: what its ask was granted, carved stage by stage as its seat + /// leases, and released (what is left of it) once the seat is seated or let go. + reserves: parking_lot::Mutex>>, /// Each bucket's minted competence signature, with the rows it was minted from: minting embeds /// every example, so it is minted again only when the bucket's rows change (Codex on the 5090 /// replay, 2026-11-25: a bucket decide() answered NotNow was re-embedded on every wake). @@ -124,15 +129,14 @@ impl OnEngine { self.seats.lock().get(&seat).map(|held| held.key.clone()) } - /// Whether `key` is still held off on `port`, with `free` what the authority shows: a defect - /// while the same engine serves, a memory wait while too little is free. A hold that no longer - /// applies is dropped. - fn holds(&self, key: &BucketKey, port: &Arc, free: &Free) -> bool { + /// Whether `key` is still held off on `port`: a defect while the same engine serves, an ask until it + /// is granted. A granted ask becomes the bucket's reserve and the hold is dropped. + fn holds(&self, key: &BucketKey, port: &Arc) -> bool { let mut held = self.held_off.lock(); - let still = match held.get(key) { + let still = match held.get_mut(key) { None => return false, Some(HeldOff::Defect { engine }) => std::ptr::addr_eq(engine.as_ptr(), Arc::as_ptr(port)), - Some(HeldOff::Memory { kind, needed }) => short(free, *kind, *needed), + Some(HeldOff::Asked { ticket }) => !self.reserve_granted(key, ticket), }; if !still { held.remove(key); @@ -140,6 +144,14 @@ impl OnEngine { still } + /// Take `ticket`'s grant into `key`'s reserve, if it was granted. + fn reserve_granted(&self, key: &BucketKey, ticket: &mut AskTicket) -> bool { + let Some(granted) = ticket.granted() else { return false }; + let key = key.clone(); + self.reserves.lock().entry(key).or_default().push(granted); + true + } + /// Say the pending buckets this engine does not serve the base of, when they or the served base /// changed since last said. fn say_unserved(&self, served: &str, elsewhere: Vec) { @@ -159,53 +171,78 @@ impl OnEngine { /// Whether any bucket waits for memory. fn waits_for_memory(&self) -> bool { - self.held_off.lock().values().any(|hold| matches!(hold, HeldOff::Memory { .. })) + self.held_off.lock().values().any(|hold| matches!(hold, HeldOff::Asked { .. })) } - /// The buckets held for memory that `free` now covers and that hold no seat, their holds - /// dropped: what a release wakes. A bucket whose seat is still being let go is left to its - /// Released ([`Self::covered`]). - fn freed(&self, free: &Free) -> Vec { + /// The buckets whose asks were granted and that hold no seat, their grants taken into their reserves + /// and their holds dropped: what a release wakes. A bucket whose seat is still being let go is left + /// to its Released ([`Self::covered`]). + fn freed(&self) -> Vec { let seats = self.seats.lock(); let mut held = self.held_off.lock(); - let ready: Vec = held - .iter() - .filter(|(key, hold)| matches!(hold, HeldOff::Memory { kind, needed } if !short(free, *kind, *needed)) && !seats.values().any(|seat| seat.key == **key)) - .map(|(key, _)| key.clone()) - .collect(); + let mut ready = Vec::new(); + for (key, hold) in held.iter_mut() { + if seats.values().any(|seat| seat.key == *key) { + continue; + } + if let HeldOff::Asked { ticket } = hold { + if self.reserve_granted(key, ticket) { + ready.push(key.clone()); + } + } + } for key in &ready { held.remove(key); } ready } - /// Whether `key`, its seat just let go, is held for memory that `free` now covers (the hold - /// dropped). A release said while that seat was still being let go woke nothing for it, so its - /// Released seats it again. - fn covered(&self, key: &BucketKey, free: &Free) -> bool { + /// Whether `key`, its seat just let go, had its ask granted (the grant taken into its reserve and + /// the hold dropped). A release said while that seat was still being let go woke nothing for it, so + /// its Released seats it again. + fn covered(&self, key: &BucketKey) -> bool { let mut held = self.held_off.lock(); - let covered = matches!(held.get(key), Some(HeldOff::Memory { kind, needed }) if !short(free, *kind, *needed)); + let covered = match held.get_mut(key) { + Some(HeldOff::Asked { ticket }) => self.reserve_granted(key, ticket), + _ => false, + }; if covered { held.remove(key); } covered } - /// Hold `key` off after the authority refused `needed` bytes of `kind` for `rows`. - fn hold_off(&self, key: &BucketKey, port: &Arc, free: &Free, wait: Short, rows: &[MemoryRow]) { - let Short { kind, needed } = wait; - let capacity = free.kind(kind).map(|governed| governed.capacity); + /// `key`'s reserve is spent or no longer wanted (its seat is seated, or let go): what is left of it + /// goes back to the authority. + fn release_reserve(&self, key: &BucketKey) { + self.reserves.lock().remove(key); + } + + /// Hold `key` off after the authority refused `needed` bytes of `kind` for `rows`: a defect past the + /// whole governed device, otherwise an ask for that much, which waits until it is granted (granted at + /// once, it is the bucket's reserve and nothing is held). + fn hold_off(&self, key: &BucketKey, port: &Arc, wait: Short, ask: impl FnOnce(ResourceKind, u64) -> Result) { + let Short { kind, needed, capacity } = wait; + let defect = |why: &str| { + continuum_base::probe!(class = "training.on_engine.measure_defect", persona = %key.persona_id, kind = ?kind, needed, capacity = ?capacity, why = why, + "the engine measured more than the whole governed device holds: a measurement defect, not a wait; this bucket is not seated again on this engine"); + HeldOff::Defect { engine: Arc::downgrade(port) } + }; let held = match capacity { - Some(capacity) if needed > capacity => { - continuum_base::probe!(class = "training.on_engine.measure_defect", persona = %key.persona_id, kind = ?kind, needed, capacity, rows = ?rows, - "the engine measured more than the whole governed device holds: a measurement defect, not a wait; this bucket is not seated again on this engine"); - HeldOff::Defect { engine: Arc::downgrade(port) } - } - _ => { - continuum_base::probe!(class = "training.on_engine.awaiting_memory", persona = %key.persona_id, kind = ?kind, needed, capacity = ?capacity, - "short of memory: this bucket is not measured again until the authority says that much is free"); - HeldOff::Memory { kind, needed } - } + Some(capacity) if needed > capacity => defect("past the governed capacity"), + _ => match ask(kind, needed) { + Ok(Ask::Granted(granted)) => { + let key = key.clone(); + self.reserves.lock().entry(key).or_default().push(granted); + return; + } + Ok(Ask::Waiting { ticket, short }) => { + continuum_base::probe!(class = "training.on_engine.awaiting_memory", persona = %key.persona_id, kind = ?kind, needed, short, capacity = ?capacity, + "short of memory: the whole seat is asked of the authority, and this bucket waits for the grant"); + HeldOff::Asked { ticket } + } + Err(refused) => defect(&format!("the authority refused the ask: {refused:?}")), + }, }; self.held_off.lock().insert(key.clone(), held); } @@ -230,20 +267,16 @@ struct Lease<'a> { whole: &'a [MemoryRow], } -/// What the authority refused: `needed` bytes of `kind`. +/// What the authority refused: `needed` bytes of `kind`, of the `capacity` it governs of that kind +/// (`None` when it governs none). struct Short { kind: ResourceKind, needed: u64, -} - -/// Whether `free` shows less than `needed` bytes of `kind` free (a kind it does not govern has -/// nothing free yet). -fn short(free: &Free, kind: ResourceKind, needed: u64) -> bool { - free.kind(kind).is_none_or(|governed| governed.available < needed) + capacity: Option, } /// What a seat may lease of each kind beside its `weights`: what the authority governs of that kind -/// less them. A kind it does not govern leaves none, as [`short`] reads it, and weights past a byte +/// less them. A kind it does not govern leaves none, and weights past a byte /// count leave none. fn fit_beside(free: &Free, weights: &[MemoryRow]) -> Fit { let room = |kind: ResourceKind| match (free.kind(kind), leased(weights, kind)) { @@ -364,13 +397,14 @@ impl TrainingTriggerState { } } - /// What is free, said by the authority, for the buckets held for memory on the node engine. - pub(crate) async fn heard_free(self: &Arc, free: &Free) { + /// The authority said its board changed: a release may have granted the asks of buckets held for + /// memory (what is free is the authority's to grant, not the trainer's to read). + pub(crate) async fn heard_free(self: &Arc, _changed: &Free) { if !self.on_engine.waits_for_memory() { return; // nothing held: the engine is not asked what it serves } let (Some(port), Some(served)) = (port(), served_model().await) else { return }; - self.on_free(&port, free, &served).await; + self.on_free(&port, &served).await; } /// Seat every bucket whose base `served_model` serves and that has a lesson waiting, through @@ -394,11 +428,20 @@ impl TrainingTriggerState { /// nothing here to seat (Codex on #6226), and the moved rows learn under their new key. pub(crate) async fn seat_bucket(self: &Arc, port: &Arc, key: &BucketKey) -> Result<(), OnEngineError> { let _gate = self.submit_gates.acquire(key).await; - if self.on_engine.seated(key) || self.on_engine.holds(key, port, &free_now(&self.authority)) { + if self.on_engine.seated(key) || self.on_engine.holds(key, port) { return Ok(()); } - let rows = self.rows_of(key).await?; - self.seat_on_engine(port, key, &rows).await + let rows = self.rows_of(key).await; + let seated = match rows { + Ok(rows) => self.seat_on_engine(port, key, &rows).await, + Err(why) => Err(why), + }; + // a reserve only ever serves a seat: a pass that seated nothing (nothing pending, not now, a + // refusal) gives it back, or it is held from everyone with nothing to spend it on + if !self.on_engine.seated(key) { + self.on_engine.release_reserve(key); + } + seated } /// Decide and measure `key`'s seat, sized for her next lesson. @@ -484,16 +527,15 @@ impl TrainingTriggerState { } } // let go while its hold was being armed: what was freed meanwhile woke nothing for it - Ok(()) if ended && self.on_engine.covered(&key, &free_now(&self.authority)) => self.seat_again(port, &key).await, + Ok(()) if ended && self.on_engine.covered(&key) => self.seat_again(port, &key).await, Ok(()) => {} } } - /// The authority said what is free: seat each bucket held for memory that it now covers, on - /// `port` while it serves `served_model`. Only held buckets are read; with none held this is - /// nothing. - pub(crate) async fn on_free(self: &Arc, port: &Arc, free: &Free, served_model: &str) { - for key in self.on_engine.freed(free) { + /// The authority's board changed: seat each bucket held for memory whose ask it granted, on `port` + /// while it serves `served_model`. Only held buckets are read; with none held this is nothing. + pub(crate) async fn on_free(self: &Arc, port: &Arc, served_model: &str) { + for key in self.on_engine.freed() { if key.base_model == served_model { self.seat_again(port, &key).await; } @@ -529,6 +571,7 @@ impl TrainingTriggerState { let workspace = self.lease(port, key, Lease { consumer: &format!("{consumer}:workspace"), rows: &workspace, whole: &whole })?; let view = optimizer.view().map_err(OnEngineError::Coverage)?; self.with_seat(seat, |held| held.run.seat(port.as_ref(), Box::new(view), optimizer, workspace)); + self.on_engine.release_reserve(key); // every stage is leased: what is left of the reserve goes back Ok(()) } Heard::Seated { .. } | Heard::Learned { .. } | Heard::Again { .. } => self.advance(port, seat, key).await, @@ -562,6 +605,7 @@ impl TrainingTriggerState { } Heard::NotSeated { .. } | Heard::Released => { self.on_engine.seats.lock().remove(&seat); // its guards drop here: nothing of it remains on the engine + self.on_engine.release_reserve(key); // and what is left of its reserve Ok(()) } } @@ -667,19 +711,26 @@ impl TrainingTriggerState { Ok(()) } - /// Lease `rows` for `consumer`. A refusal for memory holds `key` off: until that much is free, or - /// (a need past the whole device) for as long as this engine serves. - /// Lease `rows` for `consumer`. A refusal for memory holds `key` until the WHOLE seat (`whole`, - /// every row seating it again leases) fits in the short kind: held for the refused lease alone, - /// the seat's own weights freed by its release covered the hold, and it was measured, loaded and - /// refused again in a loop (the 5090, 2026-11-26: 97 Loaded, 0 Seated in four minutes). + /// Lease `rows` for `consumer`, carved from `key`'s reserve where it holds one. A refusal for memory + /// asks the authority for the WHOLE seat (`whole`, every row seating it again leases) of the short + /// kind and holds `key` until it is granted: a hold for the refused lease alone was covered by the + /// seat's own weights freed by its release, and it was measured, loaded and refused again in a loop + /// (the 5090, 2026-11-26: 97 Loaded, 0 Seated in four minutes); a hold that only watched what is free + /// was never woken while serving held the device. fn lease(&self, port: &Arc, key: &BucketKey, ask: Lease<'_>) -> Result { let Lease { consumer, rows, whole } = ask; - lease_memory(&self.authority, consumer, rows.iter().cloned()).map_err(|refusal| { + let leased_now = { + let reserves = self.on_engine.reserves.lock(); + let reserve = reserves.get(key).map_or(&[][..], Vec::as_slice); // map_or: no reserve is an empty one + lease_memory_within(&self.authority, reserve, consumer, rows.iter().cloned()) + }; + leased_now.map_err(|refusal| { if let SeatRefusal::AwaitingMemory(TrainingWait::Capacity { kind, needed, .. }) = &refusal { - // a kind the rows do not name, or rows past a byte count, hold for the refused lease alone + // a kind the rows do not name, or rows past a byte count, ask for the refused lease alone let seat = leased(whole, *kind).map_or(*needed, |seat| seat.max(*needed)); - self.on_engine.hold_off(key, port, &free_now(&self.authority), Short { kind: *kind, needed: seat }, whole); + let whole_seat = |kind, bytes| crate::inference::training_admission::ask_training_memory(&self.authority.resources, consumer, kind, bytes); + let capacity = free_now(&self.authority).kind(*kind).map(|governed| governed.capacity); + self.on_engine.hold_off(key, port, Short { kind: *kind, needed: seat, capacity }, whole_seat); } OnEngineError::Lease(refusal) }) diff --git a/core/continuum-dreaming/src/modules/training_trigger/on_engine/tests.rs b/core/continuum-dreaming/src/modules/training_trigger/on_engine/tests.rs index 2171d7285c..6723d0feae 100644 --- a/core/continuum-dreaming/src/modules/training_trigger/on_engine/tests.rs +++ b/core/continuum-dreaming/src/modules/training_trigger/on_engine/tests.rs @@ -266,11 +266,11 @@ mod held_off { refused(&state, &key, &kept, 512 << 20).await; let told = kept.told(); let port: Arc = kept.clone(); - state.on_free(&port, &crate::resources::Free::of(&state.authority.resources.board()), "qwen").await; + state.on_free(&port, "qwen").await; assert_eq!(kept.told(), told, "nothing freed yet: the wake measures nothing"); drop(occupied); - state.on_free(&port, &crate::resources::Free::of(&state.authority.resources.board()), "qwen").await; + state.on_free(&port, "qwen").await; assert_eq!(kept.told(), told + 1, "the release alone seats it again"); kept.measured(); } @@ -307,7 +307,7 @@ mod held_off { assert_eq!(kept.told(), told, "its own freed weights do not seat it again: the whole seat does not fit"); drop(occupied); - state.on_free(&port, &crate::resources::Free::of(&state.authority.resources.board()), "qwen").await; + state.on_free(&port, "qwen").await; assert_eq!(kept.told(), told + 1, "the whole seat fits: measured again"); kept.measured(); } @@ -325,11 +325,78 @@ mod held_off { let seat = refusing(&state, &key, &kept, 512 << 20).await; drop(occupied); let told = kept.told(); - state.on_free(&port, &crate::resources::Free::of(&state.authority.resources.board()), "qwen").await; + state.on_free(&port, "qwen").await; assert_eq!(kept.told(), told, "still being let go: the wake seats nothing"); state.on_said(&port, Said::Seat { seat, state: SeatState::Released }).await; assert_eq!(kept.told(), told + 1, "its Released finds the memory free and seats it again"); kept.measured(); } + + // what this catches (Codex's contract for the trainer, 2026-11-26): serving holds the device, a seat + // refused its optimizer asks for its whole seat and waits; the release grants that ask at once (a + // competing taker finds nothing), and the seat is measured, loaded and seated on stages carved from the + // grant, with no second ask and nothing of the reserve left over. + #[tokio::test] + async fn a_seat_waits_on_its_ask_and_seats_on_the_carved_grant_without_asking_again() { + use std::num::NonZeroU32; + let (state, key, _home, _dir, _guard) = waiting().await; + let free_vram = |state: &Arc| state.authority.resources.board().kinds.iter().find(|k| k.kind == crate::resources::ResourceKind::Vram).map(|k| k.available_bytes); + let occupied = crate::inference::training_admission::try_training_memory(&state.authority.resources, Admission::Free(&state.authority.serving), "occupier", crate::resources::ResourceKind::Vram, 600 << 20) + .expect("test: the authority answers") + .expect("test: 600 MiB of the 1 GiB is granted"); + let kept = Arc::new(Kept::default()); + let port: Arc = kept.clone(); + state.seat_bucket(&port, &key).await.expect("test: the bucket seats"); + let seat = kept.measured(); + let vram = |role, bytes| vec![MemoryRow { device: "CUDA0".into(), buffer_type: "CUDA0".into(), role, bytes, host: false }]; + let measured = SeatState::Measured { weights: vram(MemoryRole::Weights, 300 << 20) }; + let loaded = || SeatState::Loaded { optimizer: vram(MemoryRole::OptimizerStatic, 200 << 20), workspace: vram(MemoryRole::SharedComputeRequired, 1 << 20), reply_rows: NonZeroU32::MIN, lesson_rows: NonZeroU32::MIN }; + state.on_said(&port, Said::Seat { seat, state: measured.clone() }).await; + state.on_said(&port, Said::Seat { seat, state: loaded() }).await; + assert!(matches!(kept.0.lock().last(), Some(Learning::Release { .. })), "its optimizer refused: let go, its whole seat asked for"); + state.on_said(&port, Said::Seat { seat, state: SeatState::Released }).await; + + drop(occupied); + let competing = crate::inference::training_admission::try_training_memory(&state.authority.resources, Admission::Free(&state.authority.serving), "competitor", crate::resources::ResourceKind::Vram, 600 << 20) + .expect("test: the authority answers"); + assert!(competing.is_err(), "the release granted the seat's ask at once: a competing taker finds nothing"); + assert_eq!(free_vram(&state), Some((1 << 30) - (501 << 20)), "the whole seat (300 + 200 + 1 MiB) is the seat's reserve"); + // another taker holds everything free beside the reserve: only the reserve can seat her now + let rest = crate::inference::training_admission::try_training_memory(&state.authority.resources, Admission::Free(&state.authority.serving), "competitor", crate::resources::ResourceKind::Vram, (1 << 30) - (501 << 20)) + .expect("test: the authority answers") + .expect("test: what is free beside the reserve is granted"); + + let told = kept.told(); + state.on_free(&port, "qwen").await; + assert_eq!(kept.told(), told + 1, "its grant seats it again"); + let seat = kept.measured(); + state.on_said(&port, Said::Seat { seat, state: measured }).await; + assert!(matches!(kept.0.lock().last(), Some(Learning::Load { .. })), "its weights are carved from the reserve: it loads"); + state.on_said(&port, Said::Seat { seat, state: loaded() }).await; + assert!(matches!(kept.0.lock().last(), Some(Learning::Seat(_))), "its optimizer and workspace are carved too: it seats"); + assert_eq!(free_vram(&state), Some(0), "every stage spent the reserve, nothing more was asked and nothing is left over"); + drop(rest); + } + + // what this catches: a granted reserve kept for a bucket whose pass seats nothing (nothing pending, not + // now, a refusal): held from every other consumer with nothing to spend it on, for as long as the + // trainer runs. + #[tokio::test] + async fn a_pass_that_seats_nothing_gives_its_reserve_back() { + let (state, _key, _home, _dir, _guard) = waiting().await; + let free_vram = |state: &Arc| state.authority.resources.board().kinds.iter().find(|k| k.kind == crate::resources::ResourceKind::Vram).map(|k| k.available_bytes); + let before = free_vram(&state); + let empty = BucketKey { persona_id: Uuid::new_v4(), trait_kind: "nothing-pending".into(), base_model: "qwen".into() }; + let reserve = crate::inference::training_admission::try_training_memory(&state.authority.resources, Admission::Free(&state.authority.serving), "learning:reserve", crate::resources::ResourceKind::Vram, 100 << 20) + .expect("test: the authority answers") + .expect("test: 100 MiB is granted"); + let held_for = empty.clone(); + state.on_engine.reserves.lock().insert(held_for, vec![reserve]); + assert_ne!(free_vram(&state), before, "the reserve is held"); + let kept = Arc::new(Kept::default()); + let port: Arc = kept.clone(); + state.seat_bucket(&port, &empty).await.expect("test: the pass ends cleanly"); + assert_eq!(free_vram(&state), before, "nothing pending: the reserve is given back"); + } } diff --git a/core/continuum-engine/src/inference/training_admission.rs b/core/continuum-engine/src/inference/training_admission.rs index 06ece31ec3..6b2c19d0cf 100644 --- a/core/continuum-engine/src/inference/training_admission.rs +++ b/core/continuum-engine/src/inference/training_admission.rs @@ -66,6 +66,40 @@ pub fn try_training_memory(daemon: &std::sync::Arc, admission: A } } +/// Ask the authority for `bytes` of `kind` for `consumer`: granted now, or waiting as a ticket the caller +/// keeps until a release grants it (never refused for pressure, only past what the memory could ever +/// hold). The serving gate is not held while waiting; what is granted is spent through [`try_carve`], +/// which checks it. +pub fn ask_training_memory(daemon: &std::sync::Arc, consumer: &str, kind: ResourceKind, bytes: u64) -> Result { + daemon.ask(&request(consumer, kind, bytes)) +} + +/// [`try_training_memory`], spent from `reserve` (a granted ask its owner keeps) instead of asked for: +/// the bytes move from the reserve to the new lease in one transition. A serving gate that refuses now +/// leaves the reserve as it was, for the caller to try again or let go. +pub fn try_carve(daemon: &std::sync::Arc, admission: Admission<'_>, stage: Carve<'_>) -> Result, crate::resources::CarveError> { + let Carve { reserve, consumer, bytes } = stage; + let decided = match admission { + Admission::Free(gate) => gate.hold_for_admission().map(Some), + Admission::Within(gate, operation) => gate.admit_within(operation).map(|()| None), + }; + let hold = match decided { + Ok(hold) => hold, + Err(refusal) => return Ok(Err(TrainingWait::Serving(refusal))), + }; + let Some(kind) = reserve.kind() else { return Err(LeaseError::MissingLease { lease_id: reserve.lease_id().to_owned() }.into()) }; + let carved = daemon.carve(reserve, &request(consumer, kind, bytes)); + drop(hold); + carved.map(Ok) +} + +/// A stage to spend from a reserve: `bytes` of it, as `consumer`'s own lease. +pub struct Carve<'a> { + pub reserve: &'a LeaseGuard, + pub consumer: &'a str, + pub bytes: u64, +} + /// The caller retains this guard through child exit/reap. This non-expiring, pinned lease cannot be /// reclaimed while the child runs: the lifetime of the process, not a timer, owns release. pub fn acquire_training_memory(consumer: &str, kind: ResourceKind, bytes: u64) -> Result { diff --git a/core/continuum-genome/src/genome/learner/seat.rs b/core/continuum-genome/src/genome/learner/seat.rs index e09cf1f182..84de92f7c7 100644 --- a/core/continuum-genome/src/genome/learner/seat.rs +++ b/core/continuum-genome/src/genome/learner/seat.rs @@ -49,6 +49,9 @@ pub enum SeatRefusal { Unloaded(String), /// The engine measuring the load is not the one the caller bound the change to. EngineReplaced, + /// A stage could not be carved from its granted reserve (released, lapsed, of another kind, or + /// holding less). + Uncarved(crate::resources::CarveError), } impl std::fmt::Display for SeatRefusal { @@ -61,6 +64,7 @@ impl std::fmt::Display for SeatRefusal { SeatRefusal::Unmirrored(why) => write!(f, "the engine refused the residency: {why:?}"), SeatRefusal::Unloaded(why) => write!(f, "the shadow was not loaded: {why}"), SeatRefusal::EngineReplaced => write!(f, "the engine was replaced after the change was bound to it"), + SeatRefusal::Uncarved(error) => write!(f, "a stage could not be carved from its reserve: {error:?}"), } } } @@ -215,6 +219,13 @@ impl LeasedMemory { /// already holds, evidence and never a further lease, so it is neither leased nor handed to the view /// (leasing it would charge held memory twice, and `from_rows` refuses it; Codex on dd98bfdda). pub fn lease_memory(authority: &Authority, consumer: &str, rows: impl IntoIterator) -> Result { + lease_memory_within(authority, &[], consumer, rows) +} + +/// [`lease_memory`], each class spent from `reserve` when it holds a granted reserve of that kind with +/// room for it (a seat's granted ask, carved stage by stage: no second ask, nothing a waiter can take +/// between), otherwise leased as `lease_memory` does. +pub fn lease_memory_within(authority: &Authority, reserve: &[LeaseGuard], consumer: &str, rows: impl IntoIterator) -> Result { use crate::inference::learning::MemoryRole; let (held, rows): (Vec<_>, Vec<_>) = rows.into_iter().partition(|row| row.role == MemoryRole::SharedComputeHeld); let mut leases = Vec::new(); @@ -227,9 +238,15 @@ pub fn lease_memory(authority: &Authority, consumer: &str, rows: impl IntoIterat if bytes == 0 { continue; } - let guard = crate::inference::training_admission::try_training_memory(&authority.resources, Admission::Free(&authority.serving), consumer, resource, bytes) - .map_err(SeatRefusal::Unleased)? - .map_err(SeatRefusal::AwaitingMemory)?; + let from = reserve.iter().find(|guard| guard.kind() == Some(resource) && guard.bytes() >= bytes); + let attempt = match from { + Some(reserve) => { + let stage = crate::inference::training_admission::Carve { reserve, consumer, bytes }; + crate::inference::training_admission::try_carve(&authority.resources, Admission::Free(&authority.serving), stage).map_err(SeatRefusal::Uncarved)? + } + None => crate::inference::training_admission::try_training_memory(&authority.resources, Admission::Free(&authority.serving), consumer, resource, bytes).map_err(SeatRefusal::Unleased)?, + }; + let guard = attempt.map_err(SeatRefusal::AwaitingMemory)?; leases.push((kind, bytes, guard)); } Ok(LeasedMemory { rows, leases, held }) diff --git a/core/continuum-kernel/src/resources/daemon.rs b/core/continuum-kernel/src/resources/daemon.rs index d5cd535902..25de2b5785 100644 --- a/core/continuum-kernel/src/resources/daemon.rs +++ b/core/continuum-kernel/src/resources/daemon.rs @@ -338,17 +338,8 @@ impl ResourceDaemon { self: &std::sync::Arc, req: &LeaseRequest, ) -> Result { - // read the sources outside the lock (a slow reader never stalls other allocations), numbered before - // reading; then ingest in order and grant under one lock, against the newest accepted sample (this - // one, or a newer one a tick took meanwhile) (Codex on #6124) - let scans: Vec<_> = self.sources.iter().map(|s| (s.kind(), s.ceiling_bytes(), s.sample(), s.backed_by())).collect(); let now = EpochMs::now().millis(); - let mut g = self.governor.lock(); - for (kind, ceiling, sample, backing) in scans { - g.set_capacity(kind, ceiling); - g.set_physical_sample(kind, sample); - g.set_backing(kind, backing); - } + let mut g = self.measured_now(); let lease = g.acquire(req, now)?; self.publish_locked(&g); Ok(LeaseGuard { daemon: std::sync::Arc::clone(self), lease_id: lease.lease_id, released: false }) @@ -948,6 +939,7 @@ fn drift_should_report(drift: u64, last: &mut u64) -> bool { } } +pub mod ask; mod said; pub use said::{Free, KindFree, FREE}; diff --git a/core/continuum-kernel/src/resources/daemon/ask.rs b/core/continuum-kernel/src/resources/daemon/ask.rs new file mode 100644 index 0000000000..e7b88ac97d --- /dev/null +++ b/core/continuum-kernel/src/resources/daemon/ask.rs @@ -0,0 +1,98 @@ +//! An ask on the authority: memory a consumer waits for instead of being refused (the ledger's `ask`). +//! Granted now as a [`LeaseGuard`], or waiting as an [`AskTicket`] its owner keeps: once room is released +//! the authority grants it as a lease without being asked again, and the owner takes the guard with +//! [`AskTicket::granted`] on its next wake (the board it hears says something changed). Dropping the ticket +//! withdraws the ask, and releases a grant its owner never took, so no wait and no lease outlives the +//! one who wanted it (custody: Codex, 2026-11-09). + +use std::sync::Arc; + +use continuum_base::time::EpochMs; +use continuum_sage::place::ClaimId; + +use super::super::ledger::Asked; +use super::super::governor::ResourceGovernor; +use super::super::lease::{LeaseError, LeaseRequest}; +use super::{LeaseGuard, ResourceDaemon}; + +/// What an ask became. +pub enum Ask { + Granted(LeaseGuard), + /// Waiting: short `short` bytes of its kind when it asked. + Waiting { ticket: AskTicket, short: u64 }, +} + +/// A waiting ask, owned by the one who asked. +pub struct AskTicket { + daemon: Arc, + ask: ClaimId, + taken: bool, +} + +impl AskTicket { + /// The lease the ask became, once the authority granted it; taken once. + pub fn granted(&mut self) -> Option { + let lease = self.daemon.governor.lock().take_granted(self.ask)?; + self.taken = true; + Some(LeaseGuard { daemon: Arc::clone(&self.daemon), lease_id: lease.lease_id, released: false }) + } +} + +impl LeaseGuard { + /// The kind of memory the held lease is of, read from the governor (`None` once it is released or swept). + pub fn kind(&self) -> Option { + self.daemon.governor.lock().lease(&self.lease_id).map(|lease| lease.kind) + } +} + +impl Drop for AskTicket { + fn drop(&mut self) { + if self.taken { + return; + } + let mut governor = self.daemon.governor.lock(); + if governor.withdraw(self.ask) { + self.daemon.publish_locked(&governor); + } + } +} + +impl ResourceDaemon { + /// Ask for `req`, decided on what is physically resident now ([`Self::measured_now`]): granted now, or + /// waiting until room is released. Refused only past what the memory could ever hold. + pub fn ask(self: &Arc, req: &LeaseRequest) -> Result { + let mut governor = self.measured_now(); + let asked = governor.ask(req, EpochMs::now().millis())?; + self.publish_locked(&governor); + drop(governor); + Ok(match asked { + Asked::Granted(lease) => Ask::Granted(LeaseGuard { daemon: Arc::clone(self), lease_id: lease.lease_id, released: false }), + Asked::Waiting { ask, short } => Ask::Waiting { ticket: AskTicket { daemon: Arc::clone(self), ask, taken: false }, short }, + }) + } + + /// Spend `req.bytes` of `reserve` (a granted ask held as a seat's reserve) as a lease of their own, under + /// one lock: nobody can take those bytes between the reserve shrinking and the lease taking them. The + /// reserve keeps what is left, and is released when its guard drops. + pub fn carve(self: &Arc, reserve: &LeaseGuard, req: &LeaseRequest) -> Result { + let mut governor = self.governor.lock(); + let lease = governor.carve(reserve.lease_id(), req, EpochMs::now().millis())?; + self.publish_locked(&governor); + Ok(LeaseGuard { daemon: Arc::clone(self), lease_id: lease.lease_id, released: false }) + } + + /// The governor, locked, after every source was measured and ingested now: an admission between ticks + /// never reads a sample up to a tick old. The sources are read outside the lock (a slow reader never + /// stalls other allocations), then ingested in order under it, so the grant is decided against the + /// newest accepted sample (Codex on #6124). + pub(super) fn measured_now(&self) -> parking_lot::MutexGuard<'_, ResourceGovernor> { + let scans: Vec<_> = self.sources.iter().map(|s| (s.kind(), s.ceiling_bytes(), s.sample(), s.backed_by())).collect(); + let mut governor = self.governor.lock(); + for (kind, ceiling, sample, backing) in scans { + governor.set_capacity(kind, ceiling); + governor.set_physical_sample(kind, sample); + governor.set_backing(kind, backing); + } + governor + } +} diff --git a/core/continuum-kernel/src/resources/daemon/tests.rs b/core/continuum-kernel/src/resources/daemon/tests.rs index d960af58ad..3af5a53bb2 100644 --- a/core/continuum-kernel/src/resources/daemon/tests.rs +++ b/core/continuum-kernel/src/resources/daemon/tests.rs @@ -1,6 +1,7 @@ #![cfg(test)] use super::*; use crate::resources::capacity::MockCapacitySource; + use crate::resources::Ask; use crate::resources::consumer::{ConsumerFootprint, ReclaimRequest, ReclaimStatus}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -714,3 +715,29 @@ drop(guard); assert_eq!(free(3), 10_000, "a release is said, with nothing else changing"); } + + // what this catches (Codex's contract for the trainer, 2026-11-26): kernel leases take everything, a + // seat's ask waits, a kernel release grants it as a lease its owner takes without asking again, and a + // ticket dropped while waiting leaves no wait behind. + #[tokio::test] + async fn an_ask_waits_on_the_authority_and_is_granted_on_release() { + let src = Arc::new(MockCapacitySource::new(ResourceKind::Vram, 10_000)); + let config = DaemonConfig { tick_interval: Duration::from_secs(3600), min_reclaim_budget: Duration::from_millis(100), governor: GovernorConfig { min_dwell_ms: 0, graceful_grace_ms: 50 } }; + let daemon = ResourceDaemon::start(vec![src], vec![], config); + let serving = daemon.acquire_guarded(&req("serving", 10_000, u64::MAX, ReclaimPolicy::Pinned)).expect("test: serving takes everything"); + let Ok(Ask::Waiting { ticket: mut seat, short }) = daemon.ask(&req("learning:her", 5_000, u64::MAX, ReclaimPolicy::Graceful)) else { + panic!("test: the seat waits") + }; + assert_eq!(short, 5_000); + assert!(seat.granted().is_none(), "nothing released yet"); + let Ok(Ask::Waiting { ticket: gone, .. }) = daemon.ask(&req("learning:him", 1_000, u64::MAX, ReclaimPolicy::Graceful)) else { + panic!("test: a second seat waits") + }; + drop(gone); // its owner stopped wanting it + drop(serving); // a kernel release + let lease = seat.granted().expect("test: granted on the release, not asked again"); + assert_eq!(lease.bytes(), 5_000); + assert_eq!(daemon.board().kinds.iter().find(|k| k.kind == ResourceKind::Vram).map(|k| k.available_bytes), Some(5_000), "the withdrawn seat holds nothing"); + drop(lease); + assert_eq!(daemon.board().kinds.iter().find(|k| k.kind == ResourceKind::Vram).map(|k| k.available_bytes), Some(10_000)); + } diff --git a/core/continuum-kernel/src/resources/governor.rs b/core/continuum-kernel/src/resources/governor.rs index ed876b5e8e..780f9768e6 100644 --- a/core/continuum-kernel/src/resources/governor.rs +++ b/core/continuum-kernel/src/resources/governor.rs @@ -181,6 +181,26 @@ impl ResourceGovernor { self.ledger.release(lease_id) } + /// Ask for `req`: granted now, or waiting until room is released (the ledger's `ask`). + pub fn ask(&mut self, req: &LeaseRequest, now_ms: u64) -> Result { + let lease_id = self.mint_id(&req.consumer_id); + self.ledger.ask(req, &lease_id, now_ms) + } + + /// Spend part of the lease `reserve` as a lease of its own (the ledger's `carve`). + pub fn carve(&mut self, reserve: &str, req: &LeaseRequest, now_ms: u64) -> Result { + let lease_id = self.mint_id(&req.consumer_id); + self.ledger.carve(reserve, req, &lease_id, now_ms) + } + + pub fn withdraw(&mut self, ask: continuum_sage::place::ClaimId) -> bool { + self.ledger.withdraw(ask) + } + + pub fn take_granted(&mut self, ask: continuum_sage::place::ClaimId) -> Option { + self.ledger.take_granted(ask) + } + pub(super) fn adjust_residency(&mut self, consumer: &str, pools: &[super::daemon::ResidentFloor], change: fn(u64, u64) -> u64) { let mut footprints = Vec::new(); for kind in ResourceKind::ALL { diff --git a/core/continuum-kernel/src/resources/ledger.rs b/core/continuum-kernel/src/resources/ledger.rs index ce599d38d7..75a5fe4035 100644 --- a/core/continuum-kernel/src/resources/ledger.rs +++ b/core/continuum-kernel/src/resources/ledger.rs @@ -21,6 +21,10 @@ use std::sync::{Arc, Weak}; use std::sync::atomic::{AtomicU64, Ordering}; use ts_rs::TS; +use continuum_sage::place::{Bytes, ClaimId, Generation, Ledger, Need}; + +pub use asks::{Asked, CarveError}; + use super::arbiter::{ArbiterContext, LeaseArbiter}; use super::consumer::ConsumerFootprint; #[cfg(test)] @@ -158,6 +162,15 @@ pub struct ResourceLeaseLedger { /// /// [`CapacitySource::backed_by`]: super::capacity::CapacitySource::backed_by backing: BTreeMap, + /// The one picture of what each kind can still grant (UNIFIED-PAGING.md slice 3a): every lease is a + /// claim on it, each kind's budget is its capacity less what is resident beyond our landed leases, + /// a backed kind is charged once on its pool, and the floors above are its floors. The readings in + /// this struct are what it is told from; `available`, `available_for` and `committed` read it. + place: Ledger, + /// Each ask `place` holds as a wait, by its claim: the lease it becomes when granted (`asks.rs`). + asks: BTreeMap, + /// Asks granted and not yet taken by their owners ([`Self::take_granted`]). + granted: BTreeMap, } /// A live lease and when its holder declared it landed (Codex on #6124). Landing is never inferred from @@ -172,6 +185,8 @@ struct Held { /// When its holder declared it landed: only a reading observed at or after this can show it. None while /// undeclared. landed_from: Option, + /// Its claim on the ledger's `place`. + claim: ClaimId, } #[derive(Debug)] @@ -215,6 +230,7 @@ impl ResourceLeaseLedger { /// DiskPressureMonitor). pub fn set_capacity(&mut self, kind: ResourceKind, bytes: u64) { self.capacity.insert(kind, bytes); + self.tell(); } pub fn capacity(&self, kind: ResourceKind) -> u64 { @@ -238,6 +254,7 @@ impl ResourceLeaseLedger { /// Sibling of `set_capacity`; the ground-truth axis of the un-inversion. pub fn set_physical_used(&mut self, kind: ResourceKind, bytes: u64) { self.physical_used.insert(kind, bytes); + self.tell(); } /// Ingest `sample` only if it was observed after the reading this kind holds. Returns whether it was accepted. @@ -247,6 +264,7 @@ impl ResourceLeaseLedger { } self.sampled.insert(kind, sample.observed); self.physical_used.insert(kind, sample.used); + self.tell(); true } @@ -266,6 +284,7 @@ impl ResourceLeaseLedger { self.backing.remove(&kind); } } + self.tell(); } /// What is REALLY spoken for of this kind: the larger of what we have granted @@ -281,13 +300,12 @@ impl ResourceLeaseLedger { /// grants together. So each grant, on either axis, spends the shared headroom the moment it is /// made, once, and the next sample takes over as its bytes land (Codex on #6124). pub fn committed(&self, kind: ResourceKind) -> u64 { - self.remaining_commitment(&self.pool_kinds(kind), self.physical_used(kind), 0) - } - - fn remaining_commitment(&self, kinds: &[ResourceKind], resident: u64, released_grant: u64) -> u64 { - let promised = kinds.iter().map(|k| self.granted(*k)).fold(0u64, u64::saturating_add); - let landing = kinds.iter().map(|k| self.not_yet_resident(*k)).fold(0u64, u64::saturating_add); - promised.saturating_sub(released_grant).max(resident.saturating_add(landing)) + let root = self.pool_root(kind); + let claimed = match self.place.accounts(root) { + Some(accounts) => accounts.held.0.saturating_add(accounts.prepared.0), + None => 0, // tell() names every kind + }; + self.external(root).saturating_add(claimed) } /// The pool `kind` draws on: the kind it is backed by, or itself. @@ -298,21 +316,6 @@ impl ResourceLeaseLedger { } } - /// Every kind sharing `kind`'s physical pool: the root and each kind backed by it. - fn pool_kinds(&self, kind: ResourceKind) -> Vec { - let root = self.pool_root(kind); - std::iter::once(root).chain(self.backing.iter().filter(|(_, b)| **b == root).map(|(k, _)| *k)).collect() - } - - /// Bytes granted on `kind` whose holders have not declared them landed: owed on top of physical use. - fn not_yet_resident(&self, kind: ResourceKind) -> u64 { - self.leases - .values() - .filter(|held| held.lease.kind == kind) - .map(|held| held.pending(self.observed_for(kind))) - .fold(0u64, |acc, b| acc.saturating_add(b)) - } - /// The oldest accepted observation that must show a `kind` lease: its own, and on unified memory its backing /// pool's too (both readings have to have been taken after the landing). None until both exist. fn observed_for(&self, kind: ResourceKind) -> Option { @@ -328,6 +331,7 @@ impl ResourceLeaseLedger { pub fn landed(&mut self, lease_id: &str, from: super::observed::Observed) -> Result<(), LeaseError> { let held = self.leases.get_mut(lease_id).ok_or_else(|| LeaseError::MissingLease { lease_id: lease_id.to_string() })?; held.landed_from.get_or_insert(from); + self.tell(); Ok(()) } @@ -341,19 +345,7 @@ impl ResourceLeaseLedger { /// its backing's availability, so the shared bytes are never spent twice and a process outside /// ours is charged to the host, never to the GPU's working set. pub fn available(&self, kind: ResourceKind) -> u64 { - self.headroom_after_release(kind, 0, |_, resident| resident) - } - - fn headroom_after_release(&self, kind: ResourceKind, released_grant: u64, project: impl Fn(&[ResourceKind], u64) -> u64) -> u64 { - let root = self.pool_root(kind); - let pool = self.pool_kinds(root); - let host = self.remaining_commitment(&pool, project(&pool, self.physical_used(root)), released_grant); - let host_room = self.capacity(root).saturating_sub(host); - if root == kind { - return host_room; - } - let device = self.remaining_commitment(&[kind], project(&[kind], self.measured(kind)), released_grant); - self.capacity(kind).saturating_sub(device).min(host_room) + bytes_of(self.place.free(kind)) } /// Bytes of `kind` currently held by one specific consumer. @@ -376,6 +368,7 @@ impl ResourceLeaseLedger { } else { self.reservations.insert(key, min_bytes); } + self.tell(); } pub fn reservation(&self, consumer_id: &str, kind: ResourceKind) -> u64 { @@ -399,6 +392,7 @@ impl ResourceLeaseLedger { } else { self.measured.insert(consumer_id.to_string(), footprints); } + self.tell(); } /// Total self-declared residency of a kind across every measured consumer — @@ -427,33 +421,12 @@ impl ResourceLeaseLedger { .fold(0u64, |acc, b| acc.saturating_add(b)) } - /// Reserved-but-not-yet-granted headroom that must stay free for OTHER - /// consumers' floors. A requester never sees bytes another consumer is - /// guaranteed but hasn't claimed yet. - /// - /// A floor is met by what its holder is GRANTED or by what it is measured to HOLD, - /// whichever is more: measured residency is already in `physical_used`, so subtracting - /// the whole floor on top of it counted those bytes twice (Codex, 2026-09-27: a warm - /// build reserving 10.5 GiB and resident at 6 GiB with no grant cost serving 16.5 GiB, - /// not 10.5). Grant, measured residency and declared floor stay three facts; only the - /// unmet part of the floor is withheld. - fn reserved_headroom_excluding(&self, exclude_consumer: &str, kind: ResourceKind) -> u64 { - self.reservations - .iter() - .filter(|((k, c), _)| self.pool_root(*k) == self.pool_root(kind) && c != exclude_consumer) - .map(|((k, c), floor)| { - floor.saturating_sub(self.granted_to(c, *k).max(self.measured_by(c, *k))) - }) - .fold(0u64, |acc, h| acc.saturating_add(h)) - } - /// Headroom THIS consumer may actually acquire: physical free minus the /// unmet reservations of every OTHER consumer. The requester's own /// reservation never counts against it. This is what `acquire` enforces so /// inference cannot eat into the video call's guaranteed floor. pub fn available_for(&self, consumer_id: &str, kind: ResourceKind) -> u64 { - self.available(kind) - .saturating_sub(self.reserved_headroom_excluding(consumer_id, kind)) + bytes_of(self.place.room_for(told::owner_of(consumer_id), kind)) } /// What `consumer_id` could have **if it released what it is already holding** — @@ -495,17 +468,8 @@ impl ResourceLeaseLedger { /// planning; `acquire` must keep using `available_for`, or a consumer could grant /// itself bytes it has not yet released. pub fn budget_for_replacing(&self, consumer_id: &str, kind: ResourceKind) -> u64 { - let resident = self.measured_by(consumer_id, kind); - let landed_grant = self.granted_to(consumer_id, kind).min(resident); - self.headroom_after_release(kind, landed_grant, |axes, used| { - // A footprint estimate can exceed the physical sample. Each constrained - // pool retains the other measured allocations that actually draw from it. - let retained = self.measured.iter().flat_map(|(owner, footprints)| { - footprints.iter().filter(move |f| axes.contains(&f.kind) && (owner != consumer_id || f.kind != kind)) - }).map(|f| f.bytes).fold(0u64, u64::saturating_add); - used.saturating_sub(resident).max(retained) - }) - .saturating_sub(self.reserved_headroom_excluding(consumer_id, kind)) + let freed = self.freed_by_replacing(consumer_id, kind); + bytes_of(self.place.room_if(told::owner_of(consumer_id), kind, &freed)) } /// The room `consumer_id` may size a successor into when it holds nothing on the board yet: @@ -564,6 +528,23 @@ impl ResourceLeaseLedger { available, }); } + // a lease is a claim taken now, ahead of any wait, spent whole and held until its release; one + // not taken now is refused, never queued (an ask queues: `asks.rs`) + let claim = match self.place.take(told::owner_of(&req.consumer_id), Generation(1), &[Need { place: req.kind, amount: Bytes(req.bytes) }]) { + Ok(claim) => claim, + Err(_untaken) => return Err(LeaseError::InsufficientCapacity { kind: req.kind, requested: req.bytes, available }), + }; + let lease = self.hold(claim, req, lease_id, now_ms)?; + self.note_passed(req, now_ms); + self.tell(); + Ok(lease) + } + + /// Spend `claim` whole and commit it, and keep it as the lease `lease_id` for `req`. + fn hold(&mut self, claim: continuum_sage::place::Claim, req: &LeaseRequest, lease_id: String, now_ms: u64) -> Result { + if !claim.consume(req.kind, Bytes(req.bytes)) || self.place.commit(claim.id()).is_err() { + return Err(LeaseError::MissingLease { lease_id }); // a fresh claim spent whole: only a ledger defect lands here + } let lease = ResourceLease { lease_id: lease_id.clone(), consumer_id: req.consumer_id.clone(), @@ -573,7 +554,7 @@ impl ResourceLeaseLedger { expires_at_ms: now_ms.saturating_add(req.ttl_ms), reclaim_policy: req.reclaim_policy, }; - self.leases.insert(lease_id, Held { lease: lease.clone(), landed_from: None, view: None }); + self.leases.insert(lease_id, Held { lease: lease.clone(), landed_from: None, view: None, claim: claim.id() }); Ok(lease) } @@ -607,15 +588,13 @@ impl ResourceLeaseLedger { /// that reduces `granted`. Missing lease is a fail-loud error, never a /// silent no-op (a double-release or stale id is a real bug to surface). pub fn release(&mut self, lease_id: &str) -> Result { - self.leases - .remove(lease_id) - .map(|held| { - if let Some(view) = held.view { view.bytes.store(0, Ordering::Release); } - held.lease - }) - .ok_or_else(|| LeaseError::MissingLease { - lease_id: lease_id.to_string(), - }) + let held = self.leases.remove(lease_id).ok_or_else(|| LeaseError::MissingLease { lease_id: lease_id.to_string() })?; + if let Some(view) = held.view { view.bytes.store(0, Ordering::Release); } + if self.place.release(held.claim).is_err() { + continuum_base::probe!(class = "resources.ledger.release_unknown", lease = %lease_id, "a released lease had no claim left on place (shrunk to nothing already)"); + } + self.tell(); + Ok(held.lease) } /// Reduce a lease's footprint by `freed_bytes` without ending it — the @@ -636,10 +615,14 @@ impl ResourceLeaseLedger { let lease = &mut held.lease; lease.bytes = lease.bytes.saturating_sub(freed_bytes); if let Some(view) = &held.view { view.bytes.store(lease.bytes, Ordering::Release); } - let remaining = lease.bytes; + let (remaining, kind, claim) = (lease.bytes, lease.kind, held.claim); if remaining == 0 { self.leases.remove(lease_id); } + if self.place.shrink(claim, kind, Bytes(freed_bytes)).is_err() { + continuum_base::probe!(class = "resources.ledger.shrink_unknown", lease = %lease_id, "a shrunk lease had no claim left on place"); + } + self.tell(); Ok(remaining) } @@ -813,5 +796,17 @@ impl ResourceLeaseLedger { } } +/// An amount `place` answers for a kind. `tell` names every kind, so no answer means a kind with no +/// capacity: nothing to grant. +fn bytes_of(answer: Option) -> u64 { + match answer { + Some(Bytes(bytes)) => bytes, + None => 0, + } +} + +mod asks; +mod told; + #[cfg(test)] mod tests; diff --git a/core/continuum-kernel/src/resources/ledger/asks.rs b/core/continuum-kernel/src/resources/ledger/asks.rs new file mode 100644 index 0000000000..660638e644 --- /dev/null +++ b/core/continuum-kernel/src/resources/ledger/asks.rs @@ -0,0 +1,168 @@ +//! An ask: a lease that waits instead of being refused (UNIFIED-PAGING.md slice 3a; the 5090 on +//! 2026-11-26, where a learning seat was refused 5.7 GB with 5 MB free and nothing ever woke it). +//! +//! The ask is a wait on the authority's one `place` ledger. It is granted, in order of asking per memory, +//! from what is free once a lease is released, shrunk, or a reading frees room, and becomes the lease it +//! asked for without being asked again. A foreground acquire is taken ahead of it and never queues behind +//! it; which waits deserve room made for them is the law's to decide, not a queue's. + +use continuum_sage::place::{Answer, Bytes, ClaimId, Generation, Need}; + +use super::{told, LeaseError, LeaseRequest, ResourceLease, ResourceLeaseLedger}; + +/// What an ask became. +#[derive(Debug, Clone, PartialEq)] +pub enum Asked { + /// Granted now, as this lease. + Granted(ResourceLease), + /// Waiting as `ask`: taken once granted ([`ResourceLeaseLedger::take_granted`]), or withdrawn. + Waiting { ask: ClaimId, short: u64 }, +} + +/// Why a stage was not carved from its reserve: the lease side (released, lapsed, of another kind, holding +/// less, a duplicate id), or the refusal `place` gave the split, kept as its own type. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum CarveError { + #[error("{0:?}")] + Lease(LeaseError), + #[error("place refused the split: {0:?}")] + Place(continuum_sage::place::Refusal), +} + +impl From for CarveError { + fn from(error: LeaseError) -> Self { + Self::Lease(error) + } +} + +/// A waiting ask: the lease it becomes. +#[derive(Debug, Clone)] +pub(super) struct Asking { + req: LeaseRequest, + lease_id: String, + asked_at_ms: u64, +} + +impl ResourceLeaseLedger { + /// Ask for `req` as the lease `lease_id`: granted now if it fits (floors and earlier waits on its memory + /// honored), otherwise queued until it does. Only a need past the memory's capacity is refused. + pub fn ask(&mut self, req: &LeaseRequest, lease_id: &str, now_ms: u64) -> Result { + let lease_id = lease_id.to_owned(); + if self.leases.contains_key(&lease_id) || self.asks.values().any(|asking| asking.lease_id == lease_id) { + return Err(LeaseError::DuplicateLease { lease_id }); + } + let need = [Need { place: req.kind, amount: Bytes(req.bytes) }]; + let answer = self.place.prepare(told::owner_of(&req.consumer_id), Generation(1), &need); + let asked = match answer { + Answer::Granted(claim) => Asked::Granted(self.hold(claim, req, lease_id, now_ms)?), + Answer::Waiting { id, short } => { + self.asks.insert(id, Asking { req: req.clone(), lease_id, asked_at_ms: now_ms }); + let short = short.iter().map(|need| need.amount.0).fold(0, u64::max); // a wait behind an earlier one on its memory may lack nothing itself + Asked::Waiting { ask: id, short } + } + Answer::Never { capacity, .. } => return Err(LeaseError::InsufficientCapacity { kind: req.kind, requested: req.bytes, available: capacity.0 }), + Answer::Unknown { .. } | Answer::Stale { .. } => return Err(LeaseError::InsufficientCapacity { kind: req.kind, requested: req.bytes, available: 0 }), + }; + self.tell(); + Ok(asked) + } + + /// A foreground acquire of `req` was taken while asks wait on its kind: probed with how many wait and + /// how long the oldest has. A foreground take passes waits by design (serving never queues behind a + /// seat), so a steady stream of them can starve an ask; this is the evidence its aging bound, the + /// decide::Policy, is fitted to (Fable on 7d59f5639). + pub(super) fn note_passed(&self, req: &LeaseRequest, now_ms: u64) { + let waiting = self.asks.values().filter(|asking| asking.req.kind == req.kind); + let (count, oldest) = waiting.fold((0u32, now_ms), |(count, oldest), asking| (count + 1, oldest.min(asking.asked_at_ms))); + if count > 0 { + continuum_base::probe!(class = "resources.ask.passed", consumer = %req.consumer_id, kind = ?req.kind, bytes = req.bytes, waiting = count, oldest_wait_ms = now_ms.saturating_sub(oldest), + "a foreground take passed asks waiting on its kind"); + } + } + + /// Withdraw `ask`: its owner no longer wants it. A waiting ask leaves the queue; one granted and not yet + /// taken is released, so memory nobody will use is never held. Answers whether there was anything to + /// withdraw. + pub fn withdraw(&mut self, ask: ClaimId) -> bool { + if self.asks.remove(&ask).is_some() { + return self.place.unwind(ask).is_ok(); + } + match self.granted.remove(&ask) { + Some(lease) => self.release(&lease.lease_id).is_ok(), + None => false, + } + } + + /// The lease `ask` became, once granted; taken once (its owner then holds and releases it). + pub fn take_granted(&mut self, ask: ClaimId) -> Option { + self.granted.remove(&ask) + } + + /// Spend `req.bytes` of the lease `reserve` (a granted ask its owner keeps as a reserve) as a lease of + /// their own, `lease_id`: the reserve shrinks and the new lease takes exactly those bytes, with nothing + /// told in between, so no wait and no other taker can have them first. Refused, changing nothing, when + /// the reserve is of another kind or holds less. + pub fn carve(&mut self, reserve: &str, req: &LeaseRequest, lease_id: &str, now_ms: u64) -> Result { + let (kind, bytes, claim) = match self.leases.get(reserve) { + // a lapsed reserve stays charged for its fenced release; nothing is carved from it into a fresh term + Some(held) if held.lease.is_expired(now_ms) => return Err(LeaseError::ExpiredLease { lease_id: reserve.to_owned() }.into()), + Some(held) => (held.lease.kind, held.lease.bytes, held.claim), + None => return Err(LeaseError::MissingLease { lease_id: reserve.to_owned() }.into()), + }; + if kind != req.kind || bytes < req.bytes { + return Err(LeaseError::InsufficientCapacity { kind: req.kind, requested: req.bytes, available: if kind == req.kind { bytes } else { 0 } }.into()); + } + if self.leases.contains_key(lease_id) { + return Err(LeaseError::DuplicateLease { lease_id: lease_id.to_owned() }.into()); + } + // one transition on place: the bytes move from the reserve's claim to the stage's, every charge + // (the kind's and its pool's) unchanged, so nothing can come between + let stage = self + .place + .split(claim, Need { place: kind, amount: Bytes(req.bytes) }, told::owner_of(&req.consumer_id), Generation(1)) + .map_err(CarveError::Place)?; + let left = bytes - req.bytes; + if left == 0 { + if let Some(held) = self.leases.remove(reserve) { + if let Some(view) = held.view { view.bytes.store(0, std::sync::atomic::Ordering::Release); } + } + } else if let Some(held) = self.leases.get_mut(reserve) { + held.lease.bytes = left; + if let Some(view) = &held.view { view.bytes.store(left, std::sync::atomic::Ordering::Release); } + } + let lease = ResourceLease { + lease_id: lease_id.to_owned(), + consumer_id: req.consumer_id.clone(), + kind: req.kind, + bytes: req.bytes, + acquired_at_ms: now_ms, + expires_at_ms: now_ms.saturating_add(req.ttl_ms), + reclaim_policy: req.reclaim_policy, + }; + self.leases.insert(lease_id.to_owned(), super::Held { lease: lease.clone(), landed_from: None, view: None, claim: stage }); + self.tell(); // after the transition: what the floors and waits see is its result + Ok(lease) + } + + /// Grant every waiting ask that now fits and turn each into its lease. Run after every change that can + /// free room; returns whether any was granted (a grant can change floors, so the caller tells again). + pub(super) fn grant_asks(&mut self) -> bool { + let mut claims = Vec::new(); + self.place.grant_waiting(&mut claims); + let any = !claims.is_empty(); + for claim in claims { + let id = claim.id(); + let Some(asking) = self.asks.remove(&id) else { + continuum_base::probe!(class = "resources.ledger.grant_unasked", claim = ?id, "place granted a wait the authority holds no ask for"); + continue; + }; + match self.hold(claim, &asking.req, asking.lease_id, asking.asked_at_ms) { + Ok(lease) => { + self.granted.insert(id, lease); + } + Err(defect) => continuum_base::probe!(class = "resources.ledger.grant_unheld", claim = ?id, error = ?defect, "a granted ask could not be held"), + } + } + any + } +} diff --git a/core/continuum-kernel/src/resources/ledger/tests.rs b/core/continuum-kernel/src/resources/ledger/tests.rs index 602c7024db..9ea19475f4 100644 --- a/core/continuum-kernel/src/resources/ledger/tests.rs +++ b/core/continuum-kernel/src/resources/ledger/tests.rs @@ -889,3 +889,84 @@ } } } + + // what this catches (the 5090, 2026-11-26: a learning seat refused 5.7 GB with 5 MB free, and nothing + // ever woke it): an ask waits instead, a foreground acquire still takes what is free now without + // queueing behind it, and releasing what serving holds grants the ask as its lease, unasked again. + #[test] + fn an_ask_waits_and_becomes_its_lease_when_room_is_released() { + let mut l = ResourceLeaseLedger::new(); + l.set_capacity(ResourceKind::Vram, 10_000); + l.acquire(&req("serving", ResourceKind::Vram, 9_980, ReclaimPolicy::Pinned), "serving-1".into(), 0).expect("test: serving fits"); + let Ok(Asked::Waiting { ask, short }) = l.ask(&req("learning:her", ResourceKind::Vram, 5_000, ReclaimPolicy::Graceful), "seat", 1) else { + panic!("test: the seat waits") + }; + assert_eq!(short, 4_980, "the wait names what it lacks"); + assert!(l.take_granted(ask).is_none(), "nothing granted yet"); + assert!(l.acquire(&req("vision", ResourceKind::Vram, 10, ReclaimPolicy::Graceful), "vision".into(), 2).is_ok(), "the foreground is never queued behind an ask"); + l.release("serving-1").expect("test: serving lets go"); + let granted = l.take_granted(ask).expect("test: granted on the release, without being asked again"); + assert_eq!((granted.lease_id.as_str(), granted.bytes), ("seat", 5_000)); + assert!(l.lease("seat").is_some(), "it is a lease like any other"); + assert_eq!(l.available(ResourceKind::Vram), 10_000 - 10 - 5_000); + } + + // what this catches: a seat that stopped wanting its memory still granted it, holding memory no one + // uses. + #[test] + fn a_withdrawn_ask_is_never_granted() { + let mut l = ResourceLeaseLedger::new(); + l.set_capacity(ResourceKind::Vram, 100); + l.acquire(&req("serving", ResourceKind::Vram, 100, ReclaimPolicy::Pinned), "serving-1".into(), 0).expect("test: serving fits"); + let Ok(Asked::Waiting { ask, .. }) = l.ask(&req("learning:her", ResourceKind::Vram, 50, ReclaimPolicy::Graceful), "seat", 1) else { + panic!("test: the seat waits") + }; + assert!(l.withdraw(ask)); + l.release("serving-1").expect("test: serving lets go"); + assert!(l.take_granted(ask).is_none()); + assert_eq!(l.available(ResourceKind::Vram), 100); + // granted, then withdrawn before its owner took it: released, never held for no one + l.acquire(&req("serving", ResourceKind::Vram, 100, ReclaimPolicy::Pinned), "serving-2".into(), 2).expect("test: serving fits"); + let Ok(Asked::Waiting { ask, .. }) = l.ask(&req("learning:her", ResourceKind::Vram, 50, ReclaimPolicy::Graceful), "seat-2", 3) else { + panic!("test: the seat waits") + }; + l.release("serving-2").expect("test: serving lets go"); + assert!(l.withdraw(ask), "a granted, untaken ask is withdrawn"); + assert!(l.lease("seat-2").is_none() && l.available(ResourceKind::Vram) == 100, "and its lease released"); + } + + // what this catches: a seat's stage lease carved from its granted reserve losing the bytes to a waiting + // ask in between (the shrink told place and the wait took them), or a carve past the reserve. + #[test] + fn a_stage_carved_from_its_reserve_keeps_the_bytes_from_every_wait() { + let mut l = ResourceLeaseLedger::new(); + l.set_capacity(ResourceKind::Vram, 10_000); + l.acquire(&req("learning:her", ResourceKind::Vram, 5_000, ReclaimPolicy::Graceful), "reserve".into(), 0).expect("test: the reserve fits"); + l.acquire(&req("serving", ResourceKind::Vram, 5_000, ReclaimPolicy::Pinned), "serving-1".into(), 0).expect("test: serving fits"); + let Ok(Asked::Waiting { ask, .. }) = l.ask(&req("learning:him", ResourceKind::Vram, 1_000, ReclaimPolicy::Graceful), "his", 1) else { + panic!("test: his seat waits") + }; + let stage = l.carve("reserve", &req("learning:her", ResourceKind::Vram, 3_000, ReclaimPolicy::Graceful), "weights", 2).expect("test: carved"); + assert_eq!(stage.bytes, 3_000); + assert_eq!(l.lease("reserve").map(|lease| lease.bytes), Some(2_000), "the reserve keeps the rest"); + assert!(l.take_granted(ask).is_none(), "the wait never saw the carved bytes"); + assert!(l.carve("reserve", &req("learning:her", ResourceKind::Vram, 2_001, ReclaimPolicy::Graceful), "over", 3).is_err(), "never past the reserve"); + l.release("reserve").expect("test: the rest goes back"); + assert!(l.take_granted(ask).is_some(), "what the reserve gives back is granted to the wait"); + } + + // what this catches (Codex on 07427e2fe): a stage carved from a reserve past its term, given a fresh term + // while the lapsed reserve's charge waits for its fenced release: refused, changing nothing. + #[test] + fn nothing_is_carved_from_a_lapsed_reserve() { + let mut l = ResourceLeaseLedger::new(); + l.set_capacity(ResourceKind::Vram, 10_000); + let reserve = LeaseRequest { ttl_ms: 100, ..req("learning:her", ResourceKind::Vram, 5_000, ReclaimPolicy::Graceful) }; + l.acquire(&reserve, "reserve".into(), 0).expect("test: the reserve fits"); + let before = l.available(ResourceKind::Vram); + let stage = req("learning:her", ResourceKind::Vram, 1_000, ReclaimPolicy::Graceful); + assert!(matches!(l.carve("reserve", &stage, "weights", 100), Err(CarveError::Lease(LeaseError::ExpiredLease { .. }))), "at its term"); + assert!(matches!(l.carve("reserve", &stage, "weights", 500), Err(CarveError::Lease(LeaseError::ExpiredLease { .. }))), "after it"); + assert_eq!((l.lease("reserve").map(|lease| lease.bytes), l.available(ResourceKind::Vram)), (Some(5_000), before), "the charge is unchanged"); + assert!(l.lease("weights").is_none()); + } diff --git a/core/continuum-kernel/src/resources/ledger/told.rs b/core/continuum-kernel/src/resources/ledger/told.rs new file mode 100644 index 0000000000..5c0195c785 --- /dev/null +++ b/core/continuum-kernel/src/resources/ledger/told.rs @@ -0,0 +1,125 @@ +//! What the authority tells its `place` ledger from its readings: each kind's capacity, its budget +//! (capacity less what is resident beyond our landed leases), which kind draws on which physical pool, +//! and each reservation as a floor. Told again after every reading or lease change, so `place` is the +//! one picture every grant and every "how much is free" reads (UNIFIED-PAGING.md slice 3a, the mapping +//! agreed with Fable and Codex on 2026-11-26). + +use std::hash::{Hash, Hasher}; + +use continuum_sage::place::{Bytes, Owner}; + +use super::{ResourceKind, ResourceLeaseLedger}; + +impl ResourceLeaseLedger { + /// Tell `place` everything it reads from: pools first (a budget is checked against them), then each + /// kind's capacity and budget, then every floor. + /// Then grant every waiting ask that now fits; a grant can change a floor, so tell again until none is. + pub(super) fn tell(&mut self) { + loop { + self.tell_place(); + if !self.grant_asks() { + return; + } + } + } + + fn tell_place(&mut self) { + for kind in ResourceKind::ALL { + let pool = self.backing.get(&kind).copied(); + self.place.back(kind, pool); + } + let mut never = Vec::new(); + for kind in ResourceKind::ALL { + let capacity = self.capacity(kind); + let budget = capacity.saturating_sub(self.external(kind)); + self.place.place(kind, Bytes(capacity), Bytes(budget), &mut never); + } + // a floor is met by what its holder is granted or measured to hold, whichever is more: measured + // residency is already in the reading, so withholding the whole floor on top counted it twice + // (Codex, 2026-09-27: a build reserving 10.5 GiB, resident at 6 GiB, cost serving 16.5 GiB). So + // place is told the floor less its holder's unleased residency; its leases fill the rest + let floors: Vec<(Owner, ResourceKind, Bytes)> = self + .reservations + .iter() + .map(|((kind, consumer), floor)| { + let unleased = self.measured_by(consumer, *kind).saturating_sub(self.granted_to(consumer, *kind)); + (owner_of(consumer), *kind, Bytes(floor.saturating_sub(unleased))) + }) + .collect(); + self.place.floors(floors); + } + + /// Resident on `kind` beyond our leases proven landed in the accepted reading (Codex's rule: credit + /// only the overlap of what is resident with live leases proven landed in that sample). A kind that + /// draws on a pool reads its own residency from what our consumers measure on it (the host-wide + /// reading counts every process); a pool, or a discrete device, reads its physical use, less what + /// our landed leases on it and on every kind drawing on it hold. + pub(super) fn external(&self, kind: ResourceKind) -> u64 { + let resident = match self.backing.get(&kind) { + Some(_) => self.measured(kind), + None => self.physical_used(kind), + }; + let landed = self.pool_kinds_drawing_on(kind).iter().map(|k| self.landed_on(*k)).fold(0u64, u64::saturating_add); + resident.saturating_sub(landed) + } + + /// What `consumer` replacing itself on `kind` would give back on `kind` and on the pool it draws on: + /// the residency it measures there leaves what is resident (but never below what the others measure on + /// that memory: a footprint estimate can exceed the reading), and its leases up to that residency stop + /// being held. `place` answers the room from it ([`Ledger::room_if`]). + /// + /// [`Ledger::room_if`]: continuum_sage::place::Ledger::room_if + pub(super) fn freed_by_replacing(&self, consumer: &str, kind: ResourceKind) -> Vec<(ResourceKind, Bytes)> { + let resident = self.measured_by(consumer, kind); + let released = self.granted_to(consumer, kind).min(resident); + let its_landed = self + .leases + .values() + .filter(|held| held.lease.kind == kind && held.lease.consumer_id == consumer) + .map(|held| held.lease.bytes.saturating_sub(held.pending(self.observed_for(kind)))) + .fold(0u64, u64::saturating_add); + let axes = std::iter::once(kind).chain(self.backing.get(&kind).copied()); + axes.map(|axis| { + let kinds = self.pool_kinds_drawing_on(axis); + let reading = match self.backing.get(&axis) { + Some(_) => self.measured(axis), + None => self.physical_used(axis), + }; + let retained = self + .measured + .iter() + .flat_map(|(owner, footprints)| { let kinds = &kinds; footprints.iter().filter(move |f| kinds.contains(&f.kind) && (owner != consumer || f.kind != kind)) }) + .map(|f| f.bytes) + .fold(0u64, u64::saturating_add); + let landed = kinds.iter().map(|k| self.landed_on(*k)).fold(0u64, u64::saturating_add); + let after = reading.saturating_sub(resident).max(retained).saturating_sub(landed.saturating_sub(its_landed)); + (axis, Bytes(self.external(axis).saturating_sub(after).saturating_add(released))) + }) + .collect() + } + + /// `kind` and, when it is a pool, every kind drawing on it. + fn pool_kinds_drawing_on(&self, kind: ResourceKind) -> Vec { + if self.backing.contains_key(&kind) { + return vec![kind]; + } + std::iter::once(kind).chain(self.backing.iter().filter(|(_, pool)| **pool == kind).map(|(k, _)| *k)).collect() + } + + /// The bytes of `kind`'s leases proven landed in its accepted reading. + fn landed_on(&self, kind: ResourceKind) -> u64 { + self.leases + .values() + .filter(|held| held.lease.kind == kind) + .map(|held| held.lease.bytes.saturating_sub(held.pending(self.observed_for(kind)))) + .fold(0u64, u64::saturating_add) + } +} + +/// `consumer`'s owner on `place`: the same for its name every time, with no table to keep (step 3 of the +/// migration gives consumers a typed id and deletes this). +pub(super) fn owner_of(consumer: &str) -> Owner { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + consumer.hash(&mut hasher); + Owner(hasher.finish()) +} diff --git a/core/continuum-kernel/src/resources/mod.rs b/core/continuum-kernel/src/resources/mod.rs index 22754fc5b4..0a00c95b3d 100644 --- a/core/continuum-kernel/src/resources/mod.rs +++ b/core/continuum-kernel/src/resources/mod.rs @@ -201,7 +201,8 @@ pub use consumer::{ ConsumerFootprint, ReclaimOutcome, ReclaimReason, ReclaimRequest, ReclaimStatus, ResourceConsumer, }; -pub use ledger::LeaseView; +pub use ledger::{CarveError, LeaseView}; +pub use daemon::ask::{Ask, AskTicket}; pub use daemon::{DaemonConfig, Free, KindFree, LeaseGuard, LeasePoolView, ReplacementBudget, ResidencyGuard, ResidentFloor, ResourceDaemon, FREE}; pub use governor::{GovernorConfig, PlannedReclaim, ResourceGovernor}; pub use lease::{LeaseError, LeaseRequest, ReclaimPolicy, ResourceKind, ResourceLease}; diff --git a/core/continuum-sage/src/decide/capacity.rs b/core/continuum-sage/src/decide/capacity.rs index 87046aa4d4..10b84e1628 100644 --- a/core/continuum-sage/src/decide/capacity.rs +++ b/core/continuum-sage/src/decide/capacity.rs @@ -3,6 +3,10 @@ //! Joel and Codex, 2026-11-25: a remote GPU that looks idle is a candidate, never a plan; an accepted //! lease tells the scheduler what it can count on and for how long. The same model holds for this //! machine, my own machines, and another person's grid over the P2P mesh. +//! +//! A lease is generic over what it promises (Cormac, Codex, 2026-11-26): work a second for the grid, +//! bytes on a tier, slots of something held. They differ in dimension and lifetime, so each is its own +//! type and one is never spent as another (UNIFIED-PAGING.md, slice 3a). use std::time::{Duration, Instant}; @@ -15,22 +19,25 @@ pub struct Price { pub per_unit: f64, } -/// An accepted lease: what was agreed, until when, at what price. +/// Work a second a holder serves. +#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] +pub struct Rate(pub f64); + +/// An accepted lease: how much of `Q` was agreed, until when, at what price. #[derive(Debug, Clone, Copy, PartialEq)] -pub struct Lease { - /// Work per second the holder agreed to serve. - pub rate: f64, +pub struct Lease { + pub amount: Q, pub until: Instant, pub price: Price, } -/// One holder's capacity, as the ledger keeps it. +/// One holder's capacity to do work, as the ledger keeps it. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Capacity { /// Seen, not promised: the achieved rate as of when it was observed (it may already be gone). Observed { rate: Measured, as_of: Instant }, /// Promised for a term: counted on until the lease ends. - Committed(Lease), + Committed(Lease), } impl Capacity { @@ -38,7 +45,7 @@ impl Capacity { /// observation is only a candidate to ask for a lease. pub fn committed_at(&self, now: Instant) -> f64 { match self { - Self::Committed(lease) if now < lease.until => lease.rate, + Self::Committed(lease) if now < lease.until => lease.amount.0, _ => 0.0, } } diff --git a/core/continuum-sage/src/decide/cases/placement.rs b/core/continuum-sage/src/decide/cases/placement.rs index 31d809cfd9..949909425d 100644 --- a/core/continuum-sage/src/decide/cases/placement.rs +++ b/core/continuum-sage/src/decide/cases/placement.rs @@ -5,7 +5,7 @@ use std::time::{Duration, Instant}; -use super::super::capacity::{Capacity, Lease}; +use super::super::capacity::{Capacity, Lease, Rate}; use super::super::measured::Measured; use super::super::use_case::{Gate, UseCase, Violation}; @@ -59,14 +59,14 @@ pub struct Outcome { /// Whether `lease` carries `work` to its end from `now` within its budget: in force for the work's /// whole predicted run (plus its transfer and queue), and priced within what may be spent. Observed /// capacity is never enough; neither is a lease that ends mid-run or costs past the budget. -fn carries(lease: &Lease, holder: &Holder, work: &Work, now: Instant) -> bool { +fn carries(lease: &Lease, holder: &Holder, work: &Work, now: Instant) -> bool { let (Some(predicted), Some(transfer), Some(queue)) = (work.predicted.value(), holder.transfer.value(), holder.queue.value()) else { return false; // an unmeasured term cannot be shown to fit }; // The lease's guaranteed rate bounds how long the work takes there, whatever was predicted: a // zero or non-finite rate carries nothing (Codex on #6278). - let Ok(guaranteed) = Duration::try_from_secs_f64(work.units / lease.rate) else { return false }; - if !(lease.rate.is_finite() && lease.rate > 0.0) { + let Ok(guaranteed) = Duration::try_from_secs_f64(work.units / lease.amount.0) else { return false }; + if !(lease.amount.0.is_finite() && lease.amount.0 > 0.0) { return false; } let run = predicted.max(guaranteed) + transfer + queue; diff --git a/core/continuum-sage/src/decide/mod.rs b/core/continuum-sage/src/decide/mod.rs index c84b921511..258e66734b 100644 --- a/core/continuum-sage/src/decide/mod.rs +++ b/core/continuum-sage/src/decide/mod.rs @@ -28,7 +28,7 @@ mod replay; mod ridge; mod use_case; -pub use capacity::{Capacity, Lease, Price}; +pub use capacity::{Capacity, Lease, Price, Rate}; pub use measured::{Ewma, Fraction, LineFit, Measured, Window}; pub use algorithms::{Algorithms, Factory, Unknown}; pub use linear_ucb::{Featured, LinearUcb}; diff --git a/core/continuum-sage/src/decide/policy.rs b/core/continuum-sage/src/decide/policy.rs index 07f1e3f4e7..aeb6feea2a 100644 --- a/core/continuum-sage/src/decide/policy.rs +++ b/core/continuum-sage/src/decide/policy.rs @@ -25,9 +25,10 @@ impl Choice { /// else the envelope's own first, since an action the envelope did not offer is one it decided /// against. Index 0 here is a real action, never a stand-in for an absent one. pub fn wanted_or_envelopes_first(admissible: &[A], wanted: &A) -> Self { + const ENVELOPES_FIRST: usize = 0; let index = match admissible.iter().position(|action| action == wanted) { Some(offered) => offered, - None => 0, + None => ENVELOPES_FIRST, }; Self { index, expected: None } } diff --git a/core/continuum-sage/src/decide/tests.rs b/core/continuum-sage/src/decide/tests.rs index 2cbfa1d6d8..8ab20b5ac1 100644 --- a/core/continuum-sage/src/decide/tests.rs +++ b/core/continuum-sage/src/decide/tests.rs @@ -183,7 +183,7 @@ fn the_lane_forces_an_overdue_mind_and_offers_batches_only_as_wide_as_the_core() fn placement_admits_a_peer_only_under_a_lease_that_carries_the_work_within_budget() { let now = Instant::now(); let measured = |seconds| Measured::Value(Duration::from_secs(seconds)); - let lease = |rate, until_s, per_unit| Capacity::Committed(Lease { rate, until: now + Duration::from_secs(until_s), price: Price { per_unit } }); + let lease = |rate, until_s, per_unit| Capacity::Committed(Lease { amount: Rate(rate), until: now + Duration::from_secs(until_s), price: Price { per_unit } }); let peer = |id, capacity| placement::Holder { id, capacity, transfer: measured(2), queue: measured(1) }; let holders = vec![ peer(1, Capacity::Observed { rate: Measured::Value(40.0), as_of: now }), diff --git a/core/continuum-sage/src/lib.rs b/core/continuum-sage/src/lib.rs index 7d03444815..64abb9b99d 100644 --- a/core/continuum-sage/src/lib.rs +++ b/core/continuum-sage/src/lib.rs @@ -24,6 +24,7 @@ mod outbox; mod qos; mod scheduler; pub mod decide; +pub mod place; pub mod slice; mod stage; pub mod clock; diff --git a/core/continuum-sage/src/place/claim.rs b/core/continuum-sage/src/place/claim.rs new file mode 100644 index 0000000000..8d91f9d09a --- /dev/null +++ b/core/continuum-sage/src/place/claim.rs @@ -0,0 +1,102 @@ +//! A claim: what one owner holds or has had prepared, across every place it asked for, as one unit. +//! +//! The consumer holds a [`Claim`] and spends it with [`Claim::consume`], which answers at once from +//! the claim's own atomics and never waits: the engine thread calls it inside a graph (UNIFIED-PAGING.md, +//! "Prepare, consume, commit"). Everything that can wait (making room, demoting) happened before the +//! claim was granted, on the placer's side. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Instant; + +use super::quantity::Quantity; + +/// One claim's identity, never reused by its ledger. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ClaimId(pub u64); + +/// Who asked: an owner's identity, stable across its restarts. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Owner(pub u64); + +/// Which incarnation of an owner asked. A restarted owner has a later generation, and a claim made +/// by an earlier one can no longer be spent or committed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Generation(pub u64); + +/// How much of `Q` one claim wants on one place. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Need { + pub place: P, + pub amount: Q, +} + +/// A granted claim, as its consumer holds it: what is prepared on each place, and what of it is not +/// yet consumed. Cloning shares the same remainder. +#[derive(Debug, Clone)] +pub struct Claim { + pub(super) id: ClaimId, + pub(super) owner: Owner, + pub(super) generation: Generation, + pub(super) prepared: Arc<[(Need, AtomicU64)]>, + pub(super) expiry: Expiry, +} + +impl Claim { + pub fn id(&self) -> ClaimId { + self.id + } + + pub fn owner(&self) -> (Owner, Generation) { + (self.owner, self.generation) + } + + /// Spend `amount` on `place` from what this claim had prepared there. Answers at once, never + /// waits: false when the claim has no such place, not that much left, or has lapsed, and nothing + /// is spent. + pub fn consume(&self, place: P, amount: Q) -> bool { + if self.expiry.lapsed(Instant::now()) { + return false; // a lapsed claim is not spent + } + let Some((_, left)) = self.prepared.iter().find(|(need, _)| need.place == place) else { + return false; + }; + left.fetch_update(Ordering::AcqRel, Ordering::Acquire, |left| left.checked_sub(amount.units())).is_ok() + } + + /// What is prepared on `place` and not yet consumed, if this claim holds that place: nothing once + /// it has lapsed. + pub fn left(&self, place: P) -> Option { + let lapsed = self.expiry.lapsed(Instant::now()); + self.prepared.iter().find(|(need, _)| need.place == place).map(|(_, left)| Q::of(if lapsed { 0 } else { left.load(Ordering::Acquire) })) + } +} + +/// When a claim lapses, readable from any thread without the ledger: nanoseconds past `origin`, +/// `u64::MAX` for none. Past it the claim is overdue: its remainder reads nothing and cannot be spent, +/// and the ledger lists it for reclaim, but its holding is freed only by a release (a lease that +/// lapsed has not yet given its memory back). +#[derive(Debug, Clone)] +pub(super) struct Expiry { + origin: Instant, + until: Arc, +} + +impl Expiry { + pub(super) fn never() -> Self { + Self { origin: Instant::now(), until: Arc::new(AtomicU64::new(u64::MAX)) } + } + + /// Lapse at `until` (an instant before the claim was made lapses at once). + pub(super) fn set(&self, until: Instant) { + let nanos = until.saturating_duration_since(self.origin).as_nanos(); + // a term past u64 nanoseconds (584 years) still ends: it is held just below "none" + self.until.store(nanos.min(u128::from(u64::MAX - 1)) as u64, Ordering::Release); + } + + /// Whether it has lapsed at `now`. + pub(super) fn lapsed(&self, now: Instant) -> bool { + let until = self.until.load(Ordering::Acquire); + until != u64::MAX && u128::from(until) <= now.saturating_duration_since(self.origin).as_nanos() + } +} diff --git a/core/continuum-sage/src/place/component.rs b/core/continuum-sage/src/place/component.rs new file mode 100644 index 0000000000..20aabb46d3 --- /dev/null +++ b/core/continuum-sage/src/place/component.rs @@ -0,0 +1,262 @@ +//! The placer: the one SAGE component that owns a [`Ledger`] (UNIFIED-PAGING.md, slice 3a). Nobody +//! holds it, awaits it or locks it; a consumer spends a granted claim straight from its atomics. +//! +//! - **In: acts, by its `Teller`.** Lossless, in order, from any number of consumers. An event topic +//! has one writer and drops a lagging subscriber's oldest, so it suits neither many askers nor an ask +//! that must be answered. A consumer names each ask (`AskId`: its owner and its own sequence) and +//! refers to it after: commit, unwind, release, forget. The authority tells it room the same way. +//! - **Out: state, never events.** Each owner's asks are a state keyed by the owner on `Domain::ASKS`: +//! every live ask and where it stands (waiting with its shortfall, granted with the claim, committed, +//! retired, or a terminal answer). It is the whole table each time, so a consumer that wakes late or +//! restarts reads where everything stands; nothing hangs on catching one event. `Domain::SHORT` is +//! each place's shortfall to its waits: the law's demand, and how far each wait is from its grant. +//! +//! One placer per domain: a domain names its places, its quantity and its topics, so bytes on a node's +//! tiers and minds awake on it are two placers on the same code. + +use std::collections::HashMap; +use std::fmt::Debug; + +use super::claim::{Claim, ClaimId, Generation, Need, Owner}; +use super::ledger::{Answer, Ledger, NeverNow, Refusal}; +use super::quantity::Quantity; +use crate::component::{Bus, Component, Ctx, Key, Taken, Wiring}; +use crate::dataflow::{Publisher, TopicName}; +use crate::Qos; + +/// What one placer places: its places, the quantity they hold, and its topics. +pub trait Domain: Send + 'static { + type Place: Copy + PartialEq + Debug + Send + Sync + 'static; + type Quantity: Quantity; + /// The placer's component name. + const NAME: &'static str; + /// Each owner's asks, a state keyed by the owner. + const ASKS: TopicName; + /// Each place's shortfall to its waits, a state. + const SHORT: TopicName; +} + +/// One ask, named by its consumer: its owner and the consumer's own sequence for it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct AskId { + pub owner: Owner, + pub seq: u64, +} + +/// The key an owner's asks are published under. +pub fn key_of(owner: Owner) -> Key { + Key(u128::from(owner.0)) +} + +/// What the placer is told. +#[derive(Debug)] +pub enum Act { + Prepare { ask: AskId, generation: Generation, needs: Vec> }, + /// The claim's spending is over: what it consumed is held. + Commit(AskId), + /// It will not be spent: everything it prepared returns. + Unwind(AskId), + /// Its holding was released by its allocator (the consumer's fence): free again. + Release(AskId), + /// A terminal answer has been read: drop it from the owner's table. + Forget(AskId), + /// A place's room, as the authority measures it. + Room { place: P, capacity: Q, budget: Q }, +} + +/// Where one ask stands. +#[derive(Debug, Clone)] +pub enum Status { + Waiting { short: Vec> }, + Granted(Claim), + Committed, + /// Held by an earlier generation of its owner: charged until released. + Retired, + Never { place: P, need: Q, capacity: Q }, + Unknown { place: P }, + Stale, + Refused(Refusal), +} + +/// One owner's asks, as the placer publishes them: (its sequence, where it stands). +#[derive(Debug, Clone)] +pub struct Asks(pub Vec<(u64, Status)>); + +/// Each place's shortfall to its waits. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Shortfall(pub Vec>); + +struct Entry { + seq: u64, + claim: Option, + status: Status, +} + +struct Table { + generation: Generation, + entries: Vec>, + says: Publisher>, + changed: bool, +} + +/// The component around one domain's ledger. +pub struct Placer { + ledger: Ledger, + bus: &'static Bus, + owners: HashMap>, + asks_of: HashMap, + short: Publisher>, + last_short: Shortfall, + /// Reused across inputs: claims a pass granted, waits a capacity drop withdrew. + granted: Vec>, + never: Vec>, +} + +impl Placer { + /// Claim the domain's shortfall topic on `bus` (an owner's asks are claimed at its first ask); + /// refused if another placer holds it. + pub fn new(bus: &'static Bus) -> Result { + Ok(Self { + ledger: Ledger::default(), + bus, + owners: HashMap::new(), + asks_of: HashMap::new(), + short: bus.publisher(D::SHORT, Key::ONE)?, + last_short: Shortfall(Vec::new()), + granted: Vec::new(), + never: Vec::new(), + }) + } + + fn act(&mut self, act: Act) { + match act { + Act::Prepare { ask, generation, needs } => self.prepare(ask, generation, &needs), + Act::Commit(ask) => self.settle(ask, |ledger, id| ledger.commit(id), Some(Status::Committed)), + Act::Unwind(ask) => self.settle(ask, |ledger, id| ledger.unwind(id), None), + Act::Release(ask) => self.settle(ask, |ledger, id| ledger.release(id), None), + Act::Forget(ask) => { + if let Some(table) = self.owners.get_mut(&ask.owner) { + table.entries.retain(|entry| entry.seq != ask.seq || entry.claim.is_some()); + table.changed = true; + } + } + Act::Room { place, capacity, budget } => self.ledger.place(place, capacity, budget, &mut self.never), + } + } + + fn prepare(&mut self, ask: AskId, generation: Generation, needs: &[Need]) { + // the owner's table first: an ask whose answer cannot be said is never prepared, so no claim + // is held for an owner who could not read it + if let Err(taken) = self.table(ask.owner) { + continuum_base::probe!(class = "place.asks.taken", placer = D::NAME, owner = ask.owner.0, topic = taken.0 .0, + "an owner's asks key is held elsewhere: its ask is not prepared"); + return; + } + let answer = self.ledger.prepare(ask.owner, generation, needs); + let Some(table) = self.owners.get_mut(&ask.owner) else { return }; + if generation > table.generation { + // a later incarnation: its predecessor's holdings stay charged as retired, everything else of it is gone + table.generation = generation; + table.entries.retain_mut(|entry| match entry.status { + Status::Granted(_) | Status::Committed => { + entry.status = Status::Retired; + true + } + Status::Retired => true, + _ => false, + }); + } + let (claim, status) = match answer { + Answer::Granted(claim) => (Some(claim.id()), Status::Granted(claim)), + Answer::Waiting { id, short } => (Some(id), Status::Waiting { short }), + Answer::Never { place, need, capacity } => (None, Status::Never { place, need, capacity }), + Answer::Unknown { place } => (None, Status::Unknown { place }), + Answer::Stale { .. } => (None, Status::Stale), + }; + table.entries.push(Entry { seq: ask.seq, claim, status }); + table.changed = true; + if let Some(id) = claim { + self.asks_of.insert(id, ask); + } + } + + /// Commit, unwind or release the claim behind `ask`. On success the ask becomes `then`, or leaves + /// the table; a refusal is recorded on it. + fn settle( + &mut self, + ask: AskId, + apply: impl FnOnce(&mut Ledger, ClaimId) -> Result<(), Refusal>, + then: Option>, + ) { + let Some(table) = self.owners.get_mut(&ask.owner) else { return }; + let Some(at) = table.entries.iter().position(|entry| entry.seq == ask.seq) else { return }; + let Some(id) = table.entries[at].claim else { return }; + table.changed = true; + match (apply(&mut self.ledger, id), then) { + (Ok(()), Some(status)) => table.entries[at].status = status, + (Ok(()), None) => { + table.entries.remove(at); + self.asks_of.remove(&id); + } + (Err(refused), _) => table.entries[at].status = Status::Refused(refused), + } + } + + /// Make sure the owner has a table, claiming its topic key at its first ask; refused if the key is + /// held elsewhere. + fn table(&mut self, owner: Owner) -> Result<(), Taken> { + if !self.owners.contains_key(&owner) { + let says = self.bus.publisher(D::ASKS, key_of(owner))?; + self.owners.insert(owner, Table { generation: Generation(0), entries: Vec::new(), says, changed: false }); + } + Ok(()) + } + + /// After any act: grant what now fits, answer waits that can never fit, and say every table and + /// the shortfall that changed. + fn publish(&mut self, ctx: &mut Ctx) { + self.ledger.grant_waiting(&mut self.granted); + for claim in self.granted.drain(..) { + let Some(ask) = self.asks_of.get(&claim.id()).copied() else { continue }; + if let Some(entry) = self.owners.get_mut(&ask.owner).and_then(|table| { + table.changed = true; + table.entries.iter_mut().find(|entry| entry.seq == ask.seq) + }) { + entry.status = Status::Granted(claim); + } + } + for never in self.never.drain(..) { + let Some(ask) = self.asks_of.remove(&never.id) else { continue }; + if let Some(entry) = self.owners.get_mut(&ask.owner).and_then(|table| { + table.changed = true; + table.entries.iter_mut().find(|entry| entry.seq == ask.seq) + }) { + (entry.claim, entry.status) = (None, Status::Never { place: never.place, need: never.need, capacity: never.capacity }); + } + } + for table in self.owners.values_mut().filter(|table| table.changed) { + table.changed = false; + let asks = Asks(table.entries.iter().map(|entry| (entry.seq, entry.status.clone())).collect()); + ctx.publish(&mut table.says, asks); + } + let short = Shortfall(self.ledger.shortfalls().filter(|need| need.amount.units() > 0).collect()); + if short != self.last_short { + self.last_short.0.clone_from(&short.0); + ctx.publish(&mut self.short, short); + } + } +} + +impl Component for Placer { + type Input = Act; + const NAME: &'static str = D::NAME; + const QOS: Qos = Qos::Interactive; + + /// It hears nothing on the bus: every ask and every room arrives by its teller. + fn wire(&self, _: &mut Wiring<'_, Self>) {} + + async fn handle(&mut self, act: Self::Input, ctx: &mut Ctx) { + self.act(act); + self.publish(ctx); + } +} diff --git a/core/continuum-sage/src/place/ledger.rs b/core/continuum-sage/src/place/ledger.rs new file mode 100644 index 0000000000..af6393feb6 --- /dev/null +++ b/core/continuum-sage/src/place/ledger.rs @@ -0,0 +1,529 @@ +//! The one picture of what each place holds (UNIFIED-PAGING.md, "Every byte the engine holds is a +//! block", and slice 3a). A place has a proven capacity (what it could ever give, with everything +//! demotable demoted) and a budget (what its lease from the authority gives now, which external +//! pressure shrinks). Its budget is split into what is held by committed claims, what is prepared +//! for granted ones, and what is free. +//! +//! - A need past a place's capacity is the only refusal: [`Answer::Never`], a proven "never here". +//! - A need past what is free waits ([`Answer::Waiting`]), in order of asking, and is granted when +//! room appears: a budget that grows, a claim unwound or released. A wait names the shortfall on +//! each place, which is the demand the placement law answers by demoting. +//! - A grant is one claim across every place it asked for: all of it, or a wait. +//! - A claim belongs to one generation of its owner. A later generation retires every earlier one's +//! claims and waits, so an owner that restarted cannot spend or commit a stale claim. +//! +//! One owner (the placer's component) holds the ledger by `&mut`; the consumer spends a granted claim +//! through its atomics ([`Claim::consume`]) and never touches the ledger. + +use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + +mod room; + +use super::claim::{Claim, ClaimId, Expiry, Generation, Need, Owner}; +use super::quantity::Quantity; + +/// One place's accounts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Accounts { + /// What the place could ever give, every demotable holding demoted: the "never here" bound. + pub capacity: Q, + /// What its lease gives now. + pub budget: Q, + /// What committed claims hold. + pub held: Q, + /// What granted claims have prepared and not yet committed or unwound. + pub prepared: Q, +} + +impl Accounts { + /// What a new claim could be granted now. + pub fn free(&self) -> Q { + Q::of(self.budget.units().saturating_sub(self.held.units().saturating_add(self.prepared.units()))) + } + + /// What claims hold past the budget, after a budget shrank under them: what must be demoted. + pub fn over(&self) -> Q { + Q::of(self.held.units().saturating_add(self.prepared.units()).saturating_sub(self.budget.units())) + } +} + +/// The ledger's answer to a prepare. +#[derive(Debug)] +pub enum Answer { + /// Every need is prepared, as one claim. + Granted(Claim), + /// Not now: queued as `id`, short `short` on each place that lacks room. + Waiting { id: ClaimId, short: Vec> }, + /// Never on this node: `need` is past `place`'s capacity. + Never { place: P, need: Q, capacity: Q }, + /// A place this ledger has not been told of. + Unknown { place: P }, + /// An earlier generation of an owner a later one has replaced. + Stale { owner: Owner, generation: Generation }, +} + +/// Why a [`Ledger::take`] granted nothing: short now (what it lacks on each place), or an answer that is +/// never a grant (never here, unknown, stale). Nothing was queued. +#[derive(Debug)] +pub enum Untaken { + Short(Vec>), + Answered(Answer), +} + +/// Why a commit, unwind or release was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refusal { + /// No live claim has this id (already released, unwound, or retired by its owner's restart). + UnknownClaim(ClaimId), + /// The claim is prepared, not committed, so there is nothing held to release. + NotCommitted(ClaimId), + /// The claim is committed already. + Committed(ClaimId), + /// The claim had lapsed: it is not renewed, only released. + Lapsed(ClaimId), + /// The claim holds nothing on that place. + NotOnPlace(ClaimId), +} + +/// A wait withdrawn because a place's capacity fell below what it needs: its owner hears it as never +/// here. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct NeverNow { + pub id: ClaimId, + pub owner: Owner, + pub place: P, + pub need: Q, + pub capacity: Q, +} + +#[derive(Debug)] +enum Stage { + Prepared(Claim), + Committed { owner: Owner, generation: Generation, held: Vec>, expiry: Expiry }, + /// Held by an owner's earlier incarnation, which may still hold the memory (its process or GPU + /// context not yet gone): charged until its release is fenced, never credited on the restart alone. + Retired { held: Vec> }, +} + +#[derive(Debug)] +struct Waiting { + id: ClaimId, + owner: Owner, + generation: Generation, + needs: Vec>, +} + +/// Every place's accounts, every live claim and every wait, owned once. +#[derive(Debug)] +pub struct Ledger { + places: Vec<(P, Accounts)>, + claims: HashMap>, + waiting: VecDeque>, + generations: HashMap, + next: u64, + /// The physical pool each place that has one draws on ([`Ledger::back`]). + pools: Vec<(P, P)>, + /// Each owner's guaranteed amount of a place ([`Ledger::floor`]). + floors: Vec>, + /// `grant_waiting`'s scratch: places an earlier wait is still short on. Reused, never reallocated + /// once it has held as many places as there are. + blocked: Vec

, +} + +impl Default for Ledger { + fn default() -> Self { + Self { places: Vec::new(), claims: HashMap::new(), waiting: VecDeque::new(), generations: HashMap::new(), next: 0, pools: Vec::new(), floors: Vec::new(), blocked: Vec::new() } + } +} + +impl Ledger { + /// Tell the ledger a place's capacity and its budget now. A place is added the first time. + /// Afterwards call [`Ledger::grant_waiting`]: a budget that grew may grant a wait. A capacity that + /// fell below a queued wait's need withdraws that wait into `never`, for its owner to hear. + pub fn place(&mut self, place: P, capacity: Q, budget: Q, never: &mut Vec>) { + let budget = budget.min(capacity); + match self.places.iter_mut().find(|(at, _)| *at == place) { + Some((_, accounts)) => (accounts.capacity, accounts.budget) = (capacity, budget), + None => self.places.push((place, Accounts { capacity, budget, held: Q::of(0), prepared: Q::of(0) })), + } + self.waiting.retain(|wait| match wait.needs.iter().find(|need| need.place == place && need.amount > capacity) { + Some(need) => { + never.push(NeverNow { id: wait.id, owner: wait.owner, place, need: need.amount, capacity }); + false + } + None => true, + }); + } + + pub fn accounts(&self, place: P) -> Option> { + self.places.iter().find(|(at, _)| *at == place).map(|(_, accounts)| *accounts) + } + + /// Ask for `needs` (at most one per place; repeats are summed) as one claim of `owner`'s + /// `generation`. A later generation than the ledger knows retires the earlier one's claims first. + pub fn prepare(&mut self, owner: Owner, generation: Generation, needs: &[Need]) -> Answer { + let merged = match self.admissible(owner, generation, needs) { + Ok(merged) => merged, + Err(answer) => return answer, + }; + let id = self.issue(); + // in order of asking, per place: a newcomer waits only behind an earlier wait short on a place + // it also needs, so a wait on one place never holds up another + // (a need within its owner's own floor is a guarantee and queues behind no one) + let mut blocked = std::mem::take(&mut self.blocked); + self.held_by_waits(&mut blocked); + let behind = merged.iter().any(|need| blocked.contains(&need.place) && !self.within_floor(owner, need)); + self.blocked = blocked; + if !behind && self.fits(owner, &merged) { + return Answer::Granted(self.grant(id, owner, generation, merged)); + } + let short = self.short(owner, &merged); + self.waiting.push_back(Waiting { id, owner, generation, needs: merged }); + Answer::Waiting { id, short } + } + + /// Take `needs` now if they fit what is free, ahead of any wait, or not at all: the foreground's + /// no-wait path (the kernel authority's acquire, a turn's allocation), which never queues. A wait + /// is granted from what is free after it; which waits a foreground take may pass is the law's to + /// weigh, never a queue's. Any answer but a grant (short, never here, unknown, stale) leaves nothing + /// prepared and is returned. + pub fn take(&mut self, owner: Owner, generation: Generation, needs: &[Need]) -> Result, Untaken> { + let merged = self.admissible(owner, generation, needs).map_err(Untaken::Answered)?; + if !self.fits(owner, &merged) { + return Err(Untaken::Short(self.short(owner, &merged))); + } + let id = self.issue(); + Ok(self.grant(id, owner, generation, merged)) + } + + /// `needs` merged one per place (repeats summed), checked against the owner's generation, the places + /// the ledger knows and their capacity: the answer to give instead when they cannot be asked for. + fn admissible(&mut self, owner: Owner, generation: Generation, needs: &[Need]) -> Result>, Answer> { + if let Some(stale) = self.generation_is_stale(owner, generation) { + return Err(stale); + } + let mut merged: Vec> = Vec::with_capacity(needs.len()); + for need in needs { + match merged.iter_mut().find(|at| at.place == need.place) { + Some(at) => at.amount = Q::of(at.amount.units().saturating_add(need.amount.units())), + None => merged.push(*need), + } + } + for need in &merged { + if self.pooled_capacity(need.place).is_none() { + return Err(Answer::Unknown { place: need.place }); + } + } + if let Some((place, need, capacity)) = self.past_capacity(&merged) { + return Err(Answer::Never { place, need, capacity }); + } + Ok(merged) + } + + /// Grant every wait that fits now, in order of asking per place. Granted claims are pushed to + /// `granted` (a buffer the caller reuses). Which places each remaining wait holds is + /// [`Self::holds`]'s rule. + pub fn grant_waiting(&mut self, granted: &mut Vec>) { + let mut blocked = std::mem::take(&mut self.blocked); + blocked.clear(); + let mut at = 0; + while at < self.waiting.len() { + let wait = &self.waiting[at]; + let held_up = wait.needs.iter().any(|need| blocked.contains(&need.place) && !self.within_floor(wait.owner, need)); + if !held_up && self.fits(wait.owner, &wait.needs) { + if let Some(wait) = self.waiting.remove(at) { + let claim = self.grant(wait.id, wait.owner, wait.generation, wait.needs); + granted.push(claim); + } + continue; + } + self.holds(at, held_up, &mut blocked); + at += 1; + } + self.blocked = blocked; + } + + /// The places every queued wait holds, into `blocked` (cleared first), without granting. + fn held_by_waits(&self, blocked: &mut Vec

) { + blocked.clear(); + for at in 0..self.waiting.len() { + let wait = &self.waiting[at]; + let held_up = wait.needs.iter().any(|need| blocked.contains(&need.place) && !self.within_floor(wait.owner, need)); + self.holds(at, held_up, blocked); + } + } + + /// What the wait at `at` holds from later asks. A wait behind an earlier one holds only the places + /// it is short on, so a wait short on one place never starves another. The first wait in line on + /// its places (nobody ahead holds any of them) also holds its places that fit, so a stream of + /// later asks cannot spend them while it waits for its short place and leave it short there next + /// (Cormac, 2026-11-26 09:24Z: a seat needing Vram and Ram). + fn holds(&self, at: usize, held_up: bool, blocked: &mut Vec

) { + let wait = &self.waiting[at]; + let needs = &wait.needs; + if held_up { + blocked.extend(self.short_places(wait.owner, needs)); + } else { + blocked.extend(needs.iter().map(|need| need.place)); + } + } + + /// The claim's consumer is done spending it: what it consumed on each place becomes held, and + /// what it did not is returned. Its remainder is taken in the same atomic, so a consume after the + /// commit fails rather than spending what nobody holds. + pub fn commit(&mut self, id: ClaimId) -> Result<(), Refusal> { + let claim = match self.claims.remove(&id) { + Some(Stage::Prepared(claim)) => claim, + Some(other) => { + self.claims.insert(id, other); + return Err(Refusal::Committed(id)); + } + None => return Err(Refusal::UnknownClaim(id)), + }; + let held = self.settle(&claim); + self.claims.insert(id, Stage::Committed { owner: claim.owner, generation: claim.generation, held, expiry: claim.expiry.clone() }); + Ok(()) + } + + /// A granted claim that will not be spent (cancelled, or its allocation failed): everything it + /// prepared is returned. A queued wait with this id is withdrawn. + pub fn unwind(&mut self, id: ClaimId) -> Result<(), Refusal> { + if let Some(at) = self.waiting.iter().position(|wait| wait.id == id) { + self.waiting.remove(at); + return Ok(()); + } + match self.claims.remove(&id) { + Some(Stage::Prepared(claim)) => { + self.return_prepared(&claim); + Ok(()) + } + Some(other) => { + self.claims.insert(id, other); + Err(Refusal::Committed(id)) + } + None => Err(Refusal::UnknownClaim(id)), + } + } + + /// A committed claim's holdings, or a retired incarnation's, are released once the owner's + /// allocator has released them (the caller's fence): what it held is free again. + pub fn release(&mut self, id: ClaimId) -> Result<(), Refusal> { + match self.claims.remove(&id) { + Some(Stage::Committed { held, .. } | Stage::Retired { held }) => { + self.return_held(&held); + Ok(()) + } + Some(prepared @ Stage::Prepared(_)) => { + self.claims.insert(id, prepared); + Err(Refusal::NotCommitted(id)) + } + None => Err(Refusal::UnknownClaim(id)), + } + } + + /// Move `moved` (an amount on a place) of committed claim `id`'s holding to a new committed claim of `owner`'s + /// `generation`, as one transition: nothing is freed or taken, so every place's and pool's charge stays + /// exactly what it was and no wait or other taker can come between (Codex on 66c1fb471: a seat's stage + /// carved from its reserve). A claim moved to nothing is gone. Answers the new claim. + pub fn split(&mut self, id: ClaimId, moved: Need, owner: Owner, generation: Generation) -> Result { + let Need { place, amount } = moved; + let Some(Stage::Committed { held, .. }) = self.claims.get_mut(&id) else { + return Err(match self.claims.get(&id) { + Some(Stage::Prepared(_)) => Refusal::NotCommitted(id), + _ => Refusal::UnknownClaim(id), + }); + }; + let Some(on) = held.iter_mut().find(|need| need.place == place && need.amount >= amount) else { + return Err(Refusal::NotOnPlace(id)); + }; + on.amount = Q::of(on.amount.units() - amount.units()); + if held.iter().all(|need| need.amount.units() == 0) { + self.claims.remove(&id); + } + let new = self.issue(); + self.claims.insert(new, Stage::Committed { owner, generation, held: vec![Need { place, amount }], expiry: Expiry::never() }); + Ok(new) + } + + /// Give a live claim a term: it lapses at `until`. One already lapsed at `now` is not renewed: a + /// lapsed claim is overdue for reclaim, and only its release frees it. + pub fn renew(&mut self, id: ClaimId, until: std::time::Instant, now: std::time::Instant) -> Result<(), Refusal> { + let expiry = match self.claims.get(&id) { + Some(Stage::Prepared(claim)) => &claim.expiry, + Some(Stage::Committed { expiry, .. }) => expiry, + Some(Stage::Retired { .. }) | None => return Err(Refusal::UnknownClaim(id)), + }; + if expiry.lapsed(now) { + return Err(Refusal::Lapsed(id)); + } + expiry.set(until); + Ok(()) + } + + /// The live claims lapsed at `now`, pushed to `out` (a buffer the caller reuses): what the law + /// reclaims first. Lapsing frees nothing; their holdings stay charged until released. + pub fn overdue(&self, now: std::time::Instant, out: &mut Vec) { + out.extend(self.claims.iter().filter_map(|(id, stage)| match stage { + Stage::Prepared(claim) if claim.expiry.lapsed(now) => Some(*id), + Stage::Committed { expiry, .. } if expiry.lapsed(now) => Some(*id), + _ => None, + })); + } + + /// Part of a committed or retired claim's holding on `place` was released (its allocator gave back + /// `amount`, the caller's fence): that much is free again. Answers what it still holds there; a + /// claim holding nothing anywhere is gone. + pub fn shrink(&mut self, id: ClaimId, place: P, amount: Q) -> Result { + let held = match self.claims.get_mut(&id) { + Some(Stage::Committed { held, .. } | Stage::Retired { held }) => held, + Some(Stage::Prepared(_)) => return Err(Refusal::NotCommitted(id)), + None => return Err(Refusal::UnknownClaim(id)), + }; + let Some(on) = held.iter_mut().find(|need| need.place == place) else { + return Err(Refusal::NotOnPlace(id)); + }; + let freed = on.amount.min(amount); + on.amount = Q::of(on.amount.units() - freed.units()); + let left = on.amount; + let empty = held.iter().all(|need| need.amount.units() == 0); + if empty { + self.claims.remove(&id); + } + self.adjust(place, |accounts| accounts.held = Q::of(accounts.held.units().saturating_sub(freed.units()))); + Ok(left) + } + + /// What waits are short on `place`: their needs there past what is free. The placement law's + /// demand on that place. `None` for a place the ledger has not been told of. + pub fn shortfall(&self, place: P) -> Option { + let free = self.free(place)?.units(); + let wanted = self + .waiting + .iter() + .flat_map(|wait| wait.needs.iter()) + .filter(|need| need.place == place) + .fold(0u64, |sum, need| sum.saturating_add(need.amount.units())); + Some(Q::of(wanted.saturating_sub(free))) + } + + /// Every place's shortfall to its waits, in the order places were told. + pub fn shortfalls(&self) -> impl Iterator> + '_ { + self.places.iter().filter_map(|(place, _)| self.shortfall(*place).map(|amount| Need { place: *place, amount })) + } + + /// How many waits are queued. + pub fn waiting(&self) -> usize { + self.waiting.len() + } + + fn generation_is_stale(&mut self, owner: Owner, generation: Generation) -> Option> { + match self.generations.get(&owner).copied() { + Some(known) if generation < known => return Some(Answer::Stale { owner, generation }), + Some(known) if generation == known => return None, + _ => {} + } + self.generations.insert(owner, generation); + self.retire_before(owner, generation); + None + } + + /// Every claim and wait of `owner` from a generation before `generation` is retired. Its waits and + /// whatever its prepared claims never consumed return at once. What it consumed or committed stays + /// charged as `Retired` until [`Ledger::release`] after a fenced release, because the earlier + /// incarnation's process or GPU context may still hold that memory (Codex, 2026-11-26 07:20Z). + fn retire_before(&mut self, owner: Owner, generation: Generation) { + self.waiting.retain(|wait| wait.owner != owner || wait.generation >= generation); + let retired: Vec = self + .claims + .iter() + .filter(|(_, stage)| match stage { + Stage::Prepared(claim) => claim.owner == owner && claim.generation < generation, + Stage::Committed { owner: held_by, generation: held_in, .. } => *held_by == owner && *held_in < generation, + Stage::Retired { .. } => false, + }) + .map(|(id, _)| *id) + .collect(); + for id in retired { + match self.claims.remove(&id) { + Some(Stage::Prepared(claim)) => { + let held = self.settle(&claim); + if held.iter().any(|need| need.amount.units() > 0) { + self.claims.insert(id, Stage::Retired { held }); + } + } + Some(Stage::Committed { held, .. }) => { + self.claims.insert(id, Stage::Retired { held }); + } + Some(retired @ Stage::Retired { .. }) => { + self.claims.insert(id, retired); + } + None => {} + } + } + } + + /// Close a prepared claim's spending: take its remainders in one atomic each (a later consume + /// fails), return what was prepared, charge what was consumed as held, and answer what is held. + fn settle(&mut self, claim: &Claim) -> Vec> { + let mut held = Vec::with_capacity(claim.prepared.len()); + for (need, left) in claim.prepared.iter() { + let consumed = Q::of(need.amount.units().saturating_sub(left.swap(0, Ordering::AcqRel))); + self.adjust(need.place, |accounts| { + accounts.prepared = Q::of(accounts.prepared.units().saturating_sub(need.amount.units())); + accounts.held = Q::of(accounts.held.units().saturating_add(consumed.units())); + }); + held.push(Need { place: need.place, amount: consumed }); + } + held + } + + /// The places where `owner`'s `needs` are short of the room it has now. + fn short_places(&self, owner: Owner, needs: &[Need]) -> impl Iterator { + self.short(owner, needs).into_iter().map(|need| need.place) + } + + fn issue(&mut self) -> ClaimId { + self.next += 1; + ClaimId(self.next) + } + + fn fits(&self, owner: Owner, needs: &[Need]) -> bool { + self.short(owner, needs).is_empty() + } + + fn grant(&mut self, id: ClaimId, owner: Owner, generation: Generation, needs: Vec>) -> Claim { + for need in &needs { + self.adjust(need.place, |accounts| accounts.prepared = Q::of(accounts.prepared.units().saturating_add(need.amount.units()))); + } + let prepared: Arc<[(Need, AtomicU64)]> = needs.into_iter().map(|need| (need, AtomicU64::new(need.amount.units()))).collect(); + let claim = Claim { id, owner, generation, prepared, expiry: Expiry::never() }; + self.claims.insert(id, Stage::Prepared(claim.clone())); + claim + } + + fn return_prepared(&mut self, claim: &Claim) { + for (need, left) in claim.prepared.iter() { + left.store(0, Ordering::Release); // an unwound claim can no longer be spent + self.adjust(need.place, |accounts| accounts.prepared = Q::of(accounts.prepared.units().saturating_sub(need.amount.units()))); + } + } + + fn return_held(&mut self, held: &[Need]) { + for need in held { + self.adjust(need.place, |accounts| accounts.held = Q::of(accounts.held.units().saturating_sub(need.amount.units()))); + } + } + + /// Apply `change` to `place`'s accounts and, when it draws on a pool, to the pool's: one physical + /// memory, charged once there. + fn adjust(&mut self, place: P, change: impl Fn(&mut Accounts)) { + let pool = self.pool_of(place); + for (at, accounts) in self.places.iter_mut() { + if *at == place || Some(*at) == pool { + change(accounts); + } + } + } +} diff --git a/core/continuum-sage/src/place/ledger/room.rs b/core/continuum-sage/src/place/ledger/room.rs new file mode 100644 index 0000000000..5539675ffe --- /dev/null +++ b/core/continuum-sage/src/place/ledger/room.rs @@ -0,0 +1,213 @@ +//! What a claim can be granted on a place: its own free room, the free room of the physical pool it +//! draws on, and less every other owner's floor not yet filled. The one rule for "room" +//! (UNIFIED-PAGING.md, slice 3a; the kernel authority's `available_for`, moved here). +//! +//! - **Pools.** A place may draw on another place's physical memory (on unified memory, VRAM on RAM). +//! Every amount charged to it is charged to its pool too, once, and its room is the smaller of its +//! own and its pool's (Codex: one physical memory, one charge). +//! - **Floors.** An owner may be guaranteed an amount of a place (a live call's VRAM). Another owner's +//! room is net of what that floor still lacks; the floor's owner may fill it. A floor is a guarantee +//! like capacity, enforced here, never traded by the law (Fable, on the mapping). + +use super::super::claim::{Need, Owner}; +use super::super::quantity::Quantity; +use super::{Ledger, Stage}; + +/// `amount` of `place` guaranteed to `owner`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct Floor { + pub(super) owner: Owner, + pub(super) place: P, + pub(super) amount: Q, +} + +impl Ledger { + /// `place` draws on `pool`'s physical memory (`None`: its own). Tell it before granting on it. + /// A change moves what `place` already has charged from the pool it drew on to the new one, so a + /// later release returns it where it was posted (Codex on 7e348e827: a release after the backing + /// changed took 40 from a pool that never held it). + pub fn back(&mut self, place: P, pool: Option

) { + let pool = pool.filter(|pool| *pool != place); + let was = self.pool_of(place); + if was == pool { + return; + } + let Some(charged) = self.accounts(place) else { + self.pools.retain(|(at, _)| *at != place); + self.pools.extend(pool.map(|pool| (place, pool))); + return; + }; + let (held, prepared) = (charged.held.units(), charged.prepared.units()); + for (at, accounts) in self.places.iter_mut() { + if Some(*at) == was { + accounts.held = Q::of(accounts.held.units().saturating_sub(held)); + accounts.prepared = Q::of(accounts.prepared.units().saturating_sub(prepared)); + } + if Some(*at) == pool { + accounts.held = Q::of(accounts.held.units().saturating_add(held)); + accounts.prepared = Q::of(accounts.prepared.units().saturating_add(prepared)); + } + } + self.pools.retain(|(at, _)| *at != place); + self.pools.extend(pool.map(|pool| (place, pool))); + } + + /// Guarantee `owner` `amount` of `place` (zero withdraws the floor). + pub fn floor(&mut self, owner: Owner, place: P, amount: Q) { + self.floors.retain(|floor| floor.owner != owner || floor.place != place); + if amount.units() > 0 { + self.floors.push(Floor { owner, place, amount }); + } + } + + /// Replace every floor with `floors`: a guarantee not named again is withdrawn. + pub fn floors(&mut self, floors: impl IntoIterator) { + self.floors.clear(); + self.floors.extend(floors.into_iter().filter(|(_, _, amount)| amount.units() > 0).map(|(owner, place, amount)| Floor { owner, place, amount })); + } + + /// What `owner` could be granted on `place` now: the smaller of the place's free room and its pool's, + /// less what other owners' floors on that physical memory still lack. `None` for a place the ledger + /// has not been told of. + pub fn room_for(&self, owner: Owner, place: P) -> Option { + self.room_if(owner, place, &[]) + } + + /// What `owner` could be granted on `place` if `freed` were given back on the places it names (its + /// own holding, residency that would go with it): a planning answer, never a grant. Each place's free + /// room grows by what is freed on it, never past its capacity, and other owners' floors still bind + /// (the kernel authority's replace-myself budget, moved here). + pub fn room_if(&self, owner: Owner, place: P, freed: &[(P, Q)]) -> Option { + let on = |at: P| -> Option { + let accounts = self.accounts(at)?; + let given = freed.iter().filter(|(on, _)| *on == at).map(|(_, amount)| amount.units()).fold(0u64, u64::saturating_add); + // what is given back raises the budget before what is held is taken from it: a place already + // over its budget repays that first + let claimed = accounts.held.units().saturating_add(accounts.prepared.units()); + Some(accounts.budget.units().saturating_add(given).saturating_sub(claimed).min(accounts.capacity.units())) + }; + let free = match self.pool_of(place) { + Some(pool) => on(place)?.min(on(pool)?), + None => on(place)?, + }; + let root = self.root(place); + let owed = self + .floors + .iter() + .filter(|floor| floor.owner != owner && self.root(floor.place) == root) + .map(|floor| floor.amount.units().saturating_sub(self.holding_of(floor.owner, floor.place).units())) + .fold(0u64, u64::saturating_add); + Some(Q::of(free.saturating_sub(owed))) + } + + /// What `owner`'s `needs` lack now, as one ask: each place against its own room, and each physical + /// memory against the sum of every need drawing on it (Codex on 9bf241b3b: 60 on a place and 60 on + /// the pool of 100 it draws on were both granted, 120 prepared). One entry per short place, naming + /// the most it lacks. + pub(super) fn short(&self, owner: Owner, needs: &[Need]) -> Vec> { + let mut short: Vec> = Vec::new(); + let mut lacks = |place: P, wanted: u64, room: Option| { + let lack = match room { + Some(room) => wanted.saturating_sub(room.units()), + None => wanted, // a place never told has no room + }; + if lack == 0 { + return; + } + match short.iter_mut().find(|at| at.place == place) { + Some(at) => at.amount = Q::of(at.amount.units().max(lack)), + None => short.push(Need { place, amount: Q::of(lack) }), + } + }; + for need in needs { + lacks(need.place, need.amount.units(), self.room_for(owner, need.place)); + } + for (root, wanted) in self.by_memory(needs) { + lacks(root, wanted, self.room_for(owner, root)); + } + short + } + + /// The first need past what its physical memory could ever give, summed over every need of the ask + /// drawing on it: `(place, need, capacity)`. + pub(super) fn past_capacity(&self, needs: &[Need]) -> Option<(P, Q, Q)> { + for need in needs { + let capacity = self.pooled_capacity(need.place)?; + if need.amount > capacity { + return Some((need.place, need.amount, capacity)); + } + } + self.by_memory(needs).into_iter().find_map(|(root, wanted)| { + let capacity = self.accounts(root)?.capacity; + (wanted > capacity.units()).then(|| (root, Q::of(wanted), capacity)) + }) + } + + /// The sum of `needs` on each physical memory that more than one of them draws on. + fn by_memory(&self, needs: &[Need]) -> Vec<(P, u64)> { + let mut sums: Vec<(P, u64, usize)> = Vec::new(); + for need in needs { + let root = self.root(need.place); + match sums.iter_mut().find(|(at, _, _)| *at == root) { + Some((_, sum, count)) => { + *sum = sum.saturating_add(need.amount.units()); + *count += 1; + } + None => sums.push((root, need.amount.units(), 1)), + } + } + sums.into_iter().filter(|(_, _, count)| *count > 1).map(|(root, sum, _)| (root, sum)).collect() + } + + /// Whether `need` fits within what `owner`'s own floor on its place still lacks: a guarantee, so it + /// never queues behind another owner's wait. + pub(super) fn within_floor(&self, owner: Owner, need: &Need) -> bool { + self.floors + .iter() + .find(|floor| floor.owner == owner && floor.place == need.place) + .is_some_and(|floor| need.amount.units() <= floor.amount.units().saturating_sub(self.holding_of(owner, need.place).units())) + } + + /// What any owner could be granted on `place` now, floors aside: its free room, bounded by its + /// pool's. `None` for a place the ledger has not been told of. + pub fn free(&self, place: P) -> Option { + let own = self.accounts(place)?.free(); + match self.pool_of(place) { + Some(pool) => Some(own.min(self.accounts(pool)?.free())), + None => Some(own), + } + } + + /// The place's capacity, bounded by its pool's: the "never here" bound. + pub(super) fn pooled_capacity(&self, place: P) -> Option { + let own = self.accounts(place)?.capacity; + match self.pool_of(place) { + Some(pool) => Some(own.min(self.accounts(pool)?.capacity)), + None => Some(own), + } + } + + pub(super) fn pool_of(&self, place: P) -> Option

{ + self.pools.iter().find(|(at, _)| *at == place).map(|(_, pool)| *pool) + } + + /// The physical memory `place` draws on: its pool, or itself. + fn root(&self, place: P) -> P { + self.pool_of(place).unwrap_or(place) // unwrap_or: a place with no pool is its own physical memory, a fact + } + + /// What `owner` holds or has prepared on `place`. + fn holding_of(&self, owner: Owner, place: P) -> Q { + let on = |needs: &[Need]| needs.iter().filter(|need| need.place == place).map(|need| need.amount.units()).fold(0u64, u64::saturating_add); + let units = self + .claims + .values() + .map(|stage| match stage { + Stage::Prepared(claim) if claim.owner == owner => claim.prepared.iter().filter(|(need, _)| need.place == place).map(|(need, _)| need.amount.units()).fold(0u64, u64::saturating_add), + Stage::Committed { owner: held_by, held, .. } if *held_by == owner => on(held), + _ => 0, + }) + .fold(0u64, u64::saturating_add); + Q::of(units) + } +} diff --git a/core/continuum-sage/src/place/mod.rs b/core/continuum-sage/src/place/mod.rs new file mode 100644 index 0000000000..e84a033ec2 --- /dev/null +++ b/core/continuum-sage/src/place/mod.rs @@ -0,0 +1,28 @@ +//! SAGE's placement contract, once for everything finite that is shared (SAGE.md, "Ebb and flow"; +//! UNIFIED-PAGING.md, slice 3a). Bytes on a tier, minds awake on a node, models hot, participants +//! rendered full: each is a place holding a typed quantity, and each consumer asks the same way. +//! +//! - **Prepare**: one claim across every place it needs, all of it or a wait. A wait is never a +//! refusal; it names its shortfall, which is the demand the placement law makes room for. +//! - **Consume**: the consumer spends its granted claim from its own atomics and never waits, so a +//! claim can be spent inside an engine step. +//! - **Commit or unwind**: what was consumed becomes held, what was not is returned; a claim that will +//! not be spent returns everything. +//! - **Release**: a holding returns only when its owner's allocator has released it. +//! - **Never here**: refused only past a place's proven capacity, never for pressure. +//! +//! The ledger is `ledger`; the [`Placer`] is the component that owns one per domain (`component`). Its law +//! as a `decide::Policy` use case, and its consumers, come next on this contract. + +mod claim; +mod component; +mod ledger; +mod quantity; + +pub use claim::{Claim, ClaimId, Generation, Need, Owner}; +pub use component::{key_of, Act, AskId, Asks, Domain, Placer, Shortfall, Status}; +pub use ledger::{Accounts, Answer, Ledger, NeverNow, Refusal, Untaken}; +pub use quantity::{Bytes, Quantity, Slots}; + +#[cfg(test)] +mod tests; diff --git a/core/continuum-sage/src/place/quantity.rs b/core/continuum-sage/src/place/quantity.rs new file mode 100644 index 0000000000..65f9b32317 --- /dev/null +++ b/core/continuum-sage/src/place/quantity.rs @@ -0,0 +1,39 @@ +//! What a place holds, typed: bytes on a tier, slots of something kept (minds awake), tokens of a +//! window. Each is its own type, so one is never spent as another (UNIFIED-PAGING.md, slice 3a). A +//! quantity is whole units, so a claim's remainder can be consumed from any thread by one atomic. + +use std::fmt::Debug; + +/// A countable amount a place holds and a claim reserves. +pub trait Quantity: Copy + Ord + Debug + Send + Sync + 'static { + /// Its count of whole units. + fn units(self) -> u64; + /// The amount of `units` whole units. + fn of(units: u64) -> Self; +} + +/// Bytes, on a tier of memory or a volume. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +pub struct Bytes(pub u64); + +/// Slots of something held whole: a mind awake, a model hot, a participant rendered full. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +pub struct Slots(pub u64); + +impl Quantity for Bytes { + fn units(self) -> u64 { + self.0 + } + fn of(units: u64) -> Self { + Self(units) + } +} + +impl Quantity for Slots { + fn units(self) -> u64 { + self.0 + } + fn of(units: u64) -> Self { + Self(units) + } +} diff --git a/core/continuum-sage/src/place/tests.rs b/core/continuum-sage/src/place/tests.rs new file mode 100644 index 0000000000..8074c61557 --- /dev/null +++ b/core/continuum-sage/src/place/tests.rs @@ -0,0 +1,450 @@ +use super::*; + +const GB: u64 = 1 << 30; +const MB: u64 = 1 << 20; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Tier { + Vram, + Pinned, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Node { + Awake, +} + +const TRAINER: Owner = Owner(1); +const SERVING: Owner = Owner(2); +const FIRST: Generation = Generation(1); + +fn granted(answer: Answer) -> Claim { + match answer { + Answer::Granted(claim) => claim, + other => panic!("test: expected a grant, got {other:?}"), + } +} + +// what this catches: the 5090 on 2026-11-26 (5.18 MB of VRAM free, a seat needing 5.7 GB of a 32 GB +// card) refused outright; it must wait, naming its shortfall, and be granted when room appears. Only a +// need past the card itself is "never here". +#[test] +fn a_seat_short_of_room_waits_and_only_a_need_past_capacity_is_never_here() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(32 * GB), Bytes(32 * GB), &mut Vec::new()); + let serving = granted(ledger.prepare(SERVING, FIRST, &[Need { place: Tier::Vram, amount: Bytes(32 * GB - 5 * MB) }])); + assert!(serving.consume(Tier::Vram, Bytes(32 * GB - 5 * MB))); + assert_eq!(ledger.commit(serving.id()), Ok(())); + + let seat = Need { place: Tier::Vram, amount: Bytes(5_700 * MB) }; + let Answer::Waiting { id, short } = ledger.prepare(TRAINER, FIRST, &[seat]) else { panic!("test: a seat short of room waits") }; + assert_eq!(short, vec![Need { place: Tier::Vram, amount: Bytes(5_695 * MB) }], "the wait names what it lacks"); + assert_eq!(ledger.shortfall(Tier::Vram), Some(Bytes(5_695 * MB))); + + let mut out = Vec::new(); + ledger.grant_waiting(&mut out); + assert!(out.is_empty(), "no room yet"); + assert_eq!(ledger.release(serving.id()), Ok(()), "serving's allocation released"); + ledger.grant_waiting(&mut out); + assert_eq!(out.len(), 1, "granted when room appears"); + assert_eq!(out[0].id(), id); + + let past = ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(33 * GB) }]); + assert!(matches!(past, Answer::Never { need: Bytes(n), capacity: Bytes(c), .. } if n == 33 * GB && c == 32 * GB), "past the card: never here"); +} + +// what this catches: the engine thread waiting on, or overspending, a claim; and a commit charging what +// was prepared rather than what was spent (the night's gross-versus-growth counters). +#[test] +fn a_claim_is_spent_without_waiting_and_only_what_was_spent_is_held() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(8 * GB), Bytes(8 * GB), &mut Vec::new()); + ledger.place(Tier::Pinned, Bytes(16 * GB), Bytes(16 * GB), &mut Vec::new()); + let claim = granted(ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(2 * GB) }, Need { place: Tier::Pinned, amount: Bytes(GB) }])); + assert!(claim.consume(Tier::Vram, Bytes(GB))); + assert!(!claim.consume(Tier::Vram, Bytes(2 * GB)), "past what is left: refused, nothing spent"); + assert_eq!(claim.left(Tier::Vram), Some(Bytes(GB))); + assert!(claim.consume(Tier::Pinned, Bytes(1)), "each place spends from its own remainder"); + assert_eq!(claim.left(Tier::Pinned), Some(Bytes(GB - 1))); + assert_eq!(ledger.commit(claim.id()), Ok(())); + let vram = ledger.accounts(Tier::Vram).expect("test: told of it"); // expect: the test's own precondition + assert_eq!((vram.held, vram.prepared, vram.free()), (Bytes(GB), Bytes(0), Bytes(7 * GB)), "the unspent gigabyte is free again"); +} + +// what this catches: a seat whose allocation failed, or was cancelled, keeping its room. +#[test] +fn an_unwound_claim_returns_everything_and_a_withdrawn_wait_leaves_the_queue() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(4 * GB), Bytes(4 * GB), &mut Vec::new()); + let claim = granted(ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(3 * GB) }])); + let Answer::Waiting { id, .. } = ledger.prepare(SERVING, FIRST, &[Need { place: Tier::Vram, amount: Bytes(2 * GB) }]) else { panic!("test: waits") }; + assert_eq!(ledger.unwind(claim.id()), Ok(())); + assert_eq!(ledger.unwind(id), Ok(()), "a wait withdrawn"); + assert_eq!(ledger.waiting(), 0); + assert_eq!(ledger.accounts(Tier::Vram).map(|a| a.free()), Some(Bytes(4 * GB))); + assert_eq!(ledger.release(claim.id()), Err(Refusal::UnknownClaim(claim.id()))); +} + +// what this catches: an owner restarted mid-seat spending or holding its old incarnation's room. +#[test] +fn a_restarted_owner_retires_its_earlier_claims_and_cannot_spend_them() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(4 * GB), Bytes(4 * GB), &mut Vec::new()); + let old = granted(ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(3 * GB) }])); + let _new = granted(ledger.prepare(TRAINER, Generation(2), &[Need { place: Tier::Vram, amount: Bytes(3 * GB) }])); + assert_eq!(ledger.commit(old.id()), Err(Refusal::UnknownClaim(old.id())), "the earlier incarnation's claim is gone"); + assert!(matches!(ledger.prepare(TRAINER, FIRST, &[]), Answer::Stale { .. })); + assert_eq!(ledger.accounts(Tier::Vram).map(|a| a.prepared), Some(Bytes(3 * GB)), "only the new claim is counted"); +} + +// what this catches: a later, smaller ask passing an older wait (starvation), and pressure from +// outside read as anything but a smaller budget with what must be demoted. +#[test] +fn waits_are_granted_in_order_and_a_shrinking_budget_names_what_must_go() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(8 * GB), Bytes(4 * GB), &mut Vec::new()); + let held = granted(ledger.prepare(SERVING, FIRST, &[Need { place: Tier::Vram, amount: Bytes(3 * GB) }])); + let Answer::Waiting { id: older, .. } = ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(2 * GB) }]) else { panic!("test: waits") }; + let Answer::Waiting { .. } = ledger.prepare(Owner(3), FIRST, &[Need { place: Tier::Vram, amount: Bytes(1) }]) else { panic!("test: queued behind the older wait, though it fits") }; + ledger.place(Tier::Vram, Bytes(8 * GB), Bytes(6 * GB), &mut Vec::new()); + let mut out = Vec::new(); + ledger.grant_waiting(&mut out); + assert_eq!(out.iter().map(Claim::id).collect::>().first(), Some(&older), "the older wait first"); + assert_eq!(out.len(), 2); + + ledger.place(Tier::Vram, Bytes(8 * GB), Bytes(GB), &mut Vec::new()); + assert_eq!(ledger.accounts(Tier::Vram).map(|a| a.over()), Some(Bytes(4 * GB + 1)), "pressure from outside: this much must be demoted"); + drop(held); +} + +// what this catches: the outlier the contract must fit without forcing: minds awake on a node are +// slots, not bytes, and the same ledger places them. +#[test] +fn minds_awake_are_slots_in_the_same_ledger() { + let mut ledger: Ledger = Ledger::default(); + ledger.place(Node::Awake, Slots(4), Slots(2), &mut Vec::new()); + let aiko = granted(ledger.prepare(Owner(10), FIRST, &[Need { place: Node::Awake, amount: Slots(1) }])); + let _benchy = granted(ledger.prepare(Owner(11), FIRST, &[Need { place: Node::Awake, amount: Slots(1) }])); + assert!(matches!(ledger.prepare(Owner(12), FIRST, &[Need { place: Node::Awake, amount: Slots(1) }]), Answer::Waiting { .. }), "a third mind waits to wake"); + assert!(aiko.consume(Node::Awake, Slots(1))); + assert_eq!(ledger.commit(aiko.id()), Ok(())); + assert_eq!(ledger.release(aiko.id()), Ok(()), "she goes to sleep"); + let mut out = Vec::new(); + ledger.grant_waiting(&mut out); + assert_eq!(out.len(), 1, "the waiting mind wakes"); + assert!(matches!(ledger.prepare(Owner(13), FIRST, &[Need { place: Node::Awake, amount: Slots(5) }]), Answer::Never { .. })); +} + +// what this catches (Cormac's review of 5ea6e2edbc, 1): the 5090's Vram seat waiting with 5 MB free +// held up every later claim, a Pinned one with plenty free included. Order is per place. +#[test] +fn a_wait_short_on_one_place_never_holds_up_a_claim_on_another() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(32 * GB), Bytes(5 * MB), &mut Vec::new()); + ledger.place(Tier::Pinned, Bytes(64 * GB), Bytes(64 * GB), &mut Vec::new()); + let Answer::Waiting { id: seat, .. } = ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(5_700 * MB) }]) else { panic!("test: the seat waits") }; + let pinned = ledger.prepare(SERVING, FIRST, &[Need { place: Tier::Pinned, amount: Bytes(GB) }]); + assert!(matches!(pinned, Answer::Granted(_)), "Pinned has room and nobody waits on it"); + let Answer::Waiting { .. } = ledger.prepare(Owner(3), FIRST, &[Need { place: Tier::Vram, amount: Bytes(MB) }]) else { panic!("test: behind the older Vram wait, though it fits") }; + let Answer::Waiting { .. } = ledger.prepare(Owner(4), FIRST, &[Need { place: Tier::Vram, amount: Bytes(MB) }, Need { place: Tier::Pinned, amount: Bytes(GB) }]) else { panic!("test: waits on Vram") }; + ledger.place(Tier::Vram, Bytes(32 * GB), Bytes(5_700 * MB), &mut Vec::new()); + let mut out = Vec::new(); + ledger.grant_waiting(&mut out); + assert_eq!(out.iter().map(Claim::id).collect::>(), vec![seat], "the oldest wins its place; the 1 MB waits are then short"); + assert_eq!(ledger.waiting(), 2); +} + +// what this catches (review 2): a restarted owner's committed memory credited the moment it restarted, +// while its old process or GPU context may still hold it. +#[test] +fn a_restart_keeps_the_earlier_incarnations_holding_charged_until_its_release() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(4 * GB), Bytes(4 * GB), &mut Vec::new()); + let old = granted(ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(3 * GB) }])); + assert!(old.consume(Tier::Vram, Bytes(2 * GB))); + assert_eq!(ledger.commit(old.id()), Ok(())); + assert!(matches!(ledger.prepare(TRAINER, Generation(2), &[Need { place: Tier::Vram, amount: Bytes(3 * GB) }]), Answer::Waiting { .. }), "the old 2 GB still counts"); + assert_eq!(ledger.accounts(Tier::Vram).map(|a| a.held), Some(Bytes(2 * GB))); + assert_eq!(ledger.release(old.id()), Ok(()), "the old context's allocation released, fenced"); + let mut out = Vec::new(); + ledger.grant_waiting(&mut out); + assert_eq!(out.len(), 1, "only now is the room the new incarnation's"); +} + +// what this catches (review 3): a cloned claim spending after its commit, charged to nobody. +#[test] +fn a_consume_after_the_commit_fails() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(4 * GB), Bytes(4 * GB), &mut Vec::new()); + let claim = granted(ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(2 * GB) }])); + let late = claim.clone(); + assert!(claim.consume(Tier::Vram, Bytes(GB))); + assert_eq!(ledger.commit(claim.id()), Ok(())); + assert!(!late.consume(Tier::Vram, Bytes(1)), "nothing is left to spend once committed"); + assert_eq!(ledger.accounts(Tier::Vram).map(|a| (a.held, a.free())), Some((Bytes(GB), Bytes(3 * GB)))); +} + +// what this catches (review 4): a wait left queued forever after the place shrank below its need. +#[test] +fn a_capacity_that_falls_below_a_wait_answers_it_never_here() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(32 * GB), Bytes(GB), &mut Vec::new()); + let Answer::Waiting { id, .. } = ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(20 * GB) }]) else { panic!("test: waits") }; + let mut never = Vec::new(); + ledger.place(Tier::Vram, Bytes(16 * GB), Bytes(GB), &mut never); + assert_eq!(never, vec![NeverNow { id, owner: TRAINER, place: Tier::Vram, need: Bytes(20 * GB), capacity: Bytes(16 * GB) }]); + assert_eq!(ledger.waiting(), 0); +} + +// what this catches (Codex's repro on 5ea6e2edbc): two generations of one owner each spending the +// same 100 bytes, because the restart credited the old claim without revoking it; and a restart racing +// a spend on another thread charging nobody. +#[test] +fn a_retired_claim_cannot_be_spent_and_a_racing_spend_stays_charged() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(100), Bytes(100), &mut Vec::new()); + let old = granted(ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(100) }])); + let new = granted(ledger.prepare(TRAINER, Generation(2), &[Need { place: Tier::Vram, amount: Bytes(100) }])); + assert!(!old.consume(Tier::Vram, Bytes(100)), "the retired incarnation's claim is revoked"); + assert!(new.consume(Tier::Vram, Bytes(100))); + + for _ in 0..200 { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(100), Bytes(100), &mut Vec::new()); + let old = granted(ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(100) }])); + let spender = old.clone(); + let spend = std::thread::spawn(move || spender.consume(Tier::Vram, Bytes(60))); + assert!(matches!(ledger.prepare(TRAINER, Generation(2), &[]), Answer::Granted(_)), "the restart's own ask"); + let spent = spend.join().expect("test: the spending thread"); // expect: the test's own precondition + let held = ledger.accounts(Tier::Vram).map(|a| a.held); + assert_eq!(held, Some(Bytes(if spent { 60 } else { 0 })), "a spend that won the race is charged; one that lost spent nothing"); + } +} + +// what this catches (the kernel authority's lease terms, moving onto place): a lapsed lease still spent +// by native code, a lapsed lease credited as free before its holder released it, and a lapsed lease +// renewed back to life. +#[test] +fn a_lapsed_claim_reads_nothing_and_stays_charged_until_released() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(8 * GB), Bytes(8 * GB), &mut Vec::new()); + let claim = granted(ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(2 * GB) }])); + let now = std::time::Instant::now(); + assert_eq!(ledger.renew(claim.id(), now, now), Ok(()), "a live claim takes a term"); + assert_eq!(claim.left(Tier::Vram), Some(Bytes(0)), "past its term it reads nothing"); + assert!(!claim.consume(Tier::Vram, Bytes(1)), "and cannot be spent"); + let mut overdue = Vec::new(); + ledger.overdue(std::time::Instant::now(), &mut overdue); + assert_eq!(overdue, vec![claim.id()], "listed for reclaim"); + assert_eq!(ledger.accounts(Tier::Vram).map(|a| a.free()), Some(Bytes(6 * GB)), "lapsing frees nothing"); + assert_eq!(ledger.renew(claim.id(), now + std::time::Duration::from_secs(60), std::time::Instant::now()), Err(Refusal::Lapsed(claim.id()))); + assert_eq!(ledger.commit(claim.id()), Ok(())); + assert_eq!(ledger.release(claim.id()), Ok(())); + assert_eq!(ledger.accounts(Tier::Vram).map(|a| a.free()), Some(Bytes(8 * GB)), "its release frees it"); +} + +// what this catches (the kernel's shrink): a holder that gave back part of its memory keeping the +// whole charge, and a claim shrunk to nothing lingering. +#[test] +fn a_partial_release_frees_what_was_given_back() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(8 * GB), Bytes(8 * GB), &mut Vec::new()); + let claim = granted(ledger.prepare(SERVING, FIRST, &[Need { place: Tier::Vram, amount: Bytes(4 * GB) }])); + assert!(claim.consume(Tier::Vram, Bytes(4 * GB))); + assert_eq!(ledger.commit(claim.id()), Ok(())); + assert_eq!(ledger.shrink(claim.id(), Tier::Vram, Bytes(GB)), Ok(Bytes(3 * GB))); + assert_eq!(ledger.accounts(Tier::Vram).map(|a| (a.held, a.free())), Some((Bytes(3 * GB), Bytes(5 * GB)))); + assert_eq!(ledger.shrink(claim.id(), Tier::Pinned, Bytes(1)), Err(Refusal::NotOnPlace(claim.id()))); + assert_eq!(ledger.shrink(claim.id(), Tier::Vram, Bytes(9 * GB)), Ok(Bytes(0)), "giving back more than held frees what is held"); + assert_eq!(ledger.release(claim.id()), Err(Refusal::UnknownClaim(claim.id())), "shrunk to nothing, it is gone"); + assert_eq!(ledger.accounts(Tier::Vram).map(|a| a.free()), Some(Bytes(8 * GB))); +} + +// what this catches (the M5's unified memory, the kernel's set_backing): a VRAM claim and a host claim +// both granted out of one physical memory, as two counters would; and a VRAM need past the memory it +// draws on not answered "never here". +#[test] +fn a_place_backed_by_a_pool_is_charged_once_on_that_physical_memory() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(32 * GB), Bytes(32 * GB), &mut Vec::new()); + ledger.place(Tier::Pinned, Bytes(16 * GB), Bytes(16 * GB), &mut Vec::new()); + ledger.back(Tier::Vram, Some(Tier::Pinned)); + let gpu = granted(ledger.prepare(SERVING, FIRST, &[Need { place: Tier::Vram, amount: Bytes(10 * GB) }])); + assert_eq!(ledger.accounts(Tier::Pinned).map(|a| a.prepared), Some(Bytes(10 * GB)), "the pool carries the VRAM claim"); + assert_eq!(ledger.room_for(TRAINER, Tier::Vram), Some(Bytes(6 * GB)), "VRAM room is the pool's room"); + assert!(matches!(ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Pinned, amount: Bytes(10 * GB) }]), Answer::Waiting { .. }), "host and VRAM share one memory"); + assert!(matches!(ledger.prepare(SERVING, FIRST, &[Need { place: Tier::Vram, amount: Bytes(20 * GB) }]), Answer::Never { capacity: Bytes(c), .. } if c == 16 * GB), "past the physical memory: never here"); + assert_eq!(ledger.unwind(gpu.id()), Ok(())); + assert_eq!(ledger.accounts(Tier::Pinned).map(|a| a.prepared), Some(Bytes(0)), "returned to the pool too"); +} + +// what this catches (the kernel's reservations, a live call's floor): inference granted into the +// bytes a call is guaranteed, and the call itself kept out of its own floor. +#[test] +fn a_floor_is_kept_for_its_owner_and_others_are_granted_around_it() { + const CALL: Owner = Owner(3); + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(8 * GB), Bytes(8 * GB), &mut Vec::new()); + ledger.floor(CALL, Tier::Vram, Bytes(4 * GB)); + assert_eq!(ledger.room_for(TRAINER, Tier::Vram), Some(Bytes(4 * GB)), "others are granted around the floor"); + assert_eq!(ledger.room_for(CALL, Tier::Vram), Some(Bytes(8 * GB)), "its owner may fill it"); + assert!(matches!(ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(5 * GB) }]), Answer::Waiting { .. })); + let call = granted(ledger.prepare(CALL, FIRST, &[Need { place: Tier::Vram, amount: Bytes(3 * GB) }])); + assert_eq!(ledger.room_for(TRAINER, Tier::Vram), Some(Bytes(4 * GB)), "a floor partly filled still owes the rest"); + assert_eq!(ledger.unwind(call.id()), Ok(())); + ledger.floor(CALL, Tier::Vram, Bytes(0)); + let mut out = Vec::new(); + ledger.grant_waiting(&mut out); + assert_eq!(out.len(), 1, "a withdrawn floor's room is granted to the wait"); +} + +// what this catches (Cormac, 09:24Z): a seat needing Vram and Ram, short on Vram, while a stream of +// later Ram asks spends the Ram it will need, so when Vram frees it is short on Ram behind them. +// The first wait in line holds its fitting places too. +#[test] +fn a_two_place_wait_is_granted_when_its_short_place_frees_despite_asks_on_its_other() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(32 * GB), Bytes(GB), &mut Vec::new()); + ledger.place(Tier::Pinned, Bytes(16 * GB), Bytes(8 * GB), &mut Vec::new()); + let seat = [Need { place: Tier::Vram, amount: Bytes(6 * GB) }, Need { place: Tier::Pinned, amount: Bytes(6 * GB) }]; + let Answer::Waiting { id, .. } = ledger.prepare(TRAINER, FIRST, &seat) else { panic!("test: short on Vram") }; + for owner in 10..14 { + let ask = ledger.prepare(Owner(owner), FIRST, &[Need { place: Tier::Pinned, amount: Bytes(GB) }]); + assert!(matches!(ask, Answer::Waiting { .. }), "a later Pinned ask does not spend the seat's Pinned"); + } + let other = ledger.prepare(SERVING, FIRST, &[Need { place: Tier::Vram, amount: Bytes(1) }]); + assert!(matches!(other, Answer::Waiting { .. }), "nor its Vram"); + ledger.place(Tier::Vram, Bytes(32 * GB), Bytes(7 * GB), &mut Vec::new()); + let mut out = Vec::new(); + ledger.grant_waiting(&mut out); + assert_eq!(out.first().map(Claim::id), Some(id), "the seat first, once its short place frees"); + assert_eq!(out.len(), 1 + 2 + 1, "then the Pinned asks that still fit (2 of 4) and the 1-byte Vram ask"); +} + +/// Bytes on the test's two tiers, as one placer's domain. +struct Memory; + +impl Domain for Memory { + type Place = Tier; + type Quantity = Bytes; + const NAME: &'static str = "test-placer"; + const ASKS: crate::dataflow::TopicName = crate::dataflow::TopicName("test/place/asks"); + const SHORT: crate::dataflow::TopicName = crate::dataflow::TopicName("test/place/short"); +} + +// what this catches: a placer answering by a promise or an event a lagging consumer can lose (a lost +// grant leaks memory). Asks go in by its teller; each owner reads its whole table as state, so the +// seat that waited sees its grant once room appears, and a later ask past a shrunk capacity sees +// never-here, with nothing awaited and nothing held but the claim. +#[tokio::test] +async fn an_owner_reads_its_asks_as_state_waiting_then_granted_then_never_here() { + let bus: &'static crate::component::Bus = Box::leak(Box::new(crate::component::Bus::new())); + let placer = Placer::::new(bus).expect("test: the topics are free"); // expect: the test's own precondition + let running = crate::component::start(placer, bus, crate::dataflow::OwnerId(uuid::Uuid::from_u128(7)), 1); + let mut asks = bus.reader::>(Memory::ASKS, key_of(TRAINER)); + let seat = AskId { owner: TRAINER, seq: 1 }; + assert!(running.tell(Act::Room { place: Tier::Vram, capacity: Bytes(32 * GB), budget: Bytes(5 * MB) }).await); + assert!(running.tell(Act::Prepare { ask: seat, generation: FIRST, needs: vec![Need { place: Tier::Vram, amount: Bytes(5_700 * MB) }] }).await); + let waiting = asks.changed().await.expect("test: the placer runs"); // expect: the test's own precondition + assert!(matches!(waiting.value.0.as_slice(), [(1, Status::Waiting { .. })]), "it waits, naming its shortfall: {:?}", waiting.value); + + assert!(running.tell(Act::Room { place: Tier::Vram, capacity: Bytes(32 * GB), budget: Bytes(8 * GB) }).await); + let granted = asks.changed().await.expect("test: the placer runs"); // expect: the test's own precondition + let [(1, Status::Granted(claim))] = granted.value.0.as_slice() else { panic!("test: granted, got {:?}", granted.value) }; + assert!(claim.consume(Tier::Vram, Bytes(GB)), "spent straight from the claim, nothing awaited"); + + let later = AskId { owner: TRAINER, seq: 2 }; + assert!(running.tell(Act::Prepare { ask: later, generation: FIRST, needs: vec![Need { place: Tier::Vram, amount: Bytes(20 * GB) }] }).await); + asks.changed().await.expect("test: the placer runs"); // expect: the test's own precondition + assert!(running.tell(Act::Room { place: Tier::Vram, capacity: Bytes(16 * GB), budget: Bytes(8 * GB) }).await); + let never = asks.changed().await.expect("test: the placer runs"); // expect: the test's own precondition + assert!(matches!(never.value.0.as_slice(), [(1, Status::Granted(_)), (2, Status::Never { capacity: Bytes(c), .. })] if *c == 16 * GB), "{:?}", never.value); + assert!(running.tell(Act::Forget(later)).await); + let forgot = asks.changed().await.expect("test: the placer runs"); // expect: the test's own precondition + assert_eq!(forgot.value.0.len(), 1, "a read terminal answer leaves the table"); +} + +// what this catches (Codex on 9bf241b3b): one ask for 60 on a place and 60 on the pool of 100 it draws +// on, each checked alone against free room, granted as 120 of one physical memory. +#[test] +fn an_ask_is_summed_on_each_physical_memory_it_draws_on() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Pinned, Bytes(100), Bytes(100), &mut Vec::new()); + ledger.place(Tier::Vram, Bytes(100), Bytes(100), &mut Vec::new()); + ledger.back(Tier::Vram, Some(Tier::Pinned)); + let both = [Need { place: Tier::Vram, amount: Bytes(60) }, Need { place: Tier::Pinned, amount: Bytes(60) }]; + assert!(matches!(ledger.prepare(TRAINER, FIRST, &both), Answer::Never { place: Tier::Pinned, need: Bytes(120), capacity: Bytes(100) }), "past the memory itself: never here"); + let held = granted(ledger.prepare(SERVING, FIRST, &[Need { place: Tier::Pinned, amount: Bytes(30) }])); + let fits = [Need { place: Tier::Vram, amount: Bytes(40) }, Need { place: Tier::Pinned, amount: Bytes(40) }]; + let Answer::Waiting { short, .. } = ledger.prepare(TRAINER, FIRST, &fits) else { panic!("test: 80 of the 70 left waits") }; + assert_eq!(short, vec![Need { place: Tier::Pinned, amount: Bytes(10) }], "the memory names what the ask lacks on it"); + assert_eq!(ledger.unwind(held.id()), Ok(())); + let mut out = Vec::new(); + ledger.grant_waiting(&mut out); + assert_eq!(out.len(), 1, "granted once the memory has room for both"); + assert_eq!(ledger.accounts(Tier::Pinned).map(|a| a.prepared), Some(Bytes(80)), "charged once on the memory"); +} + +// what this catches (the kernel's replace-myself budget, #438/#214): a place already over its budget +// read as zero free before what an owner would give back is added, so the add-back hides the debt; and +// an add-back past the place's capacity. +#[test] +fn room_if_released_repays_an_over_budget_place_and_never_passes_capacity() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(100), Bytes(100), &mut Vec::new()); + let peer = granted(ledger.prepare(SERVING, FIRST, &[Need { place: Tier::Vram, amount: Bytes(20) }])); + assert!(peer.consume(Tier::Vram, Bytes(20))); + assert_eq!(ledger.commit(peer.id()), Ok(())); + ledger.place(Tier::Vram, Bytes(100), Bytes(10), &mut Vec::new()); // 90 resident beside it: 10 over + assert_eq!(ledger.room_for(TRAINER, Tier::Vram), Some(Bytes(0))); + assert_eq!(ledger.room_if(TRAINER, Tier::Vram, &[(Tier::Vram, Bytes(40))]), Some(Bytes(30)), "the 10 over is repaid first"); + assert_eq!(ledger.room_if(TRAINER, Tier::Vram, &[(Tier::Vram, Bytes(500))]), Some(Bytes(100)), "never past capacity"); +} + +// what this catches (Codex on 7e348e827): a backing that changes under live claims. Each tier holds 40; +// the GPU tier is then backed by the host pool and its claim released: the release must come off where +// the charge was posted, never off the pool's own owner's 40. +#[test] +fn a_backing_change_moves_what_is_charged_with_it() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(100), Bytes(100), &mut Vec::new()); + ledger.place(Tier::Pinned, Bytes(100), Bytes(100), &mut Vec::new()); + let held = |ledger: &mut Ledger, owner, place| { + let claim = granted(ledger.prepare(owner, FIRST, &[Need { place, amount: Bytes(40) }])); + assert!(claim.consume(place, Bytes(40))); + assert_eq!(ledger.commit(claim.id()), Ok(())); + claim.id() + }; + let gpu = held(&mut ledger, TRAINER, Tier::Vram); + held(&mut ledger, SERVING, Tier::Pinned); + ledger.back(Tier::Vram, Some(Tier::Pinned)); + assert_eq!(ledger.accounts(Tier::Pinned).map(|a| a.held), Some(Bytes(80)), "the pool carries the GPU tier's charge once backed"); + assert_eq!(ledger.release(gpu), Ok(())); + assert_eq!(ledger.accounts(Tier::Pinned).map(|a| a.held), Some(Bytes(40)), "the pool's own owner still holds its 40"); + ledger.back(Tier::Vram, None); + assert_eq!(ledger.accounts(Tier::Pinned).map(|a| a.held), Some(Bytes(40)), "unbacking moves nothing that is not there"); +} + +// what this catches (Codex on 66c1fb471): a stage carved from a reserve by releasing and taking again, +// where a wait or another taker can come between, or the taking fails after the release. A split moves +// the bytes as one transition: the place's and its pool's charges never move, and no wait is granted. +#[test] +fn a_split_moves_held_bytes_without_freeing_them() { + let mut ledger = Ledger::default(); + ledger.place(Tier::Vram, Bytes(100), Bytes(100), &mut Vec::new()); + ledger.place(Tier::Pinned, Bytes(100), Bytes(100), &mut Vec::new()); + ledger.back(Tier::Vram, Some(Tier::Pinned)); + let reserve = granted(ledger.prepare(TRAINER, FIRST, &[Need { place: Tier::Vram, amount: Bytes(100) }])); + assert!(reserve.consume(Tier::Vram, Bytes(100))); + assert_eq!(ledger.commit(reserve.id()), Ok(())); + assert!(matches!(ledger.prepare(SERVING, FIRST, &[Need { place: Tier::Vram, amount: Bytes(10) }]), Answer::Waiting { .. })); + let before = (ledger.accounts(Tier::Vram), ledger.accounts(Tier::Pinned)); + let stage = ledger.split(reserve.id(), Need { place: Tier::Vram, amount: Bytes(60) }, TRAINER, FIRST).expect("test: split"); // expect: the test's own precondition + assert_eq!((ledger.accounts(Tier::Vram), ledger.accounts(Tier::Pinned)), before, "every charge unchanged"); + let mut out = Vec::new(); + ledger.grant_waiting(&mut out); + assert!(out.is_empty(), "nothing was freed for the wait"); + assert_eq!(ledger.split(reserve.id(), Need { place: Tier::Vram, amount: Bytes(41) }, TRAINER, FIRST), Err(Refusal::NotOnPlace(reserve.id())), "never past what it holds"); + assert_eq!(ledger.release(stage), Ok(())); + assert_eq!(ledger.accounts(Tier::Pinned).map(|a| a.held), Some(Bytes(40)), "the stage releases its own 60"); +} diff --git a/core/vendor/LLAMA_CPP_PIN b/core/vendor/LLAMA_CPP_PIN index f750e51ee8..90104b7ddf 100644 --- a/core/vendor/LLAMA_CPP_PIN +++ b/core/vendor/LLAMA_CPP_PIN @@ -1 +1 @@ -7e81db0867bbd870df6622d1662fc015379ca0e0 +a29e679f7b25967885cc9b29f1ca00d18085acd4 diff --git a/core/vendor/llama.cpp b/core/vendor/llama.cpp index 7e81db0867..a29e679f7b 160000 --- a/core/vendor/llama.cpp +++ b/core/vendor/llama.cpp @@ -1 +1 @@ -Subproject commit 7e81db0867bbd870df6622d1662fc015379ca0e0 +Subproject commit a29e679f7b25967885cc9b29f1ca00d18085acd4 diff --git a/docs/architecture/UNIFIED-PAGING.md b/docs/architecture/UNIFIED-PAGING.md index 783720a242..8d07d2a2b8 100644 --- a/docs/architecture/UNIFIED-PAGING.md +++ b/docs/architecture/UNIFIED-PAGING.md @@ -85,7 +85,11 @@ stops working. So `Topology`, a SAGE component, keeps every quantity current, ea source that is true now: - **Free memory per tier:** the resource authority's `resources/free`, which already follows the OS (free and compressed RAM, swap, pressure on macOS; device free memory from the backend for VRAM). - `Topology` subscribes and never samples on its own. + `Topology` subscribes and never samples on its own. On unified memory, GPU allocations do not show + in the OS's free or available counters (measured elsewhere on Apple and Linux iGPUs; SPEED-BRAINSTORM, + "Lessons: inference-optimisation-skill"), so the authority's unified number must include the + driver's resident GPU bytes (`ioreg`/`vm_stat` on Apple), or the ledger's budget is a number that + is not true. - **Link and drive rates, passively:** every move a link makes is itself a measurement (bytes over measured time, by direction and volume), so the rates follow contention and thermal throttling at no cost. An active probe runs only for a volume no move has used within its staleness window, and @@ -536,6 +540,27 @@ would be memory-only, and each later instance would write it again. So the order `Consumer`s, and the Streamer's single lease per tier is no longer needed. Until then it is the bridge that keeps one counter. +**Audit against the golden rules (Joel, 2026-11-26: "thread and memory based, low cpu iterations and +good object oriented compression into solid generalizations").** `continuum_sage::place` at +f8d0f28655 passes the thread and memory rules: one `&mut` owner and no lock; the consumer spends +from per-place atomics and never waits; typed places, quantities, owners and generations, never a +string; nothing scans data. Prepare allocates its claim once (not per step), and a grant pass is +O(waits × places), a few of each. It fails the compression rule: it was written before searching +for copies, and three exist. + +| Copy | Where | What it has that `place` lacks | Its end | +|---|---|---|---| +| `ResourceLeaseLedger` (817 lines) | `continuum-kernel/src/resources/ledger.rs` | per-kind capacity from scans, physical-used samples, `set_backing` (a kind aliased onto another: unified memory), expiry and renew, reclaim selection; string consumer and lease ids | it becomes `place::Ledger` at node scope. Backing aliasing becomes the per-physical-memory place rule (settled above), physical samples feed `Accounts::budget`, and expiry is a claim's `until` (`Lease`). Typed `Owner`s replace the strings. Its reclaim selection is the law. Owners: Cormac (the authority, delta 8) with Codex | +| `ThroughputLeaseRegistry` | `continuum-kernel/src/resources/throughput_lease.rs` | concurrency slots for transient jobs | `Ledger<_, Slots>` | +| `Flow` + `Scheduler` | `continuum-sage/src/{flow,scheduler}.rs` | QoS classes and aging (a waiter ages one class at a time), yield requests to the lowest class; but answers through a future (a promise) and has no user outside its own tests | `Scheduler`'s aging is the placer law's answer to multi-place starvation (Cormac, 09:24Z). `Flow`'s future wrapper is deleted. | + +So slice 3a is not done until the kernel's ledger and registry are instances of `place::Ledger` and +their copies are deleted. Smaller findings on the same line: `LearningMemory::row` +(`continuum-engine/src/inference/learning/memory.rs:64`) matches a buffer by its name string on +every allocation callback on the engine thread; 3b deletes it, and until then it is bounded by a +seat's few allocations. The lane rebuilds its batch bound as a `NonZeroU64` at each pick: one add, +kept. + What it deletes, in the slice that builds it (slice 3b below): `LearningMemory`'s workspace and lease matching, `lease_memory`, `from_rows`, `learning::leased`, the metrics sum, training's path through `window_allocator`, and `GrantHandoff` as bytes. diff --git a/docs/planning/SPEED-BRAINSTORM.md b/docs/planning/SPEED-BRAINSTORM.md index ff194e3cb4..b9868deac4 100644 --- a/docs/planning/SPEED-BRAINSTORM.md +++ b/docs/planning/SPEED-BRAINSTORM.md @@ -132,6 +132,58 @@ before and after, send improvements back upstream (Codex submits). | Gufo | prompt-cache restore with thinking on (their reuse died after turn one; TTFT 199 s -> 4.1 s once fixed); the multi-hour soak method | our act-boundary reuse and the comparison harness | MIT | f2782aad | | llama.cpp | everything we ride on | keep the fork close, upstream our proven work | MIT | | +### Lessons: sybil-solutions/inference-optimisation-skill (read 2026-11-26) + +A hand hill-climb of one server for one user, on Intel Arc, RTX and Apple. Its worked example is our +model class (Qwen3.5-MoE 35B-A3B hybrid: 30 GDN + 10 full-attention layers, 256 experts, top-8). Read: +SKILL.md, references/levers.md, references/ceilings.md. Not read: methodology, gotchas, publishing, +scripts (Python; we take numbers and method, never the harness). Their numbers are priors on their +hardware, not ours (Joel: "The stats alone are worth knowing. We can beat all of this."). + +**Method we take:** +- **Ceiling first, progress as a fraction of it.** Decode bytes per token = dense + experts × top_k/n + + LM head (10-25% of the total on a large vocabulary; 0.382 of 1.648 GB in their example) + KV × context + + recurrent state × 2, over measured bandwidth (a device copy, never the spec: 115 vs 153.6 GB/s). + Prefill ≈ 2 × active params FLOPs a token at ~50% of measured peak. Their B390 reached ~55% of the + decode ceiling and ~94% of the 256K prefill ceiling. +- **Noise is ±5-10% run to run.** Median of ≥6, control / candidate / control, accept only beating both + controls with no regression past ~3%, repeat a surprising win. Three levers inside noise is a plateau. +- **Unified memory hides GPU allocations from MemAvailable and cgroups**: measure driver residency + (`ioreg` / `vm_stat` on Apple). Our Placer's per-tier budget on the M5 must come from that. +- **Never force-kill mid-batch**: drain, then stop (GPU driver faults seen). Plan S7. + +**Their stats (priors to beat):** + +| Lever | Measured there | +|---|---| +| Persisted JIT / compile caches | startup 113 s -> 43 s; 22 min -> 7 min | +| Decode graphs | c1 14.4 -> 28.4, 16 -> 32, 11 -> 27 tok/s | +| Draft LM head pruned to used vocab blocks | +27% (512 of 1,940 blocks, 98.6% coverage), +14%; worth more than an extra draft | +| Draft length by load | k=4 at c1, 3 at c4, 2 at c16; at 128K 1 draft 29.6 vs 3 drafts 15.5 tok/s | +| MTP on bandwidth-poor hardware | Apple M4 6.35 -> 3.25 tok/s with 3 drafts; llama.cpp MTP 36.7 vs 45.4 off, hard prompts | +| Verify as decode-style attention | prefill kernel grew 3.5 ms a 1K context (47 -> 104 ms at 16K) | +| Sampling on the GPU | ~3 ms a step, +10% c1 | +| q8_0 KV on a hybrid (KV in 16 of 64 layers) | 45.4 -> 27.0 tok/s on llama.cpp: KV quant is a trade | +| FP8 KV | halved one FA kernel (39 vs 69-74 TFLOPS); fp16 block dequant + LSE merge: 760 -> 1,059 tok/s | +| Hybrid state slots | cap concurrency, not KV tokens; exact 1,600-token block vs 2,048: c16 10 -> 14 streams | +| Prefix caching (engines silently disable it on hybrids) | turn-2 TTFT 36 s -> 0.45 s (66K), 29 s -> 0.95 s (32K) | +| Prefill chunk vs others' stalls | 8,192 -> 2,048: worst stall 7.1 -> 1.95 s for -4% decode | +| Int8 prefill GEMMs, Hadamard-rotated | 1.89x linears, NLL +0.17%, top-1 97.2%, decode bit-exact (labelled lossy) | +| MoE grouped GEMM tiles | 64-row M-block +7% prefill bit-exact; NT=2 +22% at c16 | +| Fusing small kernels under graphs | 0% three times: the time is in the big kernels | +| Faster attention library before writing one | +7-18%; hand-written FA 48 vs 61 TFLOPS | + +**Where we beat it, by design, not by hand:** every lever above is a constant someone climbed to on one +box. Ours are SAGE decisions learned per node and workload, each against its ceiling: chunk size is +already the lane's per-step answer from every waiter's slack (not one tuned number); draft length, +KV type, batch width and which minds are resident are `decide` use cases with replay; their "one +change, controls on both sides" is the dyno's A/B run continually; and the grid places work on whichever +node's ceiling is highest for it. A recipe is one point; a system that learns on every node keeps moving. + +**To check on ours:** the M5 decode ceiling for the served 35B as a validator (bytes a token over a +measured copy); what `llamacpp_adapter`'s per-residency KV quant picks for the hybrid; whether a draft +runs on the M5 and whether it wins there; GPU sampling (in the backlog, now with a measured reason). + Our specific integration goal (what we have to prove, not a claim about others): many persistent minds with senses sharing one engine, each with her own memory paged across GPU, RAM and disk; learning on the weights being served; one budget and scheduler across a grid of misfit hardware.