adk-session 3.0.0

Session management and state persistence for Rust Agent Development Kit (ADK-Rust) agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
//! Firestore session service backend.
//!
//! Provides [`FirestoreSessionService`] for session persistence using Google Cloud Firestore.
//! Enabled via the `firestore` feature flag.
//!
//! # Data Organization
//!
//! Firestore uses subcollections to organize session data:
//!
//! - Session: `{root}/{app_name}/sessions/{session_id}`
//! - Event: `{root}/{app_name}/sessions/{session_id}/events/{event_id}`
//! - App state: `{root}/{app_name}/app_state/current`
//! - User state: `{root}/{app_name}/users/{user_id}/state/current`
//!
//! # Tenant Isolation
//!
//! A session document is addressed by `(app_name, session_id)`; the owning `user_id` is a
//! field of the document. Every operation that addresses a session checks that the document's
//! `app_name`, `user_id`, and `session_id` match the request, and every write re-reads the
//! document inside its transaction before applying anything:
//!
//! | Operation | Session missing, or owned by another user |
//! |-----------|-------------------------------------------|
//! | `create` | Fails with `session.already_exists` (`Conflict`) when the ID is taken in the app |
//! | `get`, `append_event_for_identity` | Fails with `session.not_found` |
//! | `delete` | No-op, identical to deleting a missing session |
//! | `list`, `delete_all_sessions` | Only the caller's own sessions are returned or removed; `delete_all_sessions` then deletes the user's state document |
//!
//! A new session never inherits events: `create` removes any events left under its path.
//! App names, user IDs, and session IDs are document IDs, so they must not contain `/`.

use crate::history::{HistoryOutcome, ImportSessionRequest, RewriteHistoryRequest, SessionHistory};
use crate::service::session_not_found_for;
use crate::{
    AppendEventRequest, CreateRequest, DeleteRequest, Event, Events, GetRequest, KEY_PREFIX_TEMP,
    ListRequest, Session, SessionService, State, state_utils,
};
use adk_core::identity::{AdkIdentity, SessionId};
use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use firestore::errors::FirestoreError;
use firestore::*;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use uuid::Uuid;

const DEFAULT_ROOT_COLLECTION: &str = "adk_sessions";
const SESSIONS_COLLECTION: &str = "sessions";
const EVENTS_COLLECTION: &str = "events";
const APP_STATE_COLLECTION: &str = "app_state";
const USERS_COLLECTION: &str = "users";
const USER_STATE_COLLECTION: &str = "state";
const STATE_DOCUMENT_ID: &str = "current";
/// Attempts a history rewrite makes before giving up on a session that keeps changing between
/// the read and the commit.
const MAX_REWRITE_ATTEMPTS: usize = 16;

/// Configuration for connecting to Firestore.
///
/// # Example
///
/// ```rust,ignore
/// use adk_session::FirestoreSessionConfig;
///
/// let config = FirestoreSessionConfig {
///     project_id: "my-gcp-project".to_string(),
///     root_collection: None, // defaults to "adk_sessions"
/// };
/// ```
pub struct FirestoreSessionConfig {
    /// Google Cloud project ID.
    pub project_id: String,
    /// Root collection prefix for namespacing session data.
    /// Defaults to `"adk_sessions"` when `None`.
    pub root_collection: Option<String>,
}

/// Firestore-backed session service implementing [`SessionService`].
///
/// Uses Google Cloud Firestore with Application Default Credentials for authentication.
/// Data is organized using subcollections under a configurable root collection. See the
/// [module documentation](self) for the layout and the tenant-isolation guarantees.
pub struct FirestoreSessionService {
    core: SessionCore<FirestoreStore>,
}

impl FirestoreSessionService {
    /// Connect to Firestore using Application Default Credentials.
    ///
    /// Returns an error with "firestore connection failed" context if the connection cannot
    /// be established.
    ///
    /// # Arguments
    ///
    /// * `config` - Firestore connection configuration including project ID and optional
    ///   root collection prefix.
    pub async fn new(config: FirestoreSessionConfig) -> Result<Self> {
        let root_collection =
            config.root_collection.unwrap_or_else(|| DEFAULT_ROOT_COLLECTION.to_string());
        let db = FirestoreDb::new(&config.project_id)
            .await
            .map_err(|e| AdkError::session(format!("firestore connection failed: {e}")))?;
        Ok(Self { core: SessionCore { store: FirestoreStore { db, root_collection } } })
    }

    /// Uses an existing client, such as one the durable stores share or one from
    /// [`connect_firestore_emulator`](crate::firestore_stores::connect_firestore_emulator).
    ///
    /// `root_collection` defaults to `"adk_sessions"` when `None`.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use adk_session::FirestoreSessionService;
    /// use adk_session::firestore_stores::connect_firestore_emulator;
    ///
    /// # async fn example() -> adk_core::Result<()> {
    /// let db = connect_firestore_emulator("demo-project").await?;
    /// let sessions = FirestoreSessionService::from_db(db, None);
    /// assert_eq!(sessions.root_collection(), "adk_sessions");
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_db(db: FirestoreDb, root_collection: Option<String>) -> Self {
        let root_collection =
            root_collection.unwrap_or_else(|| DEFAULT_ROOT_COLLECTION.to_string());
        Self { core: SessionCore { store: FirestoreStore { db, root_collection } } }
    }

    /// Returns a reference to the underlying `FirestoreDb`.
    pub fn db(&self) -> &FirestoreDb {
        &self.core.store.db
    }

    /// Returns the root collection prefix.
    pub fn root_collection(&self) -> &str {
        &self.core.store.root_collection
    }
}

/// Generate the Firestore document path for a session.
///
/// Path format: `{root}/{app_name}/sessions/{session_id}`
pub fn session_path(root: &str, app_name: &str, session_id: &str) -> String {
    format!("{root}/{app_name}/{SESSIONS_COLLECTION}/{session_id}")
}

/// Generate the Firestore document path for an event within a session.
///
/// Path format: `{root}/{app_name}/sessions/{session_id}/events/{event_id}`
pub fn event_path(root: &str, app_name: &str, session_id: &str, event_id: &str) -> String {
    format!("{root}/{app_name}/{SESSIONS_COLLECTION}/{session_id}/{EVENTS_COLLECTION}/{event_id}")
}

/// Generate the Firestore document path for app-level state.
///
/// Path format: `{root}/{app_name}/app_state/current`
pub fn app_state_path(root: &str, app_name: &str) -> String {
    format!("{root}/{app_name}/{APP_STATE_COLLECTION}/{STATE_DOCUMENT_ID}")
}

/// Generate the Firestore document path for user-level state.
///
/// Path format: `{root}/{app_name}/users/{user_id}/state/current`
pub fn user_state_path(root: &str, app_name: &str, user_id: &str) -> String {
    format!(
        "{root}/{app_name}/{USERS_COLLECTION}/{user_id}/{USER_STATE_COLLECTION}/{STATE_DOCUMENT_ID}"
    )
}

// ---------------------------------------------------------------------------
// Firestore document models
// ---------------------------------------------------------------------------

/// Firestore document for a session.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct SessionDoc {
    app_name: String,
    user_id: String,
    session_id: String,
    state: HashMap<String, Value>,
    #[serde(with = "firestore::serialize_as_timestamp")]
    created_at: DateTime<Utc>,
    #[serde(with = "firestore::serialize_as_timestamp")]
    updated_at: DateTime<Utc>,
    /// Appends so far; the next event's `seq`.
    #[serde(default)]
    event_seq: i64,
    /// The session state the session was created with; absent on sessions created by
    /// earlier releases.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    initial_state: Option<HashMap<String, Value>>,
}

/// Firestore document for an event.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct EventDoc {
    id: String,
    invocation_id: String,
    branch: String,
    author: String,
    #[serde(with = "firestore::serialize_as_timestamp")]
    timestamp: DateTime<Utc>,
    llm_response: Value,
    actions: Value,
    long_running_tool_ids: Value,
    /// Position among the session's appends; orders events with equal timestamps. Absent on
    /// events written by earlier releases.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    seq: Option<i64>,
}

/// Firestore document for app-level state.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct AppStateDoc {
    state: HashMap<String, Value>,
    #[serde(with = "firestore::serialize_as_timestamp")]
    updated_at: DateTime<Utc>,
}

/// Firestore document for user-level state.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct UserStateDoc {
    state: HashMap<String, Value>,
    #[serde(with = "firestore::serialize_as_timestamp")]
    updated_at: DateTime<Utc>,
}

// ---------------------------------------------------------------------------
// Helpers: Event <-> EventDoc, identity checks, errors
// ---------------------------------------------------------------------------

fn event_to_doc(event: &Event) -> Result<EventDoc> {
    let llm_response = serde_json::to_value(&event.llm_response)
        .map_err(|e| AdkError::session(format!("serialize failed: {e}")))?;
    let actions = serde_json::to_value(&event.actions)
        .map_err(|e| AdkError::session(format!("serialize failed: {e}")))?;
    let long_running_tool_ids = serde_json::to_value(&event.long_running_tool_ids)
        .map_err(|e| AdkError::session(format!("serialize failed: {e}")))?;

    Ok(EventDoc {
        id: event.id.clone(),
        invocation_id: event.invocation_id.clone(),
        branch: event.branch.clone(),
        author: event.author.clone(),
        timestamp: event.timestamp,
        llm_response,
        actions,
        long_running_tool_ids,
        seq: None,
    })
}

