Compare commits

...
Author SHA1 Message Date
grenadeandClaude Opus 5.5 8bd371824d fix(cortex): placement waits for a neuron's own startup loads
CI / Config consistency (push) Successful in 14s
CI / Classify changes (push) Successful in 23s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 16s
CI / Clippy (push) Successful in 2m57s
CI / Test (push) Successful in 6m28s
CI / CUDA type-check (push) Successful in 19m25s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
Right after a deploy restarted benjy's neuron, a HeartMuLa job
cold-loaded while the neuron was still loading its default Qwen3-8B
(36 s). That load was in no model list and its memory had barely
started to fill, so the card looked empty; both landed and the HeartMuLa
load ran out of memory.

neuron's /health already reports its activation (pending, in_progress).
Placement now counts those models' catalogue footprint as taken, and a
cold-load that does not fit while the node is still activating answers
503 + Retry-After instead of loading over it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-19 14:09:28 +03:00
grenadeandClaude Opus 5.5 f40406e49b fix(cortex): serialise cold-loads per node; never evict a busy model
CI / Config consistency (push) Successful in 12s
CI / Classify changes (push) Successful in 18s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 14s
CI / Clippy (push) Successful in 3m24s
CI / Test (push) Successful in 7m13s
CI / Build cortex SRPM (push) Canceled after 0s
CI / Build neuron SRPM (push) Canceled after 0s
CI / Publish cortex to COPR (push) Canceled after 0s
CI / Publish neuron to COPR (push) Canceled after 0s
CI / Bump version in source (push) Canceled after 0s
CI / CUDA type-check (push) Canceled after 19m15s
Two music jobs (HeartMuLa, then ACE-Step 90 s later) both cold-loaded
onto benjy's 24 GB card. Placement reads VRAM from the last /health
poll, which could not see HeartMuLa's three-minute load still in
progress, so ACE-Step "fit" without evicting anything. Both landed
(23.8 GB used, 289 MB free) and every render on the card then failed
with CUDA_ERROR_OUT_OF_MEMORY.

- A per-node lock now covers each cold-load's evict -> load -> fresh
  /health. A request that waited re-checks inside the lock: if its model
  is now loaded it routes there; otherwise fit is decided from a fresh
  /health, refreshed again after each eviction.
