Skip to content

feat(orchestrator): shape batch pause cohorts with a concurrency cap and TTL jitter - #522

Open
yjjnls wants to merge 7 commits into
kvcache-ai:mainfrom
yjjnls:fix/batch-pause-shaping
Open

yjjnls wants to merge 7 commits into
kvcache-ai:mainfrom
yjjnls:fix/batch-pause-shaping

Conversation

@yjjnls

@yjjnls yjjnls commented Nov 18, 2026 •

Copy link
Copy Markdown

Refs #506

Pause snapshots are dense (~1x guest RAM), so a same-second expiry cohort — the default shape of rollout-end workloads and node drains — arrives at the evictor as one batch, saturates node write bandwidth, and every pause in the batch slows down. This implements the two proposal items from #506. Both are opt-in, and both defaults preserve the current behavior exactly:

  • [orchestrator].pause_concurrency_limit (default 0 = unlimited): a node-wide Semaphore shared by TTL auto-eviction and explicit pause requests, so the bound holds regardless of which entry point issued the pause. The slot is acquired at the top of pause_sandbox_impl — before any state is detached — and held across the whole capture-and-stop sequence, so a queued sandbox stays reachable while it waits.
  • [orchestrator].ttl_jitter_percent (default 0 = off): newly assigned deadlines are spread uniformly within +/- the configured percent of the requested TTL, using a deterministic offset folded from the sandbox ID. The offset is a pure function of the ID, so it never accumulates across create/resume/keep-alive cycles, and EnsureMinimum (auto-resume) keeps its documented no-less-than contract. Jitter is applied before the allow_shorter keep-alive comparison so a refresh is not rejected just because the stored deadline was jittered upward.

Shaping applies at creation (default and explicit timeouts), fork children, resume, and keep-alive assignment.

Measurements from #506

30 x 512 MiB guests, Firecracker v1.17, NVMe + ext4:

Shaping Cohort p95
Unshaped (all 30 concurrent) 4013 ms
Concurrency cap 2 421 ms
Cap 8 + 200 ms staggered starts 343 ms

ttl_jitter_percent alone does not bound an already-formed cohort; it disperses same-phase cohorts before they form, and composes with the cap.

Behavior notes

  • Defaults reproduce today's behavior exactly; no snapshot format, API, or state-machine changes.
  • A pause queued behind the cap stays in Pausing; callers that join a concurrent pause are subject to the existing 60 s transitional-state wait, so extremely large cohorts with a tiny cap can surface as a wait timeout (same failure mode as a slow pause today). Pair the cap with TTL jitter to keep cohorts dispersed.
  • The evictor keeps its inline serial drain order; this change does not reorder eviction.
  • Out of scope: the alternative eviction-queue hook from Batch pause write storms: shape TTL-eviction pause cohorts to keep p95 under budget #506, and pause queue-depth/p95 metrics. Happy to pursue either if you prefer that shape.

Tests

  • ttl_jitter_is_deterministic_and_within_band, ttl_jitter_spreads_same_phase_cohort, ttl_jitter_percent_is_clamped_to_a_positive_timeout
  • create_applies_configured_ttl_jitter (create-time wiring)
  • pause_concurrency_limit_bounds_parallel_pause_cohort (mock-backend cohort of 6, cap 2, observes the peak concurrent pause captures) and an unbounded control that proves the cohort overlaps without the cap
  • cargo test --lib: 1063 passed, 0 failed; cargo clippy --lib --tests clean; cargo fmt --check clean

Commits are DCO signed off.

…and TTL jitter

Pause snapshots are dense (~1x guest RAM), so a same-second expiry cohort —
the default shape of rollout-end workloads and node drains — saturates node
write bandwidth as one batch, and every pause in the batch slows down. Bound
pause concurrency across both entry points and stagger TTL assignment
deterministically per sandbox.

- [orchestrator].pause_concurrency_limit (default 0 = unlimited) gates a
  node-wide semaphore shared by TTL auto-eviction and explicit pause
  requests; the slot is held for the whole capture-and-stop sequence, and it
  is acquired before any state is detached so a queued sandbox stays
  reachable while it waits.
- [orchestrator].ttl_jitter_percent (default 0 = off) spreads newly assigned
  deadlines within +/- percent of the requested TTL using a stable offset
  derived from the sandbox ID, so cohorts disperse before they form and the
  offset never accumulates across create/resume/keep-alive cycles.
  EnsureMinimum keeps its documented no-less-than contract.