fn doc_to_event(doc: &EventDoc) -> std::result::Result<Event, serde_json::Error> {
    Ok(Event {
        id: doc.id.clone(),
        timestamp: doc.timestamp,
        invocation_id: doc.invocation_id.clone(),
        branch: doc.branch.clone(),
        author: doc.author.clone(),
        llm_request: None,
        llm_response: serde_json::from_value(doc.llm_response.clone())?,
        actions: serde_json::from_value(doc.actions.clone())?,
        long_running_tool_ids: serde_json::from_value(doc.long_running_tool_ids.clone())?,
        provider_metadata: HashMap::new(),
    })
}

/// Converts stored event documents, logging and skipping any that no longer deserialize
/// so one corrupt event does not hide the rest of the session history.
fn decode_event_docs(docs: &[EventDoc], session_id: &str) -> Vec<Event> {
    docs.iter()
        .filter_map(|doc| match doc_to_event(doc) {
            Ok(event) => Some(event),
            Err(error) => {
                tracing::warn!(
                    session.id = %session_id,
                    event.id = %doc.id,
                    error = %error,
                    "skipping stored event that failed to deserialize"
                );
                None
            }
        })
        .collect()
}

/// Returns `true` when `doc` is the session addressed by `(app_name, user_id, session_id)`.
fn is_owned_by(doc: &SessionDoc, app_name: &str, user_id: &str, session_id: &str) -> bool {
    doc.app_name == app_name && doc.user_id == user_id && doc.session_id == session_id
}

/// Rejects identifiers that cannot be used as a single Firestore document ID.
fn validate_path_segment(kind: &str, value: &str) -> Result<()> {
    let reserved = value.len() >= 4 && value.starts_with("__") && value.ends_with("__");
    if value.is_empty() || value.contains('/') || value == "." || value == ".." || reserved {
        return Err(AdkError::new(
            ErrorComponent::Session,
            ErrorCategory::InvalidInput,
            "session.firestore.invalid_identifier",
            format!(
                "{kind} '{value}' cannot be used as a Firestore document ID; it must be \
                 non-empty, must not contain '/', and must not be '.', '..' or match '__.*__'"
            ),
        ));
    }
    Ok(())
}

fn validate_identity(app_name: &str, user_id: &str, session_id: &str) -> Result<()> {
    validate_path_segment("app_name", app_name)?;
    validate_path_segment("user_id", user_id)?;
    validate_path_segment("session_id", session_id)
}

fn session_already_exists(app_name: &str, session_id: &str) -> AdkError {
    AdkError::new(
        ErrorComponent::Session,
        ErrorCategory::Conflict,
        "session.already_exists",
        format!(
            "session '{session_id}' already exists in app '{app_name}'; omit session_id to \
             generate a new one or choose a different ID"
        ),
    )
}

/// Maps a Firestore failure, keeping whether Firestore reported it as retryable, such as a
/// transaction aborted by contention.
fn firestore_error(context: &str, error: FirestoreError) -> AdkError {
    if crate::firestore_stores::is_retryable(&error) {
        return AdkError::new(
            ErrorComponent::Session,
            ErrorCategory::Unavailable,
            RETRYABLE_CODE,
            format!("{context}: {error}"),
        );
    }
    AdkError::session(format!("{context}: {error}"))
}

/// Code of a Firestore failure that Firestore reported as retryable.
const RETRYABLE_CODE: &str = "session.firestore.retryable";

// ---------------------------------------------------------------------------
// Storage abstraction
//
// `SessionStore` isolates the handful of Firestore calls the service makes, so the
// ownership and precondition logic in `SessionCore` is unit-tested against an in-memory
// store. `FirestoreStore` is the production implementation.
// ---------------------------------------------------------------------------

/// Precondition the store re-checks inside the write transaction before applying a commit.
#[derive(Debug, Clone, PartialEq)]
enum SessionGuard {
    /// The session document must not exist.
    Absent,
    /// The session document must exist and match the commit's app, user, and session ID.
    Owned,
    /// The session document must still be this one, the one a history rewrite was planned
    /// from. Every append changes `event_seq` and `updated_at`, so an append in between fails
    /// it.
    Unchanged(Box<SessionDoc>),
}

impl SessionGuard {
    /// Whether the guard holds for the document `current` read inside the transaction.
    fn holds(&self, current: Option<&SessionDoc>, commit: &SessionCommit) -> bool {
        match self {
            Self::Absent => current.is_none(),
            Self::Owned => current.is_some_and(|doc| {
                is_owned_by(doc, &commit.app_name, &commit.user_id, &commit.session_id)
            }),
            Self::Unchanged(expected) => current == Some(expected.as_ref()),
        }
    }
}

/// Event documents a history rewrite or an import writes and deletes.
#[derive(Debug, Clone, PartialEq, Default)]
struct EventWrites {
    /// IDs of the event documents to delete.
    remove: Vec<String>,
    /// Event documents to write, replacing any with the same ID; each carries its `seq`.
    put: Vec<EventDoc>,
}

/// What a commit does to the session document.
#[derive(Debug, Clone, PartialEq)]
enum SessionWrite {
    /// Write the document, replacing the current one.
    Put(SessionDoc),
    /// Merge keys into the session state of the document read inside the transaction.
    Merge(StateMerge),
    /// Delete the document together with its `events` subcollection.
    Delete,
}

/// Keys merged into a stored state map inside the commit transaction, so a concurrent
/// writer's keys are read and kept rather than overwritten.
#[derive(Debug, Clone, PartialEq)]
struct StateMerge {
    delta: HashMap<String, Value>,
    updated_at: DateTime<Utc>,
}

impl StateMerge {
    /// Returns `None` for an empty delta, which leaves the stored document untouched.
    fn non_empty(delta: HashMap<String, Value>, updated_at: DateTime<Utc>) -> Option<Self> {
        (!delta.is_empty()).then_some(Self { delta, updated_at })
    }

    /// Applies the merge to `stored`.
    ///
    /// Session documents written by earlier releases also hold a copy of the app and user
    /// tiers; `session_tier` drops it.
    fn apply(&self, stored: &HashMap<String, Value>, session_tier: bool) -> HashMap<String, Value> {
        let mut state =
            if session_tier { state_utils::extract_state_deltas(stored).2 } else { stored.clone() };
        state.extend(self.delta.clone());
        state
    }
}

/// One atomic write against a single session, applied by [`SessionStore::commit`].
#[derive(Debug, Clone, PartialEq)]
struct SessionCommit {
    app_name: String,
    user_id: String,
    session_id: String,
    guard: SessionGuard,
    session: SessionWrite,
    app_state: Option<StateMerge>,
    user_state: Option<StateMerge>,
    event: Option<EventDoc>,
    /// History rewrites and imports: events written and deleted as they are.
    events: EventWrites,
}

impl SessionCommit {
    /// Whether the commit removes the events stored under the session path: a create
    /// clears orphans so the new session starts empty, and a delete removes them all.
    fn purges_events(&self) -> bool {
        match (&self.guard, &self.session) {
            (SessionGuard::Absent, _) | (_, SessionWrite::Delete) => true,
            (
                SessionGuard::Owned | SessionGuard::Unchanged(_),
                SessionWrite::Put(_) | SessionWrite::Merge(_),
            ) => false,
        }
    }
}

/// Result of [`SessionStore::commit`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CommitOutcome {
    /// Every write was applied.
    Committed,
    /// The guard did not hold; nothing was written.
    GuardFailed,
}

/// The Firestore operations the session service relies on.
#[async_trait]
trait SessionStore: Send + Sync {
    /// Reads the session document at `{root}/{app_name}/sessions/{session_id}`.
    async fn session(&self, app_name: &str, session_id: &str) -> Result<Option<SessionDoc>>;
    /// Finds session documents whose `session_id` field matches, across every app.
    async fn sessions_with_id(&self, session_id: &str) -> Result<Vec<SessionDoc>>;
    /// Lists the session documents in `app_name` whose `user_id` field matches.
    async fn user_sessions(&self, app_name: &str, user_id: &str) -> Result<Vec<SessionDoc>>;
    /// Reads a session's event documents ordered by timestamp.
    async fn events(&self, app_name: &str, session_id: &str) -> Result<Vec<EventDoc>>;
    /// Reads app-level state, empty when none has been written.
    async fn app_state(&self, app_name: &str) -> Result<HashMap<String, Value>>;
    /// Reads user-level state, empty when none has been written.
    async fn user_state(&self, app_name: &str, user_id: &str) -> Result<HashMap<String, Value>>;
    /// Deletes the user-level state document; a missing one is not an error.
    async fn delete_user_state(&self, app_name: &str, user_id: &str) -> Result<()>;
    /// Applies `commit` atomically when its guard holds inside the transaction.
    async fn commit(&self, commit: SessionCommit) -> Result<CommitOutcome>;
}

/// Production [`SessionStore`] backed by a [`FirestoreDb`].
struct FirestoreStore {
    db: FirestoreDb,
    root_collection: String,
}

impl FirestoreStore {
    /// Parent path of the per-app subcollections: `{root}/{app_name}`.
    fn app_parent(&self, app_name: &str) -> Result<String> {
        let parent = self
            .db
            .parent_path(&self.root_collection, app_name)
            .map_err(|e| firestore_error("path error", e))?;
        Ok(parent.to_string())
    }

