Skip to content
12 changes: 12 additions & 0 deletions config/default.toml
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,18 @@ auto_evict_interval_ms = 1000
default_sandbox_timeout_secs = 15
# Minimum auto-resumed lifetime in seconds (300 = 5 minutes).
auto_resume_min_sandbox_timeout_secs = 300
# Maximum number of pause operations that may run concurrently on this node,
# shared by TTL auto-eviction and explicit pause requests. Pause snapshots are
# dense (~1x guest RAM), so a same-second expiry cohort can saturate node write
# bandwidth; a small cap (measured: 2, or 8 with staggered TTLs) keeps cohort
# p95 near the intrinsic per-pause cost. 0 preserves the unbounded behavior.
# Values above the platform semaphore capacity are clamped to it.
pause_concurrency_limit = 0
# Deterministic per-sandbox jitter applied when a timeout is assigned, uniform
# within +/- this percent of the requested TTL and derived from the sandbox ID.
# Staggers same-phase expiry cohorts before they form. Measured useful range
# with pause_concurrency_limit is 10-20; 0 disables jitter.
ttl_jitter_percent = 0
# Durable paused-sandbox metadata restored after a server restart.
# persisted_sandbox_store_path = "$AENV_HOME/persisted-sandboxes"

Expand Down
2 changes: 2 additions & 0 deletions docs/src/configuration/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,8 @@ Sandbox lifecycle management.
| `metrics_prometheus_max_age_secs` | integer | `60` | Stop exporting resource values at this local sample age; also bounded by `metrics_retention_secs`. Zero makes every sample unavailable. |
| `default_sandbox_timeout_secs` | integer | `15` | Default keep-alive timeout for sandboxes |
| `auto_resume_min_sandbox_timeout_secs` | integer | `300` | When a data-plane request targets a non-running sandbox, automatically resume it (if auto-resume is enabled) and refresh its timeout for no-less than this duration |
| `pause_concurrency_limit` | integer | `0` | Maximum number of pause operations that may run concurrently on this node, shared by TTL auto-eviction and explicit pause requests. Pause snapshots are dense (~1x guest RAM), so a same-second expiry cohort can saturate node write bandwidth; keep this small (measured: 2) and pair it with `ttl_jitter_percent`. `0` preserves the unbounded behavior. Values above the platform semaphore capacity are clamped to it |
| `ttl_jitter_percent` | integer | `0` | Deterministic per-sandbox TTL jitter, uniform within +/- this percent of the assigned timeout and derived from the sandbox ID, so same-phase expiry cohorts disperse before they form. Measured useful range with `pause_concurrency_limit`: 10-20. `0` disables jitter |
| `persisted_sandbox_store_path` | string | `"$AENV_HOME/persisted-sandboxes"` | Directory for persisted sandbox state |

## `[pool]`
Expand Down
32 changes: 32 additions & 0 deletions src/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,11 @@ pub struct NodeIdentityConfig {
pub service_instance_id: Option<String>,
}

/// Upper bound for `[orchestrator].ttl_jitter_percent`. The jitter band is
/// +/- the configured percent, so values at or above 100 could collapse a
/// sandbox timeout to zero.
pub(crate) const MAX_TTL_JITTER_PERCENT: u32 = 99;
Comment on lines +645 to +648

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
This upper bound does not actually guarantee a positive jittered timeout: jittered_ttl performs integer duration scaling, so a non-zero 1-second timeout can become zero at an offset below -0% (for example, 1s × 1% is 0ms after truncation) even though the configured value is within the allowed 99%. Since the setting is documented as preserving a usable TTL and the implementation's test only checks a 15-second timeout, either reject/limit jitter based on the minimum supported TTL or ensure the jitter calculation preserves at least one tick for every non-zero input.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6b6d201: jittered_ttl now floors the scaled result at 1 ns whenever the input timeout is non-zero (zero stays zero), so integer truncation cannot turn a valid short TTL into immediate expiry. ttl_jitter_percent_is_clamped_to_a_positive_timeout now asserts the sub-100 ns case (50 ns input).


