Skip to main content

adk_session/
history.rs

1//! Forking a session, rewinding it, and editing its history.
2//!
3//! | Operation | Method | Effect |
4//! |-----------|--------|--------|
5//! | Fork | [`SessionService::fork`](crate::SessionService::fork) | A new session of the same app and user holding the source's events up to an event |
6//! | Rewind | [`rewind`](crate::SessionService::rewind), [`rewind_steps`](crate::SessionService::rewind_steps) | Removes the events after a target event |
7//! | Edit | [`rewrite_history`](crate::SessionService::rewrite_history) with [`HistoryRewrite::Edit`] | Replaces or removes events |
8//!
9//! Every operation rebuilds the session's own state from the state it was created with plus the
10//! state deltas of the events it keeps. The `app:` and `user:` tiers are shared with other
11//! sessions and never change: the deltas of removed or replaced events stay in them.
12//!
13//! Three rules hold on every backend:
14//!
15//! - **Tool calls stay paired.** An operation that would keep a tool call whose response it
16//!   removes, or keep a response whose call it removes, fails with
17//!   `session.history.splits_tool_call`; no provider then receives a call without its result.
18//! - **Held calls block rewrites.** A rewind or edit of a session that holds a call for a
19//!   decision fails with `session.history.held_call`, and a fork that would copy a held call
20//!   fails the same way. Decide the call first, or fork at an earlier event.
21//! - **Writes are atomic per session.** A rewrite reads, checks, and writes the session in one
22//!   transaction or one guarded script; [`RewriteHistoryRequest::expected_version`] refuses a
23//!   rewrite when the history changed since the caller read [`SessionHistory::version`].
24//!
25//! A fork records where it came from in its state under [`FORK_ORIGIN_KEY`]; read it back with
26//! [`ForkOrigin::of`]. Each operation returns a [`HistoryChange`] naming what changed, which the
27//! runner and server record in the audit log.
28
29use crate::{Event, KEY_PREFIX_APP, KEY_PREFIX_TEMP, KEY_PREFIX_USER, Session};
30use adk_core::identity::AdkIdentity;
31use adk_core::{AdkError, ErrorCategory, ErrorComponent, Part, Result};
32use chrono::{DateTime, Utc};
33use serde::{Deserialize, Serialize};
34use serde_json::Value;
35use std::collections::{HashMap, HashSet};
36
37type StateMap = HashMap<String, Value>;
38
39/// The state key under which a fork records its [`ForkOrigin`].
40///
41/// The key is session-scoped and part of the state the fork was created with, so rewinding the
42/// fork keeps it.
43pub const FORK_ORIGIN_KEY: &str = "adk:forked_from";
44
45/// Where a forked session came from.
46///
47/// # Example
48///
49/// ```rust
50/// use adk_core::identity::AdkIdentity;
51/// use adk_session::{CreateRequest, ForkOrigin, ForkRequest, InMemorySessionService, SessionService};
52///
53/// # #[tokio::main(flavor = "current_thread")]
54/// # async fn main() -> adk_core::Result<()> {
55/// let service = InMemorySessionService::new();
56/// let source = service
57///     .create(CreateRequest {
58///         app_name: "app".into(),
59///         user_id: "alice".into(),
60///         session_id: Some("main".into()),
61///         state: Default::default(),
62///     })
63///     .await?;
64/// let fork = service.fork(ForkRequest::new(source.try_identity()?)).await?;
65/// let origin = ForkOrigin::of(fork.session.as_ref()).expect("a fork records its origin");
66/// assert_eq!(origin.session_id, "main");
67/// # Ok(())
68/// # }
69/// ```
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "camelCase")]
72#[non_exhaustive]
73pub struct ForkOrigin {
74    /// The session the fork was taken from.
75    pub session_id: String,
76    /// The last event the fork copied; `None` when the source held no events.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub event_id: Option<String>,
79    /// When the fork was taken.
80    pub forked_at: DateTime<Utc>,
81}
82
83impl ForkOrigin {
84    /// The origin `session` recorded when it was forked, or `None` for a session that is not a
85    /// fork.
86    pub fn of(session: &dyn Session) -> Option<Self> {
87        session.state().get(FORK_ORIGIN_KEY).and_then(|value| serde_json::from_value(value).ok())
88    }
89}
90
91/// A session's stored history: its events, its own state, and the state it was created with.
92///
93/// Backends read it inside the transaction of a rewrite; callers read it with
94/// [`SessionService::history`](crate::SessionService::history).
95#[derive(Debug, Clone, Default)]
96#[non_exhaustive]
97pub struct SessionHistory {
98    /// The events in read order.
99    pub events: Vec<Event>,
100    /// The session's own state: the session tier on backends that keep `app:` and `user:`
101    /// tiers apart, every key on a backend that does not.
102    pub state: StateMap,
103    /// The session state the session was created with, or `None` for a session created before
104    /// its backend recorded it.
105    pub initial_state: Option<StateMap>,
106    /// Whether `app:` and `user:` keys live in shared tiers rather than in the session.
107    pub shared_tiers: bool,
108}
109
110impl SessionHistory {
111    /// The history of a backend that keeps `app:` and `user:` keys in shared tiers.
112    pub fn new(events: Vec<Event>, state: StateMap, initial_state: Option<StateMap>) -> Self {
113        Self { events, state, initial_state, shared_tiers: true }
114    }
115
116    /// The history of a backend that stores `app:` and `user:` keys in the session itself.
117    pub fn without_shared_tiers(
118        events: Vec<Event>,
119        state: StateMap,
120        initial_state: Option<StateMap>,
121    ) -> Self {
122        Self { events, state, initial_state, shared_tiers: false }
123    }
124
125    /// A digest of the events, which changes whenever one is appended, removed, or replaced.
126    ///
127    /// Pass it as [`RewriteHistoryRequest::expected_version`] to rewrite only the history the
128    /// caller read.
129    pub fn version(&self) -> String {
130        history_version(&self.events)
131    }
132
133    /// Whether `key` belongs to this session rather than to a shared tier or to no store.
134    fn session_scoped(&self, key: &str) -> bool {
135        !key.starts_with(KEY_PREFIX_TEMP)
136            && (!self.shared_tiers
137                || !(key.starts_with(KEY_PREFIX_APP) || key.starts_with(KEY_PREFIX_USER)))
138    }
139
140    /// The session-scoped keys of `state`.
141    fn scoped(&self, state: &StateMap) -> StateMap {
142        state
143            .iter()
144            .filter(|(key, _)| self.session_scoped(key))
145            .map(|(key, value)| (key.clone(), value.clone()))
146            .collect()
147    }
148
149    /// The state the session was created with: the recorded one, or for a session created
150    /// before its backend recorded it, its current keys that no event wrote, whose values
151    /// cannot have changed since it was created.
152    pub fn creation_state(&self) -> StateMap {
153        if let Some(initial) = &self.initial_state {
154            return self.scoped(initial);
155        }
156        let mut state = self.scoped(&self.state);
157        for event in &self.events {
158            for key in event.actions.state_delta.keys() {
159                state.remove(key);
160            }
161        }
162        state
163    }
164
165    /// The session state after `events`: the creation state plus their session-scoped deltas.
166    pub fn state_after<'a>(&self, events: impl IntoIterator<Item = &'a Event>) -> StateMap {
167        let mut state = self.creation_state();
168        for event in events {
169            state.extend(self.scoped(&event.actions.state_delta));
170        }
171        state
172    }
173
174    fn position(&self, identity: &AdkIdentity, event_id: &str) -> Result<usize> {
175        let mut found = self.events.iter().enumerate().filter(|(_, event)| event.id == event_id);
176        match (found.next(), found.next()) {
177            (Some((index, _)), None) => Ok(index),
178            (Some(_), Some(_)) => Err(history_error(
179                ErrorCategory::InvalidInput,
180                "session.history.ambiguous_event",
181                format!(
182                    "event '{event_id}' appears more than once in session '{}'; the history \
183                     cannot address it",
184                    identity.session_id
185                ),
186            )),
187            (None, _) => Err(event_not_found(identity, event_id)),
188        }
189    }
190
191    /// Applies `rewrite` to this history and returns what the session holds afterwards.
192    ///
193    /// Backends call it inside the transaction that writes the result, so the checks and the
194    /// write see the same history.
195    ///
196    /// # Errors
197    ///
198    /// Returns `session.history.version_mismatch` when `expected_version` no longer matches,
199    /// `session.history.held_call` while the session holds a call for a decision,
200    /// `session.event_not_found` for a target the session does not hold,
201    /// `session.rewind.too_many_steps` for more steps than events, and
202    /// `session.history.splits_tool_call` when the result would separate a tool call from its
203    /// response.
204    pub fn rewrite(
205        &self,
206        identity: &AdkIdentity,
207        rewrite: &HistoryRewrite,
208        expected_version: Option<&str>,
209    ) -> Result<RewrittenHistory> {
210        let version_before = self.version();
211        if let Some(expected) = expected_version
212            && expected != version_before
213        {
214            return Err(history_error(
215                ErrorCategory::Conflict,
216                "session.history.version_mismatch",
217                format!(
218                    "the history of session '{}' changed since version '{expected}' was read; \
219                     read it again and retry",
220                    identity.session_id
221                ),
222            ));
223        }
224        if !matches!(rewrite, HistoryRewrite::RewindSteps { steps: 0 }) {
225            refuse_held_calls(identity, &self.events, "rewritten")?;
226        }
227
228        let (events, operation, removed, replaced) = match rewrite {
229            HistoryRewrite::RewindTo { event_id } => {
230                let keep = self.position(identity, event_id)? + 1;
231                let removed = self.events[keep..].iter().map(|e| e.id.clone()).collect();
232                (self.events[..keep].to_vec(), HistoryOperation::Rewind, removed, Vec::new())
233            }
234            HistoryRewrite::RewindSteps { steps } => {
235                let keep = self.events.len().checked_sub(*steps).ok_or_else(|| {
236                    crate::service::rewind_steps_exceed(identity, *steps, self.events.len())
237                })?;
238                let removed = self.events[keep..].iter().map(|e| e.id.clone()).collect();
239                (self.events[..keep].to_vec(), HistoryOperation::Rewind, removed, Vec::new())
240            }
241            HistoryRewrite::Edit { edits } => {
242                let mut events = self.events.clone();
243                let mut removed = Vec::new();
244                let mut replaced = Vec::new();
245                for edit in edits {
246                    match edit {
247                        HistoryEdit::Replace { event } => {
248                            let index = self.position(identity, &event.id)?;
249                            let current = events
250                                .iter()
251                                .position(|stored| stored.id == event.id)
252                                .ok_or_else(|| event_not_found(identity, &event.id))?;
253                            let mut replacement = Event::clone(event);
254                            // Order is (timestamp, append order), so the original timestamp
255                            // keeps the replacement where the original stood.
256                            replacement.timestamp = self.events[index].timestamp;
257                            replacement
258                                .actions
259                                .state_delta
260                                .retain(|key, _| !key.starts_with(KEY_PREFIX_TEMP));
261                            events[current] = replacement;
262                            replaced.push(event.id.clone());
263                        }
264                        HistoryEdit::Remove { event_id } => {
265                            self.position(identity, event_id)?;
266                            let current = events
267                                .iter()
268                                .position(|stored| &stored.id == event_id)
269                                .ok_or_else(|| event_not_found(identity, event_id))?;
270                            events.remove(current);
271                            removed.push(event_id.clone());
272                        }
273                    }
274                }
275                replaced.retain(|id| !removed.contains(id));
276                (events, HistoryOperation::Edit, removed, replaced)
277            }
278        };
279
280        refuse_split_tool_calls(identity, &self.events, &events)?;
281        let state = self.state_after(&events);
282        let changed: Vec<&Event> = self
283            .events
284            .iter()
285            .filter(|event| removed.contains(&event.id) || replaced.contains(&event.id))
286            .collect();
287        let change = HistoryChange {
288            operation,
289            session_id: identity.session_id.as_ref().to_string(),
290            version_before,
291            version_after: history_version(&events),
292            removed,
293            replaced,
294            changed_digest: (!changed.is_empty()).then(|| events_digest(&changed)),
295            events_after: events.len(),
296            fork_origin: None,
297        };
298        Ok(RewrittenHistory { events, state, change })
299    }
300
301    /// Plans the fork `request` of this history: the session to import and the change record.
302    ///
303    /// # Errors
304    ///
305    /// Returns `session.event_not_found` for a fork point the session does not hold,
306    /// `session.history.held_call` when the copied events hold a call for a decision, and
307    /// `session.history.splits_tool_call` when the fork point separates a tool call from its
308    /// response.
309    pub fn fork(&self, request: &ForkRequest) -> Result<(ImportSessionRequest, HistoryChange)> {
310        let source = &request.source;
311        let keep = match &request.at_event_id {
312            Some(event_id) => self.position(source, event_id)? + 1,
313            None => self.events.len(),
314        };
315        let events = self.events[..keep].to_vec();
316        refuse_held_calls(source, &events, "forked")?;
317        refuse_split_tool_calls(source, &self.events, &events)?;
318
319        let session_id = match &request.session_id {
320            Some(id) => adk_core::identity::SessionId::try_from(id.as_str())?,
321            None => adk_core::identity::SessionId::try_from(uuid::Uuid::new_v4().to_string())?,
322        };
323        let identity =
324            AdkIdentity::new(source.app_name.clone(), source.user_id.clone(), session_id);
325        let origin = ForkOrigin {
326            session_id: source.session_id.as_ref().to_string(),
327            event_id: events.last().map(|event| event.id.clone()),
328            forked_at: Utc::now(),
329        };
330        let origin_value = serde_json::to_value(&origin).map_err(|e| {
331            history_error(
332                ErrorCategory::Internal,
333                "session.history.serialize",
334                format!("serialize fork origin failed: {e}"),
335            )
336        })?;
337        // A fork is a new, active session: it keeps neither the source's archive mark nor the
338        // events that set it, so a later rewind of the fork cannot archive it again.
339        let events: Vec<Event> =
340            events.into_iter().filter(|event| !crate::archive::is_marker_event(event)).collect();
341        let mut initial_state = self.creation_state();
342        initial_state.remove(crate::archive::ARCHIVE_KEY);
343        initial_state.insert(FORK_ORIGIN_KEY.to_string(), origin_value.clone());
344        let mut state = self.state_after(&events);
345        state.remove(crate::archive::ARCHIVE_KEY);
346        state.insert(FORK_ORIGIN_KEY.to_string(), origin_value);
347
348        let change = HistoryChange {
349            operation: HistoryOperation::Fork,
350            session_id: identity.session_id.as_ref().to_string(),
351            version_before: self.version(),
352            version_after: history_version(&events),
353            removed: Vec::new(),
354            replaced: Vec::new(),
355            changed_digest: None,
356            events_after: events.len(),
357            fork_origin: Some(origin),
358        };
359        Ok((ImportSessionRequest { identity, initial_state, state, events }, change))
360    }
361}
362
363/// What the session holds after a [`SessionHistory::rewrite`].
364#[derive(Debug, Clone)]
365#[non_exhaustive]
366pub struct RewrittenHistory {
367    /// Every event the session holds afterwards, in order.
368    pub events: Vec<Event>,
369    /// The session's own state afterwards.
370    pub state: StateMap,
371    /// What changed.
372    pub change: HistoryChange,
373}
374
375/// An in-place change to a session's history.
376#[derive(Debug, Clone)]
377#[non_exhaustive]
378pub enum HistoryRewrite {
379    /// Keeps the events up to and including `event_id` and removes the rest.
380    RewindTo {
381        /// The last event to keep.
382        event_id: String,
383    },
384    /// Removes the last `steps` events.
385    RewindSteps {
386        /// How many events to remove from the end.
387        steps: usize,
388    },
389    /// Applies `edits` in order.
390    Edit {
391        /// The edits.
392        edits: Vec<HistoryEdit>,
393    },
394}
395
396/// One edit of a session's history.
397///
398/// # Example
399///
400/// ```rust
401/// use adk_session::{Event, HistoryEdit, HistoryRewrite};
402///
403/// let mut corrected = Event::new("inv-1");
404/// corrected.id = "event-to-correct".into();
405/// let rewrite = HistoryRewrite::Edit {
406///     edits: vec![
407///         HistoryEdit::Replace { event: Box::new(corrected) },
408///         HistoryEdit::Remove { event_id: "event-to-drop".into() },
409///     ],
410/// };
411/// assert!(matches!(rewrite, HistoryRewrite::Edit { .. }));
412/// ```
413#[derive(Debug, Clone)]
414#[non_exhaustive]
415pub enum HistoryEdit {
416    /// Replaces the stored event with the same ID by `event`.
417    ///
418    /// The replacement keeps the original's timestamp, so it stays where the original stood.
419    /// Its `temp:` state keys are dropped, and its `app:` and `user:` keys are kept on the
420    /// event but not applied to the shared tiers.
421    Replace {
422        /// The replacement; its `id` names the event it replaces.
423        event: Box<Event>,
424    },
425    /// Removes the event `event_id`.
426    Remove {
427        /// The event to remove.
428        event_id: String,
429    },
430}
431
432/// Request to rewrite a session's history in place.
433///
434/// # Example
435///
436/// ```rust
437/// use adk_core::identity::AdkIdentity;
438/// use adk_session::{HistoryRewrite, RewriteHistoryRequest};
439///
440/// let identity = AdkIdentity::new(
441///     "app".try_into().unwrap(),
442///     "alice".try_into().unwrap(),
443///     "s1".try_into().unwrap(),
444/// );
445/// let request = RewriteHistoryRequest::new(identity, HistoryRewrite::RewindSteps { steps: 2 })
446///     .expect_version("fnv1a128:0");
447/// assert_eq!(request.expected_version.as_deref(), Some("fnv1a128:0"));
448/// ```
449#[derive(Debug, Clone)]
450#[non_exhaustive]
451pub struct RewriteHistoryRequest {
452    /// The session to rewrite.
453    pub identity: AdkIdentity,
454    /// The change.
455    pub rewrite: HistoryRewrite,
456    /// When set, the rewrite applies only while the history's
457    /// [`version`](SessionHistory::version) is still this one.
458    pub expected_version: Option<String>,
459}
460
461impl RewriteHistoryRequest {
462    /// A rewrite of the session `identity` that applies whatever its current version.
463    pub fn new(identity: AdkIdentity, rewrite: HistoryRewrite) -> Self {
464        Self { identity, rewrite, expected_version: None }
465    }
466
467    /// Applies the rewrite only while the history is still at `version`.
468    #[must_use]
469    pub fn expect_version(mut self, version: impl Into<String>) -> Self {
470        self.expected_version = Some(version.into());
471        self
472    }
473}
474
475/// Request to fork a session.
476///
477/// The fork belongs to the same app and user as the source.
478///
479/// # Example
480///
481/// ```rust
482/// use adk_core::identity::AdkIdentity;
483/// use adk_session::ForkRequest;
484///
485/// let source = AdkIdentity::new(
486///     "app".try_into().unwrap(),
487///     "alice".try_into().unwrap(),
488///     "main".try_into().unwrap(),
489/// );
490/// let request = ForkRequest::new(source).at_event("event-7").with_session_id("try-b");
491/// assert_eq!(request.at_event_id.as_deref(), Some("event-7"));
492/// ```
493#[derive(Debug, Clone)]
494#[non_exhaustive]
495pub struct ForkRequest {
496    /// The session to fork.
497    pub source: AdkIdentity,
498    /// The last event the fork copies; `None` copies every event.
499    pub at_event_id: Option<String>,
500    /// The fork's session ID; a UUID when `None`.
501    pub session_id: Option<String>,
502}
503
504impl ForkRequest {
505    /// A fork of every event of `source` under a generated session ID.
506    pub fn new(source: AdkIdentity) -> Self {
507        Self { source, at_event_id: None, session_id: None }
508    }
509
510    /// Copies the events up to and including `event_id` only.
511    #[must_use]
512    pub fn at_event(mut self, event_id: impl Into<String>) -> Self {
513        self.at_event_id = Some(event_id.into());
514        self
515    }
516
517    /// Names the fork's session.
518    #[must_use]
519    pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
520        self.session_id = Some(session_id.into());
521        self
522    }
523}
524
525/// Request to create a session that already holds events.
526///
527/// Unlike [`create`](crate::SessionService::create) followed by appends, an import writes the
528/// events as they are and never applies their state deltas to the `app:` and `user:` tiers;
529/// `state` and `initial_state` hold only the session's own keys.
530/// [`fork`](crate::SessionService::fork) builds one; it also moves a session between backends.
531#[derive(Debug, Clone)]
532#[non_exhaustive]
533pub struct ImportSessionRequest {
534    /// The session to create.
535    pub identity: AdkIdentity,
536    /// The state recorded as the one the session was created with.
537    pub initial_state: StateMap,
538    /// The session's state.
539    pub state: StateMap,
540    /// The events, in order.
541    pub events: Vec<Event>,
542}
543
544impl ImportSessionRequest {
545    /// An import of `events` into the new session `identity`, with `state` as both its current
546    /// state and the state it was created with.
547    pub fn new(identity: AdkIdentity, state: StateMap, events: Vec<Event>) -> Self {
548        Self { identity, initial_state: state.clone(), state, events }
549    }
550}
551
552/// Which operation changed a history.
553#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
554#[serde(rename_all = "camelCase")]
555#[non_exhaustive]
556pub enum HistoryOperation {
557    /// A fork created a session.
558    Fork,
559    /// A rewind removed the events after a target.
560    Rewind,
561    /// An edit replaced or removed events.
562    Edit,
563}
564
565impl HistoryOperation {
566    /// The audit action name: `session.fork`, `session.rewind`, or `session.edit`.
567    pub fn action(self) -> &'static str {
568        match self {
569            Self::Fork => "session.fork",
570            Self::Rewind => "session.rewind",
571            Self::Edit => "session.edit",
572        }
573    }
574}
575
576/// What a fork, rewind, or edit changed, for the audit log.
577///
578/// It names events by ID and carries a digest of the removed and replaced events, never their
579/// content, so a record of a redaction does not repeat what was redacted.
580#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
581#[serde(rename_all = "camelCase")]
582#[non_exhaustive]
583pub struct HistoryChange {
584    /// The operation.
585    pub operation: HistoryOperation,
586    /// The session the operation wrote: the rewritten session, or the new fork.
587    pub session_id: String,
588    /// The source's [`version`](SessionHistory::version) before the operation.
589    pub version_before: String,
590    /// The written session's version afterwards.
591    pub version_after: String,
592    /// The removed events.
593    #[serde(default, skip_serializing_if = "Vec::is_empty")]
594    pub removed: Vec<String>,
595    /// The replaced events.
596    #[serde(default, skip_serializing_if = "Vec::is_empty")]
597    pub replaced: Vec<String>,
598    /// Digest of the removed and replaced events as they were before the operation.
599    #[serde(default, skip_serializing_if = "Option::is_none")]
600    pub changed_digest: Option<String>,
601    /// How many events the written session holds afterwards.
602    pub events_after: usize,
603    /// For a fork, where it came from.
604    #[serde(default, skip_serializing_if = "Option::is_none")]
605    pub fork_origin: Option<ForkOrigin>,
606}
607
608/// A session after a history operation, with what the operation changed.
609#[non_exhaustive]
610pub struct HistoryOutcome {
611    /// The session as it is afterwards: the rewritten session, or the new fork.
612    pub session: Box<dyn Session>,
613    /// What changed.
614    pub change: HistoryChange,
615}
616
617impl HistoryOutcome {
618    /// Pairs a session with the change that produced it.
619    pub fn new(session: Box<dyn Session>, change: HistoryChange) -> Self {
620        Self { session, change }
621    }
622}
623
624impl std::fmt::Debug for HistoryOutcome {
625    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
626        f.debug_struct("HistoryOutcome")
627            .field("session_id", &self.session.id())
628            .field("change", &self.change)
629            .finish()
630    }
631}
632
633/// The version digest of `events`.
634pub(crate) fn history_version(events: &[Event]) -> String {
635    let entries: Vec<&Event> = events.iter().collect();
636    events_digest(&entries)
637}
638
639fn events_digest(events: &[&Event]) -> String {
640    let value = serde_json::to_value(events).unwrap_or(Value::Null);
641    adk_core::json_digest(&value)
642}
643
644fn history_error(category: ErrorCategory, code: &'static str, message: String) -> AdkError {
645    AdkError::new(ErrorComponent::Session, category, code, message)
646}
647
648fn event_not_found(identity: &AdkIdentity, event_id: &str) -> AdkError {
649    crate::service::rewind_event_not_found(identity, event_id)
650}
651
652/// Fails while `events` hold a call for a decision.
653fn refuse_held_calls(identity: &AdkIdentity, events: &[Event], verb: &str) -> Result<()> {
654    if adk_core::held_call_compaction_limit(events, events.len()) < events.len() {
655        return Err(history_error(
656            ErrorCategory::Conflict,
657            "session.history.held_call",
658            format!(
659                "session '{}' holds a tool call waiting for a decision, so its history cannot be \
660                 {verb}; approve or reject the call first, or fork at an event before it",
661                identity.session_id
662            ),
663        ));
664    }
665    Ok(())
666}
667
668/// The IDs of the function calls and the function responses in `events`.
669fn call_and_response_ids(events: &[Event]) -> (HashSet<&str>, HashSet<&str>) {
670    let mut calls = HashSet::new();
671    let mut responses = HashSet::new();
672    for part in events
673        .iter()
674        .filter_map(|event| event.llm_response.content.as_ref())
675        .flat_map(|content| content.parts.iter())
676    {
677        match part {
678            Part::FunctionCall { id: Some(id), .. } => {
679                calls.insert(id.as_str());
680            }
681            Part::FunctionResponse { id: Some(id), .. } => {
682                responses.insert(id.as_str());
683            }
684            _ => {}
685        }
686    }
687    (calls, responses)
688}
689
690/// Fails when `after` keeps a tool call or response whose partner `before` held and `after`
691/// lost.
692fn refuse_split_tool_calls(
693    identity: &AdkIdentity,
694    before: &[Event],
695    after: &[Event],
696) -> Result<()> {
697    let (calls_before, responses_before) = call_and_response_ids(before);
698    let (calls_after, responses_after) = call_and_response_ids(after);
699    let mut split: Vec<&str> = calls_before
700        .intersection(&responses_before)
701        .filter(|id| calls_after.contains(*id) != responses_after.contains(*id))
702        .copied()
703        .collect();
704    if split.is_empty() {
705        return Ok(());
706    }
707    split.sort_unstable();
708    Err(history_error(
709        ErrorCategory::InvalidInput,
710        "session.history.splits_tool_call",
711        format!(
712            "the change to session '{}' would keep tool call {} without its response or the \
713             response without its call; keep or remove both events, or choose an event before \
714             the call",
715            identity.session_id,
716            split.join(", ")
717        ),
718    ))
719}
720
721#[cfg(test)]
722mod tests {
723    use super::*;
724    use adk_core::{Content, FunctionResponseData};
725    use serde_json::json;
726
727    fn identity() -> AdkIdentity {
728        AdkIdentity::new(
729            "app".try_into().unwrap(),
730            "alice".try_into().unwrap(),
731            "s1".try_into().unwrap(),
732        )
733    }
734
735    fn event(id: &str, delta: &[(&str, Value)]) -> Event {
736        let mut event = Event::new("inv");
737        event.id = id.to_string();
738        event.actions.state_delta =
739            delta.iter().map(|(key, value)| (key.to_string(), value.clone())).collect();
740        event
741    }
742
743    fn call(id: &str, call_id: &str) -> Event {
744        let mut event = event(id, &[]);
745        event.llm_response.content = Some(Content {
746            role: "model".into(),
747            parts: vec![Part::FunctionCall {
748                name: "lookup".into(),
749                args: json!({}),
750                id: Some(call_id.into()),
751                thought_signature: None,
752            }],
753        });
754        event
755    }
756
757    fn response(id: &str, call_id: &str) -> Event {
758        let mut event = event(id, &[]);
759        event.llm_response.content = Some(Content {
760            role: "function".into(),
761            parts: vec![Part::FunctionResponse {
762                function_response: FunctionResponseData::new("lookup", json!({"ok": true})),
763                id: Some(call_id.into()),
764                annotations: None,
765            }],
766        });
767        event
768    }
769
770    fn ids(events: &[Event]) -> Vec<&str> {
771        events.iter().map(|event| event.id.as_str()).collect()
772    }
773
774    #[test]
775    fn rebuilds_state_from_the_recorded_creation_state() {
776        let history = SessionHistory::new(
777            vec![
778                event("e1", &[("step", json!(1)), ("app:hits", json!(1))]),
779                event("e2", &[("step", json!(2)), ("tier", json!("silver"))]),
780            ],
781            HashMap::from([("step".into(), json!(2)), ("tier".into(), json!("silver"))]),
782            Some(HashMap::from([("tier".into(), json!("gold"))])),
783        );
784        let rewound =
785            history.rewrite(&identity(), &HistoryRewrite::RewindSteps { steps: 1 }, None).unwrap();
786        assert_eq!(
787            rewound.state,
788            HashMap::from([("step".into(), json!(1)), ("tier".into(), json!("gold"))])
789        );
790        assert_eq!(rewound.change.removed, ["e2"]);
791    }
792
793    #[test]
794    fn a_session_without_a_recorded_creation_state_keeps_keys_no_event_wrote() {
795        let history = SessionHistory::new(
796            vec![event("e1", &[("step", json!(1))])],
797            HashMap::from([("step".into(), json!(1)), ("owner".into(), json!("alice"))]),
798            None,
799        );
800        assert_eq!(history.creation_state(), HashMap::from([("owner".into(), json!("alice"))]));
801    }
802
803    #[test]
804    fn a_backend_without_shared_tiers_keeps_app_and_user_keys_in_the_session() {
805        let history = SessionHistory::without_shared_tiers(
806            vec![event("e1", &[("app:hits", json!(1)), ("temp:x", json!(1))])],
807            HashMap::new(),
808            Some(HashMap::new()),
809        );
810        assert_eq!(
811            history.state_after(&history.events),
812            HashMap::from([("app:hits".into(), json!(1))])
813        );
814    }
815
816    #[test]
817    fn edits_replace_in_place_and_remove() {
818        let history = SessionHistory::new(
819            vec![event("e1", &[]), event("e2", &[("draft", json!("v1"))]), event("e3", &[])],
820            HashMap::new(),
821            Some(HashMap::new()),
822        );
823        let mut replacement = event("e2", &[("draft", json!("v2")), ("temp:scratch", json!(1))]);
824        replacement.timestamp = Utc::now() + chrono::Duration::days(1);
825        let edited = history
826            .rewrite(
827                &identity(),
828                &HistoryRewrite::Edit {
829                    edits: vec![
830                        HistoryEdit::Replace { event: Box::new(replacement) },
831                        HistoryEdit::Remove { event_id: "e3".into() },
832                    ],
833                },
834                None,
835            )
836            .unwrap();
837        assert_eq!(ids(&edited.events), ["e1", "e2"]);
838        assert_eq!(edited.events[1].timestamp, history.events[1].timestamp);
839        assert_eq!(edited.state, HashMap::from([("draft".into(), json!("v2"))]));
840        assert_eq!(
841            (edited.change.replaced.as_slice(), edited.change.removed.as_slice()),
842            (&["e2".to_string()][..], &["e3".to_string()][..])
843        );
844        assert!(edited.change.changed_digest.is_some());
845    }
846
847    #[test]
848    fn a_stale_version_is_refused() {
849        let history = SessionHistory::new(vec![event("e1", &[])], HashMap::new(), None);
850        let error = history
851            .rewrite(&identity(), &HistoryRewrite::RewindSteps { steps: 1 }, Some("stale"))
852            .unwrap_err();
853        assert_eq!(
854            (error.category, error.code),
855            (ErrorCategory::Conflict, "session.history.version_mismatch")
856        );
857        let version = history.version();
858        assert!(
859            history
860                .rewrite(&identity(), &HistoryRewrite::RewindSteps { steps: 1 }, Some(&version))
861                .is_ok()
862        );
863    }
864
865    #[test]
866    fn tool_calls_stay_with_their_responses() {
867        let history = SessionHistory::new(
868            vec![
869                event("ask", &[]),
870                call("call", "c1"),
871                response("result", "c1"),
872                event("reply", &[]),
873            ],
874            HashMap::new(),
875            None,
876        );
877        for rewrite in [
878            HistoryRewrite::RewindTo { event_id: "call".into() },
879            HistoryRewrite::Edit { edits: vec![HistoryEdit::Remove { event_id: "call".into() }] },
880            HistoryRewrite::Edit { edits: vec![HistoryEdit::Remove { event_id: "result".into() }] },
881        ] {
882            let error = history.rewrite(&identity(), &rewrite, None).unwrap_err();
883            assert_eq!(error.code, "session.history.splits_tool_call", "{rewrite:?}");
884        }
885        let both = history
886            .rewrite(
887                &identity(),
888                &HistoryRewrite::Edit {
889                    edits: vec![
890                        HistoryEdit::Remove { event_id: "call".into() },
891                        HistoryEdit::Remove { event_id: "result".into() },
892                    ],
893                },
894                None,
895            )
896            .unwrap();
897        assert_eq!(ids(&both.events), ["ask", "reply"]);
898        let error = history.fork(&ForkRequest::new(identity()).at_event("call")).unwrap_err();
899        assert_eq!(error.code, "session.history.splits_tool_call");
900    }
901
902    #[test]
903    fn a_held_call_blocks_rewrites_and_forks_that_copy_it() {
904        let mut hold = call("hold", "c9");
905        hold.actions.tool_confirmation = Some(adk_core::ToolConfirmationRequest {
906            tool_name: "lookup".into(),
907            function_call_id: Some("c9".into()),
908            args: json!({}),
909            acting: None,
910            origin: None,
911            evidence: Vec::new(),
912        });
913        let history = SessionHistory::new(vec![event("ask", &[]), hold], HashMap::new(), None);
914        let error = history
915            .rewrite(&identity(), &HistoryRewrite::RewindSteps { steps: 1 }, None)
916            .unwrap_err();
917        assert_eq!(
918            (error.category, error.code),
919            (ErrorCategory::Conflict, "session.history.held_call")
920        );
921        assert_eq!(
922            history.fork(&ForkRequest::new(identity())).unwrap_err().code,
923            "session.history.held_call"
924        );
925        let (import, _) = history.fork(&ForkRequest::new(identity()).at_event("ask")).unwrap();
926        assert_eq!(ids(&import.events), ["ask"]);
927    }
928
929    #[test]
930    fn a_fork_records_its_origin_in_both_states() {
931        let history = SessionHistory::new(
932            vec![event("e1", &[("step", json!(1))]), event("e2", &[("step", json!(2))])],
933            HashMap::from([("step".into(), json!(2))]),
934            Some(HashMap::from([("owner".into(), json!("alice"))])),
935        );
936        let (import, change) = history
937            .fork(&ForkRequest::new(identity()).at_event("e1").with_session_id("fork-1"))
938            .unwrap();
939        assert_eq!(import.identity.session_id.as_ref(), "fork-1");
940        assert_eq!(ids(&import.events), ["e1"]);
941        let origin: ForkOrigin =
942            serde_json::from_value(import.state[FORK_ORIGIN_KEY].clone()).unwrap();
943        assert_eq!((origin.session_id.as_str(), origin.event_id.as_deref()), ("s1", Some("e1")));
944        assert_eq!(import.initial_state[FORK_ORIGIN_KEY], import.state[FORK_ORIGIN_KEY]);
945        assert_eq!(
946            (import.state.get("step"), import.state.get("owner")),
947            (Some(&json!(1)), Some(&json!("alice")))
948        );
949        assert_eq!(change.fork_origin, Some(origin));
950    }
951
952    #[test]
953    fn duplicated_event_ids_cannot_be_addressed() {
954        let history =
955            SessionHistory::new(vec![event("e1", &[]), event("e1", &[])], HashMap::new(), None);
956        let error = history
957            .rewrite(&identity(), &HistoryRewrite::RewindTo { event_id: "e1".into() }, None)
958            .unwrap_err();
959        assert_eq!(error.code, "session.history.ambiguous_event");
960    }
961}