Skip to main content

bamboo_engine/
session_repository.rs

1//! Canonical session coordinator owned by the framework.
2//!
3//! [`SessionRepository`] bundles the three tiers a Bamboo session lives in — the
4//! in-memory [`SessionCache`], the durable [`Storage`], and the
5//! merge-on-write [`LockedSessionStore`] — and provides the one canonical
6//! load/save coordination (cache → storage → backfill, and dual-write).
7//!
8//! This is a *framework* capability, not a server one: previously the
9//! coordination lived only as inherent methods on the server's `AppState`,
10//! which meant anything outside the HTTP server (the SDK, in-process embedders)
11//! could not load or persist sessions consistently. `SessionRepository` lets any
12//! caller that holds the three tiers share the exact same behaviour; the
13//! server's `AppState` now delegates to it.
14
15use std::sync::Arc;
16
17use bamboo_agent_core::storage::Storage;
18use bamboo_agent_core::Session;
19use bamboo_storage::LockedSessionStore;
20
21use crate::{read_cached_session, SessionCache};
22
23/// Framework-owned coordinator over a session's cache / storage / persistence
24/// tiers. Cheap to clone (all fields are `Arc`).
25#[derive(Clone)]
26pub struct SessionRepository {
27    cache: SessionCache,
28    storage: Arc<dyn Storage>,
29    persistence: Arc<LockedSessionStore>,
30}
31
32impl SessionRepository {
33    pub fn new(
34        cache: SessionCache,
35        storage: Arc<dyn Storage>,
36        persistence: Arc<LockedSessionStore>,
37    ) -> Self {
38        Self {
39            cache,
40            storage,
41            persistence,
42        }
43    }
44
45    pub fn cache(&self) -> &SessionCache {
46        &self.cache
47    }
48
49    pub fn storage(&self) -> &Arc<dyn Storage> {
50        &self.storage
51    }
52
53    pub fn persistence(&self) -> &Arc<LockedSessionStore> {
54        &self.persistence
55    }
56
57    /// Load a session from the memory cache, falling back to durable storage
58    /// (and back-filling the cache on a storage hit). `None` if absent in both.
59    pub async fn load(&self, session_id: &str) -> Option<Session> {
60        if let Some(session) = read_cached_session(&self.cache, session_id) {
61            return Some(session);
62        }
63
64        match self.storage.load_session(session_id).await {
65            Ok(Some(session)) => {
66                self.cache.insert(
67                    session_id.to_string(),
68                    Arc::new(parking_lot::RwLock::new(session.clone())),
69                );
70                Some(session)
71            }
72            _ => None,
73        }
74    }
75
76    /// Like [`load`](Self::load), but surfaces storage errors instead of
77    /// swallowing them to `None`. Cache hit short-circuits; a storage hit
78    /// back-fills the cache.
79    pub async fn try_load(&self, session_id: &str) -> std::io::Result<Option<Session>> {
80        if let Some(session) = read_cached_session(&self.cache, session_id) {
81            return Ok(Some(session));
82        }
83        let loaded = self.storage.load_session(session_id).await?;
84        if let Some(ref session) = loaded {
85            self.cache.insert(
86                session_id.to_string(),
87                Arc::new(parking_lot::RwLock::new(session.clone())),
88            );
89        }
90        Ok(loaded)
91    }
92
93    /// Persist the session (merge-on-write) and refresh the cache, surfacing
94    /// storage errors. Use [`save_and_cache`](Self::save_and_cache) for the
95    /// fire-and-forget variant that logs and continues on failure.
96    pub async fn save(&self, session: &mut Session) -> std::io::Result<()> {
97        self.persistence.merge_save_runtime(session).await?;
98        self.cache.insert(
99            session.id.clone(),
100            Arc::new(parking_lot::RwLock::new(session.clone())),
101        );
102        Ok(())
103    }
104
105    /// Atomically mutate the latest durable runtime session and refresh the
106    /// cache with the saved value. This is the safe path for narrow metadata
107    /// indexes that can be updated concurrently with runner message writes.
108    pub async fn update_runtime_session<F>(
109        &self,
110        session_id: &str,
111        metadata_keys: &[&str],
112        mutate: F,
113    ) -> std::io::Result<Option<Session>>
114    where
115        F: FnOnce(&mut Session),
116    {
117        let saved = self
118            .persistence
119            .update_runtime_config(session_id, mutate)
120            .await?;
121        if let (Some(saved), Some(cached)) = (saved.as_ref(), self.cache.get(session_id)) {
122            let mut cached = cached.write();
123            for key in metadata_keys {
124                if let Some(value) = saved.metadata.get(*key) {
125                    cached.metadata.insert((*key).to_string(), value.clone());
126                } else {
127                    cached.metadata.remove(*key);
128                }
129            }
130        }
131        Ok(saved)
132    }
133
134    /// Load a session, creating a fresh `Session::new(id, model)` if absent.
135    pub async fn load_or_create(&self, session_id: &str, model: &str) -> Session {
136        if let Some(session) = self.load(session_id).await {
137            return session;
138        }
139        Session::new(session_id.to_string(), model.to_string())
140    }
141
142    /// Load a session, reconciling the memory and storage copies via a
143    /// preference heuristic: storage wins when it is strictly newer, or when it
144    /// is the same age but still carries a pending question memory lost. Storage
145    /// is **never** preferred when it is strictly older than memory.
146    ///
147    /// The cache is refreshed cache-aside but with a no-regression guarantee:
148    /// `load_merged` never overwrites a newer cached session with an older
149    /// storage copy, so it is safe to call from hot read paths.
150    pub async fn load_merged(&self, session_id: &str) -> Option<Session> {
151        let memory_session = read_cached_session(&self.cache, session_id);
152        let storage_session = self
153            .storage
154            .load_session(session_id)
155            .await
156            .unwrap_or_default();
157
158        match (memory_session, storage_session) {
159            (Some(memory), Some(storage)) => {
160                let prefer_storage = should_prefer_storage(&memory, &storage);
161                let diverged = prefer_storage || memory.messages.len() != storage.messages.len();
162                let chosen_len = if prefer_storage {
163                    storage.messages.len()
164                } else {
165                    memory.messages.len()
166                };
167                macro_rules! merged_log {
168                    ($level:ident) => {
169                        tracing::$level!(
170                            "[{}] load_session_merged: memory={} msgs (updated_at={}), storage={} msgs (updated_at={}), prefer_storage={} -> chose {} msgs",
171                            session_id,
172                            memory.messages.len(),
173                            memory.updated_at,
174                            storage.messages.len(),
175                            storage.updated_at,
176                            prefer_storage,
177                            chosen_len,
178                        )
179                    };
180                }
181                if diverged {
182                    merged_log!(debug);
183                } else {
184                    merged_log!(trace);
185                }
186                let memory_updated_at = memory.updated_at;
187                let chosen = if prefer_storage { storage } else { memory };
188                // Cache-aside refresh with a hard no-regression invariant: only
189                // write back when we actually reconciled *to storage* (a memory
190                // win is already the cached copy; re-inserting it would needlessly
191                // replace a possibly-live Arc) AND the reconciled copy is not
192                // older than what memory already holds. This is what makes
193                // `load_merged` safe on hot read paths — it can never clobber a
194                // freshly-updated session with a stale storage copy.
195                if prefer_storage && chosen.updated_at >= memory_updated_at {
196                    self.cache.insert(
197                        session_id.to_string(),
198                        Arc::new(parking_lot::RwLock::new(chosen.clone())),
199                    );
200                }
201                Some(chosen)
202            }
203            (Some(memory), None) => Some(memory),
204            (None, Some(storage)) => {
205                self.cache.insert(
206                    session_id.to_string(),
207                    Arc::new(parking_lot::RwLock::new(storage.clone())),
208                );
209                Some(storage)
210            }
211            (None, None) => None,
212        }
213    }
214
215    /// Persist the session (merge-on-write, preserving concurrent UI edits to
216    /// the authoritative metadata group) and refresh the in-memory cache.
217    pub async fn save_and_cache(&self, session: &mut Session) {
218        if let Err(error) = self.persistence.merge_save_runtime(session).await {
219            tracing::warn!("[{}] Failed to save session: {}", session.id, error);
220        }
221        self.cache.insert(
222            session.id.clone(),
223            Arc::new(parking_lot::RwLock::new(session.clone())),
224        );
225    }
226}
227
228fn should_prefer_storage(memory_session: &Session, storage_session: &Session) -> bool {
229    // Never reconcile *backwards* to a strictly-older storage copy: if memory is
230    // newer it is authoritative (e.g. it just answered and cleared a pending
231    // question while storage still holds the stale one). Respecting `updated_at`
232    // here is what stops `load_merged` from returning — and caching — stale data.
233    if storage_session.updated_at < memory_session.updated_at {
234        return false;
235    }
236    // Storage is same-age or newer: prefer it when strictly newer, or when it
237    // still carries a pending question that the (same-age) memory copy lost, so
238    // a genuine clarification is never dropped.
239    storage_session.updated_at > memory_session.updated_at
240        || (memory_session.pending_question.is_none() && storage_session.pending_question.is_some())
241}
242
243/// `SessionRepository` is the canonical `RuntimeSessionPersistence`: the runtime
244/// can persist a session through the same coordinator (merge-on-write + cache
245/// refresh) instead of a bespoke adapter.
246#[async_trait::async_trait]
247impl bamboo_domain::RuntimeSessionPersistence for SessionRepository {
248    async fn save_runtime_session(&self, session: &mut Session) -> std::io::Result<()> {
249        // Runtime authorization reads through this same cache. Refresh it even
250        // when durable storage fails so a current activation can never observe
251        // a previous run's skill allowlist. The error is still returned to the
252        // caller and durable state remains unchanged.
253        let result = self.persistence.merge_save_runtime(session).await;
254        self.cache.insert(
255            session.id.clone(),
256            Arc::new(parking_lot::RwLock::new(session.clone())),
257        );
258        result
259    }
260
261    async fn load_runtime_session(&self, session_id: &str) -> std::io::Result<Option<Session>> {
262        self.try_load(session_id).await
263    }
264
265    async fn append_token_usage_record(
266        &self,
267        session_id: &str,
268        json_line: &str,
269    ) -> std::io::Result<()> {
270        self.storage
271            .append_token_usage_record(session_id, json_line)
272            .await
273    }
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279    use bamboo_agent_core::storage::Storage;
280    use chrono::Utc;
281    use std::collections::HashMap;
282    use std::sync::Mutex;
283
284    #[derive(Default)]
285    struct MapStorage {
286        sessions: Mutex<HashMap<String, Session>>,
287    }
288
289    struct FailingSaveStorage {
290        persisted: Mutex<Option<Session>>,
291    }
292
293    #[async_trait::async_trait]
294    impl Storage for MapStorage {
295        async fn save_session(&self, session: &Session) -> std::io::Result<()> {
296            self.sessions
297                .lock()
298                .unwrap()
299                .insert(session.id.clone(), session.clone());
300            Ok(())
301        }
302        async fn load_session(&self, session_id: &str) -> std::io::Result<Option<Session>> {
303            Ok(self.sessions.lock().unwrap().get(session_id).cloned())
304        }
305        async fn delete_session(&self, session_id: &str) -> std::io::Result<bool> {
306            Ok(self.sessions.lock().unwrap().remove(session_id).is_some())
307        }
308    }
309
310    #[async_trait::async_trait]
311    impl Storage for FailingSaveStorage {
312        async fn save_session(&self, _session: &Session) -> std::io::Result<()> {
313            Err(std::io::Error::other("injected save failure"))
314        }
315
316        async fn load_session(&self, _session_id: &str) -> std::io::Result<Option<Session>> {
317            Ok(self.persisted.lock().unwrap().clone())
318        }
319
320        async fn delete_session(&self, _session_id: &str) -> std::io::Result<bool> {
321            Ok(false)
322        }
323    }
324
325    fn test_repo(storage: Arc<dyn Storage>) -> SessionRepository {
326        let cache: SessionCache = Arc::new(dashmap::DashMap::new());
327        let persistence = Arc::new(LockedSessionStore::new(storage.clone()));
328        SessionRepository::new(cache, storage, persistence)
329    }
330
331    fn cache_put(repo: &SessionRepository, session: &Session) {
332        repo.cache().insert(
333            session.id.clone(),
334            Arc::new(parking_lot::RwLock::new(session.clone())),
335        );
336    }
337
338    #[tokio::test]
339    async fn narrow_runtime_metadata_transaction_preserves_live_and_durable_non_owned_state() {
340        let storage: Arc<dyn Storage> = Arc::new(MapStorage::default());
341        let repo = test_repo(storage.clone());
342        let id = "narrow-metadata";
343        let mut durable = Session::new(id, "durable-model");
344        durable.add_message(bamboo_agent_core::Message::user("durable user turn"));
345        durable
346            .metadata
347            .insert("external.durable".to_string(), "keep".to_string());
348        storage.save_session(&durable).await.expect("seed durable");
349
350        let mut live = durable.clone();
351        live.add_message(bamboo_agent_core::Message::assistant(
352            "in-flight assistant tool call",
353            None,
354        ));
355        live.model = "live-model".to_string();
356        live.metadata
357            .insert("external.live".to_string(), "keep".to_string());
358        cache_put(&repo, &live);
359
360        repo.update_runtime_session(id, &["workflow.owned"], |latest| {
361            latest
362                .metadata
363                .insert("workflow.owned".to_string(), "active".to_string());
364        })
365        .await
366        .expect("transaction")
367        .expect("session exists");
368
369        let saved = storage
370            .load_session(id)
371            .await
372            .expect("load durable")
373            .expect("durable exists");
374        assert_eq!(
375            saved.messages.len(),
376            1,
377            "transaction never writes stale live messages"
378        );
379        assert_eq!(
380            saved.metadata.get("external.durable").map(String::as_str),
381            Some("keep")
382        );
383        assert_eq!(
384            saved.metadata.get("workflow.owned").map(String::as_str),
385            Some("active")
386        );
387
388        let cached = read_cached_session(repo.cache(), id).expect("live cache");
389        assert_eq!(
390            cached.messages.len(),
391            2,
392            "cache live tool call is not replaced"
393        );
394        assert_eq!(cached.model, "live-model");
395        assert_eq!(
396            cached.metadata.get("external.live").map(String::as_str),
397            Some("keep")
398        );
399        assert_eq!(
400            cached.metadata.get("workflow.owned").map(String::as_str),
401            Some("active")
402        );
403    }
404
405    /// Regression guard: a strictly-newer in-memory session (e.g. one that just
406    /// answered and cleared its pending question) must win over a strictly-older
407    /// storage copy that still carries the pending question — both in the value
408    /// returned AND in the cache (no clobber).
409    #[tokio::test]
410    async fn load_merged_does_not_regress_to_older_storage() {
411        let storage: Arc<dyn Storage> = Arc::new(MapStorage::default());
412        let repo = test_repo(storage.clone());
413        let id = "s1";
414
415        let mut stale = Session::new(id.to_string(), "m");
416        stale.set_pending_question(
417            "tc1".into(),
418            "kind".into(),
419            "q?".into(),
420            vec!["OK".into()],
421            true,
422        );
423        stale.updated_at = Utc::now() - chrono::Duration::seconds(10);
424        storage.save_session(&stale).await.unwrap();
425
426        let mut fresh = Session::new(id.to_string(), "m");
427        fresh.updated_at = Utc::now();
428        cache_put(&repo, &fresh);
429
430        let merged = repo.load_merged(id).await.expect("session exists");
431        assert!(
432            merged.pending_question.is_none(),
433            "must return the newer answered memory copy, not the stale storage one"
434        );
435        let cached = read_cached_session(repo.cache(), id).expect("cached");
436        assert!(
437            cached.pending_question.is_none(),
438            "load_merged must never regress the cache to a stale storage copy"
439        );
440    }
441
442    /// The pending-question recovery still works when storage is the same age:
443    /// if memory lost a pending question that same-age storage retains, prefer
444    /// storage so a genuine clarification is not dropped.
445    #[tokio::test]
446    async fn load_merged_recovers_pending_question_from_same_age_storage() {
447        let storage: Arc<dyn Storage> = Arc::new(MapStorage::default());
448        let repo = test_repo(storage.clone());
449        let id = "s2";
450        let ts = Utc::now();
451
452        let mut with_pending = Session::new(id.to_string(), "m");
453        with_pending.set_pending_question(
454            "tc".into(),
455            "k".into(),
456            "q".into(),
457            vec!["OK".into()],
458            true,
459        );
460        with_pending.updated_at = ts;
461        storage.save_session(&with_pending).await.unwrap();
462
463        let mut lost = with_pending.clone();
464        lost.clear_pending_question();
465        lost.updated_at = ts;
466        cache_put(&repo, &lost);
467
468        let merged = repo.load_merged(id).await.expect("session exists");
469        assert!(
470            merged.pending_question.is_some(),
471            "same-age storage carrying a pending question must still be recovered"
472        );
473    }
474
475    #[tokio::test]
476    async fn runtime_publish_refreshes_cache_even_when_storage_fails() {
477        let id = "runtime-selection";
478        let mut previous = Session::new(id.to_string(), "m");
479        previous.metadata.insert(
480            "skill_runtime_selected_skill_ids".to_string(),
481            "[\"plan\"]".to_string(),
482        );
483        let storage: Arc<dyn Storage> = Arc::new(FailingSaveStorage {
484            persisted: Mutex::new(Some(previous.clone())),
485        });
486        let repo = test_repo(storage.clone());
487        cache_put(&repo, &previous);
488
489        let mut current = previous.clone();
490        current.metadata.insert(
491            "skill_runtime_selected_skill_ids".to_string(),
492            "[\"review\"]".to_string(),
493        );
494        current.updated_at = Utc::now();
495
496        let result =
497            bamboo_domain::RuntimeSessionPersistence::save_runtime_session(&repo, &mut current)
498                .await;
499        assert!(result.is_err(), "durable failure must still be surfaced");
500
501        let cached = repo.load(id).await.expect("cached current session");
502        assert_eq!(
503            cached
504                .metadata
505                .get("skill_runtime_selected_skill_ids")
506                .map(String::as_str),
507            Some("[\"review\"]")
508        );
509        let allowlist = bamboo_skills::access_control::extract_skill_allowlist(&cached.metadata)
510            .expect("runtime authorization allowlist");
511        assert!(allowlist.contains("review"));
512        assert!(!allowlist.contains("plan"));
513        let durable = storage
514            .load_session(id)
515            .await
516            .expect("load durable state")
517            .expect("previous durable session");
518        assert_eq!(
519            durable
520                .metadata
521                .get("skill_runtime_selected_skill_ids")
522                .map(String::as_str),
523            Some("[\"plan\"]")
524        );
525    }
526}