gadk-session 0.5.30

Sessions, events and the in-memory session service for gadk
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
// Copyright 2026 Chris Olson
// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

//! Port of ADK-Go `session/inmemory_test.go` (all tests but `Test_inMemoryService`, which
//! lives in `testsuite_inmemory.rs`).

use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
use std::time::Duration;

use chrono::{DateTime, TimeZone, Utc};
use gadk_genai::{Content, Part};
use gadk_platform::Platform;
use gadk_session::{
    CreateRequest, Event, EventActions, EventCompaction, GetRequest, InMemorySessionService,
    ListRequest, NodeInfo, RequestInput, Session, SessionService, ToolConfirmation,
};
use serde_json::{Map, Value, json};

fn delta(pairs: &[(&str, Value)]) -> Option<Map<String, Value>> {
    Some(
        pairs
            .iter()
            .map(|(k, v)| ((*k).to_string(), v.clone()))
            .collect(),
    )
}

async fn create(svc: &InMemorySessionService, app: &str, user: &str) -> Arc<dyn Session> {
    svc.create(CreateRequest {
        app_name: app.into(),
        user_id: user.into(),
        ..Default::default()
    })
    .await
    .unwrap()
}

async fn get(svc: &InMemorySessionService, s: &dyn Session) -> Arc<dyn Session> {
    svc.get(GetRequest {
        app_name: s.app_name().into(),
        user_id: s.user_id().into(),
        session_id: s.id().into(),
        ..Default::default()
    })
    .await
    .unwrap()
}