    /// Parent path of a session's events: `{root}/{app_name}/sessions/{session_id}`.
    fn events_parent(&self, app_name: &str, session_id: &str) -> Result<String> {
        let parent = self
            .db
            .parent_path(&self.root_collection, app_name)
            .map_err(|e| firestore_error("path error", e))?
            .at(SESSIONS_COLLECTION, session_id)
            .map_err(|e| firestore_error("path error", e))?;
        Ok(parent.to_string())
    }

    /// Parent path of a user's state: `{root}/{app_name}/users/{user_id}`.
    fn user_parent(&self, app_name: &str, user_id: &str) -> Result<String> {
        let parent = self
            .db
            .parent_path(&self.root_collection, app_name)
            .map_err(|e| firestore_error("path error", e))?
            .at(USERS_COLLECTION, user_id)
            .map_err(|e| firestore_error("path error", e))?;
        Ok(parent.to_string())
    }
}

/// Returns the last segment of a Firestore document name, which is the document ID.
fn document_id(document: &FirestoreDocument) -> &str {
    document.name.rsplit('/').next().unwrap_or_default()
}

#[async_trait]
impl SessionStore for FirestoreStore {
    async fn session(&self, app_name: &str, session_id: &str) -> Result<Option<SessionDoc>> {
        let parent = self.app_parent(app_name)?;
        self.db
            .fluent()
            .select()
            .by_id_in(SESSIONS_COLLECTION)
            .parent(&parent)
            .obj::<SessionDoc>()
            .one(session_id)
            .await
            .map_err(|e| firestore_error("query failed", e))
    }

    async fn sessions_with_id(&self, session_id: &str) -> Result<Vec<SessionDoc>> {
        // Collection-group query over every `sessions` collection in the database.
        self.db
            .fluent()
            .select()
            .from(SESSIONS_COLLECTION)
            .parent(self.db.get_documents_path())
            .all_descendants()
            .filter(|q| q.for_all([q.field("session_id").eq(session_id)]))
            .obj::<SessionDoc>()
            .query()
            .await
            .map_err(|e| firestore_error("query failed", e))
    }

    async fn user_sessions(&self, app_name: &str, user_id: &str) -> Result<Vec<SessionDoc>> {
        let parent = self.app_parent(app_name)?;
        self.db
            .fluent()
            .select()
            .from(SESSIONS_COLLECTION)
            .parent(&parent)
            .filter(|q| q.for_all([q.field("user_id").eq(user_id)]))
            .obj::<SessionDoc>()
            .query()
            .await
            .map_err(|e| firestore_error("query failed", e))
    }

    async fn events(&self, app_name: &str, session_id: &str) -> Result<Vec<EventDoc>> {
        let parent = self.events_parent(app_name, session_id)?;
        // Raw documents are decoded one by one so a single corrupt event is skipped
        // instead of failing the whole query.
        let documents = self
            .db
            .fluent()
            .select()
            .from(EVENTS_COLLECTION)
            .parent(&parent)
            .order_by([("timestamp".to_string(), FirestoreQueryDirection::Ascending)])
            .query()
            .await
            .map_err(|e| firestore_error("query failed", e))?;

        Ok(documents
            .iter()
            .filter_map(|document| match FirestoreDb::deserialize_doc_to::<EventDoc>(document) {
                Ok(doc) => Some(doc),
                Err(error) => {
                    tracing::warn!(
                        session.id = %session_id,
                        event.id = %document_id(document),
                        error = %error,
                        "skipping stored event that failed to deserialize"
                    );
                    None
                }
            })
            .collect())
    }

    async fn app_state(&self, app_name: &str) -> Result<HashMap<String, Value>> {
        let parent = self.app_parent(app_name)?;
        let doc: Option<AppStateDoc> = self
            .db
            .fluent()
            .select()
            .by_id_in(APP_STATE_COLLECTION)
            .parent(&parent)
            .obj::<AppStateDoc>()
            .one(STATE_DOCUMENT_ID)
            .await
            .map_err(|e| firestore_error("query failed", e))?;
        Ok(doc.map(|d| d.state).unwrap_or_default())
    }

    async fn user_state(&self, app_name: &str, user_id: &str) -> Result<HashMap<String, Value>> {
        let parent = self.user_parent(app_name, user_id)?;
        let doc: Option<UserStateDoc> = self
            .db
            .fluent()
            .select()
            .by_id_in(USER_STATE_COLLECTION)
            .parent(&parent)
            .obj::<UserStateDoc>()
            .one(STATE_DOCUMENT_ID)
            .await
            .map_err(|e| firestore_error("query failed", e))?;
        Ok(doc.map(|d| d.state).unwrap_or_default())
    }

    async fn delete_user_state(&self, app_name: &str, user_id: &str) -> Result<()> {
        let parent = self.user_parent(app_name, user_id)?;
        self.db
            .fluent()
            .delete()
            .from(USER_STATE_COLLECTION)
            .parent(&parent)
            .document_id(STATE_DOCUMENT_ID)
            .execute()
            .await
            .map_err(|e| firestore_error("delete failed", e))
    }

    async fn commit(&self, commit: SessionCommit) -> Result<CommitOutcome> {
        // A transaction Firestore aborts, such as one that contended with another for a
        // document, applied nothing; it runs again from its reads.
        crate::firestore_stores::retry_while(
            |error: &AdkError| error.code == RETRYABLE_CODE,
            || self.commit_once(&commit),
        )
        .await
    }
}

