Skip to content

Commit 189a96a

Browse files
committed
feat(server): time mutation lock holds and test a stalled holder
Nothing bounds how long a mutation guard is held, so a holder stuck in a compute driver, credential backend or middleware call keeps its scope locked while waiters time out. Each guard now records its hold in openshell_server_mutation_lock_hold_seconds{scope} when it is released, and logs a warning when the hold outlasted the lock wait timeout, so operators can find the replica and scope behind those timeouts. A PostgreSQL test with a stalled holder pins the current contract: waiters on its sandbox, workspace and global scopes fail by their deadline, other scopes proceed, the holder keeps its key, and a full lock pool on one replica leaves the other working. The metrics catalog, the HA guide and the debug skill describe the new signals, which observe holds without bounding them. Part of #3528 Signed-off-by: Emilien Macchi <emacchi@redhat.com>
1 parent 05babe4 commit 189a96a

6 files changed

Lines changed: 305 additions & 11 deletions

File tree

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

Lines changed: 139 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -279,13 +279,37 @@ pub struct LocalMutationGuard {
279279
/// Local and, on `PostgreSQL`, distributed keys of one guarded mutation.
280280
#[must_use = "dropping the guard releases the mutation locks"]
281281
pub struct MutationGuard {
282-
// Field order is drop order: the database guard goes first so its
283-
// connection returns to the lock pool (and is unlocked) as early as
284-
// possible.
282+
// Field order is drop order: the hold is recorded while the keys are
283+
// still held, then the database guard goes so its connection returns to
284+
// the lock pool (and is unlocked) as early as possible.
285+
_hold: HoldTimer,
285286
_distributed: DistributedMutationGuard,
286287
_local: LocalMutationGuard,
287288
}
288289

290+
/// Times one [`MutationGuard`] from acquisition to release. Guarded work has
291+
/// no time limit of its own, so a hold longer than the wait timeout means
292+
/// conflicting acquisitions may have timed out behind it.
293+
struct HoldTimer {
294+
scope: LockScope,
295+
acquired: tokio::time::Instant,
296+
warn_after: Duration,
297+
}
298+
299+
impl Drop for HoldTimer {
300+
fn drop(&mut self) {
301+
let held = self.acquired.elapsed();
302+
gateway_metrics::record_lock_hold(self.scope, held);
303+
if held > self.warn_after {
304+
warn!(
305+
scope = self.scope.label(),
306+
held_ms = duration_millis(held),
307+
"mutation lock held longer than the lock wait timeout"
308+
);
309+
}
310+
}
311+
}
312+
289313
impl ComputeRuntime {
290314
/// Serialize a cross-object mutation against every conflicting mutation
291315
/// on this and, on `PostgreSQL`, every other replica.
@@ -298,14 +322,23 @@ impl ComputeRuntime {
298322
/// left fails with [`PersistenceError::Database`]. Timeouts count in
299323
/// `openshell_server_mutation_lock_timeouts_total` and other failures in
300324
/// `openshell_server_mutation_lock_errors_total`.
325+
///
326+
/// Nothing bounds how long the guard is held. Dropping it records the
327+
/// hold in `openshell_server_mutation_lock_hold_seconds`, and logs a
328+
/// warning when the hold outlasted the wait timeout.
301329
pub(crate) async fn mutation_guard(
302330
&self,
303331
scope: MutationScope<'_>,
304332
) -> PersistenceResult<MutationGuard> {
305333
let started = tokio::time::Instant::now();
306-
let deadline = started + self.mutation_locks.timeout();
334+
let timeout = self.mutation_locks.timeout();
307335
let result = self
308-
.acquire_mutation_guard(&scope.lock_set(), deadline)
336+
.acquire_mutation_guard(
337+
&scope.lock_set(),
338+
started + timeout,
339+
scope.lock_scope(),
340+
timeout,
341+
)
309342
.await;
310343
match &result {
311344
Ok(_) => gateway_metrics::record_lock_wait(scope.lock_scope(), started.elapsed()),
@@ -331,10 +364,14 @@ impl ComputeRuntime {
331364
result
332365
}
333366

367+
/// Acquire `set` by `deadline`. The guard's hold is labeled `scope` and
368+
/// warns past `warn_after`.
334369
async fn acquire_mutation_guard(
335370
&self,
336371
set: &MutationLockSet,
337372
deadline: tokio::time::Instant,
373+
scope: LockScope,
374+
warn_after: Duration,
338375
) -> PersistenceResult<MutationGuard> {
339376
let local = tokio::time::timeout_at(deadline, self.mutation_locks.acquire(set))
340377
.await
@@ -346,6 +383,11 @@ impl ComputeRuntime {
346383
.acquire_distributed_mutation_guard(set, deadline)
347384
.await?;
348385
Ok(MutationGuard {
386+
_hold: HoldTimer {
387+
scope,
388+
acquired: tokio::time::Instant::now(),
389+
warn_after,
390+
},
349391
_distributed: distributed,
350392
_local: local,
351393
})
@@ -870,6 +912,98 @@ mod tests {
870912
assert_eq!(metrics.value(ERRORS), Some(1));
871913
}
872914

915+
/// Formatted log output of the current thread's tracing subscriber.
916+
#[derive(Clone, Default)]
917+
struct LogLines(Arc<StdMutex<Vec<u8>>>);
918+
919+
impl LogLines {
920+
fn count(&self, message: &str) -> usize {
921+
String::from_utf8_lossy(&self.0.lock().unwrap())
922+
.matches(message)
923+
.count()
924+
}
925+
}
926+
927+
impl std::io::Write for LogLines {
928+
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
929+
self.0.lock().unwrap().extend_from_slice(buf);
930+
Ok(buf.len())
931+
}
932+
933+
fn flush(&mut self) -> std::io::Result<()> {
934+
Ok(())
935+
}
936+
}
937+
938+
#[tokio::test]
939+
async fn lock_hold_is_recorded_when_a_stalled_guard_is_released() {
940+
const HOLDS: &str = "openshell_server_mutation_lock_hold_seconds_count{scope=\"sandbox\"}";
941+
// Holds no longer than the 50 ms wait timeout.
942+
const SHORT_HOLDS: &str =
943+
"openshell_server_mutation_lock_hold_seconds_bucket{scope=\"sandbox\",le=\"0.05\"}";
944+
const HELD_TOO_LONG: &str = "mutation lock held longer than the lock wait timeout";
945+
let metrics = MetricsCapture::install();
946+
let logs = LogLines::default();
947+
let _logs = crate::otel_tracing::test_exporter::install_scoped(
948+
tracing_subscriber::fmt()
949+
.with_writer({
950+
let logs = logs.clone();
951+
move || logs.clone()
952+
})
953+
.with_ansi(false)
954+
.finish(),
955+
);
956+
let runtime = test_runtime().await;
957+
let timeout = Duration::from_millis(50);
958+
runtime.set_mutation_lock_timeout_for_tests(timeout);
959+
960+
drop(
961+
runtime
962+
.mutation_guard(MutationScope::sandbox("w", "a"))
963+
.await
964+
.unwrap(),
965+
);
966+
assert_eq!(metrics.value(HOLDS), Some(1));
967+
assert_eq!(metrics.value(SHORT_HOLDS), Some(1));
968+
assert_eq!(logs.count(HELD_TOO_LONG), 0, "a short hold does not warn");
969+
970+
// A stalled holder: a waiter on its scope times out behind it, and the
971+
// hold is recorded only once the holder releases.
972+
let stalled = runtime
973+
.mutation_guard(MutationScope::sandbox("w", "a"))
974+
.await
975+
.unwrap();
976+
let waiter = {
977+
let runtime = runtime.clone();
978+
tokio::spawn(async move {
979+
runtime
980+
.mutation_guard(MutationScope::sandbox("w", "a"))
981+
.await
982+
.map(drop)
983+
})
984+
};
985+
let result = waiter.await.expect("waiter task");
986+
assert!(
987+
matches!(result, Err(PersistenceError::LockTimeout(_))),
988+
"{result:?}"
989+
);
990+
tokio::time::sleep(timeout).await;
991+
assert_eq!(
992+
metrics.value(HOLDS),
993+
Some(1),
994+
"a failed acquisition holds nothing"
995+
);
996+
997+
drop(stalled);
998+
assert_eq!(metrics.value(HOLDS), Some(2));
999+
assert_eq!(
1000+
metrics.value(SHORT_HOLDS),
1001+
Some(1),
1002+
"the stalled hold outlasted the wait timeout"
1003+
);
1004+
assert_eq!(logs.count(HELD_TOO_LONG), 1);
1005+
}
1006+
8731007
/// Workspaces and sandboxes the random scope mix draws from.
8741008
const MIX_WORKSPACES: usize = 3;
8751009
const MIX_SANDBOXES: usize = 8;

‎crates/openshell-server/src/gateway_metrics.rs‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ pub const MUTATION_LOCK_ERRORS_TOTAL: &str = "openshell_server_mutation_lock_err
3939
pub const RELAY_CLAIM_DURATION_SECONDS: &str = "openshell_server_relay_claim_duration_seconds";
4040
pub const PEER_REQUEST_DURATION_SECONDS: &str = "openshell_server_peer_request_duration_seconds";
4141
pub const MUTATION_LOCK_WAIT_SECONDS: &str = "openshell_server_mutation_lock_wait_seconds";
42+
pub const MUTATION_LOCK_HOLD_SECONDS: &str = "openshell_server_mutation_lock_hold_seconds";
4243

4344
const LABEL_REASON: &str = "reason";
4445
const LABEL_OPERATION: &str = "operation";
@@ -56,10 +57,11 @@ const LATENCY_BUCKETS_SECONDS: [f64; 14] = [
5657

5758
/// Only these names render as Prometheus histograms. Every existing `*_duration_seconds` metric
5859
/// keeps its summary format, so current dashboards are unaffected.
59-
const BUCKETED_HISTOGRAMS: [&str; 3] = [
60+
const BUCKETED_HISTOGRAMS: [&str; 4] = [
6061
RELAY_CLAIM_DURATION_SECONDS,
6162
PEER_REQUEST_DURATION_SECONDS,
6263
MUTATION_LOCK_WAIT_SECONDS,
64+
MUTATION_LOCK_HOLD_SECONDS,
6365
];
6466

6567
/// Protocol the supervisor is asked to relay. Never label metrics with the target address.
@@ -301,6 +303,11 @@ pub fn describe_and_initialize(relay: RelayCapacity, mutation_lock_connections:
301303
Unit::Seconds,
302304
"Time spent acquiring the mutation lock for a scope."
303305
);
306+
describe_histogram!(
307+
MUTATION_LOCK_HOLD_SECONDS,
308+
Unit::Seconds,
309+
"Time a mutation lock was held, from acquisition to release, including requests cancelled while holding it."
310+
);
304311

305312
// `increment(0)` registers a series without overwriting a value recorded earlier.
306313
gauge!(SUPERVISOR_SESSIONS).increment(0.0);
@@ -419,6 +426,12 @@ pub fn record_lock_wait(scope: LockScope, waited: Duration) {
419426
histogram!(MUTATION_LOCK_WAIT_SECONDS, LABEL_SCOPE => scope.label()).record(waited);
420427
}
421428

429+
/// How long one mutation guard was held, recorded when it is released. Holds longer than the
430+
/// top bucket count only in `+Inf`; the hold warning logs their duration.
431+
pub fn record_lock_hold(scope: LockScope, held: Duration) {
432+
histogram!(MUTATION_LOCK_HOLD_SECONDS, LABEL_SCOPE => scope.label()).record(held);
433+
}
434+
422435
/// A guard acquisition that timed out: a local wait, a full lock pool, too little time left to
423436
/// open a lock connection, or Postgres `lock_timeout` (SQLSTATE 55P03). A lock connection that
424437
/// Postgres does not open with at least `LOCK_CONNECTION_MIN_BUDGET` left counts in
@@ -719,6 +732,7 @@ mod tests {
719732
)
720733
.record(sample);
721734
histogram!(MUTATION_LOCK_WAIT_SECONDS, LABEL_SCOPE => "sandbox").record(sample);
735+
histogram!(MUTATION_LOCK_HOLD_SECONDS, LABEL_SCOPE => "sandbox").record(sample);
722736
histogram!(
723737
"openshell_server_grpc_request_duration_seconds",
724738
"method" => "ListSandboxes",

‎crates/openshell-server/src/persistence/mutation_lock_pg_tests.rs‎

Lines changed: 121 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33

44
//! `PostgreSQL` tests of the mutation advisory locks: exclusion between two
55
//! stores (as between two gateway replicas), exclusion against the legacy
6-
//! global key, cleanup after timed-out and cancelled acquisitions, the
7-
//! lock-pool bound and its in-use gauge, and lock connections that
6+
//! global key, cleanup after timed-out and cancelled acquisitions, a stalled
7+
//! holder, the lock-pool bound and its in-use gauge, and lock connections that
88
//! `PostgreSQL` does not open.
99
//!
1010
//! Advisory locks are database-wide, not per schema, so every test uses
@@ -1077,6 +1077,125 @@ async fn postgres_mutation_lock_connections_gauge_tracks_checked_out_connections
10771077
fixture.finish(vec![store]).await;
10781078
}
10791079

1080+
#[tokio::test]
1081+
#[ignore = "requires a disposable PostgreSQL database in OPENSHELL_TEST_POSTGRES_URL; run mise run test:rust:postgres"]
1082+
async fn postgres_mutation_lock_stalled_holder_fails_waiters_by_their_deadline() {
1083+
let fixture = LockFixture::new().await;
1084+
let store_a = fixture.store(MUTATION_LOCK_POOL_MAX_CONNECTIONS).await;
1085+
let store_b = fixture.store(MUTATION_LOCK_POOL_MAX_CONNECTIONS).await;
1086+
let workspace = random_id("ws");
1087+
let stalled = random_id("sb");
1088+
1089+
// Nothing bounds a hold, so this holder keeps its locks until the test
1090+
// drops it, like one blocked in a compute driver or middleware call.
1091+
let holder = acquire_proceeds(
1092+
&store_a,
1093+
MutationScope::sandbox(&workspace, &stalled),
1094+
"the stalled holder",
1095+
)
1096+
.await;
1097+
1098+
// Waiters that conflict with it on the other store fail with
1099+
// PostgreSQL's lock timeout by their own deadline. They run one at a
1100+
// time, so a queued exclusive request cannot hold up the next one.
1101+
for (scope, what) in [
1102+
(
1103+
MutationScope::sandbox(&workspace, &stalled),
1104+
"the stalled sandbox",
1105+
),
1106+
(
1107+
MutationScope::Workspace(&workspace),
1108+
"the stalled sandbox's workspace",
1109+
),
1110+
(MutationScope::Global, "the global scope"),
1111+
] {
1112+
wait_for_idle_lock_connection(&store_b).await;
1113+
let started = Instant::now();
1114+
acquire_times_out(&store_b, scope, what).await;
1115+
let waited = started.elapsed();
1116+
assert!(
1117+
waited < EXPECTED_TIMEOUT + CLIENT_BACKSTOP_GRACE,
1118+
"{what}: failed after {waited:?}"
1119+
);
1120+
}
1121+
drop(
1122+
acquire_proceeds(
1123+
&store_b,
1124+
MutationScope::sandbox(&workspace, &random_id("sb")),
1125+
"another sandbox in the stalled sandbox's workspace",
1126+
)
1127+
.await,
1128+
);
1129+
drop(
1130+
acquire_proceeds(
1131+
&store_b,
1132+
MutationScope::Workspace(&random_id("ws")),
1133+
"another workspace",
1134+
)
1135+
.await,
1136+
);
1137+
assert_eq!(
1138+
fixture
1139+
.lock_count(MutationLockKey::Sandbox(&stalled).advisory_key())
1140+
.await,
1141+
1,
1142+
"the holder keeps its key after every waiter gave up"
1143+
);
1144+
1145+
// Stalled holders that check out every lock connection of store A make
1146+
// its next acquisition fail by its deadline, while store B keeps working.
1147+
let mut fillers = Vec::new();
1148+
for _ in 1..MUTATION_LOCK_POOL_MAX_CONNECTIONS {
1149+
fillers.push(
1150+
acquire_proceeds(
1151+
&store_a,
1152+
MutationScope::sandbox(&random_id("ws"), &random_id("sb")),
1153+
"a holder that fills store A's lock pool",
1154+
)
1155+
.await,
1156+
);
1157+
}
1158+
let started = Instant::now();
1159+
match acquire(
1160+
&store_a,
1161+
MutationScope::sandbox(&random_id("ws"), &random_id("sb")),
1162+
EXPECTED_TIMEOUT,
1163+
)
1164+
.await
1165+
{
1166+
Err(PersistenceError::LockTimeout(detail)) => {
1167+
assert_eq!(detail, "waiting for a mutation lock connection");
1168+
}
1169+
Err(error) => panic!("expected a lock timeout from a full pool, got {error:?}"),
1170+
Ok(_) => panic!("a full lock pool handed out another connection"),
1171+
}
1172+
let waited = started.elapsed();
1173+
assert!(
1174+
waited < EXPECTED_TIMEOUT + CLIENT_BACKSTOP_GRACE,
1175+
"store A failed after {waited:?}"
1176+
);
1177+
drop(
1178+
acquire_proceeds(
1179+
&store_b,
1180+
MutationScope::sandbox(&random_id("ws"), &random_id("sb")),
1181+
"store B while store A's lock pool is full",
1182+
)
1183+
.await,
1184+
);
1185+
1186+
drop(fillers);
1187+
drop(holder);
1188+
drop(
1189+
acquire_proceeds(
1190+
&store_b,
1191+
MutationScope::sandbox(&workspace, &stalled),
1192+
"the stalled sandbox after its holder releases",
1193+
)
1194+
.await,
1195+
);
1196+
fixture.finish(vec![store_a, store_b]).await;
1197+
}
1198+
10801199
#[tokio::test]
10811200
#[ignore = "requires a disposable PostgreSQL database in OPENSHELL_TEST_POSTGRES_URL; run mise run test:rust:postgres"]
10821201
async fn postgres_mutation_lock_connection_failure_is_not_a_lock_timeout() {

0 commit comments

Comments
 (0)