strands/context_manager/strategies/offload/
conditions.rs1use 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#[derive(Debug, Clone, PartialEq)]
16#[non_exhaustive]
17pub enum ConditionValue {
18 Number(f64),
20 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
58fn 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#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
89pub struct OffloadConditions {
90 #[builder(into)]
93 pub context_utilization: Option<ConditionValue>,
94 #[builder(into)]
98 pub block_threshold: Option<ConditionValue>,
99 #[builder(into)]
102 pub preserve_recent: Option<ConditionValue>,
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub(crate) enum ConditionName {
108 ContextUtilization,
109 BlockThreshold,
110 PreserveRecent,
111}
112
113const 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#[derive(Debug, Clone, Copy, PartialEq)]
154pub(crate) struct ParsedCondition {
155 pub(crate) value: f64,
157 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 pub(crate) fn of(self, whole: u64) -> u64 {
170 if !self.is_share {
171 return self.value as u64;
172 }
173 ((self.value * whole as f64) / 100.0).ceil() as u64
175 }
176
177 pub(crate) fn share(self) -> f64 {
179 self.value / 100.0
180 }
181}
182
183fn 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
194pub(crate) fn parse_condition(name: ConditionName, raw: Option<&ConditionValue>) -> Result<Option<ParsedCondition>> {
201 parse_condition_as(name, raw, name.as_str())
202}
203
204pub(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
243fn 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
260fn to_precision_6(value: f64) -> f64 {
263 format!("{value:.5e}").parse().unwrap_or(value)
264}
265
266pub(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#[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 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 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 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 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 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 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 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;