#[derive(Debug, Config, Clone)]
pub struct OrchestratorConfig {
#[config(default = 15u64)]
Expand All @@ -661,6 +666,23 @@ pub struct OrchestratorConfig {
pub default_sandbox_timeout_secs: u64,
#[config(default = 300u64)]
pub auto_resume_min_sandbox_timeout_secs: u64,
/// Maximum number of pause operations that may run concurrently on this
/// node. TTL auto-eviction and explicit pause requests share the same
/// bound. Pause snapshots are dense (~1x guest RAM), so a same-second
/// expiry cohort can saturate node write bandwidth; a small cap keeps the
/// cohort tail latency near the intrinsic per-pause cost. 0 (default)
/// preserves the unbounded behavior. Values above the platform semaphore
/// capacity are clamped to it.
#[config(default = 0u64)]
pub pause_concurrency_limit: u64,
Comment on lines +676 to +677

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
Values above Semaphore::MAX_PERMITS are silently coerced to MAX_PERMITS when the orchestrator is constructed, so the effective concurrency limit can differ from the operator's configured value without any load-time error or warning. Please validate this field against the semaphore's supported maximum (or document and expose the clamping behavior) rather than accepting an arbitrary u64.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6b6d201 by documenting the behavior at each entry point instead of adding an arbitrary ceiling: the pause_concurrency_limit field doc, config/default.toml, and the [orchestrator] table in docs/src/configuration/reference.md now state that values above the platform semaphore capacity are clamped to it. The constructor keeps the clamp because Semaphore::MAX_PERMITS is a tokio-internal constant; exposing it in cfg.rs just for validation would duplicate a dependency internal.

/// Deterministic per-sandbox jitter applied when a timeout is assigned,
Comment on lines +676 to +678

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test · high
The schema test configuration_reference_documents_every_key requires every OrchestratorConfig field to appear in docs/src/configuration/reference.md. Neither of these new keys is documented there, so that test will fail (and the configuration reference is out of date) until entries for both orchestrator.pause_concurrency_limit and orchestrator.ttl_jitter_percent are added, or the documentation generation/update is included.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one does not reproduce: both keys are documented in docs/src/configuration/reference.md under the [orchestrator] table in this PR (pause_concurrency_limit and ttl_jitter_percent rows), and the schema test passes locally — cargo test --lib configuration_reference_documents_every_key → ok (1 passed), as does the full cargo test --lib (1063 passed, 0 failed). The test key set is derived from OrchestratorConfig field names, which match the table rows.

/// uniform within +/- this percent of the requested TTL and derived from
/// the sandbox ID. Staggers same-phase expiry cohorts before they form so
/// auto-eviction sees a spread instead of one pause batch. 0 (default)
/// disables jitter; 10-20 is the measured useful range when combined with
/// `pause_concurrency_limit`.
#[config(default = 0u64)]
pub ttl_jitter_percent: u64,
#[config(
default = "$AENV_HOME/persisted-sandboxes",
env = "AENV_PERSISTED_SANDBOX_STORE_PATH",
Expand Down Expand Up @@ -1038,6 +1060,7 @@ impl AppConfig {

fn validate(&self) -> Result<()> {
self.validate_pool_config()?;
self.validate_orchestrator_pause_shaping()?;
self.image.cache.gc.validate()?;
NetworkConfig::validate(&self.network)?;
if self.ublk.overlaybd.resize_timeout_secs == 0 {
Expand All @@ -1055,6 +1078,15 @@ impl AppConfig {
Ok(())
}

/// Validates the batch pause-shaping knobs so operator mistakes fail at
/// load time instead of silently degrading expiry behavior.
fn validate_orchestrator_pause_shaping(&self) -> Result<()> {
if self.orchestrator.ttl_jitter_percent > u64::from(MAX_TTL_JITTER_PERCENT) {
bail!("orchestrator.ttl_jitter_percent must be between 0 and {MAX_TTL_JITTER_PERCENT}");
}
Ok(())
}
Comment on lines +1083 to +1088

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test · low
The new configuration surface is only validated indirectly; there is no config-level test covering TOML parsing/defaults or the documented pause-limit mapping (0 => no semaphore, nonzero limits clamped to Semaphore::MAX_PERMITS). A regression in generated config metadata or this boundary logic could pass despite the existing jitter-range test. Add focused tests for 0, 1, MAX_PERMITS, and an oversized limit, plus the jitter endpoints.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2ac576d: the mapping is extracted into pause_semaphore_for (single source of truth shared by the constructor and the test harness), with pause_concurrency_limit_maps_onto_the_node_semaphore covering 0 => none, 1, the exact capacity, capacity+1, and u64::MAX (no panic, clamps). A config-level test validate_bounds_ttl_jitter_percent also pins the defaults (both knobs 0/off), the documented jitter upper bound passing, and MAX+1 bailing with the ttl_jitter_percent message.


fn validate_template_builder(&self) -> Result<()> {
let builder = &self.template_build;
if builder.max_concurrent_builds == 0 {
Expand Down
167 changes: 159 additions & 8 deletions src/orchestrator/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::sync::{
use std::time::{Duration, SystemTime};

use anyhow::Context;
use tokio::sync::{broadcast, oneshot, watch, Mutex, OnceCell, RwLock};
use tokio::sync::{broadcast, oneshot, watch, Mutex, OnceCell, RwLock, Semaphore};
use tokio::time::MissedTickBehavior;
use tracing::{debug, info, trace, warn};

Expand Down Expand Up @@ -66,6 +66,47 @@ const SANDBOX_EVENT_CHANNEL_CAPACITY: usize = 1024;
const MAX_SANDBOX_LOG_LIMIT: usize = 1000;
const SANDBOX_LOG_QUERY_TIMEOUT: Duration = Duration::from_secs(5);

/// Applies deterministic per-sandbox jitter to a newly assigned TTL.
///
/// Same-phase expiry cohorts (episodes of one rollout ending together, node
/// drains, recovery bursts) would otherwise reach the evictor as a single
/// batch, and their pause snapshots (~1x guest RAM each) contend for node
/// write bandwidth. Spreading the deadlines before the cohort forms disperses
/// the batch at zero runtime cost.
///
/// The offset is uniform within +/- `percent` of `timeout` and is a pure
/// function of the sandbox ID, so every assignment for a given sandbox lands
/// on the same point of the band: the offset never accumulates across
/// create/resume/keep-alive cycles, and equal inputs always produce equal
/// outputs.
fn jittered_ttl(sandbox_id: &SandboxId, timeout: Duration, percent: u32) -> Duration {
let percent = percent.min(crate::cfg::MAX_TTL_JITTER_PERCENT);
if percent == 0 {
return timeout;
}

// Fold both UUID halves into the offset. UUIDv7 keeps its random bits in
// the second half, so this mixes well without depending on a particular
// hash implementation staying stable across releases.
let bytes = sandbox_id.into_inner().into_bytes();
let mixed = u64::from_le_bytes(bytes[0..8].try_into().expect("UUID half is 8 bytes"))
^ u64::from_le_bytes(bytes[8..16].try_into().expect("UUID half is 8 bytes"));
let span = u64::from(percent) * 2 + 1;
let offset = (mixed % span) as i64 - i64::from(percent);
let factor = (100 + offset) as u32;

// Integer division truncates to whole nanoseconds, so a sub-100ns timeout
// can round down to zero. A non-zero TTL must never collapse into
// "expire immediately"; keep at least one nanosecond of lifetime. Zero
// stays zero.
let scaled = timeout.saturating_mul(factor) / 100;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
saturating_mul is applied before the division, so a sufficiently large Duration saturates at Duration::MAX and is then divided by 100. For example, a timeout near the representable maximum with any positive jitter can become roughly 1% of the requested TTL rather than remaining within the configured +/-99% band. Compute the scaled value without intermediate saturation (e.g. divide the seconds/nanoseconds components or use checked arithmetic with a fallback that preserves the intended bound) so large API-provided timeouts cannot be silently shortened.

Suggestion:

Suggested change
let scaled = timeout.saturating_mul(factor) / 100;
let scaled = timeout
.checked_mul(factor)
.map(|scaled| scaled / 100)
.unwrap_or_else(|| timeout / 100 * factor + (timeout % 100) * factor / 100);

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6eca741: the scaling now computes the exact quotient in u128 nanoseconds (timeout.as_secs()/subsec_nanos folded, times the factor, divided by 100 — the u128 intermediate cannot overflow for any representable Duration with a factor ≤ 199), so no intermediate saturation can shorten large timeouts; only the final value saturates at Duration::MAX, and the existing 1 ns floor for non-zero inputs is kept. Pinned by ttl_jitter_does_not_shorten_large_timeouts_through_intermediate_saturation (increase/decrease factors on Duration::MAX and Duration::from_secs(u64::MAX / 2); fails on the previous saturating-multiply).

if scaled.is_zero() && !timeout.is_zero() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

other · medium
Saturating before the division gives incorrect results for large durations: when timeout * factor exceeds Duration::MAX, this becomes Duration::MAX / 100, which can be far below the original timeout rather than the clamped upper-band value (and may violate the intended +/- jitter band). Compute the quotient and remainder with overflow-safe division, or explicitly clamp the mathematically scaled result to Duration::MAX.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6eca741 together with the sibling finding: the scaling computes the exact quotient in u128 nanoseconds with no intermediate saturation (see the reply above), so a large timeout scaled by an increase factor clamps at Duration::MAX only when the true quotient is unrepresentable, and a decrease factor lands on its exact in-band value. Covered by ttl_jitter_does_not_shorten_large_timeouts_through_intermediate_saturation.

Duration::from_nanos(1)
} else {
scaled
}
}

#[derive(Clone, Debug)]
enum ShutdownOutcome {
Success,
Expand Down Expand Up @@ -127,6 +168,12 @@ pub struct Orchestrator<
sandbox_metrics: Mutex<SandboxMetrics>,
sandbox_event_tx: broadcast::Sender<SandboxLifecycleEvent>,
default_sandbox_timeout: Duration,
/// Node-level bound on concurrent pause operations, shared by TTL
/// auto-eviction and explicit pause requests. `None` means unbounded.
pause_semaphore: Option<Arc<Semaphore>>,
/// Deterministic TTL jitter percent applied when a timeout is assigned
/// (0 disables jitter). Used by [`Self::shaped_timeout`].
ttl_jitter_percent: u32,
is_shutting_down: std::sync::atomic::AtomicBool,
shutdown_tx: watch::Sender<bool>,
shutdown_outcome: OnceCell<ShutdownOutcome>,
Expand Down Expand Up @@ -233,6 +280,19 @@ where
store.add(metadata).await?;
}

// Batch pause shaping: the semaphore bounds how many pause snapshots
// run at once across every entry point, and the jitter percent
// staggers same-phase expiry cohorts at TTL assignment time.
let pause_semaphore = match config.pause_concurrency_limit {
0 => None,
limit => {
let permits = usize::try_from(limit)
.unwrap_or(usize::MAX)
.min(Semaphore::MAX_PERMITS);
Some(Arc::new(Semaphore::new(permits)))
}
};

let orchestrator = Arc::new(Self {
store,
factory,
Expand All @@ -246,6 +306,9 @@ where
sandbox_metrics: Mutex::new(SandboxMetrics::default()),
sandbox_event_tx,
default_sandbox_timeout: Duration::from_secs(config.default_sandbox_timeout_secs),
pause_semaphore,
ttl_jitter_percent: u32::try_from(config.ttl_jitter_percent)
.unwrap_or(crate::cfg::MAX_TTL_JITTER_PERCENT),
is_shutting_down: std::sync::atomic::AtomicBool::new(false),
shutdown_tx,
shutdown_outcome: OnceCell::new(),
Expand Down Expand Up @@ -543,7 +606,10 @@ where
snapshot,
launch_config,
transitional_metadata,
NewTimeout::Set(timeout.unwrap_or(self.default_sandbox_timeout)),
self.shaped_timeout(
&sandbox_id,
NewTimeout::Set(timeout.unwrap_or(self.default_sandbox_timeout)),
),
))
.await
}
Expand Down Expand Up @@ -609,7 +675,10 @@ where
build_spec,
launch_config,
transitional_metadata,
NewTimeout::Set(timeout.unwrap_or(self.default_sandbox_timeout)),
self.shaped_timeout(
&sandbox_id,
NewTimeout::Set(timeout.unwrap_or(self.default_sandbox_timeout)),
),
))
.await
}
Expand Down Expand Up @@ -812,7 +881,7 @@ where
metadata.created_at = now;
metadata.paused_state = None;
metadata.volume_mounts = child.volume_mounts;
metadata.update_timeout(new_timeout);
metadata.update_timeout(self.shaped_timeout(&sandbox_id, new_timeout));

let proxy_target = match Self::proxy_target_from_sandbox(backend.as_ref()) {
Ok(proxy_target) => proxy_target,
Expand Down Expand Up @@ -992,7 +1061,14 @@ where
} else {
debug!(?timeout, "updating keep-alive timeout");
}
let valid_timeout = timeout.unwrap_or(self.default_sandbox_timeout);
// Jitter before the `allow_shorter` comparison below so a refresh
// request is not rejected because the stored deadline was jittered
// upward.
let valid_timeout = jittered_ttl(
&sandbox_id,
timeout.unwrap_or(self.default_sandbox_timeout),
self.ttl_jitter_percent,
);

let mut metadata = match self.store.get(&sandbox_id).await? {
Some(metadata) => metadata,
Expand Down Expand Up @@ -1391,6 +1467,48 @@ where
outcome.as_result()
}

/// Maps a newly assigned timeout through the configured TTL jitter.
///
/// `NewTimeout::Set` assigns a concrete duration, and `EnsureMinimum`
/// assigns one too: it sets the deadline when the sandbox has no timeout
/// yet and raises it when the stored one is shorter than the minimum (the
/// auto-resume path uses this variant). Both candidates are jittered so a
/// same-phase cohort still disperses; for `EnsureMinimum` the jittered
/// candidate is then clamped back to the minimum, preserving its
/// documented no-less-than contract. `UseExisting`/`None` assign nothing
/// new, so they pass through unchanged.
fn shaped_timeout(&self, sandbox_id: &SandboxId, timeout: NewTimeout) -> NewTimeout {
match timeout {
NewTimeout::Set(duration) => {
NewTimeout::Set(jittered_ttl(sandbox_id, duration, self.ttl_jitter_percent))
}
NewTimeout::EnsureMinimum(minimum) => NewTimeout::EnsureMinimum(
jittered_ttl(sandbox_id, minimum, self.ttl_jitter_percent).max(minimum),
),
other => other,
}
Comment on lines +1516 to +1524

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
EnsureMinimum can assign a new TTL: SandboxMetadata::update_timeout sets it to minimum when no timeout exists (and raises it when the existing value is smaller). The auto-resume path uses this variant, so those newly assigned minimum deadlines bypass jitter entirely and same-phase recovery cohorts remain synchronized. Please handle EnsureMinimum here as well, while preserving its no-less-than guarantee (for example, jitter the candidate and then clamp the result back to at least minimum).

Suggestion:

Suggested change
match timeout {
NewTimeout::Set(duration) => {
NewTimeout::Set(jittered_ttl(sandbox_id, duration, self.ttl_jitter_percent))
}
other => other,
}
match timeout {
NewTimeout::Set(duration) => {
NewTimeout::Set(jittered_ttl(sandbox_id, duration, self.ttl_jitter_percent))
}
NewTimeout::EnsureMinimum(minimum) => NewTimeout::EnsureMinimum(
jittered_ttl(sandbox_id, minimum, self.ttl_jitter_percent).max(minimum),
),
other => other,
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 16f5fde: shaped_timeout now maps EnsureMinimum as well — its candidate (minimum) is jittered with the same deterministic per-sandbox offset and then clamped back with .max(minimum), so recovery cohorts disperse above the floor while the documented no-less-than contract holds. Pinned by ensure_minimum_candidates_are_jittered_but_never_below_the_minimum (sweeps the whole band with deterministic IDs, asserts the below-minimum collapse and the above-minimum spread) and the wiring test resume_applies_configured_ttl_jitter_to_ensure_minimum.

}

/// Waits for a pause slot when batch pause shaping is configured.
///
/// Pause snapshots are dense (~1x guest RAM), so a cohort of concurrent
/// pauses saturates node write bandwidth and every pause in the cohort
/// slows down. Callers reserve the slot before claiming the `Pausing`
/// transition, so a sandbox queued behind the limit stays `Running`
/// (reachable while it waits) and the permit is held across the whole
/// capture-and-stop sequence.
async fn acquire_pause_slot(&self) -> Option<tokio::sync::OwnedSemaphorePermit> {
match &self.pause_semaphore {
Some(semaphore) => Some(
Arc::clone(semaphore)
.acquire_owned()
.await
.expect("pause semaphore is never closed"),
),
None => None,
}
}

/// Pauses a running sandbox by taking a snapshot and stopping its VM.
///
/// If another `pause_sandbox` call is already in progress for the same
Expand All @@ -1411,13 +1529,22 @@ where
)]
async fn pause_sandbox_inner(self: &Arc<Self>, sandbox_id: SandboxId) -> Result<()> {
info!("pausing sandbox");
// Reserve shaping capacity before claiming the transition: a sandbox
// queued behind the pause limit must stay `Running` (proxyable,
// keep-alive-able, deletable) until its pause actually starts.
let pause_slot = self.acquire_pause_slot().await;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · medium
This awaits the node-wide semaphore before checking whether this sandbox is already Pausing/Paused. Consequently, duplicate pause requests for a sandbox whose pause is already in progress consume request time waiting behind unrelated pauses, and cannot enter the existing join_concurrent_pause path until a permit becomes available. With a stalled or long-running pause this can turn an otherwise bounded transition wait into an unbounded semaphore wait. Check the current state/claim before waiting (or otherwise provide a prompt same-sandbox join path), while retaining the permit-before-claim ordering for a genuinely new pause.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2ac576d: pause_sandbox_inner now probes the sandbox state before waiting for a slot. An already-Pausing sandbox goes straight to the bounded join_concurrent_pause path, Paused returns Ok, Killing maps to NotFound — none of them consume queue time — while a genuinely new pause still reserves its slot before claiming Pausing, and the CAS remains authoritative for the race window (a conflict that appears after the probe still drops the slot and joins). Regression duplicate_pause_joins_promptly_even_with_a_saturated_pause_pool keeps the only permit reserved, completes the simulated in-flight pause, and asserts the duplicate returns within 5s (fails on the previous ordering, passes now).

match self
.store
.update_state_if_state(&sandbox_id, SandboxState::Pausing, &[SandboxState::Running])
.await
{
Ok(_) => {}
Err(StoreError::StateConflict { actual_state, .. }) => {
// No pause work will run for this call: another operation
// already owns the transition. Release the slot before
// joining/waiting on it so queued capacity is not consumed
// by a caller that is not pausing anything.
drop(pause_slot);
return match actual_state {
// Another task is already performing the pause. Wait for
// it to finish and then report the final outcome.
Expand All @@ -1439,10 +1566,20 @@ where
Err(err) => return Err(OrchestratorError::from(err)),
}

self.pause_sandbox_impl(sandbox_id).await
self.pause_sandbox_impl(sandbox_id, pause_slot).await
}

async fn pause_sandbox_impl(self: &Arc<Self>, sandbox_id: SandboxId) -> Result<()> {
/// Runs the pause capture-and-stop sequence for a sandbox whose transition
/// the caller has already claimed.
///
/// `_pause_slot` is the caller's pause-shaping permit (see
/// [`Self::acquire_pause_slot`]). Every caller acquires it before claiming
/// `Pausing`, and it is held for the whole sequence below.
async fn pause_sandbox_impl(
self: &Arc<Self>,
sandbox_id: SandboxId,
_pause_slot: Option<tokio::sync::OwnedSemaphorePermit>,
) -> Result<()> {
// Pin paused runtime artifacts before detaching from the running set.
let runtime_artifacts = {
let handle = self.sandboxes.read().await.get(&sandbox_id).cloned();
Expand Down Expand Up @@ -1660,6 +1797,11 @@ where
) -> Result<SandboxMetadata> {
self.ensure_accepting_lifecycle_operations()?;

// Apply TTL staggering once at the entry point so every downstream
// path (launch, concurrent-resume join, keep-alive refresh) uses the
// same jittered deadline.
let timeout = self.shaped_timeout(&sandbox_id, timeout);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
This shapes the caller's NewTimeout, but the resulting duration is later passed to maybe_update_running_timeout on the already-running/concurrent-resume paths, and that helper applies jittered_ttl again. For example, a resume with NewTimeout::Set(base) can become J(J(base)), and repeated/concurrent resume calls can keep moving the deadline outside the configured single +/- jitter band. Keep the timeout unshaped until the actual assignment site, or carry an explicit marker that it has already been shaped so each assignment applies jitter exactly once.

Suggestion:

Suggested change
let timeout = self.shaped_timeout(&sandbox_id, timeout);
// Shape only at the timeout assignment site; the running/concurrent
// resume paths may otherwise shape this value a second time.
let timeout = timeout;

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This does not reproduce: maybe_update_running_timeout never re-jitters. Its body passes the incoming NewTimeout straight to metadata.update_timeout(timeout) (service.rs:2321-2343) and it does not call jittered_ttl/shaped_timeout. The only jitter application sites are the resume entry point (once per call, on the caller's raw value), create/fork, and keep_alive_for (which jitters its own raw input); no path feeds an already-shaped duration back into the shaper, and run_cancellation_safe does not retry the operation. Pinned mechanically in fe72e54 by resume_jitter_is_applied_exactly_once_across_repeated_calls: three running-path resumes plus a paused-launch resume with Set(120s) all land on exactly jittered_ttl(id, 120s, 20); a compounded J(J(...)) would land on a different value and drift further per call.


info!("resuming sandbox");
let mut metadata = self
.store
Expand Down Expand Up @@ -2288,12 +2430,21 @@ where
// Use the same operation lock as explicit deletion before claiming Killing.
let deletion = self.deletion_progress(metadata.id).await;
let mut progress = deletion.lock().await;
// Reserve pause capacity before claiming `Pausing`, so an expired
// sandbox queued behind the pause limit keeps running (and stays
// proxyable) until its pause actually starts.
let pause_slot = match metadata.timeout_action {
SandboxTimeoutAction::Pause => self.acquire_pause_slot().await,
SandboxTimeoutAction::Delete => None,
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

other · medium
The eviction loop holds the per-sandbox deletion progress mutex while awaiting a global pause permit. If the pause pool is saturated, this can block delete_sandbox_inner for this sandbox indefinitely even though the sandbox is still Running and deletion could otherwise proceed. Acquire the permit before locking deletion_progress, or avoid holding this lock across the semaphore wait, while preserving the claim/operation serialization before doing pause work.

Suggestion:

Suggested change
let deletion = self.deletion_progress(metadata.id).await;
let mut progress = deletion.lock().await;
// Reserve pause capacity before claiming `Pausing`, so an expired
// sandbox queued behind the pause limit keeps running (and stays
// proxyable) until its pause actually starts.
let pause_slot = match metadata.timeout_action {
SandboxTimeoutAction::Pause => self.acquire_pause_slot().await,
SandboxTimeoutAction::Delete => None,
};
let pause_slot = match metadata.timeout_action {
SandboxTimeoutAction::Pause => self.acquire_pause_slot().await,
SandboxTimeoutAction::Delete => None,
};
let deletion = self.deletion_progress(metadata.id).await;
let mut progress = deletion.lock().await;

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fe72e54: the evictor now acquires the pause slot before deletion_progress/the per-sandbox lock, exactly as suggested. The claim-and-work serialization still runs under the lock, so the claim-vs-delete race semantics are unchanged; only the permit wait moved out from under it. Regression auto_evict_pause_does_not_block_deletion_while_waiting_for_a_slot: with the only permit reserved, a delete of the expired sandbox completes while the evictor is parked on the semaphore (verified to fail with Elapsed on the previous ordering and pass now); after release the evictor re-claims the entry, sees the sandbox gone, and skips it.

Comment on lines +2506 to +2509

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · medium
evict_expired_sandboxes processes expired serially, so awaiting this pause permit stops the entire eviction pass. If the first expired sandbox is a pause action and the pause pool is saturated, later expired sandboxes—including Delete actions that do not need a permit—are not even claimed until an unrelated pause finishes. This can delay deletion well beyond the eviction interval; consider claiming/processing entries independently (or otherwise avoid awaiting a pause-only resource in the single scan loop).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2ac576d for the actionable part: the eviction pass now claims deletion entries before pause entries (stable sort on the timeout action), so deletes are no longer reachable only after a parked pause entry — deletes need no slot and are claimed/processed regardless of pool depth. Per-entry spawning was left out deliberately: pause entries are processed serially in list order by design (the semaphore additionally bounds cross-entry-point pauses; the sequential scan predates this PR), and making the scan concurrent would introduce overlapping eviction passes for no shaping benefit. Regression auto_evict_claims_deletes_before_pause_entries_parked_on_a_saturated_pool lists a pause entry first (earlier expiry) with the pool saturated and asserts the later delete entry still completes within 5s (fails on the previous ordering with the deadline assertion, passes now).

Comment on lines +2506 to +2509

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · medium
The eviction task awaits a pause permit inline while iterating the entire expired snapshot. Once it reaches the first expired pause entry, all later work (including deletes that become expired after list_expired and any subsequent eviction pass) is blocked until that pause finishes; if a backend pause stalls, the single background evictor stalls as well. Consider claiming eligible delete entries independently and/or spawning/queueing pause work without holding up the eviction scheduler, with bounded retry/cancellation handling.

Suggestion:

Suggested change
let pause_slot = match metadata.timeout_action {
SandboxTimeoutAction::Pause => self.acquire_pause_slot().await,
SandboxTimeoutAction::Delete => None,
};
let pause_slot = match metadata.timeout_action {
SandboxTimeoutAction::Pause => self.acquire_pause_slot().await,
SandboxTimeoutAction::Delete => None,
};

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recording this as a design-level item rather than changing it here, with the current behavior spelled out:

  • The user-visible half of this class was fixed earlier: each eviction pass claims delete entries before pause entries, so no delete waits behind a pause entry in the same pass (regression in fe72e54). Entries that expire after list_expired are only visible to the next pass by construction, independent of the pause pool.
  • The remaining inline wait is for pause entries only, and pause entries are serial in this loop by design (the loop predates this PR; the semaphore bounds cross-entry-point concurrency, not the scan). Waiting for capacity is precisely the backpressure that keeps a rollout-end cohort from re-saturating node write bandwidth — the feature this PR ships.
  • Spawning/queueing pause work would change the synchronous eviction contract: evict_expired_sandboxes is awaited by the background ticker and reports ids only after each claimed operation completes; detaching would require owned deletion-lock guards to preserve the claim-and-work serialization against deletes and would change eviction reporting semantics for callers and tests. That is a design change beyond this PR — happy to follow up if maintainers want detached pause work, but I would not relabel a claimed sandbox as evicted before its pause snapshot exists.

If you spot a concrete stall path that is not bounded by pause-work duration (the stalled-backend case saturates any pause entry point, not just the evictor), please point at it and I will fix it.

let result = match self
.claim_expired_sandbox(metadata.id, eviction_cutoff, metadata.state, claimed_state)
.await
{
Ok(true) => match metadata.timeout_action {
SandboxTimeoutAction::Pause => self.pause_sandbox_impl(metadata.id).await,
SandboxTimeoutAction::Pause => {
self.pause_sandbox_impl(metadata.id, pause_slot).await
}
SandboxTimeoutAction::Delete => {
self.delete_sandbox_impl(metadata.id, metadata.state, &mut progress)
.await
Expand Down
Loading
Loading