Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(proxy): Sperrvergiftung heilt, Deckel-Verdraengung in einem Rutsch

purple61044a6e7481
diff --git a/src-tauri/src/cancel_registry.rs b/src-tauri/src/cancel_registry.rs
index 31e4cf14..6956d173 100644
--- a/src-tauri/src/cancel_registry.rs
+++ b/src-tauri/src/cancel_registry.rs
@@ -82,6 +82,21 @@ impl CancelRegistry {
Self::default()
}
+ /// Locks `entries`, healing past poisoning instead of panicking.
+ ///
+ /// F4 fix (review-w2rust.md): a panic while any lock holder ran would
+ /// have poisoned the `std::sync::Mutex` and every later `register`/
+ /// `cancel` call would then panic too, turning one bad moment into a
+ /// permanently dead Stop button. Nothing under this lock can leave the
+ /// map in a state worth refusing to read (`register`/`cancel` only ever
+ /// do `HashMap` operations and `CancellationToken::cancel()`, see the
+ /// module doc), so recovering the guard the same way the `Drop` impl
+ /// already does (`if let Ok(...)`) is strictly safer than staying
+ /// panicked.
+ fn lock_entries(&self) -> std::sync::MutexGuard<'_, HashMap<String, Entry>> {
+ self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
+ }
+
/// Register a fresh token under `id`. The returned token is:
/// - already cancelled, if a `cancel(id)` arrived before this call (the
/// startup-window race this module exists for), the NEW token is the
@@ -100,7 +115,7 @@ impl CancelRegistry {
/// module, just shared instead of duplicated.
pub fn register(&self, id: String) -> (CancellationToken, Guard) {
let token = CancellationToken::new();
- let mut map = self.entries.lock().unwrap();
+ let mut map = self.lock_entries();
sweep_expired(&mut map);
match map.insert(id.clone(), Entry::Active(token.clone())) {
Some(Entry::Tombstone(_)) => token.cancel(),
@@ -122,7 +137,7 @@ impl CancelRegistry {
/// `register` already ran, plus the hard `MAX_ENTRIES` cap as a
/// backstop for callers that never register at all.
pub fn cancel(&self, id: &str) {
- let mut map = self.entries.lock().unwrap();
+ let mut map = self.lock_entries();
sweep_expired(&mut map);
match map.get(id) {
Some(Entry::Active(token)) => token.cancel(),
@@ -154,16 +169,29 @@ fn sweep_expired(map: &mut HashMap<String, Entry>) {
map.retain(|_, v| !matches!(v, Entry::Tombstone(at) if now.duration_since(*at) > TOMBSTONE_TTL));
}
-/// Evict tombstones oldest-first until inserting one more entry stays at or
-/// under `MAX_ENTRIES`. Only `Tombstone`s are ever evicted here, never
-/// `Active` ones: an in-flight call's own cancellation slot must never be
-/// dropped to make room for someone else's stray cancel, and the number of
-/// genuinely concurrent calls is bounded by how many requests a webview can
-/// have in flight at once, not by anything this cap needs to police.
-/// Oldest-first is what keeps the guarantee this module promises: under cap
-/// pressure, the most recently arrived tombstone (the one still likely to be
-/// matched by a `register` a few milliseconds behind it) survives, and only
-/// the stalest, most-likely-abandoned ones are dropped first.
+/// Once eviction runs at all, it clears down to this fraction of the cap
+/// instead of just the one slot the pending insert needs (F2 fix, review-
+/// w2rust.md): a flood that holds the map AT the cap would otherwise pay
+/// the full clone-and-sort cost of this function on every single further
+/// `cancel`, under the same lock that every real `register`/`cancel` also
+/// needs. Clearing a batch means the expensive path runs roughly once per
+/// `(1 - LOW_WATERMARK_FRACTION) * MAX_ENTRIES` cancels instead of once per
+/// cancel while at the cap, at the cost of evicting a few hundred more
+/// (still only ever tombstones, still oldest-first) than the single slot
+/// strictly needed.
+const LOW_WATERMARK_FRACTION: usize = 90; // percent
+
+/// Evict tombstones oldest-first until the map is back at or under the low
+/// watermark (with room for the one entry `cancel` is about to insert).
+/// Only `Tombstone`s are ever evicted here, never `Active` ones: an
+/// in-flight call's own cancellation slot must never be dropped to make
+/// room for someone else's stray cancel, and the number of genuinely
+/// concurrent calls is bounded by how many requests a webview can have in
+/// flight at once, not by anything this cap needs to police. Oldest-first
+/// is what keeps the guarantee this module promises: under cap pressure,
+/// the most recently arrived tombstone (the one still likely to be matched
+/// by a `register` a few milliseconds behind it) survives, and only the
+/// stalest, most-likely-abandoned ones are dropped first.
///
/// No-op (and therefore cheap) in the overwhelmingly common case where the
/// map is nowhere near the cap.
@@ -179,8 +207,11 @@ fn evict_oldest_tombstones_to_fit(map: &mut HashMap<String, Entry>) {
})
.collect();
tombstones.sort_by_key(|(_, at)| *at);
- // +1 to make room for the entry `cancel` is about to insert.
- let over = map.len() + 1 - MAX_ENTRIES;
+ let low_watermark = MAX_ENTRIES * LOW_WATERMARK_FRACTION / 100;
+ // +1 to make room for the entry `cancel` is about to insert; `max` so a
+ // low watermark that somehow sits above the cap (a pathological
+ // constant edit) still evicts at least the one slot actually needed.
+ let over = (map.len() + 1).saturating_sub(low_watermark).max(map.len() + 1 - MAX_ENTRIES);
for (key, _) in tombstones.into_iter().take(over) {
map.remove(&key);
}
@@ -331,6 +362,31 @@ mod tests {
assert!(!registry.contains("panicking"));
}
+ /// F4 fix (review-w2rust.md): a panic while the lock is HELD (not the
+ /// case above, where the guard was released cleanly by the time the
+ /// panic happened) poisons a `std::sync::Mutex`. Before the fix,
+ /// `register`/`cancel`'s `.lock().unwrap()` would then panic on every
+ /// later call too, turning one bad moment into a permanently dead Stop
+ /// button. This test poisons the lock directly, then proves both
+ /// `register` and `cancel` keep working afterwards instead of
+ /// panicking.
+ #[test]
+ fn a_poisoned_lock_heals_instead_of_wedging_every_later_call() {
+ let registry = CancelRegistry::new();
+ let for_poison = registry.clone();
+ let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ let _guard = for_poison.entries.lock().unwrap();
+ panic!("simulated panic while the lock is held");
+ }));
+ assert!(outcome.is_err(), "the setup itself must panic to poison the mutex");
+
+ // Neither call must panic now that the mutex is poisoned.
+ let (token, _guard) = registry.register("after-poison".to_string());
+ assert!(!token.is_cancelled());
+ registry.cancel("after-poison");
+ assert!(token.is_cancelled(), "cancel must still reach the token after healing past poisoning");
+ }
+
// ── Tombstone TTL sweep (the "Aufraeumpfad") ─────────────────────────
#[test]
@@ -383,6 +439,31 @@ mod tests {
assert!(len <= MAX_ENTRIES, "map grew to {len} entries, cap is {MAX_ENTRIES}");
}
+ /// F2 fix (review-w2rust.md): eviction at the cap clears a batch down to
+ /// `LOW_WATERMARK_FRACTION`, not just the one slot the pending insert
+ /// needs. Filling to exactly the cap and cancelling once more must drop
+ /// the map noticeably below the cap, not merely to `MAX_ENTRIES - 1`,
+ /// which is what the pre-fix, evict-one-per-call version would leave.
+ #[test]
+ fn eviction_at_the_cap_clears_a_batch_not_one_slot_at_a_time() {
+ let registry = CancelRegistry::new();
+ for i in 0..MAX_ENTRIES {
+ registry.cancel(&format!("stray-{i}"));
+ }
+ assert_eq!(registry.entries.lock().unwrap().len(), MAX_ENTRIES);
+
+ registry.cancel("one-more");
+ let len = registry.entries.lock().unwrap().len();
+ let low_watermark = MAX_ENTRIES * LOW_WATERMARK_FRACTION / 100;
+ assert!(
+ len <= low_watermark + 1,
+ "one eviction at the cap must clear down to the low watermark \
+ ({low_watermark} plus the new entry), got {len} -- an evict-one-\
+ per-call regression would leave {}",
+ MAX_ENTRIES,
+ );
+ }
+
#[test]
fn under_cap_pressure_the_most_recently_arrived_tombstone_survives() {
// Fill exactly to the cap with older stray cancels, then one more.