about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-08 13:45:50 +0000
committerPjotr <wrk@bosa.lan>2026-11-08 13:45:50 +0000
commit1f76ef2ef19ae36882236be7c016f0ab98d31f11 (patch)
treeb9c1e479560ca48631592e212adea87cb893e995 /src
parent875d680a9c3cfe7f3b5a92f86ce211b5a5dfcbb4 (diff)
downloadgenenetwork4-1f76ef2ef19ae36882236be7c016f0ab98d31f11.tar.gz
compute_gate: undo the claim if the wait for the slot is cancelled
`claim()` inserts the subject into `claimants` and *then* awaits the
permit, and that await is cancellable: a client disconnect while queued
dropped the handler's future with the entry still in the set, so that
subject was refused `compute_busy` for the life of the process. The
reservation guard removes the entry when the wait is cancelled, and hands
ownership to the `Claim` once the permit arrives -- the slot itself was
never leaked (no permit had been taken), only the subject's name.

Found by asking what could race; the new test fails without the guard
(verified by disabling it) and passes with it.

* src/compute_gate.rs (Reservation): the entry's owner from insertion to
permit, `hand_over()` at the hand-off.
(Drop for Claim): field order is load-bearing -- the maps are cleaned
before `_permit` is released, so the next waiter cannot see a stale
entry or a stale `running` record; and take the locks poisoned-tolerant
(`lock_recover`) rather than silently skipping the cleanup.
(tests): `a_cancelled_waiter_does_not_wedge_its_subject`.
Diffstat (limited to 'src')
-rw-r--r--src/compute_gate.rs117
1 files changed, 83 insertions, 34 deletions
diff --git a/src/compute_gate.rs b/src/compute_gate.rs
index 538d293..cfff61c 100644
--- a/src/compute_gate.rs
+++ b/src/compute_gate.rs
@@ -33,6 +33,44 @@ use std::time::Instant;
 
 use tokio::sync::{Semaphore, SemaphorePermit};
 
+/// Take a lock, recovering from poisoning: the guarded data is a `HashSet`
+/// or an `Option`, both still valid after a panic elsewhere, and wedging
+/// the gate (or leaking an entry) is worse than trusting them.
+fn lock_recover<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
+    mutex
+        .lock()
+        .unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+
+/// A subject's place in the queue, from insertion until it becomes a
+/// [`Claim`].
+///
+/// This exists for one reason: `claim()` inserts the subject *before*
+/// awaiting the permit, and awaiting is cancellable -- a client
+/// disconnect drops the handler's future. Without this guard the entry
+/// would stay in `claimants` with nothing to remove it, and that subject
+/// would be refused with `compute_busy` for the life of the process.
+struct Reservation<'a> {
+    gate: &'a Gate,
+    subject: String,
+    /// False once the [`Claim`] takes over the removal.
+    held: bool,
+}
+
+impl Reservation<'_> {
+    fn hand_over(&mut self) {
+        self.held = false;
+    }
+}
+
+impl Drop for Reservation<'_> {
+    fn drop(&mut self) {
+        if self.held {
+            lock_recover(&self.gate.claimants).remove(&self.subject);
+        }
+    }
+}
+
 /// A claim on the slot.
 pub struct Claim<'a> {
     gate: &'a Gate,
@@ -51,12 +89,11 @@ impl std::fmt::Debug for Claim<'_> {
 
 impl Drop for Claim<'_> {
     fn drop(&mut self) {
-        if let Ok(mut claimants) = self.gate.claimants.lock() {
-            claimants.remove(&self.subject);
-        }
-        if let Ok(mut running) = self.gate.running.lock() {
-            *running = None;
-        }
+        // Field drop order matters here: this runs before `_permit` is
+        // released, so the next waiter cannot see a stale entry or a
+        // stale `running` record.
+        lock_recover(&self.gate.claimants).remove(&self.subject);
+        *lock_recover(&self.gate.running) = None;
     }
 }
 
@@ -125,52 +162,45 @@ impl Gate {
     /// the caller turns that into a `409`.
     pub async fn claim(&self, subject: &str, run_id: Option<&str>) -> Result<Claim<'_>, Busy> {
         {
-            let Ok(mut claimants) = self.claimants.lock() else {
-                // A poisoned lock means another thread panicked while
-                // holding it; refusing is safer than letting two jobs in.
-                return Err(Busy {
-                    run_id: None,
-                    elapsed: std::time::Duration::ZERO,
-                });
-            };
+            let mut claimants = lock_recover(&self.claimants);
             if !claimants.insert(subject.to_string()) {
-                let elapsed = self
-                    .running
-                    .lock()
-                    .ok()
-                    .and_then(|running| running.as_ref().map(|active| active.started.elapsed()))
+                let running = lock_recover(&self.running);
+                let elapsed = running
+                    .as_ref()
+                    .map(|active| active.started.elapsed())
                     .unwrap_or_default();
-                let run_id = self
-                    .running
-                    .lock()
-                    .ok()
-                    .and_then(|running| running.as_ref().and_then(|active| active.run_id.clone()));
+                let run_id = running.as_ref().and_then(|active| active.run_id.clone());
                 return Err(Busy { run_id, elapsed });
             }
         }
+        // From here to the permit, cancellation must undo the insertion.
+        let mut reservation = Reservation {
+            gate: self,
+            subject: subject.to_string(),
+            held: true,
+        };
 
         // Another subject's job may be running: this is where a different
         // user waits (indefinitely -- the request timeout is the bound).
         let permit = match self.slot.acquire().await {
             Ok(permit) => permit,
             Err(_) => {
-                // The semaphore is never closed in this code; be safe.
-                if let Ok(mut claimants) = self.claimants.lock() {
-                    claimants.remove(subject);
-                }
+                // The semaphore is never closed in this code; the
+                // reservation's drop undoes the insertion either way.
                 return Err(Busy {
                     run_id: None,
                     elapsed: std::time::Duration::ZERO,
                 });
             }
         };
+        // The permit is ours: the Claim (not the reservation) now owns the
+        // entry's removal.
+        reservation.hand_over();
 
-        if let Ok(mut running) = self.running.lock() {
-            *running = Some(Active {
-                run_id: run_id.map(str::to_string),
-                started: Instant::now(),
-            });
-        }
+        *lock_recover(&self.running) = Some(Active {
+            run_id: run_id.map(str::to_string),
+            started: Instant::now(),
+        });
         Ok(Claim {
             gate: self,
             subject: subject.to_string(),
@@ -315,6 +345,25 @@ mod tests {
         );
     }
 
+    /// A client that disconnects while queued must not leave its subject
+    /// blocked for ever: the reservation has to undo the insertion when
+    /// the `acquire()` future is dropped.
+    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+    async fn a_cancelled_waiter_does_not_wedge_its_subject() {
+        let gate = leaked_gate();
+        let holder = gate.claim("alice", None).await.expect("alice's claim");
+        let waiter = tokio::spawn(async move { gate.claim("bob", None).await.map(|_| ()) });
+        tokio::time::sleep(Duration::from_millis(50)).await;
+        waiter.abort();
+        let _ = waiter.await;
+        drop(holder);
+        let claim = tokio::time::timeout(Duration::from_secs(1), gate.claim("bob", None))
+            .await
+            .expect("bob must not be refused after their waiter was cancelled")
+            .expect("bob's claim");
+        drop(claim);
+    }
+
     #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
     async fn a_queued_subject_cannot_queue_a_second_job() {
         let gate = leaked_gate();