Skip to main content

strands/context_manager/strategies/offload/
conditions.rs

1//! Offload conditions: when a strategy fires, how large content must be to act on, and what it
2//! protects.
3
4use std::fmt;
5
6use crate::agent::LocalAgent;
7use crate::context_manager::types::ContextState;
8use crate::error::{Error, Result};
9use crate::models::model_info::default_context_window_limit;
10
11/// One condition value: a whole number, or a `'N%'` share written as a string such as `"70%"`.
12///
13/// Numbers and strings convert into it, so conditions read as in the docs:
14/// `context_utilization: Some("80%".into())`, `block_threshold: Some(1500.into())`.
15#[derive(Debug, Clone, PartialEq)]
16#[non_exhaustive]
17pub enum ConditionValue {
18    /// A number: a count when it is a whole number, rejected otherwise.
19    Number(f64),
20    /// A string: a share when it reads `N%`, rejected otherwise.
21    Text(String),
22}
23
24macro_rules! condition_from_number {
25    ($($number:ty),*) => {$(
26        impl From<$number> for ConditionValue {
27            #[allow(clippy::cast_precision_loss, clippy::cast_lossless, reason = "condition values are small")]
28            fn from(value: $number) -> Self {
29                Self::Number(value as f64)
30            }
31        }
32    )*};
33}
34
35condition_from_number!(f64, f32, i32, i64, u32, u64, usize);
36
37impl From<&str> for ConditionValue {
38    fn from(value: &str) -> Self {
39        Self::Text(value.to_owned())
40    }
41}
42
43impl From<String> for ConditionValue {
44    fn from(value: String) -> Self {
45        Self::Text(value)
46    }
47}
48
49impl fmt::Display for ConditionValue {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        match self {
52            Self::Text(text) => write!(f, "\"{text}\""),
53            Self::Number(number) => f.write_str(&js_number(*number)),
54        }
55    }
56}
57
58/// A number as JavaScript prints it, for the values a condition error quotes.
59fn js_number(number: f64) -> String {
60    if number.is_nan() {
61        return "NaN".to_owned();
62    }
63    if number.is_infinite() {
64        return if number > 0.0 { "Infinity" } else { "-Infinity" }.to_owned();
65    }
66    number.to_string()
67}
68
69/// Conditions that decide when and how an offload strategy fires (`OffloadConditions`).
70///
71/// - `context_utilization` sets when the strategy fires. `"80%"` fires at 80% of the context
72///   window; a whole number of 1,000 or more fires at that many conversation tokens, and is
73///   rejected if it exceeds the model's context window.
74/// - `block_threshold` sets how large each block, or each message for [`OffloadTarget::All`],
75///   must be to act on. A whole number selects content larger than that many tokens; `"5%"`
76///   selects content larger than 5% of the context window.
77/// - `preserve_recent` sets which matching messages it never touches. A whole number keeps that
78///   many of the newest; `"70%"` keeps the newest 70% of them.
79///
80/// With no `context_utilization`, the strategy runs before every model call, or on each message as
81/// it arrives when the target isn't [`OffloadTarget::All`] and `preserve_recent` is unset or 0.
82///
83/// Target [`OffloadTarget::All`] acts on whole messages: drop removes them, summarize merges each
84/// contiguous run, and truncate elides the middle and takes no `block_threshold`. Any other target
85/// acts on each block.
86///
87/// [`OffloadTarget::All`]: super::OffloadTarget::All
88#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
89pub struct OffloadConditions {
90    /// Context usage at or above which the strategy fires: `"80%"` of the context window, or a
91    /// whole number of 1,000 or more for conversation tokens, at most the model's context window.
92    #[builder(into)]
93    pub context_utilization: Option<ConditionValue>,
94    /// Size above which a message (target `All`) or block is offloaded: a whole number of tokens
95    /// above 0, or `"5%"` of the context window. Unset, there is no size check. Media the token
96    /// count measures as 0, alone or in a tool result, always passes.
97    #[builder(into)]
98    pub block_threshold: Option<ConditionValue>,
99    /// Newest matching messages never touched: a count, or `"70%"` of the matches, rounded up so a
100    /// share above 0 keeps at least one.
101    #[builder(into)]
102    pub preserve_recent: Option<ConditionValue>,
103}
104
105/// Which condition a value is for.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub(crate) enum ConditionName {
108    ContextUtilization,
109    BlockThreshold,
110    PreserveRecent,
111}
112
113/// Smaller whole numbers are almost always a percent written without "%", like
114/// `context_utilization: 80`.
115const MIN_UTILIZATION_TOKENS: f64 = 1000.0;
116
117impl ConditionName {
118    fn as_str(self) -> &'static str {
119        match self {
120            Self::ContextUtilization => "contextUtilization",
121            Self::BlockThreshold => "blockThreshold",
122            Self::PreserveRecent => "preserveRecent",
123        }
124    }
125
126    fn percent_in_range(self, percent: f64) -> bool {
127        match self {
128            Self::ContextUtilization => percent > 0.0 && percent <= 100.0,
129            Self::BlockThreshold => percent > 0.0 && percent < 100.0,
130            Self::PreserveRecent => (0.0..100.0).contains(&percent),
131        }
132    }
133
134    fn min_count(self) -> f64 {
135        match self {
136            Self::ContextUtilization => MIN_UTILIZATION_TOKENS,
137            Self::BlockThreshold => 1.0,
138            Self::PreserveRecent => 0.0,
139        }
140    }
141
142    fn expected(self) -> &'static str {
143        match self {
144            Self::ContextUtilization => "a \"N%\" string up to \"100%\" or a whole token count of at least 1000",
145            Self::BlockThreshold => "a \"N%\" string below \"100%\" or a whole token count above 0",
146            Self::PreserveRecent => "a \"N%\" string below \"100%\" or a whole message count",
147        }
148    }
149}
150
151/// A parsed condition: a count in the condition's unit, or a share of a whole
152/// (`ParsedCondition`).
153#[derive(Debug, Clone, Copy, PartialEq)]
154pub(crate) struct ParsedCondition {
155    /// The count, or a share's percent as written.
156    pub(crate) value: f64,
157    /// Whether `value` is a percent of a whole rather than a count.
158    pub(crate) is_share: bool,
159}
160
161impl ParsedCondition {
162    #[allow(
163        clippy::cast_possible_truncation,
164        clippy::cast_sign_loss,
165        clippy::cast_precision_loss,
166        reason = "counts and wholes are small non-negative numbers"
167    )]
168    /// The count this condition stands for out of `whole`, rounded up.
169    pub(crate) fn of(self, whole: u64) -> u64 {
170        if !self.is_share {
171            return self.value as u64;
172        }
173        // Multiplying before dividing keeps "7%" of 100 at 7: `percent / 100` is inexact.
174        ((self.value * whole as f64) / 100.0).ceil() as u64
175    }
176
177    /// A share's fraction of the whole.
178    pub(crate) fn share(self) -> f64 {
179        self.value / 100.0
180    }
181}
182
183/// `N%` or `N.N%`, the percent as a number.
184fn parse_percent(text: &str) -> Option<f64> {
185    let digits = text.strip_suffix('%')?;
186    let (whole, fraction) = digits.split_once('.').unwrap_or((digits, ""));
187    let all_digits = |part: &str| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit());
188    if !all_digits(whole) || (digits.contains('.') && !all_digits(fraction)) {
189        return None;
190    }
191    digits.parse().ok()
192}
193
194/// Parses one condition value: a `'N%'` string is a share, and a whole number is a count
195/// (`parseCondition`).
196///
197/// # Errors
198///
199/// A value the condition does not accept.
200pub(crate) fn parse_condition(name: ConditionName, raw: Option<&ConditionValue>) -> Result<Option<ParsedCondition>> {
201    parse_condition_as(name, raw, name.as_str())
202}
203
204/// [`parse_condition`] for a condition that takes the same values under another name, which the
205/// error reports (`parseCondition` with a label).
206///
207/// # Errors
208///
209/// A value the condition does not accept.
210pub(crate) fn parse_condition_as(
211    name: ConditionName,
212    raw: Option<&ConditionValue>,
213    label: &str,
214) -> Result<Option<ParsedCondition>> {
215    let Some(raw) = raw else {
216        return Ok(None);
217    };
218    match raw {
219        ConditionValue::Text(text) => {
220            if let Some(percent) = parse_percent(text).filter(|percent| name.percent_in_range(*percent)) {
221                return Ok(Some(ParsedCondition {
222                    value: percent,
223                    is_share: true,
224                }));
225            }
226        }
227        ConditionValue::Number(number) => {
228            if number.is_finite() && number.fract() == 0.0 && *number >= name.min_count() {
229                return Ok(Some(ParsedCondition {
230                    value: *number,
231                    is_share: false,
232                }));
233            }
234        }
235    }
236    Err(Error::other(format!(
237        "{label}={raw} is invalid: expected {}{}",
238        name.expected(),
239        percent_hint(raw)
240    )))
241}
242
243/// Suggests the `'N%'` spelling for a rejected number that reads as a share or a percent.
244fn percent_hint(raw: &ConditionValue) -> String {
245    let ConditionValue::Number(number) = raw else {
246        return String::new();
247    };
248    if !(*number > 0.0 && *number <= 100.0) {
249        return String::new();
250    }
251    let percent = if *number <= 1.0 {
252        to_precision_6(number * 100.0)
253    } else {
254        *number
255    };
256    let shown = js_number(percent);
257    format!("; for {shown}%, write \"{shown}%\"")
258}
259
260/// `Number(value.toPrecision(6))`: six significant digits, which drops float noise like
261/// `85.00000000000001`.
262fn to_precision_6(value: f64) -> f64 {
263    format!("{value:.5e}").parse().unwrap_or(value)
264}
265
266/// The model's context window, falling back to the default `estimate_utilization` uses.
267pub(crate) fn effective_window_limit(agent: &LocalAgent) -> u64 {
268    agent
269        .model()
270        .model_info()
271        .limits
272        .context_window
273        .filter(|limit| *limit > 0)
274        .unwrap_or_else(default_context_window_limit)
275}
276
277/// A strategy's parsed conditions, and what they resolve to on an agent (`ResolvedConditions`).
278#[derive(Debug, Clone, Copy, Default, PartialEq)]
279pub(crate) struct ResolvedConditions {
280    pub(crate) context_utilization: Option<ParsedCondition>,
281    pub(crate) block_threshold: Option<ParsedCondition>,
282    pub(crate) preserve_recent: Option<ParsedCondition>,
283}
284
285impl ResolvedConditions {
286    /// # Errors
287    ///
288    /// A condition value that is not accepted.
289    pub(crate) fn new(conditions: &OffloadConditions) -> Result<Self> {
290        let preserve_recent = parse_condition(ConditionName::PreserveRecent, conditions.preserve_recent.as_ref())?;
291        Ok(Self {
292            context_utilization: parse_condition(
293                ConditionName::ContextUtilization,
294                conditions.context_utilization.as_ref(),
295            )?,
296            block_threshold: parse_condition(ConditionName::BlockThreshold, conditions.block_threshold.as_ref())?,
297            preserve_recent: preserve_recent.filter(|preserve| preserve.value != 0.0),
298        })
299    }
300
301    /// Whether no condition narrows when or what the strategy acts on.
302    pub(crate) fn is_empty(&self) -> bool {
303        self.context_utilization.is_none() && self.block_threshold.is_none() && self.preserve_recent.is_none()
304    }
305
306    /// Whether something other than size defers the strategy past a message's arrival.
307    pub(crate) fn defers_arrival(&self) -> bool {
308        self.context_utilization.is_some() || self.preserve_recent.is_some()
309    }
310
311    #[allow(clippy::cast_precision_loss, reason = "token counts are far below 2^52")]
312    /// Whether the utilization gate, if any, is open: on overflow, or at or above the configured
313    /// share.
314    pub(crate) fn reached(&self, context: &ContextState<'_>) -> bool {
315        let Some(utilization) = self.context_utilization else {
316            return true;
317        };
318        if context.overflow {
319            return true;
320        }
321        let share = if utilization.is_share {
322            utilization.share()
323        } else {
324            utilization.value / effective_window_limit(context.agent) as f64
325        };
326        context.utilization >= share
327    }
328
329    /// Tokens above which content is offloaded, or `None` when `block_threshold` is unset so no
330    /// size check applies.
331    pub(crate) fn threshold_tokens(&self, agent: &LocalAgent) -> Option<u64> {
332        let threshold = self.block_threshold?;
333        if threshold.is_share {
334            return Some(threshold.of(effective_window_limit(agent)));
335        }
336        Some(threshold.of(0))
337    }
338
339    /// `matching` without the newest ones `preserve_recent` protects.
340    pub(crate) fn without_preserved<T: Clone>(&self, matching: &[T]) -> Vec<T> {
341        let keep = self.preserve_recent.map_or(0, |preserve| {
342            usize::try_from(preserve.of(matching.len() as u64)).unwrap_or(usize::MAX)
343        });
344        if keep >= matching.len() {
345            return Vec::new();
346        }
347        matching[..matching.len() - keep].to_vec()
348    }
349
350    /// Checks a token-count `context_utilization` fits the model's context window.
351    ///
352    /// # Errors
353    ///
354    /// A token count larger than the model's context window.
355    pub(crate) fn check_fits(&self, agent: &LocalAgent) -> Result<()> {
356        let Some(utilization) = self.context_utilization.filter(|utilization| !utilization.is_share) else {
357            return Ok(());
358        };
359        let tokens = js_number(utilization.value);
360        let Some(limit) = agent
361            .model()
362            .model_info()
363            .limits
364            .context_window
365            .filter(|limit| *limit > 0)
366        else {
367            tracing::warn!(
368                "contextUtilization=<{tokens}> | contextWindowLimit is not set on the model, skipping the context window check | set contextWindowLimit in your model config"
369            );
370            return Ok(());
371        };
372        #[allow(clippy::cast_precision_loss, reason = "context windows are far below 2^52")]
373        if utilization.value <= limit as f64 {
374            return Ok(());
375        }
376        Err(Error::other(format!(
377            "contextUtilization ({tokens}) is larger than the model's context window ({limit} tokens); use a smaller token count or a \"N%\" share"
378        )))
379    }
380}
381
382#[cfg(test)]
383#[path = "conditions_tests.rs"]
384mod tests;