#[tokio::test]
async fn test_in_memory_service_create_uses_providers() {
    let fixed_time = Utc.with_ymd_and_hms(2024, 1, 2, 3, 4, 5).unwrap();
    let platform = Platform::default()
        .with_time(move || fixed_time)
        .with_uuid(|| "fixed-session-id".to_string());
    let s = InMemorySessionService::with_platform(platform);
    let sess = s
        .create(CreateRequest {
            app_name: "app".into(),
            user_id: "user".into(),
            ..Default::default()
        })
        .await
        .unwrap();
    assert_eq!(
        sess.id(),
        "fixed-session-id",
        "autogenerated session ID should be the provider value"
    );
    assert_eq!(
        sess.last_update_time(),
        fixed_time,
        "LastUpdateTime() should be the provider value"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_in_memory_service_create_concurrent_access() {
    const GOROUTINES: usize = 16;
    const ATTEMPTS: usize = 32;
    let s = Arc::new(InMemorySessionService::new());
    let start = Arc::new(tokio::sync::Barrier::new(GOROUTINES));
    let success = Arc::new(AtomicI32::new(0));
    let errors = Arc::new(AtomicI32::new(0));

    let mut handles = Vec::new();
    for _ in 0..GOROUTINES {
        let (s, start, success, errors) =
            (s.clone(), start.clone(), success.clone(), errors.clone());
        handles.push(tokio::spawn(async move {
            start.wait().await;
            for _ in 0..ATTEMPTS {
                let res = s
                    .create(CreateRequest {
                        app_name: "race-app".into(),
                        user_id: "race-user".into(),
                        session_id: Some("race-session".into()),
                        ..Default::default()
                    })
                    .await;
                match res {
                    Ok(_) => {
                        success.fetch_add(1, Ordering::SeqCst);
                    }
                    Err(e) if e.to_string().contains("already exists") => {
                        errors.fetch_add(1, Ordering::SeqCst);
                    }
                    Err(_) => {}
                }
            }
        }));
    }
    for h in handles {
        h.await.unwrap();
    }

    assert_eq!(
        success.load(Ordering::SeqCst),
        1,
        "expected 1 successful creation"
    );
    let expected_errors = i32::try_from(GOROUTINES * ATTEMPTS - 1).unwrap();
    assert_eq!(
        errors.load(Ordering::SeqCst),
        expected_errors,
        "expected {expected_errors} 'already exists' errors"
    );
}

#[tokio::test]
async fn test_in_memory_session_append_event_workflow_fields_round_trip() {
    let service = InMemorySessionService::new();
    let sess = create(&service, "app", "user").await;

    const WANT_SCOPE: &str = "adk-task-isolation-scope";
    let mut event = Event {
        id: "wf_event".into(),
        author: "agent".into(),
        isolation_scope: WANT_SCOPE.into(),
        node_info: Some(NodeInfo {
            path: "ask_name".into(),
            ..Default::default()
        }),
        requested_input: Some(RequestInput {
            interrupt_id: "ask_name".into(),
            message: "What's your name?".into(),
            ..Default::default()
        }),
        routes: vec!["route_a".into()],
        ..Default::default()
    };
    service
        .append_event(sess.as_ref(), &mut event)
        .await
        .unwrap();

    let got = get(&service, sess.as_ref()).await;
    let evs = got.events();
    assert_eq!(evs.len(), 1, "got {} events, want 1", evs.len());
    let ev = &evs[0];
    assert!(
        ev.node_info.as_ref().is_some_and(|n| n.path == "ask_name"),
        "NodeInfo not persisted: {:?}",
        ev.node_info
    );
    assert!(
        ev.requested_input
            .as_ref()
            .is_some_and(|r| r.interrupt_id == "ask_name"),
        "RequestedInput not persisted: {:?}",
        ev.requested_input
    );
    assert_eq!(
        ev.routes,
        vec!["route_a".to_string()],
        "Routes not persisted"
    );
    assert_eq!(ev.isolation_scope, WANT_SCOPE, "IsolationScope");
}

// Regression guard for ADK-Go #530: `State::all` must snapshot under the lock. In Rust
// `all()` returns an owned `Vec`, so the Go map-iteration race cannot occur; the test still
// checks the observable invariants (seed key always present, count never goes backwards).
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_in_memory_state_all_concurrent_set() {
    const WRITERS: usize = 8;
    const ITERATIONS: usize = 200;
    let svc = Arc::new(InMemorySessionService::new());
    let sess = svc
        .create(CreateRequest {
            app_name: "app".into(),
            user_id: "user".into(),
            state: delta(&[("k0", json!(0))]),
            ..Default::default()
        })
        .await
        .unwrap();

    let start = Arc::new(tokio::sync::Barrier::new(WRITERS + 1));
    let mut handles = Vec::new();
    for w in 0..WRITERS {
        let (svc, sess, start) = (svc.clone(), sess.clone(), start.clone());
        handles.push(tokio::spawn(async move {
            start.wait().await;
            for i in 0..ITERATIONS {
                let mut ev = Event {
                    timestamp: Utc::now(),
                    actions: EventActions {
                        state_delta: delta(&[(&format!("w{w}_k{i}"), json!(i))]),
                        ..Default::default()
                    },
                    ..Default::default()
                };
                svc.append_event(sess.as_ref(), &mut ev)
                    .await
                    .unwrap_or_else(|e| panic!("AppendEvent(w{w}, i{i}) failed: {e}"));
            }
        }));
    }

    {
        let (sess, start) = (sess.clone(), start.clone());
        handles.push(tokio::spawn(async move {
            start.wait().await;
            let mut prev_count = 0;
            for _ in 0..ITERATIONS {
                let mut count = 0;
                let mut saw_seed = false;
                for (k, _) in sess.state().all() {
                    count += 1;
                    if k == "k0" {
                        saw_seed = true;
                    }
                }
                assert!(saw_seed, "All() did not yield seed key \"k0\"");
                assert!(
                    count >= prev_count,
                    "All() yielded {count} keys, want at least {prev_count} (the previous snapshot's count)"
                );
                prev_count = count;
                tokio::task::yield_now().await;
            }
        }));
    }
    for h in handles {
        h.await.unwrap();
    }
}

#[tokio::test]
async fn test_in_memory_state_all_is_snapshot() {
    let svc = InMemorySessionService::new();
    let sess = svc
        .create(CreateRequest {
            app_name: "app".into(),
            user_id: "user".into(),
            state: Some(Map::new()),
            ..Default::default()
        })
        .await
        .unwrap();
    let st = sess.state();
    for i in 0..64 {
        st.set(&format!("seed_{i:03}"), json!(i)).unwrap();
    }

    let mut got = Vec::new();
    let mut leaked = Vec::new();
    let mut first = true;
    for (k, _) in st.all() {
        if k.starts_with("injected_") {
            leaked.push(k.clone());
        }
        got.push(k);
        if first {
            // mutate hard, once, while iteration is live
            first = false;
            for i in 0..2048 {
                let _ = st.set(&format!("injected_{i:05}"), json!(i));
            }
        }
    }

    assert!(
        leaked.is_empty(),
        "All() yielded {} keys written after iteration began, e.g. {:?}",
        leaked.len(),
        leaked.first()
    );
    assert_eq!(
        got.len(),
        64,
        "All() yielded {} keys, want the 64 present when iteration began",
        got.len()
    );
}

#[tokio::test]
async fn test_in_memory_session_append_event_deadlock() {
    let service = InMemorySessionService::new();
    let sess = create(&service, "testapp", "testuser").await;

    // Event with StateDelta to trigger updateSessionState.
    let mut event = Event {
        id: "event1".into(),
        timestamp: Utc::now(),
        actions: EventActions {
            state_delta: delta(&[("test_key", json!("test_value"))]),
            ..Default::default()
        },
        ..Default::default()
    };

    // This call would hang if a deadlock were present.
    let res = tokio::time::timeout(
        Duration::from_secs(5),
        service.append_event(sess.as_ref(), &mut event),
    )
    .await
    .expect("AppendEvent deadlocked");
    res.unwrap_or_else(|e| panic!("AppendEvent failed: {e}"));
}

#[tokio::test]
async fn test_in_memory_service_append_event_preserves_input_event_temp_state() {
    let service = InMemorySessionService::new();
    let sess = create(&service, "testapp", "testuser").await;

    let mut event = Event {
        id: "event1".into(),
        timestamp: Utc::now(),
        actions: EventActions {
            state_delta: delta(&[("temp:k1", json!("v1")), ("sk", json!("v2"))]),
            ..Default::default()
        },
        ..Default::default()
    };
    service
        .append_event(sess.as_ref(), &mut event)
        .await
        .unwrap();

    // The input event's StateDelta was not mutated in place.
    let input = event.actions.state_delta.as_ref().unwrap();
    assert!(
        input.contains_key("temp:k1"),
        "expected temp:k1 to be preserved on input event after AppendEvent, but it was removed: {input:?}"
    );
    assert_eq!(
        input.get("sk"),
        Some(&json!("v2")),
        "expected non-temp key sk to remain in input event, got: {input:?}"
    );

    // The stored event in the session has temp keys stripped.
    let stored = sess
        .events()
        .last()
        .cloned()
        .expect("expected stored event in session, got none");
    let sd = stored.actions.state_delta.unwrap_or_default();
    assert!(
        !sd.contains_key("temp:k1"),
        "expected temp:k1 to be stripped from stored event, but it still exists: {sd:?}"
    );
    assert_eq!(
        sd.get("sk"),
        Some(&json!("v2")),
        "expected non-temp key sk on stored event, got: {sd:?}"
    );
}

#[tokio::test]
async fn test_in_memory_service_append_event_strips_temp_keys_from_canonical_record() {
    let service = InMemorySessionService::new();
    let sess = create(&service, "testapp", "testuser").await;

    let mut event = Event {
        id: "event1".into(),
        timestamp: Utc::now(),
        actions: EventActions {
            state_delta: delta(&[("temp:k1", json!("v1")), ("sk", json!("v2"))]),
            ..Default::default()
        },
        ..Default::default()
    };
    service
        .append_event(sess.as_ref(), &mut event)
        .await
        .unwrap();

    let got = get(&service, sess.as_ref()).await;
    let stored = got
        .events()
        .last()
        .cloned()
        .expect("expected stored event in session, got none");
    let sd = stored.actions.state_delta.unwrap_or_default();
    assert!(
        !sd.contains_key("temp:k1"),
        "temp:k1 leaked into the canonical record returned by Get(): {sd:?}"
    );
    assert_eq!(
        sd.get("sk"),
        Some(&json!("v2")),
        "expected non-temp key sk on stored event, got: {sd:?}"
    );
}

#[tokio::test]
async fn test_in_memory_service_append_event_multiple_events_all_stripped() {
    let service = InMemorySessionService::new();
    let sess = create(&service, "testapp", "testuser").await;

    for (i, temp_val) in ["first", "second", "third"].iter().enumerate() {
        let mut event = Event {
            id: format!("event{i}"),
            timestamp: Utc::now(),
            actions: EventActions {
                state_delta: delta(&[("temp:turn", json!(temp_val)), ("turn", json!(i))]),
                ..Default::default()
            },
            ..Default::default()
        };
        service
            .append_event(sess.as_ref(), &mut event)
            .await
            .unwrap_or_else(|e| panic!("AppendEvent({i}) failed: {e}"));
    }

    let got = get(&service, sess.as_ref()).await;
    let events = got.events();
    for (i, ev) in events.iter().enumerate() {
        let sd = ev.actions.state_delta.clone().unwrap_or_default();
        assert!(
            !sd.contains_key("temp:turn"),
            "event {i}: temp:turn leaked into the canonical record: {sd:?}"
        );
        assert_eq!(
            sd.get("turn"),
            Some(&json!(i)),
            "event {i}: expected non-temp key turn={i}, got: {sd:?}"
        );
    }
    assert_eq!(events.len(), 3, "expected 3 stored events");
}

#[tokio::test]
async fn test_in_memory_service_append_event_copies_compaction() {
    let service = InMemorySessionService::new();
    let sess = create(&service, "app", "user").await;

    let start = Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap();
    let end = start + chrono::Duration::minutes(1);
    let mut event = Event {
        id: "c1".into(),
        author: "user".into(),
        ..Default::default()
    };
    event.actions.compaction = Some(EventCompaction {
        start_timestamp: start,
        end_timestamp: end,
        compacted_content: Some(Content {
            role: "model".into(),
            parts: vec![Part::from_text("summary")],
        }),
        excluded_events: Vec::new(),
    });
    service
        .append_event(sess.as_ref(), &mut event)
        .await
        .unwrap();

    // Rewrite the record through the event we still hold. A stored event must not follow.
    let mine = event.actions.compaction.as_mut().unwrap();
    mine.end_timestamp = end + chrono::Duration::hours(100);
    mine.compacted_content.as_mut().unwrap().parts[0].text = "rewritten after the append".into();

    let got = get(&service, sess.as_ref()).await;
    let stored = got.events()[0]
        .actions
        .compaction
        .clone()
        .expect("compaction was not persisted");
    assert_eq!(
        stored.end_timestamp, end,
        "stored EndTimestamp: the caller moved the covered range after the append"
    );
    assert_eq!(
        stored.compacted_content.unwrap().parts[0].text,
        "summary",
        "stored summary: the caller rewrote the stored content"
    );
}

// TestInMemoryService_AppendEvent_CopiesRequestedAuthConfigs pins that a write to the map the
// caller passed in does not reach the stored event.
#[tokio::test]
async fn test_in_memory_service_append_event_copies_requested_auth_configs() {
    let service = InMemorySessionService::new();
    let sess = create(&service, "app", "user").await;
    let api_key = gadk_session::toolauth::Scheme {
        r#type: gadk_session::toolauth::SchemeType::API_KEY,
        r#in: "header".into(),
        name: "X-Key".into(),
        ..Default::default()
    };
    let config = |key: &str| gadk_session::toolauth::Config {
        auth_scheme: api_key.clone(),
        credential_key: key.into(),
        ..Default::default()
    };
    let mut event = Event {
        id: "e1".into(),
        author: "agent".into(),
        ..Default::default()
    };
    event.actions.requested_auth_configs = BTreeMap::from([("call-1".into(), config("k1"))]);
    service
        .append_event(sess.as_ref(), &mut event)
        .await
        .unwrap();

    event
        .actions
        .requested_auth_configs
        .insert("call-2".into(), config("k2"));

    let got = get(&service, sess.as_ref()).await;
    let stored = &got.events()[0].actions.requested_auth_configs;
    assert!(
        !stored.contains_key("call-2") && stored.len() == 1,
        "stored RequestedAuthConfigs has {} entries, want only call-1: the caller's write reached the stored event",
        stored.len()
    );
}

type ActionWrite = fn(&mut Event);

// In Go this guards a fatal concurrent map read/write: `Session.Events` hands out the live
// event pointers. In Rust `Session::events` returns owned copies, so a reader writing into
// what it got cannot reach the session at all; the race is impossible by construction. The
// case is kept with the same shape (a reader mutating the newest event while appends run),
// plus a check the Go race detector stood in for: the writes never reach the canonical
// record.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_in_memory_service_append_event_concurrent_action_map_writes() {
    let action_maps: [(&str, ActionWrite); 3] = [
        ("ArtifactDelta", |e| {
            e.actions
                .artifact_delta
                .get_or_insert_default()
                .insert("injected".into(), 1);
        }),
        ("RequestedToolConfirmations", |e| {
            e.actions.requested_tool_confirmations.insert(
                "injected".into(),
                ToolConfirmation {
                    confirmed: true,
                    ..Default::default()
                },
            );
        }),
        ("StateDelta", |e| {
            if let Some(d) = e.actions.state_delta.as_mut() {
                d.insert("injected".into(), json!(1));
            }
        }),
    ];
    const N: usize = 20000;
    for (name, write) in action_maps {
        for delta_shape in ["with_temp", "without_temp", "nil"] {
            // A nil StateDelta cannot be written through the live event.
            if name == "StateDelta" && delta_shape == "nil" {
                continue;
            }
            let case = format!("{name}/{delta_shape}");
            let svc = Arc::new(InMemorySessionService::new());
            let live = create(&svc, "app", "u").await;
            let stop = Arc::new(AtomicBool::new(false));
            let first_write = Arc::new(tokio::sync::Notify::new());
            let reader = {
                let (live, stop, first_write) = (live.clone(), stop.clone(), first_write.clone());
                tokio::spawn(async move {
                    let mut wrote = false;
                    while !stop.load(Ordering::SeqCst) {
                        let mut evs = live.events();
                        if let Some(last) = evs.last_mut() {
                            write(last);
                            if !wrote {
                                first_write.notify_one();
                                wrote = true;
                            }
                        }
                        tokio::task::yield_now().await;
                    }
                })
            };
            for i in 0..N {
                let state_delta = match delta_shape {
                    "with_temp" => delta(&[("temp:t", json!(i)), ("k", json!(i))]),
                    "without_temp" => delta(&[("k", json!(i))]),
                    _ => None,
                };
                let mut ev = Event {
                    id: format!("e{i}"),
                    timestamp: Utc::now(),
                    actions: EventActions {
                        state_delta,
                        artifact_delta: Some(BTreeMap::from([(
                            "a".to_string(),
                            i64::try_from(i).unwrap(),
                        )])),
                        requested_tool_confirmations: BTreeMap::from([(
                            "call".to_string(),
                            ToolConfirmation::default(),
                        )]),
                        ..Default::default()
                    },
                    ..Default::default()
                };
                svc.append_event(live.as_ref(), &mut ev)
                    .await
                    .unwrap_or_else(|e| panic!("{case}: AppendEvent: {e}"));
                if i == 0 {
                    // Ensure the history writer runs before the remaining appends.
                    first_write.notified().await;
                }
            }
            stop.store(true, Ordering::SeqCst);
            reader.await.unwrap();

            let got = get(&svc, live.as_ref()).await;
            for (i, ev) in got.events().iter().enumerate() {
                let a = &ev.actions;
                assert!(
                    !a.artifact_delta
                        .as_ref()
                        .is_some_and(|m| m.contains_key("injected"))
                        && !a.requested_tool_confirmations.contains_key("injected")
                        && !a
                            .state_delta
                            .as_ref()
                            .is_some_and(|m| m.contains_key("injected")),
                    "{case}: event {i}: a reader's write reached the canonical record: {a:?}"
                );
            }
        }
    }
}

#[tokio::test]
async fn test_in_memory_service_append_event_all_temp_keys_stripped_keeps_empty_delta() {
    let service = InMemorySessionService::new();
    let sess = create(&service, "testapp", "testuser").await;

    let mut event = Event {
        id: "event1".into(),
        timestamp: Utc::now(),
        actions: EventActions {
            state_delta: delta(&[("temp:a", json!(1))]),
            ..Default::default()
        },
        ..Default::default()
    };
    service
        .append_event(sess.as_ref(), &mut event)
        .await
        .unwrap();

    let got = get(&service, sess.as_ref()).await;
    let stored = got
        .events()
        .first()
        .cloned()
        .expect("expected stored event in session, got none");
    let sd = stored
        .actions
        .state_delta
        .expect("stored StateDelta is None; stripping every key must leave an empty map, not None");
    assert!(sd.is_empty(), "stored StateDelta = {sd:?}, want empty");
}

#[tokio::test]
async fn test_in_memory_service_append_event_canonical_record_does_not_alias_live_delta() {
    // Both delta shapes matter in Go (trimTempDeltaState returns the event unchanged when it
    // strips nothing). In Rust `events()` returns owned copies, so the writes below go into
    // copies; the case still pins that neither reaches the canonical record.
    for (name, d) in [
        (
            "temp key stripped",
            delta(&[("temp:scratch", json!("x")), ("keep", json!("y"))]),
        ),
        ("nothing stripped", delta(&[("keep", json!("y"))])),
    ] {
        let service = InMemorySessionService::new();
        let live = create(&service, "app", "user").await;

        let mut event = Event {
            id: "e1".into(),
            timestamp: Utc::now(),
            actions: EventActions {
                state_delta: d,
                ..Default::default()
            },
            ..Default::default()
        };
        service
            .append_event(live.as_ref(), &mut event)
            .await
            .unwrap();

        // Write through the handle the caller still holds.
        let mut stored = live
            .events()
            .first()
            .cloned()
            .unwrap_or_else(|| panic!("{name}: expected an event on the live session handle"));
        stored
            .actions
            .state_delta
            .get_or_insert_default()
            .insert("injected".into(), json!(true));
        // And through the caller's own event.
        event
            .actions
            .state_delta
            .get_or_insert_default()
            .insert("also-injected".into(), json!(true));

        let got = get(&service, live.as_ref()).await;
        let canonical = got.events()[0]
            .actions
            .state_delta
            .clone()
            .unwrap_or_default();
        assert!(
            !canonical.contains_key("injected"),
            "{name}: canonical StateDelta = {canonical:?}: it shares the map the live handle publishes"
        );
        assert!(
            !canonical.contains_key("also-injected"),
            "{name}: canonical StateDelta = {canonical:?}: it shares the caller's map"
        );
        assert_eq!(
            canonical.get("keep"),
            Some(&json!("y")),
            "{name}: canonical StateDelta = {canonical:?}, want the non-temp key preserved"
        );
    }
}

// Not a Go test: pins Go `Create`, which stores `MergeStates(app, user, req.State)` with the
// raw request state, so `temp:` keys given at create stay in session state (only appended
// event deltas are trimmed).
#[tokio::test]
async fn create_keeps_temp_keys_like_go() {
    let svc = InMemorySessionService::new();
    let created = svc
        .create(CreateRequest {
            app_name: "app".into(),
            user_id: "user".into(),
            state: delta(&[
                ("temp:x", json!("t")),
                ("sk", json!("s")),
                ("app:a", json!("av")),
                ("user:u", json!("uv")),
            ]),
            ..Default::default()
        })
        .await
        .unwrap();
    let fetched = get(&svc, created.as_ref()).await;
    for (what, sess) in [("Create", &created), ("Get", &fetched)] {
        let st = sess.state();
        assert_eq!(st.get("temp:x").ok(), Some(json!("t")), "{what}: temp:x");
        assert_eq!(st.get("sk").ok(), Some(json!("s")), "{what}: sk");
        assert_eq!(st.get("app:a").ok(), Some(json!("av")), "{what}: app:a");
        assert_eq!(st.get("user:u").ok(), Some(json!("uv")), "{what}: user:u");
    }
    // App and user keys still route to the shared maps; temp: stays per-session.
    let other = create(&svc, "app", "user").await;
    assert_eq!(other.state().get("app:a").ok(), Some(json!("av")));
    assert_eq!(other.state().get("user:u").ok(), Some(json!("uv")));
    assert!(
        other.state().get("temp:x").is_err(),
        "temp:x is per-session"
    );
}

// Not a Go test: pins Go's Get filter order (NumRecentEvents first, then After). With 5
// events the last 2 are ts[3] and ts[4]; of those only ts[4] is not before `after = ts[4]`.
#[tokio::test]
async fn get_applies_num_recent_events_before_after_like_go() {
    let svc = InMemorySessionService::new();
    let sess = create(&svc, "app", "user").await;
    let base = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
    let ts: Vec<_> = (1..=5)
        .map(|i| base + chrono::Duration::seconds(i))
        .collect();
    for (i, t) in ts.iter().enumerate() {
        let mut ev = Event {
            id: i.to_string(),
            timestamp: *t,
            ..Default::default()
        };
        svc.append_event(sess.as_ref(), &mut ev).await.unwrap();
    }
    let got = svc
        .get(GetRequest {
            app_name: "app".into(),
            user_id: "user".into(),
            session_id: sess.id().into(),
            num_recent_events: 2,
            after: Some(ts[4]),
        })
        .await
        .unwrap();
    let ids: Vec<String> = got.events().into_iter().map(|e| e.id).collect();
    assert_eq!(ids, vec!["4".to_string()]);
}

/// A service whose clock the test moves: Go passes a time provider per call through ctx; gadk
/// sets one on the service's Platform and moves the shared instant between calls.
fn clocked() -> (
    InMemorySessionService,
    Arc<parking_lot::Mutex<DateTime<Utc>>>,
) {
    let now = Arc::new(parking_lot::Mutex::new(Utc.timestamp_opt(0, 0).unwrap()));
    let clock = now.clone();
    let svc =
        InMemorySessionService::with_platform(Platform::default().with_time(move || *clock.lock()));
    (svc, now)
}

async fn create_with_id(svc: &InMemorySessionService, user: &str, id: &str) -> Arc<dyn Session> {
    svc.create(CreateRequest {
        app_name: "app".into(),
        user_id: user.into(),
        session_id: Some(id.into()),
        ..Default::default()
    })
    .await
    .unwrap()
}

// parity: adapted: Go injects the create time per call via ctx; gadk uses one service Platform whose clock the test moves
#[tokio::test]
async fn test_in_memory_service_list_ordered_by_last_update_time() {
    let (svc, clock) = clocked();
    let base = Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap();
    let mut created = BTreeMap::new();
    for (i, id) in ["a", "b", "c"].into_iter().enumerate() {
        *clock.lock() = base + chrono::Duration::seconds(i as i64);
        created.insert(id, create_with_id(&svc, "u", id).await);
    }
    // Make the oldest session the most recently active one.
    let mut ev = Event::new(&Platform::default(), "inv");
    ev.timestamp = base + chrono::Duration::minutes(1);
    svc.append_event(created["a"].as_ref(), &mut ev)
        .await
        .unwrap();

    let got: Vec<String> = svc
        .list(ListRequest {
            app_name: "app".into(),
            user_id: "u".into(),
        })
        .await
        .unwrap()
        .iter()
        .map(|s| s.id().to_string())
        .collect();
    assert_eq!(
        got,
        ["b", "c", "a"],
        "List() session order (oldest update first)"
    );
}

// TestInMemoryService_Get_AfterWithOutOfOrderTimestamps checks the After filter when events were
// not appended in timestamp order. An event carries the time it was created, or one its producer
// set, not the time it was appended.
#[tokio::test]
async fn test_in_memory_service_get_after_with_out_of_order_timestamps() {
    let svc = InMemorySessionService::new();
    let created = create_with_id(&svc, "user", "s").await;
    let base = Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap();
    // Minutes after base, in append order.
    for minute in [10, 40, 20, 30, 50, 60, 70] {
        let mut event = Event {
            id: format!("e{minute}"),
            author: "agent".into(),
            timestamp: base + chrono::Duration::minutes(minute),
            ..Default::default()
        };
        svc.append_event(created.as_ref(), &mut event)
            .await
            .unwrap();
    }

    let cases: [(&str, usize, &[&str]); 3] = [
        ("after only", 0, &["e40", "e30", "e50", "e60", "e70"]),
        (
            "with num recent events",
            6,
            &["e40", "e30", "e50", "e60", "e70"],
        ),
        // The trim runs before the filter, in append order, so e40 falls out of a five-event
        // window even though it is at or after After.
        (
            "num recent events trims first",
            5,
            &["e30", "e50", "e60", "e70"],
        ),
    ];
    for (name, num_recent_events, want) in cases {
        let got = svc
            .get(GetRequest {
                app_name: "app".into(),
                user_id: "user".into(),
                session_id: "s".into(),
                num_recent_events,
                after: Some(base + chrono::Duration::minutes(25)),
            })
            .await
            .unwrap();
        let ids: Vec<String> = got.events().into_iter().map(|e| e.id).collect();
        assert_eq!(ids, want, "{name}: Get() event IDs");
    }
}

// Port of ADK-Go `session/inmemory_internal_test.go` TestCompareByLastUpdate. Go tests the
// comparator directly because List scans a map ordered by (app, user, session), so ties already
// arrive in tie-break order there; that holds for gadk's BTreeMap too.
// parity: adapted: gadk has no compareByLastUpdate; the order is checked through List across users, with the create times set on the service's moved clock
#[tokio::test]
async fn test_compare_by_last_update() {
    let (svc, clock) = clocked();
    let base = Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap();
    // At time 0, u2/a ties with u1/a and u1/b. Its session ID sorts before u1/b's but its user
    // ID after, so only user ID then session ID gives the want.
    for (user, id, d) in [
        ("u2", "x", chrono::Duration::minutes(1)),
        ("u2", "a", chrono::Duration::zero()),
        ("u1", "b", chrono::Duration::zero()),
        ("u1", "c", chrono::Duration::hours(1)),
        ("u1", "a", chrono::Duration::zero()),
    ] {
        *clock.lock() = base + d;
        create_with_id(&svc, user, id).await;
    }
    let got: Vec<String> = svc
        .list(ListRequest {
            app_name: "app".into(),
            user_id: String::new(),
        })
        .await
        .unwrap()
        .iter()
        .map(|s| format!("{}/{}", s.user_id(), s.id()))
        .collect();
    assert_eq!(
        got,
        ["u1/a", "u1/b", "u2/a", "u2/x", "u1/c"],
        "List() ordered by last update, user ID, session ID"
    );
}