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
//! Neo4j session service backend.
//!
//! Provides [`Neo4jSessionService`] for session persistence using Neo4j graph database.
//! Enabled via the `neo4j` feature flag.
//!
//! # Graph Schema
//!
//! Sessions are modeled as graph nodes with typed relationships:
//!
//! ```text
//! (:Session)-[:HAS_EVENT]->(:Event)
//! (:Session)-[:HAS_APP_STATE]->(:AppState)
//! (:Session)-[:HAS_USER_STATE]->(:UserState)
//! ```
//!
//! # Example
//!
//! ```rust,ignore
//! use adk_session::Neo4jSessionService;
//!
//! let service = Neo4jSessionService::new("bolt://localhost:7687", "neo4j", "password").await?;
//! service.migrate().await?;
//! ```

use crate::history::{
    HistoryOutcome, ImportSessionRequest, RewriteHistoryRequest, RewrittenHistory, SessionHistory,
};
use crate::neo4j_stores::{Inline, detached};
use crate::service::{
    identity_not_found, session_already_exists, session_id_not_found, session_not_found_for,
    validate_scope, validate_session_id,
};
use crate::{
    AppendEventRequest, CreateRequest, DeleteRequest, Event, Events, GetRequest, KEY_PREFIX_TEMP,
    ListRequest, Session, SessionService, State, state_utils,
};
use adk_core::Result;
use adk_core::identity::AdkIdentity;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use neo4rs::Graph;
use serde_json::Value;
use std::collections::HashMap;
use tracing::instrument;
use uuid::Uuid;

/// Neo4j-backed session service implementing [`SessionService`].
///
/// Stores sessions as graph nodes with relationships to event, app-state,
/// and user-state nodes. Each state key is a node property holding the value
/// as a JSON string, since Neo4j has no native JSON type, so an append writes
/// only its own keys and concurrent appends keep each other's writes.
#[derive(Clone)]
pub struct Neo4jSessionService {
    graph: Graph,
}

impl Neo4jSessionService {
    /// Connect to Neo4j using URI, username, and password.
    ///
    /// Returns an error with "neo4j connection failed" context if the
    /// connection cannot be established.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let service = Neo4jSessionService::new(
    ///     "bolt://localhost:7687",
    ///     "neo4j",
    ///     "password",
    /// ).await?;
    /// ```
    pub async fn new(uri: &str, username: &str, password: &str) -> Result<Self> {
        let graph = Graph::new(uri, username, password)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("neo4j connection failed: {e}")))?;
        Ok(Self { graph })
    }

    /// Returns a reference to the underlying Neo4j graph connection.
    pub fn graph(&self) -> &Graph {
        &self.graph
    }

    /// Registry node label for tracking applied migration versions.
    const REGISTRY_LABEL: &'static str = "_AdkSessionMigration";

    /// Compiled-in Neo4j migration steps.
    ///
    /// Each entry is `(version, description, &[cypher_statements])`. All Cypher
    /// statements use `IF NOT EXISTS` for idempotent execution.
    const NEO4J_SESSION_MIGRATIONS: &'static [(i64, &'static str, &'static [&'static str])] = &[(
        1,
        "create initial constraints and indexes",
        &[
            "CREATE CONSTRAINT session_unique IF NOT EXISTS \
             FOR (s:Session) REQUIRE (s.app_name, s.user_id, s.session_id) IS UNIQUE",
            "CREATE INDEX event_session_ts IF NOT EXISTS \
             FOR (e:Event) ON (e.session_id, e.timestamp)",
            "CREATE CONSTRAINT app_state_unique IF NOT EXISTS \
             FOR (a:AppState) REQUIRE (a.app_name) IS UNIQUE",
            "CREATE CONSTRAINT user_state_unique IF NOT EXISTS \
             FOR (u:UserState) REQUIRE (u.app_name, u.user_id) IS UNIQUE",
        ],
    )];

    /// Run versioned migrations for Neo4j session storage.
    ///
    /// The runner:
    /// 1. Creates a uniqueness constraint on registry nodes.
    /// 2. Detects baseline — if v1's last rule, the `user_state_unique`
    ///    constraint, exists but the registry is empty, records v1 as applied.
    /// 3. Reads the maximum applied version from the registry.
    /// 4. Returns an error if the database version exceeds the compiled-in max.
    /// 5. Executes each unapplied step idempotently and records it.
    ///
    /// Several processes may migrate one database at once: a schema statement that
    /// loses a race to create the same rule succeeds, and each version is recorded with
    /// `MERGE`, so a version another process recorded first is not an error.
    pub async fn migrate(&self) -> Result<()> {
        // Step 1: Ensure registry has a uniqueness constraint on `version`
        run_schema_statement(
            &self.graph,
            &format!(
                "CREATE CONSTRAINT {}_version_unique IF NOT EXISTS \
                 FOR (m:{}) REQUIRE (m.version) IS UNIQUE",
                Self::REGISTRY_LABEL.to_lowercase(),
                Self::REGISTRY_LABEL,
            ),
        )
        .await
        .map_err(|e| {
            adk_core::AdkError::session(format!("migration registry creation failed: {e}"))
        })?;

        // Step 2: Read current max applied version
        let mut max_applied = self.read_max_applied_version().await?;

        // Step 3: Baseline detection — if registry is empty but v1's last
        // constraint already exists, record v1 as applied.
        if max_applied == 0 {
            let existing = self.detect_existing_tables().await?;
            if existing
                && let Some(&(version, description, _)) = Self::NEO4J_SESSION_MIGRATIONS.first()
            {
                self.record_migration(version, description).await?;
                max_applied = version;
            }
        }

        // Step 4: Compiled-in max version
        let max_compiled = Self::NEO4J_SESSION_MIGRATIONS.last().map(|s| s.0).unwrap_or(0);

        // Step 5: Version mismatch check
        if max_applied > max_compiled {
            return Err(adk_core::AdkError::session(format!(
                "schema version mismatch: database is at v{max_applied} \
                 but code only knows up to v{max_compiled}. \
                 Upgrade your ADK version."
            )));
        }

        // Step 6: Execute unapplied steps idempotently
        for &(version, description, cypher_statements) in Self::NEO4J_SESSION_MIGRATIONS {
            if version <= max_applied {
                continue;
            }

            for cypher in cypher_statements {
                run_schema_statement(&self.graph, cypher).await.map_err(|e| {
                    adk_core::AdkError::session(format!(
                        "{}",
                        crate::migration::MigrationError {
                            version,
                            description: description.to_string(),
                            cause: e.to_string(),
                        }
                    ))
                })?;
            }

            self.record_migration(version, description).await?;
        }

        Ok(())
    }

    /// Returns the highest applied migration version, or 0 if no registry
    /// exists or the registry is empty.
    pub async fn schema_version(&self) -> Result<i64> {
        self.read_max_applied_version().await
    }

    /// Read the maximum applied version from the registry nodes.
    async fn read_max_applied_version(&self) -> Result<i64> {
        let query_str =
            format!("OPTIONAL MATCH (m:{}) RETURN max(m.version) AS max_v", Self::REGISTRY_LABEL,);
        let mut row_stream = self.graph.execute(neo4rs::query(&query_str)).await.map_err(|e| {
            adk_core::AdkError::session(format!("migration registry read failed: {e}"))
        })?;

        if let Some(row) = row_stream.next().await.map_err(|e| {
            adk_core::AdkError::session(format!("migration registry read failed: {e}"))
        })? {
            // max() returns null when no nodes exist; treat as 0
            Ok(row.get::<i64>("max_v").unwrap_or(0))
        } else {
            Ok(0)
        }
    }

    /// Detect whether v1's last rule, the `user_state_unique` constraint, already
    /// exists (baseline). A first `migrate` running in another process creates v1's
    /// rules in order, so an earlier rule existing does not mean v1 is complete.
    async fn detect_existing_tables(&self) -> Result<bool> {
        let mut row_stream = self
            .graph
            .execute(neo4rs::query(
                "SHOW CONSTRAINTS YIELD name WHERE name = 'user_state_unique' RETURN name",
            ))
            .await
            .map_err(|e| adk_core::AdkError::session(format!("baseline detection failed: {e}")))?;

        let found = row_stream
            .next()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("baseline detection failed: {e}")))?
            .is_some();

        Ok(found)
    }

    /// Records an applied migration step as a registry node, unless another process
    /// recorded it first. The uniqueness constraint on `version` makes `MERGE` take a lock,
    /// so concurrent records create one node.
    async fn record_migration(&self, version: i64, description: &str) -> Result<()> {
        let query_str = format!(
            "MERGE (m:{} {{version: $version}}) \
             ON CREATE SET m.description = $description, m.applied_at = datetime()",
            Self::REGISTRY_LABEL,
        );
        self.graph
            .run(
                neo4rs::query(&query_str)
                    .param("version", version)
                    .param("description", description.to_string()),
            )
            .await
            .map_err(|e| {
                adk_core::AdkError::session(format!(
                    "{}",
                    crate::migration::MigrationError {
                        version,
                        description: description.to_string(),
                        cause: format!("registry record failed: {e}"),
                    }
                ))
            })?;
        Ok(())
    }
}

/// Runs one idempotent schema statement, succeeding when a concurrent `migrate` created
/// the same rule first.
async fn run_schema_statement(
    graph: &Graph,
    cypher: &str,
) -> std::result::Result<(), neo4rs::Error> {
    match graph.run(neo4rs::query(cypher)).await {
        Err(error) if crate::neo4j_stores::lost_schema_race(&error) => Ok(()),
        result => result,
    }
}

/// Serialize a `HashMap<String, Value>` to a JSON string for Neo4j storage.
fn state_to_json_string(
    state: &HashMap<String, Value>,
) -> std::result::Result<String, adk_core::AdkError> {
    serde_json::to_string(state)
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))
}

/// Deserialize a JSON string from Neo4j into a `HashMap<String, Value>`.
///
/// Returns an error if the string is not valid JSON. An empty string
/// is treated as an empty state (not an error).
fn json_string_to_state(
    s: &str,
) -> std::result::Result<HashMap<String, Value>, adk_core::AdkError> {
    if s.is_empty() {
        return Ok(HashMap::new());
    }
    serde_json::from_str::<HashMap<String, Value>>(s)
        .map_err(|e| adk_core::AdkError::session(format!("deserialize state failed: {e}")))
}

/// Prefix of the node property that holds one state key.
///
/// Each key is its own property holding the value as JSON, so an append writes its delta
/// with `SET n += $delta`: Neo4j locks the node for the statement and writes only the
/// delta's keys, and concurrent appends that touch different keys keep each other's
/// writes. The `state` property holds the JSON object written by `create` and by earlier
/// releases; a per-key property overrides the same key in it.
const STATE_KEY_PREFIX: &str = "state.";

/// Cypher list of `[property, json]` pairs for the per-key state properties of `node`.
fn state_entries(node: &str) -> String {
    format!("[key IN keys({node}) WHERE key STARTS WITH '{STATE_KEY_PREFIX}' | [key, {node}[key]]]")
}

/// Encodes a state delta as per-key node properties for `SET n += $delta`.
fn state_properties(
    delta: &HashMap<String, Value>,
) -> std::result::Result<HashMap<String, String>, adk_core::AdkError> {
    delta
        .iter()
        .map(|(key, value)| Ok((format!("{STATE_KEY_PREFIX}{key}"), serde_json::to_string(value)?)))
        .collect::<std::result::Result<_, serde_json::Error>>()
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))
}

/// Builds one node's state from its `state` JSON object and its per-key properties.
fn node_state(
    object: &str,
    entries: Vec<(String, String)>,
) -> std::result::Result<HashMap<String, Value>, adk_core::AdkError> {
    let mut state = json_string_to_state(object)?;
    for (property, json) in entries {
        if let Some(key) = property.strip_prefix(STATE_KEY_PREFIX) {
            let value = serde_json::from_str(&json).map_err(|e| {
                adk_core::AdkError::session(format!("deserialize state key '{key}' failed: {e}"))
            })?;
            state.insert(key.to_string(), value);
        }
    }
    Ok(state)
}

/// Reads the state of the node returned as `<column>` (its `state` object) and
/// `<column>_entries` (its per-key properties). A node that `OPTIONAL MATCH` did not find
/// has an empty state.
fn row_state(
    row: &neo4rs::Row,
    column: &str,
) -> std::result::Result<HashMap<String, Value>, adk_core::AdkError> {
    node_state(
        &row.get::<String>(column).unwrap_or_default(),
        row.get::<Vec<(String, String)>>(&format!("{column}_entries")).unwrap_or_default(),
    )
}

/// Writes `event` and its state delta to one session inside `txn`.
///
/// The session, app, and user nodes are locked in that order, the order `create` also
/// follows for the app and user nodes, so concurrent appends cannot deadlock.
async fn write_event(
    txn: &mut neo4rs::Txn,
    app_name: &str,
    user_id: &str,
    session_id: &str,
    event: &Event,
) -> Result<()> {
    let (app_delta, user_delta, session_delta) =
        state_utils::extract_state_deltas(&event.actions.state_delta);
    let now_str = event.timestamp.to_rfc3339();

    let mut updated = txn
        .execute(
            neo4rs::query(
                "MATCH (s:Session {session_id: $session_id, app_name: $app_name, \
                        user_id: $user_id}) \
                 SET s += $delta, s.updated_at = $now, \
                     s.event_seq = coalesce(s.event_seq, 0) + 1 \
                 RETURN s.event_seq AS seq",
            )
            .param("session_id", session_id.to_string())
            .param("app_name", app_name.to_string())
            .param("user_id", user_id.to_string())
            .param("delta", state_properties(&session_delta)?)
            .param("now", now_str.clone()),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
    // `event_seq` counts the session's appends; it orders events with equal timestamps.
    let seq = updated
        .next(&mut *txn)
        .await
        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?
        .ok_or_else(|| session_not_found_for(app_name, user_id, session_id))?
        .get::<i64>("seq")
        .unwrap_or_default();

    if !app_delta.is_empty() {
        txn.run(
            neo4rs::query(
                "MERGE (a:AppState {app_name: $app_name}) \
                 SET a += $delta, a.updated_at = $now",
            )
            .param("app_name", app_name.to_string())
            .param("delta", state_properties(&app_delta)?)
            .param("now", now_str.clone()),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
    }

    if !user_delta.is_empty() {
        txn.run(
            neo4rs::query(
                "MERGE (u:UserState {app_name: $app_name, user_id: $user_id}) \
                 SET u += $delta, u.updated_at = $now",
            )
            .param("app_name", app_name.to_string())
            .param("user_id", user_id.to_string())
            .param("delta", state_properties(&user_delta)?)
            .param("now", now_str.clone()),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
    }

    create_event(txn, app_name, user_id, session_id, event, seq).await
}

/// Creates the node of `event` at append position `seq` under its session, without touching
/// any state.
async fn create_event(
    txn: &mut neo4rs::Txn,
    app_name: &str,
    user_id: &str,
    session_id: &str,
    event: &Event,
    seq: i64,
) -> Result<()> {
    let llm_response_json = serde_json::to_string(&event.llm_response)
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
    let actions_json = serde_json::to_string(&event.actions)
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
    let tool_ids_json = serde_json::to_string(&event.long_running_tool_ids)
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;

    txn.run(
        neo4rs::query(
            "MATCH (s:Session {session_id: $session_id, app_name: $app_name, \
                    user_id: $user_id}) \
             CREATE (s)-[:HAS_EVENT]->(e:Event { \
                 id: $id, \
                 session_id: $session_id, \
                 invocation_id: $invocation_id, \
                 branch: $branch, \
                 author: $author, \
                 timestamp: $timestamp, \
                 seq: $seq, \
                 llm_response: $llm_response, \
                 actions: $actions, \
                 long_running_tool_ids: $long_running_tool_ids \
             })",
        )
        .param("session_id", session_id.to_string())
        .param("app_name", app_name.to_string())
        .param("user_id", user_id.to_string())
        .param("id", event.id.clone())
        .param("invocation_id", event.invocation_id.clone())
        .param("branch", event.branch.clone())
        .param("author", event.author.clone())
        .param("timestamp", event.timestamp.to_rfc3339())
        .param("seq", seq)
        .param("llm_response", llm_response_json)
        .param("actions", actions_json)
        .param("long_running_tool_ids", tool_ids_json),
    )
    .await
    .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;

    Ok(())
}

/// Reads the history of `identity` inside `txn`, with the names of its per-key state
/// properties. `lock` writes the session node first, which takes the lock every append takes.
async fn load_history(
    txn: &mut neo4rs::Txn,
    identity: &AdkIdentity,
    lock: bool,
) -> Result<(SessionHistory, Vec<String>)> {
    let lock_clause = if lock { "SET s.history_rev = coalesce(s.history_rev, 0) + 1 " } else { "" };
    let mut rows = txn
        .execute(
            neo4rs::query(&format!(
                "MATCH (s:Session {{app_name: $app_name, user_id: $user_id, \
                        session_id: $session_id}}) {lock_clause}\
                 RETURN s.state AS state, {} AS state_entries, s.initial_state AS initial_state",
                state_entries("s"),
            ))
            .param("app_name", identity.app_name.as_ref().to_string())
            .param("user_id", identity.user_id.as_ref().to_string())
            .param("session_id", identity.session_id.as_ref().to_string()),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
    let row = rows
        .next(&mut *txn)
        .await
        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
        .ok_or_else(|| identity_not_found(identity))?;
    let properties: Vec<String> = row
        .get::<Vec<(String, String)>>("state_entries")
        .unwrap_or_default()
        .into_iter()
        .map(|(property, _)| property)
        .collect();
    // Session records written by earlier releases also hold a copy of the app and user tiers.
    let (_, _, state) = state_utils::extract_state_deltas(&row_state(&row, "state")?);
    let initial_state = match row.get::<Option<String>>("initial_state").ok().flatten() {
        Some(json) => Some(json_string_to_state(&json)?),
        None => None,
    };
    drop(rows);

    let mut event_rows = txn
        .execute(
            neo4rs::query(
                "MATCH (s:Session {app_name: $app_name, user_id: $user_id, \
                        session_id: $session_id})-[:HAS_EVENT]->(e:Event) \
                 RETURN e.id AS id, e.invocation_id AS invocation_id, \
                        e.branch AS branch, e.author AS author, \
                        e.timestamp AS timestamp, e.llm_response AS llm_response, \
                        e.actions AS actions, \
                        e.long_running_tool_ids AS long_running_tool_ids \
                 ORDER BY e.timestamp, e.seq",
            )
            .param("app_name", identity.app_name.as_ref().to_string())
            .param("user_id", identity.user_id.as_ref().to_string())
            .param("session_id", identity.session_id.as_ref().to_string()),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
    let mut events = Vec::new();
    while let Some(row) = event_rows
        .next(&mut *txn)
        .await
        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
    {
        if let Some(event) = row_to_event(&row) {
            events.push(event);
        }
    }
    Ok((SessionHistory::new(events, state, initial_state), properties))
}

/// Applies a history rewrite inside `txn`, which holds the session node's lock from the read
/// to the commit.
async fn rewrite_in(
    txn: &mut neo4rs::Txn,
    req: &RewriteHistoryRequest,
    now: DateTime<Utc>,
) -> Result<RewrittenHistory> {
    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());
    let (history, properties) = load_history(txn, identity, true).await?;
    let rewritten = history.rewrite(identity, &req.rewrite, req.expected_version.as_deref())?;
    let change = &rewritten.change;

    if !change.removed.is_empty() {
        txn.run(
            neo4rs::query(
                "MATCH (s:Session {app_name: $app_name, user_id: $user_id, \
                        session_id: $session_id})-[:HAS_EVENT]->(e:Event) \
                 WHERE e.id IN $ids DETACH DELETE e",
            )
            .param("app_name", app_name.to_string())
            .param("user_id", user_id.to_string())
            .param("session_id", session_id.to_string())
            .param("ids", change.removed.clone()),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("delete events failed: {e}")))?;
    }
    for event in rewritten.events.iter().filter(|e| change.replaced.contains(&e.id)) {
        txn.run(
            neo4rs::query(
                "MATCH (s:Session {app_name: $app_name, user_id: $user_id, \
                        session_id: $session_id})-[:HAS_EVENT]->(e:Event {id: $id}) \
                 SET e.invocation_id = $invocation_id, e.branch = $branch, \
                     e.author = $author, e.llm_response = $llm_response, \
                     e.actions = $actions, e.long_running_tool_ids = $long_running_tool_ids",
            )
            .param("app_name", app_name.to_string())
            .param("user_id", user_id.to_string())
            .param("session_id", session_id.to_string())
            .param("id", event.id.clone())
            .param("invocation_id", event.invocation_id.clone())
            .param("branch", event.branch.clone())
            .param("author", event.author.clone())
            .param("llm_response", to_json(&event.llm_response)?)
            .param("actions", to_json(&event.actions)?)
            .param("long_running_tool_ids", to_json(&event.long_running_tool_ids)?),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("update event failed: {e}")))?;
    }

    // The rebuilt state replaces the `state` object; every per-key property is removed.
    let cleared: HashMap<String, Option<String>> =
        properties.into_iter().map(|property| (property, None)).collect();
    txn.run(
        neo4rs::query(
            "MATCH (s:Session {app_name: $app_name, user_id: $user_id, session_id: $session_id}) \
             SET s += $cleared, s.state = $state, s.updated_at = $now",
        )
        .param("app_name", app_name.to_string())
        .param("user_id", user_id.to_string())
        .param("session_id", session_id.to_string())
        .param("cleared", cleared)
        .param("state", state_to_json_string(&rewritten.state)?)
        .param("now", now.to_rfc3339()),
    )
    .await
    .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
    Ok(rewritten)
}

fn to_json<T: serde::Serialize + ?Sized>(value: &T) -> Result<String> {
    serde_json::to_string(value)
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))
}

/// Reads the current app and user tiers.
async fn read_tiers(
    graph: &Graph,
    app_name: &str,
    user_id: &str,
) -> Result<(HashMap<String, Value>, HashMap<String, Value>)> {
    let mut rows = graph
        .execute(
            neo4rs::query(&format!(
                "OPTIONAL MATCH (a:AppState {{app_name: $app_name}}) \
                 OPTIONAL MATCH (u:UserState {{app_name: $app_name, user_id: $user_id}}) \
                 RETURN a.state AS app_state, {} AS app_state_entries, \
                        u.state AS user_state, {} AS user_state_entries",
                state_entries("a"),
                state_entries("u"),
            ))
            .param("app_name", app_name.to_string())
            .param("user_id", user_id.to_string()),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
    match rows
        .next()
        .await
        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
    {
        Some(row) => Ok((row_state(&row, "app_state")?, row_state(&row, "user_state")?)),
        None => Ok((HashMap::new(), HashMap::new())),
    }
}

/// Convert a Neo4j row to an `Event`.
fn row_to_event(row: &neo4rs::Row) -> Option<Event> {
    let id = row.get::<String>("id").ok()?;
    let invocation_id = row.get::<String>("invocation_id").unwrap_or_default();
    let branch = row.get::<String>("branch").unwrap_or_default();
    let author = row.get::<String>("author").unwrap_or_default();
    let timestamp_str = row.get::<String>("timestamp").unwrap_or_default();
    let timestamp = DateTime::parse_from_rfc3339(&timestamp_str)
        .map(|dt| dt.with_timezone(&Utc))
        .unwrap_or_else(|_| Utc::now());

    let llm_response_str = row.get::<String>("llm_response").unwrap_or_default();
    let actions_str = row.get::<String>("actions").unwrap_or_default();
    let tool_ids_str = row.get::<String>("long_running_tool_ids").unwrap_or_default();

    let llm_response = serde_json::from_str(&llm_response_str).ok()?;
    let actions = serde_json::from_str(&actions_str).ok()?;
    let long_running_tool_ids = serde_json::from_str(&tool_ids_str).ok()?;

    Some(Event {
        id,
        timestamp,
        invocation_id,
        branch,
        author,
        llm_response,
        actions,
        long_running_tool_ids,
        llm_request: None,
        provider_metadata: std::collections::HashMap::new(),
    })
}

#[async_trait]
impl SessionService for Inline<Neo4jSessionService> {
    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
    async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>> {
        let session_id = req.session_id.unwrap_or_else(|| Uuid::new_v4().to_string());
        let now = Utc::now();
        let now_str = now.to_rfc3339();

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

        let conflict = || session_already_exists(&req.app_name, &req.user_id, &session_id);
        let mut txn = self
            .graph
            .start_txn()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;

        let mut existing = txn
            .execute(
                neo4rs::query(
                    "MATCH (s:Session {app_name: $app_name, user_id: $user_id, \
                            session_id: $session_id}) \
                     RETURN s.session_id AS session_id",
                )
                .param("app_name", req.app_name.clone())
                .param("user_id", req.user_id.clone())
                .param("session_id", session_id.clone()),
            )
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
        if existing
            .next(&mut txn)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
            .is_some()
        {
            return Err(conflict());
        }

        txn.run(
            neo4rs::query(
                "MERGE (a:AppState {app_name: $app_name}) \
                 SET a += $delta, a.updated_at = $now",
            )
            .param("app_name", req.app_name.clone())
            .param("delta", state_properties(&app_delta)?)
            .param("now", now_str.clone()),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("create failed: {e}")))?;

        txn.run(
            neo4rs::query(
                "MERGE (u:UserState {app_name: $app_name, user_id: $user_id}) \
                 SET u += $delta, u.updated_at = $now",
            )
            .param("app_name", req.app_name.clone())
            .param("user_id", req.user_id.clone())
            .param("delta", state_properties(&user_delta)?)
            .param("now", now_str.clone()),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("create failed: {e}")))?;

        // The session record holds session-scoped keys only; `get` reads the tiers.
        txn.run(
            neo4rs::query(
                "CREATE (s:Session { \
                     app_name: $app_name, \
                     user_id: $user_id, \
                     session_id: $session_id, \
                     state: $state, \
                     initial_state: $state, \
                     created_at: $now, \
                     updated_at: $now \
                 })",
            )
            .param("app_name", req.app_name.clone())
            .param("user_id", req.user_id.clone())
            .param("session_id", session_id.clone())
            .param("state", state_to_json_string(&session_state)?)
            .param("now", now_str.clone()),
        )
        .await
        .map_err(|e| {
            // The `session_unique` constraint rejects a concurrent create of the same identity.
            if e.to_string().contains("ConstraintValidationFailed") {
                conflict()
            } else {
                adk_core::AdkError::session(format!("create failed: {e}"))
            }
        })?;

        // Create relationships: Session -> AppState, Session -> UserState
        txn.run(
            neo4rs::query(
                "MATCH (s:Session {session_id: $session_id, app_name: $app_name, user_id: $user_id}), \
                       (a:AppState {app_name: $app_name}), \
                       (u:UserState {app_name: $app_name, user_id: $user_id}) \
                 CREATE (s)-[:HAS_APP_STATE]->(a), (s)-[:HAS_USER_STATE]->(u)",
            )
            .param("app_name", req.app_name.clone())
            .param("user_id", req.user_id.clone())
            .param("session_id", session_id.clone()),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("create failed: {e}")))?;

        // This transaction holds both tier locks, so the tiers read here are current.
        let mut tiers = txn
            .execute(
                neo4rs::query(&format!(
                    "MATCH (a:AppState {{app_name: $app_name}}), \
                           (u:UserState {{app_name: $app_name, user_id: $user_id}}) \
                     RETURN a.state AS app_state, {} AS app_state_entries, \
                            u.state AS user_state, {} AS user_state_entries",
                    state_entries("a"),
                    state_entries("u"),
                ))
                .param("app_name", req.app_name.clone())
                .param("user_id", req.user_id.clone()),
            )
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
        let (app_state, user_state) = match tiers
            .next(&mut txn)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
        {
            Some(row) => (row_state(&row, "app_state")?, row_state(&row, "user_state")?),
            None => (HashMap::new(), HashMap::new()),
        };

        txn.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;

        Ok(Box::new(Neo4jSession {
            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,
        }))
    }

    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id, session_id = %req.session_id))]
    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
        let mut row_stream = self
            .graph
            .execute(
                neo4rs::query(&format!(
                    "MATCH (s:Session {{app_name: $app_name, user_id: $user_id, session_id: $session_id}}) \
                     OPTIONAL MATCH (a:AppState {{app_name: $app_name}}) \
                     OPTIONAL MATCH (u:UserState {{app_name: $app_name, user_id: $user_id}}) \
                     RETURN s.state AS state, {} AS state_entries, s.updated_at AS updated_at, \
                            a.state AS app_state, {} AS app_state_entries, \
                            u.state AS user_state, {} AS user_state_entries",
                    state_entries("s"),
                    state_entries("a"),
                    state_entries("u"),
                ))
                .param("app_name", req.app_name.clone())
                .param("user_id", req.user_id.clone())
                .param("session_id", req.session_id.clone()),
            )
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;

        let row = row_stream
            .next()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
            .ok_or_else(|| crate::service::session_not_found(&req))?;

        let updated_at_str = row.get::<String>("updated_at").unwrap_or_default();
        let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
            .map(|dt| dt.with_timezone(&Utc))
            .unwrap_or_else(|_| Utc::now());

        let state = state_utils::merge_current_tiers(
            &row_state(&row, "app_state")?,
            &row_state(&row, "user_state")?,
            &row_state(&row, "state")?,
        );

        // Fetch events ordered by timestamp
        let mut event_stream = self
            .graph
            .execute(
                neo4rs::query(
                    "MATCH (s:Session {app_name: $app_name, user_id: $user_id, \
                            session_id: $session_id})-[:HAS_EVENT]->(e:Event) \
                     RETURN e.id AS id, e.invocation_id AS invocation_id, \
                            e.branch AS branch, e.author AS author, \
                            e.timestamp AS timestamp, e.llm_response AS llm_response, \
                            e.actions AS actions, \
                            e.long_running_tool_ids AS long_running_tool_ids \
                     ORDER BY e.timestamp, e.seq",
                )
                .param("app_name", req.app_name.clone())
                .param("user_id", req.user_id.clone())
                .param("session_id", req.session_id.clone()),
            )
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;

        let mut events: Vec<Event> = Vec::new();
        while let Some(row) = event_stream
            .next()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
        {
            if let Some(event) = row_to_event(&row) {
                events.push(event);
            }
        }

        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(Neo4jSession {
            app_name: req.app_name,
            user_id: req.user_id,
            session_id: req.session_id,
            state,
            events,
            updated_at,
        }))
    }

    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
        let limit = req.limit.unwrap_or(i64::MAX as usize) as i64;
        let offset = req.offset.unwrap_or(0) as i64;

        let mut tier_stream = self
            .graph
            .execute(
                neo4rs::query(&format!(
                    "OPTIONAL MATCH (a:AppState {{app_name: $app_name}}) \
                     OPTIONAL MATCH (u:UserState {{app_name: $app_name, user_id: $user_id}}) \
                     RETURN a.state AS app_state, {} AS app_state_entries, \
                            u.state AS user_state, {} AS user_state_entries",
                    state_entries("a"),
                    state_entries("u"),
                ))
                .param("app_name", req.app_name.clone())
                .param("user_id", req.user_id.clone()),
            )
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
        let tiers = tier_stream
            .next()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
        let tier = |column: &str| match &tiers {
            Some(row) => row_state(row, column),
            None => Ok(HashMap::new()),
        };
        let (app_state, user_state) = (tier("app_state")?, tier("user_state")?);

        let mut row_stream = self
            .graph
            .execute(
                neo4rs::query(&format!(
                    "MATCH (s:Session {{app_name: $app_name, user_id: $user_id}}) \
                     RETURN s.session_id AS session_id, s.state AS state, \
                            {} AS state_entries, s.updated_at AS updated_at \
                     ORDER BY s.updated_at DESC, s.session_id DESC \
                     SKIP $offset LIMIT $limit",
                    state_entries("s"),
                ))
                .param("app_name", req.app_name.clone())
                .param("user_id", req.user_id.clone())
                .param("offset", offset)
                .param("limit", limit),
            )
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;

        let mut sessions: Vec<Box<dyn Session>> = Vec::new();
        while let Some(row) = row_stream
            .next()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
        {
            let session_id = row.get::<String>("session_id").unwrap_or_default();
            let updated_at_str = row.get::<String>("updated_at").unwrap_or_default();
            let state = state_utils::merge_current_tiers(
                &app_state,
                &user_state,
                &row_state(&row, "state")?,
            );
            let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
                .map(|dt| dt.with_timezone(&Utc))
                .unwrap_or_else(|_| Utc::now());

            sessions.push(Box::new(Neo4jSession {
                app_name: req.app_name.clone(),
                user_id: req.user_id.clone(),
                session_id,
                state,
                events: Vec::new(),
                updated_at,
            }));
        }

        Ok(sessions)
    }

    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id, session_id = %req.session_id))]
    async fn delete(&self, req: DeleteRequest) -> Result<()> {
        let mut txn = self
            .graph
            .start_txn()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;

        // DETACH DELETE session and connected event nodes
        txn.run(
            neo4rs::query(
                "MATCH (s:Session {app_name: $app_name, user_id: $user_id, \
                        session_id: $session_id}) \
                 OPTIONAL MATCH (s)-[:HAS_EVENT]->(e:Event) \
                 DETACH DELETE s, e",
            )
            .param("app_name", req.app_name)
            .param("user_id", req.user_id)
            .param("session_id", req.session_id),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("delete failed: {e}")))?;

        txn.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;

        Ok(())
    }

    #[instrument(skip_all, fields(session_id = %session_id))]
    async fn append_event(&self, session_id: &str, mut event: Event) -> Result<()> {
        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));

        let mut txn = self
            .graph
            .start_txn()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;

        // Find the session
        let mut row_stream = txn
            .execute(
                neo4rs::query(
                    "MATCH (s:Session {session_id: $session_id}) \
                     RETURN s.app_name AS app_name, s.user_id AS user_id",
                )
                .param("session_id", session_id.to_string()),
            )
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;

        let row = row_stream
            .next(&mut txn)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
            .ok_or_else(|| session_id_not_found(session_id))?;

        let app_name = row.get::<String>("app_name").unwrap_or_default();
        let user_id = row.get::<String>("user_id").unwrap_or_default();

        write_event(&mut txn, &app_name, &user_id, session_id, &event).await?;

        txn.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;

        Ok(())
    }

    #[instrument(skip_all, fields(
        app_name = %req.identity.app_name,
        user_id = %req.identity.user_id,
        session_id = %req.identity.session_id,
    ))]
    async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
        let mut event = req.event;
        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));

        let mut txn = self
            .graph
            .start_txn()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;

        write_event(
            &mut txn,
            req.identity.app_name.as_ref(),
            req.identity.user_id.as_ref(),
            req.identity.session_id.as_ref(),
            &event,
        )
        .await?;

        txn.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;

        Ok(())
    }
    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
        let mut txn = self
            .graph
            .start_txn()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;

        txn.run(
            neo4rs::query(
                "MATCH (s:Session {app_name: $app_name, user_id: $user_id}) \
                 OPTIONAL MATCH (s)-[:HAS_EVENT]->(e:Event) \
                 DETACH DELETE s, e",
            )
            .param("app_name", app_name.to_string())
            .param("user_id", user_id.to_string()),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("delete_all_sessions failed: {e}")))?;

        txn.run(
            neo4rs::query(
                "MATCH (u:UserState {app_name: $app_name, user_id: $user_id}) DETACH DELETE u",
            )
            .param("app_name", app_name.to_string())
            .param("user_id", user_id.to_string()),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("delete_all_sessions failed: {e}")))?;

        txn.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;

        Ok(())
    }

    #[instrument(skip_all)]
    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
        let mut txn = self
            .graph
            .start_txn()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;
        let (history, _) = load_history(&mut txn, identity, false).await?;
        txn.rollback()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("rollback failed: {e}")))?;
        Ok(history)
    }

    async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
        let now = Utc::now();
        let mut txn = self
            .graph
            .start_txn()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;
        let rewritten = match rewrite_in(&mut txn, &req, now).await {
            Ok(rewritten) => rewritten,
            Err(error) => {
                txn.rollback().await.ok();
                return Err(error);
            }
        };
        txn.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;
        let identity = &req.identity;
        let (app_state, user_state) =
            read_tiers(&self.graph, identity.app_name.as_ref(), identity.user_id.as_ref()).await?;
        let session = Box::new(Neo4jSession {
            app_name: identity.app_name.as_ref().to_string(),
            user_id: identity.user_id.as_ref().to_string(),
            session_id: identity.session_id.as_ref().to_string(),
            state: state_utils::merge_states(&app_state, &user_state, &rewritten.state),
            events: rewritten.events,
            updated_at: now,
        });
        Ok(HistoryOutcome::new(session, rewritten.change))
    }

    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());
        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 conflict = || session_already_exists(app_name, user_id, session_id);

        let mut txn = self
            .graph
            .start_txn()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("transaction failed: {e}")))?;
        let mut existing = txn
            .execute(
                neo4rs::query(
                    "MATCH (s:Session {app_name: $app_name, user_id: $user_id, \
                            session_id: $session_id}) \
                     RETURN s.session_id AS session_id",
                )
                .param("app_name", app_name.to_string())
                .param("user_id", user_id.to_string())
                .param("session_id", session_id.to_string()),
            )
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
        if existing
            .next(&mut txn)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
            .is_some()
        {
            return Err(conflict());
        }
        drop(existing);

        let event_count = i64::try_from(req.events.len()).unwrap_or(i64::MAX);
        txn.run(
            neo4rs::query(
                "MERGE (a:AppState {app_name: $app_name}) ON CREATE SET a.updated_at = $created \
                 MERGE (u:UserState {app_name: $app_name, user_id: $user_id}) \
                     ON CREATE SET u.updated_at = $created \
                 CREATE (s:Session { \
                     app_name: $app_name, user_id: $user_id, session_id: $session_id, \
                     state: $state, initial_state: $initial_state, event_seq: $event_seq, \
                     created_at: $created, updated_at: $updated \
                 }) \
                 CREATE (s)-[:HAS_APP_STATE]->(a), (s)-[:HAS_USER_STATE]->(u)",
            )
            .param("app_name", app_name.to_string())
            .param("user_id", user_id.to_string())
            .param("session_id", session_id.to_string())
            .param("state", state_to_json_string(&state)?)
            .param("initial_state", state_to_json_string(&initial_state)?)
            .param("event_seq", event_count)
            .param("created", Utc::now().to_rfc3339())
            .param("updated", updated_at.to_rfc3339()),
        )
        .await
        .map_err(|e| {
            if e.to_string().contains("ConstraintValidationFailed") {
                conflict()
            } else {
                adk_core::AdkError::session(format!("import failed: {e}"))
            }
        })?;
        for (event, seq) in req.events.iter().zip(1_i64..) {
            create_event(&mut txn, app_name, user_id, session_id, event, seq).await?;
        }
        txn.commit()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;

        let (app_state, user_state) = read_tiers(&self.graph, app_name, user_id).await?;
        Ok(Box::new(Neo4jSession {
            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,
        }))
    }

    async fn health_check(&self) -> Result<()> {
        let _ = self
            .graph
            .execute(neo4rs::query("RETURN 1"))
            .await
            .map_err(|e| adk_core::AdkError::session(format!("health check failed: {e}")))?;
        Ok(())
    }
}

#[async_trait]
impl SessionService for Neo4jSessionService {
    async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>> {
        req.try_identity()?;
        let inline = Inline(self.clone());
        detached(async move { inline.create(req).await }).await
    }

    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
        req.try_identity()?;
        let inline = Inline(self.clone());
        detached(async move { inline.get(req).await }).await
    }

    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
        validate_scope(&req.app_name, &req.user_id)?;
        let inline = Inline(self.clone());
        detached(async move { inline.list(req).await }).await
    }

    async fn delete(&self, req: DeleteRequest) -> Result<()> {
        req.try_identity()?;
        let inline = Inline(self.clone());
        detached(async move { inline.delete(req).await }).await
    }

    async fn append_event(&self, session_id: &str, event: Event) -> Result<()> {
        validate_session_id(session_id)?;
        let inline = Inline(self.clone());
        let session_id = session_id.to_owned();
        detached(async move { inline.append_event(&session_id, event).await }).await
    }

    async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
        let inline = Inline(self.clone());
        detached(async move { inline.append_event_for_identity(req).await }).await
    }

    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
        validate_scope(app_name, user_id)?;
        let inline = Inline(self.clone());
        let app_name = app_name.to_owned();
        let user_id = user_id.to_owned();
        detached(async move { inline.delete_all_sessions(&app_name, &user_id).await }).await
    }

    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
        let inline = Inline(self.clone());
        let identity = identity.clone();
        detached(async move { inline.history(&identity).await }).await
    }

    async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
        let inline = Inline(self.clone());
        detached(async move { inline.rewrite_history(req).await }).await
    }

    async fn import_session(&self, req: ImportSessionRequest) -> Result<Box<dyn Session>> {
        let inline = Inline(self.clone());
        detached(async move { inline.import_session(req).await }).await
    }

    async fn health_check(&self) -> Result<()> {
        let inline = Inline(self.clone());
        detached(async move { inline.health_check().await }).await
    }
}

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

impl Session for Neo4jSession {
    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 Neo4jSession {
    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 Neo4jSession {
    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)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn state(pairs: &[(&str, Value)]) -> HashMap<String, Value> {
        pairs.iter().map(|(key, value)| (key.to_string(), value.clone())).collect()
    }

    #[test]
    fn a_delta_becomes_one_json_property_per_key() {
        let delta = state(&[
            ("theme", json!("dark")),
            ("limits", json!({"daily": 5})),
            ("gone", Value::Null),
        ]);

        let properties = state_properties(&delta).unwrap();

        let expected: HashMap<String, String> = [
            ("state.theme", r#""dark""#),
            ("state.limits", r#"{"daily":5}"#),
            ("state.gone", "null"),
        ]
        .into_iter()
        .map(|(key, value)| (key.to_string(), value.to_string()))
        .collect();
        assert_eq!(properties, expected);
    }

    #[test]
    fn per_key_properties_override_the_state_object() {
        let object = r#"{"theme":"light","language":"en"}"#;
        let entries = vec![
            ("state.theme".to_string(), r#""dark""#.to_string()),
            ("state.flag".to_string(), "true".to_string()),
            // Not a state property; `state_entries` filters these out, and so does the reader.
            ("app_name".to_string(), "app".to_string()),
        ];

        let merged = node_state(object, entries).unwrap();

        assert_eq!(
            merged,
            state(&[("theme", json!("dark")), ("language", json!("en")), ("flag", json!(true))])
        );
    }

    #[test]
    fn written_properties_read_back_as_the_same_state() {
        let delta = state(&[("app:nested", json!({"a": [1, 2]})), ("plain", json!(3))]);
        let entries = state_properties(&delta).unwrap().into_iter().collect();

        assert_eq!(node_state("", entries).unwrap(), delta);
    }

    #[test]
    fn a_property_that_is_not_json_is_an_error() {
        let error = node_state("", vec![("state.theme".to_string(), "{".to_string())]).unwrap_err();
        assert!(error.to_string().contains("state key 'theme'"), "{error}");
    }

    #[test]
    fn the_entries_expression_selects_only_state_properties() {
        assert_eq!(
            state_entries("a"),
            "[key IN keys(a) WHERE key STARTS WITH 'state.' | [key, a[key]]]"
        );
    }
}