Skip to main content

strands/context_manager/strategies/offload/
base.rs

1//! Base offload strategy: conditions, target routing, eager hooks, and the shared per-block and
2//! message-level execution paths.
3//!
4//! Reading order: `apply` checks `reached`, then a block target runs `transform_blocks`, which
5//! calls each strategy's `replace_block`, and target `All` runs the strategy's
6//! `apply_per_message` on `removable_messages`, which hands them to `remove_messages` in
7//! `message_trimming` before `repair_alternation` restores alternation.
8//!
9//! Messages are identified by their index into the history.
10
11use std::collections::{HashMap, HashSet};
12use std::sync::{Arc, Mutex, PoisonError};
13
14use async_trait::async_trait;
15
16use super::conditions::{OffloadConditions, ResolvedConditions};
17use super::target::{
18    OffloadTarget, OffloadTargetMatcher, build_tool_name_map, is_media_block, is_media_content, is_protocol_block,
19    target_json,
20};
21use crate::agent::{InvocationContext, LocalAgent};
22use crate::context_manager::archive::Archive;
23use crate::context_manager::message_trimming::{
24    FormattedPlaceholder, collect_removable_with_pair, remove_messages, repair_alternation,
25};
26use crate::context_manager::placeholder::{
27    carried_tokens, format_elided, is_offloaded, offload_placeholder, offloaded_content_of,
28};
29use crate::context_manager::retrieval_tool::RETRIEVAL_TOOL_NAME;
30use crate::context_manager::types::{ContextState, ContextStrategy};
31use crate::conversation_manager::compression::pin_message::is_pinned;
32use crate::error::{Error, Result};
33use crate::hooks::MessageAddedEvent;
34use crate::logging::warn_once;
35use crate::models::model_proxy::ModelProxy;
36use crate::models::tool_references::holds_tool_reference;
37use crate::models::{CountTokensOptions, is_js_whitespace};
38use crate::types::{ContentBlock, Message, OffloadMethod, Role, TextBlock, ToolResultBlock};
39
40/// How one offload method replaces a block and removes whole messages.
41#[async_trait]
42pub(crate) trait OffloadBehavior: Send + Sync + 'static {
43    /// The replacement for a block, or `None` to leave it. `tokens` is the size the replacement
44    /// stands for: the block's own tokens plus what a placeholder it holds already stood for.
45    /// `archive_ref` is the reference the original is retrievable under; `tool_name` names the tool
46    /// that produced a tool result, when its tool use is in the conversation.
47    #[allow(clippy::too_many_arguments, reason = "mirrors the shared replace hook")]
48    async fn replace_block(
49        &self,
50        core: &OffloadCore,
51        block: &ContentBlock,
52        tokens: u64,
53        message: &Message,
54        agent: &LocalAgent,
55        archive_ref: Option<&str>,
56        tool_name: Option<&str>,
57        invocation_context: Option<&InvocationContext>,
58    ) -> Result<Option<ContentBlock>>;
59
60    /// Message-level execution for target `All`; `apply` restores alternation afterwards.
61    async fn apply_per_message(&self, core: &OffloadCore, context: &mut ContextState<'_>) -> Result<bool>;
62}
63
64/// The state every offload strategy shares: conditions, firing, granularity, eager hooks and
65/// `preserve_recent`.
66pub(crate) struct OffloadCore {
67    pub(crate) name: String,
68    pub(crate) method: OffloadMethod,
69    pub(crate) matcher: OffloadTargetMatcher,
70    pub(crate) conditions: ResolvedConditions,
71    /// Whether the eager hook processes each message as it arrives.
72    runs_eagerly: bool,
73    /// The conditions as given to `when`, for `Debug`.
74    pub(crate) offload_conditions: Option<OffloadConditions>,
75    archive: Mutex<Option<Archive>>,
76}
77
78impl OffloadCore {
79    /// A core for `method` on `target`; with `conditions` given, they are checked to leave the
80    /// strategy runnable.
81    ///
82    /// # Errors
83    ///
84    /// A target that matches nothing, an invalid condition value, or conditions that leave the
85    /// strategy unable to run.
86    pub(crate) fn new(
87        method: OffloadMethod,
88        target: OffloadTarget,
89        conditions: Option<OffloadConditions>,
90    ) -> Result<Self> {
91        let matcher = OffloadTargetMatcher::new(target)?;
92        let resolved = conditions
93            .as_ref()
94            .map(ResolvedConditions::new)
95            .transpose()?
96            .unwrap_or_default();
97        let runs_eagerly = !matcher.matches_all() && !resolved.defers_arrival();
98        let core = Self {
99            name: format!("offload:{method}"),
100            method,
101            matcher,
102            conditions: resolved,
103            runs_eagerly,
104            offload_conditions: conditions,
105            archive: Mutex::new(None),
106        };
107        if core.offload_conditions.is_some() {
108            core.check_runnable()?;
109        }
110        Ok(core)
111    }
112
113    pub(crate) fn target(&self) -> &OffloadTarget {
114        &self.matcher.target
115    }
116
117    pub(crate) fn archive(&self) -> Option<Archive> {
118        self.archive.lock().unwrap_or_else(PoisonError::into_inner).clone()
119    }
120
121    fn set_archive(&self, archive: Option<Archive>) {
122        *self.archive.lock().unwrap_or_else(PoisonError::into_inner) = archive;
123    }
124
125    /// Rejects conditions that leave the strategy acting on every message, or removing media
126    /// unseen.
127    fn check_runnable(&self) -> Result<()> {
128        let method = self.method;
129        if self.matcher.matches_all() && self.conditions.is_empty() {
130            return Err(Error::other(format!(
131                "Offload.{method}(\"*\") would act on every message; use .when() to set contextUtilization, blockThreshold, or a preserveRecent above 0"
132            )));
133        }
134        if self.matcher.target == OffloadTarget::Media && self.runs_eagerly {
135            return Err(Error::other(format!(
136                "Offload.{method}(\"media\") would remove media before the model sees it; use .when() to set contextUtilization or a preserveRecent above 0"
137            )));
138        }
139        Ok(())
140    }
141
142    /// Checks the conditions can run on this agent, then registers the eager hook if this runs
143    /// eagerly (`init`).
144    ///
145    /// # Errors
146    ///
147    /// A whole-message strategy with none of `context_utilization`, `block_threshold` or
148    /// `preserve_recent`, a media strategy with neither `context_utilization` nor
149    /// `preserve_recent`, or a token-count `context_utilization` larger than the model's context
150    /// window.
151    pub(crate) fn init(
152        self: &Arc<Self>,
153        behavior: Arc<dyn OffloadBehavior>,
154        agent: &mut LocalAgent,
155        archive: Option<&Archive>,
156    ) -> Result<()> {
157        self.set_archive(archive.cloned());
158        self.check_runnable()?;
159        self.conditions.check_fits(agent)?;
160        if !self.runs_eagerly {
161            return Ok(());
162        }
163        if self.conditions.is_empty() {
164            let target = target_json(&self.matcher.target);
165            warn_once(&format!(
166                "strategy=<{}>, target=<{target}> | strategy has no conditions, so it acts on every matching block as it arrives, before the model reads it | use .when() to set blockThreshold, contextUtilization, or preserveRecent",
167                self.name
168            ));
169        }
170        let core = self.clone();
171        agent.add_async_hook::<MessageAddedEvent<'_>>(move |event| {
172            let core = core.clone();
173            let behavior = behavior.clone();
174            Box::pin(async move {
175                let tracking_id = event.message().tracking_id().to_owned();
176                let agent = event.agent_mut();
177                let Some(index) = agent
178                    .messages()
179                    .iter()
180                    .rposition(|message| message.tracking_id() == tracking_id)
181                else {
182                    return Ok::<(), Error>(());
183                };
184                if is_pinned(agent.messages(), index) {
185                    return Ok(());
186                }
187                let threshold = core.conditions.threshold_tokens(agent);
188                let tool_names = build_tool_name_map(agent.messages());
189                let archive = core.archive();
190                core.transform_blocks(
191                    behavior.as_ref(),
192                    agent,
193                    index,
194                    &tool_names,
195                    threshold,
196                    archive.as_ref(),
197                    None,
198                )
199                .await?;
200                Ok(())
201            })
202        });
203        Ok(())
204    }
205
206    /// Runs the strategy (`apply`).
207    pub(crate) async fn apply(&self, behavior: &dyn OffloadBehavior, context: &mut ContextState<'_>) -> Result<bool> {
208        if context.archive.is_some() {
209            self.set_archive(context.archive.clone());
210        }
211        if !self.conditions.reached(context) {
212            return Ok(false);
213        }
214        if !self.matcher.matches_all() {
215            return self.apply_per_block(behavior, context).await;
216        }
217        let acted = behavior.apply_per_message(self, context).await?;
218        if acted {
219            repair_alternation(context.agent.messages_mut());
220        }
221        Ok(acted)
222    }
223
224    /// Per-block execution: walk each message and replace individual blocks above the threshold.
225    async fn apply_per_block(&self, behavior: &dyn OffloadBehavior, context: &mut ContextState<'_>) -> Result<bool> {
226        let invocation_context = context.invocation_context.clone();
227        let archive = self.archive();
228        let agent = &mut *context.agent;
229        let tool_names = build_tool_name_map(agent.messages());
230        let threshold = self.conditions.threshold_tokens(agent);
231        let last = agent.messages().len().saturating_sub(1);
232        let mut acted = false;
233        for index in self.unprotected_matches(agent.messages(), &tool_names) {
234            // Without the eager hook, message 0 is the task and the last message is one the model
235            // has not yet responded to.
236            if !self.runs_eagerly && (index == 0 || index == last) {
237                continue;
238            }
239            if self
240                .transform_blocks(
241                    behavior,
242                    agent,
243                    index,
244                    &tool_names,
245                    threshold,
246                    archive.as_ref(),
247                    invocation_context.as_ref(),
248                )
249                .await?
250            {
251                acted = true;
252            }
253        }
254        Ok(acted)
255    }
256
257    /// Matching messages outside `preserve_recent`, without pinned ones, in history order.
258    fn unprotected_matches(&self, messages: &[Message], tool_names: &HashMap<String, String>) -> Vec<usize> {
259        let matching: Vec<usize> = (0..messages.len())
260            .filter(|&index| self.matcher.matches_message(&messages[index], tool_names))
261            .collect();
262        self.conditions
263            .without_preserved(&matching)
264            .into_iter()
265            .filter(|&index| !is_pinned(messages, index))
266            .collect()
267    }
268
269    /// Messages outside `preserve_recent` and larger than `block_threshold`, excluding message 0,
270    /// pinned messages, and messages whose tool partner is protected, since removing a message
271    /// removes its partner too.
272    ///
273    /// # Errors
274    ///
275    /// The model's token count error.
276    pub(crate) async fn removable_messages(&self, agent: &LocalAgent) -> Result<Vec<usize>> {
277        let messages = agent.messages();
278        let unprotected = self.unprotected_matches(messages, &build_tool_name_map(messages));
279        let unprotected_set: HashSet<usize> = unprotected.iter().copied().collect();
280        let removable: Vec<usize> = unprotected
281            .into_iter()
282            .filter(|&index| {
283                index != 0
284                    && collect_removable_with_pair(messages, index)
285                        .iter()
286                        .all(|removed| unprotected_set.contains(removed))
287            })
288            .collect();
289        let Some(threshold) = self.conditions.threshold_tokens(agent) else {
290            return Ok(removable);
291        };
292        let mut over = Vec::new();
293        for index in removable {
294            let size = agent
295                .model()
296                .count_tokens(std::slice::from_ref(&messages[index]), CountTokensOptions::default())
297                .await?;
298            if size > threshold {
299                over.push(index);
300            }
301        }
302        Ok(over)
303    }
304
305    /// The placeholder this strategy leaves for a block it replaced, recording the tokens it
306    /// stands for.
307    pub(crate) fn placeholder(&self, preview: &str, archive_ref: Option<&str>, tokens: u64) -> TextBlock {
308        offload_placeholder(self.method, preview, archive_ref, tokens)
309    }
310
311    /// Whether a block in `message` is content this strategy may replace.
312    fn is_offloadable(
313        &self,
314        block: &ContentBlock,
315        message: &Message,
316        tool_names: &HashMap<String, String>,
317        archive: Option<&Archive>,
318    ) -> bool {
319        if is_protocol_block(block) || is_offloaded(block) {
320            return false;
321        }
322        match block {
323            ContentBlock::Text(text) if text.text.trim_matches(is_js_whitespace).is_empty() => return false,
324            // Injected text is written after its message was archived, so a ref to it would point at
325            // nothing.
326            ContentBlock::Injected(_) => return false,
327            ContentBlock::ToolResult(result) if self.is_protected_result(result, tool_names, archive) => return false,
328            _ => {}
329        }
330        self.matcher.matches_block(block, message, tool_names)
331    }
332
333    /// Whether a tool result is the retrieval tool's output, holds a tool reference, or already
334    /// holds a placeholder this strategy shouldn't replace. Only drop goes further, since truncate
335    /// and summarize would read the placeholder as the content.
336    fn is_protected_result(
337        &self,
338        block: &ToolResultBlock,
339        tool_names: &HashMap<String, String>,
340        archive: Option<&Archive>,
341    ) -> bool {
342        if archive.is_some() && tool_names.get(&block.tool_use_id).map(String::as_str) == Some(RETRIEVAL_TOOL_NAME) {
343            return true;
344        }
345        // A tool reference is what keeps a loaded tool's schema in the model's context.
346        if holds_tool_reference(block) {
347            return true;
348        }
349        block
350            .content
351            .iter()
352            .find_map(offloaded_content_of)
353            .is_some_and(|placeholder| self.method != OffloadMethod::Drop || placeholder.method == OffloadMethod::Drop)
354    }
355
356    /// Replaces each eligible block of the message at `index` larger than `threshold` tokens, or
357    /// every one when unset.
358    #[allow(
359        clippy::too_many_arguments,
360        reason = "the per-block pass and the eager hook share it"
361    )]
362    pub(crate) async fn transform_blocks(
363        &self,
364        behavior: &dyn OffloadBehavior,
365        agent: &mut LocalAgent,
366        index: usize,
367        tool_names: &HashMap<String, String>,
368        threshold: Option<u64>,
369        archive: Option<&Archive>,
370        invocation_context: Option<&InvocationContext>,
371    ) -> Result<bool> {
372        let Some(message) = agent.messages().get(index).cloned() else {
373            return Ok(false);
374        };
375        let mut acted = false;
376        for (block_index, block) in message.content.iter().enumerate() {
377            if !self.is_offloadable(block, &message, tool_names, archive) {
378                continue;
379            }
380            let measured = count_block_tokens(agent, message.role, block).await?;
381            // The token heuristic counts media as 0, so unmeasured media is never treated as within
382            // the threshold.
383            if threshold.is_some_and(|threshold| measured <= threshold) && !(measured == 0 && holds_media(block)) {
384                continue;
385            }
386            let archive_ref = match archive {
387                Some(archive) => Some(archive.ensure_archived(block, &message, block_index).await?),
388                None => None,
389            };
390            let tool_name = match block {
391                ContentBlock::ToolResult(result) => tool_names.get(&result.tool_use_id).map(String::as_str),
392                _ => None,
393            };
394            // The threshold measures what the block occupies now; the replacement stands for what is
395            // behind it as well.
396            let tokens = measured + carried_tokens([block]);
397            let Some(replacement) = behavior
398                .replace_block(
399                    self,
400                    block,
401                    tokens,
402                    &message,
403                    agent,
404                    archive_ref.as_deref(),
405                    tool_name,
406                    invocation_context,
407                )
408                .await?
409            else {
410                continue;
411            };
412            if &replacement == block {
413                continue;
414            }
415            if let Some(slot) = agent
416                .messages_mut()
417                .get_mut(index)
418                .and_then(|live| live.content.get_mut(block_index))
419            {
420                *slot = replacement;
421                acted = true;
422            }
423        }
424        Ok(acted)
425    }
426}
427
428/// Whether a block is media, or a tool result holding media.
429fn holds_media(block: &ContentBlock) -> bool {
430    match block {
431        ContentBlock::ToolResult(result) => result.content.iter().any(is_media_content),
432        other => is_media_block(other),
433    }
434}
435
436/// The tokens of one block sent alone in a message of `role`.
437///
438/// # Errors
439///
440/// The model's token count error.
441pub(crate) async fn count_block_tokens(agent: &LocalAgent, role: Role, block: &ContentBlock) -> Result<u64> {
442    agent
443        .model()
444        .count_tokens(
445            &[Message::new(role, vec![block.clone()])],
446            CountTokensOptions::default(),
447        )
448        .await
449}
450
451const EMERGENCY_REMOVAL_RATIO: f64 = 0.2;
452
453/// The last-resort strategy the context manager appends: when the window still overflows after
454/// every configured strategy, it drops the oldest 20% of the messages after message 0, ignoring
455/// pins so an all-pinned overflow is still recoverable (`EmergencyTruncateStrategy`).
456#[derive(Debug, Default)]
457pub struct EmergencyTruncateStrategy;
458
459impl EmergencyTruncateStrategy {
460    /// Creates the strategy.
461    #[must_use]
462    pub fn new() -> Self {
463        Self
464    }
465}
466
467#[async_trait]
468impl ContextStrategy for EmergencyTruncateStrategy {
469    fn name(&self) -> &str {
470        "offload:emergency-truncate"
471    }
472
473    #[allow(
474        clippy::cast_possible_truncation,
475        clippy::cast_sign_loss,
476        clippy::cast_precision_loss,
477        reason = "message counts are small"
478    )]
479    async fn apply(&self, context: &mut ContextState<'_>) -> Result<bool> {
480        let length = context.agent.messages().len();
481        if length <= 3 {
482            return Ok(false);
483        }
484        if !context.overflow {
485            // Only what this strategy can remove, never the pipeline's whole-request utilization:
486            // that also carries the system prompt and tool specs, which dropping messages cannot
487            // shrink, and it is anchored on the last call's usage, which an earlier strategy in the
488            // pass has already invalidated.
489            let model = context.agent.model().clone();
490            let tokens = ModelProxy::new(model.clone())
491                .count_tokens(context.agent.messages(), CountTokensOptions::default())
492                .await?;
493            if model.estimate_utilization(tokens) < 1.0 {
494                return Ok(false);
495            }
496        }
497        let removable: Vec<usize> = (1..length).collect();
498        let mut remove_count = ((removable.len() as f64 * EMERGENCY_REMOVAL_RATIO).floor() as usize).max(1);
499        // Cut just before an assistant message, which holds no tool result to orphan and never
500        // merges into message 0.
501        let next_is_assistant = removable
502            .get(remove_count)
503            .is_some_and(|&index| context.agent.messages()[index].role == Role::Assistant);
504        if !next_is_assistant {
505            remove_count += 1;
506        }
507        let to_remove = &removable[..remove_count.min(removable.len())];
508        let text_for = FormattedPlaceholder::new(format_elided);
509        let archive = context.archive.clone();
510        if !remove_messages(
511            context.agent,
512            to_remove,
513            &text_for,
514            OffloadMethod::Truncate,
515            archive.as_ref(),
516        )
517        .await?
518        {
519            return Ok(false);
520        }
521        repair_alternation(context.agent.messages_mut());
522        Ok(true)
523    }
524}
525
526#[cfg(test)]
527#[path = "tests.rs"]
528mod tests;