Skip to main content

a2a_protocol_server/tool_loop/
limit.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`InferenceLimit`] and [`LimitedModel`]: at most so many turns in flight
5//! at a model provider, shared by every loop that talks to it (audit H17,
6//! ADR 0048).
7
8use std::fmt;
9use std::future::Future;
10use std::pin::Pin;
11use std::sync::Arc;
12
13use tokio::sync::Semaphore;
14
15use super::model::{ChatRequest, ModelError, ModelTurn, TextSink, ToolModel};
16
17/// How many turns may be in flight at once at one model provider.
18///
19/// Cloning shares the limit: give every [`LimitedModel`] that talks to the
20/// same provider a clone of one `InferenceLimit`, and together they send at
21/// most [`max`](Self::max) turns at a time. A turn past the limit waits for
22/// one to finish, in arrival order (a fair semaphore), and the wait is
23/// abandoned when the run is cancelled or the executor's timeout ends it.
24///
25/// ```rust
26/// use a2a_protocol_server::tool_loop::InferenceLimit;
27///
28/// // llama-server started with `-np 2` serves two turns at once.
29/// let limit = InferenceLimit::new(2);
30/// let shared = limit.clone();
31/// assert_eq!(shared.max(), 2);
32/// assert_eq!(limit.available(), 2);
33/// ```
34#[derive(Clone)]
35pub struct InferenceLimit {
36    permits: Arc<Semaphore>,
37    max: usize,
38}
39
40impl InferenceLimit {
41    /// A limit of `max` turns in flight. `0` is taken as `1`: a limit that
42    /// admitted nothing would hang every run.
43    #[must_use]
44    pub fn new(max: usize) -> Self {
45        let max = max.max(1);
46        Self {
47            permits: Arc::new(Semaphore::new(max)),
48            max,
49        }
50    }
51
52    /// The most turns in flight at once.
53    #[must_use]
54    pub const fn max(&self) -> usize {
55        self.max
56    }
57
58    /// How many more turns could start now without waiting.
59    #[must_use]
60    pub fn available(&self) -> usize {
61        self.permits.available_permits()
62    }
63}
64
65impl fmt::Debug for InferenceLimit {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.debug_struct("InferenceLimit")
68            .field("max", &self.max)
69            .field("available", &self.available())
70            .finish_non_exhaustive()
71    }
72}
73
74/// A [`ToolModel`] that takes a slot of an [`InferenceLimit`] for each turn
75/// and gives it back when the turn ends, however it ends.
76///
77/// The slot is held for the turn only: a loop waiting to retry a
78/// rate-limited turn ([`ToolLoop::with_model_retry`](super::ToolLoop::with_model_retry))
79/// holds none, so another task's turn can use it.
80///
81/// ```rust,no_run
82/// use a2a_protocol_server::tool_loop::{InferenceLimit, LimitedModel, OpenAiChatModel};
83///
84/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
85/// let limit = InferenceLimit::new(2);
86/// let model = LimitedModel::new(
87///     OpenAiChatModel::new("http://127.0.0.1:8080/v1", "qwen3:1.7b")?,
88///     &limit,
89/// );
90/// # drop(model); Ok(()) }
91/// ```
92pub struct LimitedModel<M> {
93    inner: M,
94    limit: InferenceLimit,
95}
96
97impl<M: ToolModel> LimitedModel<M> {
98    /// `inner`, held to `limit`, which it shares with every other model
99    /// given a clone of it.
100    #[must_use]
101    pub fn new(inner: M, limit: &InferenceLimit) -> Self {
102        Self {
103            inner,
104            limit: limit.clone(),
105        }
106    }
107
108    /// The model this wraps.
109    #[must_use]
110    pub const fn inner(&self) -> &M {
111        &self.inner
112    }
113
114    /// The limit this is held to.
115    #[must_use]
116    pub const fn limit(&self) -> &InferenceLimit {
117        &self.limit
118    }
119
120    /// Runs `turn` holding a slot. The semaphore is never closed (nothing
121    /// outside this module can reach it, and nothing here closes it), so the
122    /// acquire cannot fail.
123    async fn limited<F>(&self, turn: F) -> Result<ModelTurn, ModelError>
124    where
125        F: Future<Output = Result<ModelTurn, ModelError>>,
126    {
127        let _slot = self.limit.permits.acquire().await.ok();
128        turn.await
129    }
130}
131
132impl<M: ToolModel + fmt::Debug> fmt::Debug for LimitedModel<M> {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        f.debug_struct("LimitedModel")
135            .field("inner", &self.inner)
136            .field("limit", &self.limit)
137            .finish()
138    }
139}
140
141impl<M: ToolModel> ToolModel for LimitedModel<M> {
142    fn model_name(&self) -> &str {
143        self.inner.model_name()
144    }
145
146    fn provider_name(&self) -> &str {
147        self.inner.provider_name()
148    }
149
150    fn server(&self) -> Option<(&str, u16)> {
151        self.inner.server()
152    }
153
154    fn complete<'a>(
155        &'a self,
156        request: ChatRequest<'a>,
157    ) -> Pin<Box<dyn Future<Output = Result<ModelTurn, ModelError>> + Send + 'a>> {
158        Box::pin(self.limited(self.inner.complete(request)))
159    }
160
161    fn complete_streaming<'a>(
162        &'a self,
163        request: ChatRequest<'a>,
164        text: &'a TextSink,
165    ) -> Pin<Box<dyn Future<Output = Result<ModelTurn, ModelError>> + Send + 'a>> {
166        Box::pin(self.limited(self.inner.complete_streaming(request, text)))
167    }
168}
169
170#[cfg(test)]
171#[path = "limit_tests.rs"]
172mod tests;