adk_session/archive.rs
1//! Session archive: put a finished conversation away without deleting it.
2//!
3//! An archived session keeps its events and state, is left out of
4//! [`list_active`](crate::SessionService::list_active), takes no new turns, and comes back with
5//! [`unarchive`](crate::SessionService::unarchive). [`export_session`](crate::SessionService::export_session)
6//! writes any session, archived or not, as a portable [`SessionBundle`].
7//!
8//! | Rule | Where it is kept |
9//! |---|---|
10//! | The mark lives with the session | Its own state, under [`ARCHIVE_KEY`], written by a content-less marker event, so every backend that keeps session state keeps it and the archive is in the session's history |
11//! | Hidden from default lists | [`list_active`](crate::SessionService::list_active) leaves archived sessions out; offset and limit count only the sessions it returns. [`list`](crate::SessionService::list) still lists every session, archived ones with their mark |
12//! | Read-only | [`ensure_writable`] refuses an archived session with `session.archived`; `adk_runner::Runner` calls it before every turn and before recovering held calls, so no agent, schedule, chat or API turn adds to it |
13//! | Restorable | [`unarchive`](crate::SessionService::unarchive) clears the mark with another marker event; the session lists and takes turns again |
14//! | Portable | A [`SessionBundle`] is JSON (`adk.session.bundle/v1`): identity, the session's own state, every event, the archive mark |
15//!
16//! Marker events carry no content, so no model ever sees them.
17//!
18//! # Example
19//!
20//! ```rust
21//! use adk_session::{CreateRequest, InMemorySessionService, ListRequest, SessionService};
22//!
23//! # #[tokio::main(flavor = "current_thread")]
24//! # async fn main() -> adk_core::Result<()> {
25//! let service = InMemorySessionService::new();
26//! let session = service
27//! .create(CreateRequest {
28//! app_name: "app".into(),
29//! user_id: "ana".into(),
30//! session_id: Some("trip".into()),
31//! state: Default::default(),
32//! })
33//! .await?;
34//! let identity = session.try_identity()?;
35//!
36//! let mark = service.archive(&identity, Some("trip booked".into())).await?;
37//! assert_eq!(mark.reason.as_deref(), Some("trip booked"));
38//! let listed = ListRequest { app_name: "app".into(), user_id: "ana".into(), limit: None, offset: None };
39//! assert!(service.list_active(listed.clone()).await?.is_empty());
40//! assert_eq!(service.list_archived(listed.clone()).await?.len(), 1);
41//!
42//! let bundle = service.export_session(&identity).await?;
43//! assert_eq!(bundle.archived, Some(mark));
44//!
45//! service.unarchive(&identity).await?;
46//! assert_eq!(service.list_active(listed).await?.len(), 1);
47//! # Ok(())
48//! # }
49//! ```
50
51use std::collections::HashMap;
52
53use adk_core::identity::AdkIdentity;
54use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
55use chrono::{DateTime, Utc};
56use serde::{Deserialize, Serialize};
57use serde_json::Value;
58
59use crate::{Event, Session};
60
61/// The session-state key an archived session's [`ArchiveMark`] is kept under.
62pub const ARCHIVE_KEY: &str = "adk:archived";
63
64/// The author of the marker events [`archive`](crate::SessionService::archive) and
65/// [`unarchive`](crate::SessionService::unarchive) append.
66pub const ARCHIVE_AUTHOR: &str = "adk.session";
67
68/// The format a [`SessionBundle`] declares, so a reader knows what it holds.
69pub const SESSION_BUNDLE_FORMAT: &str = "adk.session.bundle/v1";
70
71/// How many sessions [`list_active`](crate::SessionService::list_active) and
72/// [`list_archived`](crate::SessionService::list_archived) read from
73/// [`list`](crate::SessionService::list) at a time.
74pub(crate) const LIST_PAGE: usize = 100;
75
76/// When and why a session was archived, kept in its state under [`ARCHIVE_KEY`].
77///
78/// # Example
79///
80/// ```rust
81/// use adk_session::ArchiveMark;
82///
83/// let mark = ArchiveMark::new(Some("done".into()));
84/// let json = serde_json::to_value(&mark).unwrap();
85/// assert_eq!(json["reason"], "done");
86/// assert!(json["archivedAt"].is_string());
87/// ```
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90#[non_exhaustive]
91pub struct ArchiveMark {
92 /// When the session was archived.
93 pub archived_at: DateTime<Utc>,
94 /// Why, in the words of whoever archived it.
95 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub reason: Option<String>,
97}
98
99impl ArchiveMark {
100 /// A mark made now, with `reason`.
101 pub fn new(reason: Option<String>) -> Self {
102 Self { archived_at: Utc::now(), reason }
103 }
104
105 /// The mark `session` carries, or `None` when it is not archived.
106 ///
107 /// # Example
108 ///
109 /// ```rust
110 /// use adk_session::{ArchiveMark, CreateRequest, InMemorySessionService, SessionService};
111 ///
112 /// # #[tokio::main(flavor = "current_thread")]
113 /// # async fn main() -> adk_core::Result<()> {
114 /// let service = InMemorySessionService::new();
115 /// let session = service
116 /// .create(CreateRequest {
117 /// app_name: "app".into(),
118 /// user_id: "ana".into(),
119 /// session_id: None,
120 /// state: Default::default(),
121 /// })
122 /// .await?;
123 /// assert_eq!(ArchiveMark::of(session.as_ref()), None);
124 /// # Ok(())
125 /// # }
126 /// ```
127 pub fn of(session: &dyn Session) -> Option<Self> {
128 Self::in_state(session.state().get(ARCHIVE_KEY).as_ref())
129 }
130
131 /// The mark a state value holds: an object is a mark, anything else (`null` once
132 /// unarchived) is not.
133 fn in_state(value: Option<&Value>) -> Option<Self> {
134 value
135 .filter(|value| value.is_object())
136 .and_then(|value| serde_json::from_value(value.clone()).ok())
137 }
138
139 /// The marker event that writes this mark into a session's state.
140 pub(crate) fn event(&self) -> Result<Event> {
141 let value = serde_json::to_value(self).map_err(|error| {
142 AdkError::session(format!("the archive mark could not be serialized: {error}"))
143 })?;
144 Ok(marker_event(value))
145 }
146}
147
148/// The content-less event that sets [`ARCHIVE_KEY`] to `value`.
149pub(crate) fn marker_event(value: Value) -> Event {
150 let mut event = Event::new(format!("archive-{}", uuid::Uuid::new_v4()));
151 event.author = ARCHIVE_AUTHOR.to_string();
152 event.actions.state_delta.insert(ARCHIVE_KEY.to_string(), value);
153 event
154}
155
156/// Whether `event` is a marker that sets or clears [`ARCHIVE_KEY`].
157pub(crate) fn is_marker_event(event: &Event) -> bool {
158 event.author == ARCHIVE_AUTHOR && event.actions.state_delta.contains_key(ARCHIVE_KEY)
159}
160
161/// Refuses an archived session with `session.archived`, so nothing is added to it.
162///
163/// `adk_runner::Runner` calls this on the session it loaded before every turn. A host that
164/// appends events to a session itself calls it the same way.
165///
166/// # Errors
167///
168/// Returns `session.archived` ([`Conflict`](adk_core::ErrorCategory::Conflict)) when the session
169/// carries an [`ArchiveMark`].
170///
171/// # Example
172///
173/// ```rust
174/// use adk_session::{CreateRequest, InMemorySessionService, SessionService, ensure_writable};
175///
176/// # #[tokio::main(flavor = "current_thread")]
177/// # async fn main() -> adk_core::Result<()> {
178/// let service = InMemorySessionService::new();
179/// let session = service
180/// .create(CreateRequest {
181/// app_name: "app".into(),
182/// user_id: "ana".into(),
183/// session_id: Some("s".into()),
184/// state: Default::default(),
185/// })
186/// .await?;
187/// let identity = session.try_identity()?;
188/// ensure_writable(session.as_ref())?;
189///
190/// service.archive(&identity, None).await?;
191/// let archived = service.get_for_identity(&identity).await?;
192/// let error = ensure_writable(archived.as_ref()).unwrap_err();
193/// assert_eq!(error.code, "session.archived");
194/// # Ok(())
195/// # }
196/// ```
197pub fn ensure_writable(session: &dyn Session) -> Result<()> {
198 match ArchiveMark::of(session) {
199 None => Ok(()),
200 Some(mark) => Err(session_archived(session.id(), &mark)),
201 }
202}
203
204/// The error for a change to an archived session.
205pub(crate) fn session_archived(session_id: &str, mark: &ArchiveMark) -> AdkError {
206 AdkError::new(
207 ErrorComponent::Session,
208 ErrorCategory::Conflict,
209 "session.archived",
210 format!(
211 "session '{session_id}' was archived at {} and is read-only; unarchive it with \
212 SessionService::unarchive (`adk-rust sessions unarchive {session_id}`) to continue \
213 it",
214 mark.archived_at.to_rfc3339()
215 ),
216 )
217}
218
219/// A session written out as one portable JSON document (`adk.session.bundle/v1`).
220///
221/// It holds the session's identity, its own state (the `app:` and `user:` tiers belong to
222/// other sessions too and stay out), every event in order, and the archive mark. Any tool that
223/// reads JSON reads it; the events are [`adk_core::Event`] as every backend stores them.
224///
225/// # Example
226///
227/// ```rust
228/// use adk_session::{CreateRequest, InMemorySessionService, SessionBundle, SessionService};
229///
230/// # #[tokio::main(flavor = "current_thread")]
231/// # async fn main() -> adk_core::Result<()> {
232/// let service = InMemorySessionService::new();
233/// let session = service
234/// .create(CreateRequest {
235/// app_name: "app".into(),
236/// user_id: "ana".into(),
237/// session_id: Some("s".into()),
238/// state: [("topic".to_string(), serde_json::json!("trip"))].into(),
239/// })
240/// .await?;
241/// let bundle = service.export_session(&session.try_identity()?).await?;
242/// let json = serde_json::to_string(&bundle).unwrap();
243/// let read: SessionBundle = serde_json::from_str(&json).unwrap();
244/// assert_eq!(read.format, "adk.session.bundle/v1");
245/// assert_eq!(read.state["topic"], "trip");
246/// # Ok(())
247/// # }
248/// ```
249#[derive(Debug, Clone, Serialize, Deserialize)]
250#[serde(rename_all = "camelCase")]
251#[non_exhaustive]
252pub struct SessionBundle {
253 /// Always [`SESSION_BUNDLE_FORMAT`].
254 pub format: String,
255 /// When the bundle was written.
256 pub exported_at: DateTime<Utc>,
257 /// The application the session belongs to.
258 pub app_name: String,
259 /// The user the session belongs to.
260 pub user_id: String,
261 /// The session's ID.
262 pub session_id: String,
263 /// When the session last changed.
264 pub updated_at: DateTime<Utc>,
265 /// The session's own state, the archive mark included.
266 pub state: HashMap<String, Value>,
267 /// The archive mark, when the session is archived.
268 #[serde(default, skip_serializing_if = "Option::is_none")]
269 pub archived: Option<ArchiveMark>,
270 /// Every event, oldest first.
271 pub events: Vec<Event>,
272}
273
274impl SessionBundle {
275 /// The bundle of `session`, which holds its full history.
276 pub fn of(session: &dyn Session) -> Self {
277 let (_, _, state) = crate::state_utils::extract_state_deltas(&session.state().all());
278 Self {
279 format: SESSION_BUNDLE_FORMAT.to_string(),
280 exported_at: Utc::now(),
281 app_name: session.app_name().to_string(),
282 user_id: session.user_id().to_string(),
283 session_id: session.id().to_string(),
284 updated_at: session.last_update_time(),
285 state,
286 archived: ArchiveMark::of(session),
287 events: session.events().all(),
288 }
289 }
290
291 /// The identity of the session the bundle holds.
292 ///
293 /// # Errors
294 ///
295 /// Returns an invalid-input error when an identifier fails validation.
296 pub fn identity(&self) -> Result<AdkIdentity> {
297 Ok(AdkIdentity::new(
298 self.app_name.as_str().try_into()?,
299 self.user_id.as_str().try_into()?,
300 self.session_id.as_str().try_into()?,
301 ))
302 }
303}
304
305/// Which sessions a listing keeps.
306#[derive(Debug, Clone, Copy, PartialEq, Eq)]
307pub(crate) enum Keep {
308 Active,
309 Archived,
310}
311
312impl Keep {
313 pub(crate) fn keeps(self, session: &dyn Session) -> bool {
314 let archived = ArchiveMark::of(session).is_some();
315 match self {
316 Self::Active => !archived,
317 Self::Archived => archived,
318 }
319 }
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325 use crate::{CreateRequest, InMemorySessionService, ListRequest, SessionService};
326
327 fn listing(limit: Option<usize>, offset: Option<usize>) -> ListRequest {
328 ListRequest { app_name: "app".into(), user_id: "ana".into(), limit, offset }
329 }
330
331 fn ids(sessions: &[Box<dyn Session>]) -> Vec<String> {
332 sessions.iter().map(|session| session.id().to_string()).collect()
333 }
334
335 /// Pages of `list_active` and `list_archived` span several pages of `list` and count only
336 /// the sessions they keep.
337 #[tokio::test]
338 async fn listings_page_across_several_reads_of_list() {
339 let service = InMemorySessionService::new();
340 for index in 0..(LIST_PAGE * 2 + 50) {
341 let session = service
342 .create(CreateRequest {
343 app_name: "app".into(),
344 user_id: "ana".into(),
345 session_id: Some(format!("s{index:04}")),
346 state: Default::default(),
347 })
348 .await
349 .unwrap();
350 if index % 3 == 0 {
351 service.archive(&session.try_identity().unwrap(), None).await.unwrap();
352 }
353 }
354 let all = service.list(listing(None, None)).await.unwrap();
355 let active: Vec<String> = all
356 .iter()
357 .filter(|session| ArchiveMark::of(session.as_ref()).is_none())
358 .map(|session| session.id().to_string())
359 .collect();
360 let archived: Vec<String> = all
361 .iter()
362 .filter(|session| ArchiveMark::of(session.as_ref()).is_some())
363 .map(|session| session.id().to_string())
364 .collect();
365 assert_eq!((active.len(), archived.len()), (166, 84));
366
367 assert_eq!(ids(&service.list_active(listing(None, None)).await.unwrap()), active);
368 assert_eq!(ids(&service.list_archived(listing(None, None)).await.unwrap()), archived);
369 let page = service.list_active(listing(Some(100), Some(50))).await.unwrap();
370 assert_eq!(ids(&page), active[50..150].to_vec());
371 let tail = service.list_active(listing(Some(100), Some(150))).await.unwrap();
372 assert_eq!(ids(&tail), active[150..].to_vec());
373 let page = service.list_archived(listing(Some(10), Some(80))).await.unwrap();
374 assert_eq!(ids(&page), archived[80..].to_vec());
375 assert!(service.list_active(listing(Some(5), Some(500))).await.unwrap().is_empty());
376 }
377
378 /// A state value other than an object, such as the `null` an unarchive writes, is no mark.
379 #[test]
380 fn only_an_object_is_a_mark() {
381 assert_eq!(ArchiveMark::in_state(None), None);
382 assert_eq!(ArchiveMark::in_state(Some(&Value::Null)), None);
383 assert_eq!(ArchiveMark::in_state(Some(&serde_json::json!(true))), None);
384 let mark = ArchiveMark::new(Some("done".into()));
385 let value = serde_json::to_value(&mark).unwrap();
386 assert_eq!(ArchiveMark::in_state(Some(&value)), Some(mark.clone()));
387 let event = mark.event().unwrap();
388 assert_eq!(event.author, ARCHIVE_AUTHOR);
389 assert!(event.llm_response.content.is_none());
390 assert_eq!(event.actions.state_delta[ARCHIVE_KEY], value);
391 let error = session_archived("s1", &mark);
392 assert_eq!((error.code, error.category), ("session.archived", ErrorCategory::Conflict));
393 assert!(error.message.contains("adk-rust sessions unarchive s1"), "{}", error.message);
394 }
395}