Skip to main content

adk_runner/
history.rs

1//! Forking, rewinding, and editing session history under the runtime's rules.
2//!
3//! [`HistoryControl`] wraps the [`SessionService`] history operations with what the store
4//! cannot know:
5//!
6//! | Rule | Error |
7//! |------|-------|
8//! | No history operation runs on a session while a turn runs on it: a run of any runner sharing the [`SessionActivity`], or a run a durable run store records as running | `session.history.run_active` (`Conflict`) |
9//! | Each operation is recorded in the audit log before it is applied, and its outcome after; a decision record that cannot be written refuses the operation under [`AuditFailureMode::Block`](adk_core::audit_log::AuditFailureMode::Block) | `audit.record_failed` |
10//!
11//! The store's own rules hold underneath: a held call blocks rewinds and edits, and no result
12//! separates a tool call from its response (see [`adk_session::history`]). History operations
13//! run no agent, tool, or model, so the kill switch does not stop them: rewinding a session past
14//! a bad turn is part of what a freeze is for.
15
16use std::collections::HashMap;
17use std::sync::{Arc, Mutex};
18
19use adk_core::audit_log::{
20    AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditRecordOutcome, AuditTrail,
21};
22use adk_core::identity::AdkIdentity;
23use adk_core::{
24    AdkError, DurableRunStore, ErrorCategory, ErrorComponent, Result, RunFilter, RunState,
25};
26use adk_session::{
27    ForkRequest, HistoryChange, HistoryEdit, HistoryOutcome, HistoryRewrite, RewriteHistoryRequest,
28    SessionHistory, SessionService,
29};
30use serde_json::{Value, json};
31
32/// The sessions with a turn in flight, shared by every runner that holds a clone.
33///
34/// A [`Runner`](crate::Runner) registers each run here for as long as its event stream lives.
35/// A host that builds one runner per request, such as `adk-server`, gives every runner the same
36/// registry, so a [`HistoryControl`] sees the runs of all of them.
37///
38/// # Example
39///
40/// ```rust
41/// use adk_core::identity::AdkIdentity;
42/// use adk_runner::SessionActivity;
43///
44/// let activity = SessionActivity::new();
45/// let identity = AdkIdentity::new(
46///     "app".try_into().unwrap(),
47///     "alice".try_into().unwrap(),
48///     "s1".try_into().unwrap(),
49/// );
50/// let guard = activity.enter(identity.clone());
51/// assert!(activity.is_active(&identity));
52/// drop(guard);
53/// assert!(!activity.is_active(&identity));
54/// ```
55#[derive(Clone, Default)]
56pub struct SessionActivity {
57    runs: Arc<Mutex<HashMap<AdkIdentity, usize>>>,
58}
59
60impl std::fmt::Debug for SessionActivity {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        let runs = self.runs.lock().unwrap_or_else(|e| e.into_inner());
63        f.debug_struct("SessionActivity").field("active_sessions", &runs.len()).finish()
64    }
65}
66
67impl SessionActivity {
68    /// An empty registry.
69    pub fn new() -> Self {
70        Self::default()
71    }
72
73    /// Records a turn on `identity` until the returned guard drops.
74    pub fn enter(&self, identity: AdkIdentity) -> ActivityGuard {
75        *self
76            .runs
77            .lock()
78            .unwrap_or_else(|e| e.into_inner())
79            .entry(identity.clone())
80            .or_default() += 1;
81        ActivityGuard { runs: self.runs.clone(), identity }
82    }
83
84    /// Whether a turn runs on `identity`.
85    pub fn is_active(&self, identity: &AdkIdentity) -> bool {
86        self.runs.lock().unwrap_or_else(|e| e.into_inner()).contains_key(identity)
87    }
88}
89
90/// A turn recorded in a [`SessionActivity`]; dropping it ends the record.
91#[must_use = "the turn is recorded only while the guard lives"]
92pub struct ActivityGuard {
93    runs: Arc<Mutex<HashMap<AdkIdentity, usize>>>,
94    identity: AdkIdentity,
95}
96
97impl std::fmt::Debug for ActivityGuard {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        f.debug_struct("ActivityGuard").field("session_id", &self.identity.session_id).finish()
100    }
101}
102
103impl Drop for ActivityGuard {
104    fn drop(&mut self) {
105        let mut runs = self.runs.lock().unwrap_or_else(|e| e.into_inner());
106        if let Some(count) = runs.get_mut(&self.identity) {
107            *count -= 1;
108            if *count == 0 {
109                runs.remove(&self.identity);
110            }
111        }
112    }
113}
114
115/// Where a rewind stops.
116#[derive(Debug, Clone, PartialEq, Eq)]
117#[non_exhaustive]
118pub enum RewindTarget {
119    /// Keep the events up to and including this one.
120    Event(String),
121    /// Remove this many events from the end.
122    Steps(usize),
123    /// Remove the invocation with this ID and every event after it: the turn it ran is undone.
124    BeforeInvocation(String),
125}
126
127/// Session fork, rewind, and edit under the runtime's rules: refused while a turn runs on the
128/// session, and recorded in the audit log.
129///
130/// Get one from [`Runner::history_control`](crate::Runner::history_control), or build one over
131/// a session service for a host without a runner.
132///
133/// # Example
134///
135/// ```rust
136/// use std::sync::Arc;
137/// use adk_core::audit_log::AuditActor;
138/// use adk_core::principal::SubjectRef;
139/// use adk_runner::{HistoryControl, RewindTarget, SessionActivity};
140/// use adk_session::{CreateRequest, ForkRequest, InMemorySessionService, SessionService};
141///
142/// # #[tokio::main(flavor = "current_thread")]
143/// # async fn main() -> adk_core::Result<()> {
144/// let sessions = Arc::new(InMemorySessionService::new());
145/// let session = sessions
146///     .create(CreateRequest {
147///         app_name: "app".into(),
148///         user_id: "alice".into(),
149///         session_id: Some("main".into()),
150///         state: Default::default(),
151///     })
152///     .await?;
153/// let control = HistoryControl::new(sessions).with_activity(SessionActivity::new());
154/// let actor = AuditActor::subject(SubjectRef::human("alice"));
155/// let fork = control.fork(&actor, ForkRequest::new(session.try_identity()?)).await?;
156/// let rewound = control
157///     .rewind(&actor, &fork.session.try_identity()?, RewindTarget::Steps(0), None)
158///     .await?;
159/// assert_eq!(rewound.session.events().len(), 0);
160/// # Ok(())
161/// # }
162/// ```
163#[derive(Clone)]
164pub struct HistoryControl {
165    sessions: Arc<dyn SessionService>,
166    activity: SessionActivity,
167    audit: Option<AuditTrail>,
168    run_store: Option<Arc<dyn DurableRunStore>>,
169}
170
171impl std::fmt::Debug for HistoryControl {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        f.debug_struct("HistoryControl")
174            .field("activity", &self.activity)
175            .field("audit", &self.audit.is_some())
176            .field("run_store", &self.run_store.is_some())
177            .finish()
178    }
179}
180
181impl HistoryControl {
182    /// History operations on `sessions`, with an empty activity registry and no audit log.
183    pub fn new(sessions: Arc<dyn SessionService>) -> Self {
184        Self { sessions, activity: SessionActivity::new(), audit: None, run_store: None }
185    }
186
187    /// Refuses operations on sessions with a turn recorded in `activity`.
188    #[must_use]
189    pub fn with_activity(mut self, activity: SessionActivity) -> Self {
190        self.activity = activity;
191        self
192    }
193
194    /// Records every operation in `audit`.
195    #[must_use]
196    pub fn with_audit(mut self, audit: AuditTrail) -> Self {
197        self.audit = Some(audit);
198        self
199    }
200
201    /// Also refuses operations on sessions a durable run in `store` is running on, whichever
202    /// process runs it.
203    #[must_use]
204    pub fn with_run_store(mut self, store: Arc<dyn DurableRunStore>) -> Self {
205        self.run_store = Some(store);
206        self
207    }
208
209    /// The session's history and its version.
210    ///
211    /// # Errors
212    ///
213    /// Returns `session.not_found` or a backend error.
214    pub async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
215        self.sessions.history(identity).await
216    }
217
218    /// Forks a session; see [`SessionService::fork`].
219    ///
220    /// # Errors
221    ///
222    /// Returns `session.history.run_active` while a turn runs on the source, `audit.record_failed`
223    /// when the decision cannot be recorded, and the errors of [`SessionService::fork`].
224    pub async fn fork(&self, actor: &AuditActor, mut req: ForkRequest) -> Result<HistoryOutcome> {
225        self.refuse_running(&req.source).await?;
226        // A generated ID is chosen once, so the recorded plan and the fork name the same
227        // session.
228        req.session_id.get_or_insert_with(|| uuid::Uuid::new_v4().to_string());
229        let (_, planned) = self.sessions.history(&req.source).await?.fork(&req)?;
230        let args = json!({
231            "source": req.source.session_id.as_ref(),
232            "atEventId": req.at_event_id,
233            "sessionId": req.session_id,
234        });
235        self.decide(actor, &req.source, &planned, &args).await?;
236        let outcome = self.sessions.fork(req.clone()).await;
237        self.record_outcome(actor, &req.source, &planned, &args, &outcome).await;
238        outcome
239    }
240
241    /// Rewinds a session to `target`; see [`SessionService::rewrite_history`].
242    ///
243    /// # Errors
244    ///
245    /// Returns `session.history.run_active` while a turn runs on the session,
246    /// `session.invocation_not_found` for a [`RewindTarget::BeforeInvocation`] the session does
247    /// not hold, `audit.record_failed` when the decision cannot be recorded, and the errors of
248    /// [`SessionService::rewrite_history`].
249    pub async fn rewind(
250        &self,
251        actor: &AuditActor,
252        identity: &AdkIdentity,
253        target: RewindTarget,
254        expected_version: Option<String>,
255    ) -> Result<HistoryOutcome> {
256        self.refuse_running(identity).await?;
257        let history = self.sessions.history(identity).await?;
258        let rewrite = match &target {
259            RewindTarget::Event(event_id) => {
260                HistoryRewrite::RewindTo { event_id: event_id.clone() }
261            }
262            RewindTarget::Steps(steps) => HistoryRewrite::RewindSteps { steps: *steps },
263            RewindTarget::BeforeInvocation(invocation_id) => {
264                let first = history
265                    .events
266                    .iter()
267                    .position(|event| &event.invocation_id == invocation_id)
268                    .ok_or_else(|| {
269                        AdkError::not_found(
270                            ErrorComponent::Session,
271                            "session.invocation_not_found",
272                            format!(
273                                "invocation '{invocation_id}' has no events in session '{}'",
274                                identity.session_id
275                            ),
276                        )
277                    })?;
278                match first.checked_sub(1) {
279                    Some(last) => {
280                        HistoryRewrite::RewindTo { event_id: history.events[last].id.clone() }
281                    }
282                    None => HistoryRewrite::RewindSteps { steps: history.events.len() },
283                }
284            }
285        };
286        let args = match &target {
287            RewindTarget::Event(event_id) => json!({ "eventId": event_id }),
288            RewindTarget::Steps(steps) => json!({ "steps": steps }),
289            RewindTarget::BeforeInvocation(id) => json!({ "beforeInvocationId": id }),
290        };
291        self.rewrite(actor, identity, history, rewrite, expected_version, args).await
292    }
293
294    /// Replaces or removes events of a session; see [`HistoryEdit`].
295    ///
296    /// # Errors
297    ///
298    /// Returns `session.history.run_active` while a turn runs on the session,
299    /// `audit.record_failed` when the decision cannot be recorded, and the errors of
300    /// [`SessionService::rewrite_history`].
301    pub async fn edit(
302        &self,
303        actor: &AuditActor,
304        identity: &AdkIdentity,
305        edits: Vec<HistoryEdit>,
306        expected_version: Option<String>,
307    ) -> Result<HistoryOutcome> {
308        self.refuse_running(identity).await?;
309        let history = self.sessions.history(identity).await?;
310        let args = json!({
311            "replace": edits.iter().filter_map(|edit| match edit {
312                HistoryEdit::Replace { event } => Some(event.id.clone()),
313                _ => None,
314            }).collect::<Vec<_>>(),
315            "remove": edits.iter().filter_map(|edit| match edit {
316                HistoryEdit::Remove { event_id } => Some(event_id.clone()),
317                _ => None,
318            }).collect::<Vec<_>>(),
319        });
320        let rewrite = HistoryRewrite::Edit { edits };
321        self.rewrite(actor, identity, history, rewrite, expected_version, args).await
322    }
323
324    /// Plans `rewrite` against `history` and applies it only to that history.
325    async fn rewrite(
326        &self,
327        actor: &AuditActor,
328        identity: &AdkIdentity,
329        history: SessionHistory,
330        rewrite: HistoryRewrite,
331        expected_version: Option<String>,
332        args: Value,
333    ) -> Result<HistoryOutcome> {
334        let planned = history.rewrite(identity, &rewrite, expected_version.as_deref())?.change;
335        self.decide(actor, identity, &planned, &args).await?;
336        // The planned history is the one the decision names, so the write applies to it alone.
337        let request =
338            RewriteHistoryRequest::new(identity.clone(), rewrite).expect_version(history.version());
339        let outcome = self.sessions.rewrite_history(request).await;
340        self.record_outcome(actor, identity, &planned, &args, &outcome).await;
341        outcome
342    }
343
344    async fn refuse_running(&self, identity: &AdkIdentity) -> Result<()> {
345        let mut running = self.activity.is_active(identity);
346        if !running && let Some(store) = &self.run_store {
347            let filter = RunFilter::default()
348                .app_name(identity.app_name.as_ref())
349                .user_id(identity.user_id.as_ref())
350                .session_id(identity.session_id.as_ref())
351                .states([RunState::Running]);
352            running = !store.list(filter).await?.is_empty();
353        }
354        if running {
355            return Err(AdkError::new(
356                ErrorComponent::Session,
357                ErrorCategory::Conflict,
358                "session.history.run_active",
359                format!(
360                    "a turn is running on session '{}'; wait for it to finish, or interrupt it, \
361                     before forking, rewinding, or editing the session",
362                    identity.session_id
363                ),
364            ));
365        }
366        Ok(())
367    }
368
369    fn draft(
370        &self,
371        actor: &AuditActor,
372        identity: &AdkIdentity,
373        change: &HistoryChange,
374        args: &Value,
375        trail: &AuditTrail,
376    ) -> AuditRecordDraft {
377        let mut draft =
378            AuditRecordDraft::new(AuditRecordKind::SessionHistory, change.operation.action())
379                .actor(actor.clone())
380                .args_digest(trail.digest(args))
381                .decision(AuditDecision::Allowed)
382                .ext("app", json!(identity.app_name.as_ref()))
383                .ext("user", json!(identity.user_id.as_ref()))
384                .ext("session", json!(identity.session_id.as_ref()))
385                .ext("versionBefore", json!(change.version_before))
386                .ext("eventsAfter", json!(change.events_after));
387        if change.session_id != identity.session_id.as_ref() {
388            draft = draft.ext("fork", json!(change.session_id));
389        }
390        if !change.removed.is_empty() {
391            draft = draft.ext("removed", json!(change.removed));
392        }
393        if !change.replaced.is_empty() {
394            draft = draft.ext("replaced", json!(change.replaced));
395        }
396        if let Some(digest) = &change.changed_digest {
397            draft = draft.payload_ref(digest.clone());
398        }
399        draft
400    }
401
402    /// Records the decision to apply `change`; a refused record refuses the operation.
403    async fn decide(
404        &self,
405        actor: &AuditActor,
406        identity: &AdkIdentity,
407        change: &HistoryChange,
408        args: &Value,
409    ) -> Result<()> {
410        let Some(trail) = &self.audit else { return Ok(()) };
411        trail.record(self.draft(actor, identity, change, args, trail)).await
412    }
413
414    /// Records what happened; the change is already applied, so a failed record is logged.
415    async fn record_outcome(
416        &self,
417        actor: &AuditActor,
418        identity: &AdkIdentity,
419        planned: &HistoryChange,
420        args: &Value,
421        outcome: &Result<HistoryOutcome>,
422    ) {
423        let Some(trail) = &self.audit else { return };
424        let draft = match outcome {
425            Ok(done) => self
426                .draft(actor, identity, &done.change, args, trail)
427                .outcome(AuditRecordOutcome::Succeeded)
428                .ext("versionAfter", json!(done.change.version_after)),
429            Err(error) => self
430                .draft(actor, identity, planned, args, trail)
431                .outcome(AuditRecordOutcome::Failed)
432                .ext("error", json!(error.code)),
433        };
434        if let Err(error) = trail.recorder().record(draft).await {
435            tracing::error!(
436                session.id = %identity.session_id,
437                error = %error,
438                "history operation applied but its outcome record failed"
439            );
440        }
441    }
442}