- The evictor (and placement's evictable estimate) skip models with
  requests running or queued, and models cortex cold-loaded in the last
  30 s for a request that has not reached them yet. Evicting either
  kills work in progress.
- When a model still does not fit only because a model it would
  displace is busy, routing answers 503 + Retry-After (10 s) instead of
  loading into an out-of-memory. Audio jobs treat that as busy and wait
  without spending an attempt.

tests/cold_load.rs drives a mock neuron that keeps VRAM books for one
card and flags over-commit; removing the lock, the eviction guard or the
deferral each fails it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-19 13:49:51 +03:00
grenade 6535efc51f Merge branch 'feat/audio-disk-guard': refuse audio jobs when the store is low on disk
build-prerelease / Resolve version stamps + change detection (push) Successful in 20s
build-prerelease / Build helexa-bench binary (push) Successful in 2m31s
build-prerelease / Build helexa-upstream binary (push) Successful in 2m49s
build-prerelease / Build neuron-ada (push) Successful in 3m0s
build-prerelease / Build cortex binary (push) Successful in 3m5s
build-prerelease / Package helexa-bench RPM (push) Successful in 31s
build-prerelease / Package helexa-upstream RPM (push) Successful in 29s
build-prerelease / Build helexa-angels binary (push) Successful in 3m36s
build-prerelease / Lint (fmt + clippy) (push) Successful in 3m50s
build-prerelease / Package cortex RPM (push) Successful in 35s
build-prerelease / Package helexa-angels RPM (push) Successful in 27s
build-prerelease / Build helexa-tools binary (push) Successful in 1m47s
build-prerelease / Build helexa-router binary (push) Successful in 1m56s
build-prerelease / Package helexa-tools RPM (push) Successful in 21s
build-prerelease / Package helexa-router RPM (push) Successful in 20s
build-prerelease / Build neuron-blackwell (push) Successful in 16m33s
build-prerelease / Test (push) Successful in 18m17s
build-prerelease / Build neuron-ampere (push) Successful in 21m31s
build-prerelease / Package helexa-neuron-ada RPM (push) Successful in 1m17s
build-prerelease / Package helexa-neuron-ampere RPM (push) Successful in 3m59s
build-prerelease / Package helexa-neuron-blackwell RPM (push) Successful in 4m9s
build-prerelease / Publish to rpm.lair.cafe (unstable) (push) Successful in 35s
2026-10-19 13:37:02 +03:00
grenade 231c4b3991 Merge branch 'fix/music-hide-stale-on-compose': clear earlier songs when composing
build-prerelease / Resolve version stamps + change detection (push) Successful in 19s
build-prerelease / Lint (fmt + clippy) (push) Skipped
build-prerelease / Test (push) Skipped
build-prerelease / Build cortex binary (push) Skipped
build-prerelease / Build helexa-bench binary (push) Skipped
build-prerelease / Build helexa-upstream binary (push) Skipped
build-prerelease / Build helexa-angels binary (push) Skipped
build-prerelease / Build helexa-router binary (push) Skipped
build-prerelease / Build helexa-tools binary (push) Skipped
build-prerelease / Build neuron-blackwell (push) Skipped
build-prerelease / Build neuron-ampere (push) Skipped
build-prerelease / Build neuron-ada (push) Skipped
build-prerelease / Package cortex RPM (push) Skipped
build-prerelease / Package helexa-bench RPM (push) Skipped
build-prerelease / Package helexa-upstream RPM (push) Skipped
build-prerelease / Package helexa-angels RPM (push) Skipped
build-prerelease / Package helexa-router RPM (push) Skipped
build-prerelease / Package helexa-tools RPM (push) Skipped
build-prerelease / Package helexa-neuron-ada RPM (push) Skipped
build-prerelease / Package helexa-neuron-ampere RPM (push) Skipped
build-prerelease / Package helexa-neuron-blackwell RPM (push) Skipped
build-prerelease / Publish to rpm.lair.cafe (unstable) (push) Skipped
2026-10-19 13:23:35 +03:00
grenadeandClaude Opus 5.5 1f96bf1d16 feat(cortex): refuse audio jobs when the job store is low on disk
CI / Config consistency (push) Successful in 10s
CI / Classify changes (push) Successful in 17s
CI / Web (lint + typecheck + i18n + build) (push) Skipped
CI / Format (push) Successful in 13s
CI / Clippy (push) Successful in 2m56s
CI / Test (push) Successful in 6m18s
CI / CUDA type-check (push) Successful in 19m39s
CI / Build cortex SRPM (push) Skipped
CI / Build neuron SRPM (push) Skipped
CI / Publish cortex to COPR (push) Skipped
CI / Publish neuron to COPR (push) Skipped
CI / Bump version in source (push) Skipped
Rendered audio is written to [audio_jobs] dir, which on the gateway host
is the root filesystem. A store that filled it would take cortex and the
OS down with it. Submissions are now refused with 503
audio_storage_full and Retry-After: 600 (about one sweep interval) while
that filesystem has less than min_free_mb free (default 10 GiB, 0
disables). The check runs before any budget is reserved, so a refusal
costs the caller nothing; jobs already accepted still finish.

An interim guard: shared object storage for a large fleet is #411.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017ohK2pULMVJctL5B1Gixdp
2026-10-19 13:16:13 +03:00
12 changed files with 621 additions and 36 deletions
+3 -1
View File
@@ -1274,7 +1274,9 @@ stored as that lossless master. MP3 (320 kbps CBR, LAME) is a download
format only: `/content?format=mp3` transcodes the FLAC once and caches
`{id}.mp3` beside it until the job expires; `response_format` sets a
job's default download. Results stored as WAV by older neurons are
served as WAV.
served as WAV. cortex refuses new jobs (503 `audio_storage_full`) while the job
directory's filesystem has under `[audio_jobs] min_free_mb` free (10 GiB
default); shared object storage for the Pascal-scale fleet is #411.
**Metering: per audio-second**, at a per-model rate stored in
helexa-upstream's `model_rates` table (`GET /authz/v1/rates`, cached by
Generated
+1
View File
@@ -875,6 +875,7 @@ dependencies = [
"metrics-exporter-prometheus",
"mp3lame-encoder",
"reqwest",
"rustix",
"serde",
"serde_json",
"tempfile",
+3
View File
@@ -129,3 +129,6 @@ enabled = false
# max_attempts = 2
# How long a job may wait on a busy model before failing, in seconds.
# queue_timeout_secs = 3600
# New jobs are refused (503) while the job directory's filesystem has less
# than this much free space, in MiB. 0 disables the check.
# min_free_mb = 10240
+12
View File
@@ -57,6 +57,12 @@ pub struct AudioJobsConfig {
/// How long a job may wait for a busy model before it fails, in seconds.
#[serde(default = "default_audio_queue_timeout")]
pub queue_timeout_secs: u64,
/// New jobs are refused (503 + `Retry-After`) while the filesystem
/// holding `dir` has less than this much free space, in MiB. Rendered
/// audio is written there, so this keeps a busy store from filling the
/// disk it shares. 0 disables the check.
#[serde(default = "default_audio_min_free_mb")]
pub min_free_mb: u64,
}
impl Default for AudioJobsConfig {
@@ -67,6 +73,7 @@ impl Default for AudioJobsConfig {
max_concurrent: default_audio_max_concurrent(),
max_attempts: default_audio_max_attempts(),
queue_timeout_secs: default_audio_queue_timeout(),
min_free_mb: default_audio_min_free_mb(),
}
}
}
@@ -86,6 +93,11 @@ fn default_audio_max_attempts() -> u32 {
fn default_audio_queue_timeout() -> u64 {
3600
}
/// 10 GiB: room for well over a hundred of the longest songs while jobs
/// already accepted finish.
fn default_audio_min_free_mb() -> u64 {
10 * 1024
}
/// `[upstream]` — the helexa-upstream authority client (#57). Locally
/// unrecognised bearer keys are resolved against `url`'s `/authz/v1` surface
+1
View File
@@ -28,6 +28,7 @@ bytes = "1"
urlencoding = "2"
url = "2"
uuid = { version = "1", features = ["v4"] }
rustix = { version = "1", default-features = false, features = ["std", "fs"] }
claxon = "0.4.3"
mp3lame-encoder = { version = "0.2.5", features = ["std"] }
+47
View File
@@ -55,6 +55,10 @@ const DEFAULT_BUSY_WAIT: Duration = Duration::from_secs(5);
/// How often expired jobs are swept.
const SWEEP_INTERVAL: Duration = Duration::from_secs(600);
/// `Retry-After` on a submission refused for lack of disk space: about as
/// long as it takes the sweep to come round and expire old jobs.
const STORAGE_RETRY_AFTER_SECS: u64 = 600;
/// A job as cortex stores it: the public object plus what is needed to run
/// (or re-run) it.
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -126,6 +130,30 @@ impl AudioJobs {
.as_ref()
}
/// Free space on the filesystem holding the job directory, in MiB.
/// `None` when there is no directory (memory only) or it cannot be
/// read, in which case submissions are not refused on its account.
fn free_mb(&self) -> Option<u64> {
let dir = self.dir()?;
match rustix::fs::statvfs(dir) {
Ok(st) => Some(st.f_bavail.saturating_mul(st.f_frsize) / (1024 * 1024)),
Err(e) => {
tracing::warn!(dir = %dir.display(), error = %e, "cannot read free space for audio jobs");
None
}
}
}
/// Whether a new job may be accepted: the store's filesystem must keep
/// at least `min_free_mb` free. Returns the free space when it may not.
fn storage_full(&self) -> Option<u64> {
let floor = self.config.min_free_mb;
if floor == 0 {
return None;
}
self.free_mb().filter(|free| *free < floor)
}
fn record_path(&self, id: &str) -> Option<PathBuf> {
self.dir().map(|d| d.join(format!("{id}.json")))
}
@@ -342,6 +370,25 @@ async fn submit(
return invalid_params(msg);
}
// Refused before any budget is reserved: nothing to release.
if let Some(free) = fleet.audio_jobs.storage_full() {
metrics::counter!("cortex_audio_jobs_rejected_total", "reason" => "storage").increment(1);
tracing::warn!(
free_mb = free,
min_free_mb = fleet.audio_jobs.config.min_free_mb,
"audio job refused: job store is low on disk space"
);
return crate::error::envelope_response(
OpenAiError::new(
503,
"server_error",
"audio_storage_full",
"audio generation is temporarily unavailable: the job store is full",
)
.with_retry_after(STORAGE_RETRY_AFTER_SECS),
);
}
let owner = crate::metering::principal_from_headers(&headers);
let mut request = request;
request.model = model.clone();
+1
View File
@@ -46,6 +46,7 @@ pub async fn evict_lru_on_node(
.models
.values()
.filter(|m| m.status == ModelStatus::Loaded)
.filter(|m| !fleet.eviction_blocked(node, &m.id))
.filter(|m| match incoming {
Some(inc) => fleet.catalogue.may_displace(inc, &m.id),
None => {
+1 -1
View File
@@ -310,7 +310,7 @@ async fn discover_capabilities(fleet: &CortexState, name: &str, endpoint: &str)
/// Fetch `/health` and stash the activation snapshot on NodeState.
/// Decoupled from the /models poll so a /health glitch doesn't mark
/// the neuron unhealthy or evict the model list.
async fn poll_health(fleet: &CortexState, name: &str, endpoint: &str) {
pub async fn poll_health(fleet: &CortexState, name: &str, endpoint: &str) {
let url = format!("{endpoint}/health");
let resp = match fleet
.http_client
+140 -34
View File
@@ -64,6 +64,10 @@ pub enum RouteError {
"model '{model_id}' is recovering on node '{node}' (device context rebuild in progress) — retry shortly"
)]
ModelRecovering { model_id: String, node: String },
#[error(
"model '{model_id}' does not fit on '{node}' until a model there finishes its work — retry shortly"
)]
NodeBusy { model_id: String, node: String },
}
impl RouteError {
@@ -74,7 +78,8 @@ impl RouteError {
match self {
RouteError::NoHealthyNodes
| RouteError::ModelRecovering { .. }
| RouteError::FeasibleNodeUnhealthy { .. } => 503,
| RouteError::FeasibleNodeUnhealthy { .. }
| RouteError::NodeBusy { .. } => 503,
_ => 404,
}
}
@@ -88,7 +93,8 @@ impl RouteError {
| RouteError::NoFeasibleNeuron { .. }
| RouteError::ColdLoadFailed { .. }
| RouteError::ModelRecovering { .. }
| RouteError::FeasibleNodeUnhealthy { .. } => "api_error",
| RouteError::FeasibleNodeUnhealthy { .. }
| RouteError::NodeBusy { .. } => "api_error",
}
}
@@ -102,6 +108,7 @@ impl RouteError {
RouteError::ColdLoadFailed { .. } => "service_unavailable",
RouteError::ModelRecovering { .. } => "service_unavailable",
RouteError::FeasibleNodeUnhealthy { .. } => "service_unavailable",
RouteError::NodeBusy { .. } => "service_unavailable",
}
}
@@ -115,6 +122,8 @@ impl RouteError {
RouteError::ModelRecovering { .. } => Some(2),
RouteError::FeasibleNodeUnhealthy { .. } => Some(3),
RouteError::NoHealthyNodes => Some(5),
// Clears when the resident model's requests finish.
RouteError::NodeBusy { .. } => Some(10),
_ => None,
}
}
@@ -205,11 +214,10 @@ pub async fn resolve(
// Loading is gateway-synthesised from neuron's
// activation snapshot; it never appears on the
// wire from neuron's `/models`. Skip — the model
// isn't actually servable yet. The pre-existing
// race (catalogue cold_load fires a parallel
// /models/load against the in-flight load) is no
// worse than before; fixing it needs neuron-side
// in-flight tracking on /models/load itself.
// isn't actually servable yet. Cortex's own
// cold-loads are serialised per node (priority 4);
// a load neuron started by itself at activation is
// still invisible to that lock.
ModelStatus::Loading => {}
}
}
@@ -247,41 +255,109 @@ pub async fn resolve(
// Priority 4: catalogue × topology cold-load.
if let Some(profile) = fleet.catalogue.get(model_id) {
let (node_name, neuron_endpoint, fits_free) = pick_feasible_neuron(fleet, profile).await?;
// Cold-swap (#203): when the chosen node's devices don't have the
// free VRAM *right now*, evict unpinned LRU models there until
// the profile fits (bounded — a node whose evictable set can't
// free enough was ranked below one that can).
if !fits_free {
for _ in 0..3 {
match crate::evictor::evict_lru_on_node(fleet, &node_name, Some(&profile.id)).await
{
Ok(Some(evicted)) => {
tracing::info!(
model = %profile.id,
node = %node_name,
evicted = %evicted,
"cold-swap: evicted LRU model to make room"
);
if node_fits_free(fleet, &node_name, profile).await {
break;
}
}
Ok(None) => break,
Err(e) => {
tracing::warn!(node = %node_name, error = %e, "cold-swap eviction failed");
break;
}
let (node_name, neuron_endpoint, _) = pick_feasible_neuron(fleet, profile).await?;
// One cold-load per node at a time. The choice above rests on the
// last poll's VRAM, which cannot see a load in progress, so every
// decision that follows is re-made inside the lock from a fresh
// `/health`.
let lock = fleet.cold_load_lock(&node_name);
let _turn = lock.lock().await;
// Whoever held the lock may have been loading this very model.
if let Some((node, endpoint)) = loaded_location(fleet, model_id).await {
return finish(fleet, &node, &endpoint, model_id, false).await;
}
crate::poller::poll_health(fleet, &node_name, &neuron_endpoint).await;
// Cold-swap (#203): when the node's devices don't have the free
// VRAM right now, evict unpinned LRU models there until the
// profile fits (bounded — a node whose evictable set can't free
// enough was ranked below one that can).
for _ in 0..3 {
if node_fits_free(fleet, &node_name, profile).await {
break;
}
match crate::evictor::evict_lru_on_node(fleet, &node_name, Some(&profile.id)).await {
Ok(Some(evicted)) => {
tracing::info!(
model = %profile.id,
node = %node_name,
evicted = %evicted,
"cold-swap: evicted LRU model to make room"
);
crate::poller::poll_health(fleet, &node_name, &neuron_endpoint).await;
}
Ok(None) => break,
Err(e) => {
tracing::warn!(node = %node_name, error = %e, "cold-swap eviction failed");
break;
}
}
}
// Still short, and a model that would otherwise be displaced is
// busy: loading now would land beside it and fail out of memory.
// Answer "retry shortly" instead; the room appears when its work
// ends.
if !node_fits_free(fleet, &node_name, profile).await
&& blocked_displaceable(fleet, &node_name, profile).await
{
tracing::info!(
model = %profile.id,
node = %node_name,
"cold-load deferred: the model it would displace is busy"
);
return Err(RouteError::NodeBusy {
model_id: profile.id.clone(),
node: node_name,
});
}
cold_load(fleet, &node_name, &neuron_endpoint, profile).await?;
fleet.note_cold_load(&node_name, &profile.id);
// The next cold-load in line decides from these readings.
crate::poller::poll_health(fleet, &node_name, &neuron_endpoint).await;
drop(_turn);
return finish(fleet, &node_name, &neuron_endpoint, model_id, true).await;
}
Err(RouteError::ModelNotFound(model_id.to_string()))
}
/// A healthy node where `model_id` is loaded and servable, if any.
async fn loaded_location(fleet: &Arc<CortexState>, model_id: &str) -> Option<(String, String)> {
let nodes = fleet.nodes.read().await;
nodes
.values()
.filter(|n| n.healthy)
.find(|n| {
n.models.get(model_id).is_some_and(|m| {
matches!(m.status, ModelStatus::Loaded | ModelStatus::Reloading) && m.is_servable()
})
})
.map(|n| (n.name.clone(), n.endpoint.clone()))
}
/// Whether `node_name` holds a model the profile may displace but that
/// cannot be evicted right now because it is busy (see
/// [`CortexState::eviction_blocked`]), or is still loading its startup
/// models.
async fn blocked_displaceable(
fleet: &Arc<CortexState>,
node_name: &str,
profile: &ModelProfile,
) -> bool {
let nodes = fleet.nodes.read().await;
nodes.get(node_name).is_some_and(|node| {
// A startup load cannot be evicted until it finishes, and its
// memory is still arriving: wait for it.
activating(node)
|| node.models.values().any(|m| {
m.status == ModelStatus::Loaded
&& fleet.catalogue.may_displace(&profile.id, &m.id)
&& fleet.eviction_blocked(node, &m.id)
})
})
}
/// True when `node_name`'s live device readings show enough free VRAM
/// on some device for the profile. Conservative: unknown health (no
/// /health poll yet) counts as not-fitting so the ranking prefers
@@ -289,12 +365,40 @@ pub async fn resolve(
async fn node_fits_free(fleet: &Arc<CortexState>, node_name: &str, profile: &ModelProfile) -> bool {
let nodes = fleet.nodes.read().await;
nodes.get(node_name).is_some_and(|node| {
let reserved = activation_reserved_mb(fleet, node);
node.device_health
.iter()
.any(|d| d.vram_free_mb >= profile.vram_mb.unwrap_or(0))
.any(|d| d.vram_free_mb.saturating_sub(reserved) >= profile.vram_mb.unwrap_or(0))
})
}
/// VRAM promised to models the neuron is loading on its own at startup
/// (its `default_models`), by their catalogue footprint. Those loads are
/// not in the neuron's model list until they finish and their memory
/// fills in gradually, so free VRAM alone overstates what is available.
fn activation_reserved_mb(fleet: &CortexState, node: &cortex_core::node::NodeState) -> u64 {
node.activation.as_ref().map_or(0, |a| {
a.in_progress
.iter()
.chain(a.pending.iter())
.filter(|id| {
!node
.models
.get(id.as_str())
.is_some_and(|m| m.status == ModelStatus::Loaded)
})
.filter_map(|id| fleet.catalogue.get(id).and_then(|p| p.vram_mb))
.sum()
})
}
/// Whether the neuron is still loading its startup models.
fn activating(node: &cortex_core::node::NodeState) -> bool {
node.activation
.as_ref()
.is_some_and(|a| a.in_progress.is_some() || !a.pending.is_empty())
}
/// Pick a healthy neuron whose discovered topology satisfies the
/// profile. Preference order (#203):
/// 1. A neuron from `profile.pinned_on` that is healthy + feasible.
@@ -332,7 +436,8 @@ async fn pick_feasible_neuron(
.iter()
.map(|d| d.vram_free_mb)
.max()
.unwrap_or(0);
.unwrap_or(0)
.saturating_sub(activation_reserved_mb(fleet, node));
let need = profile.vram_mb.unwrap_or(0);
let fits_free = max_free >= need;
// Evictable estimate: free + the VRAM of loaded models this
@@ -344,6 +449,7 @@ async fn pick_feasible_neuron(
.values()
.filter(|m| {
matches!(m.status, cortex_core::node::ModelStatus::Loaded)
&& !fleet.eviction_blocked(node, &m.id)
&& fleet.catalogue.may_displace(&profile.id, &m.id)
})
// neuron reports vram_used_mb: null today; fall back to the
+61
View File
@@ -57,8 +57,22 @@ pub struct CortexState {
/// Per-model rates for non-token units (#386), from upstream when it
/// is enabled, else the local default.
pub rates: Arc<crate::rates::Rates>,
/// One lock per node, held across a cold-load's evict → load → fresh
/// `/health` sequence. Placement reads VRAM from the last poll, which
/// cannot see a load still in progress; two cold-loads deciding at
/// once both saw the same free card and loaded side by side into an
/// out-of-memory.
cold_load_locks: std::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
/// When cortex last cold-loaded each `(node, model)`. A model loaded
/// for a request is protected from eviction for [`COLD_LOAD_GRACE`],
/// long enough for that request to reach it; otherwise the next
/// cold-load in line evicts it before it has served anything.
recent_cold_loads: std::sync::Mutex<HashMap<(String, String), std::time::Instant>>,
}
/// How long a freshly cold-loaded model is protected from eviction.
pub const COLD_LOAD_GRACE: std::time::Duration = std::time::Duration::from_secs(30);
impl CortexState {
pub fn from_config(config: &GatewayConfig) -> Self {
let mut nodes = HashMap::new();
@@ -142,6 +156,53 @@ impl CortexState {
} else {
crate::rates::Rates::local()
}),
cold_load_locks: std::sync::Mutex::new(HashMap::new()),
recent_cold_loads: std::sync::Mutex::new(HashMap::new()),
}
}
/// The lock that serialises cold-loads on `node`.
pub fn cold_load_lock(&self, node: &str) -> Arc<tokio::sync::Mutex<()>> {
let mut locks = self
.cold_load_locks
.lock()
.unwrap_or_else(|e| e.into_inner());
Arc::clone(locks.entry(node.to_string()).or_default())
}
/// Record that cortex has just cold-loaded `model` on `node`.
pub fn note_cold_load(&self, node: &str, model: &str) {
let mut recent = self
.recent_cold_loads
.lock()
.unwrap_or_else(|e| e.into_inner());
recent.retain(|_, at| at.elapsed() < COLD_LOAD_GRACE);
recent.insert(
(node.to_string(), model.to_string()),
std::time::Instant::now(),
);
}
/// Whether `model` on `node` is inside its post-cold-load grace.
pub fn recently_cold_loaded(&self, node: &str, model: &str) -> bool {
let recent = self
.recent_cold_loads
.lock()
.unwrap_or_else(|e| e.into_inner());
recent
.get(&(node.to_string(), model.to_string()))
.is_some_and(|at| at.elapsed() < COLD_LOAD_GRACE)
}
/// Whether a resident model must not be evicted right now: it has
/// requests running or queued (as of the last `/health`), or cortex
/// cold-loaded it moments ago for a request that has yet to arrive.
/// Evicting either kills work in progress.
pub fn eviction_blocked(&self, node: &cortex_core::node::NodeState, model: &str) -> bool {
let busy = node
.model_load
.get(model)
.is_some_and(|l| l.in_flight + l.queue_depth > 0);
busy || self.recently_cold_loaded(&node.name, model)
}
}
+43
View File
@@ -202,6 +202,9 @@ fn config(neuron: &str, dir: &std::path::Path) -> GatewayConfig {
audio_jobs: AudioJobsConfig {
dir: dir.to_string_lossy().into_owned(),
queue_timeout_secs: 20,
// The free-space floor is tested on its own below; elsewhere it
// must not make results depend on the build host's disk.
min_free_mb: 0,
..Default::default()
},
}
@@ -741,6 +744,46 @@ async fn expired_jobs_are_swept() {
assert!(!dir.path().join(format!("{id}.mp3")).exists());
}
#[tokio::test]
async fn submissions_are_refused_when_the_store_is_low_on_disk() {
let mock = spawn_mock(Mode::Ok).await;
let rates = [("*", 1000)];
// A floor no filesystem can meet: refused, retryable, nothing written,
// nothing reserved.
let dir = tempfile::tempdir().unwrap();
let mut cfg = config(&mock.url, dir.path());
cfg.audio_jobs.min_free_mb = u64::MAX;
for k in &mut cfg.entitlements.keys {
k.hard_cap = Some(1_000_000);
}
let fleet = Arc::new(CortexState::from_config(&cfg));
let mut table = cortex_gateway::rates::RateTable::default();
for (model, rate) in rates {
table.set(cortex_gateway::rates::AUDIO_SECOND, model, rate);
}
fleet.rates.replace(table).await;
seed_model(&fleet).await;
let gw = serve(&fleet).await;
let resp = submit(&gw, Some("key-alice"), song()).await;
assert_eq!(resp.status(), 503);
assert_eq!(resp.headers()["retry-after"], "600");
let body: Value = resp.json().await.unwrap();
assert_eq!(body["error"]["code"], "audio_storage_full");
assert_eq!(spent(&fleet, "alice").await, 0);
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
// A floor any filesystem meets: accepted.
let dir = tempfile::tempdir().unwrap();
let mut cfg = config(&mock.url, dir.path());
cfg.audio_jobs.min_free_mb = 1;
let fleet = Arc::new(CortexState::from_config(&cfg));
seed_model(&fleet).await;
let gw = serve(&fleet).await;
assert_eq!(submit(&gw, None, song()).await.status(), 202);
}
// ── Per-model rates (#386) ───────────────────────────────────────────
/// A gateway whose keys are capped at `cap` tokens and whose audio rate
+308
View File
@@ -0,0 +1,308 @@
//! Cold-load placement under concurrency.
//!
//! The mock neuron keeps real VRAM books for one 24 GB card: loads take
//! time, `/health` reports what is actually resident, and the card notes
//! if it is ever asked to hold more than it has. That last flag is the
//! failure being guarded against — two cold-loads deciding from the same
//! stale poll, both landing, and every request on the card then failing
//! out of memory.
use axum::extract::{Path, State};
use axum::routing::{get, post};
use axum::{Json, Router};
use cortex_core::config::{
EvictionSettings, EvictionStrategy, GatewayConfig, GatewaySettings, NeuronEndpoint,
};
use cortex_core::discovery::{DeviceInfo, DiscoveryResponse};
use cortex_core::node::{ModelEntry, ModelStatus};
use cortex_gateway::router::RouteError;
use cortex_gateway::state::CortexState;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
const CARD_MB: u64 = 24_000;
const CATALOGUE: &str = r#"
[[models]]
id = "music-a"
harness = "candle"
vram_mb = 14000
[[models]]
id = "music-b"
harness = "candle"
vram_mb = 12000
"#;
#[derive(Default)]
struct Card {
resident: HashMap<String, u64>,
in_flight: HashMap<String, usize>,
overcommitted: bool,
unloads: Vec<String>,
/// A model the neuron is loading by itself at startup: not resident
/// yet, its memory not yet showing.
activating: Option<String>,
loads: Vec<String>,
}
fn footprint(model: &str) -> u64 {
match model {
"music-a" => 14_000,
"music-b" => 12_000,
_ => 1_000,
}
}
async fn spawn_neuron(card: Arc<Mutex<Card>>) -> String {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let inference = url.clone();
let app = Router::new()
.route(
"/models/load",
post(
|State(card): State<Arc<Mutex<Card>>>, Json(spec): Json<Value>| async move {
let id = spec["model_id"].as_str().unwrap().to_string();
// A load takes a while: long enough for a second
// request to decide while this one is in progress.
tokio::time::sleep(Duration::from_millis(300)).await;
let mut card = card.lock().unwrap();
card.loads.push(id.clone());
card.resident.insert(id.clone(), footprint(&id));
if card.resident.values().sum::<u64>() > CARD_MB {
card.overcommitted = true;
}
Json(json!({"status": "loaded"}))
},
),
)
.route(
"/models/unload",
post(
|State(card): State<Arc<Mutex<Card>>>, Json(body): Json<Value>| async move {
let id = body["model_id"].as_str().unwrap().to_string();
let mut card = card.lock().unwrap();
card.resident.remove(&id);
card.unloads.push(id);
Json(json!({"status": "unloaded"}))
},
),
)
.route(
"/health",
get(|State(card): State<Arc<Mutex<Card>>>| async move {
let card = card.lock().unwrap();
let used: u64 = card.resident.values().sum();
let models: Vec<Value> = card
.resident
.keys()
.map(|id| {
json!({
"id": id,
"in_flight": card.in_flight.get(id).copied().unwrap_or(0),
"queue_depth": 0
})
})
.collect();
let activation = match &card.activating {
Some(id) => json!({"state": "pre_warming", "in_progress": id}),
None => json!({"state": "ready"}),
};
Json(json!({
"uptime_secs": 1,
"activation": activation,
"devices": [{
"index": 0,
"vram_used_mb": used,
"vram_free_mb": CARD_MB.saturating_sub(used),
"utilization_pct": 0,
"temp_c": 40
}],
"models": models
}))
}),
)
.route(
"/models/{id}/endpoint",
get(move |Path(_id): Path<String>| {
let url = inference.clone();
async move { Json(json!({"url": url})) }
}),
)
.with_state(card);
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
url
}
/// A gateway with one healthy 24 GB node, its first `/health` already in.
async fn gateway(neuron: &str, tag: &str) -> Arc<CortexState> {
let path = std::env::temp_dir().join(format!("cortex-cold-load-{tag}.toml"));
std::fs::write(&path, CATALOGUE).unwrap();
let config = GatewayConfig {
gateway: GatewaySettings {
listen: "127.0.0.1:0".into(),
metrics_listen: "127.0.0.1:0".into(),
},
eviction: EvictionSettings {
strategy: EvictionStrategy::Lru,
defrag_after_cycles: 0,
},
neurons: vec![NeuronEndpoint {
name: "gpu".into(),
endpoint: neuron.to_string(),
}],
models_config: path.to_string_lossy().into_owned(),
entitlements: Default::default(),
upstream: Default::default(),
audio_jobs: Default::default(),
};
let fleet = Arc::new(CortexState::from_config(&config));
{
let mut nodes = fleet.nodes.write().await;
let node = nodes.get_mut("gpu").unwrap();
node.healthy = true;
node.discovery = Some(DiscoveryResponse {
hostname: "gpu".into(),
os: "linux".into(),
kernel: "6".into(),
cuda_version: None,
driver_version: None,
devices: vec![DeviceInfo {
index: 0,
name: "RTX 4090".into(),
vram_total_mb: CARD_MB,
compute_capability: "8.9".into(),
}],
harnesses: vec!["candle".into()],
cuda_unavailable_reason: None,
max_prompt_tokens: 0,
});
}
cortex_gateway::poller::poll_health(&fleet, "gpu", neuron).await;
fleet
}
/// Mark `id` resident in the mock and in cortex's view, last used long
/// ago — as the poller would have seen it, not as a fresh cold-load.
async fn seed_resident(fleet: &CortexState, card: &Mutex<Card>, neuron: &str, id: &str) {
card.lock()
.unwrap()
.resident
.insert(id.into(), footprint(id));
{
let mut nodes = fleet.nodes.write().await;
nodes.get_mut("gpu").unwrap().models.insert(
id.into(),
ModelEntry {
id: id.into(),
status: ModelStatus::Loaded,
last_accessed: Some(chrono::Utc::now() - chrono::Duration::minutes(10)),
vram_estimate_mb: Some(footprint(id)),
capabilities: Vec::new(),
tool_call: false,
reasoning: false,
limit: None,
servable: None,
reasoning_budget: Vec::new(),
},
);
}
cortex_gateway::poller::poll_health(fleet, "gpu", neuron).await;
}
#[tokio::test]
async fn concurrent_cold_loads_never_overcommit_the_card() {
let card = Arc::new(Mutex::new(Card::default()));
let neuron = spawn_neuron(Arc::clone(&card)).await;
let fleet = gateway(&neuron, "concurrent").await;
// Both decide while the card is empty; together they do not fit.
let (a, b) = tokio::join!(cortex_gateway::router::resolve(&fleet, "music-a"), async {
tokio::time::sleep(Duration::from_millis(50)).await;
cortex_gateway::router::resolve(&fleet, "music-b").await
});
let card = card.lock().unwrap();
assert!(!card.overcommitted, "both models were resident at once");
assert!(a.is_ok(), "{a:?}");
// music-a was cold-loaded for a request that has yet to reach it, so
// music-b may not take its place yet: retry shortly, not a failure.
match b {
Err(e @ RouteError::NodeBusy { .. }) => {
assert_eq!(e.http_status(), 503);
assert!(e.retry_after_secs().is_some());
}
other => panic!("expected NodeBusy, got {other:?}"),
}
assert_eq!(card.resident.keys().collect::<Vec<_>>(), ["music-a"]);
assert!(card.unloads.is_empty());
}
#[tokio::test]
async fn a_model_with_requests_in_flight_is_not_evicted() {
let card = Arc::new(Mutex::new(Card::default()));
let neuron = spawn_neuron(Arc::clone(&card)).await;
let fleet = gateway(&neuron, "in-flight").await;
card.lock().unwrap().in_flight.insert("music-a".into(), 1);
seed_resident(&fleet, &card, &neuron, "music-a").await;
let b = cortex_gateway::router::resolve(&fleet, "music-b").await;
assert!(matches!(b, Err(RouteError::NodeBusy { .. })), "{b:?}");
let card = card.lock().unwrap();
assert!(card.unloads.is_empty(), "evicted a busy model");
assert!(!card.overcommitted);
}
#[tokio::test]
async fn an_idle_model_is_swapped_out() {
let card = Arc::new(Mutex::new(Card::default()));
let neuron = spawn_neuron(Arc::clone(&card)).await;
let fleet = gateway(&neuron, "idle").await;
seed_resident(&fleet, &card, &neuron, "music-a").await;
let b = cortex_gateway::router::resolve(&fleet, "music-b").await;
assert!(b.is_ok(), "{b:?}");
let card = card.lock().unwrap();
assert_eq!(card.unloads, ["music-a"]);
assert_eq!(card.resident.keys().collect::<Vec<_>>(), ["music-b"]);
assert!(!card.overcommitted);
}
#[tokio::test]
async fn a_cold_load_waits_for_the_neuron_s_own_startup_load() {
// The neuron has just restarted and is loading its default model.
// That load is in no model list yet and its memory has barely
// started to fill, so the card still looks empty.
let card = Arc::new(Mutex::new(Card {
activating: Some("music-a".into()),
..Default::default()
}));
let neuron = spawn_neuron(Arc::clone(&card)).await;
let fleet = gateway(&neuron, "activating").await;
let b = cortex_gateway::router::resolve(&fleet, "music-b").await;
assert!(matches!(b, Err(RouteError::NodeBusy { .. })), "{b:?}");
assert!(
card.lock().unwrap().loads.is_empty(),
"loaded over a startup load"
);
// Once the startup load finishes and its model is idle, the swap
// goes ahead as usual.
{
let mut c = card.lock().unwrap();
c.activating = None;
}
seed_resident(&fleet, &card, &neuron, "music-a").await;
let b = cortex_gateway::router::resolve(&fleet, "music-b").await;
assert!(b.is_ok(), "{b:?}");
let card = card.lock().unwrap();
assert_eq!(card.unloads, ["music-a"]);
assert!(!card.overcommitted);
}