Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
45c2fdd
SAGE's placement ledger (slice 3a, first part): one claim across plac…
joelteply Nov 26, 2026
8b25a3f
place: order per place, retired holdings stay charged until a fenced …
joelteply Nov 26, 2026
397fed7
place: Codex's stale-spend repro and a restart racing a spend, as tests
joelteply Nov 26, 2026
30af7e4
Lessons from inference-optimisation-skill: its method and measured st…
joelteply Nov 26, 2026
f773b70
Design 3a: the golden-rules audit of place; three copies of the ledge…
joelteply Nov 26, 2026
275281f
place gains the kernel authority's lease terms, partial release, pool…
joelteply Nov 26, 2026
5a168d7
The placer as a SAGE component (slice 3a): asks in by its teller (los…
joelteply Nov 26, 2026
11a5ffb
place: an ask is summed on each physical memory it draws on (Codex on…
joelteply Nov 26, 2026
b0200b1
The kernel authority's leases are claims on place (slice 3a, step 2b,…
joelteply Nov 26, 2026
5232b29
The replace-myself budget reads place too; the kernel ledger's own ar…
joelteply Nov 26, 2026
688880a
place: a backing change moves what is charged with it (Codex on 7e348…
joelteply Nov 26, 2026
7309dbc
The authority waits instead of refusing: ask, a ticket its owner keep…
joelteply Nov 26, 2026
dc72e92
The authority carves a stage lease from a granted reserve under one lock
joelteply Nov 26, 2026
6c8fef6
Carve is one transition: place.split moves held bytes to the stage's …
joelteply Nov 26, 2026
67e25c8
Carve: split takes a Need (contract_shape), the test's expect is just…
joelteply Nov 26, 2026
03502b2
The trainer's seat waits on an ask and seats on stages carved from it…
joelteply Nov 26, 2026
61eed1d
Fable's follow-ups (1) and (4) on 7d59f5639: a probe when a take pass…
joelteply Nov 26, 2026
4c3e3eb
Pin the fork at a29e679f7: execution graphs build the mixed-input pat…
joelteply Nov 26, 2026
362c130
Record the fork pin a29e679f7 in LLAMA_CPP_PIN (vendor_pin; Fable on …
joelteply Nov 26, 2026
4b55de4
A pass that seats nothing gives its granted reserve back
joelteply Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
187 changes: 119 additions & 68 deletions core/continuum-dreaming/src/modules/training_trigger/on_engine.rs

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -266,11 +266,11 @@ mod held_off {
refused(&state, &key, &kept, 512 << 20).await;
let told = kept.told();
let port: Arc<dyn LearnPort> = 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();
}
Expand Down Expand Up @@ -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();
}
Expand All @@ -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<TrainingTriggerState>| 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<dyn LearnPort> = 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<TrainingTriggerState>| 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<dyn LearnPort> = 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");
}
}
34 changes: 34 additions & 0 deletions core/continuum-engine/src/inference/training_admission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,40 @@ pub fn try_training_memory(daemon: &std::sync::Arc<ResourceDaemon>, 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<ResourceDaemon>, consumer: &str, kind: ResourceKind, bytes: u64) -> Result<crate::resources::Ask, LeaseError> {
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<ResourceDaemon>, admission: Admission<'_>, stage: Carve<'_>) -> Result<Result<LeaseGuard, TrainingWait>, 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<LeaseGuard, String> {
Expand Down
23 changes: 20 additions & 3 deletions core/continuum-genome/src/genome/learner/seat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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:?}"),
}
}
}
Expand Down Expand Up @@ -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<Item = crate::inference::learning::MemoryRow>) -> Result<LeasedMemory, SeatRefusal> {
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<Item = crate::inference::learning::MemoryRow>) -> Result<LeasedMemory, SeatRefusal> {
use crate::inference::learning::MemoryRole;
let (held, rows): (Vec<_>, Vec<_>) = rows.into_iter().partition(|row| row.role == MemoryRole::SharedComputeHeld);
let mut leases = Vec::new();
Expand All @@ -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 })
Expand Down
12 changes: 2 additions & 10 deletions core/continuum-kernel/src/resources/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,17 +338,8 @@ impl ResourceDaemon {
self: &std::sync::Arc<Self>,
req: &LeaseRequest,
) -> Result<LeaseGuard, LeaseError> {
// 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 })
Expand Down Expand Up @@ -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};

Expand Down
98 changes: 98 additions & 0 deletions core/continuum-kernel/src/resources/daemon/ask.rs
Original file line number Diff line number Diff line change
@@ -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<ResourceDaemon>,
ask: ClaimId,
taken: bool,
}

impl AskTicket {
/// The lease the ask became, once the authority granted it; taken once.
pub fn granted(&mut self) -> Option<LeaseGuard> {
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<super::super::lease::ResourceKind> {
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<Self>, req: &LeaseRequest) -> Result<Ask, LeaseError> {
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<Self>, reserve: &LeaseGuard, req: &LeaseRequest) -> Result<LeaseGuard, super::super::ledger::CarveError> {
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
}
}
Loading
Loading