From c290bec744cf092d56955a4c1e631ab14e2aa4cf Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:25:34 +0100 Subject: [PATCH 01/11] feat(service): Report peak permits in use for concurrency limiters The in-use gauges reach Datadog as one snapshot per flush interval, so a limiter could reject requests while its graph stayed below the limit. Each limiter now tracks the peak permits in use between emissions and reports it as a distribution, whose max is the true peak over any period. --- objectstore-service/src/backend/tiered.rs | 12 +- objectstore-service/src/concurrency.rs | 108 +++++++++++-- .../src/concurrency/limiter.rs | 143 ++++++++++++++++-- objectstore-service/src/service.rs | 8 +- 4 files changed, 240 insertions(+), 31 deletions(-) diff --git a/objectstore-service/src/backend/tiered.rs b/objectstore-service/src/backend/tiered.rs index 4be0d7c9..f7e4b516 100644 --- a/objectstore-service/src/backend/tiered.rs +++ b/objectstore-service/src/backend/tiered.rs @@ -335,11 +335,15 @@ impl TieredStorage { let emitter = high_volume.clone(); tokio::spawn(async move { emitter - .run_emitter(|stats| async move { + .run_emitter(|stats, in_use_peak| async move { objectstore_metrics::gauge!( "tiered.concurrency.in_use" = stats.in_use, tier = "high-volume" ); + objectstore_metrics::record!( + "tiered.concurrency.in_use_peak" = in_use_peak, + tier = "high-volume" + ); objectstore_metrics::gauge!( "tiered.concurrency.waiting" = stats.waiting_normal as u64, tier = "high-volume", @@ -356,11 +360,15 @@ impl TieredStorage { let emitter = long_term.clone(); tokio::spawn(async move { emitter - .run_emitter(|stats| async move { + .run_emitter(|stats, in_use_peak| async move { objectstore_metrics::gauge!( "tiered.concurrency.in_use" = stats.in_use, tier = "long-term" ); + objectstore_metrics::record!( + "tiered.concurrency.in_use_peak" = in_use_peak, + tier = "long-term" + ); }) .await; }); diff --git a/objectstore-service/src/concurrency.rs b/objectstore-service/src/concurrency.rs index 47f27faf..d08cced7 100644 --- a/objectstore-service/src/concurrency.rs +++ b/objectstore-service/src/concurrency.rs @@ -9,6 +9,11 @@ //! waiters on drop, allowing [`ConcurrencyLimiter::wait_all`] to resolve once //! all permits have been returned. //! +//! Every limiter has a `run_emitter` method that reports its usage once per second. Since such +//! snapshots miss shorter bursts, the emitters also report the peak permits in use since their +//! previous report. A limiter that had no free permit for an acquisition always reports a peak +//! equal to its capacity. +//! //! [`run_metered`] runs an isolated task and waits for its result, while //! [`spawn_metered`] starts the same task without waiting. Both provide panic //! recovery and `service.task.*` metric emission. @@ -25,6 +30,7 @@ use crate::error::{Error, ErrorKind, Panic, Result}; mod limiter; +use limiter::Peak; pub use limiter::{Limiter, LimiterStats, Permit, Priority, PriorityLimiter, PriorityLimiterStats}; /// Interval for the periodic metrics emitter. @@ -61,6 +67,7 @@ pub struct ConcurrencyLimiter { tasks: Arc, queue: Arc, bulk: Arc, + in_use_peak: Arc, tasks_total: u32, queue_total: u32, bulk_total: u32, @@ -81,6 +88,7 @@ impl ConcurrencyLimiter { tasks: Arc::new(Semaphore::new(max as usize)), queue: Arc::new(Semaphore::new(0)), bulk: Arc::new(Semaphore::new(max as usize)), + in_use_peak: Arc::default(), tasks_total: max, queue_total: 0, bulk_total: max, @@ -136,7 +144,7 @@ impl ConcurrencyLimiter { } // Fast path: Instantly grab a free permit without parking. - if let Ok(task_permit) = self.tasks.clone().try_acquire_owned() { + if let Some(task_permit) = self.try_acquire_task() { return Ok(ConcurrencyPermit { task_permit: Some(task_permit), bulk_permit: None, @@ -169,11 +177,7 @@ impl ConcurrencyLimiter { /// /// Returns [`ErrorKind::AtCapacity`] when no permits are available. pub fn try_acquire(&self) -> Result { - let task_permit = self - .tasks - .clone() - .try_acquire_owned() - .map_err(|_| ErrorKind::AtCapacity)?; + let task_permit = self.try_acquire_task().ok_or(ErrorKind::AtCapacity)?; Ok(ConcurrencyPermit { task_permit: Some(task_permit), @@ -196,12 +200,12 @@ impl ConcurrencyLimiter { return Err(ErrorKind::AtCapacity.into()); } - let bulk_sem = self.bulk.clone(); - let tasks_sem = self.tasks.clone(); - - let acquire = async move { - let bulk_permit = bulk_sem.acquire_owned().await?; - let task_permit = tasks_sem.acquire_owned().await?; + let acquire = async { + let bulk_permit = self.bulk.clone().acquire_owned().await?; + let task_permit = match self.try_acquire_task() { + Some(task_permit) => task_permit, + None => self.tasks.clone().acquire_owned().await?, + }; Ok((task_permit, bulk_permit)) }; @@ -217,6 +221,23 @@ impl ConcurrencyLimiter { }) } + /// Takes a free execution permit without waiting, tracking the peak permits in use. + fn try_acquire_task(&self) -> Option { + match self.tasks.clone().try_acquire_owned() { + Ok(permit) => { + // A release between the acquisition and this read lowers the reading. + self.in_use_peak.observe(self.used_permits()); + Some(permit) + } + Err(_) => { + // No permit was free. Recording that here makes every rejection and wait show + // up as a full limiter, whatever is released right after. + self.in_use_peak.observe(self.tasks_total); + None + } + } + } + /// Returns the number of permits currently available. pub fn available_permits(&self) -> u32 { u32::try_from(self.tasks.available_permits()).unwrap_or(self.tasks_total) @@ -277,17 +298,21 @@ impl ConcurrencyLimiter { /// Periodically calls `emit` with the current in-use and queued counts. /// + /// The second argument is the highest number of execution permits held since the previous + /// call, which captures bursts that the stats miss. + /// /// This future runs forever and is intended to be spawned as a background /// task alongside the service. pub async fn run_emitter(&self, mut emit: F) -> ! where - F: FnMut(Stats) -> Fut, + F: FnMut(Stats, u32) -> Fut, Fut: Future, { let mut ticker = tokio::time::interval(EMITTER_INTERVAL); loop { ticker.tick().await; - emit(self.stats()).await; + let stats = self.stats(); + emit(stats, self.in_use_peak.take(stats.in_use)).await; } } } @@ -490,7 +515,7 @@ mod tests { let in_use_clone = Arc::clone(&emitted_in_use); let queued_clone = Arc::clone(&emitted_queued); - let emitter = limiter.run_emitter(move |stats| { + let emitter = limiter.run_emitter(move |stats, _| { let in_use_ref = Arc::clone(&in_use_clone); let queued_ref = Arc::clone(&queued_clone); async move { @@ -508,6 +533,57 @@ mod tests { assert_eq!(emitted_queued.load(Ordering::Relaxed), 0); } + #[tokio::test(start_paused = true)] + async fn emitter_reports_peak_usage_between_emissions() { + let limiter = ConcurrencyLimiter::new(3).with_queue(1); + let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel(); + let emitter = limiter.run_emitter(|stats, peak| { + sender.send((stats.in_use, peak)).unwrap(); + std::future::ready(()) + }); + tokio::pin!(emitter); + let mut emit = async |advance: Duration| { + tokio::time::advance(advance).await; + assert!(futures::poll!(&mut emitter).is_pending()); + receiver.try_recv().unwrap() + }; + assert_eq!(emit(Duration::ZERO).await, (0, 0)); + + // A burst that is over before the next emission is still reported. + let held = limiter.acquire().await.unwrap(); + drop(limiter.acquire_bulk().await.unwrap()); + assert_eq!(emit(EMITTER_INTERVAL).await, (1, 2)); + + // Permits held throughout count even though nothing was acquired. + assert_eq!(emit(EMITTER_INTERVAL).await, (1, 1)); + + // Permits released since the previous emission were in use at its start. + drop(held); + assert_eq!(emit(EMITTER_INTERVAL).await, (0, 1)); + assert_eq!(emit(EMITTER_INTERVAL).await, (0, 0)); + } + + #[tokio::test(start_paused = true)] + async fn contention_marks_the_limiter_as_full() { + for bulk in [false, true] { + let limiter = ConcurrencyLimiter::new(2).with_queue(1); + let held = ( + limiter.try_acquire().unwrap(), + limiter.try_acquire().unwrap(), + ); + // Lower the peak so that only the failed acquisition can raise it back to capacity. + assert_eq!(limiter.in_use_peak.take(1), 2); + let mut waiting: std::pin::Pin>> = match bulk { + false => Box::pin(limiter.acquire()), + true => Box::pin(limiter.acquire_bulk()), + }; + assert!(futures::poll!(&mut waiting).is_pending()); + drop(waiting); + drop(held); + assert_eq!(limiter.in_use_peak.take(0), 2); + } + } + #[tokio::test] async fn wait_all_resolves_when_permits_returned() { let limiter = ConcurrencyLimiter::new(2); @@ -698,7 +774,7 @@ mod tests { let in_use_clone = Arc::clone(&emitted_in_use); let queued_clone = Arc::clone(&emitted_queued); - let emitter = limiter.run_emitter(move |stats| { + let emitter = limiter.run_emitter(move |stats, _| { let in_use_ref = Arc::clone(&in_use_clone); let queued_ref = Arc::clone(&queued_clone); async move { diff --git a/objectstore-service/src/concurrency/limiter.rs b/objectstore-service/src/concurrency/limiter.rs index 191afea3..032afc37 100644 --- a/objectstore-service/src/concurrency/limiter.rs +++ b/objectstore-service/src/concurrency/limiter.rs @@ -3,8 +3,9 @@ use std::collections::BTreeMap; use std::future::Future; use std::io; -use std::mem::DropGuard; +use std::mem::{self, DropGuard}; use std::num::NonZeroU32; +use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use std::task::Poll; use std::time::Duration; @@ -71,16 +72,41 @@ pub struct LimiterStats { pub in_use: u32, } +/// High-water mark of the permits in use, for limiters that count them outside of a lock. +/// +/// A periodic snapshot misses bursts that start and end between two snapshots, so limiters +/// also [`observe`](Self::observe) their usage as permits are acquired. +#[derive(Debug, Default)] +pub(super) struct Peak(AtomicU32); + +impl Peak { + /// Raises the mark to `in_use` if that is higher. + pub(super) fn observe(&self, in_use: u32) { + self.0.fetch_max(in_use, Ordering::Relaxed); + } + + /// Returns the highest count since the previous call and restarts the mark at `in_use`. + /// + /// Restarting at the current count instead of zero keeps permits visible that stay held + /// while nothing new is acquired. + pub(super) fn take(&self, in_use: u32) -> u32 { + self.0.swap(in_use, Ordering::Relaxed).max(in_use) + } +} + /// Shared interval loop for the metric emitters. -async fn run_emitter(mut snapshot: impl FnMut() -> S, mut emit: F) -> ! +/// +/// `sample` returns the stats and the peak permits in use since its previous call. +async fn run_emitter(mut sample: impl FnMut() -> (S, u32), mut emit: F) -> ! where - F: FnMut(S) -> Fut, + F: FnMut(S, u32) -> Fut, Fut: Future, { let mut ticker = tokio::time::interval(METRICS_EMITTER_INTERVAL); loop { ticker.tick().await; - emit(snapshot()).await; + let (stats, in_use_peak) = sample(); + emit(stats, in_use_peak).await; } } @@ -89,6 +115,7 @@ where pub struct Limiter { semaphore: Arc, queue: Option>, + peak: Arc, capacity: u32, timeout: Duration, } @@ -100,6 +127,7 @@ impl Limiter { Self { semaphore: Arc::new(Semaphore::new(capacity as usize)), queue: max_queue_size.map(|size| Arc::new(Semaphore::new(size as usize))), + peak: Arc::default(), capacity, timeout, } @@ -111,8 +139,13 @@ impl Limiter { /// Dropping the future releases its queue slot and any assigned permit. pub async fn acquire(&self) -> Result { if let Ok(permit) = self.semaphore.clone().try_acquire_owned() { + // A release between the acquisition and this read lowers the reading. + self.peak.observe(self.in_use()); return Ok(Permit::semaphore(permit)); } + // No permit was free. Recording that here makes every rejection and wait show up as a + // full limiter, whatever is released right after. + self.peak.observe(self.capacity); if self.timeout.is_zero() { return Err(ErrorKind::AtCapacity.into()); } @@ -129,20 +162,31 @@ impl Limiter { Ok(Permit::semaphore(permit)) } + fn in_use(&self) -> u32 { + self.capacity - self.semaphore.available_permits() as u32 + } + /// Returns the current number of permits in use. pub fn stats(&self) -> LimiterStats { LimiterStats { - in_use: self.capacity - self.semaphore.available_permits() as u32, + in_use: self.in_use(), } } /// Passes this limiter's stats to `emit` immediately and once per second thereafter. + /// + /// The second argument is the highest number of permits in use since the previous call, + /// which captures bursts that the stats miss. pub async fn run_emitter(&self, emit: F) -> ! where - F: FnMut(LimiterStats) -> Fut, + F: FnMut(LimiterStats, u32) -> Fut, Fut: Future, { - run_emitter(|| self.stats(), emit).await + let sample = || { + let stats = self.stats(); + (stats, self.peak.take(stats.in_use)) + }; + run_emitter(sample, emit).await } } @@ -199,6 +243,7 @@ impl PriorityLimiter { capacity: capacity.get(), state: Arc::new(Mutex::new(PriorityState { free: capacity.get(), + peak_in_use: 0, next_id: 0, normal_queue: WaiterQueue::new(), high_queue: WaiterQueue::new(), @@ -221,6 +266,7 @@ impl PriorityLimiter { // A free permit implies that nobody is queued, so taking it overtakes no one. if state.free > 0 { state.free -= 1; + state.peak_in_use = state.peak_in_use.max(self.capacity - state.free); return Ok(Permit::priority(self.state.clone())); } if timeout == Some(Duration::ZERO) { @@ -264,13 +310,23 @@ impl PriorityLimiter { } } + /// Returns the highest number of permits in use since the previous call. + fn take_peak(&self) -> u32 { + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + let in_use = self.capacity - state.free; + mem::replace(&mut state.peak_in_use, in_use) + } + /// Passes this limiter's stats to `emit` immediately and once per second thereafter. + /// + /// The second argument is the highest number of permits in use since the previous call, + /// which captures bursts that the stats miss. pub async fn run_emitter(&self, emit: F) -> ! where - F: FnMut(PriorityLimiterStats) -> Fut, + F: FnMut(PriorityLimiterStats, u32) -> Fut, Fut: Future, { - run_emitter(|| self.stats(), emit).await + run_emitter(|| (self.stats(), self.take_peak()), emit).await } } @@ -283,6 +339,9 @@ type WaiterQueue = BTreeMap>; #[derive(Debug)] struct PriorityState { free: u32, + /// Highest number of permits in use since the emitter last took it. Handing a slot to a + /// waiter keeps it in use, so only taking a free permit can raise this. + peak_in_use: u32, next_id: u64, normal_queue: WaiterQueue, high_queue: WaiterQueue, @@ -341,11 +400,11 @@ mod tests { let simple_permit = simple.acquire().await.unwrap(); let (priority_sender, mut priority_receiver) = tokio::sync::mpsc::unbounded_channel(); let (simple_sender, mut simple_receiver) = tokio::sync::mpsc::unbounded_channel(); - let priority_emitter = priority.run_emitter(|stats| { + let priority_emitter = priority.run_emitter(|stats, _| { priority_sender.send(stats).unwrap(); std::future::ready(()) }); - let simple_emitter = simple.run_emitter(|stats| { + let simple_emitter = simple.run_emitter(|stats, _| { simple_sender.send(stats).unwrap(); std::future::ready(()) }); @@ -367,6 +426,68 @@ mod tests { assert_eq!(simple_receiver.try_recv().unwrap(), LimiterStats::default()); } + #[tokio::test(start_paused = true)] + async fn emitter_reports_peak_usage_between_emissions() { + const CAPACITY: u32 = 3; + let capacity = NonZeroU32::new(CAPACITY).unwrap(); + let priority = PriorityLimiter::new(capacity, TIMEOUT, TIMEOUT, None, None); + let simple = Limiter::new(capacity, Duration::ZERO, None); + let (priority_sender, mut priority_peaks) = tokio::sync::mpsc::unbounded_channel(); + let (simple_sender, mut simple_peaks) = tokio::sync::mpsc::unbounded_channel(); + let priority_emitter = priority.run_emitter(|stats, peak| { + priority_sender.send((stats.in_use, peak)).unwrap(); + std::future::ready(()) + }); + let simple_emitter = simple.run_emitter(|stats, peak| { + simple_sender.send((stats.in_use, peak)).unwrap(); + std::future::ready(()) + }); + tokio::pin!(priority_emitter, simple_emitter); + let mut emit = async |advance: Duration| { + tokio::time::advance(advance).await; + assert!(poll!(&mut priority_emitter).is_pending()); + assert!(poll!(&mut simple_emitter).is_pending()); + let priority = priority_peaks.try_recv().unwrap(); + assert_eq!(priority, simple_peaks.try_recv().unwrap()); + priority + }; + assert_eq!(emit(Duration::ZERO).await, (0, 0)); + + // A burst that is over before the next emission is still reported. + let held = ( + priority.acquire(Priority::Normal).await.unwrap(), + simple.acquire().await.unwrap(), + ); + let burst = ( + priority.acquire(Priority::Normal).await.unwrap(), + simple.acquire().await.unwrap(), + ); + drop(burst); + assert_eq!(emit(METRICS_EMITTER_INTERVAL).await, (1, 2)); + + // Permits held throughout count even though nothing was acquired. + assert_eq!(emit(METRICS_EMITTER_INTERVAL).await, (1, 1)); + + // Permits released since the previous emission were in use at its start. + drop(held); + assert_eq!(emit(METRICS_EMITTER_INTERVAL).await, (0, 1)); + assert_eq!(emit(METRICS_EMITTER_INTERVAL).await, (0, 0)); + } + + #[tokio::test(start_paused = true)] + async fn rejection_marks_the_limiter_as_full() { + let limiter = Limiter::new(NonZeroU32::new(2).unwrap(), Duration::ZERO, None); + let held = ( + limiter.acquire().await.unwrap(), + limiter.acquire().await.unwrap(), + ); + // Lower the peak so that only the failed acquisition can raise it back to capacity. + assert_eq!(limiter.peak.take(1), 2); + limiter.acquire().await.unwrap_err(); + drop(held); + assert_eq!(limiter.peak.take(0), 2); + } + #[tokio::test(start_paused = true)] async fn stream_retains_then_releases_at_terminal_item() { for error in [false, true] { diff --git a/objectstore-service/src/service.rs b/objectstore-service/src/service.rs index c6c7ff07..a621aea9 100644 --- a/objectstore-service/src/service.rs +++ b/objectstore-service/src/service.rs @@ -168,8 +168,11 @@ impl StorageService { /// - `service.concurrency.queue_limit`: queue size for waiting tasks /// - `service.concurrency.bulk_limit`: concurrent task execution slots for bulk operations /// - /// Also spawns tasks that emit runtime gauges once per second: + /// Also spawns tasks that emit runtime metrics once per second, as gauges unless noted: /// - `service.concurrency.in_use`: currently running tasks + /// - `service.concurrency.in_use_peak` (distribution): most tasks running at once since the + /// previous emission. Unlike the gauges, which only keep the last value of each flush + /// interval, its `max` over any period is the true peak. /// - `service.concurrency.queued`: currently queued tasks /// - `service.concurrency.bulk_in_use`: currently running bulk tasks /// - `service.expiry_renewal.queued`: expiry renewals waiting for the background worker @@ -183,8 +186,9 @@ impl StorageService { tokio::spawn(async move { concurrency - .run_emitter(|stats| async move { + .run_emitter(|stats, in_use_peak| async move { objectstore_metrics::gauge!("service.concurrency.in_use" = stats.in_use); + objectstore_metrics::record!("service.concurrency.in_use_peak" = in_use_peak); objectstore_metrics::gauge!("service.concurrency.queued" = stats.queued); objectstore_metrics::gauge!( "service.concurrency.bulk_in_use" = stats.bulk_in_use From fbb87fc203e28db9448b05a1dad8a0c1699cdec7 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:33:51 +0100 Subject: [PATCH 02/11] ref(service): Report the peak permits in use as part of limiter stats Pass the peak to the emitter callbacks inside the stats structs instead of as a separate argument. --- clients/python/CHANGELOG.md | 2 +- objectstore-service/src/backend/tiered.rs | 8 +- objectstore-service/src/concurrency.rs | 36 ++++-- .../src/concurrency/limiter.rs | 119 ++++++++++++------ objectstore-service/src/service.rs | 6 +- 5 files changed, 112 insertions(+), 59 deletions(-) diff --git a/clients/python/CHANGELOG.md b/clients/python/CHANGELOG.md index cd3d5a5e..182a4ca7 100644 --- a/clients/python/CHANGELOG.md +++ b/clients/python/CHANGELOG.md @@ -20,7 +20,7 @@ ```python # Before client = Client(url, token=SecretKey(kid, secret_key, expiry_seconds=300)) - + # After key = SecretKey(kid, secret_key) client = Client(url, token=TokenGenerator(key, expiry_seconds=300)) diff --git a/objectstore-service/src/backend/tiered.rs b/objectstore-service/src/backend/tiered.rs index f7e4b516..9f378756 100644 --- a/objectstore-service/src/backend/tiered.rs +++ b/objectstore-service/src/backend/tiered.rs @@ -335,13 +335,13 @@ impl TieredStorage { let emitter = high_volume.clone(); tokio::spawn(async move { emitter - .run_emitter(|stats, in_use_peak| async move { + .run_emitter(|stats| async move { objectstore_metrics::gauge!( "tiered.concurrency.in_use" = stats.in_use, tier = "high-volume" ); objectstore_metrics::record!( - "tiered.concurrency.in_use_peak" = in_use_peak, + "tiered.concurrency.in_use_peak" = stats.in_use_peak, tier = "high-volume" ); objectstore_metrics::gauge!( @@ -360,13 +360,13 @@ impl TieredStorage { let emitter = long_term.clone(); tokio::spawn(async move { emitter - .run_emitter(|stats, in_use_peak| async move { + .run_emitter(|stats| async move { objectstore_metrics::gauge!( "tiered.concurrency.in_use" = stats.in_use, tier = "long-term" ); objectstore_metrics::record!( - "tiered.concurrency.in_use_peak" = in_use_peak, + "tiered.concurrency.in_use_peak" = stats.in_use_peak, tier = "long-term" ); }) diff --git a/objectstore-service/src/concurrency.rs b/objectstore-service/src/concurrency.rs index d08cced7..98e62413 100644 --- a/objectstore-service/src/concurrency.rs +++ b/objectstore-service/src/concurrency.rs @@ -9,10 +9,10 @@ //! waiters on drop, allowing [`ConcurrencyLimiter::wait_all`] to resolve once //! all permits have been returned. //! -//! Every limiter has a `run_emitter` method that reports its usage once per second. Since such -//! snapshots miss shorter bursts, the emitters also report the peak permits in use since their -//! previous report. A limiter that had no free permit for an acquisition always reports a peak -//! equal to its capacity. +//! Every limiter has a `run_emitter` method that reports its stats once per second. Since the +//! permits in use at that moment miss shorter bursts, the stats also contain the peak permits +//! in use since the previous report. A limiter that had no free permit for an acquisition +//! always reports a peak equal to its capacity. //! //! [`run_metered`] runs an isolated task and waits for its result, while //! [`spawn_metered`] starts the same task without waiting. Both provide panic @@ -45,6 +45,10 @@ const EMITTER_INTERVAL: Duration = Duration::from_secs(1); pub struct Stats { /// Number of execution permits currently held. pub in_use: u32, + /// Most execution permits held at once since [`ConcurrencyLimiter::run_emitter`] last + /// reported, or since the limiter was created. Unlike `in_use`, this captures bursts between + /// two reports. + pub in_use_peak: u32, /// Number of callers waiting in the queue for a permit. pub queued: u32, /// Number of bulk operations currently in flight. @@ -289,8 +293,10 @@ impl ConcurrencyLimiter { /// Returns a snapshot of the current counts. pub fn stats(&self) -> Stats { + let in_use = self.used_permits(); Stats { - in_use: self.used_permits(), + in_use, + in_use_peak: self.in_use_peak.get(in_use), queued: self.queued_permits(), bulk_in_use: self.used_bulk_permits(), } @@ -298,21 +304,25 @@ impl ConcurrencyLimiter { /// Periodically calls `emit` with the current in-use and queued counts. /// - /// The second argument is the highest number of execution permits held since the previous - /// call, which captures bursts that the stats miss. + /// Each call restarts the peak, so it covers the time since the previous call. /// /// This future runs forever and is intended to be spawned as a background /// task alongside the service. pub async fn run_emitter(&self, mut emit: F) -> ! where - F: FnMut(Stats, u32) -> Fut, + F: FnMut(Stats) -> Fut, Fut: Future, { let mut ticker = tokio::time::interval(EMITTER_INTERVAL); loop { ticker.tick().await; let stats = self.stats(); - emit(stats, self.in_use_peak.take(stats.in_use)).await; + let in_use_peak = self.in_use_peak.take(stats.in_use); + emit(Stats { + in_use_peak, + ..stats + }) + .await; } } } @@ -515,7 +525,7 @@ mod tests { let in_use_clone = Arc::clone(&emitted_in_use); let queued_clone = Arc::clone(&emitted_queued); - let emitter = limiter.run_emitter(move |stats, _| { + let emitter = limiter.run_emitter(move |stats| { let in_use_ref = Arc::clone(&in_use_clone); let queued_ref = Arc::clone(&queued_clone); async move { @@ -537,8 +547,8 @@ mod tests { async fn emitter_reports_peak_usage_between_emissions() { let limiter = ConcurrencyLimiter::new(3).with_queue(1); let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel(); - let emitter = limiter.run_emitter(|stats, peak| { - sender.send((stats.in_use, peak)).unwrap(); + let emitter = limiter.run_emitter(|stats| { + sender.send((stats.in_use, stats.in_use_peak)).unwrap(); std::future::ready(()) }); tokio::pin!(emitter); @@ -774,7 +784,7 @@ mod tests { let in_use_clone = Arc::clone(&emitted_in_use); let queued_clone = Arc::clone(&emitted_queued); - let emitter = limiter.run_emitter(move |stats, _| { + let emitter = limiter.run_emitter(move |stats| { let in_use_ref = Arc::clone(&in_use_clone); let queued_ref = Arc::clone(&queued_clone); async move { diff --git a/objectstore-service/src/concurrency/limiter.rs b/objectstore-service/src/concurrency/limiter.rs index 032afc37..060298ed 100644 --- a/objectstore-service/src/concurrency/limiter.rs +++ b/objectstore-service/src/concurrency/limiter.rs @@ -70,6 +70,9 @@ impl Permit { pub struct LimiterStats { /// Permits currently in use. pub in_use: u32, + /// Most permits in use at once since [`Limiter::run_emitter`] last reported, or since the + /// limiter was created. Unlike `in_use`, this captures bursts between two reports. + pub in_use_peak: u32, } /// High-water mark of the permits in use, for limiters that count them outside of a lock. @@ -85,6 +88,11 @@ impl Peak { self.0.fetch_max(in_use, Ordering::Relaxed); } + /// Returns the highest count since the previous [`take`](Self::take). + pub(super) fn get(&self, in_use: u32) -> u32 { + self.0.load(Ordering::Relaxed).max(in_use) + } + /// Returns the highest count since the previous call and restarts the mark at `in_use`. /// /// Restarting at the current count instead of zero keeps permits visible that stay held @@ -95,18 +103,15 @@ impl Peak { } /// Shared interval loop for the metric emitters. -/// -/// `sample` returns the stats and the peak permits in use since its previous call. -async fn run_emitter(mut sample: impl FnMut() -> (S, u32), mut emit: F) -> ! +async fn run_emitter(mut snapshot: impl FnMut() -> S, mut emit: F) -> ! where - F: FnMut(S, u32) -> Fut, + F: FnMut(S) -> Fut, Fut: Future, { let mut ticker = tokio::time::interval(METRICS_EMITTER_INTERVAL); loop { ticker.tick().await; - let (stats, in_use_peak) = sample(); - emit(stats, in_use_peak).await; + emit(snapshot()).await; } } @@ -166,27 +171,31 @@ impl Limiter { self.capacity - self.semaphore.available_permits() as u32 } - /// Returns the current number of permits in use. + /// Returns the current and peak number of permits in use. pub fn stats(&self) -> LimiterStats { + let in_use = self.in_use(); LimiterStats { - in_use: self.in_use(), + in_use, + in_use_peak: self.peak.get(in_use), } } /// Passes this limiter's stats to `emit` immediately and once per second thereafter. /// - /// The second argument is the highest number of permits in use since the previous call, - /// which captures bursts that the stats miss. + /// Each call restarts the peak, so it covers the time since the previous call. pub async fn run_emitter(&self, emit: F) -> ! where - F: FnMut(LimiterStats, u32) -> Fut, + F: FnMut(LimiterStats) -> Fut, Fut: Future, { - let sample = || { + let snapshot = || { let stats = self.stats(); - (stats, self.peak.take(stats.in_use)) + LimiterStats { + in_use_peak: self.peak.take(stats.in_use), + ..stats + } }; - run_emitter(sample, emit).await + run_emitter(snapshot, emit).await } } @@ -204,6 +213,9 @@ pub enum Priority { pub struct PriorityLimiterStats { /// Permits currently in use. pub in_use: u32, + /// Most permits in use at once since [`PriorityLimiter::run_emitter`] last reported, or + /// since the limiter was created. Unlike `in_use`, this captures bursts between two reports. + pub in_use_peak: u32, /// Normal-priority acquisitions waiting in the queue. pub waiting_normal: usize, /// High-priority acquisitions waiting in the queue. @@ -243,7 +255,7 @@ impl PriorityLimiter { capacity: capacity.get(), state: Arc::new(Mutex::new(PriorityState { free: capacity.get(), - peak_in_use: 0, + in_use_peak: 0, next_id: 0, normal_queue: WaiterQueue::new(), high_queue: WaiterQueue::new(), @@ -266,7 +278,7 @@ impl PriorityLimiter { // A free permit implies that nobody is queued, so taking it overtakes no one. if state.free > 0 { state.free -= 1; - state.peak_in_use = state.peak_in_use.max(self.capacity - state.free); + state.in_use_peak = state.in_use_peak.max(self.capacity - state.free); return Ok(Permit::priority(self.state.clone())); } if timeout == Some(Duration::ZERO) { @@ -305,28 +317,35 @@ impl PriorityLimiter { let state = self.state.lock().unwrap_or_else(PoisonError::into_inner); PriorityLimiterStats { in_use: self.capacity - state.free, + in_use_peak: state.in_use_peak, waiting_normal: state.normal_queue.len(), waiting_high: state.high_queue.len(), } } /// Returns the highest number of permits in use since the previous call. + /// + /// The next peak starts at the current number instead of zero, which keeps permits visible + /// that stay held while nothing new is acquired. fn take_peak(&self) -> u32 { let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); let in_use = self.capacity - state.free; - mem::replace(&mut state.peak_in_use, in_use) + mem::replace(&mut state.in_use_peak, in_use) } /// Passes this limiter's stats to `emit` immediately and once per second thereafter. /// - /// The second argument is the highest number of permits in use since the previous call, - /// which captures bursts that the stats miss. + /// Each call restarts the peak, so it covers the time since the previous call. pub async fn run_emitter(&self, emit: F) -> ! where - F: FnMut(PriorityLimiterStats, u32) -> Fut, + F: FnMut(PriorityLimiterStats) -> Fut, Fut: Future, { - run_emitter(|| (self.stats(), self.take_peak()), emit).await + let snapshot = || PriorityLimiterStats { + in_use_peak: self.take_peak(), + ..self.stats() + }; + run_emitter(snapshot, emit).await } } @@ -339,9 +358,9 @@ type WaiterQueue = BTreeMap>; #[derive(Debug)] struct PriorityState { free: u32, - /// Highest number of permits in use since the emitter last took it. Handing a slot to a - /// waiter keeps it in use, so only taking a free permit can raise this. - peak_in_use: u32, + /// Most permits in use at once since the emitter last took it. Handing a slot to a waiter + /// keeps it in use, so only taking a free permit can raise this. + in_use_peak: u32, next_id: u64, normal_queue: WaiterQueue, high_queue: WaiterQueue, @@ -392,6 +411,15 @@ mod tests { const TIMEOUT: Duration = Duration::from_secs(1); + /// Stats of a limiter with nothing in use or waiting, after at most `in_use_peak` permits + /// were in use at once. + fn idle(in_use_peak: u32) -> PriorityLimiterStats { + PriorityLimiterStats { + in_use_peak, + ..Default::default() + } + } + #[tokio::test(start_paused = true)] async fn emitter_reports_current_limiter_usage() { let priority = PriorityLimiter::new(NonZeroU32::MIN, TIMEOUT, TIMEOUT, None, None); @@ -400,11 +428,11 @@ mod tests { let simple_permit = simple.acquire().await.unwrap(); let (priority_sender, mut priority_receiver) = tokio::sync::mpsc::unbounded_channel(); let (simple_sender, mut simple_receiver) = tokio::sync::mpsc::unbounded_channel(); - let priority_emitter = priority.run_emitter(|stats, _| { + let priority_emitter = priority.run_emitter(|stats| { priority_sender.send(stats).unwrap(); std::future::ready(()) }); - let simple_emitter = simple.run_emitter(|stats, _| { + let simple_emitter = simple.run_emitter(|stats| { simple_sender.send(stats).unwrap(); std::future::ready(()) }); @@ -419,11 +447,15 @@ mod tests { tokio::time::advance(Duration::from_secs(1)).await; assert!(poll!(&mut priority_emitter).is_pending()); assert!(poll!(&mut simple_emitter).is_pending()); + // Both permits were still in use when the previous emission restarted the peak. + assert_eq!(priority_receiver.try_recv().unwrap(), idle(1)); assert_eq!( - priority_receiver.try_recv().unwrap(), - PriorityLimiterStats::default() + simple_receiver.try_recv().unwrap(), + LimiterStats { + in_use: 0, + in_use_peak: 1 + } ); - assert_eq!(simple_receiver.try_recv().unwrap(), LimiterStats::default()); } #[tokio::test(start_paused = true)] @@ -434,12 +466,16 @@ mod tests { let simple = Limiter::new(capacity, Duration::ZERO, None); let (priority_sender, mut priority_peaks) = tokio::sync::mpsc::unbounded_channel(); let (simple_sender, mut simple_peaks) = tokio::sync::mpsc::unbounded_channel(); - let priority_emitter = priority.run_emitter(|stats, peak| { - priority_sender.send((stats.in_use, peak)).unwrap(); + let priority_emitter = priority.run_emitter(|stats| { + priority_sender + .send((stats.in_use, stats.in_use_peak)) + .unwrap(); std::future::ready(()) }); - let simple_emitter = simple.run_emitter(|stats, peak| { - simple_sender.send((stats.in_use, peak)).unwrap(); + let simple_emitter = simple.run_emitter(|stats| { + simple_sender + .send((stats.in_use, stats.in_use_peak)) + .unwrap(); std::future::ready(()) }); tokio::pin!(priority_emitter, simple_emitter); @@ -628,6 +664,7 @@ mod tests { limiter.stats(), PriorityLimiterStats { in_use: 1, + in_use_peak: 1, waiting_normal: 2, waiting_high: 2 } @@ -638,6 +675,7 @@ mod tests { limiter.stats(), PriorityLimiterStats { in_use: 1, + in_use_peak: 1, waiting_normal: 2, waiting_high: 1 } @@ -659,7 +697,7 @@ mod tests { assert!(poll!(&mut newcomer).is_pending()); drop(normal2.await.unwrap()); drop(newcomer.await.unwrap()); - assert_eq!(limiter.stats(), PriorityLimiterStats::default()); + assert_eq!(limiter.stats(), idle(1)); } #[tokio::test(start_paused = true)] @@ -681,6 +719,7 @@ mod tests { limiter.stats(), PriorityLimiterStats { in_use: 3, + in_use_peak: 3, waiting_normal: 0, waiting_high: 0 } @@ -688,7 +727,7 @@ mod tests { for waiter in &mut waiters { assert!(poll!(waiter).is_ready()); } - assert_eq!(limiter.stats(), PriorityLimiterStats::default()); + assert_eq!(limiter.stats(), idle(3)); } #[tokio::test(start_paused = true)] @@ -739,7 +778,7 @@ mod tests { drop(other); drop(held); drop(next.await.unwrap()); - assert_eq!(limiter.stats(), PriorityLimiterStats::default()); + assert_eq!(limiter.stats(), idle(1)); } } @@ -756,7 +795,7 @@ mod tests { drop(held); drop(cancelled); drop(next.await.unwrap()); - assert_eq!(limiter.stats(), PriorityLimiterStats::default()); + assert_eq!(limiter.stats(), idle(1)); // Both normal queue slots must be available after cancellation and completion. let held = limiter.acquire(Priority::Normal).await.unwrap(); let mut first = Box::pin(limiter.acquire(Priority::Normal)); @@ -829,7 +868,7 @@ mod tests { assert!(poll!(&mut retry).is_pending()); drop(held); drop(retry.await.unwrap()); - assert_eq!(limiter.stats(), PriorityLimiterStats::default()); + assert_eq!(limiter.stats(), idle(1)); } } @@ -874,7 +913,9 @@ mod tests { task.await.unwrap(); } - assert_eq!(limiter.stats(), PriorityLimiterStats::default()); + let stats = limiter.stats(); + assert!(stats.in_use_peak <= CAPACITY); + assert_eq!(stats, idle(stats.in_use_peak)); let mut permits = Vec::new(); for _ in 0..CAPACITY { permits.push(limiter.acquire(Priority::Normal).await.unwrap()); diff --git a/objectstore-service/src/service.rs b/objectstore-service/src/service.rs index a621aea9..5b4502dc 100644 --- a/objectstore-service/src/service.rs +++ b/objectstore-service/src/service.rs @@ -186,9 +186,11 @@ impl StorageService { tokio::spawn(async move { concurrency - .run_emitter(|stats, in_use_peak| async move { + .run_emitter(|stats| async move { objectstore_metrics::gauge!("service.concurrency.in_use" = stats.in_use); - objectstore_metrics::record!("service.concurrency.in_use_peak" = in_use_peak); + objectstore_metrics::record!( + "service.concurrency.in_use_peak" = stats.in_use_peak + ); objectstore_metrics::gauge!("service.concurrency.queued" = stats.queued); objectstore_metrics::gauge!( "service.concurrency.bulk_in_use" = stats.bulk_in_use From 55de42ae0e1c6a7b7aae8753735141346248351d Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:34:07 +0100 Subject: [PATCH 03/11] chore(python-client): Restore changelog whitespace The previous commit included an unrelated whitespace fix by accident. --- clients/python/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clients/python/CHANGELOG.md b/clients/python/CHANGELOG.md index 182a4ca7..cd3d5a5e 100644 --- a/clients/python/CHANGELOG.md +++ b/clients/python/CHANGELOG.md @@ -20,7 +20,7 @@ ```python # Before client = Client(url, token=SecretKey(kid, secret_key, expiry_seconds=300)) - + # After key = SecretKey(kid, secret_key) client = Client(url, token=TokenGenerator(key, expiry_seconds=300)) From 7931b2fb646b18037da39dc2bd7d85820b41c986 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:59:17 +0100 Subject: [PATCH 04/11] fix(service): Make limiter peaks consistent and track the bulk budget Take each stats snapshot in one step, so that a peak is never lower than the permits in use and never restarts at a stale count. Track a separate peak for the bulk budget, which rejects bulk operations while execution permits are free. --- objectstore-service/src/concurrency.rs | 75 ++++++++----- .../src/concurrency/limiter.rs | 105 +++++++++--------- objectstore-service/src/service.rs | 4 + 3 files changed, 103 insertions(+), 81 deletions(-) diff --git a/objectstore-service/src/concurrency.rs b/objectstore-service/src/concurrency.rs index 98e62413..8e1d40d4 100644 --- a/objectstore-service/src/concurrency.rs +++ b/objectstore-service/src/concurrency.rs @@ -12,7 +12,8 @@ //! Every limiter has a `run_emitter` method that reports its stats once per second. Since the //! permits in use at that moment miss shorter bursts, the stats also contain the peak permits //! in use since the previous report. A limiter that had no free permit for an acquisition -//! always reports a peak equal to its capacity. +//! always reports a peak equal to its capacity. [`ConcurrencyLimiter`] tracks a second peak for +//! its bulk budget, which can reject bulk operations while execution permits are free. //! //! [`run_metered`] runs an isolated task and waits for its result, while //! [`spawn_metered`] starts the same task without waiting. Both provide panic @@ -53,6 +54,8 @@ pub struct Stats { pub queued: u32, /// Number of bulk operations currently in flight. pub bulk_in_use: u32, + /// Most bulk operations in flight at once, over the same time as `in_use_peak`. + pub bulk_in_use_peak: u32, } /// Limits concurrent backend operations and tracks in-flight count. @@ -72,6 +75,7 @@ pub struct ConcurrencyLimiter { queue: Arc, bulk: Arc, in_use_peak: Arc, + bulk_in_use_peak: Arc, tasks_total: u32, queue_total: u32, bulk_total: u32, @@ -93,6 +97,7 @@ impl ConcurrencyLimiter { queue: Arc::new(Semaphore::new(0)), bulk: Arc::new(Semaphore::new(max as usize)), in_use_peak: Arc::default(), + bulk_in_use_peak: Arc::default(), tasks_total: max, queue_total: 0, bulk_total: max, @@ -205,7 +210,13 @@ impl ConcurrencyLimiter { } let acquire = async { - let bulk_permit = self.bulk.clone().acquire_owned().await?; + let free_bulk_permit = self + .bulk_in_use_peak + .try_acquire(&self.bulk, self.bulk_total); + let bulk_permit = match free_bulk_permit { + Some(bulk_permit) => bulk_permit, + None => self.bulk.clone().acquire_owned().await?, + }; let task_permit = match self.try_acquire_task() { Some(task_permit) => task_permit, None => self.tasks.clone().acquire_owned().await?, @@ -227,19 +238,7 @@ impl ConcurrencyLimiter { /// Takes a free execution permit without waiting, tracking the peak permits in use. fn try_acquire_task(&self) -> Option { - match self.tasks.clone().try_acquire_owned() { - Ok(permit) => { - // A release between the acquisition and this read lowers the reading. - self.in_use_peak.observe(self.used_permits()); - Some(permit) - } - Err(_) => { - // No permit was free. Recording that here makes every rejection and wait show - // up as a full limiter, whatever is released right after. - self.in_use_peak.observe(self.tasks_total); - None - } - } + self.in_use_peak.try_acquire(&self.tasks, self.tasks_total) } /// Returns the number of permits currently available. @@ -293,18 +292,28 @@ impl ConcurrencyLimiter { /// Returns a snapshot of the current counts. pub fn stats(&self) -> Stats { + self.snapshot(false) + } + + fn snapshot(&self, restart_peaks: bool) -> Stats { + // Each count is read right before its peak restarts there, so that a restarted peak + // does not include permits that were released in between. let in_use = self.used_permits(); + let in_use_peak = self.in_use_peak.read(in_use, restart_peaks); + let bulk_in_use = self.used_bulk_permits(); + let bulk_in_use_peak = self.bulk_in_use_peak.read(bulk_in_use, restart_peaks); Stats { in_use, - in_use_peak: self.in_use_peak.get(in_use), + in_use_peak, queued: self.queued_permits(), - bulk_in_use: self.used_bulk_permits(), + bulk_in_use, + bulk_in_use_peak, } } /// Periodically calls `emit` with the current in-use and queued counts. /// - /// Each call restarts the peak, so it covers the time since the previous call. + /// Each call restarts the peaks, so they cover the time since the previous call. /// /// This future runs forever and is intended to be spawned as a background /// task alongside the service. @@ -316,13 +325,7 @@ impl ConcurrencyLimiter { let mut ticker = tokio::time::interval(EMITTER_INTERVAL); loop { ticker.tick().await; - let stats = self.stats(); - let in_use_peak = self.in_use_peak.take(stats.in_use); - emit(Stats { - in_use_peak, - ..stats - }) - .await; + emit(self.snapshot(true)).await; } } } @@ -582,7 +585,7 @@ mod tests { limiter.try_acquire().unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.in_use_peak.take(1), 2); + assert_eq!(limiter.in_use_peak.read(1, true), 2); let mut waiting: std::pin::Pin>> = match bulk { false => Box::pin(limiter.acquire()), true => Box::pin(limiter.acquire_bulk()), @@ -590,10 +593,28 @@ mod tests { assert!(futures::poll!(&mut waiting).is_pending()); drop(waiting); drop(held); - assert_eq!(limiter.in_use_peak.take(0), 2); + assert_eq!(limiter.stats().in_use_peak, 2); } } + #[tokio::test(start_paused = true)] + async fn bulk_contention_marks_only_the_bulk_budget_as_full() { + let limiter = ConcurrencyLimiter::new(4).with_bulk(50); + let held = ( + limiter.acquire_bulk().await.unwrap(), + limiter.acquire_bulk().await.unwrap(), + ); + // Lower the peak so that only the failed acquisition can raise it back to capacity. + assert_eq!(limiter.bulk_in_use_peak.read(1, true), 2); + limiter.acquire_bulk().await.unwrap_err(); + drop(held); + + let stats = limiter.stats(); + assert_eq!(stats.bulk_in_use_peak, limiter.total_bulk()); + // Execution permits were free throughout, so only the bulk peak shows the rejection. + assert_eq!(stats.in_use_peak, 2); + } + #[tokio::test] async fn wait_all_resolves_when_permits_returned() { let limiter = ConcurrencyLimiter::new(2); diff --git a/objectstore-service/src/concurrency/limiter.rs b/objectstore-service/src/concurrency/limiter.rs index 060298ed..634b8865 100644 --- a/objectstore-service/src/concurrency/limiter.rs +++ b/objectstore-service/src/concurrency/limiter.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use std::future::Future; use std::io; -use std::mem::{self, DropGuard}; +use std::mem::DropGuard; use std::num::NonZeroU32; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; @@ -75,30 +75,43 @@ pub struct LimiterStats { pub in_use_peak: u32, } -/// High-water mark of the permits in use, for limiters that count them outside of a lock. +/// High-water mark of the permits in use of a semaphore. /// /// A periodic snapshot misses bursts that start and end between two snapshots, so limiters -/// also [`observe`](Self::observe) their usage as permits are acquired. +/// acquire free permits through [`try_acquire`](Self::try_acquire), which tracks their usage. #[derive(Debug, Default)] pub(super) struct Peak(AtomicU32); impl Peak { - /// Raises the mark to `in_use` if that is higher. - pub(super) fn observe(&self, in_use: u32) { + /// Takes a free permit from `semaphore` without waiting and raises the mark to the + /// resulting number of its `capacity` permits in use. + pub(super) fn try_acquire( + &self, + semaphore: &Arc, + capacity: u32, + ) -> Option { + let permit = semaphore.clone().try_acquire_owned().ok(); + let in_use = match permit { + // A release between the acquisition and this read lowers the reading. + Some(_) => capacity - semaphore.available_permits() as u32, + // No permit was free. Recording that here makes every rejection and wait show up + // as a full limiter, whatever is released right after. + None => capacity, + }; self.0.fetch_max(in_use, Ordering::Relaxed); + permit } - /// Returns the highest count since the previous [`take`](Self::take). - pub(super) fn get(&self, in_use: u32) -> u32 { - self.0.load(Ordering::Relaxed).max(in_use) - } - - /// Returns the highest count since the previous call and restarts the mark at `in_use`. + /// Returns the highest number of permits in use since the mark was last restarted. /// - /// Restarting at the current count instead of zero keeps permits visible that stay held - /// while nothing new is acquired. - pub(super) fn take(&self, in_use: u32) -> u32 { - self.0.swap(in_use, Ordering::Relaxed).max(in_use) + /// `in_use` is the current number. With `restart`, the mark restarts there instead of at + /// zero, which keeps permits visible that stay held while nothing new is acquired. + pub(super) fn read(&self, in_use: u32, restart: bool) -> u32 { + let peak = match restart { + true => self.0.swap(in_use, Ordering::Relaxed), + false => self.0.load(Ordering::Relaxed), + }; + peak.max(in_use) } } @@ -143,14 +156,9 @@ impl Limiter { /// Returns [`ErrorKind::AtCapacity`] when the queue is full or the wait times out. /// Dropping the future releases its queue slot and any assigned permit. pub async fn acquire(&self) -> Result { - if let Ok(permit) = self.semaphore.clone().try_acquire_owned() { - // A release between the acquisition and this read lowers the reading. - self.peak.observe(self.in_use()); + if let Some(permit) = self.peak.try_acquire(&self.semaphore, self.capacity) { return Ok(Permit::semaphore(permit)); } - // No permit was free. Recording that here makes every rejection and wait show up as a - // full limiter, whatever is released right after. - self.peak.observe(self.capacity); if self.timeout.is_zero() { return Err(ErrorKind::AtCapacity.into()); } @@ -167,16 +175,16 @@ impl Limiter { Ok(Permit::semaphore(permit)) } - fn in_use(&self) -> u32 { - self.capacity - self.semaphore.available_permits() as u32 - } - /// Returns the current and peak number of permits in use. pub fn stats(&self) -> LimiterStats { - let in_use = self.in_use(); + self.snapshot(false) + } + + fn snapshot(&self, restart_peak: bool) -> LimiterStats { + let in_use = self.capacity - self.semaphore.available_permits() as u32; LimiterStats { in_use, - in_use_peak: self.peak.get(in_use), + in_use_peak: self.peak.read(in_use, restart_peak), } } @@ -188,14 +196,7 @@ impl Limiter { F: FnMut(LimiterStats) -> Fut, Fut: Future, { - let snapshot = || { - let stats = self.stats(); - LimiterStats { - in_use_peak: self.peak.take(stats.in_use), - ..stats - } - }; - run_emitter(snapshot, emit).await + run_emitter(|| self.snapshot(true), emit).await } } @@ -314,23 +315,23 @@ impl PriorityLimiter { /// Returns a snapshot of permits in use and queued acquisitions. pub fn stats(&self) -> PriorityLimiterStats { - let state = self.state.lock().unwrap_or_else(PoisonError::into_inner); - PriorityLimiterStats { + self.snapshot(false) + } + + fn snapshot(&self, restart_peak: bool) -> PriorityLimiterStats { + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + let stats = PriorityLimiterStats { in_use: self.capacity - state.free, in_use_peak: state.in_use_peak, waiting_normal: state.normal_queue.len(), waiting_high: state.high_queue.len(), + }; + if restart_peak { + // Restarting at the current number instead of zero keeps permits visible that stay + // held while nothing new is acquired. + state.in_use_peak = stats.in_use; } - } - - /// Returns the highest number of permits in use since the previous call. - /// - /// The next peak starts at the current number instead of zero, which keeps permits visible - /// that stay held while nothing new is acquired. - fn take_peak(&self) -> u32 { - let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); - let in_use = self.capacity - state.free; - mem::replace(&mut state.in_use_peak, in_use) + stats } /// Passes this limiter's stats to `emit` immediately and once per second thereafter. @@ -341,11 +342,7 @@ impl PriorityLimiter { F: FnMut(PriorityLimiterStats) -> Fut, Fut: Future, { - let snapshot = || PriorityLimiterStats { - in_use_peak: self.take_peak(), - ..self.stats() - }; - run_emitter(snapshot, emit).await + run_emitter(|| self.snapshot(true), emit).await } } @@ -518,10 +515,10 @@ mod tests { limiter.acquire().await.unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.peak.take(1), 2); + assert_eq!(limiter.peak.read(1, true), 2); limiter.acquire().await.unwrap_err(); drop(held); - assert_eq!(limiter.peak.take(0), 2); + assert_eq!(limiter.stats().in_use_peak, 2); } #[tokio::test(start_paused = true)] diff --git a/objectstore-service/src/service.rs b/objectstore-service/src/service.rs index 5b4502dc..f5ab15f7 100644 --- a/objectstore-service/src/service.rs +++ b/objectstore-service/src/service.rs @@ -173,6 +173,7 @@ impl StorageService { /// - `service.concurrency.in_use_peak` (distribution): most tasks running at once since the /// previous emission. Unlike the gauges, which only keep the last value of each flush /// interval, its `max` over any period is the true peak. + /// - `service.concurrency.bulk_in_use_peak` (distribution): the same for bulk tasks /// - `service.concurrency.queued`: currently queued tasks /// - `service.concurrency.bulk_in_use`: currently running bulk tasks /// - `service.expiry_renewal.queued`: expiry renewals waiting for the background worker @@ -195,6 +196,9 @@ impl StorageService { objectstore_metrics::gauge!( "service.concurrency.bulk_in_use" = stats.bulk_in_use ); + objectstore_metrics::record!( + "service.concurrency.bulk_in_use_peak" = stats.bulk_in_use_peak + ); }) .await; }); From 65c89911a68b90889d18de09c98a54abaf7ba831 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:08:12 +0100 Subject: [PATCH 05/11] ref(service): Restart limiter peaks in stats instead of a snapshot flag Only the emitters read the stats in production, so the separate read-only path is not needed. --- objectstore-service/src/concurrency.rs | 24 ++++---- .../src/concurrency/limiter.rs | 56 ++++++++----------- 2 files changed, 32 insertions(+), 48 deletions(-) diff --git a/objectstore-service/src/concurrency.rs b/objectstore-service/src/concurrency.rs index 8e1d40d4..2dbc610a 100644 --- a/objectstore-service/src/concurrency.rs +++ b/objectstore-service/src/concurrency.rs @@ -46,9 +46,8 @@ const EMITTER_INTERVAL: Duration = Duration::from_secs(1); pub struct Stats { /// Number of execution permits currently held. pub in_use: u32, - /// Most execution permits held at once since [`ConcurrencyLimiter::run_emitter`] last - /// reported, or since the limiter was created. Unlike `in_use`, this captures bursts between - /// two reports. + /// Most execution permits held at once since the previous call to + /// [`ConcurrencyLimiter::stats`]. Unlike `in_use`, this captures bursts between two calls. pub in_use_peak: u32, /// Number of callers waiting in the queue for a permit. pub queued: u32, @@ -291,17 +290,16 @@ impl ConcurrencyLimiter { } /// Returns a snapshot of the current counts. + /// + /// Each call restarts the peaks. [`run_emitter`](Self::run_emitter) calls this, so another + /// caller takes away from the peaks that the emitter reports. pub fn stats(&self) -> Stats { - self.snapshot(false) - } - - fn snapshot(&self, restart_peaks: bool) -> Stats { // Each count is read right before its peak restarts there, so that a restarted peak // does not include permits that were released in between. let in_use = self.used_permits(); - let in_use_peak = self.in_use_peak.read(in_use, restart_peaks); + let in_use_peak = self.in_use_peak.take(in_use); let bulk_in_use = self.used_bulk_permits(); - let bulk_in_use_peak = self.bulk_in_use_peak.read(bulk_in_use, restart_peaks); + let bulk_in_use_peak = self.bulk_in_use_peak.take(bulk_in_use); Stats { in_use, in_use_peak, @@ -313,8 +311,6 @@ impl ConcurrencyLimiter { /// Periodically calls `emit` with the current in-use and queued counts. /// - /// Each call restarts the peaks, so they cover the time since the previous call. - /// /// This future runs forever and is intended to be spawned as a background /// task alongside the service. pub async fn run_emitter(&self, mut emit: F) -> ! @@ -325,7 +321,7 @@ impl ConcurrencyLimiter { let mut ticker = tokio::time::interval(EMITTER_INTERVAL); loop { ticker.tick().await; - emit(self.snapshot(true)).await; + emit(self.stats()).await; } } } @@ -585,7 +581,7 @@ mod tests { limiter.try_acquire().unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.in_use_peak.read(1, true), 2); + assert_eq!(limiter.in_use_peak.take(1), 2); let mut waiting: std::pin::Pin>> = match bulk { false => Box::pin(limiter.acquire()), true => Box::pin(limiter.acquire_bulk()), @@ -605,7 +601,7 @@ mod tests { limiter.acquire_bulk().await.unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.bulk_in_use_peak.read(1, true), 2); + assert_eq!(limiter.bulk_in_use_peak.take(1), 2); limiter.acquire_bulk().await.unwrap_err(); drop(held); diff --git a/objectstore-service/src/concurrency/limiter.rs b/objectstore-service/src/concurrency/limiter.rs index 634b8865..f07e0276 100644 --- a/objectstore-service/src/concurrency/limiter.rs +++ b/objectstore-service/src/concurrency/limiter.rs @@ -70,8 +70,8 @@ impl Permit { pub struct LimiterStats { /// Permits currently in use. pub in_use: u32, - /// Most permits in use at once since [`Limiter::run_emitter`] last reported, or since the - /// limiter was created. Unlike `in_use`, this captures bursts between two reports. + /// Most permits in use at once since the previous call to [`Limiter::stats`]. Unlike + /// `in_use`, this captures bursts between two calls. pub in_use_peak: u32, } @@ -102,16 +102,12 @@ impl Peak { permit } - /// Returns the highest number of permits in use since the mark was last restarted. + /// Returns the highest number of permits in use since the previous call. /// - /// `in_use` is the current number. With `restart`, the mark restarts there instead of at - /// zero, which keeps permits visible that stay held while nothing new is acquired. - pub(super) fn read(&self, in_use: u32, restart: bool) -> u32 { - let peak = match restart { - true => self.0.swap(in_use, Ordering::Relaxed), - false => self.0.load(Ordering::Relaxed), - }; - peak.max(in_use) + /// The mark restarts at `in_use`, the current number, instead of at zero. This keeps + /// permits visible that stay held while nothing new is acquired. + pub(super) fn take(&self, in_use: u32) -> u32 { + self.0.swap(in_use, Ordering::Relaxed).max(in_use) } } @@ -176,27 +172,24 @@ impl Limiter { } /// Returns the current and peak number of permits in use. + /// + /// Each call restarts the peak. [`run_emitter`](Self::run_emitter) calls this, so another + /// caller takes away from the peak that the emitter reports. pub fn stats(&self) -> LimiterStats { - self.snapshot(false) - } - - fn snapshot(&self, restart_peak: bool) -> LimiterStats { let in_use = self.capacity - self.semaphore.available_permits() as u32; LimiterStats { in_use, - in_use_peak: self.peak.read(in_use, restart_peak), + in_use_peak: self.peak.take(in_use), } } /// Passes this limiter's stats to `emit` immediately and once per second thereafter. - /// - /// Each call restarts the peak, so it covers the time since the previous call. pub async fn run_emitter(&self, emit: F) -> ! where F: FnMut(LimiterStats) -> Fut, Fut: Future, { - run_emitter(|| self.snapshot(true), emit).await + run_emitter(|| self.stats(), emit).await } } @@ -214,8 +207,8 @@ pub enum Priority { pub struct PriorityLimiterStats { /// Permits currently in use. pub in_use: u32, - /// Most permits in use at once since [`PriorityLimiter::run_emitter`] last reported, or - /// since the limiter was created. Unlike `in_use`, this captures bursts between two reports. + /// Most permits in use at once since the previous call to [`PriorityLimiter::stats`]. + /// Unlike `in_use`, this captures bursts between two calls. pub in_use_peak: u32, /// Normal-priority acquisitions waiting in the queue. pub waiting_normal: usize, @@ -314,11 +307,10 @@ impl PriorityLimiter { } /// Returns a snapshot of permits in use and queued acquisitions. + /// + /// Each call restarts the peak. [`run_emitter`](Self::run_emitter) calls this, so another + /// caller takes away from the peak that the emitter reports. pub fn stats(&self) -> PriorityLimiterStats { - self.snapshot(false) - } - - fn snapshot(&self, restart_peak: bool) -> PriorityLimiterStats { let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); let stats = PriorityLimiterStats { in_use: self.capacity - state.free, @@ -326,23 +318,19 @@ impl PriorityLimiter { waiting_normal: state.normal_queue.len(), waiting_high: state.high_queue.len(), }; - if restart_peak { - // Restarting at the current number instead of zero keeps permits visible that stay - // held while nothing new is acquired. - state.in_use_peak = stats.in_use; - } + // Restarting at the current number instead of zero keeps permits visible that stay held + // while nothing new is acquired. + state.in_use_peak = stats.in_use; stats } /// Passes this limiter's stats to `emit` immediately and once per second thereafter. - /// - /// Each call restarts the peak, so it covers the time since the previous call. pub async fn run_emitter(&self, emit: F) -> ! where F: FnMut(PriorityLimiterStats) -> Fut, Fut: Future, { - run_emitter(|| self.snapshot(true), emit).await + run_emitter(|| self.stats(), emit).await } } @@ -515,7 +503,7 @@ mod tests { limiter.acquire().await.unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.peak.read(1, true), 2); + assert_eq!(limiter.peak.take(1), 2); limiter.acquire().await.unwrap_err(); drop(held); assert_eq!(limiter.stats().in_use_peak, 2); From b3881e4cff2c2768c2e9df63fd2bbf28fd7857a7 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:13:19 +0100 Subject: [PATCH 06/11] ref(service): Track acquisitions in a free function and drop helpers Move the peak-tracking acquisition out of the Peak type, inline its single-purpose wrapper in the service limiter, and write the expected stats out in the tests instead of using a helper. --- objectstore-service/src/concurrency.rs | 23 ++-- .../src/concurrency/limiter.rs | 105 ++++++++++++------ 2 files changed, 81 insertions(+), 47 deletions(-) diff --git a/objectstore-service/src/concurrency.rs b/objectstore-service/src/concurrency.rs index 2dbc610a..fe91be43 100644 --- a/objectstore-service/src/concurrency.rs +++ b/objectstore-service/src/concurrency.rs @@ -31,8 +31,8 @@ use crate::error::{Error, ErrorKind, Panic, Result}; mod limiter; -use limiter::Peak; pub use limiter::{Limiter, LimiterStats, Permit, Priority, PriorityLimiter, PriorityLimiterStats}; +use limiter::{Peak, try_acquire_tracked}; /// Interval for the periodic metrics emitter. const EMITTER_INTERVAL: Duration = Duration::from_secs(1); @@ -152,7 +152,8 @@ impl ConcurrencyLimiter { } // Fast path: Instantly grab a free permit without parking. - if let Some(task_permit) = self.try_acquire_task() { + let free_permit = try_acquire_tracked(&self.tasks, self.tasks_total, &self.in_use_peak); + if let Some(task_permit) = free_permit { return Ok(ConcurrencyPermit { task_permit: Some(task_permit), bulk_permit: None, @@ -185,7 +186,8 @@ impl ConcurrencyLimiter { /// /// Returns [`ErrorKind::AtCapacity`] when no permits are available. pub fn try_acquire(&self) -> Result { - let task_permit = self.try_acquire_task().ok_or(ErrorKind::AtCapacity)?; + let task_permit = try_acquire_tracked(&self.tasks, self.tasks_total, &self.in_use_peak) + .ok_or(ErrorKind::AtCapacity)?; Ok(ConcurrencyPermit { task_permit: Some(task_permit), @@ -209,14 +211,14 @@ impl ConcurrencyLimiter { } let acquire = async { - let free_bulk_permit = self - .bulk_in_use_peak - .try_acquire(&self.bulk, self.bulk_total); - let bulk_permit = match free_bulk_permit { + let free_permit = + try_acquire_tracked(&self.bulk, self.bulk_total, &self.bulk_in_use_peak); + let bulk_permit = match free_permit { Some(bulk_permit) => bulk_permit, None => self.bulk.clone().acquire_owned().await?, }; - let task_permit = match self.try_acquire_task() { + let free_permit = try_acquire_tracked(&self.tasks, self.tasks_total, &self.in_use_peak); + let task_permit = match free_permit { Some(task_permit) => task_permit, None => self.tasks.clone().acquire_owned().await?, }; @@ -235,11 +237,6 @@ impl ConcurrencyLimiter { }) } - /// Takes a free execution permit without waiting, tracking the peak permits in use. - fn try_acquire_task(&self) -> Option { - self.in_use_peak.try_acquire(&self.tasks, self.tasks_total) - } - /// Returns the number of permits currently available. pub fn available_permits(&self) -> u32 { u32::try_from(self.tasks.available_permits()).unwrap_or(self.tasks_total) diff --git a/objectstore-service/src/concurrency/limiter.rs b/objectstore-service/src/concurrency/limiter.rs index f07e0276..c2928ce9 100644 --- a/objectstore-service/src/concurrency/limiter.rs +++ b/objectstore-service/src/concurrency/limiter.rs @@ -78,28 +78,14 @@ pub struct LimiterStats { /// High-water mark of the permits in use of a semaphore. /// /// A periodic snapshot misses bursts that start and end between two snapshots, so limiters -/// acquire free permits through [`try_acquire`](Self::try_acquire), which tracks their usage. +/// acquire free permits through [`try_acquire_tracked`], which raises the mark. #[derive(Debug, Default)] pub(super) struct Peak(AtomicU32); impl Peak { - /// Takes a free permit from `semaphore` without waiting and raises the mark to the - /// resulting number of its `capacity` permits in use. - pub(super) fn try_acquire( - &self, - semaphore: &Arc, - capacity: u32, - ) -> Option { - let permit = semaphore.clone().try_acquire_owned().ok(); - let in_use = match permit { - // A release between the acquisition and this read lowers the reading. - Some(_) => capacity - semaphore.available_permits() as u32, - // No permit was free. Recording that here makes every rejection and wait show up - // as a full limiter, whatever is released right after. - None => capacity, - }; + /// Raises the mark to `in_use` if that is higher. + fn observe(&self, in_use: u32) { self.0.fetch_max(in_use, Ordering::Relaxed); - permit } /// Returns the highest number of permits in use since the previous call. @@ -111,6 +97,24 @@ impl Peak { } } +/// Takes a free permit from `semaphore` without waiting and raises `peak` to the resulting +/// number of its `capacity` permits in use. +pub(super) fn try_acquire_tracked( + semaphore: &Arc, + capacity: u32, + peak: &Peak, +) -> Option { + let permit = semaphore.clone().try_acquire_owned().ok(); + peak.observe(match permit { + // A release between the acquisition and this read lowers the reading. + Some(_) => capacity - semaphore.available_permits() as u32, + // No permit was free. Recording that here makes every rejection and wait show up as a + // full limiter, whatever is released right after. + None => capacity, + }); + permit +} + /// Shared interval loop for the metric emitters. async fn run_emitter(mut snapshot: impl FnMut() -> S, mut emit: F) -> ! where @@ -152,7 +156,7 @@ impl Limiter { /// Returns [`ErrorKind::AtCapacity`] when the queue is full or the wait times out. /// Dropping the future releases its queue slot and any assigned permit. pub async fn acquire(&self) -> Result { - if let Some(permit) = self.peak.try_acquire(&self.semaphore, self.capacity) { + if let Some(permit) = try_acquire_tracked(&self.semaphore, self.capacity, &self.peak) { return Ok(Permit::semaphore(permit)); } if self.timeout.is_zero() { @@ -396,15 +400,6 @@ mod tests { const TIMEOUT: Duration = Duration::from_secs(1); - /// Stats of a limiter with nothing in use or waiting, after at most `in_use_peak` permits - /// were in use at once. - fn idle(in_use_peak: u32) -> PriorityLimiterStats { - PriorityLimiterStats { - in_use_peak, - ..Default::default() - } - } - #[tokio::test(start_paused = true)] async fn emitter_reports_current_limiter_usage() { let priority = PriorityLimiter::new(NonZeroU32::MIN, TIMEOUT, TIMEOUT, None, None); @@ -433,7 +428,13 @@ mod tests { assert!(poll!(&mut priority_emitter).is_pending()); assert!(poll!(&mut simple_emitter).is_pending()); // Both permits were still in use when the previous emission restarted the peak. - assert_eq!(priority_receiver.try_recv().unwrap(), idle(1)); + assert_eq!( + priority_receiver.try_recv().unwrap(), + PriorityLimiterStats { + in_use_peak: 1, + ..Default::default() + } + ); assert_eq!( simple_receiver.try_recv().unwrap(), LimiterStats { @@ -682,7 +683,13 @@ mod tests { assert!(poll!(&mut newcomer).is_pending()); drop(normal2.await.unwrap()); drop(newcomer.await.unwrap()); - assert_eq!(limiter.stats(), idle(1)); + assert_eq!( + limiter.stats(), + PriorityLimiterStats { + in_use_peak: 1, + ..Default::default() + } + ); } #[tokio::test(start_paused = true)] @@ -712,7 +719,13 @@ mod tests { for waiter in &mut waiters { assert!(poll!(waiter).is_ready()); } - assert_eq!(limiter.stats(), idle(3)); + assert_eq!( + limiter.stats(), + PriorityLimiterStats { + in_use_peak: 3, + ..Default::default() + } + ); } #[tokio::test(start_paused = true)] @@ -763,7 +776,13 @@ mod tests { drop(other); drop(held); drop(next.await.unwrap()); - assert_eq!(limiter.stats(), idle(1)); + assert_eq!( + limiter.stats(), + PriorityLimiterStats { + in_use_peak: 1, + ..Default::default() + } + ); } } @@ -780,7 +799,13 @@ mod tests { drop(held); drop(cancelled); drop(next.await.unwrap()); - assert_eq!(limiter.stats(), idle(1)); + assert_eq!( + limiter.stats(), + PriorityLimiterStats { + in_use_peak: 1, + ..Default::default() + } + ); // Both normal queue slots must be available after cancellation and completion. let held = limiter.acquire(Priority::Normal).await.unwrap(); let mut first = Box::pin(limiter.acquire(Priority::Normal)); @@ -853,7 +878,13 @@ mod tests { assert!(poll!(&mut retry).is_pending()); drop(held); drop(retry.await.unwrap()); - assert_eq!(limiter.stats(), idle(1)); + assert_eq!( + limiter.stats(), + PriorityLimiterStats { + in_use_peak: 1, + ..Default::default() + } + ); } } @@ -900,7 +931,13 @@ mod tests { let stats = limiter.stats(); assert!(stats.in_use_peak <= CAPACITY); - assert_eq!(stats, idle(stats.in_use_peak)); + assert_eq!( + stats, + PriorityLimiterStats { + in_use_peak: stats.in_use_peak, + ..Default::default() + } + ); let mut permits = Vec::new(); for _ in 0..CAPACITY { permits.push(limiter.acquire(Priority::Normal).await.unwrap()); From 026954b25dc950f30e23d27413f284c37a1f1bb4 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:30:45 +0100 Subject: [PATCH 07/11] ref(service): Track limiter peaks with plain atomics Replace the Peak type and its acquisition function with an atomic per limiter that the acquire paths raise directly. --- objectstore-service/src/concurrency.rs | 71 +++++++++++-------- .../src/concurrency/limiter.rs | 63 +++++----------- 2 files changed, 59 insertions(+), 75 deletions(-) diff --git a/objectstore-service/src/concurrency.rs b/objectstore-service/src/concurrency.rs index fe91be43..e6816616 100644 --- a/objectstore-service/src/concurrency.rs +++ b/objectstore-service/src/concurrency.rs @@ -11,9 +11,9 @@ //! //! Every limiter has a `run_emitter` method that reports its stats once per second. Since the //! permits in use at that moment miss shorter bursts, the stats also contain the peak permits -//! in use since the previous report. A limiter that had no free permit for an acquisition -//! always reports a peak equal to its capacity. [`ConcurrencyLimiter`] tracks a second peak for -//! its bulk budget, which can reject bulk operations while execution permits are free. +//! in use since the previous report. An acquisition that must wait or is rejected raises the +//! peak to the capacity. [`ConcurrencyLimiter`] tracks a second peak for its bulk budget, which +//! can reject bulk operations while execution permits are free. //! //! [`run_metered`] runs an isolated task and waits for its result, while //! [`spawn_metered`] starts the same task without waiting. Both provide panic @@ -21,6 +21,7 @@ use std::future::Future; use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; use std::time::Duration; use futures_util::FutureExt; @@ -32,7 +33,6 @@ use crate::error::{Error, ErrorKind, Panic, Result}; mod limiter; pub use limiter::{Limiter, LimiterStats, Permit, Priority, PriorityLimiter, PriorityLimiterStats}; -use limiter::{Peak, try_acquire_tracked}; /// Interval for the periodic metrics emitter. const EMITTER_INTERVAL: Duration = Duration::from_secs(1); @@ -73,8 +73,8 @@ pub struct ConcurrencyLimiter { tasks: Arc, queue: Arc, bulk: Arc, - in_use_peak: Arc, - bulk_in_use_peak: Arc, + in_use_peak: Arc, + bulk_in_use_peak: Arc, tasks_total: u32, queue_total: u32, bulk_total: u32, @@ -152,14 +152,19 @@ impl ConcurrencyLimiter { } // Fast path: Instantly grab a free permit without parking. - let free_permit = try_acquire_tracked(&self.tasks, self.tasks_total, &self.in_use_peak); - if let Some(task_permit) = free_permit { + if let Ok(task_permit) = self.tasks.clone().try_acquire_owned() { + self.in_use_peak + .fetch_max(self.used_permits(), Ordering::Relaxed); return Ok(ConcurrencyPermit { task_permit: Some(task_permit), bulk_permit: None, released: Arc::clone(&self.released), }); } + // No permit was free, so the limiter is full. Recording that here makes every wait and + // rejection visible, whatever is released right after. + self.in_use_peak + .fetch_max(self.tasks_total, Ordering::Relaxed); // Slow path: acquire a temporary queue ticket to bound concurrent // waiters. Released in this scope when the permit is constructed. @@ -186,8 +191,13 @@ impl ConcurrencyLimiter { /// /// Returns [`ErrorKind::AtCapacity`] when no permits are available. pub fn try_acquire(&self) -> Result { - let task_permit = try_acquire_tracked(&self.tasks, self.tasks_total, &self.in_use_peak) - .ok_or(ErrorKind::AtCapacity)?; + let Ok(task_permit) = self.tasks.clone().try_acquire_owned() else { + self.in_use_peak + .fetch_max(self.tasks_total, Ordering::Relaxed); + return Err(ErrorKind::AtCapacity.into()); + }; + self.in_use_peak + .fetch_max(self.used_permits(), Ordering::Relaxed); Ok(ConcurrencyPermit { task_permit: Some(task_permit), @@ -211,17 +221,19 @@ impl ConcurrencyLimiter { } let acquire = async { - let free_permit = - try_acquire_tracked(&self.bulk, self.bulk_total, &self.bulk_in_use_peak); - let bulk_permit = match free_permit { - Some(bulk_permit) => bulk_permit, - None => self.bulk.clone().acquire_owned().await?, - }; - let free_permit = try_acquire_tracked(&self.tasks, self.tasks_total, &self.in_use_peak); - let task_permit = match free_permit { - Some(task_permit) => task_permit, - None => self.tasks.clone().acquire_owned().await?, - }; + // The peaks are also raised before each wait, which shows a full budget or limiter + // even when the wait then times out. + self.bulk_in_use_peak + .fetch_max(self.used_bulk_permits(), Ordering::Relaxed); + let bulk_permit = self.bulk.clone().acquire_owned().await?; + self.bulk_in_use_peak + .fetch_max(self.used_bulk_permits(), Ordering::Relaxed); + + self.in_use_peak + .fetch_max(self.used_permits(), Ordering::Relaxed); + let task_permit = self.tasks.clone().acquire_owned().await?; + self.in_use_peak + .fetch_max(self.used_permits(), Ordering::Relaxed); Ok((task_permit, bulk_permit)) }; @@ -291,18 +303,19 @@ impl ConcurrencyLimiter { /// Each call restarts the peaks. [`run_emitter`](Self::run_emitter) calls this, so another /// caller takes away from the peaks that the emitter reports. pub fn stats(&self) -> Stats { - // Each count is read right before its peak restarts there, so that a restarted peak - // does not include permits that were released in between. + // Each peak restarts at the current count instead of zero, which keeps permits visible + // that stay held while nothing new is acquired. The count is read right before, so + // that the restarted peak does not include permits released in between. let in_use = self.used_permits(); - let in_use_peak = self.in_use_peak.take(in_use); + let in_use_peak = self.in_use_peak.swap(in_use, Ordering::Relaxed); let bulk_in_use = self.used_bulk_permits(); - let bulk_in_use_peak = self.bulk_in_use_peak.take(bulk_in_use); + let bulk_in_use_peak = self.bulk_in_use_peak.swap(bulk_in_use, Ordering::Relaxed); Stats { in_use, - in_use_peak, + in_use_peak: in_use_peak.max(in_use), queued: self.queued_permits(), bulk_in_use, - bulk_in_use_peak, + bulk_in_use_peak: bulk_in_use_peak.max(bulk_in_use), } } @@ -578,7 +591,7 @@ mod tests { limiter.try_acquire().unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.in_use_peak.take(1), 2); + assert_eq!(limiter.in_use_peak.swap(1, Ordering::Relaxed), 2); let mut waiting: std::pin::Pin>> = match bulk { false => Box::pin(limiter.acquire()), true => Box::pin(limiter.acquire_bulk()), @@ -598,7 +611,7 @@ mod tests { limiter.acquire_bulk().await.unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.bulk_in_use_peak.take(1), 2); + assert_eq!(limiter.bulk_in_use_peak.swap(1, Ordering::Relaxed), 2); limiter.acquire_bulk().await.unwrap_err(); drop(held); diff --git a/objectstore-service/src/concurrency/limiter.rs b/objectstore-service/src/concurrency/limiter.rs index c2928ce9..3d4218c8 100644 --- a/objectstore-service/src/concurrency/limiter.rs +++ b/objectstore-service/src/concurrency/limiter.rs @@ -75,46 +75,6 @@ pub struct LimiterStats { pub in_use_peak: u32, } -/// High-water mark of the permits in use of a semaphore. -/// -/// A periodic snapshot misses bursts that start and end between two snapshots, so limiters -/// acquire free permits through [`try_acquire_tracked`], which raises the mark. -#[derive(Debug, Default)] -pub(super) struct Peak(AtomicU32); - -impl Peak { - /// Raises the mark to `in_use` if that is higher. - fn observe(&self, in_use: u32) { - self.0.fetch_max(in_use, Ordering::Relaxed); - } - - /// Returns the highest number of permits in use since the previous call. - /// - /// The mark restarts at `in_use`, the current number, instead of at zero. This keeps - /// permits visible that stay held while nothing new is acquired. - pub(super) fn take(&self, in_use: u32) -> u32 { - self.0.swap(in_use, Ordering::Relaxed).max(in_use) - } -} - -/// Takes a free permit from `semaphore` without waiting and raises `peak` to the resulting -/// number of its `capacity` permits in use. -pub(super) fn try_acquire_tracked( - semaphore: &Arc, - capacity: u32, - peak: &Peak, -) -> Option { - let permit = semaphore.clone().try_acquire_owned().ok(); - peak.observe(match permit { - // A release between the acquisition and this read lowers the reading. - Some(_) => capacity - semaphore.available_permits() as u32, - // No permit was free. Recording that here makes every rejection and wait show up as a - // full limiter, whatever is released right after. - None => capacity, - }); - permit -} - /// Shared interval loop for the metric emitters. async fn run_emitter(mut snapshot: impl FnMut() -> S, mut emit: F) -> ! where @@ -133,7 +93,7 @@ where pub struct Limiter { semaphore: Arc, queue: Option>, - peak: Arc, + in_use_peak: Arc, capacity: u32, timeout: Duration, } @@ -145,7 +105,7 @@ impl Limiter { Self { semaphore: Arc::new(Semaphore::new(capacity as usize)), queue: max_queue_size.map(|size| Arc::new(Semaphore::new(size as usize))), - peak: Arc::default(), + in_use_peak: Arc::default(), capacity, timeout, } @@ -156,9 +116,13 @@ impl Limiter { /// Returns [`ErrorKind::AtCapacity`] when the queue is full or the wait times out. /// Dropping the future releases its queue slot and any assigned permit. pub async fn acquire(&self) -> Result { - if let Some(permit) = try_acquire_tracked(&self.semaphore, self.capacity, &self.peak) { + if let Ok(permit) = self.semaphore.clone().try_acquire_owned() { + self.in_use_peak.fetch_max(self.in_use(), Ordering::Relaxed); return Ok(Permit::semaphore(permit)); } + // No permit was free, so the limiter is full. Recording that here makes every wait and + // rejection visible, whatever is released right after. + self.in_use_peak.fetch_max(self.capacity, Ordering::Relaxed); if self.timeout.is_zero() { return Err(ErrorKind::AtCapacity.into()); } @@ -180,13 +144,20 @@ impl Limiter { /// Each call restarts the peak. [`run_emitter`](Self::run_emitter) calls this, so another /// caller takes away from the peak that the emitter reports. pub fn stats(&self) -> LimiterStats { - let in_use = self.capacity - self.semaphore.available_permits() as u32; + let in_use = self.in_use(); + // Restarting at the current number instead of zero keeps permits visible that stay held + // while nothing new is acquired. + let in_use_peak = self.in_use_peak.swap(in_use, Ordering::Relaxed); LimiterStats { in_use, - in_use_peak: self.peak.take(in_use), + in_use_peak: in_use_peak.max(in_use), } } + fn in_use(&self) -> u32 { + self.capacity - self.semaphore.available_permits() as u32 + } + /// Passes this limiter's stats to `emit` immediately and once per second thereafter. pub async fn run_emitter(&self, emit: F) -> ! where @@ -504,7 +475,7 @@ mod tests { limiter.acquire().await.unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.peak.take(1), 2); + assert_eq!(limiter.in_use_peak.swap(1, Ordering::Relaxed), 2); limiter.acquire().await.unwrap_err(); drop(held); assert_eq!(limiter.stats().in_use_peak, 2); From ae4f8a5e4e991de2dfb61064262ffe4ad1657d59 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:38:44 +0100 Subject: [PATCH 08/11] ref(service): Wrap limiter peak atomics in a Peak type --- objectstore-service/src/concurrency.rs | 48 ++++++++----------- .../src/concurrency/limiter.rs | 32 +++++++++---- 2 files changed, 44 insertions(+), 36 deletions(-) diff --git a/objectstore-service/src/concurrency.rs b/objectstore-service/src/concurrency.rs index e6816616..2def3f86 100644 --- a/objectstore-service/src/concurrency.rs +++ b/objectstore-service/src/concurrency.rs @@ -21,7 +21,6 @@ use std::future::Future; use std::sync::Arc; -use std::sync::atomic::{AtomicU32, Ordering}; use std::time::Duration; use futures_util::FutureExt; @@ -32,6 +31,8 @@ use crate::error::{Error, ErrorKind, Panic, Result}; mod limiter; +use limiter::Peak; + pub use limiter::{Limiter, LimiterStats, Permit, Priority, PriorityLimiter, PriorityLimiterStats}; /// Interval for the periodic metrics emitter. @@ -73,8 +74,8 @@ pub struct ConcurrencyLimiter { tasks: Arc, queue: Arc, bulk: Arc, - in_use_peak: Arc, - bulk_in_use_peak: Arc, + in_use_peak: Arc, + bulk_in_use_peak: Arc, tasks_total: u32, queue_total: u32, bulk_total: u32, @@ -153,8 +154,7 @@ impl ConcurrencyLimiter { // Fast path: Instantly grab a free permit without parking. if let Ok(task_permit) = self.tasks.clone().try_acquire_owned() { - self.in_use_peak - .fetch_max(self.used_permits(), Ordering::Relaxed); + self.in_use_peak.record(self.used_permits()); return Ok(ConcurrencyPermit { task_permit: Some(task_permit), bulk_permit: None, @@ -163,8 +163,7 @@ impl ConcurrencyLimiter { } // No permit was free, so the limiter is full. Recording that here makes every wait and // rejection visible, whatever is released right after. - self.in_use_peak - .fetch_max(self.tasks_total, Ordering::Relaxed); + self.in_use_peak.record(self.tasks_total); // Slow path: acquire a temporary queue ticket to bound concurrent // waiters. Released in this scope when the permit is constructed. @@ -192,12 +191,10 @@ impl ConcurrencyLimiter { /// Returns [`ErrorKind::AtCapacity`] when no permits are available. pub fn try_acquire(&self) -> Result { let Ok(task_permit) = self.tasks.clone().try_acquire_owned() else { - self.in_use_peak - .fetch_max(self.tasks_total, Ordering::Relaxed); + self.in_use_peak.record(self.tasks_total); return Err(ErrorKind::AtCapacity.into()); }; - self.in_use_peak - .fetch_max(self.used_permits(), Ordering::Relaxed); + self.in_use_peak.record(self.used_permits()); Ok(ConcurrencyPermit { task_permit: Some(task_permit), @@ -223,17 +220,13 @@ impl ConcurrencyLimiter { let acquire = async { // The peaks are also raised before each wait, which shows a full budget or limiter // even when the wait then times out. - self.bulk_in_use_peak - .fetch_max(self.used_bulk_permits(), Ordering::Relaxed); + self.bulk_in_use_peak.record(self.used_bulk_permits()); let bulk_permit = self.bulk.clone().acquire_owned().await?; - self.bulk_in_use_peak - .fetch_max(self.used_bulk_permits(), Ordering::Relaxed); + self.bulk_in_use_peak.record(self.used_bulk_permits()); - self.in_use_peak - .fetch_max(self.used_permits(), Ordering::Relaxed); + self.in_use_peak.record(self.used_permits()); let task_permit = self.tasks.clone().acquire_owned().await?; - self.in_use_peak - .fetch_max(self.used_permits(), Ordering::Relaxed); + self.in_use_peak.record(self.used_permits()); Ok((task_permit, bulk_permit)) }; @@ -303,19 +296,18 @@ impl ConcurrencyLimiter { /// Each call restarts the peaks. [`run_emitter`](Self::run_emitter) calls this, so another /// caller takes away from the peaks that the emitter reports. pub fn stats(&self) -> Stats { - // Each peak restarts at the current count instead of zero, which keeps permits visible - // that stay held while nothing new is acquired. The count is read right before, so - // that the restarted peak does not include permits released in between. + // Each count is read right before its peak restarts, so that the restarted peak does not + // include permits released in between. let in_use = self.used_permits(); - let in_use_peak = self.in_use_peak.swap(in_use, Ordering::Relaxed); + let in_use_peak = self.in_use_peak.restart(in_use); let bulk_in_use = self.used_bulk_permits(); - let bulk_in_use_peak = self.bulk_in_use_peak.swap(bulk_in_use, Ordering::Relaxed); + let bulk_in_use_peak = self.bulk_in_use_peak.restart(bulk_in_use); Stats { in_use, - in_use_peak: in_use_peak.max(in_use), + in_use_peak, queued: self.queued_permits(), bulk_in_use, - bulk_in_use_peak: bulk_in_use_peak.max(bulk_in_use), + bulk_in_use_peak, } } @@ -591,7 +583,7 @@ mod tests { limiter.try_acquire().unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.in_use_peak.swap(1, Ordering::Relaxed), 2); + assert_eq!(limiter.in_use_peak.restart(1), 2); let mut waiting: std::pin::Pin>> = match bulk { false => Box::pin(limiter.acquire()), true => Box::pin(limiter.acquire_bulk()), @@ -611,7 +603,7 @@ mod tests { limiter.acquire_bulk().await.unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.bulk_in_use_peak.swap(1, Ordering::Relaxed), 2); + assert_eq!(limiter.bulk_in_use_peak.restart(1), 2); limiter.acquire_bulk().await.unwrap_err(); drop(held); diff --git a/objectstore-service/src/concurrency/limiter.rs b/objectstore-service/src/concurrency/limiter.rs index 3d4218c8..e21f4f1f 100644 --- a/objectstore-service/src/concurrency/limiter.rs +++ b/objectstore-service/src/concurrency/limiter.rs @@ -75,6 +75,25 @@ pub struct LimiterStats { pub in_use_peak: u32, } +/// Most permits in use at once since the last [`restart`](Self::restart). +#[derive(Debug, Default)] +pub(super) struct Peak(AtomicU32); + +impl Peak { + /// Raises the peak to `in_use` if it is higher. + pub(super) fn record(&self, in_use: u32) { + self.0.fetch_max(in_use, Ordering::Relaxed); + } + + /// Returns the peak and restarts it at `in_use`. + /// + /// Restarting at the current number instead of zero keeps permits visible that stay held while + /// nothing new is acquired. + pub(super) fn restart(&self, in_use: u32) -> u32 { + self.0.swap(in_use, Ordering::Relaxed).max(in_use) + } +} + /// Shared interval loop for the metric emitters. async fn run_emitter(mut snapshot: impl FnMut() -> S, mut emit: F) -> ! where @@ -93,7 +112,7 @@ where pub struct Limiter { semaphore: Arc, queue: Option>, - in_use_peak: Arc, + in_use_peak: Arc, capacity: u32, timeout: Duration, } @@ -117,12 +136,12 @@ impl Limiter { /// Dropping the future releases its queue slot and any assigned permit. pub async fn acquire(&self) -> Result { if let Ok(permit) = self.semaphore.clone().try_acquire_owned() { - self.in_use_peak.fetch_max(self.in_use(), Ordering::Relaxed); + self.in_use_peak.record(self.in_use()); return Ok(Permit::semaphore(permit)); } // No permit was free, so the limiter is full. Recording that here makes every wait and // rejection visible, whatever is released right after. - self.in_use_peak.fetch_max(self.capacity, Ordering::Relaxed); + self.in_use_peak.record(self.capacity); if self.timeout.is_zero() { return Err(ErrorKind::AtCapacity.into()); } @@ -145,12 +164,9 @@ impl Limiter { /// caller takes away from the peak that the emitter reports. pub fn stats(&self) -> LimiterStats { let in_use = self.in_use(); - // Restarting at the current number instead of zero keeps permits visible that stay held - // while nothing new is acquired. - let in_use_peak = self.in_use_peak.swap(in_use, Ordering::Relaxed); LimiterStats { in_use, - in_use_peak: in_use_peak.max(in_use), + in_use_peak: self.in_use_peak.restart(in_use), } } @@ -475,7 +491,7 @@ mod tests { limiter.acquire().await.unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.in_use_peak.swap(1, Ordering::Relaxed), 2); + assert_eq!(limiter.in_use_peak.restart(1), 2); limiter.acquire().await.unwrap_err(); drop(held); assert_eq!(limiter.stats().in_use_peak, 2); From 9574e055731aca988380cdffa2724c00cc13bd30 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:57:10 +0100 Subject: [PATCH 09/11] ref(service): Rename Peak::restart to take --- objectstore-service/src/concurrency.rs | 8 ++++---- objectstore-service/src/concurrency/limiter.rs | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/objectstore-service/src/concurrency.rs b/objectstore-service/src/concurrency.rs index 2def3f86..95f595b9 100644 --- a/objectstore-service/src/concurrency.rs +++ b/objectstore-service/src/concurrency.rs @@ -299,9 +299,9 @@ impl ConcurrencyLimiter { // Each count is read right before its peak restarts, so that the restarted peak does not // include permits released in between. let in_use = self.used_permits(); - let in_use_peak = self.in_use_peak.restart(in_use); + let in_use_peak = self.in_use_peak.take(in_use); let bulk_in_use = self.used_bulk_permits(); - let bulk_in_use_peak = self.bulk_in_use_peak.restart(bulk_in_use); + let bulk_in_use_peak = self.bulk_in_use_peak.take(bulk_in_use); Stats { in_use, in_use_peak, @@ -583,7 +583,7 @@ mod tests { limiter.try_acquire().unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.in_use_peak.restart(1), 2); + assert_eq!(limiter.in_use_peak.take(1), 2); let mut waiting: std::pin::Pin>> = match bulk { false => Box::pin(limiter.acquire()), true => Box::pin(limiter.acquire_bulk()), @@ -603,7 +603,7 @@ mod tests { limiter.acquire_bulk().await.unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.bulk_in_use_peak.restart(1), 2); + assert_eq!(limiter.bulk_in_use_peak.take(1), 2); limiter.acquire_bulk().await.unwrap_err(); drop(held); diff --git a/objectstore-service/src/concurrency/limiter.rs b/objectstore-service/src/concurrency/limiter.rs index e21f4f1f..fee9dad6 100644 --- a/objectstore-service/src/concurrency/limiter.rs +++ b/objectstore-service/src/concurrency/limiter.rs @@ -75,7 +75,7 @@ pub struct LimiterStats { pub in_use_peak: u32, } -/// Most permits in use at once since the last [`restart`](Self::restart). +/// Most permits in use at once since the last [`take`](Self::take). #[derive(Debug, Default)] pub(super) struct Peak(AtomicU32); @@ -89,7 +89,7 @@ impl Peak { /// /// Restarting at the current number instead of zero keeps permits visible that stay held while /// nothing new is acquired. - pub(super) fn restart(&self, in_use: u32) -> u32 { + pub(super) fn take(&self, in_use: u32) -> u32 { self.0.swap(in_use, Ordering::Relaxed).max(in_use) } } @@ -166,7 +166,7 @@ impl Limiter { let in_use = self.in_use(); LimiterStats { in_use, - in_use_peak: self.in_use_peak.restart(in_use), + in_use_peak: self.in_use_peak.take(in_use), } } @@ -491,7 +491,7 @@ mod tests { limiter.acquire().await.unwrap(), ); // Lower the peak so that only the failed acquisition can raise it back to capacity. - assert_eq!(limiter.in_use_peak.restart(1), 2); + assert_eq!(limiter.in_use_peak.take(1), 2); limiter.acquire().await.unwrap_err(); drop(held); assert_eq!(limiter.stats().in_use_peak, 2); From 6c7d14a526272732ac29ef63bd056d65b5eac097 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:53:59 +0100 Subject: [PATCH 10/11] ref(service): Make Peak crate-visible --- objectstore-service/src/concurrency/limiter.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/objectstore-service/src/concurrency/limiter.rs b/objectstore-service/src/concurrency/limiter.rs index fee9dad6..63da714d 100644 --- a/objectstore-service/src/concurrency/limiter.rs +++ b/objectstore-service/src/concurrency/limiter.rs @@ -77,11 +77,11 @@ pub struct LimiterStats { /// Most permits in use at once since the last [`take`](Self::take). #[derive(Debug, Default)] -pub(super) struct Peak(AtomicU32); +pub(crate) struct Peak(AtomicU32); impl Peak { /// Raises the peak to `in_use` if it is higher. - pub(super) fn record(&self, in_use: u32) { + pub(crate) fn record(&self, in_use: u32) { self.0.fetch_max(in_use, Ordering::Relaxed); } @@ -89,7 +89,7 @@ impl Peak { /// /// Restarting at the current number instead of zero keeps permits visible that stay held while /// nothing new is acquired. - pub(super) fn take(&self, in_use: u32) -> u32 { + pub(crate) fn take(&self, in_use: u32) -> u32 { self.0.swap(in_use, Ordering::Relaxed).max(in_use) } } From ce4564a2065277ed8ec0abb882c21fe169da4b72 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:55:27 +0100 Subject: [PATCH 11/11] ref(service): Track the PriorityLimiter peak with Peak --- .../src/concurrency/limiter.rs | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/objectstore-service/src/concurrency/limiter.rs b/objectstore-service/src/concurrency/limiter.rs index 63da714d..4a4fdc4e 100644 --- a/objectstore-service/src/concurrency/limiter.rs +++ b/objectstore-service/src/concurrency/limiter.rs @@ -240,7 +240,7 @@ impl PriorityLimiter { capacity: capacity.get(), state: Arc::new(Mutex::new(PriorityState { free: capacity.get(), - in_use_peak: 0, + in_use_peak: Peak::default(), next_id: 0, normal_queue: WaiterQueue::new(), high_queue: WaiterQueue::new(), @@ -263,7 +263,7 @@ impl PriorityLimiter { // A free permit implies that nobody is queued, so taking it overtakes no one. if state.free > 0 { state.free -= 1; - state.in_use_peak = state.in_use_peak.max(self.capacity - state.free); + state.in_use_peak.record(self.capacity - state.free); return Ok(Permit::priority(self.state.clone())); } if timeout == Some(Duration::ZERO) { @@ -302,17 +302,14 @@ impl PriorityLimiter { /// Each call restarts the peak. [`run_emitter`](Self::run_emitter) calls this, so another /// caller takes away from the peak that the emitter reports. pub fn stats(&self) -> PriorityLimiterStats { - let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); - let stats = PriorityLimiterStats { - in_use: self.capacity - state.free, - in_use_peak: state.in_use_peak, + let state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + let in_use = self.capacity - state.free; + PriorityLimiterStats { + in_use, + in_use_peak: state.in_use_peak.take(in_use), waiting_normal: state.normal_queue.len(), waiting_high: state.high_queue.len(), - }; - // Restarting at the current number instead of zero keeps permits visible that stay held - // while nothing new is acquired. - state.in_use_peak = stats.in_use; - stats + } } /// Passes this limiter's stats to `emit` immediately and once per second thereafter. @@ -336,7 +333,7 @@ struct PriorityState { free: u32, /// Most permits in use at once since the emitter last took it. Handing a slot to a waiter /// keeps it in use, so only taking a free permit can raise this. - in_use_peak: u32, + in_use_peak: Peak, next_id: u64, normal_queue: WaiterQueue, high_queue: WaiterQueue,