Skip to main content

strands/context_manager/
archive.rs

1//! The L1 archive: durable storage for content the context manager offloads, so the agent can
2//! retrieve it with `retrieve_context`.
3
4use std::collections::HashSet;
5use std::fmt;
6use std::sync::Arc;
7
8use super::placeholder::{is_offloaded, is_offloaded_content};
9use super::strategies::offload::target::is_protocol_block;
10use crate::error::Result;
11use crate::storage::{NamespacedStorage, Storage};
12use crate::types::{ContentBlock, JsonObject, JsonValue, Message, ToolResultBlock};
13
14/// The key prefix every per-agent archive lives under (`ARCHIVE_PREFIX`).
15pub(crate) const ARCHIVE_PREFIX: &str = "context";
16
17/// An archive key, `<id>_<index>` (`ArchiveKey`). The id is a tool result's `toolUseId`, a message's
18/// `trackingId`, or `removed-<trackingId>` for messages removed together.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub(crate) struct ArchiveKey {
21    /// Owner of the entry.
22    pub(crate) id: String,
23    /// Position of the entry among the owner's items.
24    pub(crate) index: usize,
25}
26
27/// `<id>_<index>` (`formatArchiveKey`).
28pub(crate) fn format_archive_key(id: &str, index: usize) -> String {
29    format!("{id}_{index}")
30}
31
32/// Parses an archive key (`parseArchiveKey`). The id may itself contain `_`, so the index is whatever
33/// follows the last one; `None` when that is not an index.
34pub(crate) fn parse_archive_key(key: &str) -> Option<ArchiveKey> {
35    let separator = key.rfind('_').filter(|&separator| separator > 0)?;
36    let index = &key[separator + 1..];
37    if index.is_empty() || !index.bytes().all(|byte| byte.is_ascii_digit()) {
38        return None;
39    }
40    Some(ArchiveKey {
41        id: key[..separator].to_owned(),
42        index: index.parse().ok()?,
43    })
44}
45
46fn encode(value: &impl serde::Serialize) -> Result<Vec<u8>> {
47    Ok(serde_json::to_vec(value)?)
48}
49
50fn decode(bytes: &[u8]) -> Result<JsonValue> {
51    Ok(serde_json::from_slice(bytes)?)
52}
53
54struct Inner {
55    storage: Arc<dyn Storage>,
56    base_storage: Arc<dyn Storage>,
57    caller_scoped: bool,
58    session_id: String,
59    storage_type_name: String,
60}
61
62/// Key management and content framing over a [`Storage`] for the context manager's offloaded
63/// content (`Archive`).
64///
65/// Each agent archives under `context/<sessionId>/scopes/agent/<agentId>/`. Keys are deterministic
66/// (`<toolUseId>_<index>` for tool result content, `<trackingId>_<blockIndex>` for other blocks),
67/// so placeholders can name them before the content is stored again after a restore. Clones share
68/// the same archive.
69#[derive(Clone)]
70pub struct Archive {
71    inner: Arc<Inner>,
72}
73
74impl Archive {
75    /// An archive for `agent_id` in `session_id`, under `context/<sessionId>/scopes/agent/<agentId>/`
76    /// of `storage`.
77    ///
78    /// # Errors
79    ///
80    /// An id that does not form a valid storage prefix.
81    pub fn new(storage: Arc<dyn Storage>, session_id: &str, agent_id: &str) -> Result<Self> {
82        Self::with_namespace(storage, session_id, agent_id, false)
83    }
84
85    /// As [`new`](Self::new); with `custom_archive_namespace`, a namespaced view of a built-in backend
86    /// is used as the exact archive root.
87    pub(crate) fn with_namespace(
88        storage: Arc<dyn Storage>,
89        session_id: &str,
90        agent_id: &str,
91        custom_archive_namespace: bool,
92    ) -> Result<Self> {
93        let caller_scoped = custom_archive_namespace && storage.is_namespaced();
94        let scoped: Arc<dyn Storage> = if caller_scoped {
95            storage.clone()
96        } else {
97            Arc::new(NamespacedStorage::new(
98                storage.clone(),
99                &format!("{ARCHIVE_PREFIX}/{session_id}/scopes/agent/{agent_id}"),
100            )?)
101        };
102        let storage_type_name = storage.storage_type().to_owned();
103        Ok(Self {
104            inner: Arc::new(Inner {
105                storage: scoped,
106                base_storage: storage,
107                caller_scoped,
108                session_id: session_id.to_owned(),
109                storage_type_name,
110            }),
111        })
112    }
113
114    /// The type name of the base storage, recorded in session snapshots of a durable archive.
115    #[must_use]
116    pub fn storage_type_name(&self) -> &str {
117        &self.inner.storage_type_name
118    }
119
120    /// Stores serialized data under `<id>_<blockIndex>` and returns that reference (`store`).
121    ///
122    /// # Errors
123    ///
124    /// The storage's write error.
125    pub async fn store(&self, id: &str, block_index: usize, data: &[u8]) -> Result<String> {
126        let key = format_archive_key(id, block_index);
127        self.inner.storage.write(&key, data).await?;
128        Ok(key)
129    }
130
131    /// The reference an offload placeholder carries for the block it replaces, with the block
132    /// stored under that reference if it is not already (`ensureArchived`).
133    ///
134    /// A tool result is referenced by its `toolUseId`; the retrieval tool resolves it to every
135    /// stored item (`<toolUseId>_<i>`). Any other block is referenced by its position
136    /// (`<trackingId>_<blockIndex>`). History edits move blocks between messages and positions, so
137    /// the key a block was stored under on arrival can differ from its key now; storing here keeps
138    /// every emitted reference resolvable.
139    ///
140    /// # Errors
141    ///
142    /// The storage's list or write error.
143    pub(crate) async fn ensure_archived(
144        &self,
145        block: &ContentBlock,
146        message: &Message,
147        block_index: usize,
148    ) -> Result<String> {
149        if let ContentBlock::ToolResult(result) = block {
150            // A result that already holds a placeholder is not the original; its items were stored
151            // before it was offloaded.
152            if result.content.iter().any(is_offloaded_content) {
153                return Ok(result.tool_use_id.clone());
154            }
155            if self.keys_of(&result.tool_use_id).await?.len() < result.content.len() {
156                self.store_tool_result(result).await;
157            }
158            return Ok(result.tool_use_id.clone());
159        }
160        let key = format_archive_key(message.tracking_id(), block_index);
161        if !self.list(&key).await?.contains(&key) {
162            self.store(message.tracking_id(), block_index, &encode(block)?).await?;
163        }
164        Ok(key)
165    }
166
167    /// Stores messages removed from the context window as one entry and returns the reference the
168    /// placeholder left in their place carries (`storeRemoved`).
169    ///
170    /// # Errors
171    ///
172    /// The storage's write error.
173    pub(crate) async fn store_removed(&self, removed: &[Message]) -> Result<String> {
174        let first = removed.first().map_or("", Message::tracking_id);
175        let id = format!("removed-{first}");
176        self.store(&id, 0, &encode(&removed)?).await?;
177        Ok(id)
178    }
179
180    /// Stores every block of a message as it arrives (`storeMessage`). Protocol blocks, offload
181    /// placeholders and tool results in `skip_tool_use_ids` are left out, and a block already
182    /// stored under one of `stored_keys` keeps its entry, since a restored history can hold a
183    /// placeholder where the stored original was. Failures are logged.
184    pub async fn store_message(
185        &self,
186        message: &Message,
187        skip_tool_use_ids: Option<&HashSet<String>>,
188        stored_keys: Option<&HashSet<String>>,
189    ) {
190        for (block_index, block) in message.content.iter().enumerate() {
191            if is_skipped(block, message, block_index, skip_tool_use_ids, stored_keys) {
192                continue;
193            }
194            if let ContentBlock::ToolResult(result) = block {
195                self.store_tool_result(result).await;
196                continue;
197            }
198            let stored = match encode(block) {
199                Ok(bytes) => self.store(message.tracking_id(), block_index, &bytes).await.map(drop),
200                Err(error) => Err(error),
201            };
202            if let Err(error) = stored {
203                tracing::warn!(
204                    "tracking_id=<{}>, error=<{error}> | failed to archive block",
205                    message.tracking_id()
206                );
207            }
208        }
209    }
210
211    async fn store_tool_result(&self, block: &ToolResultBlock) {
212        for (block_index, item) in block.content.iter().enumerate() {
213            let stored = match encode(item) {
214                Ok(bytes) => self.store(&block.tool_use_id, block_index, &bytes).await.map(drop),
215                Err(error) => Err(error),
216            };
217            if let Err(error) = stored {
218                tracing::warn!(
219                    "tool_use_id=<{}>, block_index=<{block_index}>, error=<{error}> | failed to archive sub-block",
220                    block.tool_use_id
221                );
222            }
223        }
224    }
225
226    /// The stored JSON of a reference, or `None` when there is none (`retrieve`).
227    ///
228    /// # Errors
229    ///
230    /// The storage's read error, or stored bytes that are not JSON.
231    pub async fn retrieve(&self, reference: &str) -> Result<Option<JsonValue>> {
232        let Some(bytes) = self.inner.storage.read(reference).await? else {
233            return Ok(None);
234        };
235        decode(&bytes).map(Some)
236    }
237
238    /// The stored references starting with `prefix`; every one for `""` (`list`).
239    ///
240    /// # Errors
241    ///
242    /// The storage's list error.
243    pub async fn list(&self, prefix: &str) -> Result<Vec<String>> {
244        self.inner.storage.list(prefix).await
245    }
246
247    /// The keys stored under `id`, in index order (`keysOf`). A prefix list alone also returns ids
248    /// that extend this one.
249    ///
250    /// # Errors
251    ///
252    /// The storage's list error.
253    pub(crate) async fn keys_of(&self, id: &str) -> Result<Vec<String>> {
254        let mut keys: Vec<(usize, String)> = self
255            .list(&format!("{id}_"))
256            .await?
257            .into_iter()
258            .filter_map(|key| {
259                let parsed = parse_archive_key(&key)?;
260                (parsed.id == id).then_some((parsed.index, key))
261            })
262            .collect();
263        keys.sort_by_key(|(index, _)| *index);
264        Ok(keys.into_iter().map(|(_, key)| key).collect())
265    }
266
267    /// Deletes a stored entry (`delete`).
268    ///
269    /// # Errors
270    ///
271    /// The storage's delete error.
272    pub async fn delete(&self, reference: &str) -> Result<()> {
273        self.inner.storage.delete(reference).await?;
274        tracing::debug!("reference=<{reference}> | archive entry deleted");
275        Ok(())
276    }
277
278    /// Deletes every entry of this archive (`clear`). On a caller-scoped archive this is the whole
279    /// shared view, other agents' entries included.
280    ///
281    /// # Errors
282    ///
283    /// The storage's list or delete error.
284    pub async fn clear(&self) -> Result<()> {
285        for key in self.list("").await? {
286            self.delete(&key).await?;
287        }
288        Ok(())
289    }
290
291    /// Deletes the archive data of this session for every agent, `context/<sessionId>/` on the base
292    /// storage. A caller-scoped archive may be shared beyond the session and is
293    /// left in place.
294    ///
295    /// # Errors
296    ///
297    /// The storage's list or delete error.
298    pub async fn clear_session(&self) -> Result<()> {
299        if self.inner.caller_scoped {
300            tracing::debug!(
301                "session_id=<{}> | skipping archive deletion, archive is caller-scoped",
302                self.inner.session_id
303            );
304            return Ok(());
305        }
306        let prefix = format!("{ARCHIVE_PREFIX}/{}/", self.inner.session_id);
307        for key in self.inner.base_storage.list(&prefix).await? {
308            self.inner.base_storage.delete(&key).await?;
309        }
310        Ok(())
311    }
312
313    /// Every entry as reference to stored JSON, for a session snapshot.
314    ///
315    /// # Errors
316    ///
317    /// The storage's errors, or stored bytes that are not JSON.
318    pub async fn take_snapshot(&self) -> Result<JsonObject> {
319        let mut entries = JsonObject::new();
320        for key in self.list("").await? {
321            if let Some(data) = self.retrieve(&key).await? {
322                entries.insert(key, data);
323            }
324        }
325        Ok(entries)
326    }
327
328    /// Writes back entries captured by [`take_snapshot`](Self::take_snapshot).
329    ///
330    /// # Errors
331    ///
332    /// The storage's write error.
333    pub async fn load_snapshot(&self, entries: &JsonObject) -> Result<()> {
334        for (key, data) in entries {
335            self.inner.storage.write(key, &encode(data)?).await?;
336        }
337        Ok(())
338    }
339}
340
341/// Whether [`Archive::store_message`] leaves a block out.
342fn is_skipped(
343    block: &ContentBlock,
344    message: &Message,
345    block_index: usize,
346    skip_tool_use_ids: Option<&HashSet<String>>,
347    stored_keys: Option<&HashSet<String>>,
348) -> bool {
349    if is_protocol_block(block) {
350        return true;
351    }
352    if let ContentBlock::ToolResult(result) = block {
353        if skip_tool_use_ids.is_some_and(|skip| skip.contains(&result.tool_use_id))
354            || result.content.iter().any(is_offloaded_content)
355        {
356            return true;
357        }
358        return stored_keys.is_some_and(|keys| {
359            keys.iter()
360                .any(|key| parse_archive_key(key).is_some_and(|parsed| parsed.id == result.tool_use_id))
361        });
362    }
363    if is_offloaded(block) {
364        return true;
365    }
366    stored_keys.is_some_and(|keys| keys.contains(&format_archive_key(message.tracking_id(), block_index)))
367}
368
369impl fmt::Debug for Archive {
370    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371        f.debug_struct("Archive")
372            .field("session_id", &self.inner.session_id)
373            .field("storage_type_name", &self.inner.storage_type_name)
374            .field("caller_scoped", &self.inner.caller_scoped)
375            .finish_non_exhaustive()
376    }
377}
378
379#[cfg(test)]
380#[path = "archive/tests.rs"]
381mod tests;