impl FirestoreStore {
    /// Runs `commit` in one transaction.
    async fn commit_once(&self, commit: &SessionCommit) -> Result<CommitOutcome> {
        let app_parent = self.app_parent(&commit.app_name)?;
        let events_parent = self.events_parent(&commit.app_name, &commit.session_id)?;
        let user_parent = self.user_parent(&commit.app_name, &commit.user_id)?;

        let mut transaction = self
            .db
            .begin_transaction()
            .await
            .map_err(|e| firestore_error("transaction failed", e))?;
        // Reads through this handle join the transaction, so the guard check and the writes
        // below apply to the same document version.
        let tx_db = self.db.clone_with_consistency_selector(
            FirestoreConsistencySelector::Transaction(transaction.transaction_id().clone()),
        );

        let staged: Result<bool> = async {
            let current: Option<SessionDoc> = tx_db
                .fluent()
                .select()
                .by_id_in(SESSIONS_COLLECTION)
                .parent(&app_parent)
                .obj::<SessionDoc>()
                .one(&commit.session_id)
                .await
                .map_err(|e| firestore_error("query failed", e))?;
            if !commit.guard.holds(current.as_ref(), commit) {
                return Ok(false);
            }

            if commit.purges_events() {
                let stored_events = tx_db
                    .fluent()
                    .select()
                    .from(EVENTS_COLLECTION)
                    .parent(&events_parent)
                    .query()
                    .await
                    .map_err(|e| firestore_error("query failed", e))?;
                // Documents the commit writes again are replaced by that write instead.
                for document in stored_events.iter().filter(|document| {
                    !commit.events.put.iter().any(|event| event.id == document_id(document))
                }) {
                    self.db
                        .fluent()
                        .delete()
                        .from(EVENTS_COLLECTION)
                        .parent(&events_parent)
                        .document_id(document_id(document))
                        .add_to_transaction(&mut transaction)
                        .map_err(|e| firestore_error("delete failed", e))?;
                }
            }

            // Reads through `tx_db` hold these documents until the commit, so the merges
            // below apply to the stored state rather than a copy read earlier.
            let app_state = match &commit.app_state {
                Some(merge) => {
                    let stored = tx_db
                        .fluent()
                        .select()
                        .by_id_in(APP_STATE_COLLECTION)
                        .parent(&app_parent)
                        .obj::<AppStateDoc>()
                        .one(STATE_DOCUMENT_ID)
                        .await
                        .map_err(|e| firestore_error("query failed", e))?
                        .map(|doc| doc.state)
                        .unwrap_or_default();
                    Some(AppStateDoc {
                        state: merge.apply(&stored, false),
                        updated_at: merge.updated_at,
                    })
                }
                None => None,
            };
            let user_state = match &commit.user_state {
                Some(merge) => {
                    let stored = tx_db
                        .fluent()
                        .select()
                        .by_id_in(USER_STATE_COLLECTION)
                        .parent(&user_parent)
                        .obj::<UserStateDoc>()
                        .one(STATE_DOCUMENT_ID)
                        .await
                        .map_err(|e| firestore_error("query failed", e))?
                        .map(|doc| doc.state)
                        .unwrap_or_default();
                    Some(UserStateDoc {
                        state: merge.apply(&stored, false),
                        updated_at: merge.updated_at,
                    })
                }
                None => None,
            };

            let session_doc = match (&commit.session, current) {
                (SessionWrite::Put(doc), _) => Some(doc.clone()),
                (SessionWrite::Merge(merge), Some(current)) => Some(SessionDoc {
                    state: merge.apply(&current.state, true),
                    updated_at: merge.updated_at,
                    event_seq: current.event_seq + i64::from(commit.event.is_some()),
                    ..current
                }),
                // The `Owned` guard above guarantees a current document.
                (SessionWrite::Merge(_), None) => return Ok(false),
                (SessionWrite::Delete, _) => None,
            };

            match &session_doc {
                Some(doc) => {
                    // Backs up the in-transaction guard check at commit time.
                    let precondition = match commit.guard {
                        SessionGuard::Absent => FirestoreWritePrecondition::Exists(false),
                        SessionGuard::Owned | SessionGuard::Unchanged(_) => {
                            FirestoreWritePrecondition::Exists(true)
                        }
                    };
                    self.db
                        .fluent()
                        .update()
                        .in_col(SESSIONS_COLLECTION)
                        .precondition(precondition)
                        .document_id(&commit.session_id)
                        .parent(&app_parent)
                        .object(doc)
                        .add_to_transaction(&mut transaction)
                        .map_err(|e| firestore_error("write failed", e))?;
                }
                None => {
                    self.db
                        .fluent()
                        .delete()
                        .from(SESSIONS_COLLECTION)
                        .parent(&app_parent)
                        .document_id(&commit.session_id)
                        .add_to_transaction(&mut transaction)
                        .map_err(|e| firestore_error("delete failed", e))?;
                }
            }

            if let Some(app_state) = &app_state {
                self.db
                    .fluent()
                    .update()
                    .in_col(APP_STATE_COLLECTION)
                    .document_id(STATE_DOCUMENT_ID)
                    .parent(&app_parent)
                    .object(app_state)
                    .add_to_transaction(&mut transaction)
                    .map_err(|e| firestore_error("write failed", e))?;
            }
            if let Some(user_state) = &user_state {
                self.db
                    .fluent()
                    .update()
                    .in_col(USER_STATE_COLLECTION)
                    .document_id(STATE_DOCUMENT_ID)
                    .parent(&user_parent)
                    .object(user_state)
                    .add_to_transaction(&mut transaction)
                    .map_err(|e| firestore_error("write failed", e))?;
            }
            for event_id in &commit.events.remove {
                self.db
                    .fluent()
                    .delete()
                    .from(EVENTS_COLLECTION)
                    .parent(&events_parent)
                    .document_id(event_id)
                    .add_to_transaction(&mut transaction)
                    .map_err(|e| firestore_error("delete failed", e))?;
            }
            for event in &commit.events.put {
                self.db
                    .fluent()
                    .update()
                    .in_col(EVENTS_COLLECTION)
                    .document_id(&event.id)
                    .parent(&events_parent)
                    .object(event)
                    .add_to_transaction(&mut transaction)
                    .map_err(|e| firestore_error("write failed", e))?;
            }
            if let Some(event) = &commit.event {
                let event = EventDoc {
                    seq: session_doc.as_ref().map(|doc| doc.event_seq),
                    ..event.clone()
                };
                self.db
                    .fluent()
                    .update()
                    .in_col(EVENTS_COLLECTION)
                    .document_id(&event.id)
                    .parent(&events_parent)
                    .object(&event)
                    .add_to_transaction(&mut transaction)
                    .map_err(|e| firestore_error("write failed", e))?;
            }
            Ok(true)
        }
        .await;

        match staged {
            Ok(true) => match transaction.commit().await {
                Ok(_) => Ok(CommitOutcome::Committed),
                Err(
                    FirestoreError::DataConflictError(_) | FirestoreError::DataNotFoundError(_),
                ) => Ok(CommitOutcome::GuardFailed),
                Err(error) => Err(firestore_error("commit failed", error)),
            },
            Ok(false) => {
                if let Err(error) = transaction.rollback().await {
                    tracing::warn!(error = %error, "firestore transaction rollback failed");
                }
                Ok(CommitOutcome::GuardFailed)
            }
            Err(error) => {
                if let Err(rollback_error) = transaction.rollback().await {
                    tracing::warn!(error = %rollback_error, "firestore transaction rollback failed");
                }
                Err(error)
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Session logic
// ---------------------------------------------------------------------------

/// Session semantics over a [`SessionStore`]: identity checks, state tiers, and guards.
struct SessionCore<S> {
    store: S,
}

impl<S: SessionStore> SessionCore<S> {
    /// Appends `event` to the session owned by `(app_name, user_id, session_id)`.
    async fn append(
        &self,
        app_name: &str,
        user_id: &str,
        session_id: &str,
        mut event: Event,
    ) -> Result<()> {
        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));
        let not_found = || session_not_found_for(app_name, user_id, session_id);

        self.store
            .session(app_name, session_id)
            .await?
            .filter(|doc| is_owned_by(doc, app_name, user_id, session_id))
            .ok_or_else(not_found)?;

        let (app_delta, user_delta, session_delta) =
            state_utils::extract_state_deltas(&event.actions.state_delta);

        let now = event.timestamp;
        let commit = SessionCommit {
            app_name: app_name.to_string(),
            user_id: user_id.to_string(),
            session_id: session_id.to_string(),
            guard: SessionGuard::Owned,
            session: SessionWrite::Merge(StateMerge { delta: session_delta, updated_at: now }),
            app_state: StateMerge::non_empty(app_delta, now),
            user_state: StateMerge::non_empty(user_delta, now),
            event: Some(event_to_doc(&event)?),
            events: EventWrites::default(),
        };

        match self.store.commit(commit).await? {
            CommitOutcome::Committed => Ok(()),
            CommitOutcome::GuardFailed => Err(not_found()),
        }
    }

    /// Reads the session document `identity` names and its history, with each event's `seq`.
    async fn load_history(
        &self,
        identity: &AdkIdentity,
    ) -> Result<(SessionDoc, SessionHistory, HashMap<String, Option<i64>>)> {
        let (app_name, user_id, session_id) =
            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
        validate_identity(app_name, user_id, session_id)?;
        let doc = self
            .store
            .session(app_name, session_id)
            .await?
            .filter(|doc| is_owned_by(doc, app_name, user_id, session_id))
            .ok_or_else(|| session_not_found_for(app_name, user_id, session_id))?;
        let mut event_docs = self.store.events(app_name, session_id).await?;
        event_docs.sort_by_key(|doc| (doc.timestamp, doc.seq));
        let seqs = event_docs.iter().map(|event| (event.id.clone(), event.seq)).collect();
        // Documents written by earlier releases also hold a copy of the app and user tiers.
        let (_, _, state) = state_utils::extract_state_deltas(&doc.state);
        let history = SessionHistory::new(
            decode_event_docs(&event_docs, session_id),
            state,
            doc.initial_state.clone(),
        );
        Ok((doc, history, seqs))
    }
}

#[async_trait]
impl<S: SessionStore> SessionService for SessionCore<S> {
    async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>> {
        let session_id = req.session_id.clone().unwrap_or_else(|| Uuid::new_v4().to_string());
        req.try_app_name()?;
        req.try_user_id()?;
        SessionId::try_from(session_id.as_str())?;
        validate_identity(&req.app_name, &req.user_id, &session_id)?;

        let (app_delta, user_delta, session_state) = state_utils::extract_state_deltas(&req.state);

        let now = Utc::now();
        let commit = SessionCommit {
            app_name: req.app_name.clone(),
            user_id: req.user_id.clone(),
            session_id: session_id.clone(),
            guard: SessionGuard::Absent,
            session: SessionWrite::Put(SessionDoc {
                app_name: req.app_name.clone(),
                user_id: req.user_id.clone(),
                session_id: session_id.clone(),
                state: session_state.clone(),
                created_at: now,
                updated_at: now,
                event_seq: 0,
                initial_state: Some(session_state.clone()),
            }),
            app_state: StateMerge::non_empty(app_delta, now),
            user_state: StateMerge::non_empty(user_delta, now),
            event: None,
            events: EventWrites::default(),
        };

        match self.store.commit(commit).await? {
            CommitOutcome::Committed => {
                let app_state = self.store.app_state(&req.app_name).await?;
                let user_state = self.store.user_state(&req.app_name, &req.user_id).await?;
                Ok(Box::new(FirestoreSession {
                    app_name: req.app_name,
                    user_id: req.user_id,
                    session_id,
                    state: state_utils::merge_states(&app_state, &user_state, &session_state),
                    events: Vec::new(),
                    updated_at: now,
                }))
            }
            CommitOutcome::GuardFailed => Err(session_already_exists(&req.app_name, &session_id)),
        }
    }

    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
        req.try_identity()?;
        validate_identity(&req.app_name, &req.user_id, &req.session_id)?;

        let session_doc = self
            .store
            .session(&req.app_name, &req.session_id)
            .await?
            .filter(|doc| is_owned_by(doc, &req.app_name, &req.user_id, &req.session_id))
            .ok_or_else(|| crate::service::session_not_found(&req))?;

        let app_state = self.store.app_state(&req.app_name).await?;
        let user_state = self.store.user_state(&req.app_name, &req.user_id).await?;
        let mut event_docs = self.store.events(&req.app_name, &req.session_id).await?;
        // Stable, so events of earlier releases (no `seq`) keep the store's order.
        event_docs.sort_by_key(|doc| (doc.timestamp, doc.seq));
        let mut events = decode_event_docs(&event_docs, &req.session_id);

        if let Some(num) = req.num_recent_events {
            let start = events.len().saturating_sub(num);
            events = events[start..].to_vec();
        }
        if let Some(after) = req.after {
            events.retain(|e| e.timestamp >= after);
        }

        Ok(Box::new(FirestoreSession {
            app_name: req.app_name,
            user_id: req.user_id,
            session_id: req.session_id,
            state: state_utils::merge_current_tiers(&app_state, &user_state, &session_doc.state),
            events,
            updated_at: session_doc.updated_at,
        }))
    }

    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
        req.try_app_name()?;
        req.try_user_id()?;
        validate_path_segment("app_name", &req.app_name)?;
        validate_path_segment("user_id", &req.user_id)?;

        let mut docs: Vec<SessionDoc> = self
            .store
            .user_sessions(&req.app_name, &req.user_id)
            .await?
            .into_iter()
            .filter(|doc| doc.app_name == req.app_name && doc.user_id == req.user_id)
            .collect();
        docs.sort_by(|a, b| {
            b.updated_at.cmp(&a.updated_at).then_with(|| b.session_id.cmp(&a.session_id))
        });

        let app_state = self.store.app_state(&req.app_name).await?;
        let user_state = self.store.user_state(&req.app_name, &req.user_id).await?;

        Ok(docs
            .into_iter()
            .skip(req.offset.unwrap_or(0))
            .take(req.limit.unwrap_or(usize::MAX))
            .map(|doc| {
                Box::new(FirestoreSession {
                    app_name: doc.app_name,
                    user_id: doc.user_id,
                    session_id: doc.session_id,
                    state: state_utils::merge_current_tiers(&app_state, &user_state, &doc.state),
                    events: Vec::new(),
                    updated_at: doc.updated_at,
                }) as Box<dyn Session>
            })
            .collect())
    }

