Skip to main content

adk_session/
firestore.rs

1//! Firestore session service backend.
2//!
3//! Provides [`FirestoreSessionService`] for session persistence using Google Cloud Firestore.
4//! Enabled via the `firestore` feature flag.
5//!
6//! # Data Organization
7//!
8//! Firestore uses subcollections to organize session data:
9//!
10//! - Session: `{root}/{app_name}/sessions/{session_id}`
11//! - Event: `{root}/{app_name}/sessions/{session_id}/events/{event_id}`
12//! - App state: `{root}/{app_name}/app_state/current`
13//! - User state: `{root}/{app_name}/users/{user_id}/state/current`
14//!
15//! # Tenant Isolation
16//!
17//! A session document is addressed by `(app_name, session_id)`; the owning `user_id` is a
18//! field of the document. Every operation that addresses a session checks that the document's
19//! `app_name`, `user_id`, and `session_id` match the request, and every write re-reads the
20//! document inside its transaction before applying anything:
21//!
22//! | Operation | Session missing, or owned by another user |
23//! |-----------|-------------------------------------------|
24//! | `create` | Fails with `session.already_exists` (`Conflict`) when the ID is taken in the app |
25//! | `get`, `append_event_for_identity` | Fails with `session.not_found` |
26//! | `delete` | No-op, identical to deleting a missing session |
27//! | `list`, `delete_all_sessions` | Only the caller's own sessions are returned or removed; `delete_all_sessions` then deletes the user's state document |
28//!
29//! A new session never inherits events: `create` removes any events left under its path.
30//! App names, user IDs, and session IDs are document IDs, so they must not contain `/`.
31
32use crate::history::{HistoryOutcome, ImportSessionRequest, RewriteHistoryRequest, SessionHistory};
33use crate::service::session_not_found_for;
34use crate::{
35    AppendEventRequest, CreateRequest, DeleteRequest, Event, Events, GetRequest, KEY_PREFIX_TEMP,
36    ListRequest, Session, SessionService, State, state_utils,
37};
38use adk_core::identity::{AdkIdentity, SessionId};
39use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
40use async_trait::async_trait;
41use chrono::{DateTime, Utc};
42use firestore::errors::FirestoreError;
43use firestore::*;
44use serde::{Deserialize, Serialize};
45use serde_json::Value;
46use std::collections::HashMap;
47use uuid::Uuid;
48
49const DEFAULT_ROOT_COLLECTION: &str = "adk_sessions";
50const SESSIONS_COLLECTION: &str = "sessions";
51const EVENTS_COLLECTION: &str = "events";
52const APP_STATE_COLLECTION: &str = "app_state";
53const USERS_COLLECTION: &str = "users";
54const USER_STATE_COLLECTION: &str = "state";
55const STATE_DOCUMENT_ID: &str = "current";
56/// Attempts a history rewrite makes before giving up on a session that keeps changing between
57/// the read and the commit.
58const MAX_REWRITE_ATTEMPTS: usize = 16;
59
60/// Configuration for connecting to Firestore.
61///
62/// # Example
63///
64/// ```rust,ignore
65/// use adk_session::FirestoreSessionConfig;
66///
67/// let config = FirestoreSessionConfig {
68///     project_id: "my-gcp-project".to_string(),
69///     root_collection: None, // defaults to "adk_sessions"
70/// };
71/// ```
72pub struct FirestoreSessionConfig {
73    /// Google Cloud project ID.
74    pub project_id: String,
75    /// Root collection prefix for namespacing session data.
76    /// Defaults to `"adk_sessions"` when `None`.
77    pub root_collection: Option<String>,
78}
79
80/// Firestore-backed session service implementing [`SessionService`].
81///
82/// Uses Google Cloud Firestore with Application Default Credentials for authentication.
83/// Data is organized using subcollections under a configurable root collection. See the
84/// [module documentation](self) for the layout and the tenant-isolation guarantees.
85pub struct FirestoreSessionService {
86    core: SessionCore<FirestoreStore>,
87}
88
89impl FirestoreSessionService {
90    /// Connect to Firestore using Application Default Credentials.
91    ///
92    /// Returns an error with "firestore connection failed" context if the connection cannot
93    /// be established.
94    ///
95    /// # Arguments
96    ///
97    /// * `config` - Firestore connection configuration including project ID and optional
98    ///   root collection prefix.
99    pub async fn new(config: FirestoreSessionConfig) -> Result<Self> {
100        let root_collection =
101            config.root_collection.unwrap_or_else(|| DEFAULT_ROOT_COLLECTION.to_string());
102        let db = FirestoreDb::new(&config.project_id)
103            .await
104            .map_err(|e| AdkError::session(format!("firestore connection failed: {e}")))?;
105        Ok(Self { core: SessionCore { store: FirestoreStore { db, root_collection } } })
106    }
107
108    /// Uses an existing client, such as one the durable stores share or one from
109    /// [`connect_firestore_emulator`](crate::firestore_stores::connect_firestore_emulator).
110    ///
111    /// `root_collection` defaults to `"adk_sessions"` when `None`.
112    ///
113    /// # Example
114    ///
115    /// ```rust,no_run
116    /// use adk_session::FirestoreSessionService;
117    /// use adk_session::firestore_stores::connect_firestore_emulator;
118    ///
119    /// # async fn example() -> adk_core::Result<()> {
120    /// let db = connect_firestore_emulator("demo-project").await?;
121    /// let sessions = FirestoreSessionService::from_db(db, None);
122    /// assert_eq!(sessions.root_collection(), "adk_sessions");
123    /// # Ok(())
124    /// # }
125    /// ```
126    pub fn from_db(db: FirestoreDb, root_collection: Option<String>) -> Self {
127        let root_collection =
128            root_collection.unwrap_or_else(|| DEFAULT_ROOT_COLLECTION.to_string());
129        Self { core: SessionCore { store: FirestoreStore { db, root_collection } } }
130    }
131
132    /// Returns a reference to the underlying `FirestoreDb`.
133    pub fn db(&self) -> &FirestoreDb {
134        &self.core.store.db
135    }
136
137    /// Returns the root collection prefix.
138    pub fn root_collection(&self) -> &str {
139        &self.core.store.root_collection
140    }
141}
142
143/// Generate the Firestore document path for a session.
144///
145/// Path format: `{root}/{app_name}/sessions/{session_id}`
146pub fn session_path(root: &str, app_name: &str, session_id: &str) -> String {
147    format!("{root}/{app_name}/{SESSIONS_COLLECTION}/{session_id}")
148}
149
150/// Generate the Firestore document path for an event within a session.
151///
152/// Path format: `{root}/{app_name}/sessions/{session_id}/events/{event_id}`
153pub fn event_path(root: &str, app_name: &str, session_id: &str, event_id: &str) -> String {
154    format!("{root}/{app_name}/{SESSIONS_COLLECTION}/{session_id}/{EVENTS_COLLECTION}/{event_id}")
155}
156
157/// Generate the Firestore document path for app-level state.
158///
159/// Path format: `{root}/{app_name}/app_state/current`
160pub fn app_state_path(root: &str, app_name: &str) -> String {
161    format!("{root}/{app_name}/{APP_STATE_COLLECTION}/{STATE_DOCUMENT_ID}")
162}
163
164/// Generate the Firestore document path for user-level state.
165///
166/// Path format: `{root}/{app_name}/users/{user_id}/state/current`
167pub fn user_state_path(root: &str, app_name: &str, user_id: &str) -> String {
168    format!(
169        "{root}/{app_name}/{USERS_COLLECTION}/{user_id}/{USER_STATE_COLLECTION}/{STATE_DOCUMENT_ID}"
170    )
171}
172
173// ---------------------------------------------------------------------------
174// Firestore document models
175// ---------------------------------------------------------------------------
176
177/// Firestore document for a session.
178#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
179struct SessionDoc {
180    app_name: String,
181    user_id: String,
182    session_id: String,
183    state: HashMap<String, Value>,
184    #[serde(with = "firestore::serialize_as_timestamp")]
185    created_at: DateTime<Utc>,
186    #[serde(with = "firestore::serialize_as_timestamp")]
187    updated_at: DateTime<Utc>,
188    /// Appends so far; the next event's `seq`.
189    #[serde(default)]
190    event_seq: i64,
191    /// The session state the session was created with; absent on sessions created by
192    /// earlier releases.
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    initial_state: Option<HashMap<String, Value>>,
195}
196
197/// Firestore document for an event.
198#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
199struct EventDoc {
200    id: String,
201    invocation_id: String,
202    branch: String,
203    author: String,
204    #[serde(with = "firestore::serialize_as_timestamp")]
205    timestamp: DateTime<Utc>,
206    llm_response: Value,
207    actions: Value,
208    long_running_tool_ids: Value,
209    /// Position among the session's appends; orders events with equal timestamps. Absent on
210    /// events written by earlier releases.
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    seq: Option<i64>,
213}
214
215/// Firestore document for app-level state.
216#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
217struct AppStateDoc {
218    state: HashMap<String, Value>,
219    #[serde(with = "firestore::serialize_as_timestamp")]
220    updated_at: DateTime<Utc>,
221}
222
223/// Firestore document for user-level state.
224#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
225struct UserStateDoc {
226    state: HashMap<String, Value>,
227    #[serde(with = "firestore::serialize_as_timestamp")]
228    updated_at: DateTime<Utc>,
229}
230
231// ---------------------------------------------------------------------------
232// Helpers: Event <-> EventDoc, identity checks, errors
233// ---------------------------------------------------------------------------
234
235fn event_to_doc(event: &Event) -> Result<EventDoc> {
236    let llm_response = serde_json::to_value(&event.llm_response)
237        .map_err(|e| AdkError::session(format!("serialize failed: {e}")))?;
238    let actions = serde_json::to_value(&event.actions)
239        .map_err(|e| AdkError::session(format!("serialize failed: {e}")))?;
240    let long_running_tool_ids = serde_json::to_value(&event.long_running_tool_ids)
241        .map_err(|e| AdkError::session(format!("serialize failed: {e}")))?;
242
243    Ok(EventDoc {
244        id: event.id.clone(),
245        invocation_id: event.invocation_id.clone(),
246        branch: event.branch.clone(),
247        author: event.author.clone(),
248        timestamp: event.timestamp,
249        llm_response,
250        actions,
251        long_running_tool_ids,
252        seq: None,
253    })
254}
255
256fn doc_to_event(doc: &EventDoc) -> std::result::Result<Event, serde_json::Error> {
257    Ok(Event {
258        id: doc.id.clone(),
259        timestamp: doc.timestamp,
260        invocation_id: doc.invocation_id.clone(),
261        branch: doc.branch.clone(),
262        author: doc.author.clone(),
263        llm_request: None,
264        llm_response: serde_json::from_value(doc.llm_response.clone())?,
265        actions: serde_json::from_value(doc.actions.clone())?,
266        long_running_tool_ids: serde_json::from_value(doc.long_running_tool_ids.clone())?,
267        provider_metadata: HashMap::new(),
268    })
269}
270
271/// Converts stored event documents, logging and skipping any that no longer deserialize
272/// so one corrupt event does not hide the rest of the session history.
273fn decode_event_docs(docs: &[EventDoc], session_id: &str) -> Vec<Event> {
274    docs.iter()
275        .filter_map(|doc| match doc_to_event(doc) {
276            Ok(event) => Some(event),
277            Err(error) => {
278                tracing::warn!(
279                    session.id = %session_id,
280                    event.id = %doc.id,
281                    error = %error,
282                    "skipping stored event that failed to deserialize"
283                );
284                None
285            }
286        })
287        .collect()
288}
289
290/// Returns `true` when `doc` is the session addressed by `(app_name, user_id, session_id)`.
291fn is_owned_by(doc: &SessionDoc, app_name: &str, user_id: &str, session_id: &str) -> bool {
292    doc.app_name == app_name && doc.user_id == user_id && doc.session_id == session_id
293}
294
295/// Rejects identifiers that cannot be used as a single Firestore document ID.
296fn validate_path_segment(kind: &str, value: &str) -> Result<()> {
297    let reserved = value.len() >= 4 && value.starts_with("__") && value.ends_with("__");
298    if value.is_empty() || value.contains('/') || value == "." || value == ".." || reserved {
299        return Err(AdkError::new(
300            ErrorComponent::Session,
301            ErrorCategory::InvalidInput,
302            "session.firestore.invalid_identifier",
303            format!(
304                "{kind} '{value}' cannot be used as a Firestore document ID; it must be \
305                 non-empty, must not contain '/', and must not be '.', '..' or match '__.*__'"
306            ),
307        ));
308    }
309    Ok(())
310}
311
312fn validate_identity(app_name: &str, user_id: &str, session_id: &str) -> Result<()> {
313    validate_path_segment("app_name", app_name)?;
314    validate_path_segment("user_id", user_id)?;
315    validate_path_segment("session_id", session_id)
316}
317
318fn session_already_exists(app_name: &str, session_id: &str) -> AdkError {
319    AdkError::new(
320        ErrorComponent::Session,
321        ErrorCategory::Conflict,
322        "session.already_exists",
323        format!(
324            "session '{session_id}' already exists in app '{app_name}'; omit session_id to \
325             generate a new one or choose a different ID"
326        ),
327    )
328}
329
330/// Maps a Firestore failure, keeping whether Firestore reported it as retryable, such as a
331/// transaction aborted by contention.
332fn firestore_error(context: &str, error: FirestoreError) -> AdkError {
333    if crate::firestore_stores::is_retryable(&error) {
334        return AdkError::new(
335            ErrorComponent::Session,
336            ErrorCategory::Unavailable,
337            RETRYABLE_CODE,
338            format!("{context}: {error}"),
339        );
340    }
341    AdkError::session(format!("{context}: {error}"))
342}
343
344/// Code of a Firestore failure that Firestore reported as retryable.
345const RETRYABLE_CODE: &str = "session.firestore.retryable";
346
347// ---------------------------------------------------------------------------
348// Storage abstraction
349//
350// `SessionStore` isolates the handful of Firestore calls the service makes, so the
351// ownership and precondition logic in `SessionCore` is unit-tested against an in-memory
352// store. `FirestoreStore` is the production implementation.
353// ---------------------------------------------------------------------------
354
355/// Precondition the store re-checks inside the write transaction before applying a commit.
356#[derive(Debug, Clone, PartialEq)]
357enum SessionGuard {
358    /// The session document must not exist.
359    Absent,
360    /// The session document must exist and match the commit's app, user, and session ID.
361    Owned,
362    /// The session document must still be this one, the one a history rewrite was planned
363    /// from. Every append changes `event_seq` and `updated_at`, so an append in between fails
364    /// it.
365    Unchanged(Box<SessionDoc>),
366}
367
368impl SessionGuard {
369    /// Whether the guard holds for the document `current` read inside the transaction.
370    fn holds(&self, current: Option<&SessionDoc>, commit: &SessionCommit) -> bool {
371        match self {
372            Self::Absent => current.is_none(),
373            Self::Owned => current.is_some_and(|doc| {
374                is_owned_by(doc, &commit.app_name, &commit.user_id, &commit.session_id)
375            }),
376            Self::Unchanged(expected) => current == Some(expected.as_ref()),
377        }
378    }
379}
380
381/// Event documents a history rewrite or an import writes and deletes.
382#[derive(Debug, Clone, PartialEq, Default)]
383struct EventWrites {
384    /// IDs of the event documents to delete.
385    remove: Vec<String>,
386    /// Event documents to write, replacing any with the same ID; each carries its `seq`.
387    put: Vec<EventDoc>,
388}
389
390/// What a commit does to the session document.
391#[derive(Debug, Clone, PartialEq)]
392enum SessionWrite {
393    /// Write the document, replacing the current one.
394    Put(SessionDoc),
395    /// Merge keys into the session state of the document read inside the transaction.
396    Merge(StateMerge),
397    /// Delete the document together with its `events` subcollection.
398    Delete,
399}
400
401/// Keys merged into a stored state map inside the commit transaction, so a concurrent
402/// writer's keys are read and kept rather than overwritten.
403#[derive(Debug, Clone, PartialEq)]
404struct StateMerge {
405    delta: HashMap<String, Value>,
406    updated_at: DateTime<Utc>,
407}
408
409impl StateMerge {
410    /// Returns `None` for an empty delta, which leaves the stored document untouched.
411    fn non_empty(delta: HashMap<String, Value>, updated_at: DateTime<Utc>) -> Option<Self> {
412        (!delta.is_empty()).then_some(Self { delta, updated_at })
413    }
414
415    /// Applies the merge to `stored`.
416    ///
417    /// Session documents written by earlier releases also hold a copy of the app and user
418    /// tiers; `session_tier` drops it.
419    fn apply(&self, stored: &HashMap<String, Value>, session_tier: bool) -> HashMap<String, Value> {
420        let mut state =
421            if session_tier { state_utils::extract_state_deltas(stored).2 } else { stored.clone() };
422        state.extend(self.delta.clone());
423        state
424    }
425}
426
427/// One atomic write against a single session, applied by [`SessionStore::commit`].
428#[derive(Debug, Clone, PartialEq)]
429struct SessionCommit {
430    app_name: String,
431    user_id: String,
432    session_id: String,
433    guard: SessionGuard,
434    session: SessionWrite,
435    app_state: Option<StateMerge>,
436    user_state: Option<StateMerge>,
437    event: Option<EventDoc>,
438    /// History rewrites and imports: events written and deleted as they are.
439    events: EventWrites,
440}
441
442impl SessionCommit {
443    /// Whether the commit removes the events stored under the session path: a create
444    /// clears orphans so the new session starts empty, and a delete removes them all.
445    fn purges_events(&self) -> bool {
446        match (&self.guard, &self.session) {
447            (SessionGuard::Absent, _) | (_, SessionWrite::Delete) => true,
448            (
449                SessionGuard::Owned | SessionGuard::Unchanged(_),
450                SessionWrite::Put(_) | SessionWrite::Merge(_),
451            ) => false,
452        }
453    }
454}
455
456/// Result of [`SessionStore::commit`].
457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
458enum CommitOutcome {
459    /// Every write was applied.
460    Committed,
461    /// The guard did not hold; nothing was written.
462    GuardFailed,
463}
464
465/// The Firestore operations the session service relies on.
466#[async_trait]
467trait SessionStore: Send + Sync {
468    /// Reads the session document at `{root}/{app_name}/sessions/{session_id}`.
469    async fn session(&self, app_name: &str, session_id: &str) -> Result<Option<SessionDoc>>;
470    /// Finds session documents whose `session_id` field matches, across every app.
471    async fn sessions_with_id(&self, session_id: &str) -> Result<Vec<SessionDoc>>;
472    /// Lists the session documents in `app_name` whose `user_id` field matches.
473    async fn user_sessions(&self, app_name: &str, user_id: &str) -> Result<Vec<SessionDoc>>;
474    /// Reads a session's event documents ordered by timestamp.
475    async fn events(&self, app_name: &str, session_id: &str) -> Result<Vec<EventDoc>>;
476    /// Reads app-level state, empty when none has been written.
477    async fn app_state(&self, app_name: &str) -> Result<HashMap<String, Value>>;
478    /// Reads user-level state, empty when none has been written.
479    async fn user_state(&self, app_name: &str, user_id: &str) -> Result<HashMap<String, Value>>;
480    /// Deletes the user-level state document; a missing one is not an error.
481    async fn delete_user_state(&self, app_name: &str, user_id: &str) -> Result<()>;
482    /// Applies `commit` atomically when its guard holds inside the transaction.
483    async fn commit(&self, commit: SessionCommit) -> Result<CommitOutcome>;
484}
485
486/// Production [`SessionStore`] backed by a [`FirestoreDb`].
487struct FirestoreStore {
488    db: FirestoreDb,
489    root_collection: String,
490}
491
492impl FirestoreStore {
493    /// Parent path of the per-app subcollections: `{root}/{app_name}`.
494    fn app_parent(&self, app_name: &str) -> Result<String> {
495        let parent = self
496            .db
497            .parent_path(&self.root_collection, app_name)
498            .map_err(|e| firestore_error("path error", e))?;
499        Ok(parent.to_string())
500    }
501
502    /// Parent path of a session's events: `{root}/{app_name}/sessions/{session_id}`.
503    fn events_parent(&self, app_name: &str, session_id: &str) -> Result<String> {
504        let parent = self
505            .db
506            .parent_path(&self.root_collection, app_name)
507            .map_err(|e| firestore_error("path error", e))?
508            .at(SESSIONS_COLLECTION, session_id)
509            .map_err(|e| firestore_error("path error", e))?;
510        Ok(parent.to_string())
511    }
512
513    /// Parent path of a user's state: `{root}/{app_name}/users/{user_id}`.
514    fn user_parent(&self, app_name: &str, user_id: &str) -> Result<String> {
515        let parent = self
516            .db
517            .parent_path(&self.root_collection, app_name)
518            .map_err(|e| firestore_error("path error", e))?
519            .at(USERS_COLLECTION, user_id)
520            .map_err(|e| firestore_error("path error", e))?;
521        Ok(parent.to_string())
522    }
523}
524
525/// Returns the last segment of a Firestore document name, which is the document ID.
526fn document_id(document: &FirestoreDocument) -> &str {
527    document.name.rsplit('/').next().unwrap_or_default()
528}
529
530#[async_trait]
531impl SessionStore for FirestoreStore {
532    async fn session(&self, app_name: &str, session_id: &str) -> Result<Option<SessionDoc>> {
533        let parent = self.app_parent(app_name)?;
534        self.db
535            .fluent()
536            .select()
537            .by_id_in(SESSIONS_COLLECTION)
538            .parent(&parent)
539            .obj::<SessionDoc>()
540            .one(session_id)
541            .await
542            .map_err(|e| firestore_error("query failed", e))
543    }
544
545    async fn sessions_with_id(&self, session_id: &str) -> Result<Vec<SessionDoc>> {
546        // Collection-group query over every `sessions` collection in the database.
547        self.db
548            .fluent()
549            .select()
550            .from(SESSIONS_COLLECTION)
551            .parent(self.db.get_documents_path())
552            .all_descendants()
553            .filter(|q| q.for_all([q.field("session_id").eq(session_id)]))
554            .obj::<SessionDoc>()
555            .query()
556            .await
557            .map_err(|e| firestore_error("query failed", e))
558    }
559
560    async fn user_sessions(&self, app_name: &str, user_id: &str) -> Result<Vec<SessionDoc>> {
561        let parent = self.app_parent(app_name)?;
562        self.db
563            .fluent()
564            .select()
565            .from(SESSIONS_COLLECTION)
566            .parent(&parent)
567            .filter(|q| q.for_all([q.field("user_id").eq(user_id)]))
568            .obj::<SessionDoc>()
569            .query()
570            .await
571            .map_err(|e| firestore_error("query failed", e))
572    }
573
574    async fn events(&self, app_name: &str, session_id: &str) -> Result<Vec<EventDoc>> {
575        let parent = self.events_parent(app_name, session_id)?;
576        // Raw documents are decoded one by one so a single corrupt event is skipped
577        // instead of failing the whole query.
578        let documents = self
579            .db
580            .fluent()
581            .select()
582            .from(EVENTS_COLLECTION)
583            .parent(&parent)
584            .order_by([("timestamp".to_string(), FirestoreQueryDirection::Ascending)])
585            .query()
586            .await
587            .map_err(|e| firestore_error("query failed", e))?;
588
589        Ok(documents
590            .iter()
591            .filter_map(|document| match FirestoreDb::deserialize_doc_to::<EventDoc>(document) {
592                Ok(doc) => Some(doc),
593                Err(error) => {
594                    tracing::warn!(
595                        session.id = %session_id,
596                        event.id = %document_id(document),
597                        error = %error,
598                        "skipping stored event that failed to deserialize"
599                    );
600                    None
601                }
602            })
603            .collect())
604    }
605
606    async fn app_state(&self, app_name: &str) -> Result<HashMap<String, Value>> {
607        let parent = self.app_parent(app_name)?;
608        let doc: Option<AppStateDoc> = self
609            .db
610            .fluent()
611            .select()
612            .by_id_in(APP_STATE_COLLECTION)
613            .parent(&parent)
614            .obj::<AppStateDoc>()
615            .one(STATE_DOCUMENT_ID)
616            .await
617            .map_err(|e| firestore_error("query failed", e))?;
618        Ok(doc.map(|d| d.state).unwrap_or_default())
619    }
620
621    async fn user_state(&self, app_name: &str, user_id: &str) -> Result<HashMap<String, Value>> {
622        let parent = self.user_parent(app_name, user_id)?;
623        let doc: Option<UserStateDoc> = self
624            .db
625            .fluent()
626            .select()
627            .by_id_in(USER_STATE_COLLECTION)
628            .parent(&parent)
629            .obj::<UserStateDoc>()
630            .one(STATE_DOCUMENT_ID)
631            .await
632            .map_err(|e| firestore_error("query failed", e))?;
633        Ok(doc.map(|d| d.state).unwrap_or_default())
634    }
635
636    async fn delete_user_state(&self, app_name: &str, user_id: &str) -> Result<()> {
637        let parent = self.user_parent(app_name, user_id)?;
638        self.db
639            .fluent()
640            .delete()
641            .from(USER_STATE_COLLECTION)
642            .parent(&parent)
643            .document_id(STATE_DOCUMENT_ID)
644            .execute()
645            .await
646            .map_err(|e| firestore_error("delete failed", e))
647    }
648
649    async fn commit(&self, commit: SessionCommit) -> Result<CommitOutcome> {
650        // A transaction Firestore aborts, such as one that contended with another for a
651        // document, applied nothing; it runs again from its reads.
652        crate::firestore_stores::retry_while(
653            |error: &AdkError| error.code == RETRYABLE_CODE,
654            || self.commit_once(&commit),
655        )
656        .await
657    }
658}
659
660impl FirestoreStore {
661    /// Runs `commit` in one transaction.
662    async fn commit_once(&self, commit: &SessionCommit) -> Result<CommitOutcome> {
663        let app_parent = self.app_parent(&commit.app_name)?;
664        let events_parent = self.events_parent(&commit.app_name, &commit.session_id)?;
665        let user_parent = self.user_parent(&commit.app_name, &commit.user_id)?;
666
667        let mut transaction = self
668            .db
669            .begin_transaction()
670            .await
671            .map_err(|e| firestore_error("transaction failed", e))?;
672        // Reads through this handle join the transaction, so the guard check and the writes
673        // below apply to the same document version.
674        let tx_db = self.db.clone_with_consistency_selector(
675            FirestoreConsistencySelector::Transaction(transaction.transaction_id().clone()),
676        );
677
678        let staged: Result<bool> = async {
679            let current: Option<SessionDoc> = tx_db
680                .fluent()
681                .select()
682                .by_id_in(SESSIONS_COLLECTION)
683                .parent(&app_parent)
684                .obj::<SessionDoc>()
685                .one(&commit.session_id)
686                .await
687                .map_err(|e| firestore_error("query failed", e))?;
688            if !commit.guard.holds(current.as_ref(), commit) {
689                return Ok(false);
690            }
691
692            if commit.purges_events() {
693                let stored_events = tx_db
694                    .fluent()
695                    .select()
696                    .from(EVENTS_COLLECTION)
697                    .parent(&events_parent)
698                    .query()
699                    .await
700                    .map_err(|e| firestore_error("query failed", e))?;
701                // Documents the commit writes again are replaced by that write instead.
702                for document in stored_events.iter().filter(|document| {
703                    !commit.events.put.iter().any(|event| event.id == document_id(document))
704                }) {
705                    self.db
706                        .fluent()
707                        .delete()
708                        .from(EVENTS_COLLECTION)
709                        .parent(&events_parent)
710                        .document_id(document_id(document))
711                        .add_to_transaction(&mut transaction)
712                        .map_err(|e| firestore_error("delete failed", e))?;
713                }
714            }
715
716            // Reads through `tx_db` hold these documents until the commit, so the merges
717            // below apply to the stored state rather than a copy read earlier.
718            let app_state = match &commit.app_state {
719                Some(merge) => {
720                    let stored = tx_db
721                        .fluent()
722                        .select()
723                        .by_id_in(APP_STATE_COLLECTION)
724                        .parent(&app_parent)
725                        .obj::<AppStateDoc>()
726                        .one(STATE_DOCUMENT_ID)
727                        .await
728                        .map_err(|e| firestore_error("query failed", e))?
729                        .map(|doc| doc.state)
730                        .unwrap_or_default();
731                    Some(AppStateDoc {
732                        state: merge.apply(&stored, false),
733                        updated_at: merge.updated_at,
734                    })
735                }
736                None => None,
737            };
738            let user_state = match &commit.user_state {
739                Some(merge) => {
740                    let stored = tx_db
741                        .fluent()
742                        .select()
743                        .by_id_in(USER_STATE_COLLECTION)
744                        .parent(&user_parent)
745                        .obj::<UserStateDoc>()
746                        .one(STATE_DOCUMENT_ID)
747                        .await
748                        .map_err(|e| firestore_error("query failed", e))?
749                        .map(|doc| doc.state)
750                        .unwrap_or_default();
751                    Some(UserStateDoc {
752                        state: merge.apply(&stored, false),
753                        updated_at: merge.updated_at,
754                    })
755                }
756                None => None,
757            };
758
759            let session_doc = match (&commit.session, current) {
760                (SessionWrite::Put(doc), _) => Some(doc.clone()),
761                (SessionWrite::Merge(merge), Some(current)) => Some(SessionDoc {
762                    state: merge.apply(&current.state, true),
763                    updated_at: merge.updated_at,
764                    event_seq: current.event_seq + i64::from(commit.event.is_some()),
765                    ..current
766                }),
767                // The `Owned` guard above guarantees a current document.
768                (SessionWrite::Merge(_), None) => return Ok(false),
769                (SessionWrite::Delete, _) => None,
770            };
771
772            match &session_doc {
773                Some(doc) => {
774                    // Backs up the in-transaction guard check at commit time.
775                    let precondition = match commit.guard {
776                        SessionGuard::Absent => FirestoreWritePrecondition::Exists(false),
777                        SessionGuard::Owned | SessionGuard::Unchanged(_) => {
778                            FirestoreWritePrecondition::Exists(true)
779                        }
780                    };
781                    self.db
782                        .fluent()
783                        .update()
784                        .in_col(SESSIONS_COLLECTION)
785                        .precondition(precondition)
786                        .document_id(&commit.session_id)
787                        .parent(&app_parent)
788                        .object(doc)
789                        .add_to_transaction(&mut transaction)
790                        .map_err(|e| firestore_error("write failed", e))?;
791                }
792                None => {
793                    self.db
794                        .fluent()
795                        .delete()
796                        .from(SESSIONS_COLLECTION)
797                        .parent(&app_parent)
798                        .document_id(&commit.session_id)
799                        .add_to_transaction(&mut transaction)
800                        .map_err(|e| firestore_error("delete failed", e))?;
801                }
802            }
803
804            if let Some(app_state) = &app_state {
805                self.db
806                    .fluent()
807                    .update()
808                    .in_col(APP_STATE_COLLECTION)
809                    .document_id(STATE_DOCUMENT_ID)
810                    .parent(&app_parent)
811                    .object(app_state)
812                    .add_to_transaction(&mut transaction)
813                    .map_err(|e| firestore_error("write failed", e))?;
814            }
815            if let Some(user_state) = &user_state {
816                self.db
817                    .fluent()
818                    .update()
819                    .in_col(USER_STATE_COLLECTION)
820                    .document_id(STATE_DOCUMENT_ID)
821                    .parent(&user_parent)
822                    .object(user_state)
823                    .add_to_transaction(&mut transaction)
824                    .map_err(|e| firestore_error("write failed", e))?;
825            }
826            for event_id in &commit.events.remove {
827                self.db
828                    .fluent()
829                    .delete()
830                    .from(EVENTS_COLLECTION)
831                    .parent(&events_parent)
832                    .document_id(event_id)
833                    .add_to_transaction(&mut transaction)
834                    .map_err(|e| firestore_error("delete failed", e))?;
835            }
836            for event in &commit.events.put {
837                self.db
838                    .fluent()
839                    .update()
840                    .in_col(EVENTS_COLLECTION)
841                    .document_id(&event.id)
842                    .parent(&events_parent)
843                    .object(event)
844                    .add_to_transaction(&mut transaction)
845                    .map_err(|e| firestore_error("write failed", e))?;
846            }
847            if let Some(event) = &commit.event {
848                let event = EventDoc {
849                    seq: session_doc.as_ref().map(|doc| doc.event_seq),
850                    ..event.clone()
851                };
852                self.db
853                    .fluent()
854                    .update()
855                    .in_col(EVENTS_COLLECTION)
856                    .document_id(&event.id)
857                    .parent(&events_parent)
858                    .object(&event)
859                    .add_to_transaction(&mut transaction)
860                    .map_err(|e| firestore_error("write failed", e))?;
861            }
862            Ok(true)
863        }
864        .await;
865
866        match staged {
867            Ok(true) => match transaction.commit().await {
868                Ok(_) => Ok(CommitOutcome::Committed),
869                Err(
870                    FirestoreError::DataConflictError(_) | FirestoreError::DataNotFoundError(_),
871                ) => Ok(CommitOutcome::GuardFailed),
872                Err(error) => Err(firestore_error("commit failed", error)),
873            },
874            Ok(false) => {
875                if let Err(error) = transaction.rollback().await {
876                    tracing::warn!(error = %error, "firestore transaction rollback failed");
877                }
878                Ok(CommitOutcome::GuardFailed)
879            }
880            Err(error) => {
881                if let Err(rollback_error) = transaction.rollback().await {
882                    tracing::warn!(error = %rollback_error, "firestore transaction rollback failed");
883                }
884                Err(error)
885            }
886        }
887    }
888}
889
890// ---------------------------------------------------------------------------
891// Session logic
892// ---------------------------------------------------------------------------
893
894/// Session semantics over a [`SessionStore`]: identity checks, state tiers, and guards.
895struct SessionCore<S> {
896    store: S,
897}
898
899impl<S: SessionStore> SessionCore<S> {
900    /// Appends `event` to the session owned by `(app_name, user_id, session_id)`.
901    async fn append(
902        &self,
903        app_name: &str,
904        user_id: &str,
905        session_id: &str,
906        mut event: Event,
907    ) -> Result<()> {
908        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));
909        let not_found = || session_not_found_for(app_name, user_id, session_id);
910
911        self.store
912            .session(app_name, session_id)
913            .await?
914            .filter(|doc| is_owned_by(doc, app_name, user_id, session_id))
915            .ok_or_else(not_found)?;
916
917        let (app_delta, user_delta, session_delta) =
918            state_utils::extract_state_deltas(&event.actions.state_delta);
919
920        let now = event.timestamp;
921        let commit = SessionCommit {
922            app_name: app_name.to_string(),
923            user_id: user_id.to_string(),
924            session_id: session_id.to_string(),
925            guard: SessionGuard::Owned,
926            session: SessionWrite::Merge(StateMerge { delta: session_delta, updated_at: now }),
927            app_state: StateMerge::non_empty(app_delta, now),
928            user_state: StateMerge::non_empty(user_delta, now),
929            event: Some(event_to_doc(&event)?),
930            events: EventWrites::default(),
931        };
932
933        match self.store.commit(commit).await? {
934            CommitOutcome::Committed => Ok(()),
935            CommitOutcome::GuardFailed => Err(not_found()),
936        }
937    }
938
939    /// Reads the session document `identity` names and its history, with each event's `seq`.
940    async fn load_history(
941        &self,
942        identity: &AdkIdentity,
943    ) -> Result<(SessionDoc, SessionHistory, HashMap<String, Option<i64>>)> {
944        let (app_name, user_id, session_id) =
945            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
946        validate_identity(app_name, user_id, session_id)?;
947        let doc = self
948            .store
949            .session(app_name, session_id)
950            .await?
951            .filter(|doc| is_owned_by(doc, app_name, user_id, session_id))
952            .ok_or_else(|| session_not_found_for(app_name, user_id, session_id))?;
953        let mut event_docs = self.store.events(app_name, session_id).await?;
954        event_docs.sort_by_key(|doc| (doc.timestamp, doc.seq));
955        let seqs = event_docs.iter().map(|event| (event.id.clone(), event.seq)).collect();
956        // Documents written by earlier releases also hold a copy of the app and user tiers.
957        let (_, _, state) = state_utils::extract_state_deltas(&doc.state);
958        let history = SessionHistory::new(
959            decode_event_docs(&event_docs, session_id),
960            state,
961            doc.initial_state.clone(),
962        );
963        Ok((doc, history, seqs))
964    }
965}
966
967#[async_trait]
968impl<S: SessionStore> SessionService for SessionCore<S> {
969    async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>> {
970        let session_id = req.session_id.clone().unwrap_or_else(|| Uuid::new_v4().to_string());
971        req.try_app_name()?;
972        req.try_user_id()?;
973        SessionId::try_from(session_id.as_str())?;
974        validate_identity(&req.app_name, &req.user_id, &session_id)?;
975
976        let (app_delta, user_delta, session_state) = state_utils::extract_state_deltas(&req.state);
977
978        let now = Utc::now();
979        let commit = SessionCommit {
980            app_name: req.app_name.clone(),
981            user_id: req.user_id.clone(),
982            session_id: session_id.clone(),
983            guard: SessionGuard::Absent,
984            session: SessionWrite::Put(SessionDoc {
985                app_name: req.app_name.clone(),
986                user_id: req.user_id.clone(),
987                session_id: session_id.clone(),
988                state: session_state.clone(),
989                created_at: now,
990                updated_at: now,
991                event_seq: 0,
992                initial_state: Some(session_state.clone()),
993            }),
994            app_state: StateMerge::non_empty(app_delta, now),
995            user_state: StateMerge::non_empty(user_delta, now),
996            event: None,
997            events: EventWrites::default(),
998        };
999
1000        match self.store.commit(commit).await? {
1001            CommitOutcome::Committed => {
1002                let app_state = self.store.app_state(&req.app_name).await?;
1003                let user_state = self.store.user_state(&req.app_name, &req.user_id).await?;
1004                Ok(Box::new(FirestoreSession {
1005                    app_name: req.app_name,
1006                    user_id: req.user_id,
1007                    session_id,
1008                    state: state_utils::merge_states(&app_state, &user_state, &session_state),
1009                    events: Vec::new(),
1010                    updated_at: now,
1011                }))
1012            }
1013            CommitOutcome::GuardFailed => Err(session_already_exists(&req.app_name, &session_id)),
1014        }
1015    }
1016
1017    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
1018        req.try_identity()?;
1019        validate_identity(&req.app_name, &req.user_id, &req.session_id)?;
1020
1021        let session_doc = self
1022            .store
1023            .session(&req.app_name, &req.session_id)
1024            .await?
1025            .filter(|doc| is_owned_by(doc, &req.app_name, &req.user_id, &req.session_id))
1026            .ok_or_else(|| crate::service::session_not_found(&req))?;
1027
1028        let app_state = self.store.app_state(&req.app_name).await?;
1029        let user_state = self.store.user_state(&req.app_name, &req.user_id).await?;
1030        let mut event_docs = self.store.events(&req.app_name, &req.session_id).await?;
1031        // Stable, so events of earlier releases (no `seq`) keep the store's order.
1032        event_docs.sort_by_key(|doc| (doc.timestamp, doc.seq));
1033        let mut events = decode_event_docs(&event_docs, &req.session_id);
1034
1035        if let Some(num) = req.num_recent_events {
1036            let start = events.len().saturating_sub(num);
1037            events = events[start..].to_vec();
1038        }
1039        if let Some(after) = req.after {
1040            events.retain(|e| e.timestamp >= after);
1041        }
1042
1043        Ok(Box::new(FirestoreSession {
1044            app_name: req.app_name,
1045            user_id: req.user_id,
1046            session_id: req.session_id,
1047            state: state_utils::merge_current_tiers(&app_state, &user_state, &session_doc.state),
1048            events,
1049            updated_at: session_doc.updated_at,
1050        }))
1051    }
1052
1053    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
1054        req.try_app_name()?;
1055        req.try_user_id()?;
1056        validate_path_segment("app_name", &req.app_name)?;
1057        validate_path_segment("user_id", &req.user_id)?;
1058
1059        let mut docs: Vec<SessionDoc> = self
1060            .store
1061            .user_sessions(&req.app_name, &req.user_id)
1062            .await?
1063            .into_iter()
1064            .filter(|doc| doc.app_name == req.app_name && doc.user_id == req.user_id)
1065            .collect();
1066        docs.sort_by(|a, b| {
1067            b.updated_at.cmp(&a.updated_at).then_with(|| b.session_id.cmp(&a.session_id))
1068        });
1069
1070        let app_state = self.store.app_state(&req.app_name).await?;
1071        let user_state = self.store.user_state(&req.app_name, &req.user_id).await?;
1072
1073        Ok(docs
1074            .into_iter()
1075            .skip(req.offset.unwrap_or(0))
1076            .take(req.limit.unwrap_or(usize::MAX))
1077            .map(|doc| {
1078                Box::new(FirestoreSession {
1079                    app_name: doc.app_name,
1080                    user_id: doc.user_id,
1081                    session_id: doc.session_id,
1082                    state: state_utils::merge_current_tiers(&app_state, &user_state, &doc.state),
1083                    events: Vec::new(),
1084                    updated_at: doc.updated_at,
1085                }) as Box<dyn Session>
1086            })
1087            .collect())
1088    }
1089
1090    async fn delete(&self, req: DeleteRequest) -> Result<()> {
1091        req.try_identity()?;
1092        validate_identity(&req.app_name, &req.user_id, &req.session_id)?;
1093
1094        let commit = SessionCommit {
1095            app_name: req.app_name,
1096            user_id: req.user_id,
1097            session_id: req.session_id,
1098            guard: SessionGuard::Owned,
1099            session: SessionWrite::Delete,
1100            app_state: None,
1101            user_state: None,
1102            event: None,
1103            events: EventWrites::default(),
1104        };
1105        // A missing or foreign session is a no-op, so deletion reveals nothing about
1106        // sessions the caller does not own.
1107        match self.store.commit(commit).await? {
1108            CommitOutcome::Committed | CommitOutcome::GuardFailed => Ok(()),
1109        }
1110    }
1111
1112    async fn append_event(&self, session_id: &str, event: Event) -> Result<()> {
1113        SessionId::try_from(session_id)?;
1114        validate_path_segment("session_id", session_id)?;
1115
1116        let mut owners: Vec<(String, String)> = self
1117            .store
1118            .sessions_with_id(session_id)
1119            .await?
1120            .into_iter()
1121            .filter(|doc| doc.session_id == session_id)
1122            .map(|doc| (doc.app_name, doc.user_id))
1123            .collect();
1124        owners.sort();
1125        owners.dedup();
1126
1127        match owners.as_slice() {
1128            [] => Err(AdkError::not_found(
1129                ErrorComponent::Session,
1130                "session.not_found",
1131                format!("session '{session_id}' was not found"),
1132            )),
1133            [(app_name, user_id)] => self.append(app_name, user_id, session_id, event).await,
1134            _ => Err(AdkError::new(
1135                ErrorComponent::Session,
1136                ErrorCategory::InvalidInput,
1137                "session.ambiguous_id",
1138                format!(
1139                    "session ID '{session_id}' exists for more than one app or user; use \
1140                     append_event_for_identity to address the session unambiguously"
1141                ),
1142            )),
1143        }
1144    }
1145
1146    async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
1147        let app_name = req.identity.app_name.as_ref();
1148        let user_id = req.identity.user_id.as_ref();
1149        let session_id = req.identity.session_id.as_ref();
1150        validate_identity(app_name, user_id, session_id)?;
1151        self.append(app_name, user_id, session_id, req.event).await
1152    }
1153
1154    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
1155        // Sessions first, so a failure part-way leaves the tier for the repeated call.
1156        let sessions = self
1157            .list(ListRequest {
1158                app_name: app_name.to_string(),
1159                user_id: user_id.to_string(),
1160                limit: None,
1161                offset: None,
1162            })
1163            .await?;
1164
1165        for session in &sessions {
1166            self.delete(DeleteRequest {
1167                app_name: app_name.to_string(),
1168                user_id: user_id.to_string(),
1169                session_id: session.id().to_string(),
1170            })
1171            .await?;
1172        }
1173
1174        self.store.delete_user_state(app_name, user_id).await
1175    }
1176
1177    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
1178        Ok(self.load_history(identity).await?.1)
1179    }
1180
1181    async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
1182        let identity = &req.identity;
1183        let (app_name, user_id, session_id) =
1184            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
1185        for _ in 0..MAX_REWRITE_ATTEMPTS {
1186            let (doc, history, seqs) = self.load_history(identity).await?;
1187            let rewritten =
1188                history.rewrite(identity, &req.rewrite, req.expected_version.as_deref())?;
1189            let now = Utc::now();
1190            let put = rewritten
1191                .events
1192                .iter()
1193                .filter(|event| rewritten.change.replaced.contains(&event.id))
1194                .map(|event| {
1195                    Ok(EventDoc {
1196                        seq: seqs.get(&event.id).copied().flatten(),
1197                        ..event_to_doc(event)?
1198                    })
1199                })
1200                .collect::<Result<Vec<_>>>()?;
1201            let commit = SessionCommit {
1202                app_name: app_name.to_string(),
1203                user_id: user_id.to_string(),
1204                session_id: session_id.to_string(),
1205                guard: SessionGuard::Unchanged(Box::new(doc.clone())),
1206                session: SessionWrite::Put(SessionDoc {
1207                    state: rewritten.state.clone(),
1208                    updated_at: now,
1209                    ..doc
1210                }),
1211                app_state: None,
1212                user_state: None,
1213                event: None,
1214                events: EventWrites { remove: rewritten.change.removed.clone(), put },
1215            };
1216            match self.store.commit(commit).await? {
1217                CommitOutcome::Committed => {
1218                    let app_state = self.store.app_state(app_name).await?;
1219                    let user_state = self.store.user_state(app_name, user_id).await?;
1220                    let session = Box::new(FirestoreSession {
1221                        app_name: app_name.to_string(),
1222                        user_id: user_id.to_string(),
1223                        session_id: session_id.to_string(),
1224                        state: state_utils::merge_states(&app_state, &user_state, &rewritten.state),
1225                        events: rewritten.events,
1226                        updated_at: now,
1227                    });
1228                    return Ok(HistoryOutcome::new(session, rewritten.change));
1229                }
1230                CommitOutcome::GuardFailed => continue,
1231            }
1232        }
1233        Err(AdkError::new(
1234            ErrorComponent::Session,
1235            ErrorCategory::Unavailable,
1236            "session.firestore.history_contention",
1237            format!(
1238                "session '{session_id}' changed on each of {MAX_REWRITE_ATTEMPTS} rewrite \
1239                 attempts; retry the rewrite"
1240            ),
1241        ))
1242    }
1243
1244    async fn import_session(&self, req: ImportSessionRequest) -> Result<Box<dyn Session>> {
1245        let identity = &req.identity;
1246        let (app_name, user_id, session_id) =
1247            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
1248        validate_identity(app_name, user_id, session_id)?;
1249        let (_, _, state) = state_utils::extract_state_deltas(&req.state);
1250        let (_, _, initial_state) = state_utils::extract_state_deltas(&req.initial_state);
1251        let updated_at = req.events.last().map_or_else(Utc::now, |event| event.timestamp);
1252        let put = req
1253            .events
1254            .iter()
1255            .zip(1_i64..)
1256            .map(|(event, seq)| Ok(EventDoc { seq: Some(seq), ..event_to_doc(event)? }))
1257            .collect::<Result<Vec<_>>>()?;
1258        let commit = SessionCommit {
1259            app_name: app_name.to_string(),
1260            user_id: user_id.to_string(),
1261            session_id: session_id.to_string(),
1262            guard: SessionGuard::Absent,
1263            session: SessionWrite::Put(SessionDoc {
1264                app_name: app_name.to_string(),
1265                user_id: user_id.to_string(),
1266                session_id: session_id.to_string(),
1267                state: state.clone(),
1268                created_at: Utc::now(),
1269                updated_at,
1270                event_seq: i64::try_from(put.len()).unwrap_or(i64::MAX),
1271                initial_state: Some(initial_state),
1272            }),
1273            app_state: None,
1274            user_state: None,
1275            event: None,
1276            events: EventWrites { remove: Vec::new(), put },
1277        };
1278        match self.store.commit(commit).await? {
1279            CommitOutcome::Committed => {
1280                let app_state = self.store.app_state(app_name).await?;
1281                let user_state = self.store.user_state(app_name, user_id).await?;
1282                Ok(Box::new(FirestoreSession {
1283                    app_name: app_name.to_string(),
1284                    user_id: user_id.to_string(),
1285                    session_id: session_id.to_string(),
1286                    state: state_utils::merge_states(&app_state, &user_state, &state),
1287                    events: req.events,
1288                    updated_at,
1289                }))
1290            }
1291            CommitOutcome::GuardFailed => Err(session_already_exists(app_name, session_id)),
1292        }
1293    }
1294}
1295
1296// ---------------------------------------------------------------------------
1297// SessionService implementation
1298// ---------------------------------------------------------------------------
1299
1300#[async_trait]
1301impl SessionService for FirestoreSessionService {
1302    async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>> {
1303        self.core.create(req).await
1304    }
1305
1306    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
1307        self.core.get(req).await
1308    }
1309
1310    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
1311        self.core.list(req).await
1312    }
1313
1314    async fn delete(&self, req: DeleteRequest) -> Result<()> {
1315        self.core.delete(req).await
1316    }
1317
1318    async fn append_event(&self, session_id: &str, event: Event) -> Result<()> {
1319        self.core.append_event(session_id, event).await
1320    }
1321
1322    async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
1323        self.core.append_event_for_identity(req).await
1324    }
1325
1326    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
1327        self.core.delete_all_sessions(app_name, user_id).await
1328    }
1329
1330    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
1331        self.core.history(identity).await
1332    }
1333
1334    async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
1335        self.core.rewrite_history(req).await
1336    }
1337
1338    async fn import_session(&self, req: ImportSessionRequest) -> Result<Box<dyn Session>> {
1339        self.core.import_session(req).await
1340    }
1341}
1342
1343// ---------------------------------------------------------------------------
1344// FirestoreSession — implements Session, State, Events
1345// ---------------------------------------------------------------------------
1346
1347struct FirestoreSession {
1348    app_name: String,
1349    user_id: String,
1350    session_id: String,
1351    state: HashMap<String, Value>,
1352    events: Vec<Event>,
1353    updated_at: DateTime<Utc>,
1354}
1355
1356impl Session for FirestoreSession {
1357    fn id(&self) -> &str {
1358        &self.session_id
1359    }
1360
1361    fn app_name(&self) -> &str {
1362        &self.app_name
1363    }
1364
1365    fn user_id(&self) -> &str {
1366        &self.user_id
1367    }
1368
1369    fn state(&self) -> &dyn State {
1370        self
1371    }
1372
1373    fn events(&self) -> &dyn Events {
1374        self
1375    }
1376
1377    fn last_update_time(&self) -> DateTime<Utc> {
1378        self.updated_at
1379    }
1380
1381    fn take_events(&mut self) -> Vec<Event> {
1382        std::mem::take(&mut self.events)
1383    }
1384}
1385
1386impl State for FirestoreSession {
1387    fn get(&self, key: &str) -> Option<Value> {
1388        self.state.get(key).cloned()
1389    }
1390
1391    fn set(&mut self, key: String, value: Value) {
1392        if let Err(msg) = adk_core::validate_state_key(&key) {
1393            tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
1394            return;
1395        }
1396        self.state.insert(key, value);
1397    }
1398
1399    fn all(&self) -> HashMap<String, Value> {
1400        self.state.clone()
1401    }
1402}
1403
1404impl Events for FirestoreSession {
1405    fn all(&self) -> Vec<Event> {
1406        self.events.clone()
1407    }
1408
1409    fn len(&self) -> usize {
1410        self.events.len()
1411    }
1412
1413    fn at(&self, index: usize) -> Option<&Event> {
1414        self.events.get(index)
1415    }
1416}
1417
1418// ---------------------------------------------------------------------------
1419// Tests
1420//
1421// These exercise `SessionCore` over an in-memory `SessionStore` that models the Firestore
1422// layout: session documents keyed by `(app_name, session_id)` and event subcollections that
1423// outlive their parent document. `FirestoreStore` itself (transactional reads, write
1424// preconditions, collection-group queries, document paths) needs the Firestore emulator.
1425// ---------------------------------------------------------------------------
1426
1427#[cfg(test)]
1428mod tests {
1429    use super::*;
1430    use adk_core::identity::{AdkIdentity, AppName, UserId};
1431    use serde_json::json;
1432    use std::sync::Mutex;
1433
1434    type SessionKey = (String, String);
1435    type CommitHook = Box<dyn FnOnce(&mut FakeData) + Send>;
1436
1437    #[derive(Default)]
1438    struct FakeData {
1439        sessions: HashMap<SessionKey, SessionDoc>,
1440        events: HashMap<SessionKey, Vec<EventDoc>>,
1441        app_states: HashMap<String, AppStateDoc>,
1442        user_states: HashMap<SessionKey, UserStateDoc>,
1443    }
1444
1445    #[derive(Default)]
1446    struct FakeStore {
1447        data: Mutex<FakeData>,
1448        /// Runs once at the start of the next commit, to simulate a concurrent writer.
1449        before_commit: Mutex<Option<CommitHook>>,
1450    }
1451
1452    fn key(app_name: &str, session_id: &str) -> SessionKey {
1453        (app_name.to_string(), session_id.to_string())
1454    }
1455
1456    #[async_trait]
1457    impl SessionStore for FakeStore {
1458        async fn session(&self, app_name: &str, session_id: &str) -> Result<Option<SessionDoc>> {
1459            Ok(self.data.lock().unwrap().sessions.get(&key(app_name, session_id)).cloned())
1460        }
1461
1462        async fn sessions_with_id(&self, session_id: &str) -> Result<Vec<SessionDoc>> {
1463            let data = self.data.lock().unwrap();
1464            Ok(data.sessions.values().filter(|doc| doc.session_id == session_id).cloned().collect())
1465        }
1466
1467        async fn user_sessions(&self, app_name: &str, user_id: &str) -> Result<Vec<SessionDoc>> {
1468            let data = self.data.lock().unwrap();
1469            Ok(data
1470                .sessions
1471                .iter()
1472                .filter(|((app, _), doc)| app == app_name && doc.user_id == user_id)
1473                .map(|(_, doc)| doc.clone())
1474                .collect())
1475        }
1476
1477        async fn events(&self, app_name: &str, session_id: &str) -> Result<Vec<EventDoc>> {
1478            let data = self.data.lock().unwrap();
1479            let mut events =
1480                data.events.get(&key(app_name, session_id)).cloned().unwrap_or_default();
1481            // Firestore orders equal `timestamp` values by document ID, the event ID.
1482            events.sort_by(|a, b| a.timestamp.cmp(&b.timestamp).then_with(|| a.id.cmp(&b.id)));
1483            Ok(events)
1484        }
1485
1486        async fn app_state(&self, app_name: &str) -> Result<HashMap<String, Value>> {
1487            let data = self.data.lock().unwrap();
1488            Ok(data.app_states.get(app_name).map(|doc| doc.state.clone()).unwrap_or_default())
1489        }
1490
1491        async fn user_state(
1492            &self,
1493            app_name: &str,
1494            user_id: &str,
1495        ) -> Result<HashMap<String, Value>> {
1496            let data = self.data.lock().unwrap();
1497            Ok(data
1498                .user_states
1499                .get(&key(app_name, user_id))
1500                .map(|doc| doc.state.clone())
1501                .unwrap_or_default())
1502        }
1503
1504        async fn delete_user_state(&self, app_name: &str, user_id: &str) -> Result<()> {
1505            self.data.lock().unwrap().user_states.remove(&key(app_name, user_id));
1506            Ok(())
1507        }
1508
1509        async fn commit(&self, commit: SessionCommit) -> Result<CommitOutcome> {
1510            let hook = self.before_commit.lock().unwrap().take();
1511            let mut data = self.data.lock().unwrap();
1512            if let Some(hook) = hook {
1513                hook(&mut data);
1514            }
1515
1516            let session_key = key(&commit.app_name, &commit.session_id);
1517            if !commit.guard.holds(data.sessions.get(&session_key), &commit) {
1518                return Ok(CommitOutcome::GuardFailed);
1519            }
1520
1521            if commit.purges_events() {
1522                data.events.remove(&session_key);
1523            }
1524            match commit.session {
1525                SessionWrite::Put(doc) => {
1526                    data.sessions.insert(session_key.clone(), doc);
1527                }
1528                SessionWrite::Merge(merge) => {
1529                    let doc = data.sessions.get_mut(&session_key).expect("guarded by Owned");
1530                    doc.state = merge.apply(&doc.state, true);
1531                    doc.updated_at = merge.updated_at;
1532                    doc.event_seq += i64::from(commit.event.is_some());
1533                }
1534                SessionWrite::Delete => {
1535                    data.sessions.remove(&session_key);
1536                }
1537            }
1538            if let Some(merge) = commit.app_state {
1539                let stored = data.app_states.get(&commit.app_name).map(|doc| doc.state.clone());
1540                let state = merge.apply(&stored.unwrap_or_default(), false);
1541                data.app_states.insert(
1542                    commit.app_name.clone(),
1543                    AppStateDoc { state, updated_at: merge.updated_at },
1544                );
1545            }
1546            if let Some(merge) = commit.user_state {
1547                let user_key = key(&commit.app_name, &commit.user_id);
1548                let stored = data.user_states.get(&user_key).map(|doc| doc.state.clone());
1549                let state = merge.apply(&stored.unwrap_or_default(), false);
1550                data.user_states
1551                    .insert(user_key, UserStateDoc { state, updated_at: merge.updated_at });
1552            }
1553            let stored = data.events.entry(session_key.clone()).or_default();
1554            stored.retain(|event| !commit.events.remove.contains(&event.id));
1555            for event in commit.events.put {
1556                match stored.iter_mut().find(|stored| stored.id == event.id) {
1557                    Some(existing) => *existing = event,
1558                    None => stored.push(event),
1559                }
1560            }
1561            if let Some(event) = commit.event {
1562                let seq = data.sessions.get(&session_key).map(|doc| doc.event_seq);
1563                data.events.entry(session_key).or_default().push(EventDoc { seq, ..event });
1564            }
1565            Ok(CommitOutcome::Committed)
1566        }
1567    }
1568
1569    fn service() -> SessionCore<FakeStore> {
1570        SessionCore { store: FakeStore::default() }
1571    }
1572
1573    fn create_req(app: &str, user: &str, session: &str, state: Value) -> CreateRequest {
1574        CreateRequest {
1575            app_name: app.to_string(),
1576            user_id: user.to_string(),
1577            session_id: Some(session.to_string()),
1578            state: serde_json::from_value(state).unwrap(),
1579        }
1580    }
1581
1582    fn get_req(app: &str, user: &str, session: &str) -> GetRequest {
1583        GetRequest {
1584            app_name: app.to_string(),
1585            user_id: user.to_string(),
1586            session_id: session.to_string(),
1587            num_recent_events: None,
1588            after: None,
1589        }
1590    }
1591
1592    fn delete_req(app: &str, user: &str, session: &str) -> DeleteRequest {
1593        DeleteRequest {
1594            app_name: app.to_string(),
1595            user_id: user.to_string(),
1596            session_id: session.to_string(),
1597        }
1598    }
1599
1600    fn append_req(app: &str, user: &str, session: &str, event: Event) -> AppendEventRequest {
1601        AppendEventRequest {
1602            identity: AdkIdentity::new(
1603                AppName::try_from(app).unwrap(),
1604                UserId::try_from(user).unwrap(),
1605                SessionId::try_from(session).unwrap(),
1606            ),
1607            event,
1608        }
1609    }
1610
1611    fn event_with_delta(id: &str, delta: Value) -> Event {
1612        let mut event = Event::with_id(id, "inv-1");
1613        event.author = "agent".to_string();
1614        event.actions.state_delta = serde_json::from_value(delta).unwrap();
1615        event
1616    }
1617
1618    /// Snapshot of everything stored under one session path.
1619    fn stored(
1620        core: &SessionCore<FakeStore>,
1621        app: &str,
1622        session: &str,
1623    ) -> (Option<SessionDoc>, Vec<EventDoc>) {
1624        let data = core.store.data.lock().unwrap();
1625        (
1626            data.sessions.get(&key(app, session)).cloned(),
1627            data.events.get(&key(app, session)).cloned().unwrap_or_default(),
1628        )
1629    }
1630
1631    async fn alice_session_with_event(core: &SessionCore<FakeStore>) {
1632        core.create(create_req("app", "alice", "s1", json!({"secret": "alice-data"})))
1633            .await
1634            .unwrap();
1635        core.append_event_for_identity(append_req(
1636            "app",
1637            "alice",
1638            "s1",
1639            event_with_delta("e1", json!({"secret": "alice-updated"})),
1640        ))
1641        .await
1642        .unwrap();
1643    }
1644
1645    fn assert_error(error: &AdkError, category: ErrorCategory, code: &str) {
1646        assert_eq!((error.category, error.code), (category, code), "{error}");
1647    }
1648
1649    #[test]
1650    fn a_failure_firestore_reports_as_retryable_stays_retryable() {
1651        let failure = |retry_possible| {
1652            FirestoreError::DatabaseError(firestore::errors::FirestoreDatabaseError {
1653                public: firestore::errors::FirestoreErrorPublicGenericDetails {
1654                    code: "Aborted".to_string(),
1655                },
1656                details: "Transaction lock timeout.".to_string(),
1657                retry_possible,
1658            })
1659        };
1660        let retryable = firestore_error("commit failed", failure(true));
1661        assert_error(&retryable, ErrorCategory::Unavailable, RETRYABLE_CODE);
1662        assert!(retryable.is_retryable(), "{retryable:?}");
1663        assert_error(
1664            &firestore_error("commit failed", failure(false)),
1665            ErrorCategory::Internal,
1666            "session.legacy",
1667        );
1668    }
1669
1670    #[tokio::test]
1671    async fn create_rejects_a_session_id_owned_by_another_user() {
1672        let core = service();
1673        alice_session_with_event(&core).await;
1674        let before = stored(&core, "app", "s1");
1675
1676        let error = core
1677            .create(create_req("app", "bob", "s1", json!({"secret": "bob-data"})))
1678            .await
1679            .err()
1680            .expect("taking over another user's session id must fail");
1681        assert_error(&error, ErrorCategory::Conflict, "session.already_exists");
1682
1683        assert_eq!(stored(&core, "app", "s1"), before);
1684        let bob_get = core.get(get_req("app", "bob", "s1")).await.err().unwrap();
1685        assert_error(&bob_get, ErrorCategory::NotFound, "session.not_found");
1686    }
1687
1688    #[tokio::test]
1689    async fn create_rejects_a_duplicate_session_id_for_the_same_user() {
1690        let core = service();
1691        alice_session_with_event(&core).await;
1692        let before = stored(&core, "app", "s1");
1693
1694        let error = core
1695            .create(create_req("app", "alice", "s1", json!({})))
1696            .await
1697            .err()
1698            .expect("recreating an existing session must fail");
1699        assert_error(&error, ErrorCategory::Conflict, "session.already_exists");
1700        assert_eq!(stored(&core, "app", "s1"), before);
1701    }
1702
1703    #[tokio::test]
1704    async fn create_does_not_inherit_orphaned_events() {
1705        let core = service();
1706        let orphan = event_to_doc(&event_with_delta("orphan", json!({}))).unwrap();
1707        core.store.data.lock().unwrap().events.insert(key("app", "s1"), vec![orphan]);
1708
1709        core.create(create_req("app", "bob", "s1", json!({}))).await.unwrap();
1710
1711        let session = core.get(get_req("app", "bob", "s1")).await.unwrap();
1712        assert_eq!(session.events().len(), 0);
1713    }
1714
1715    #[tokio::test]
1716    async fn delete_by_another_user_leaves_the_session_untouched() {
1717        let core = service();
1718        alice_session_with_event(&core).await;
1719        let before = stored(&core, "app", "s1");
1720
1721        core.delete(delete_req("app", "bob", "s1")).await.unwrap();
1722        assert_eq!(stored(&core, "app", "s1"), before);
1723
1724        core.delete(delete_req("app", "alice", "s1")).await.unwrap();
1725        assert_eq!(stored(&core, "app", "s1"), (None, Vec::new()));
1726    }
1727
1728    #[tokio::test]
1729    async fn append_with_another_users_identity_is_not_found() {
1730        let core = service();
1731        alice_session_with_event(&core).await;
1732        let before = stored(&core, "app", "s1");
1733
1734        let error = core
1735            .append_event_for_identity(append_req(
1736                "app",
1737                "bob",
1738                "s1",
1739                event_with_delta("e2", json!({"secret": "bob-overwrite"})),
1740            ))
1741            .await
1742            .expect_err("appending to another user's session must fail");
1743        assert_error(&error, ErrorCategory::NotFound, "session.not_found");
1744        assert_eq!(stored(&core, "app", "s1"), before);
1745    }
1746
1747    #[tokio::test]
1748    async fn append_rechecks_ownership_inside_the_commit() {
1749        let core = service();
1750        core.create(create_req("app", "alice", "s1", json!({}))).await.unwrap();
1751
1752        // Between the ownership read and the commit, the session is deleted and recreated
1753        // by another user.
1754        let takeover = SessionDoc {
1755            app_name: "app".to_string(),
1756            user_id: "mallory".to_string(),
1757            session_id: "s1".to_string(),
1758            state: serde_json::from_value(json!({"owner": "mallory"})).unwrap(),
1759            created_at: Utc::now(),
1760            updated_at: Utc::now(),
1761            event_seq: 0,
1762            initial_state: None,
1763        };
1764        let replacement = takeover.clone();
1765        *core.store.before_commit.lock().unwrap() = Some(Box::new(move |data: &mut FakeData| {
1766            data.sessions.insert(key("app", "s1"), replacement);
1767        }));
1768
1769        let error = core
1770            .append_event_for_identity(append_req(
1771                "app",
1772                "alice",
1773                "s1",
1774                event_with_delta("e1", json!({"owner": "alice"})),
1775            ))
1776            .await
1777            .expect_err("a commit against a session that changed owner must fail");
1778        assert_error(&error, ErrorCategory::NotFound, "session.not_found");
1779        assert_eq!(stored(&core, "app", "s1"), (Some(takeover), Vec::new()));
1780    }
1781
1782    #[tokio::test]
1783    async fn legacy_append_event_resolves_the_unique_owner() {
1784        let core = service();
1785        core.create(create_req("app", "alice", "s1", json!({}))).await.unwrap();
1786
1787        core.append_event("s1", event_with_delta("e1", json!({"k": 1}))).await.unwrap();
1788        let session = core.get(get_req("app", "alice", "s1")).await.unwrap();
1789        assert_eq!(session.state().all(), serde_json::from_value(json!({"k": 1})).unwrap());
1790        assert_eq!(session.events().len(), 1);
1791
1792        let missing = core.append_event("missing", Event::new("inv")).await.err().unwrap();
1793        assert_error(&missing, ErrorCategory::NotFound, "session.not_found");
1794
1795        core.create(create_req("other_app", "bob", "s1", json!({}))).await.unwrap();
1796        let ambiguous = core.append_event("s1", Event::new("inv")).await.err().unwrap();
1797        assert_error(&ambiguous, ErrorCategory::InvalidInput, "session.ambiguous_id");
1798    }
1799
1800    #[tokio::test]
1801    async fn events_with_equal_timestamps_read_back_in_append_order() {
1802        let core = service();
1803        core.create(create_req("app", "alice", "s1", json!({}))).await.unwrap();
1804        let at = Utc::now();
1805        // Document IDs sort opposite to the append order.
1806        let ids = ["e-c", "e-b", "e-a"];
1807        for id in ids {
1808            let mut event = event_with_delta(id, json!({}));
1809            event.timestamp = at;
1810            core.append_event_for_identity(append_req("app", "alice", "s1", event)).await.unwrap();
1811        }
1812
1813        let session = core.get(get_req("app", "alice", "s1")).await.unwrap();
1814        let read: Vec<String> = session.events().all().into_iter().map(|event| event.id).collect();
1815        assert_eq!(read, ids);
1816    }
1817
1818    #[tokio::test]
1819    async fn list_orders_equal_update_times_by_session_id_descending() {
1820        let core = service();
1821        let at = Utc::now();
1822        for session in ["s1", "s3", "s2"] {
1823            core.create(create_req("app", "alice", session, json!({}))).await.unwrap();
1824            let mut event = event_with_delta(&format!("{session}-e"), json!({}));
1825            event.timestamp = at;
1826            core.append_event_for_identity(append_req("app", "alice", session, event))
1827                .await
1828                .unwrap();
1829        }
1830
1831        let listed = core
1832            .list(ListRequest {
1833                app_name: "app".to_string(),
1834                user_id: "alice".to_string(),
1835                limit: None,
1836                offset: None,
1837            })
1838            .await
1839            .unwrap();
1840        let ids: Vec<&str> = listed.iter().map(|session| session.id()).collect();
1841        assert_eq!(ids, ["s3", "s2", "s1"]);
1842    }
1843
1844    #[tokio::test]
1845    async fn list_and_delete_all_are_scoped_to_the_caller() {
1846        let core = service();
1847        for (app, user, session) in [
1848            ("app", "alice", "a1"),
1849            ("app", "alice", "a2"),
1850            ("app", "bob", "b1"),
1851            ("other_app", "alice", "a3"),
1852        ] {
1853            let state = json!({ "user:lang": format!("{app}/{user}"), "app:theme": app });
1854            core.create(create_req(app, user, session, state)).await.unwrap();
1855        }
1856        // A document stored under `app` that claims to belong to another app.
1857        let forged = SessionDoc {
1858            app_name: "elsewhere".to_string(),
1859            user_id: "alice".to_string(),
1860            session_id: "forged".to_string(),
1861            state: HashMap::new(),
1862            created_at: Utc::now(),
1863            updated_at: Utc::now(),
1864            event_seq: 0,
1865            initial_state: None,
1866        };
1867        core.store.data.lock().unwrap().sessions.insert(key("app", "forged"), forged);
1868
1869        let list = |app: &'static str, user: &'static str| {
1870            let core = &core;
1871            async move {
1872                let mut ids: Vec<String> = core
1873                    .list(ListRequest {
1874                        app_name: app.to_string(),
1875                        user_id: user.to_string(),
1876                        limit: None,
1877                        offset: None,
1878                    })
1879                    .await
1880                    .unwrap()
1881                    .iter()
1882                    .map(|session| session.id().to_string())
1883                    .collect();
1884                ids.sort();
1885                ids
1886            }
1887        };
1888        assert_eq!(list("app", "alice").await, vec!["a1", "a2"]);
1889
1890        core.delete_all_sessions("app", "alice").await.unwrap();
1891        assert_eq!(list("app", "alice").await, Vec::<String>::new());
1892        assert_eq!(list("app", "bob").await, vec!["b1"]);
1893        assert_eq!(list("other_app", "alice").await, vec!["a3"]);
1894        // Alice's user tier in `app` goes with her sessions; every other tier stays.
1895        assert_eq!(core.store.user_state("app", "alice").await.unwrap(), HashMap::new());
1896        assert_eq!(core.store.user_state("app", "bob").await.unwrap()["lang"], json!("app/bob"));
1897        let elsewhere = core.store.user_state("other_app", "alice").await.unwrap();
1898        assert_eq!(elsewhere["lang"], json!("other_app/alice"));
1899        assert_eq!(core.store.app_state("app").await.unwrap()["theme"], json!("app"));
1900        core.delete_all_sessions("app", "alice").await.unwrap();
1901    }
1902
1903    #[tokio::test]
1904    async fn state_tiers_round_trip_through_create_append_and_get() {
1905        let core = service();
1906        core.create(create_req(
1907            "app",
1908            "alice",
1909            "s1",
1910            json!({"app:theme": "dark", "user:lang": "sw", "k": 1, "temp:scratch": true}),
1911        ))
1912        .await
1913        .unwrap();
1914        core.append_event_for_identity(append_req(
1915            "app",
1916            "alice",
1917            "s1",
1918            event_with_delta("e1", json!({"k": 2, "user:lang": "en", "temp:x": 1})),
1919        ))
1920        .await
1921        .unwrap();
1922
1923        let session = core.get(get_req("app", "alice", "s1")).await.unwrap();
1924        assert_eq!(
1925            session.state().all(),
1926            serde_json::from_value::<HashMap<String, Value>>(
1927                json!({"app:theme": "dark", "user:lang": "en", "k": 2})
1928            )
1929            .unwrap()
1930        );
1931        let delta = session.events().at(0).unwrap().actions.state_delta.clone();
1932        assert_eq!(
1933            delta,
1934            serde_json::from_value::<HashMap<String, Value>>(json!({"k": 2, "user:lang": "en"}))
1935                .unwrap()
1936        );
1937    }
1938
1939    #[tokio::test]
1940    async fn get_and_list_serve_the_current_shared_tiers() {
1941        let core = service();
1942        core.create(create_req("app", "alice", "s1", json!({"app:theme": "light", "k": 1})))
1943            .await
1944            .unwrap();
1945        core.create(create_req("app", "alice", "s2", json!({}))).await.unwrap();
1946        core.append_event_for_identity(append_req(
1947            "app",
1948            "alice",
1949            "s2",
1950            event_with_delta("e1", json!({"app:theme": "dark", "user:lang": "fr"})),
1951        ))
1952        .await
1953        .unwrap();
1954
1955        let expected: HashMap<String, Value> =
1956            serde_json::from_value(json!({"app:theme": "dark", "user:lang": "fr", "k": 1}))
1957                .unwrap();
1958        let session = core.get(get_req("app", "alice", "s1")).await.unwrap();
1959        assert_eq!(session.state().all(), expected);
1960
1961        let listed = core
1962            .list(ListRequest {
1963                app_name: "app".to_string(),
1964                user_id: "alice".to_string(),
1965                limit: None,
1966                offset: None,
1967            })
1968            .await
1969            .unwrap();
1970        let listed = listed.iter().find(|session| session.id() == "s1").unwrap();
1971        assert_eq!(listed.state().all(), expected);
1972    }
1973
1974    #[tokio::test]
1975    async fn append_keeps_keys_a_concurrent_writer_committed_first() {
1976        let core = service();
1977        core.create(create_req("app", "alice", "s1", json!({}))).await.unwrap();
1978
1979        // Between the append's ownership read and its commit, another writer commits its
1980        // own key to every tier.
1981        *core.store.before_commit.lock().unwrap() = Some(Box::new(|data: &mut FakeData| {
1982            let theirs: HashMap<String, Value> = HashMap::from([("theirs".to_string(), json!(1))]);
1983            data.app_states.insert(
1984                "app".to_string(),
1985                AppStateDoc { state: theirs.clone(), updated_at: Utc::now() },
1986            );
1987            data.user_states.insert(
1988                key("app", "alice"),
1989                UserStateDoc { state: theirs.clone(), updated_at: Utc::now() },
1990            );
1991            data.sessions.get_mut(&key("app", "s1")).unwrap().state = theirs;
1992        }));
1993
1994        core.append_event_for_identity(append_req(
1995            "app",
1996            "alice",
1997            "s1",
1998            event_with_delta("e1", json!({"app:mine": 2, "user:mine": 2, "mine": 2})),
1999        ))
2000        .await
2001        .unwrap();
2002
2003        let session = core.get(get_req("app", "alice", "s1")).await.unwrap();
2004        assert_eq!(
2005            session.state().all(),
2006            serde_json::from_value::<HashMap<String, Value>>(json!({
2007                "app:theirs": 1, "app:mine": 2,
2008                "user:theirs": 1, "user:mine": 2,
2009                "theirs": 1, "mine": 2,
2010            }))
2011            .unwrap()
2012        );
2013    }
2014
2015    #[tokio::test]
2016    async fn identifiers_that_are_not_single_document_ids_are_rejected() {
2017        let core = service();
2018        let error =
2019            core.create(create_req("app", "alice", "s1/events/e1", json!({}))).await.err().unwrap();
2020        assert_error(&error, ErrorCategory::InvalidInput, "session.firestore.invalid_identifier");
2021
2022        for bad in ["", "a/b", ".", "..", "__reserved__"] {
2023            let error = validate_path_segment("user_id", bad).err().unwrap();
2024            assert_error(
2025                &error,
2026                ErrorCategory::InvalidInput,
2027                "session.firestore.invalid_identifier",
2028            );
2029        }
2030        validate_path_segment("user_id", "alice@example.com").unwrap();
2031    }
2032
2033    #[test]
2034    fn undecodable_event_documents_are_skipped() {
2035        let good = event_to_doc(&event_with_delta("good", json!({}))).unwrap();
2036        let bad = EventDoc { id: "bad".to_string(), actions: json!("not actions"), ..good.clone() };
2037
2038        let events = decode_event_docs(&[bad, good], "s1");
2039        let ids: Vec<&str> = events.iter().map(|event| event.id.as_str()).collect();
2040        assert_eq!(ids, vec!["good"]);
2041    }
2042
2043    fn identity(app: &str, user: &str, session: &str) -> AdkIdentity {
2044        AdkIdentity::new(
2045            AppName::try_from(app).unwrap(),
2046            UserId::try_from(user).unwrap(),
2047            SessionId::try_from(session).unwrap(),
2048        )
2049    }
2050
2051    async fn three_events(core: &SessionCore<FakeStore>) -> Vec<String> {
2052        core.create(create_req("app", "alice", "s1", json!({"tier": "gold"}))).await.unwrap();
2053        let mut ids = Vec::new();
2054        for n in 0..3 {
2055            let mut event =
2056                event_with_delta(&format!("e{n}"), json!({"step": n, "tier": "silver"}));
2057            event.timestamp = Utc::now() + chrono::Duration::milliseconds(n);
2058            ids.push(event.id.clone());
2059            core.append_event_for_identity(append_req("app", "alice", "s1", event)).await.unwrap();
2060        }
2061        ids
2062    }
2063
2064    #[tokio::test]
2065    async fn history_rewrites_delete_and_replace_event_documents() {
2066        let core = service();
2067        let ids = three_events(&core).await;
2068        let alice = identity("app", "alice", "s1");
2069
2070        let rewound = core.rewind(&alice, &ids[1]).await.unwrap();
2071        assert_eq!(rewound.state().get("step"), Some(json!(1)));
2072        let stored: Vec<String> = core.store.data.lock().unwrap().events[&key("app", "s1")]
2073            .iter()
2074            .map(|event| event.id.clone())
2075            .collect();
2076        assert_eq!(stored, ids[..2]);
2077
2078        let mut replacement = event_with_delta(&ids[0], json!({"step": 7}));
2079        replacement.author = "editor".into();
2080        let edited = core
2081            .rewrite_history(RewriteHistoryRequest::new(
2082                alice.clone(),
2083                crate::HistoryRewrite::Edit {
2084                    edits: vec![crate::HistoryEdit::Replace { event: Box::new(replacement) }],
2085                },
2086            ))
2087            .await
2088            .unwrap();
2089        assert_eq!(edited.session.state().get("step"), Some(json!(1)), "e1 still writes last");
2090        let reread = core.get(get_req("app", "alice", "s1")).await.unwrap();
2091        assert_eq!(reread.events().all()[0].author, "editor");
2092        assert_eq!(reread.events().len(), 2);
2093
2094        let emptied = core.rewind_steps(&alice, 2).await.unwrap();
2095        assert_eq!((emptied.events().len(), emptied.state().get("tier")), (0, Some(json!("gold"))));
2096    }
2097
2098    #[tokio::test]
2099    async fn a_rewrite_racing_an_append_plans_again_and_keeps_the_append() {
2100        let core = service();
2101        let ids = three_events(&core).await;
2102        let mut late = event_with_delta("late", json!({"step": 9}));
2103        late.timestamp = Utc::now() + chrono::Duration::days(1);
2104        let late_doc = EventDoc { seq: Some(4), ..event_to_doc(&late).unwrap() };
2105        *core.store.before_commit.lock().unwrap() = Some(Box::new(move |data: &mut FakeData| {
2106            let doc = data.sessions.get_mut(&key("app", "s1")).unwrap();
2107            doc.event_seq += 1;
2108            doc.updated_at = Utc::now();
2109            data.events.get_mut(&key("app", "s1")).unwrap().push(late_doc);
2110        }));
2111
2112        let edited = core
2113            .rewrite_history(RewriteHistoryRequest::new(
2114                identity("app", "alice", "s1"),
2115                crate::HistoryRewrite::Edit {
2116                    edits: vec![crate::HistoryEdit::Remove { event_id: ids[0].clone() }],
2117                },
2118            ))
2119            .await
2120            .unwrap();
2121        let kept: Vec<String> = edited.session.events().all().into_iter().map(|e| e.id).collect();
2122        assert_eq!(kept, [ids[1].clone(), ids[2].clone(), "late".to_string()]);
2123    }
2124
2125    #[tokio::test]
2126    async fn a_fork_imports_events_and_refuses_a_taken_id() {
2127        let core = service();
2128        let ids = three_events(&core).await;
2129        let fork = core
2130            .fork(
2131                crate::ForkRequest::new(identity("app", "alice", "s1"))
2132                    .at_event(&ids[0])
2133                    .with_session_id("s2"),
2134            )
2135            .await
2136            .unwrap();
2137        assert_eq!(
2138            (fork.session.events().len(), fork.session.state().get("step")),
2139            (1, Some(json!(0)))
2140        );
2141        let doc = core.store.data.lock().unwrap().sessions[&key("app", "s2")].clone();
2142        assert_eq!(doc.event_seq, 1);
2143        assert!(doc.initial_state.unwrap().contains_key(crate::FORK_ORIGIN_KEY));
2144        let taken = core
2145            .fork(crate::ForkRequest::new(identity("app", "alice", "s1")).with_session_id("s2"))
2146            .await
2147            .err()
2148            .unwrap();
2149        assert_error(&taken, ErrorCategory::Conflict, "session.already_exists");
2150    }
2151
2152    #[test]
2153    fn layout_paths_are_document_paths() {
2154        assert_eq!(app_state_path("root", "app"), "root/app/app_state/current");
2155        assert_eq!(user_state_path("root", "app", "alice"), "root/app/users/alice/state/current");
2156        assert_eq!(session_path("root", "app", "s1"), "root/app/sessions/s1");
2157        assert_eq!(event_path("root", "app", "s1", "e1"), "root/app/sessions/s1/events/e1");
2158    }
2159}