Skip to content

Commit 098b69c

Browse files
committed
fix(server): bound the provisioning-deadline scan's lock wait
The provisioning-deadline scan takes each provisioning sandbox's local S(global) S(workspace) X(sandbox) keys in ascending key order and waited for them with no deadline. When a sandbox's key sorts before its workspace's key, the scan held X(sandbox) while it waited behind a provider or profile writer, so start, stop and delete for that sandbox waited for the writer too. In the other order, the scan held S(workspace) while it waited for a busy sandbox, and provider writers on that workspace queued behind it. Either way the rest of the pass waited as well. Each pass now has a 500 ms budget for waiting on these keys. A sandbox whose keys stay busy is skipped and picked up on the next pass a second later. Once the budget is spent, the rest of the pass only takes keys that are free when it reaches them, so a busy workspace or global key costs one wait per pass rather than one per sandbox. The local acquisition is cancel-safe, so giving up releases the keys it already took. Skips log at debug and count in the new openshell_server_provisioning_deadline_skips_total counter, labeled by whether the sandbox was already past its deadline. A steady rate of delayed expiries can then be alerted on without a warning every pass. The gateway metrics page and the cluster debugging skill describe it. The test that pinned the old wait is replaced by tests for both key orders: a lifecycle lock or a provider writer proceeds and the scan finishes while the other side holds its key, the skipped sandbox is untouched and expires once the writer releases, and a skip doesn't end the pass for other sandboxes. Another test checks that sandboxes behind one busy workspace share a single wait. Part of #4307 Closes #4547 Signed-off-by: Emilien Macchi <emacchi@redhat.com>
1 parent a4c848a commit 098b69c

7 files changed

Lines changed: 337 additions & 16 deletions

File tree

‎crates/openshell-server/src/compute/mod.rs‎

Lines changed: 254 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18876,40 +18876,283 @@ mod tests {
1887618876
}
1887718877