    async fn delete(&self, req: DeleteRequest) -> Result<()> {
        req.try_identity()?;
        validate_identity(&req.app_name, &req.user_id, &req.session_id)?;

        let commit = SessionCommit {
            app_name: req.app_name,
            user_id: req.user_id,
            session_id: req.session_id,
            guard: SessionGuard::Owned,
            session: SessionWrite::Delete,
            app_state: None,
            user_state: None,
            event: None,
            events: EventWrites::default(),
        };
        // A missing or foreign session is a no-op, so deletion reveals nothing about
        // sessions the caller does not own.
        match self.store.commit(commit).await? {
            CommitOutcome::Committed | CommitOutcome::GuardFailed => Ok(()),
        }
    }

    async fn append_event(&self, session_id: &str, event: Event) -> Result<()> {
        SessionId::try_from(session_id)?;
        validate_path_segment("session_id", session_id)?;

        let mut owners: Vec<(String, String)> = self
            .store
            .sessions_with_id(session_id)
            .await?
            .into_iter()
            .filter(|doc| doc.session_id == session_id)
            .map(|doc| (doc.app_name, doc.user_id))
            .collect();
        owners.sort();
        owners.dedup();

        match owners.as_slice() {
            [] => Err(AdkError::not_found(
                ErrorComponent::Session,
                "session.not_found",
                format!("session '{session_id}' was not found"),
            )),
            [(app_name, user_id)] => self.append(app_name, user_id, session_id, event).await,
            _ => Err(AdkError::new(
                ErrorComponent::Session,
                ErrorCategory::InvalidInput,
                "session.ambiguous_id",
                format!(
                    "session ID '{session_id}' exists for more than one app or user; use \
                     append_event_for_identity to address the session unambiguously"
                ),
            )),
        }
    }

    async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
        let app_name = req.identity.app_name.as_ref();
        let user_id = req.identity.user_id.as_ref();
        let session_id = req.identity.session_id.as_ref();
        validate_identity(app_name, user_id, session_id)?;
        self.append(app_name, user_id, session_id, req.event).await
    }

    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
        // Sessions first, so a failure part-way leaves the tier for the repeated call.
        let sessions = self
            .list(ListRequest {
                app_name: app_name.to_string(),
                user_id: user_id.to_string(),
                limit: None,
                offset: None,
            })
            .await?;

        for session in &sessions {
            self.delete(DeleteRequest {
                app_name: app_name.to_string(),
                user_id: user_id.to_string(),
                session_id: session.id().to_string(),
            })
            .await?;
        }

        self.store.delete_user_state(app_name, user_id).await
    }

    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
        Ok(self.load_history(identity).await?.1)
    }

    async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
        let identity = &req.identity;
        let (app_name, user_id, session_id) =
            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
        for _ in 0..MAX_REWRITE_ATTEMPTS {
            let (doc, history, seqs) = self.load_history(identity).await?;
            let rewritten =
                history.rewrite(identity, &req.rewrite, req.expected_version.as_deref())?;
            let now = Utc::now();
            let put = rewritten
                .events
                .iter()
                .filter(|event| rewritten.change.replaced.contains(&event.id))
                .map(|event| {
                    Ok(EventDoc {
                        seq: seqs.get(&event.id).copied().flatten(),
                        ..event_to_doc(event)?
                    })
                })
                .collect::<Result<Vec<_>>>()?;
            let commit = SessionCommit {
                app_name: app_name.to_string(),
                user_id: user_id.to_string(),
                session_id: session_id.to_string(),
                guard: SessionGuard::Unchanged(Box::new(doc.clone())),
                session: SessionWrite::Put(SessionDoc {
                    state: rewritten.state.clone(),
                    updated_at: now,
                    ..doc
                }),
                app_state: None,
                user_state: None,
                event: None,
                events: EventWrites { remove: rewritten.change.removed.clone(), put },
            };
            match self.store.commit(commit).await? {
                CommitOutcome::Committed => {
                    let app_state = self.store.app_state(app_name).await?;
                    let user_state = self.store.user_state(app_name, user_id).await?;
                    let session = Box::new(FirestoreSession {
                        app_name: app_name.to_string(),
                        user_id: user_id.to_string(),
                        session_id: session_id.to_string(),
                        state: state_utils::merge_states(&app_state, &user_state, &rewritten.state),
                        events: rewritten.events,
                        updated_at: now,
                    });
                    return Ok(HistoryOutcome::new(session, rewritten.change));
                }
                CommitOutcome::GuardFailed => continue,
            }
        }
        Err(AdkError::new(
            ErrorComponent::Session,
            ErrorCategory::Unavailable,
            "session.firestore.history_contention",
            format!(
                "session '{session_id}' changed on each of {MAX_REWRITE_ATTEMPTS} rewrite \
                 attempts; retry the rewrite"
            ),
        ))
    }

    async fn import_session(&self, req: ImportSessionRequest) -> Result<Box<dyn Session>> {
        let identity = &req.identity;
        let (app_name, user_id, session_id) =
            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
        validate_identity(app_name, user_id, session_id)?;
        let (_, _, state) = state_utils::extract_state_deltas(&req.state);
        let (_, _, initial_state) = state_utils::extract_state_deltas(&req.initial_state);
        let updated_at = req.events.last().map_or_else(Utc::now, |event| event.timestamp);
        let put = req
            .events
            .iter()
            .zip(1_i64..)
            .map(|(event, seq)| Ok(EventDoc { seq: Some(seq), ..event_to_doc(event)? }))
            .collect::<Result<Vec<_>>>()?;
        let commit = SessionCommit {
            app_name: app_name.to_string(),
            user_id: user_id.to_string(),
            session_id: session_id.to_string(),
            guard: SessionGuard::Absent,
            session: SessionWrite::Put(SessionDoc {
                app_name: app_name.to_string(),
                user_id: user_id.to_string(),
                session_id: session_id.to_string(),
                state: state.clone(),
                created_at: Utc::now(),
                updated_at,
                event_seq: i64::try_from(put.len()).unwrap_or(i64::MAX),
                initial_state: Some(initial_state),
            }),
            app_state: None,
            user_state: None,
            event: None,
            events: EventWrites { remove: Vec::new(), put },
        };
        match self.store.commit(commit).await? {
            CommitOutcome::Committed => {
                let app_state = self.store.app_state(app_name).await?;
                let user_state = self.store.user_state(app_name, user_id).await?;
                Ok(Box::new(FirestoreSession {
                    app_name: app_name.to_string(),
                    user_id: user_id.to_string(),
                    session_id: session_id.to_string(),
                    state: state_utils::merge_states(&app_state, &user_state, &state),
                    events: req.events,
                    updated_at,
                }))
            }
            CommitOutcome::GuardFailed => Err(session_already_exists(app_name, session_id)),
        }
    }
}

// ---------------------------------------------------------------------------
// SessionService implementation
// ---------------------------------------------------------------------------

#[async_trait]
impl SessionService for FirestoreSessionService {
    async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>> {
        self.core.create(req).await
    }

    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
        self.core.get(req).await
    }

    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
        self.core.list(req).await
    }

    async fn delete(&self, req: DeleteRequest) -> Result<()> {
        self.core.delete(req).await
    }

    async fn append_event(&self, session_id: &str, event: Event) -> Result<()> {
        self.core.append_event(session_id, event).await
    }

    async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
        self.core.append_event_for_identity(req).await
    }

    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
        self.core.delete_all_sessions(app_name, user_id).await
    }

    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
        self.core.history(identity).await
    }

    async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
        self.core.rewrite_history(req).await
    }

    async fn import_session(&self, req: ImportSessionRequest) -> Result<Box<dyn Session>> {
        self.core.import_session(req).await
    }
}

// ---------------------------------------------------------------------------
// FirestoreSession — implements Session, State, Events
// ---------------------------------------------------------------------------

struct FirestoreSession {
    app_name: String,
    user_id: String,
    session_id: String,
    state: HashMap<String, Value>,
    events: Vec<Event>,
    updated_at: DateTime<Utc>,
}

impl Session for FirestoreSession {
    fn id(&self) -> &str {
        &self.session_id
    }

    fn app_name(&self) -> &str {
        &self.app_name
    }

    fn user_id(&self) -> &str {
        &self.user_id
    }

    fn state(&self) -> &dyn State {
        self
    }

