From e1aed1cd97292cc8ffc8e217d089d11160517607 Mon Sep 17 00:00:00 2001 From: Mlanawo MBECHEZI Date: Mon, 23 Nov 2026 13:45:29 +0200 Subject: [PATCH 1/2] Give back the memory reserved for a start that did not happen --- CHANGELOG.md | 1 + documentation/reference/manifest.md | 2 +- src/hypervisor/resources.rs | 114 +++++++++++++++++++--- src/runtime/cloud_hypervisor/lifecycle.rs | 3 +- src/runtime/containerd/lifecycle.rs | 3 +- src/runtime/docker/container.rs | 3 +- src/runtime/firecracker/lifecycle.rs | 3 +- 7 files changed, 113 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 37880af4..818434d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `GET /deployments` and `GET /deployments/{id}` returned the registry `config.password` to any token allowed to read deployments. The API no longer returns it; it reads back as `null` ### Fixed +- An instance whose image was still being pulled kept the memory admitted for it reserved: the next pass refused that very instance on its own reservation, and any other deployment needing the memory, until the pull ended or the reservation expired. A start that does not get its instance running now gives its reservation back - A config update whose request was cut short after the config was stored (a client that hung up, a server stopped) left the deployments mounting it on the old content: `live` files were not rewritten and `rollout` deployments not redeployed, and nothing caught up. The change is now recorded with the update and the scheduler finishes it - After the disk filled up during a database write, Ring failed every later write with `database is locked` until it was restarted, and lost writes it had already confirmed. Writes now resume once there is room again - Replicas started one after the other could all be admitted on the same free memory, before the first had allocated its own, and the OOM killer settled it later. Each admitted instance now reserves its memory for 60 seconds, and later admissions count those reservations diff --git a/documentation/reference/manifest.md b/documentation/reference/manifest.md index a623a8c2..a1a3cee5 100644 --- a/documentation/reference/manifest.md +++ b/documentation/reference/manifest.md @@ -374,7 +374,7 @@ resources: Both `limits` and `requests` are optional. Within each, `cpu` and `memory` are also optional. -> **Memory admission control.** Before creating a container or booting a VM, Ring checks the deployment's requested memory against the host's currently-available memory. The figure it admits against is `requests.memory` if set, otherwise `limits.memory` (and, on Cloud Hypervisor, the 256 MiB default when neither is set). If the host can't hold it, the deployment goes to `backing_off` with the reason `insufficient_resources` and an event naming the gap (`needs X MiB but only Y MiB is available`), and is checked again every few seconds since memory gets freed (a refusal is not a restart: it does not raise `restart_count` or use up `max_attempts`), instead of starting and getting OOM-killed (Docker) or failing the VM spawn opaquely (CH). Each admitted instance reserves its memory for 60 seconds, the time to actually allocate it, and later admissions subtract those reservations, so replicas started one after the other cannot all be admitted on the same free memory (`… 300 MiB reserved by instances started in the last 60s`). A deployment never holds more reservations than its `replicas`, so a crash loop does not stack them. The check is still best-effort (workloads Ring did not start are only seen once they allocate), and it is *not* applied to CPU, since CPU overcommit is non-fatal. A deployment that declares no memory request or limit is not gated. +> **Memory admission control.** Before creating a container or booting a VM, Ring checks the deployment's requested memory against the host's currently-available memory. The figure it admits against is `requests.memory` if set, otherwise `limits.memory` (and, on Cloud Hypervisor, the 256 MiB default when neither is set). If the host can't hold it, the deployment goes to `backing_off` with the reason `insufficient_resources` and an event naming the gap (`needs X MiB but only Y MiB is available`), and is checked again every few seconds since memory gets freed (a refusal is not a restart: it does not raise `restart_count` or use up `max_attempts`), instead of starting and getting OOM-killed (Docker) or failing the VM spawn opaquely (CH). Each admitted instance reserves its memory for 60 seconds, the time to actually allocate it, and later admissions subtract those reservations, so replicas started one after the other cannot all be admitted on the same free memory (`… 300 MiB reserved by instances started in the last 60s`). A deployment never holds more reservations than its `replicas`, so a crash loop does not stack them, and a start that does not get its instance running (an image still being pulled, a failed create) gives its reservation back. The check is still best-effort (workloads Ring did not start are only seen once they allocate), and it is *not* applied to CPU, since CPU overcommit is non-fatal. A deployment that declares no memory request or limit is not gated. > **Cloud Hypervisor sizing.** When `resources` is not set on a CH deployment, the VM defaults to 1 vCPU and 256 MiB of RAM. Resizing is at-boot only; Ring does not use Cloud Hypervisor's `vm.resize` API to live-resize a running VM, so changing `resources` requires a redeploy. diff --git a/src/hypervisor/resources.rs b/src/hypervisor/resources.rs index 93d1b948..fc2b8612 100644 --- a/src/hypervisor/resources.rs +++ b/src/hypervisor/resources.rs @@ -45,6 +45,9 @@ pub(crate) struct Reservations { } struct Reservation { + /// Tells this reservation apart, so the start it was made for can give it + /// back without touching the others of its deployment. + id: u64, deployment_id: String, at: Instant, bytes: i64, @@ -62,7 +65,13 @@ impl Reservations { /// has more than `replicas` instances alive, so it never holds more than /// `replicas` reservations: the oldest goes, which is what keeps a crash /// loop restarting the same instance from stacking reservations. - pub(crate) fn reserve(&mut self, now: Instant, deployment_id: &str, replicas: u32, bytes: i64) { + pub(crate) fn reserve( + &mut self, + now: Instant, + deployment_id: &str, + replicas: u32, + bytes: i64, + ) -> u64 { let held = self .entries .iter() @@ -76,11 +85,19 @@ impl Reservations { { self.entries.remove(oldest); } + let id = NEXT_RESERVATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); self.entries.push(Reservation { + id, deployment_id: deployment_id.to_string(), at: now, bytes, }); + id + } + + /// Give back reservation `id`: the start it was made for did not happen. + pub(crate) fn release(&mut self, id: u64) { + self.entries.retain(|r| r.id != id); } /// Admit `required_bytes` against `available_bytes` minus what is still @@ -91,14 +108,13 @@ impl Reservations { deployment: &Deployment, required_bytes: i64, available_bytes: i64, - ) -> Result<(), RuntimeError> { + ) -> Result { let replicas = deployment.replicas; // The oldest reservation of this deployment is about to make room for // this one when it already holds all its slots: do not count it. let reserved = self.reserved(now) - self.displaced(deployment, replicas); check_against(&deployment.name, required_bytes, available_bytes, reserved)?; - self.reserve(now, &deployment.id, replicas, required_bytes); - Ok(()) + Ok(self.reserve(now, &deployment.id, replicas, required_bytes)) } fn displaced(&self, deployment: &Deployment, replicas: u32) -> i64 { @@ -118,6 +134,40 @@ static RESERVATIONS: Mutex = Mutex::new(Reservations { entries: Vec::new(), }); +static NEXT_RESERVATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +fn ledger() -> std::sync::MutexGuard<'static, Reservations> { + // A poisoned lock only means another admission panicked mid-way; the + // ledger is still a plain list of reservations. + RESERVATIONS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The memory an admitted start reserved. Dropped without [`keep`], the start +/// did not happen (it failed, or returned while its image is pulled), and the +/// memory goes back: held for the whole reservation window, it refused the +/// next attempt of the very instance it was reserved for. +/// +/// [`keep`]: Admission::keep +#[must_use = "dropping an admission gives its memory back: call keep() once the instance started"] +pub(crate) struct Admission { + reservation: Option, +} + +impl Admission { + /// The instance started: its memory stays reserved for the window. + pub(crate) fn keep(mut self) { + self.reservation = None; + } +} + +impl Drop for Admission { + fn drop(&mut self) { + if let Some(id) = self.reservation.take() { + ledger().release(id); + } + } +} + /// The memory figure we admit against, in bytes. `requests.memory` is the /// scheduling intent ("how much this workload needs to run"), so it wins; /// `limits.memory` is the cap and is used as a fallback when no request is @@ -179,9 +229,9 @@ pub(crate) fn check_against( /// not start, but it catches the common, gross case ("asked for 8 GiB on a /// 2 GiB host") and replicas outrunning each other before any expensive image /// pull or VM boot. -pub(crate) fn check_host_memory(deployment: &Deployment) -> Result<(), RuntimeError> { +pub(crate) fn check_host_memory(deployment: &Deployment) -> Result { let Some(required) = required_memory_bytes(deployment) else { - return Ok(()); + return Ok(Admission { reservation: None }); }; let mut sys = match System::new() { @@ -191,7 +241,7 @@ pub(crate) fn check_host_memory(deployment: &Deployment) -> Result<(), RuntimeEr "skipping the host memory check for '{}': {}", deployment.name, e ); - return Ok(()); + return Ok(Admission { reservation: None }); } }; sys.refresh_memory(); @@ -199,10 +249,10 @@ pub(crate) fn check_host_memory(deployment: &Deployment) -> Result<(), RuntimeEr // matching what the kernel would actually hand out. let available = sys.available_memory() as i64; - // A poisoned lock only means another admission panicked mid-way; the - // ledger is still a plain list of reservations. - let mut reservations = RESERVATIONS.lock().unwrap_or_else(|e| e.into_inner()); - reservations.admit(Instant::now(), deployment, required, available) + let reservation = ledger().admit(Instant::now(), deployment, required, available)?; + Ok(Admission { + reservation: Some(reservation), + }) } #[cfg(test)] @@ -411,4 +461,46 @@ mod tests { .is_ok() ); } + + #[test] + fn a_released_reservation_leaves_the_others_of_its_deployment() { + let mut ledger = Reservations::default(); + let now = Instant::now(); + let first = ledger.reserve(now, "dep", 2, 100); + let second = ledger.reserve(now, "dep", 2, 50); + ledger.release(second); + assert_eq!(ledger.reserved(now), 100); + ledger.release(first); + assert_eq!(ledger.reserved(now), 0); + } + + fn held_by(deployment_id: &str) -> usize { + ledger() + .entries + .iter() + .filter(|r| r.deployment_id == deployment_id) + .count() + } + + /// A start that returns before its instance exists (an image still being + /// pulled, a failed create) gives its memory back, so the next attempt of + /// the same instance is not refused on it. + #[test] + fn an_admission_given_up_returns_its_memory_and_a_kept_one_holds_it() { + let dropped = format!("dropped-{}", uuid::Uuid::new_v4()); + let id = ledger().reserve(Instant::now(), &dropped, 1, 100); + drop(Admission { + reservation: Some(id), + }); + assert_eq!(held_by(&dropped), 0); + + let kept = format!("kept-{}", uuid::Uuid::new_v4()); + let id = ledger().reserve(Instant::now(), &kept, 1, 100); + Admission { + reservation: Some(id), + } + .keep(); + assert_eq!(held_by(&kept), 1); + ledger().entries.retain(|r| r.deployment_id != kept); + } } diff --git a/src/runtime/cloud_hypervisor/lifecycle.rs b/src/runtime/cloud_hypervisor/lifecycle.rs index 4ce31276..84ea9fe2 100644 --- a/src/runtime/cloud_hypervisor/lifecycle.rs +++ b/src/runtime/cloud_hypervisor/lifecycle.rs @@ -450,7 +450,7 @@ impl CloudHypervisorLifecycle { // reserves its whole memory at boot, so an over-ask fails the spawn with // an opaque "Cannot allocate memory". Catch it here with a clear // need/have message instead. - crate::hypervisor::resources::check_host_memory(deployment)?; + let admission = crate::hypervisor::resources::check_host_memory(deployment)?; let instance_image = self.instance_image_path(instance_id); if !instance_image.exists() { @@ -811,6 +811,7 @@ impl CloudHypervisorLifecycle { instance_id, deployment.id ); + admission.keep(); Ok(()) } diff --git a/src/runtime/containerd/lifecycle.rs b/src/runtime/containerd/lifecycle.rs index b8917e03..7806d836 100644 --- a/src/runtime/containerd/lifecycle.rs +++ b/src/runtime/containerd/lifecycle.rs @@ -477,7 +477,7 @@ impl ContainerdLifecycle { client: &containerd_client::Client, resolved_mounts: &[ResolvedMount], ) -> Result<(), RuntimeError> { - crate::hypervisor::resources::check_host_memory(deployment)?; + let admission = crate::hypervisor::resources::check_host_memory(deployment)?; let ns = &self.config.namespace; @@ -566,6 +566,7 @@ impl ContainerdLifecycle { deployment.instances.push(instance_id.clone()); info!("containerd instance {} created and started", instance_id); + admission.keep(); Ok(()) } diff --git a/src/runtime/docker/container.rs b/src/runtime/docker/container.rs index ef4b675b..f7b86f41 100644 --- a/src/runtime/docker/container.rs +++ b/src/runtime/docker/container.rs @@ -544,7 +544,7 @@ pub(crate) async fn create_container( // if the host can't hold the requested memory, the container would only get // OOM-killed at runtime (or, with no limit, take the host down with it). // Fail here with an actionable message instead. - crate::hypervisor::resources::check_host_memory(deployment)?; + let admission = crate::hypervisor::resources::check_host_memory(deployment)?; let (name, reference) = parse_image_reference(&deployment.image); @@ -758,6 +758,7 @@ pub(crate) async fn create_container( "Docker container {} created and started successfully", container_name ); + admission.keep(); Ok(()) } Err(e) => { diff --git a/src/runtime/firecracker/lifecycle.rs b/src/runtime/firecracker/lifecycle.rs index 7fbb253e..9ac7d91a 100644 --- a/src/runtime/firecracker/lifecycle.rs +++ b/src/runtime/firecracker/lifecycle.rs @@ -471,7 +471,7 @@ impl FirecrackerLifecycle { // allocation failure — and here it would do so only *after* copying a // full rootfs image. Same check Cloud Hypervisor already ran; without it // Firecracker had no memory gate at all. - crate::hypervisor::resources::check_host_memory(deployment)?; + let admission = crate::hypervisor::resources::check_host_memory(deployment)?; // Private to Ring's user: it stages the decrypted config files and the // environment handed to the guest. @@ -732,6 +732,7 @@ impl FirecrackerLifecycle { self.taps.lock().unwrap().insert(instance_id.clone(), t); } info!("Firecracker microVM {} booted (pid {})", instance_id, pid); + admission.keep(); Ok(instance_id) } From 9aee40dd520e85957d6df7bddf70a71fce68c02b Mon Sep 17 00:00:00 2001 From: Mlanawo MBECHEZI Date: Mon, 23 Nov 2026 13:45:29 +0200 Subject: [PATCH 2/2] Add an e2e checking an instance waiting on its pull reserves no memory --- ...t59_pulling_instance_reserves_no_memory.sh | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100755 tests/e2e/docker/t59_pulling_instance_reserves_no_memory.sh diff --git a/tests/e2e/docker/t59_pulling_instance_reserves_no_memory.sh b/tests/e2e/docker/t59_pulling_instance_reserves_no_memory.sh new file mode 100755 index 00000000..e6ca4480 --- /dev/null +++ b/tests/e2e/docker/t59_pulling_instance_reserves_no_memory.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# T59: an instance whose image is still being pulled holds no memory. +# +# Memory admission reserves what it admits, so that replicas started one after +# the other cannot all fit in the same free memory. The reservation was made +# before the image pull, and kept when the start returned to wait for the +# pull in the background: the next pass then refused that very instance on its +# own reservation, and any other deployment needing the memory with it. +# +# A deployment requesting 60% of the host's memory pulls from a registry that +# never answers. Another one requesting the same 60% must still start. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../lib.sh +source "$SCRIPT_DIR/../lib.sh" + +log "== T59: an instance waiting on its pull reserves no memory ==" + +command -v python3 > /dev/null || fail "python3 is needed for the fake registry" + +REGISTRY_PORT="" +for candidate in $(seq 16100 16200); do + if ! (exec 3<>"/dev/tcp/127.0.0.1/$candidate") 2>/dev/null; then + REGISTRY_PORT=$candidate + break + fi +done +[ -n "$REGISTRY_PORT" ] || fail "no free port for the fake registry" + +python3 - "$REGISTRY_PORT" <<'PY' & +import socket, sys +s = socket.socket() +s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) +s.bind(("127.0.0.1", int(sys.argv[1]))) +s.listen(64) +held = [] +while True: + conn, _ = s.accept() + held.append(conn) # accept, never answer +PY +REGISTRY_PID=$! + +cleanup_registry() { + local ec=$? + kill "$REGISTRY_PID" 2>/dev/null || true + cleanup_ring + return $ec +} +trap cleanup_registry EXIT + +start_ring +ring_login + +available_mib=$(awk '/^MemAvailable:/ { print int($2 / 1024) }' /proc/meminfo) +request_mib=$(( available_mib * 60 / 100 )) +log "host has ${available_mib} MiB available, each deployment requests ${request_mib} MiB" + +cat > "$RING_TEST_DIR/hang.yaml" < "$RING_TEST_DIR/web.yaml" < /dev/null +"$RING_BIN" apply --file "$RING_TEST_DIR/hang.yaml" > /dev/null +# A few passes: each one admits 'hang' and finds its pull still running. +sleep 5 +log "'hang' is waiting on a registry that never answers" + +"$RING_BIN" apply --file "$RING_TEST_DIR/web.yaml" > /dev/null +wait_deployment_state "ring-e2e" "web" "running" 30 +log "'web' was admitted beside the pulling instance" + +log "PASS"