1887818878
#[tokio::test]
18879-
async fn provisioning_reconcile_waits_for_a_local_workspace_writer() {
18879+
async fn provisioning_reconcile_skips_a_sandbox_behind_a_workspace_writer() {
18880+
use crate::gateway_metrics::MetricsCapture;
18881+
use crate::persistence::MutationLockKey;
18882+
let metrics = MetricsCapture::install();
1888018883
let runtime = test_runtime(ControlledDriver::new()).await;
18884+
// Keys are taken in ascending order. With the sandbox key first, the
18885+
// scan holds X(sandbox) while it waits for S(workspace).
18886+
let workspace_key = MutationLockKey::Workspace("default").advisory_key();
18887+
let sandbox_id = (0..1000)
18888+
.map(|i| format!("sb-ws-writer-{i}"))
18889+
.find(|id| MutationLockKey::Sandbox(id).advisory_key() < workspace_key)
18890+
.expect("a sandbox key that sorts before the workspace key");
18891+
let sandbox_key = MutationLockKey::Sandbox(&sandbox_id).advisory_key();
1888118892
runtime
1888218893
.store
1888318894
.put_message(&sandbox_record(
18884-
"sb-ws-writer",
18895+
&sandbox_id,
1888518896
"ws-writer",
1888618897
SandboxPhase::Provisioning,
1888718898
))
1888818899
.await
1888918900
.unwrap();
18901+
let now = openshell_core::time::now_ms();
18902+
runtime.reconcile_provisioning_deadlines(now).await.unwrap();
18903+
1889018904
// Reconcile re-derives configuration from provider and profile
18891-
// records, so it waits for their writers, which hold X(workspace).
18905+
// records, so it must not run under their writers, which hold
18906+
// X(workspace).
1889218907
let writer = runtime
1889318908
.mutation_guard(MutationScope::Workspace("default"))
1889418909
.await
1889518910
.unwrap();
18896-
let mut reconcile = {
18911+
let reconcile = {
1889718912
let runtime = runtime.clone();
18898-
let now = openshell_core::time::now_ms();
18899-
tokio::spawn(async move { runtime.reconcile_provisioning_deadlines(now).await })
18913+
tokio::spawn(async move {
18914+
runtime
18915+
.reconcile_provisioning_deadlines(now + 300_000)
18916+
.await
18917+
})
1890018918
};
18901-
assert!(
18902-
tokio::time::timeout(Duration::from_millis(100), &mut reconcile)
18919+
tokio::time::timeout(Duration::from_secs(5), async {
18920+
while runtime.mutation_locks.key_references(sandbox_key) == 0
18921+
|| runtime.mutation_locks.key_references(workspace_key) < 2
18922+
{
18923+
tokio::task::yield_now().await;
18924+
}
18925+
})
18926+
.await
18927+
.expect("the scan holds the sandbox key and waits for the workspace key");
18928+
18929+
// Start, stop, and delete take the sandbox key; they must not wait
18930+
// for the writer through the scan.
18931+
let lifecycle = {
18932+
let runtime = runtime.clone();
18933+
let sandbox_id = sandbox_id.clone();
18934+
tokio::spawn(async move { drop(runtime.lock_sandbox_local(&sandbox_id).await) })
18935+
};
18936+
tokio::time::timeout(Duration::from_secs(5), lifecycle)
18937+
.await
18938+
.expect("a lifecycle lock proceeds while the writer holds the workspace")
18939+
.unwrap();
18940+
tokio::time::timeout(Duration::from_secs(5), reconcile)
18941+
.await
18942+
.expect("the scan skips the busy sandbox instead of waiting for the writer")
18943+
.unwrap()
18944+
.unwrap();
18945+
assert_eq!(runtime.mutation_locks.key_references(sandbox_key), 0);
18946+
assert_eq!(
18947+
metrics.value("openshell_server_provisioning_deadline_skips_total{overdue=\"true\"}"),
18948+
Some(1),
18949+
"the sandbox was past its deadline when the scan skipped it"
18950+
);
18951+
let skipped = runtime
18952+
.store
18953+
.get_message::<Sandbox>(&sandbox_id)
18954+
.await
18955+
.unwrap()
18956+
.unwrap();
18957+
assert_eq!(skipped.phase(), i32::from(SandboxPhase::Provisioning));
18958+
18959+
drop(writer);
18960+
runtime
18961+
.reconcile_provisioning_deadlines(now + 300_000)
18962+
.await
18963+
.unwrap();
18964+
let expired = runtime
18965+
.store
18966+
.get_message::<Sandbox>(&sandbox_id)
18967+
.await
18968+
.unwrap()
18969+
.unwrap();
18970+
assert_eq!(expired.phase(), i32::from(SandboxPhase::Error));
18971+
}
18972+
18973+
#[tokio::test]
18974+
async fn provisioning_reconcile_continues_past_a_skipped_sandbox() {
18975+
let runtime = test_runtime(ControlledDriver::new()).await;
18976+
// The scan orders by insert time, then name: the busy sandbox is stored
18977+
// first and named first, so a skip that ended the pass would leave the
18978+
// other sandbox alone.
18979+
let busy = sandbox_record("sb-skip-busy", "a-busy", SandboxPhase::Provisioning);
18980+
let mut other = sandbox_record("sb-skip-other", "b-other", SandboxPhase::Provisioning);
18981+
other.metadata.as_mut().unwrap().workspace = "alpha".to_string();
18982+
runtime.store.put_message(&busy).await.unwrap();
18983+
runtime.store.put_message(&other).await.unwrap();
18984+
let now = openshell_core::time::now_ms();
18985+
runtime.reconcile_provisioning_deadlines(now).await.unwrap();
18986+
18987+
let writer = runtime
18988+
.mutation_guard(MutationScope::Workspace("default"))
18989+
.await
18990+
.unwrap();
18991+
// Spawned: the lock-order check forbids nesting under the writer in this task.
18992+
let reconcile = {
18993+
let runtime = runtime.clone();
18994+
tokio::spawn(async move {
18995+
runtime
18996+
.reconcile_provisioning_deadlines(now + 300_000)
18997+
.await
18998+
})
18999+
};
19000+
tokio::time::timeout(Duration::from_secs(5), reconcile)
19001+
.await
19002+
.expect("the scan skips the busy sandbox instead of waiting for the writer")
19003+
.unwrap()
19004+
.unwrap();
19005+
let skipped = runtime
19006+
.store
19007+
.get_message::<Sandbox>("sb-skip-busy")
19008+
.await
19009+
.unwrap()
19010+
.unwrap();
19011+
assert_eq!(skipped.phase(), i32::from(SandboxPhase::Provisioning));
19012+
let expired = runtime
19013+
.store
19014+
.get_message::<Sandbox>("sb-skip-other")
19015+
.await
19016+
.unwrap()
19017+
.unwrap();
19018+
assert_eq!(
19019+
expired.phase(),
19020+
i32::from(SandboxPhase::Error),
19021+
"a skipped sandbox must not end the pass"
19022+
);
19023+
drop(writer);
19024+
}
19025+
19026+
#[tokio::test]
19027+
async fn provisioning_reconcile_waits_once_per_pass_behind_a_busy_workspace() {
19028+
use super::provisioning_deadline::SCAN_LOCK_WAIT_BUDGET;
19029+
use crate::gateway_metrics::MetricsCapture;
19030+
let metrics = MetricsCapture::install();
19031+
let runtime = test_runtime(ControlledDriver::new()).await;
19032+
let ids: Vec<String> = (0..6).map(|i| format!("sb-budget-{i}")).collect();
19033+
for (i, id) in ids.iter().enumerate() {
19034+
runtime
19035+
.store
19036+
.put_message(&sandbox_record(
19037+
id,
19038+
&format!("budget-{i}"),
19039+
SandboxPhase::Provisioning,
19040+
))
1890319041
.await
18904-
.is_err(),
18905-
"provisioning reconcile must wait for the workspace writer"
19042+
.unwrap();
19043+
}
19044+
let now = openshell_core::time::now_ms();
19045+
runtime.reconcile_provisioning_deadlines(now).await.unwrap();
19046+
19047+
// Every sandbox needs S(workspace), which the writer holds.
19048+
let writer = runtime
19049+
.mutation_guard(MutationScope::Workspace("default"))
19050+
.await
19051+
.unwrap();
19052+
let started = tokio::time::Instant::now();
19053+
// Spawned: the lock-order check forbids nesting under the writer in this task.
19054+
let reconcile = {
19055+
let runtime = runtime.clone();
19056+
tokio::spawn(async move { runtime.reconcile_provisioning_deadlines(now + 1_000).await })
19057+
};
19058+
tokio::time::timeout(Duration::from_secs(10), reconcile)
19059+
.await
19060+
.expect("the scan finishes while the writer holds the workspace")
19061+
.unwrap()
19062+
.unwrap();
19063+
let waited = started.elapsed();
19064+
assert!(
19065+
waited < SCAN_LOCK_WAIT_BUDGET * 4,
19066+
"one wait per sandbox would take {:?}; the pass took {waited:?}",
19067+
SCAN_LOCK_WAIT_BUDGET * 6
19068+
);
19069+
assert_eq!(
19070+
metrics.value("openshell_server_provisioning_deadline_skips_total{overdue=\"false\"}"),
19071+
Some(6)
1890619072
);
19073+
for id in &ids {
19074+
let skipped = runtime
19075+
.store
19076+
.get_message::<Sandbox>(id)
19077+
.await
19078+
.unwrap()
19079+
.unwrap();
19080+
assert_eq!(skipped.phase(), i32::from(SandboxPhase::Provisioning));
19081+
}
1890719082
drop(writer);
19083+
}
19084+
19085+
#[tokio::test]
19086+
async fn provisioning_reconcile_releases_the_workspace_behind_a_busy_sandbox() {
19087+
use crate::persistence::MutationLockKey;
19088+
let runtime = test_runtime(ControlledDriver::new()).await;
19089+
// With the workspace key first, the scan holds S(workspace) while it
19090+
// waits for X(sandbox), and a provider writer queues behind the scan.
19091+
let workspace_key = MutationLockKey::Workspace("default").advisory_key();
19092+
let sandbox_id = (0..1000)
19093+
.map(|i| format!("sb-busy-{i}"))
19094+
.find(|id| MutationLockKey::Sandbox(id).advisory_key() > workspace_key)
19095+
.expect("a sandbox key that sorts after the workspace key");
19096+
let sandbox_key = MutationLockKey::Sandbox(&sandbox_id).advisory_key();
19097+
runtime
19098+
.store
19099+
.put_message(&sandbox_record(
19100+
&sandbox_id,
19101+
"busy",
19102+
SandboxPhase::Provisioning,
19103+
))
19104+
.await
19105+
.unwrap();
19106+
let now = openshell_core::time::now_ms();
19107+
runtime.reconcile_provisioning_deadlines(now).await.unwrap();
19108+
19109+
let lifecycle = runtime.lock_sandbox_local(&sandbox_id).await;
19110+
let reconcile = {
19111+
let runtime = runtime.clone();
19112+
tokio::spawn(async move {
19113+
runtime
19114+
.reconcile_provisioning_deadlines(now + 300_000)
19115+
.await
19116+
})
19117+
};
19118+
tokio::time::timeout(Duration::from_secs(5), async {
19119+
while runtime.mutation_locks.key_references(workspace_key) == 0
19120+
|| runtime.mutation_locks.key_references(sandbox_key) < 2
19121+
{
19122+
tokio::task::yield_now().await;
19123+
}
19124+
})
19125+
.await
19126+
.expect("the scan holds the workspace key and waits for the sandbox key");
19127+
19128+
let writer = {
19129+
let runtime = runtime.clone();
19130+
tokio::spawn(async move {
19131+
drop(
19132+
runtime
19133+
.mutation_guard(MutationScope::Workspace("default"))
19134+
.await
19135+
.unwrap(),
19136+
);
19137+
})
19138+
};
19139+
tokio::time::timeout(Duration::from_secs(5), writer)
19140+
.await
19141+
.expect("a provider writer proceeds while the sandbox is busy")
19142+
.unwrap();
1890819143
tokio::time::timeout(Duration::from_secs(5), reconcile)
1890919144
.await
18910-
.expect("provisioning reconcile proceeds once the writer releases")
19145+
.expect("the scan skips the busy sandbox instead of waiting for it")
19146+
.unwrap()
19147+
.unwrap();
19148+
drop(lifecycle);
19149+
let skipped = runtime
19150+
.store
19151+
.get_message::<Sandbox>(&sandbox_id)
19152+
.await
1891119153
.unwrap()
1891219154
.unwrap();
19155+
assert_eq!(skipped.phase(), i32::from(SandboxPhase::Provisioning));
1891319156
}
1891419157

1891519158
#[tokio::test]

‎crates/openshell-server/src/compute/mutation_guard.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,11 @@ impl ComputeRuntime {
452452
/// Local S(global) S(workspace) X(sandbox), for provisioning-deadline
453453
/// reconciliation, which re-derives configuration from provider and
454454
/// profile records and must not interleave with their local writers.
455+
///
456+
/// The wait is unbounded. When the sandbox key sorts first, the caller
457+
/// holds X(sandbox) while it waits behind a workspace writer, so a
458+
/// background caller should bound the wait with a timeout; dropping the
459+
/// future releases the keys already taken.
455460
pub(super) async fn lock_sandbox_local_in_workspace(
456461
&self,
457462
workspace: &str,

‎crates/openshell-server/src/compute/provisioning_deadline.rs‎

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,16 @@ use serde::{Deserialize, Serialize};
1414

1515
const REPAIR_WINDOW_MS: i64 = 300_000;
1616

17+
/// How long one scan pass waits, in total, for sandboxes' local keys. A sandbox
18+
/// whose keys are still busy is skipped until the next pass. Keys are taken in
19+
/// ascending order, so the scan can hold X(sandbox) while it waits for
20+
/// S(workspace) behind a provider or profile writer, and the sandbox's
21+
/// lifecycle operations wait behind the scan. Once the budget is spent, the
22+
/// rest of the pass waits about a timer tick for each sandbox's keys, so a
23+
/// busy workspace or global key costs one wait per pass, not one per sandbox.
24+
/// Well under the mutation lock timeout.
25+
pub(super) const SCAN_LOCK_WAIT_BUDGET: std::time::Duration = std::time::Duration::from_millis(500);
26+
1727
/// Opaque identity of a committed effective configuration change. A -> B -> A
1828
/// must use three different IDs even if the first and last content hashes match.
1929
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -456,6 +466,7 @@ impl super::ComputeRuntime {
456466
.collect_records(Sandbox::object_type(), ObjectListQuery::AllWorkspaces)
457467
.await
458468
.map_err(|error| error.to_string())?;
469+
let mut lock_wait_left = SCAN_LOCK_WAIT_BUDGET;
459470
for record in records {
460471
let candidate =
461472
Sandbox::decode(record.payload.as_slice()).map_err(|error| error.to_string())?;
@@ -469,9 +480,35 @@ impl super::ComputeRuntime {
469480
// Expiration can fence Starting while its driver RPC owns the
470481
// lifecycle gate. Cleanup waits for that gate; Error never waits
471482
// for compute I/O, matching the existing driver-observation fence.
472-
let local_guard = self
473-
.lock_sandbox_local_in_workspace(candidate.object_workspace(), &record.id)
474-
.await;
483+
// A timed-out acquisition releases the keys it already took. With
484+
// no budget left, the timeout still polls the keys before its timer
485+
// fires, and unlike `now_or_never` it yields instead of skipping
486+
// free keys when the task's coop budget is spent.
487+
let wait_started = tokio::time::Instant::now();
488+
let acquired = tokio::time::timeout(
489+
lock_wait_left,
490+
self.lock_sandbox_local_in_workspace(candidate.object_workspace(), &record.id),
491+
)
492+
.await;
493+
lock_wait_left = lock_wait_left.saturating_sub(wait_started.elapsed());
494+
let Ok(local_guard) = acquired else {
495+
// Brief contention is routine; a skip past the deadline delays
496+
// expiry. The counter shows both without a warning per pass.
497+
let overdue = candidate
498+
.status
499+
.as_ref()
500+
.and_then(|status| status.provisioning.as_ref())
501+
.and_then(|record| record.deadline.as_ref())
502+
.and_then(|deadline| timestamp_to_millis(deadline).ok())
503+
.is_some_and(|deadline| deadline <= now_ms);
504+
crate::gateway_metrics::record_provisioning_deadline_skip(overdue);
505+
tracing::debug!(
506+
sandbox_id = %record.id,
507+
overdue,
508+
"Provisioning deadline scan skipped a sandbox whose locks are busy"
509+
);
510+
continue;
511+
};
475512
let Some(mut current) = self
476513
.store
477514
.get_message::<Sandbox>(&record.id)

0 commit comments

Comments
 (0)