    fn events(&self) -> &dyn Events {
        self
    }

    fn last_update_time(&self) -> DateTime<Utc> {
        self.updated_at
    }

    fn take_events(&mut self) -> Vec<Event> {
        std::mem::take(&mut self.events)
    }
}

impl State for FirestoreSession {
    fn get(&self, key: &str) -> Option<Value> {
        self.state.get(key).cloned()
    }

    fn set(&mut self, key: String, value: Value) {
        if let Err(msg) = adk_core::validate_state_key(&key) {
            tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
            return;
        }
        self.state.insert(key, value);
    }

    fn all(&self) -> HashMap<String, Value> {
        self.state.clone()
    }
}

impl Events for FirestoreSession {
    fn all(&self) -> Vec<Event> {
        self.events.clone()
    }

    fn len(&self) -> usize {
        self.events.len()
    }

    fn at(&self, index: usize) -> Option<&Event> {
        self.events.get(index)
    }
}

// ---------------------------------------------------------------------------
// Tests
//
// These exercise `SessionCore` over an in-memory `SessionStore` that models the Firestore
// layout: session documents keyed by `(app_name, session_id)` and event subcollections that
// outlive their parent document. `FirestoreStore` itself (transactional reads, write
// preconditions, collection-group queries, document paths) needs the Firestore emulator.
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use adk_core::identity::{AdkIdentity, AppName, UserId};
    use serde_json::json;
    use std::sync::Mutex;

    type SessionKey = (String, String);
    type CommitHook = Box<dyn FnOnce(&mut FakeData) + Send>;

    #[derive(Default)]
    struct FakeData {
        sessions: HashMap<SessionKey, SessionDoc>,
        events: HashMap<SessionKey, Vec<EventDoc>>,
        app_states: HashMap<String, AppStateDoc>,
        user_states: HashMap<SessionKey, UserStateDoc>,
    }

    #[derive(Default)]
    struct FakeStore {
        data: Mutex<FakeData>,
        /// Runs once at the start of the next commit, to simulate a concurrent writer.
        before_commit: Mutex<Option<CommitHook>>,
    }

    fn key(app_name: &str, session_id: &str) -> SessionKey {
        (app_name.to_string(), session_id.to_string())
    }

    #[async_trait]
    impl SessionStore for FakeStore {
        async fn session(&self, app_name: &str, session_id: &str) -> Result<Option<SessionDoc>> {
            Ok(self.data.lock().unwrap().sessions.get(&key(app_name, session_id)).cloned())
        }

        async fn sessions_with_id(&self, session_id: &str) -> Result<Vec<SessionDoc>> {
            let data = self.data.lock().unwrap();
            Ok(data.sessions.values().filter(|doc| doc.session_id == session_id).cloned().collect())
        }

        async fn user_sessions(&self, app_name: &str, user_id: &str) -> Result<Vec<SessionDoc>> {
            let data = self.data.lock().unwrap();
            Ok(data
                .sessions
                .iter()
                .filter(|((app, _), doc)| app == app_name && doc.user_id == user_id)
                .map(|(_, doc)| doc.clone())
                .collect())
        }

        async fn events(&self, app_name: &str, session_id: &str) -> Result<Vec<EventDoc>> {
            let data = self.data.lock().unwrap();
            let mut events =
                data.events.get(&key(app_name, session_id)).cloned().unwrap_or_default();
            // Firestore orders equal `timestamp` values by document ID, the event ID.
            events.sort_by(|a, b| a.timestamp.cmp(&b.timestamp).then_with(|| a.id.cmp(&b.id)));
            Ok(events)
        }

        async fn app_state(&self, app_name: &str) -> Result<HashMap<String, Value>> {
            let data = self.data.lock().unwrap();
            Ok(data.app_states.get(app_name).map(|doc| doc.state.clone()).unwrap_or_default())
        }

        async fn user_state(
            &self,
            app_name: &str,
            user_id: &str,
        ) -> Result<HashMap<String, Value>> {
            let data = self.data.lock().unwrap();
            Ok(data
                .user_states
                .get(&key(app_name, user_id))
                .map(|doc| doc.state.clone())
                .unwrap_or_default())
        }

        async fn delete_user_state(&self, app_name: &str, user_id: &str) -> Result<()> {
            self.data.lock().unwrap().user_states.remove(&key(app_name, user_id));
            Ok(())
        }

        async fn commit(&self, commit: SessionCommit) -> Result<CommitOutcome> {
            let hook = self.before_commit.lock().unwrap().take();
            let mut data = self.data.lock().unwrap();
            if let Some(hook) = hook {
                hook(&mut data);
            }

            let session_key = key(&commit.app_name, &commit.session_id);
            if !commit.guard.holds(data.sessions.get(&session_key), &commit) {
                return Ok(CommitOutcome::GuardFailed);
            }

            if commit.purges_events() {
                data.events.remove(&session_key);
            }
            match commit.session {
                SessionWrite::Put(doc) => {
                    data.sessions.insert(session_key.clone(), doc);
                }
                SessionWrite::Merge(merge) => {
                    let doc = data.sessions.get_mut(&session_key).expect("guarded by Owned");
                    doc.state = merge.apply(&doc.state, true);
                    doc.updated_at = merge.updated_at;
                    doc.event_seq += i64::from(commit.event.is_some());
                }
                SessionWrite::Delete => {
                    data.sessions.remove(&session_key);
                }
            }
            if let Some(merge) = commit.app_state {
                let stored = data.app_states.get(&commit.app_name).map(|doc| doc.state.clone());
                let state = merge.apply(&stored.unwrap_or_default(), false);
                data.app_states.insert(
                    commit.app_name.clone(),
                    AppStateDoc { state, updated_at: merge.updated_at },
                );
            }
            if let Some(merge) = commit.user_state {
                let user_key = key(&commit.app_name, &commit.user_id);
                let stored = data.user_states.get(&user_key).map(|doc| doc.state.clone());
                let state = merge.apply(&stored.unwrap_or_default(), false);
                data.user_states
                    .insert(user_key, UserStateDoc { state, updated_at: merge.updated_at });
            }
            let stored = data.events.entry(session_key.clone()).or_default();
            stored.retain(|event| !commit.events.remove.contains(&event.id));
            for event in commit.events.put {
                match stored.iter_mut().find(|stored| stored.id == event.id) {
                    Some(existing) => *existing = event,
                    None => stored.push(event),
                }
            }
            if let Some(event) = commit.event {
                let seq = data.sessions.get(&session_key).map(|doc| doc.event_seq);
                data.events.entry(session_key).or_default().push(EventDoc { seq, ..event });
            }
            Ok(CommitOutcome::Committed)
        }
    }

    fn service() -> SessionCore<FakeStore> {
        SessionCore { store: FakeStore::default() }
    }

    fn create_req(app: &str, user: &str, session: &str, state: Value) -> CreateRequest {
        CreateRequest {
            app_name: app.to_string(),
            user_id: user.to_string(),
            session_id: Some(session.to_string()),
            state: serde_json::from_value(state).unwrap(),
        }
    }

    fn get_req(app: &str, user: &str, session: &str) -> GetRequest {
        GetRequest {
            app_name: app.to_string(),
            user_id: user.to_string(),
            session_id: session.to_string(),
            num_recent_events: None,
            after: None,
        }
    }

    fn delete_req(app: &str, user: &str, session: &str) -> DeleteRequest {
        DeleteRequest {
            app_name: app.to_string(),
            user_id: user.to_string(),
            session_id: session.to_string(),
        }
    }

    fn append_req(app: &str, user: &str, session: &str, event: Event) -> AppendEventRequest {
        AppendEventRequest {
            identity: AdkIdentity::new(
                AppName::try_from(app).unwrap(),
                UserId::try_from(user).unwrap(),
                SessionId::try_from(session).unwrap(),
            ),
            event,
        }
    }

    fn event_with_delta(id: &str, delta: Value) -> Event {
        let mut event = Event::with_id(id, "inv-1");
        event.author = "agent".to_string();
        event.actions.state_delta = serde_json::from_value(delta).unwrap();
        event
    }

    /// Snapshot of everything stored under one session path.
    fn stored(
        core: &SessionCore<FakeStore>,
        app: &str,
        session: &str,
    ) -> (Option<SessionDoc>, Vec<EventDoc>) {
        let data = core.store.data.lock().unwrap();
        (
            data.sessions.get(&key(app, session)).cloned(),
            data.events.get(&key(app, session)).cloned().unwrap_or_default(),
        )
    }

    async fn alice_session_with_event(core: &SessionCore<FakeStore>) {
        core.create(create_req("app", "alice", "s1", json!({"secret": "alice-data"})))
            .await
            .unwrap();
        core.append_event_for_identity(append_req(
            "app",
            "alice",
            "s1",
            event_with_delta("e1", json!({"secret": "alice-updated"})),
        ))
        .await
        .unwrap();
    }

    fn assert_error(error: &AdkError, category: ErrorCategory, code: &str) {
        assert_eq!((error.category, error.code), (category, code), "{error}");
    }

    #[test]
    fn a_failure_firestore_reports_as_retryable_stays_retryable() {
        let failure = |retry_possible| {
            FirestoreError::DatabaseError(firestore::errors::FirestoreDatabaseError {
                public: firestore::errors::FirestoreErrorPublicGenericDetails {
                    code: "Aborted".to_string(),
                },
                details: "Transaction lock timeout.".to_string(),
                retry_possible,
            })
        };
        let retryable = firestore_error("commit failed", failure(true));
        assert_error(&retryable, ErrorCategory::Unavailable, RETRYABLE_CODE);
        assert!(retryable.is_retryable(), "{retryable:?}");
        assert_error(
            &firestore_error("commit failed", failure(false)),
            ErrorCategory::Internal,
            "session.legacy",
        );
    }

    #[tokio::test]
    async fn create_rejects_a_session_id_owned_by_another_user() {
        let core = service();
        alice_session_with_event(&core).await;
        let before = stored(&core, "app", "s1");

        let error = core
            .create(create_req("app", "bob", "s1", json!({"secret": "bob-data"})))
            .await
            .err()
            .expect("taking over another user's session id must fail");
        assert_error(&error, ErrorCategory::Conflict, "session.already_exists");

        assert_eq!(stored(&core, "app", "s1"), before);
        let bob_get = core.get(get_req("app", "bob", "s1")).await.err().unwrap();
        assert_error(&bob_get, ErrorCategory::NotFound, "session.not_found");
    }

    #[tokio::test]
    async fn create_rejects_a_duplicate_session_id_for_the_same_user() {
        let core = service();
        alice_session_with_event(&core).await;
        let before = stored(&core, "app", "s1");

        let error = core
            .create(create_req("app", "alice", "s1", json!({})))
            .await
            .err()
            .expect("recreating an existing session must fail");
        assert_error(&error, ErrorCategory::Conflict, "session.already_exists");
        assert_eq!(stored(&core, "app", "s1"), before);
    }

    #[tokio::test]
    async fn create_does_not_inherit_orphaned_events() {
        let core = service();
        let orphan = event_to_doc(&event_with_delta("orphan", json!({}))).unwrap();
        core.store.data.lock().unwrap().events.insert(key("app", "s1"), vec![orphan]);

        core.create(create_req("app", "bob", "s1", json!({}))).await.unwrap();

        let session = core.get(get_req("app", "bob", "s1")).await.unwrap();
        assert_eq!(session.events().len(), 0);
    }

    #[tokio::test]
    async fn delete_by_another_user_leaves_the_session_untouched() {
        let core = service();
        alice_session_with_event(&core).await;
        let before = stored(&core, "app", "s1");

        core.delete(delete_req("app", "bob", "s1")).await.unwrap();
        assert_eq!(stored(&core, "app", "s1"), before);

        core.delete(delete_req("app", "alice", "s1")).await.unwrap();
        assert_eq!(stored(&core, "app", "s1"), (None, Vec::new()));
    }

    #[tokio::test]
    async fn append_with_another_users_identity_is_not_found() {
        let core = service();
        alice_session_with_event(&core).await;
        let before = stored(&core, "app", "s1");

        let error = core
            .append_event_for_identity(append_req(
                "app",
                "bob",
                "s1",
                event_with_delta("e2", json!({"secret": "bob-overwrite"})),
            ))
            .await
            .expect_err("appending to another user's session must fail");
        assert_error(&error, ErrorCategory::NotFound, "session.not_found");
        assert_eq!(stored(&core, "app", "s1"), before);
    }

    #[tokio::test]
    async fn append_rechecks_ownership_inside_the_commit() {
        let core = service();
        core.create(create_req("app", "alice", "s1", json!({}))).await.unwrap();

        // Between the ownership read and the commit, the session is deleted and recreated
        // by another user.
        let takeover = SessionDoc {
            app_name: "app".to_string(),
            user_id: "mallory".to_string(),
            session_id: "s1".to_string(),
            state: serde_json::from_value(json!({"owner": "mallory"})).unwrap(),
            created_at: Utc::now(),
            updated_at: Utc::now(),
            event_seq: 0,
            initial_state: None,
        };
        let replacement = takeover.clone();
        *core.store.before_commit.lock().unwrap() = Some(Box::new(move |data: &mut FakeData| {
            data.sessions.insert(key("app", "s1"), replacement);
        }));

        let error = core
            .append_event_for_identity(append_req(
                "app",
                "alice",
                "s1",
                event_with_delta("e1", json!({"owner": "alice"})),
            ))
            .await
            .expect_err("a commit against a session that changed owner must fail");
        assert_error(&error, ErrorCategory::NotFound, "session.not_found");
        assert_eq!(stored(&core, "app", "s1"), (Some(takeover), Vec::new()));
    }

    #[tokio::test]
    async fn legacy_append_event_resolves_the_unique_owner() {
        let core = service();
        core.create(create_req("app", "alice", "s1", json!({}))).await.unwrap();

        core.append_event("s1", event_with_delta("e1", json!({"k": 1}))).await.unwrap();
        let session = core.get(get_req("app", "alice", "s1")).await.unwrap();
        assert_eq!(session.state().all(), serde_json::from_value(json!({"k": 1})).unwrap());
        assert_eq!(session.events().len(), 1);

        let missing = core.append_event("missing", Event::new("inv")).await.err().unwrap();
        assert_error(&missing, ErrorCategory::NotFound, "session.not_found");

        core.create(create_req("other_app", "bob", "s1", json!({}))).await.unwrap();
        let ambiguous = core.append_event("s1", Event::new("inv")).await.err().unwrap();
        assert_error(&ambiguous, ErrorCategory::InvalidInput, "session.ambiguous_id");
    }

    #[tokio::test]
    async fn events_with_equal_timestamps_read_back_in_append_order() {
        let core = service();
        core.create(create_req("app", "alice", "s1", json!({}))).await.unwrap();
        let at = Utc::now();
        // Document IDs sort opposite to the append order.
        let ids = ["e-c", "e-b", "e-a"];
        for id in ids {
            let mut event = event_with_delta(id, json!({}));
            event.timestamp = at;
            core.append_event_for_identity(append_req("app", "alice", "s1", event)).await.unwrap();
        }

        let session = core.get(get_req("app", "alice", "s1")).await.unwrap();
        let read: Vec<String> = session.events().all().into_iter().map(|event| event.id).collect();
        assert_eq!(read, ids);
    }

    #[tokio::test]
    async fn list_orders_equal_update_times_by_session_id_descending() {
        let core = service();
        let at = Utc::now();
        for session in ["s1", "s3", "s2"] {
            core.create(create_req("app", "alice", session, json!({}))).await.unwrap();
            let mut event = event_with_delta(&format!("{session}-e"), json!({}));
            event.timestamp = at;
            core.append_event_for_identity(append_req("app", "alice", session, event))
                .await
                .unwrap();
        }

        let listed = core
            .list(ListRequest {
                app_name: "app".to_string(),
                user_id: "alice".to_string(),
                limit: None,
                offset: None,
            })
            .await
            .unwrap();
        let ids: Vec<&str> = listed.iter().map(|session| session.id()).collect();
        assert_eq!(ids, ["s3", "s2", "s1"]);
    }

    #[tokio::test]
    async fn list_and_delete_all_are_scoped_to_the_caller() {
        let core = service();
        for (app, user, session) in [
            ("app", "alice", "a1"),
            ("app", "alice", "a2"),
            ("app", "bob", "b1"),
            ("other_app", "alice", "a3"),
        ] {
            let state = json!({ "user:lang": format!("{app}/{user}"), "app:theme": app });
            core.create(create_req(app, user, session, state)).await.unwrap();
        }
        // A document stored under `app` that claims to belong to another app.
        let forged = SessionDoc {
            app_name: "elsewhere".to_string(),
            user_id: "alice".to_string(),
            session_id: "forged".to_string(),
            state: HashMap::new(),
            created_at: Utc::now(),
            updated_at: Utc::now(),
            event_seq: 0,
            initial_state: None,
        };
        core.store.data.lock().unwrap().sessions.insert(key("app", "forged"), forged);

        let list = |app: &'static str, user: &'static str| {
            let core = &core;
            async move {
                let mut ids: Vec<String> = core
                    .list(ListRequest {
                        app_name: app.to_string(),
                        user_id: user.to_string(),
                        limit: None,
                        offset: None,
                    })
                    .await
                    .unwrap()
                    .iter()
                    .map(|session| session.id().to_string())
                    .collect();
                ids.sort();
                ids
            }
        };
        assert_eq!(list("app", "alice").await, vec!["a1", "a2"]);

        core.delete_all_sessions("app", "alice").await.unwrap();
        assert_eq!(list("app", "alice").await, Vec::<String>::new());
        assert_eq!(list("app", "bob").await, vec!["b1"]);
        assert_eq!(list("other_app", "alice").await, vec!["a3"]);
        // Alice's user tier in `app` goes with her sessions; every other tier stays.
        assert_eq!(core.store.user_state("app", "alice").await.unwrap(), HashMap::new());
        assert_eq!(core.store.user_state("app", "bob").await.unwrap()["lang"], json!("app/bob"));
        let elsewhere = core.store.user_state("other_app", "alice").await.unwrap();
        assert_eq!(elsewhere["lang"], json!("other_app/alice"));
        assert_eq!(core.store.app_state("app").await.unwrap()["theme"], json!("app"));
        core.delete_all_sessions("app", "alice").await.unwrap();
    }

    #[tokio::test]
    async fn state_tiers_round_trip_through_create_append_and_get() {
        let core = service();
        core.create(create_req(
            "app",
            "alice",
            "s1",
            json!({"app:theme": "dark", "user:lang": "sw", "k": 1, "temp:scratch": true}),
        ))
        .await
        .unwrap();
        core.append_event_for_identity(append_req(
            "app",
            "alice",
            "s1",
            event_with_delta("e1", json!({"k": 2, "user:lang": "en", "temp:x": 1})),
        ))
        .await
        .unwrap();

        let session = core.get(get_req("app", "alice", "s1")).await.unwrap();
        assert_eq!(
            session.state().all(),
            serde_json::from_value::<HashMap<String, Value>>(
                json!({"app:theme": "dark", "user:lang": "en", "k": 2})
            )
            .unwrap()
        );
        let delta = session.events().at(0).unwrap().actions.state_delta.clone();
        assert_eq!(
            delta,
            serde_json::from_value::<HashMap<String, Value>>(json!({"k": 2, "user:lang": "en"}))
                .unwrap()
        );
    }

    #[tokio::test]
    async fn get_and_list_serve_the_current_shared_tiers() {
        let core = service();
        core.create(create_req("app", "alice", "s1", json!({"app:theme": "light", "k": 1})))
            .await
            .unwrap();
        core.create(create_req("app", "alice", "s2", json!({}))).await.unwrap();
        core.append_event_for_identity(append_req(
            "app",
            "alice",
            "s2",
            event_with_delta("e1", json!({"app:theme": "dark", "user:lang": "fr"})),
        ))
        .await
        .unwrap();

        let expected: HashMap<String, Value> =
            serde_json::from_value(json!({"app:theme": "dark", "user:lang": "fr", "k": 1}))
                .unwrap();
        let session = core.get(get_req("app", "alice", "s1")).await.unwrap();
        assert_eq!(session.state().all(), expected);

        let listed = core
            .list(ListRequest {
                app_name: "app".to_string(),
                user_id: "alice".to_string(),
                limit: None,
                offset: None,
            })
            .await
            .unwrap();
        let listed = listed.iter().find(|session| session.id() == "s1").unwrap();
        assert_eq!(listed.state().all(), expected);
    }

    #[tokio::test]
    async fn append_keeps_keys_a_concurrent_writer_committed_first() {
        let core = service();
        core.create(create_req("app", "alice", "s1", json!({}))).await.unwrap();

        // Between the append's ownership read and its commit, another writer commits its
        // own key to every tier.
        *core.store.before_commit.lock().unwrap() = Some(Box::new(|data: &mut FakeData| {
            let theirs: HashMap<String, Value> = HashMap::from([("theirs".to_string(), json!(1))]);
            data.app_states.insert(
                "app".to_string(),
                AppStateDoc { state: theirs.clone(), updated_at: Utc::now() },
            );
            data.user_states.insert(
                key("app", "alice"),
                UserStateDoc { state: theirs.clone(), updated_at: Utc::now() },
            );
            data.sessions.get_mut(&key("app", "s1")).unwrap().state = theirs;
        }));

        core.append_event_for_identity(append_req(
            "app",
            "alice",
            "s1",
            event_with_delta("e1", json!({"app:mine": 2, "user:mine": 2, "mine": 2})),
        ))
        .await
        .unwrap();

        let session = core.get(get_req("app", "alice", "s1")).await.unwrap();
        assert_eq!(
            session.state().all(),
            serde_json::from_value::<HashMap<String, Value>>(json!({
                "app:theirs": 1, "app:mine": 2,
                "user:theirs": 1, "user:mine": 2,
                "theirs": 1, "mine": 2,
            }))
            .unwrap()
        );
    }

    #[tokio::test]
    async fn identifiers_that_are_not_single_document_ids_are_rejected() {
        let core = service();
        let error =
            core.create(create_req("app", "alice", "s1/events/e1", json!({}))).await.err().unwrap();
        assert_error(&error, ErrorCategory::InvalidInput, "session.firestore.invalid_identifier");

        for bad in ["", "a/b", ".", "..", "__reserved__"] {
            let error = validate_path_segment("user_id", bad).err().unwrap();
            assert_error(
                &error,
                ErrorCategory::InvalidInput,
                "session.firestore.invalid_identifier",
            );
        }
        validate_path_segment("user_id", "alice@example.com").unwrap();
    }

    #[test]
    fn undecodable_event_documents_are_skipped() {
        let good = event_to_doc(&event_with_delta("good", json!({}))).unwrap();
        let bad = EventDoc { id: "bad".to_string(), actions: json!("not actions"), ..good.clone() };

        let events = decode_event_docs(&[bad, good], "s1");
        let ids: Vec<&str> = events.iter().map(|event| event.id.as_str()).collect();
        assert_eq!(ids, vec!["good"]);
    }

    fn identity(app: &str, user: &str, session: &str) -> AdkIdentity {
        AdkIdentity::new(
            AppName::try_from(app).unwrap(),
            UserId::try_from(user).unwrap(),
            SessionId::try_from(session).unwrap(),
        )
    }

    async fn three_events(core: &SessionCore<FakeStore>) -> Vec<String> {
        core.create(create_req("app", "alice", "s1", json!({"tier": "gold"}))).await.unwrap();
        let mut ids = Vec::new();
        for n in 0..3 {
            let mut event =
                event_with_delta(&format!("e{n}"), json!({"step": n, "tier": "silver"}));
            event.timestamp = Utc::now() + chrono::Duration::milliseconds(n);
            ids.push(event.id.clone());
            core.append_event_for_identity(append_req("app", "alice", "s1", event)).await.unwrap();
        }
        ids
    }

    #[tokio::test]
    async fn history_rewrites_delete_and_replace_event_documents() {
        let core = service();
        let ids = three_events(&core).await;
        let alice = identity("app", "alice", "s1");

        let rewound = core.rewind(&alice, &ids[1]).await.unwrap();
        assert_eq!(rewound.state().get("step"), Some(json!(1)));
        let stored: Vec<String> = core.store.data.lock().unwrap().events[&key("app", "s1")]
            .iter()
            .map(|event| event.id.clone())
            .collect();
        assert_eq!(stored, ids[..2]);

        let mut replacement = event_with_delta(&ids[0], json!({"step": 7}));
        replacement.author = "editor".into();
        let edited = core
            .rewrite_history(RewriteHistoryRequest::new(
                alice.clone(),
                crate::HistoryRewrite::Edit {
                    edits: vec![crate::HistoryEdit::Replace { event: Box::new(replacement) }],
                },
            ))
            .await
            .unwrap();
        assert_eq!(edited.session.state().get("step"), Some(json!(1)), "e1 still writes last");
        let reread = core.get(get_req("app", "alice", "s1")).await.unwrap();
        assert_eq!(reread.events().all()[0].author, "editor");
        assert_eq!(reread.events().len(), 2);

        let emptied = core.rewind_steps(&alice, 2).await.unwrap();
        assert_eq!((emptied.events().len(), emptied.state().get("tier")), (0, Some(json!("gold"))));
    }

    #[tokio::test]
    async fn a_rewrite_racing_an_append_plans_again_and_keeps_the_append() {
        let core = service();
        let ids = three_events(&core).await;
        let mut late = event_with_delta("late", json!({"step": 9}));
        late.timestamp = Utc::now() + chrono::Duration::days(1);
        let late_doc = EventDoc { seq: Some(4), ..event_to_doc(&late).unwrap() };
        *core.store.before_commit.lock().unwrap() = Some(Box::new(move |data: &mut FakeData| {
            let doc = data.sessions.get_mut(&key("app", "s1")).unwrap();
            doc.event_seq += 1;
            doc.updated_at = Utc::now();
            data.events.get_mut(&key("app", "s1")).unwrap().push(late_doc);
        }));

        let edited = core
            .rewrite_history(RewriteHistoryRequest::new(
                identity("app", "alice", "s1"),
                crate::HistoryRewrite::Edit {
                    edits: vec![crate::HistoryEdit::Remove { event_id: ids[0].clone() }],
                },
            ))
            .await
            .unwrap();
        let kept: Vec<String> = edited.session.events().all().into_iter().map(|e| e.id).collect();
        assert_eq!(kept, [ids[1].clone(), ids[2].clone(), "late".to_string()]);
    }

    #[tokio::test]
    async fn a_fork_imports_events_and_refuses_a_taken_id() {
        let core = service();
        let ids = three_events(&core).await;
        let fork = core
            .fork(
                crate::ForkRequest::new(identity("app", "alice", "s1"))
                    .at_event(&ids[0])
                    .with_session_id("s2"),
            )
            .await
            .unwrap();
        assert_eq!(
            (fork.session.events().len(), fork.session.state().get("step")),
            (1, Some(json!(0)))
        );
        let doc = core.store.data.lock().unwrap().sessions[&key("app", "s2")].clone();
        assert_eq!(doc.event_seq, 1);
        assert!(doc.initial_state.unwrap().contains_key(crate::FORK_ORIGIN_KEY));
        let taken = core
            .fork(crate::ForkRequest::new(identity("app", "alice", "s1")).with_session_id("s2"))
            .await
            .err()
            .unwrap();
        assert_error(&taken, ErrorCategory::Conflict, "session.already_exists");
    }

    #[test]
    fn layout_paths_are_document_paths() {
        assert_eq!(app_state_path("root", "app"), "root/app/app_state/current");
        assert_eq!(user_state_path("root", "app", "alice"), "root/app/users/alice/state/current");
        assert_eq!(session_path("root", "app", "s1"), "root/app/sessions/s1");
        assert_eq!(event_path("root", "app", "s1", "e1"), "root/app/sessions/s1/events/e1");
    }
}