Both defaults preserve the current behavior exactly. Measured on 30 x
512 MiB guests: unshaped cohort p95 4013 ms; cap 2 -> 421 ms; cap 8 with
200 ms staggered starts -> 343 ms.

Tests cover the jitter band/determinism/cohort spread, create-time wiring,
and a mock-backend cohort that observes the concurrent pause capture peak.

Refs kvcache-ai#506

Signed-off-by: yjjnls <yjjnls@users.noreply.github.com>
@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

✅ OpenCodeReview: Review complete: 0 finding(s) across 4 selected item(s).

Comment thread src/cfg.rs
Comment on lines +645 to +648
/// 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;

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).

Comment thread src/cfg.rs
Comment on lines +675 to +676
#[config(default = 0u64)]
pub pause_concurrency_limit: u64,

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.

Comment thread src/cfg.rs
Comment on lines +675 to +677
#[config(default = 0u64)]
pub pause_concurrency_limit: u64,
/// Deterministic per-sandbox jitter applied when a timeout is assigned,

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.

Comment thread src/orchestrator/service.rs Outdated
let offset = (mixed % span) as i64 - i64::from(percent);
let factor = (100 + offset) as u32;

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
For nonzero durations below 100 ns, Duration::saturating_mul(factor) still has nanosecond precision and dividing by 100 truncates to zero (for example, with the minimum factor 1). That makes a valid short TTL expire immediately; the ttl_jitter_percent clamp only prevents a zero factor, not zero-duration rounding. Preserve at least one nanosecond for any nonzero input, or do the scaling in a wider integer representation and clamp the result to Duration::from_nanos(1).

Suggestion:

Suggested change
timeout.saturating_mul(factor) / 100
let nanos = timeout.as_nanos().saturating_mul(u128::from(factor)) / 100;
Duration::from_nanos(nanos.max(u128::from(timeout != Duration::ZERO)) as 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 with a smaller change than the suggestion: keep timeout.saturating_mul(factor) / 100 (it preserves Duration saturation at Duration::MAX) and floor the result at Duration::from_nanos(1) only when the input is non-zero. A zero timeout stays zero. Pinned by the extended ttl_jitter_percent_is_clamped_to_a_positive_timeout assertion.

Comment thread src/orchestrator/service.rs Outdated
let offset = (mixed % span) as i64 - i64::from(percent);
let factor = (100 + offset) as u32;

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
Correction to the suggested fix: preserve Duration saturation while avoiding sub-nanosecond truncation. For example, compute the quotient from timeout.as_nanos() in u128, clamp it to u64::MAX before Duration::from_nanos, and use .max(1) only when the original timeout is nonzero.

Suggestion:

Suggested change
timeout.saturating_mul(factor) / 100
let nanos = timeout.as_nanos().saturating_mul(u128::from(factor)) / 100;
Duration::from_nanos(nanos.min(u128::from(u64::MAX)).max(u128::from(timeout != Duration::ZERO)) as 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.

Same finding as the sibling thread — fixed in 6b6d201 without the u128 round-trip (see the reply above): the existing Duration saturating multiply plus a 1 ns floor for non-zero inputs covers the truncation case and keeps saturation semantics.

Comment thread src/orchestrator/service.rs Outdated
let offset = (mixed % span) as i64 - i64::from(percent);
let factor = (100 + offset) as u32;

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
The prior suggested snippet's u128::from(timeout != Duration::ZERO) is not a valid Rust conversion. The intended fix should use an explicit conditional (for example, let minimum = if timeout.is_zero() { 0 } else { 1 };) when clamping the nanosecond result.

Suggestion:

Suggested change
timeout.saturating_mul(factor) / 100
let nanos = timeout.as_nanos().saturating_mul(u128::from(factor)) / 100;
let minimum = if timeout.is_zero() { 0 } else { 1 };
Duration::from_nanos(nanos.min(u128::from(u64::MAX)).max(minimum) as 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.

Also the same finding — fixed in 6b6d201 (see the first thread): no conditional-zero math needed beyond if scaled.is_zero() && !timeout.is_zero().

Comment thread src/orchestrator/tests.rs Outdated
sandbox_metrics: Mutex::new(SandboxMetrics::default()),
sandbox_event_tx,
default_sandbox_timeout: Duration::from_secs(15),
pause_semaphore: pause_concurrency_limit.map(|limit| Arc::new(Semaphore::new(limit))),

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
This test helper does not mirror production's 0 => None semantics: Some(0) creates a semaphore with no permits, so any pause test using that value waits forever. Normalize zero to None here (or accept the raw config value and apply the same conversion as the constructor) to keep tests from hanging when exercising the documented unlimited setting.

Suggestion:

Suggested change
pause_semaphore: pause_concurrency_limit.map(|limit| Arc::new(Semaphore::new(limit))),
pause_semaphore: pause_concurrency_limit
.filter(|&limit| limit != 0)
.map(|limit| Arc::new(Semaphore::new(limit))),

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: the helper now mirrors the production mapping (0 => None, unlimited) and clamps to Semaphore::MAX_PERMITS like the constructor, with a comment saying exactly that so future callers cannot build the zero-permit semaphore.

…aping plumbing

Addresses the open-code-review findings on the batch pause shaping:

- jittered_ttl: integer truncation could round a sub-100ns timeout down to
  zero, expiring immediately. A non-zero TTL now keeps at least one
  nanosecond of lifetime (a zero timeout stays zero), pinned by a regression
  assertion.
- pause_concurrency_limit: the constructor clamps values above the platform
  semaphore capacity; the field docs, default.toml, and the configuration
  reference now state that instead of leaving it silent.
- test helper: mirror the production 0 => unlimited mapping so Some(0)
  cannot create a zero-permit semaphore that would deadlock every pause, and
  clamp to Semaphore::MAX_PERMITS the same way the constructor does.

Refs kvcache-ai#506

Signed-off-by: yjjnls <yjjnls@users.noreply.github.com>
Comment on lines +1476 to +1481
match timeout {
NewTimeout::Set(duration) => {
NewTimeout::Set(jittered_ttl(sandbox_id, duration, self.ttl_jitter_percent))
}
other => other,
}

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.

Comment thread src/orchestrator/tests.rs Outdated
Comment on lines +6460 to +6462
for _ in 0..200 {
let sandbox_id = SandboxId::new();
let shaped = jittered_ttl(&sandbox_id, base, 20);

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
This test samples UUIDs and asserts a fixed number of occupied jitter buckets. Although unlikely to fail with the current 200 samples, it is still probabilistic and can become flaky if the bucket count or duration precision changes. Construct IDs for deterministic bucket coverage (or assert the expected bucket set directly) instead of relying on random SandboxId::new() values.

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: the test now covers the band deterministically instead of sampling random UUIDs. A jitter_probe_id(index) helper constructs IDs whose folded UUID halves equal index, so every one of the 41 offsets (+/-20%) is asserted directly and distinct.len() is pinned to the band width — no probabilistic coverage left to flake if the band width or duration precision changes.

…me TTLs

Addresses the second open-code-review round on the batch pause shaping:

- pause concurrency: the shaping slot is now acquired before the sandbox
  claims the Pausing transition -- both the explicit/shutdown path and the
  TTL eviction claim -- so a sandbox queued behind the limit stays Running
  and reachable instead of exposing a pause that has not started. A call
  that conflicts with an in-flight pause releases its slot before joining,
  so waiters consume no pause capacity.
- shaped_timeout: NewTimeout::EnsureMinimum assigns a fresh deadline when
  no timeout exists or a shorter one is stored, and the auto-resume path
  uses it, so its candidate is jittered like Set and clamped back to the
  minimum to preserve the documented no-less-than contract.
- tests: the cohort-spread test now sweeps every band offset with
  deterministic IDs instead of sampling random UUIDs. New regressions pin
  Running-while-queued, slot release before joining, and EnsureMinimum
  jitter (unit plus pause/resume wiring).

Refs kvcache-ai#506

Signed-off-by: yjjnls <yjjnls@users.noreply.github.com>
@yjjnls

yjjnls commented Nov 19, 2026

Copy link
Copy Markdown
Author

Second-round findings addressed in 16f5fde — including this one that failed to post inline:

Semaphore acquired after the Pausing CAS. The pause slot is now reserved before the Running -> Pausing transition on both entry points that claim it — pause_sandbox_inner and the TTL eviction claim (claim_expired_sandbox) — so a sandbox queued behind the limit stays Running (proxyable, keep-alive-able, deletable) until its pause actually starts. On the StateConflict early-return path the slot is released with drop(pause_slot) before joining the in-flight pause, matching the suggested change; every other path (store error, detach, pause/persist failure) releases the permit on return since it is held in a named binding. Regression tests: queued_pause_leaves_its_sandbox_running_until_a_slot_frees (asserts the queued sandbox stays Running and unfinished across the whole queue delay, then completes once a slot frees) and conflicting_pause_releases_its_slot_before_waiting (observes the conflicting call entering the join wait via a store wait-hook, then asserts the permit is already back).

The two inline threads are answered separately: EnsureMinimum now gets its candidate jittered (clamped to the minimum) and the cohort-spread test is deterministic.

cargo test --lib 1067 passed / 0 failed, cargo clippy -p agentenv --all-targets --all-features -- -D warnings clean, cargo fmt --check clean.

// 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.

Comment thread src/orchestrator/service.rs Outdated
Comment on lines +2431 to +2439
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 thread src/orchestrator/tests.rs Outdated
Comment on lines +6585 to +6597
let mut deadlines = HashSet::new();
for _ in 0..5 {
let created = orchestrator
.create_sandbox(create_request(Some(60), &[]))
.await?;
let expected = jittered_ttl(&created.id, Duration::from_secs(60), 20);
assert_eq!(created.timeout, Some(expected));
deadlines.insert(created.timeout);
}
assert!(
deadlines.len() >= 2,
"a same-phase create cohort must not share one deadline"
);

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
This assertion makes the test probabilistic: five randomly generated sandbox IDs are mapped into only 41 jitter buckets, so there is a non-zero chance that all five receive the same offset and the test fails even though jitter works. Use deterministic probe IDs (or assert the individual values against jittered_ttl without requiring a collision-free sample) so the test is stable.

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 distinct-count assertion is gone. The create wiring is now asserted per ID (created.timeout == jittered_ttl(created.id, 60s, 20) for every created sandbox), which is deterministic; band coverage and dispersion are pinned deterministically by ttl_jitter_spreads_same_phase_cohort, which sweeps all 41 offsets with constructed IDs, so the probabilistic collision-free requirement was redundant.

…queue

Addresses the third open-code-review round on the batch pause shaping:

- eviction: the expired-sandbox loop now reserves its pause slot before
  taking the per-sandbox deletion lock, so a saturated pause pool no longer
  blocks an explicit delete of that sandbox behind the evictor's wait. The
  claim-and-work serialization still runs under the lock.
- tests: create_applies_configured_ttl_jitter asserts the exact per-ID
  mapping instead of a probabilistic distinct-count over server-generated
  IDs; new regressions pin delete-vs-pause-queue independence and that
  resume jitter is applied exactly once (repeated running-path and
  paused-launch resumes keep the same deadline).

The reported double application of jitter on the resume paths does not
reproduce: maybe_update_running_timeout passes the already-shaped
NewTimeout straight to metadata.update_timeout and never calls
jittered_ttl/shaped_timeout, and every jitter application site receives a
raw caller/config value. The exactly-once regression pins that.

Refs kvcache-ai#506

Signed-off-by: yjjnls <yjjnls@users.noreply.github.com>
Comment thread src/cfg.rs
Comment on lines +1083 to +1088
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(())
}

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.

Comment thread src/orchestrator/service.rs Outdated
Comment on lines +1532 to +1535
// 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).

Comment on lines +2434 to +2437
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.

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 +2434 to 2439
let pause_slot = match metadata.timeout_action {
SandboxTimeoutAction::Pause => self.acquire_pause_slot().await,
SandboxTimeoutAction::Delete => None,
};
// Use the same operation lock as explicit deletion before claiming Killing.
let deletion = self.deletion_progress(metadata.id).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.

other · medium
The claimed ordering does not guarantee that explicit deletion is independent of the evictor: once the evictor acquires pause_slot, it can block on deletion_progress(...).lock() while retaining the permit, and then claim Pausing before a waiting delete can claim Killing. The delete consequently waits for the full pause snapshot (and the permit can also be held while waiting for the deletion lock). To preserve the stated behavior, serialize/claim the per-sandbox operation before waiting for the pause permit, or re-check the operation state and release the permit when deletion has won.

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 describes the intended serialization rather than a regression from this PR, and the first suggested remedy is mutually exclusive with the round-2 finding (which required acquiring the slot before claiming Pausing so a queued sandbox stays Running and deletable). Concretely:

  • Queue-depth independence holds where it was claimed: a saturated pool parks the evictor on the semaphore before it touches deletion_progress/the claim, so an explicit delete of that sandbox proceeds untouched (pinned by auto_evict_pause_does_not_block_deletion_while_waiting_for_a_slot).
  • 'The delete waits for the full pause snapshot' is the pre-existing, deliberate design, unchanged by this PR: the shared per-sandbox operation lock serializes claim-and-work against deletes, and the identical sequence (evictor claims Pausing, snapshots while a delete waits on the lock) exists in the pre-PR code. Once the evictor has claimed, the delete waits for pause work, not for the queue.
  • The residual window (permit held while waiting for a lock held by an in-flight delete) is bounded by that delete's duration and cannot deadlock — deletes never take pause permits. After the lock is acquired, claim_expired_sandbox re-validates and returns Ok(false) when deletion won, so the permit is released with zero pause work: that is exactly the second suggested remedy, already in place.

Claim-before-permit would reintroduce the round-2 defect (queued sandboxes left non-proxyable in Pausing, deletes/resume/keep-alive waiting behind an unbounded semaphore wait), so the current ordering is the deliberate trade-off.

Addresses the fourth open-code-review round on the batch pause shaping:

- duplicate pause calls probe the sandbox state before waiting for a slot:
  an already-Pausing sandbox joins the in-flight pause (bounded wait)
  without consuming queue time, Paused/Killing map to their outcomes
  immediately, and a genuinely new pause still reserves its slot before
  claiming Pausing (the CAS stays authoritative for races).
- eviction claims deletion entries before pause entries: deletes need no
  pause slot, so a saturated pool no longer delays them behind paused work
  parked on the semaphore (stable sort preserves expiry order per group).
- config: the pause-limit mapping is extracted into pause_semaphore_for
  (shared by the constructor and the test harness) with boundary tests for
  0/1/capacity/oversized/u64::MAX, and a config-level test pins the jitter
  percent validation endpoints and the default-off knobs.

Refs kvcache-ai#506

Signed-off-by: yjjnls <yjjnls@users.noreply.github.com>
Comment thread src/orchestrator/service.rs Outdated
// 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).

Comment thread src/orchestrator/service.rs Outdated
Comment on lines +102 to +103
let scaled = timeout.saturating_mul(factor) / 100;
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.

Comment thread src/orchestrator/service.rs Outdated
Comment on lines 2468 to 2474
let pause_slot = match metadata.timeout_action {
SandboxTimeoutAction::Pause => self.acquire_pause_slot().await,
SandboxTimeoutAction::Delete => None,
};
// 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;

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 evictor acquires a scarce pause permit before waiting for the per-sandbox deletion-progress mutex. If an explicit delete (or another lifecycle operation using this mutex) is in progress, this task holds the permit while it cannot perform any pause work, reducing the effective node-wide concurrency and potentially blocking unrelated pauses behind it. Acquire/claim the operation lock first, then reserve the pause slot immediately before pause_sandbox_impl (while preserving the delete-vs-pause ordering needed for explicit deletion).

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 with a twist that avoids reintroducing the round-3 blocking: the evictor still reserves the slot before touching the per-sandbox lock, but it now takes that lock with try_lock and defers the entry to the next pass when another operation (an in-flight delete or an overlapping pass) owns the sandbox. So the permit is never held while waiting for the lock (this finding) and the lock is never held while waiting for the permit (round-3 finding) — the literal suggestion here would have brought back round 3. Deferral is safe by construction: a winning delete makes the pause moot, a failing delete leaves the sandbox Running for the next pass. Regression auto_evict_defers_pause_entries_while_another_operation_owns_the_sandbox: with the lock held by another task the pass returns promptly, the permit is back (available_permits == 1), the sandbox stays Running, and the next pass pauses it once the lock is free (fails on the previous ordering).

Comment thread src/orchestrator/tests.rs Outdated
Comment on lines +6806 to +6821
for _ in 0..40 {
assert!(
!pause.is_finished(),
"pause must wait for the reserved slot before claiming Pausing"
);
assert_eq!(
orchestrator
.get_sandbox(&sandbox_id)
.await?
.expect("sandbox exists")
.state,
SandboxState::Running,
"a sandbox queued for a pause slot must stay Running"
);
sleep(Duration::from_millis(5)).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.

test · low
The polling loop relies on scheduler timing and can fail spuriously if the test task is delayed for more than the 200 ms polling window, even though the semaphore behavior is correct. Synchronize with an explicit signal that the pause task has entered the semaphore wait, then assert Running while the test-held permit remains reserved.

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: rather than a longer polling window, the test now synchronizes on a test-only queue-entry signal (pause_queue_entered, a #[cfg(test)] Notify fired by acquire_pause_slot when the semaphore is exhausted). The test reserves the slot, spawns the pause, awaits the signal (proof the call is parked on the shaping queue), then asserts the sandbox is still Running and the task unfinished — deterministic, because a parked caller cannot claim Pausing. It fails on the pre-fix ordering with left: Pausing, right: Running.

Comment thread src/orchestrator/tests.rs Outdated
Comment on lines +6937 to +6942
let evictor = tokio::spawn({
let orchestrator = Arc::clone(&orchestrator);
async move { orchestrator.evict_expired_sandboxes().await }
});
// Give the evictor time to reach its pause-slot wait.
sleep(Duration::from_millis(150)).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.

test · low
This fixed sleep does not establish that the evictor has reached acquire_pause_slot(). On a busy or slow CI worker, deletion may run before the evictor is scheduled (so the test passes without exercising the intended contention), while shortening the sleep could make the test flaky. Add a deterministic notification/hook around the semaphore wait (or otherwise await an observable state) before issuing the deletion.

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 fixed sleep is gone. The test now awaits the same test-only queue-entry signal, which proves the evictor's pause is parked on the semaphore before anything else happens; it then asserts the per-sandbox deletion lock is still free (try_lock succeeds — the exact property the sleep was trying to approximate) and that an explicit delete completes. On the previous ordering the lock assertion fails deterministically instead of relying on timing.

…waits

Addresses the fifth open-code-review round on the batch pause shaping:

- jittered_ttl scales the exact quotient in u128 nanoseconds: saturating
  the intermediate timeout * factor collapsed large timeouts to ~1% of the
  request (far outside the band) because Duration tops out at u64::MAX
  seconds. Only the final value saturates, and the sub-100ns floor stays.
- the evictor claims the per-sandbox operation lock with try_lock and
  defers the entry to the next pass when another operation owns that
  sandbox, so the pause permit is never held while waiting for that lock.
- tests: the queued-pause and evictor-delete regressions synchronize on a
  test-only queue-entry signal instead of polling loops or fixed sleeps;
  new regressions cover the large-timeout scaling and the deferred
  eviction entry.

Refs kvcache-ai#506

Signed-off-by: yjjnls <yjjnls@users.noreply.github.com>
Comment thread src/cfg.rs
Comment on lines +1544 to +1546
fn validate_bounds_ttl_jitter_percent() {
// Defaults ship with the batch pause-shaping knobs disabled.
let config = AppConfig::default();

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
This only exercises a manually constructed AppConfig; it does not prove that the newly documented TOML keys (or their environment overrides) deserialize into these fields. A loader-level test should parse a minimal config containing both keys and assert the resulting values, especially since the default-file test only checks that parsing succeeds.

Suggestion:

Suggested change
fn validate_bounds_ttl_jitter_percent() {
// Defaults ship with the batch pause-shaping knobs disabled.
let config = AppConfig::default();
fn validate_bounds_ttl_jitter_percent() {
// Defaults ship with the batch pause-shaping knobs disabled.
let config = AppConfig::default();

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 42d339c: pause_shaping_keys_load_from_toml writes a minimal TOML with [orchestrator] pause_concurrency_limit = 7 / ttl_jitter_percent = 25, loads it through ConfigManager::new_from_path, asserts the resolved field values, and validates the result. Neither key declares an environment override, so the file is the only external source; the defaults-off assertions stay in validate_bounds_ttl_jitter_percent.

Comment on lines +1539 to +1542
#[cfg(test)]
if semaphore.available_permits() == 0 {
self.pause_queue_entered.notify_one();
}

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
available_permits() == 0 does not mean this particular caller has entered the semaphore's wait queue: another task may consume/release a permit between this check and acquire_owned(), and notify_one() can be consumed by a different queued pause. Tests waiting on this notification can therefore proceed before their target is actually queued (or miss the notification and time out). Prefer an explicit test hook around the actual acquire future/queueing path, or make the notification identify the operation being synchronized.

Suggestion:

Suggested change
#[cfg(test)]
if semaphore.available_permits() == 0 {
self.pause_queue_entered.notify_one();
}
#[cfg(test)]
if semaphore.available_permits() == 0 {
self.pause_queue_entered.notify_one();
}

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 42d339c: the notification now identifies the operation. pause_queue_entered is a #[cfg(test)] broadcast channel keyed by sandbox id, fired by acquire_pause_slot(sandbox_id) when the semaphore is exhausted; both regressions subscribe before starting their operation and wait for their own id, so an unrelated pause's entry cannot satisfy them. On the check/acquire race: the check is synchronous with constructing the acquire future (no await point between), and each of these tests holds the sole permit for the duration, so no competing consumer exists — the event means this sandbox is at the queue entry under exhaustion. The hook stays test-only (#[cfg(test)] field; production builds pay nothing).

Comment on lines +2499 to +2502
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.

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.

…ading

Addresses the sixth open-code-review round on the batch pause shaping:

- the test-only queue-entry hook is now a broadcast keyed by sandbox id
  (pause_queue_entered) instead of a bare Notify; the two regressions
  subscribe before their operation and wait for their own id, so a
  notification cannot be consumed by an unrelated pause.
- a file-loader test pins that the documented pause-shaping keys
  deserialize from a minimal TOML and that the loaded values validate;
  neither key declares an environment override.

The eviction-scheduler suggestion (spawn/queue pause work) is recorded for
human review rather than changed here: delete entries are already claimed
before pause entries each pass, the serial eviction pass predates the
shaping, and detaching pause work would break the synchronous eviction
contract (evict_expired_sandboxes reports only after each claimed
operation completes).

Refs kvcache-ai#506

Signed-off-by: yjjnls <yjjnls@users.noreply.github.com>
@yjjnls

yjjnls commented Nov 19, 2026

Copy link
Copy Markdown
Author

Six review rounds processed on this branch — summary for the human reviewer. State: head 42d339c, mergeable, all suites green.

Round-by-round dispositions (every finding has an inline reply with commit hash and regression name):

  • R1 (7 findings, fix 6b6d201): 1 ns floor for non-zero sub-100 ns TTLs, documented pause-limit clamp, test helper mirrors the production 0 => unlimited mapping.
  • R2 (3, fix 16f5fde): slot reserved before claiming Pausing on both claim sites and released before joining a conflict; EnsureMinimum candidates jittered (clamped to the minimum); cohort-spread test made deterministic.
  • R3 (3, fix fe72e54): eviction deletes independent of the pause queue; reported resume double-jitter did not reproduce (exactly-once regression added); create-test probabilistic assertion removed.
  • R4 (4, fix 2ac576d): duplicate pauses probe state before queueing; deletes claimed before pause entries each pass; pause-limit mapping extracted with boundary + TOML-loader tests; evictor lock-ordering answered with evidence (shared-lock serialization is pre-existing design).
  • R5 (5, fix 6eca741): jittered_ttl scales exactly in u128 (no intermediate saturation for large TTLs); evictor defers on per-sandbox lock contention via try_lock; the two timing-based tests synchronized on the queue-entry hook.
  • R6 (3, fix 42d339c): TOML loader test for both keys; queue-entry hook keyed by sandbox id; eviction-scheduler detaching = design-level, deferred with rationale.

Verification: cargo test --lib 1076 passed / 0 failed; cargo clippy -p agentenv --all-targets --all-features -- -D warnings clean; cargo fmt --check clean. Every behavioral regression (10 cases) was verified to fail on the pre-fix code before being accepted.

Open item for maintainers: whether pause work in the eviction loop should be detached (spawned) instead of awaited inline. Current behavior keeps evict_expired_sandboxes synchronous — it reports an id only after that sandbox's pause snapshot exists — and claims delete entries before pause entries each pass. I did not change that contract unilaterally; happy to follow up if detached pause work is desired.

Requesting human review; will keep iterating on any concrete defect.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant