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
//! MongoDB session service backend.
//!
//! Provides [`MongoSessionService`] for session persistence using MongoDB.
//! Enabled via the `mongodb` feature flag.
//!
//! Supports both standalone and replica-set deployments. Transactions are
//! used automatically when the deployment supports them (replica set / sharded
//! cluster). On standalone deployments, operations execute sequentially
//! without transactions — the upsert-based writes are idempotent, so partial
//! failures leave state recoverable.
//!
//! # Example
//!
//! ```rust,ignore
//! let service = MongoSessionService::new("mongodb://localhost:27017", "adk_sessions").await?;
//! service.migrate().await?;
//! ```

use crate::history::{
    HistoryOutcome, ImportSessionRequest, RewriteHistoryRequest, RewrittenHistory, SessionHistory,
};
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::identity::AdkIdentity;
use adk_core::{ErrorCategory, ErrorComponent, Result};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use mongodb::bson::{self, Document, doc};
use mongodb::options::{FindOptions, IndexOptions, ReturnDocument, UpdateOptions};
use mongodb::{Client, Database, IndexModel};
use serde_json::Value;
use std::collections::HashMap;
use tracing::instrument;
use uuid::Uuid;

/// Whether the deployment that sent `reply` to `hello` runs multi-document transactions.
///
/// A replica set member names its set (`setName`), and the `mongos` router of a sharded
/// cluster answers `msg: "isdbgrid"`; a standalone `mongod` does neither.
pub(crate) fn hello_supports_transactions(reply: &Document) -> bool {
    reply.contains_key("setName") || reply.get_str("msg") == Ok("isdbgrid")
}

/// MongoDB-backed session service implementing [`SessionService`].
///
/// Uses four collections for the three-tier state model:
/// - `sessions` — session documents with session-level state
/// - `events` — event documents linked by `session_id`
/// - `app_states` — application-level state keyed by `app_name`
/// - `user_states` — user-level state keyed by `(app_name, user_id)`
///
/// Automatically detects whether the MongoDB deployment supports transactions
/// (replica set or sharded cluster) and falls back to non-transactional
/// sequential writes on standalone deployments.
pub struct MongoSessionService {
    db: Database,
    supports_transactions: bool,
}

impl MongoSessionService {
    /// Connect to MongoDB using a connection string and database name.
    ///
    /// Automatically detects whether the deployment supports transactions from the
    /// `hello` command: a replica set member and a sharded cluster's `mongos` router do,
    /// a standalone server does not. A failed `hello` is treated as standalone.
    pub async fn new(connection_string: &str, database_name: &str) -> Result<Self> {
        let client_options = mongodb::options::ClientOptions::parse(connection_string)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("mongodb connection failed: {e}")))?;
        let client = Client::with_options(client_options)
            .map_err(|e| adk_core::AdkError::session(format!("mongodb connection failed: {e}")))?;
        let db = client.database(database_name);

        let supports_transactions = match db.run_command(doc! { "hello": 1 }).await {
            Ok(reply) => hello_supports_transactions(&reply),
            Err(error) => {
                tracing::warn!(error = %error, "mongodb hello failed; writing without transactions");
                false
            }
        };

        if supports_transactions {
            tracing::info!("mongodb replica set or sharded cluster detected; transactions enabled");
        } else {
            tracing::info!(
                "mongodb standalone detected; writing sequentially without transactions"
            );
        }

        Ok(Self { db, supports_transactions })
    }

    /// Returns whether this deployment supports multi-document transactions.
    pub fn supports_transactions(&self) -> bool {
        self.supports_transactions
    }

    const REGISTRY_COLLECTION: &'static str = "_adk_session_migrations";

    const MONGO_SESSION_MIGRATIONS: &'static [(i64, &'static str)] =
        &[(1, "create initial indexes"), (2, "index events in read order")];

    /// Run versioned migrations for MongoDB session storage.
    ///
    /// Several processes may migrate one database at once: every step creates its
    /// indexes idempotently, and each version is recorded with an upsert, so a version
    /// another process recorded first is not an error.
    pub async fn migrate(&self) -> Result<()> {
        self.db
            .collection::<Document>(Self::REGISTRY_COLLECTION)
            .create_index(
                IndexModel::builder()
                    .keys(doc! { "version": 1 })
                    .options(
                        IndexOptions::builder()
                            .unique(true)
                            .name("idx_migration_version_unique".to_string())
                            .build(),
                    )
                    .build(),
            )
            .await
            .map_err(|e| {
                adk_core::AdkError::session(format!("migration registry creation failed: {e}"))
            })?;

        let mut max_applied = self.read_max_applied_version().await?;

        if max_applied == 0 {
            let existing = self.detect_existing_tables().await?;
            if existing
                && let Some(&(version, description)) = Self::MONGO_SESSION_MIGRATIONS.first()
            {
                self.record_migration(version, description).await?;
                max_applied = version;
            }
        }

        let max_compiled = Self::MONGO_SESSION_MIGRATIONS.last().map(|s| s.0).unwrap_or(0);
        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."
            )));
        }

        for &(version, description) in Self::MONGO_SESSION_MIGRATIONS {
            if version <= max_applied {
                continue;
            }
            run_mongo_session_step(&self.db, version).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 migrations have been applied.
    pub async fn schema_version(&self) -> Result<i64> {
        let collections = self.db.list_collection_names().await.map_err(|e| {
            adk_core::AdkError::session(format!("schema version query failed: {e}"))
        })?;
        if !collections.contains(&Self::REGISTRY_COLLECTION.to_string()) {
            return Ok(0);
        }
        self.read_max_applied_version().await
    }

    async fn read_max_applied_version(&self) -> Result<i64> {
        use mongodb::options::FindOneOptions;
        let registry = self.db.collection::<Document>(Self::REGISTRY_COLLECTION);
        let opts = FindOneOptions::builder().sort(doc! { "version": -1 }).build();
        let result = registry.find_one(doc! {}).with_options(opts).await.map_err(|e| {
            adk_core::AdkError::session(format!("migration registry read failed: {e}"))
        })?;
        match result {
            Some(doc) => Ok(doc.get_i64("version").unwrap_or(0)),
            None => Ok(0),
        }
    }

    /// Whether v1's last index exists. A first `migrate` running in another process
    /// creates v1's indexes in order, so an earlier one existing does not mean v1 is
    /// complete.
    async fn detect_existing_tables(&self) -> Result<bool> {
        let failed = |e: mongodb::error::Error| {
            adk_core::AdkError::session(format!("baseline detection failed: {e}"))
        };
        let collections = self.db.list_collection_names().await.map_err(failed)?;
        if !collections.iter().any(|name| name == "user_states") {
            return Ok(false);
        }
        let indexes = self
            .db
            .collection::<Document>("user_states")
            .list_index_names()
            .await
            .map_err(failed)?;
        Ok(indexes.iter().any(|name| name == "idx_user_states_unique"))
    }

    /// Records `version` unless another process recorded it first.
    async fn record_migration(&self, version: i64, description: &str) -> Result<()> {
        let registry = self.db.collection::<Document>(Self::REGISTRY_COLLECTION);
        let now = chrono_to_bson_dt(Utc::now());
        let recorded = registry
            .update_one(
                doc! { "version": version },
                doc! { "$setOnInsert": { "description": description, "applied_at": now } },
            )
            .upsert(true)
            .await;
        // The server retries an upsert that loses a race on the unique `version` index;
        // a duplicate key that still surfaces means the version is recorded.
        match recorded {
            Ok(_) => Ok(()),
            Err(e) if is_duplicate_key(&e) => Ok(()),
            Err(e) => Err(e),
        }
        .map_err(|e| {
            adk_core::AdkError::session(format!(
                "{}",
                crate::migration::MigrationError {
                    version,
                    description: description.to_string(),
                    cause: format!("registry record failed: {e}"),
                }
            ))
        })?;
        Ok(())
    }

    /// Start a transaction if supported, otherwise return None.
    async fn maybe_start_transaction(&self) -> Result<Option<mongodb::ClientSession>> {
        if self.supports_transactions {
            let mut s =
                self.db.client().start_session().await.map_err(|e| {
                    adk_core::AdkError::session(format!("session start failed: {e}"))
                })?;
            s.start_transaction().await.map_err(|e| {
                adk_core::AdkError::session(format!("transaction start failed: {e}"))
            })?;
            Ok(Some(s))
        } else {
            Ok(None)
        }
    }

    /// Commit a transaction if one is active.
    async fn maybe_commit(session: &mut Option<mongodb::ClientSession>) -> Result<()> {
        if let Some(s) = session {
            s.commit_transaction()
                .await
                .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;
        }
        Ok(())
    }
}

// ── Migration steps ──

async fn run_mongo_session_step(db: &Database, version: i64) -> Result<()> {
    match version {
        1 => mongo_session_v1(db).await,
        2 => mongo_session_v2(db).await,
        _ => Err(adk_core::AdkError::session(format!("unknown migration version: {version}"))),
    }
}

async fn mongo_session_v1(db: &Database) -> Result<()> {
    db.collection::<Document>("sessions")
        .create_index(
            IndexModel::builder()
                .keys(doc! { "app_name": 1, "user_id": 1, "session_id": 1 })
                .options(
                    IndexOptions::builder()
                        .unique(true)
                        .name("idx_sessions_unique".to_string())
                        .build(),
                )
                .build(),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;

    db.collection::<Document>("events")
        .create_index(
            IndexModel::builder()
                .keys(doc! { "session_id": 1, "timestamp": 1 })
                .options(IndexOptions::builder().name("idx_events_session_ts".to_string()).build())
                .build(),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;

    db.collection::<Document>("app_states")
        .create_index(
            IndexModel::builder()
                .keys(doc! { "app_name": 1 })
                .options(
                    IndexOptions::builder()
                        .unique(true)
                        .name("idx_app_states_unique".to_string())
                        .build(),
                )
                .build(),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;

    db.collection::<Document>("user_states")
        .create_index(
            IndexModel::builder()
                .keys(doc! { "app_name": 1, "user_id": 1 })
                .options(
                    IndexOptions::builder()
                        .unique(true)
                        .name("idx_user_states_unique".to_string())
                        .build(),
                )
                .build(),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;

    Ok(())
}

/// Indexes events by session and read order: timestamp, then the append sequence `seq`.
async fn mongo_session_v2(db: &Database) -> Result<()> {
    db.collection::<Document>("events")
        .create_index(
            IndexModel::builder()
                .keys(doc! {
                    "app_name": 1, "user_id": 1, "session_id": 1, "timestamp": 1, "seq": 1,
                })
                .options(IndexOptions::builder().name("idx_events_read_order".to_string()).build())
                .build(),
        )
        .await
        .map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;
    Ok(())
}

/// Whether `error` is a duplicate-key violation of a unique index.
fn is_duplicate_key(error: &mongodb::error::Error) -> bool {
    use mongodb::error::{ErrorKind, WriteFailure};
    match &*error.kind {
        ErrorKind::Write(WriteFailure::WriteError(write)) => write.code == 11000,
        _ => false,
    }
}

/// Attempts a history rewrite makes before giving up on a session that keeps changing between
/// the read and the write.
const MAX_REWRITE_ATTEMPTS: usize = 16;

// ── BSON helpers ──

fn state_to_bson(
    state: &HashMap<String, Value>,
) -> std::result::Result<Document, adk_core::AdkError> {
    let json_value = serde_json::to_value(state)
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
    let bson_value = bson::to_bson(&json_value)
        .map_err(|e| adk_core::AdkError::session(format!("bson conversion failed: {e}")))?;
    match bson_value {
        bson::Bson::Document(doc) => Ok(doc),
        _ => Ok(Document::new()),
    }
}

fn bson_to_state(doc: &Document) -> HashMap<String, Value> {
    let bson_value = bson::Bson::Document(doc.clone());
    match bson::from_bson::<serde_json::Value>(bson_value) {
        Ok(Value::Object(map)) => map.into_iter().collect(),
        _ => HashMap::new(),
    }
}

fn chrono_to_bson_dt(dt: DateTime<Utc>) -> bson::DateTime {
    bson::DateTime::from_millis(dt.timestamp_millis())
}

fn bson_dt_to_chrono(dt: bson::DateTime) -> DateTime<Utc> {
    let millis = dt.timestamp_millis();
    DateTime::from_timestamp_millis(millis).unwrap_or_default()
}

/// Builds an update pipeline that merges `delta` into a document's `state` and sets
/// `updated_at`.
///
/// `$mergeObjects` runs against the stored document while the write holds it, so
/// concurrent writers of different keys never overwrite each other. `$literal` keeps
/// keys and values that would otherwise parse as expressions (a leading `$`) as data.
fn merge_state_pipeline(
    delta: &HashMap<String, Value>,
    updated_at: bson::DateTime,
) -> std::result::Result<Vec<Document>, adk_core::AdkError> {
    let delta = state_to_bson(delta)?;
    Ok(vec![doc! { "$set": {
        "state": { "$mergeObjects": [{ "$ifNull": ["$state", {}] }, { "$literal": delta }] },
        "updated_at": updated_at,
    } }])
}

// ── Session-optional DB operation helpers ──
// Each helper accepts Option<&mut ClientSession>. When Some, the op runs
// inside the transaction; when None, it runs standalone.

macro_rules! with_optional_session {
    ($action:expr, $session:expr) => {
        match $session {
            Some(s) => $action.session(s).await,
            None => $action.await,
        }
    };
}

impl MongoSessionService {
    /// Reads the current app and user state tiers.
    async fn read_tiers(
        &self,
        txn: &mut Option<mongodb::ClientSession>,
        app_name: &str,
        user_id: &str,
    ) -> Result<(HashMap<String, Value>, HashMap<String, Value>)> {
        let app_coll = self.db.collection::<Document>("app_states");
        let user_coll = self.db.collection::<Document>("user_states");

        let app_state =
            with_optional_session!(app_coll.find_one(doc! { "app_name": app_name }), txn.as_mut())
                .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
                .and_then(|d| d.get_document("state").ok().map(bson_to_state))
                .unwrap_or_default();
        let user_state = with_optional_session!(
            user_coll.find_one(doc! { "app_name": app_name, "user_id": user_id }),
            txn.as_mut()
        )
        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
        .and_then(|d| d.get_document("state").ok().map(bson_to_state))
        .unwrap_or_default();

        Ok((app_state, user_state))
    }

    /// Merges each non-empty tier delta into the stored tier.
    async fn apply_tier_deltas(
        &self,
        txn: &mut Option<mongodb::ClientSession>,
        app_name: &str,
        user_id: &str,
        app_delta: &HashMap<String, Value>,
        user_delta: &HashMap<String, Value>,
        updated_at: bson::DateTime,
    ) -> Result<()> {
        let upsert = UpdateOptions::builder().upsert(true).build();
        if !app_delta.is_empty() {
            let app_coll = self.db.collection::<Document>("app_states");
            with_optional_session!(
                app_coll
                    .update_one(
                        doc! { "app_name": app_name },
                        merge_state_pipeline(app_delta, updated_at)?
                    )
                    .with_options(upsert.clone()),
                txn.as_mut()
            )
            .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
        }
        if !user_delta.is_empty() {
            let user_coll = self.db.collection::<Document>("user_states");
            with_optional_session!(
                user_coll
                    .update_one(
                        doc! { "app_name": app_name, "user_id": user_id },
                        merge_state_pipeline(user_delta, updated_at)?
                    )
                    .with_options(upsert),
                txn.as_mut()
            )
            .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
        }
        Ok(())
    }

    /// Reads the history of `identity`, with the session document's `event_seq` and
    /// `updated_at` as stored, which a rewrite requires to be unchanged when it writes.
    async fn load_history(
        &self,
        txn: &mut Option<mongodb::ClientSession>,
        identity: &AdkIdentity,
    ) -> Result<(SessionHistory, bson::Bson, bson::Bson)> {
        let filter = doc! {
            "app_name": identity.app_name.as_ref(),
            "user_id": identity.user_id.as_ref(),
            "session_id": identity.session_id.as_ref(),
        };
        let session_doc = with_optional_session!(
            self.db.collection::<Document>("sessions").find_one(filter.clone()),
            txn.as_mut()
        )
        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
        .ok_or_else(|| identity_not_found(identity))?;
        let stored = session_doc.get_document("state").map(bson_to_state).unwrap_or_default();
        // Documents written by earlier releases also hold a copy of the app and user tiers.
        let (_, _, state) = state_utils::extract_state_deltas(&stored);
        let initial_state = session_doc.get_document("initial_state").ok().map(bson_to_state);
        let event_seq = session_doc.get("event_seq").cloned().unwrap_or(bson::Bson::Null);
        let updated_at = session_doc.get("updated_at").cloned().unwrap_or(bson::Bson::Null);

        let events_coll = self.db.collection::<Document>("events");
        let options = FindOptions::builder().sort(doc! { "timestamp": 1, "seq": 1 }).build();
        let query_error =
            |e: mongodb::error::Error| adk_core::AdkError::session(format!("query failed: {e}"));
        let mut docs = Vec::new();
        match txn.as_mut() {
            Some(session) => {
                let mut cursor = events_coll
                    .find(filter)
                    .with_options(options)
                    .session(&mut *session)
                    .await
                    .map_err(query_error)?;
                while cursor.advance(&mut *session).await.map_err(query_error)? {
                    docs.push(cursor.deserialize_current().map_err(query_error)?);
                }
            }
            None => {
                let mut cursor =
                    events_coll.find(filter).with_options(options).await.map_err(query_error)?;
                while cursor.advance().await.map_err(query_error)? {
                    docs.push(cursor.deserialize_current().map_err(query_error)?);
                }
            }
        }
        let events = docs.iter().filter_map(doc_to_event).collect();
        Ok((SessionHistory::new(events, state, initial_state), event_seq, updated_at))
    }

    /// One attempt at a rewrite: `None` when the session changed between the read and the
    /// guarded write, so the caller reads it again.
    async fn try_rewrite(
        &self,
        req: &RewriteHistoryRequest,
    ) -> Result<Option<(RewrittenHistory, DateTime<Utc>)>> {
        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 mut txn = self.maybe_start_transaction().await?;
        let (history, event_seq, updated_at) = self.load_history(&mut txn, identity).await?;
        let rewritten = history.rewrite(identity, &req.rewrite, req.expected_version.as_deref())?;

        let now = Utc::now();
        // The session document is written first and only while it still holds the append
        // count and update time that were read, so without a transaction a concurrent append
        // fails the guard instead of being overwritten.
        let claimed = with_optional_session!(
            self.db.collection::<Document>("sessions").update_one(
                doc! {
                    "app_name": app_name, "user_id": user_id, "session_id": session_id,
                    "event_seq": event_seq, "updated_at": updated_at,
                },
                doc! { "$set": {
                    "state": state_to_bson(&rewritten.state)?,
                    "updated_at": chrono_to_bson_dt(now),
                } }
            ),
            txn.as_mut()
        )
        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
        if claimed.matched_count == 0 {
            if let Some(session) = txn.as_mut() {
                session.abort_transaction().await.ok();
            }
            return Ok(None);
        }

        let events_coll = self.db.collection::<Document>("events");
        let change = &rewritten.change;
        if !change.removed.is_empty() {
            with_optional_session!(
                events_coll.delete_many(doc! {
                    "app_name": app_name, "user_id": user_id, "session_id": session_id,
                    "id": { "$in": &change.removed },
                }),
                txn.as_mut()
            )
            .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)) {
            let replacement = event_doc(app_name, user_id, session_id, event, 0)?;
            with_optional_session!(
                events_coll.update_one(
                    doc! {
                        "app_name": app_name, "user_id": user_id, "session_id": session_id,
                        "id": &event.id,
                    },
                    doc! { "$set": {
                        "invocation_id": replacement.get("invocation_id").cloned(),
                        "branch": replacement.get("branch").cloned(),
                        "author": replacement.get("author").cloned(),
                        "llm_response": replacement.get("llm_response").cloned(),
                        "actions": replacement.get("actions").cloned(),
                        "long_running_tool_ids": replacement.get("long_running_tool_ids").cloned(),
                    } }
                ),
                txn.as_mut()
            )
            .map_err(|e| adk_core::AdkError::session(format!("update event failed: {e}")))?;
        }
        Self::maybe_commit(&mut txn).await?;
        Ok(Some((rewritten, now)))
    }

    /// Applies `event` to the session `(app_name, user_id, session_id)`: merges each
    /// tier's delta, bumps `updated_at`, and inserts the event.
    async fn apply_event(
        &self,
        txn: &mut Option<mongodb::ClientSession>,
        app_name: &str,
        user_id: &str,
        session_id: &str,
        event: &Event,
    ) -> Result<()> {
        let sess_coll = self.db.collection::<Document>("sessions");
        let ev_coll = self.db.collection::<Document>("events");

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

        // `event_seq` counts the session's appends; it orders events with equal timestamps,
        // which millisecond BSON dates make common.
        let mut pipeline = merge_state_pipeline(&session_delta, bson_ts)?;
        if let Some(set) =
            pipeline.first_mut().and_then(|stage| stage.get_document_mut("$set").ok())
        {
            set.insert(
                "event_seq",
                doc! { "$add": [{ "$toLong": { "$ifNull": ["$event_seq", 0] } }, 1] },
            );
        }
        let updated = with_optional_session!(
            sess_coll
                .find_one_and_update(
                    doc! { "app_name": app_name, "user_id": user_id, "session_id": session_id },
                    pipeline
                )
                .return_document(ReturnDocument::After)
                .projection(doc! { "event_seq": 1 }),
            txn.as_mut()
        )
        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?
        .ok_or_else(|| session_not_found_for(app_name, user_id, session_id))?;
        let seq = updated
            .get_i64("event_seq")
            .or_else(|_| updated.get_i32("event_seq").map(i64::from))
            .unwrap_or_default();

        self.apply_tier_deltas(txn, app_name, user_id, &app_delta, &user_delta, bson_ts).await?;

        with_optional_session!(
            ev_coll.insert_one(event_doc(app_name, user_id, session_id, event, seq)?),
            txn.as_mut()
        )
        .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;

        Ok(())
    }
}

// ── SessionService implementation ──

#[async_trait]
impl SessionService for MongoSessionService {
    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
    async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>> {
        req.try_identity()?;
        let session_id = req.session_id.unwrap_or_else(|| Uuid::new_v4().to_string());
        let now = Utc::now();
        let bson_now = chrono_to_bson_dt(now);
        let (app_delta, user_delta, session_state) = state_utils::extract_state_deltas(&req.state);

        let sess_coll = self.db.collection::<Document>("sessions");

        let conflict = || session_already_exists(&req.app_name, &req.user_id, &session_id);
        let identity = doc! {
            "app_name": &req.app_name, "user_id": &req.user_id, "session_id": &session_id,
        };
        let mut txn = self.maybe_start_transaction().await?;

        // The session document is written before the tiers, so a create that conflicts writes
        // nothing even without a transaction; the unique index catches a concurrent create.
        let existing = with_optional_session!(sess_coll.find_one(identity.clone()), txn.as_mut())
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
        if existing.is_some() {
            return Err(conflict());
        }
        let session_bson = state_to_bson(&session_state)?;
        let mut session_doc = identity;
        session_doc.insert("initial_state", session_bson.clone());
        session_doc.insert("state", session_bson);
        session_doc.insert("created_at", bson_now);
        session_doc.insert("updated_at", bson_now);
        with_optional_session!(sess_coll.insert_one(session_doc), txn.as_mut()).map_err(|e| {
            if is_duplicate_key(&e) {
                conflict()
            } else {
                adk_core::AdkError::session(format!("insert failed: {e}"))
            }
        })?;

        self.apply_tier_deltas(
            &mut txn,
            &req.app_name,
            &req.user_id,
            &app_delta,
            &user_delta,
            bson_now,
        )
        .await?;
        let (app_state, user_state) =
            self.read_tiers(&mut txn, &req.app_name, &req.user_id).await?;

        MongoSessionService::maybe_commit(&mut txn).await?;

        Ok(Box::new(MongoSession {
            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>> {
        req.try_identity()?;
        let sess_coll = self.db.collection::<Document>("sessions");
        let session_doc = sess_coll
            .find_one(doc! { "app_name": &req.app_name, "user_id": &req.user_id, "session_id": &req.session_id })
            .await.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
            .ok_or_else(|| crate::service::session_not_found(&req))?;

        let stored = session_doc.get_document("state").map(bson_to_state).unwrap_or_default();
        let (app_state, user_state) =
            self.read_tiers(&mut None, &req.app_name, &req.user_id).await?;
        let updated_at = session_doc
            .get_datetime("updated_at")
            .map(|dt| bson_dt_to_chrono(*dt))
            .unwrap_or_else(|_| Utc::now());

        let events_coll = self.db.collection::<Document>("events");
        let mut cursor = events_coll
            .find(doc! { "app_name": &req.app_name, "user_id": &req.user_id, "session_id": &req.session_id })
            .with_options(FindOptions::builder().sort(doc! { "timestamp": 1, "seq": 1 }).build())
            .await.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;

        let mut events: Vec<Event> = Vec::new();
        while cursor
            .advance()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
        {
            let doc = cursor
                .deserialize_current()
                .map_err(|e| adk_core::AdkError::session(format!("deserialize failed: {e}")))?;
            if let Some(event) = doc_to_event(&doc) {
                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(MongoSession {
            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, &stored),
            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>>> {
        validate_scope(&req.app_name, &req.user_id)?;
        let sess_coll = self.db.collection::<Document>("sessions");
        let opts = FindOptions::builder()
            .sort(doc! { "updated_at": -1, "session_id": -1 })
            .limit(req.limit.map(|l| l as i64))
            .skip(req.offset.map(|o| o as u64))
            .build();
        let mut cursor = sess_coll
            .find(doc! { "app_name": &req.app_name, "user_id": &req.user_id })
            .with_options(opts)
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;

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

        let mut sessions: Vec<Box<dyn Session>> = Vec::new();
        while cursor
            .advance()
            .await
            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
        {
            let doc = cursor
                .deserialize_current()
                .map_err(|e| adk_core::AdkError::session(format!("deserialize failed: {e}")))?;
            let stored = doc.get_document("state").map(bson_to_state).unwrap_or_default();
            sessions.push(Box::new(MongoSession {
                app_name: req.app_name.clone(),
                user_id: req.user_id.clone(),
                session_id: doc.get_str("session_id").unwrap_or_default().to_string(),
                state: state_utils::merge_current_tiers(&app_state, &user_state, &stored),
                events: Vec::new(),
                updated_at: doc
                    .get_datetime("updated_at")
                    .map(|dt| bson_dt_to_chrono(*dt))
                    .unwrap_or_else(|_| Utc::now()),
            }));
        }
        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<()> {
        req.try_identity()?;
        let ev_coll = self.db.collection::<Document>("events");
        let sess_coll = self.db.collection::<Document>("sessions");
        let filter = doc! { "app_name": &req.app_name, "user_id": &req.user_id, "session_id": &req.session_id };

        let mut txn = self.maybe_start_transaction().await?;
        with_optional_session!(ev_coll.delete_many(filter.clone()), txn.as_mut())
            .map_err(|e| adk_core::AdkError::session(format!("delete failed: {e}")))?;
        with_optional_session!(sess_coll.delete_one(filter), txn.as_mut())
            .map_err(|e| adk_core::AdkError::session(format!("delete failed: {e}")))?;
        MongoSessionService::maybe_commit(&mut txn).await?;
        Ok(())
    }

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

        let sess_coll = self.db.collection::<Document>("sessions");

        let mut txn = self.maybe_start_transaction().await?;

        let session_doc = with_optional_session!(
            sess_coll.find_one(doc! { "session_id": session_id }),
            txn.as_mut()
        )
        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
        .ok_or_else(|| session_id_not_found(session_id))?;

        let app_name = session_doc.get_str("app_name").unwrap_or_default().to_string();
        let user_id = session_doc.get_str("user_id").unwrap_or_default().to_string();

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

        MongoSessionService::maybe_commit(&mut txn).await?;
        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.maybe_start_transaction().await?;
        self.apply_event(
            &mut txn,
            req.identity.app_name.as_ref(),
            req.identity.user_id.as_ref(),
            req.identity.session_id.as_ref(),
            &event,
        )
        .await?;
        MongoSessionService::maybe_commit(&mut txn).await?;
        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<()> {
        validate_scope(app_name, user_id)?;
        let filter = doc! { "app_name": app_name, "user_id": user_id };
        let ev_coll = self.db.collection::<Document>("events");
        let sess_coll = self.db.collection::<Document>("sessions");
        let user_coll = self.db.collection::<Document>("user_states");

        let mut txn = self.maybe_start_transaction().await?;
        with_optional_session!(ev_coll.delete_many(filter.clone()), txn.as_mut())
            .map_err(|e| adk_core::AdkError::session(format!("delete_all_sessions failed: {e}")))?;
        with_optional_session!(sess_coll.delete_many(filter.clone()), txn.as_mut())
            .map_err(|e| adk_core::AdkError::session(format!("delete_all_sessions failed: {e}")))?;
        with_optional_session!(user_coll.delete_many(filter), txn.as_mut())
            .map_err(|e| adk_core::AdkError::session(format!("delete_all_sessions failed: {e}")))?;
        MongoSessionService::maybe_commit(&mut txn).await?;
        Ok(())
    }

    #[instrument(skip_all)]
    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
        Ok(self.load_history(&mut None, identity).await?.0)
    }

    async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
        let identity = &req.identity;
        for _ in 0..MAX_REWRITE_ATTEMPTS {
            let Some((rewritten, updated_at)) = self.try_rewrite(&req).await? else {
                continue;
            };
            let (app_state, user_state) = self
                .read_tiers(&mut None, identity.app_name.as_ref(), identity.user_id.as_ref())
                .await?;
            let session = Box::new(MongoSession {
                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,
            });
            return Ok(HistoryOutcome::new(session, rewritten.change));
        }
        Err(adk_core::AdkError::new(
            ErrorComponent::Session,
            ErrorCategory::Unavailable,
            "session.mongodb.history_contention",
            format!(
                "session '{}' changed on each of {MAX_REWRITE_ATTEMPTS} rewrite attempts; retry \
                 the rewrite",
                identity.session_id
            ),
        ))
    }

    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 event_count = i64::try_from(req.events.len()).unwrap_or(i64::MAX);

        let mut txn = self.maybe_start_transaction().await?;
        // The session document goes first, so its unique index refuses an existing session
        // before any event is written.
        let session_doc = doc! {
            "app_name": app_name, "user_id": user_id, "session_id": session_id,
            "state": state_to_bson(&state)?,
            "initial_state": state_to_bson(&initial_state)?,
            "created_at": chrono_to_bson_dt(Utc::now()),
            "updated_at": chrono_to_bson_dt(updated_at),
            "event_seq": event_count,
        };
        with_optional_session!(
            self.db.collection::<Document>("sessions").insert_one(session_doc),
            txn.as_mut()
        )
        .map_err(|e| {
            if is_duplicate_key(&e) {
                session_already_exists(app_name, user_id, session_id)
            } else {
                adk_core::AdkError::session(format!("insert failed: {e}"))
            }
        })?;
        if !req.events.is_empty() {
            let docs = req
                .events
                .iter()
                .zip(1_i64..)
                .map(|(event, seq)| event_doc(app_name, user_id, session_id, event, seq))
                .collect::<Result<Vec<_>>>()?;
            let inserted = with_optional_session!(
                self.db.collection::<Document>("events").insert_many(docs),
                txn.as_mut()
            );
            if let Err(error) = inserted {
                if txn.is_none() {
                    // Without a transaction, take back the session document so no partial
                    // import remains.
                    let _ = self
                        .db
                        .collection::<Document>("sessions")
                        .delete_one(doc! {
                            "app_name": app_name, "user_id": user_id, "session_id": session_id,
                        })
                        .await;
                }
                return Err(adk_core::AdkError::session(format!("insert events failed: {error}")));
            }
        }
        let (app_state, user_state) = self.read_tiers(&mut txn, app_name, user_id).await?;
        MongoSessionService::maybe_commit(&mut txn).await?;

        Ok(Box::new(MongoSession {
            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<()> {
        self.db
            .run_command(doc! { "ping": 1 })
            .await
            .map_err(|e| adk_core::AdkError::session(format!("health check failed: {e}")))?;
        Ok(())
    }
}

// ── Event deserialization ──

/// The stored document of `event`, at append position `seq`.
fn event_doc(
    app_name: &str,
    user_id: &str,
    session_id: &str,
    event: &Event,
    seq: i64,
) -> Result<Document> {
    let llm_bson = bson::to_bson(&event.llm_response)
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
    let act_bson = bson::to_bson(&event.actions)
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
    let tid_bson = bson::to_bson(&event.long_running_tool_ids)
        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
    Ok(doc! {
        "id": &event.id, "session_id": session_id, "app_name": app_name, "user_id": user_id,
        "invocation_id": &event.invocation_id, "branch": &event.branch, "author": &event.author,
        "timestamp": chrono_to_bson_dt(event.timestamp), "seq": seq, "llm_response": llm_bson,
        "actions": act_bson, "long_running_tool_ids": tid_bson,
    })
}

fn doc_to_event(doc: &Document) -> Option<Event> {
    let llm_response_bson = doc.get("llm_response")?;
    let actions_bson = doc.get("actions")?;
    let tool_ids_bson = doc.get("long_running_tool_ids")?;

    let llm_response = bson::from_bson(llm_response_bson.clone()).ok()?;
    let actions = bson::from_bson(actions_bson.clone()).ok()?;
    let long_running_tool_ids = bson::from_bson(tool_ids_bson.clone()).ok()?;

    let timestamp = doc
        .get_datetime("timestamp")
        .map(|dt| bson_dt_to_chrono(*dt))
        .unwrap_or_else(|_| Utc::now());

    Some(Event {
        id: doc.get_str("id").unwrap_or_default().to_string(),
        timestamp,
        invocation_id: doc.get_str("invocation_id").unwrap_or_default().to_string(),
        branch: doc.get_str("branch").unwrap_or_default().to_string(),
        author: doc.get_str("author").unwrap_or_default().to_string(),
        llm_request: None,
        llm_response,
        actions,
        long_running_tool_ids,
        provider_metadata: std::collections::HashMap::new(),
    })
}

// ── MongoSession type ──

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

impl Session for MongoSession {
    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 MongoSession {
    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 MongoSession {
    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::*;

    #[test]
    fn replica_set_members_support_transactions() {
        let primary = doc! { "isWritablePrimary": true, "setName": "rs0", "hosts": ["a:27017"] };
        assert!(hello_supports_transactions(&primary));
        let secondary = doc! { "isWritablePrimary": false, "secondary": true, "setName": "rs0" };
        assert!(hello_supports_transactions(&secondary));
    }

    #[test]
    fn mongos_routers_support_transactions() {
        let mongos = doc! { "isWritablePrimary": true, "msg": "isdbgrid", "maxWireVersion": 21 };
        assert!(hello_supports_transactions(&mongos));
    }

    #[test]
    fn standalone_servers_do_not_support_transactions() {
        let standalone = doc! { "isWritablePrimary": true, "maxWireVersion": 21 };
        assert!(!hello_supports_transactions(&standalone));
        assert!(!hello_supports_transactions(&doc! { "msg": "not a router" }));
    }
}