duroxide-cdb 0.1.10

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

use duroxide::runtime::registry::ActivityRegistry;
use duroxide::runtime::{self, RuntimeOptions};
use duroxide::{ActivityContext, Client, OrchestrationContext, OrchestrationRegistry};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

mod common;

static INIT_LOGGING: std::sync::Once = std::sync::Once::new();

fn init_test_logging() {
    INIT_LOGGING.call_once(|| {
        use tracing_subscriber::EnvFilter;
        let env_filter =
            EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("debug"));
        let _ = tracing_subscriber::fmt()
            .with_env_filter(env_filter)
            .with_max_level(tracing::Level::INFO)
            .with_test_writer()
            .try_init();
    });
}

// ============================================================================
// 1. Basic session scheduling
// ============================================================================

/// Two activities on the same session_id complete in order.
#[tokio::test]
async fn test_session_activity_basic() {
    init_test_logging();
    let (store, container) = common::create_cosmos_store().await;

    let activities = ActivityRegistry::builder()
        .register("Echo", |_ctx: ActivityContext, input: String| async move {
            Ok(format!("echo:{input}"))
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "SessionOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                let r1 = ctx
                    .schedule_activity_on_session("Echo", "hello", "my-session")
                    .await?;
                let r2 = ctx
                    .schedule_activity_on_session("Echo", "world", "my-session")
                    .await?;
                Ok(format!("{r1}|{r2}"))
            },
        )
        .build();

    let rt = runtime::Runtime::start_with_store(store.clone(), activities, orchestrations).await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-session-basic", "SessionOrch", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-session-basic", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "echo:hello|echo:world");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

// ============================================================================
// 2. Session ID visible in ActivityContext
// ============================================================================

/// Verify `ActivityContext::session_id()` returns the correct session ID.
#[tokio::test]
async fn test_session_id_visible_in_activity_context() {
    init_test_logging();
    let (store, container) = common::create_cosmos_store().await;

    let session_seen = Arc::new(AtomicBool::new(false));
    let session_seen_clone = session_seen.clone();

    let activities = ActivityRegistry::builder()
        .register(
            "CheckSession",
            move |ctx: ActivityContext, _input: String| {
                let seen = session_seen_clone.clone();
                async move {
                    if ctx.session_id() == Some("test-session-123") {
                        seen.store(true, Ordering::SeqCst);
                    }
                    Ok("ok".to_string())
                }
            },
        )
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "CheckSessionOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                ctx.schedule_activity_on_session("CheckSession", "input", "test-session-123")
                    .await?;
                Ok("done".to_string())
            },
        )
        .build();

    let rt = runtime::Runtime::start_with_store(store.clone(), activities, orchestrations).await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-ctx-session", "CheckSessionOrch", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-ctx-session", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { .. } => {}
        other => panic!("Expected completed, got {:?}", other),
    }

    assert!(
        session_seen.load(Ordering::SeqCst),
        "Activity should see session_id 'test-session-123' in context"
    );

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

// ============================================================================
// 3. Mixed session and regular activities
// ============================================================================

/// Mix session-pinned and regular activities in the same orchestration.
#[tokio::test]
async fn test_mixed_session_and_regular_activities() {
    init_test_logging();
    let (store, container) = common::create_cosmos_store().await;

    let activities = ActivityRegistry::builder()
        .register(
            "SessionTask",
            |_ctx: ActivityContext, input: String| async move { Ok(format!("session:{input}")) },
        )
        .register(
            "RegularTask",
            |_ctx: ActivityContext, input: String| async move { Ok(format!("regular:{input}")) },
        )
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "MixedOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                let r1 = ctx.schedule_activity("RegularTask", "a").await?;
                let r2 = ctx
                    .schedule_activity_on_session("SessionTask", "b", "sess-1")
                    .await?;
                let r3 = ctx.schedule_activity("RegularTask", "c").await?;
                Ok(format!("{r1}|{r2}|{r3}"))
            },
        )
        .build();

    let rt = runtime::Runtime::start_with_store(store.clone(), activities, orchestrations).await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-mixed", "MixedOrch", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-mixed", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "regular:a|session:b|regular:c");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

// ============================================================================
// 4. Multiple sessions in one orchestration
// ============================================================================

/// Two different session IDs in the same orchestration both complete.
#[tokio::test]
async fn test_multiple_sessions_in_orchestration() {
    init_test_logging();
    let (store, container) = common::create_cosmos_store().await;

    let activities = ActivityRegistry::builder()
        .register("Task", |_ctx: ActivityContext, input: String| async move {
            Ok(input)
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "MultiSessionOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                let r1 = ctx
                    .schedule_activity_on_session("Task", "a", "session-A")
                    .await?;
                let r2 = ctx
                    .schedule_activity_on_session("Task", "b", "session-B")
                    .await?;
                let r3 = ctx
                    .schedule_activity_on_session("Task", "c", "session-A")
                    .await?;
                Ok(format!("{r1}|{r2}|{r3}"))
            },
        )
        .build();

    let rt = runtime::Runtime::start_with_store(store.clone(), activities, orchestrations).await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-multi-session", "MultiSessionOrch", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-multi-session", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "a|b|c");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

// ============================================================================
// 5. Session with worker_node_id
// ============================================================================

/// With worker_node_id set, multiple activities on the same session complete
/// without head-of-line blocking across worker_concurrency slots.
#[tokio::test]
async fn test_session_with_worker_node_id_completes() {
    init_test_logging();
    let (store, container) = common::create_cosmos_store().await;

    let activities = ActivityRegistry::builder()
        .register("Work", |_ctx: ActivityContext, input: String| async move {
            Ok(format!("done:{input}"))
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "StableOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                let r1 = ctx
                    .schedule_activity_on_session("Work", "a", "stable-sess")
                    .await?;
                let r2 = ctx
                    .schedule_activity_on_session("Work", "b", "stable-sess")
                    .await?;
                let r3 = ctx
                    .schedule_activity_on_session("Work", "c", "stable-sess")
                    .await?;
                Ok(format!("{r1}|{r2}|{r3}"))
            },
        )
        .build();

    let options = RuntimeOptions {
        worker_concurrency: 4,
        worker_node_id: Some("stable-pod-1".to_string()),
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-stable-node", "StableOrch", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-stable-node", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "done:a|done:b|done:c");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

// ============================================================================
// 6. Fan-out: concurrent session activities on the same session
// ============================================================================

/// Fan-out multiple concurrent session activities on the same session using `join3`.
#[tokio::test]
async fn test_session_fan_out_same_session() {
    init_test_logging();
    let (store, container) = common::create_cosmos_store().await;

    let counter = Arc::new(AtomicUsize::new(0));
    let counter_clone = counter.clone();

    let activities = ActivityRegistry::builder()
        .register("FanTask", move |_ctx: ActivityContext, input: String| {
            let c = counter_clone.clone();
            async move {
                c.fetch_add(1, Ordering::SeqCst);
                Ok(format!("fan:{input}"))
            }
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "FanOutOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                let f1 = ctx.schedule_activity_on_session("FanTask", "x", "fan-session");
                let f2 = ctx.schedule_activity_on_session("FanTask", "y", "fan-session");
                let f3 = ctx.schedule_activity_on_session("FanTask", "z", "fan-session");
                let (r1, r2, r3) = ctx.join3(f1, f2, f3).await;
                Ok(format!("{}|{}|{}", r1?, r2?, r3?))
            },
        )
        .build();

    // Use worker_node_id so all slots can serve the same session concurrently
    let options = RuntimeOptions {
        worker_concurrency: 4,
        worker_node_id: Some("fan-node".to_string()),
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-fan-out", "FanOutOrch", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-fan-out", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "fan:x|fan:y|fan:z");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    assert!(
        counter.load(Ordering::SeqCst) >= 3,
        "All 3 fan-out activities should have executed"
    );

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

// ============================================================================
// 7. Copilot SDK session pattern (simplified)
// ============================================================================

/// Models the durable-copilot-sdk pattern: an orchestration calls `runAgentTurn`
/// with session affinity, using `continue_as_new` for multi-turn conversations.
///
/// Simplified for PostgreSQL: starts 2 single-turn conversations and verifies
/// in-memory session state accumulates correctly.
#[tokio::test]
async fn test_copilot_sdk_session_pattern() {
    init_test_logging();
    let (store, container) = common::create_cosmos_store().await;

    // ── SessionManager: in-memory session cache ──
    struct SessionManager {
        sessions: std::sync::Mutex<HashMap<String, Vec<String>>>,
        create_count: AtomicUsize,
    }

    impl SessionManager {
        fn new() -> Self {
            Self {
                sessions: std::sync::Mutex::new(HashMap::new()),
                create_count: AtomicUsize::new(0),
            }
        }

        fn get_or_create(&self, session_id: &str) -> Vec<String> {
            let mut map = self.sessions.lock().unwrap();
            if let Some(msgs) = map.get(session_id) {
                msgs.clone()
            } else {
                self.create_count.fetch_add(1, Ordering::SeqCst);
                let msgs = Vec::new();
                map.insert(session_id.to_string(), msgs.clone());
                msgs
            }
        }

        fn update(&self, session_id: &str, messages: Vec<String>) {
            self.sessions
                .lock()
                .unwrap()
                .insert(session_id.to_string(), messages);
        }

        fn message_count(&self, session_id: &str) -> usize {
            self.sessions
                .lock()
                .unwrap()
                .get(session_id)
                .map(|m| m.len())
                .unwrap_or(0)
        }
    }

    let session_mgr = Arc::new(SessionManager::new());
    let mgr_clone = session_mgr.clone();

    let activities = ActivityRegistry::builder()
        .register(
            "runAgentTurn",
            move |ctx: ActivityContext, input: String| {
                let mgr = mgr_clone.clone();
                async move {
                    // input = "session_id|prompt"
                    let parts: Vec<&str> = input.splitn(2, '|').collect();
                    let session_id = parts[0];
                    let prompt = parts.get(1).unwrap_or(&"");

                    // Verify session routing
                    assert_eq!(
                        ctx.session_id(),
                        Some(session_id),
                        "Activity must see its session_id"
                    );

                    let mut messages = mgr.get_or_create(session_id);
                    messages.push(format!("user:{prompt}"));
                    let response = format!("assistant:reply-to-{prompt}");
                    messages.push(response.clone());
                    mgr.update(session_id, messages);

                    Ok(response)
                }
            },
        )
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "durable-turn",
            |ctx: OrchestrationContext, input: String| async move {
                // input = "session_id|prompt"
                let parts: Vec<&str> = input.splitn(2, '|').collect();
                let session_id = parts[0].to_string();

                let result = ctx
                    .schedule_activity_on_session("runAgentTurn", &input, &session_id)
                    .await?;

                Ok(result)
            },
        )
        .build();

    let options = RuntimeOptions {
        worker_concurrency: 2,
        worker_node_id: Some("copilot-pod".to_string()),
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    // Start 2 conversations
    client
        .start_orchestration("conv-1", "durable-turn", "sess-conv-1|Hello Rust")
        .await
        .unwrap();
    client
        .start_orchestration("conv-2", "durable-turn", "sess-conv-2|Explain async")
        .await
        .unwrap();

    // Wait for both to complete
    for conv_id in &["conv-1", "conv-2"] {
        match client
            .wait_for_orchestration(conv_id, Duration::from_secs(60))
            .await
            .unwrap()
        {
            runtime::OrchestrationStatus::Completed { output, .. } => {
                assert!(
                    output.contains("assistant:reply-to-"),
                    "Conversation {conv_id} should have a reply, got: {output}"
                );
            }
            other => panic!("Conversation {conv_id} expected completed, got {:?}", other),
        }
    }

    // Verify in-memory session state accumulated correctly
    assert_eq!(
        session_mgr.message_count("sess-conv-1"),
        2,
        "Session conv-1 should have 2 messages (user + assistant)"
    );
    assert_eq!(
        session_mgr.message_count("sess-conv-2"),
        2,
        "Session conv-2 should have 2 messages (user + assistant)"
    );
    assert_eq!(
        session_mgr.create_count.load(Ordering::SeqCst),
        2,
        "Each session should be created exactly once"
    );

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

// ============================================================================
// Typed session activity
// ============================================================================

#[tokio::test]
async fn test_session_activity_typed() {
    init_test_logging();
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize)]
    struct DoubleInput {
        value: i32,
    }

    let (store, container) = common::create_cosmos_store().await;

    let activities = ActivityRegistry::builder()
        .register(
            "Double",
            |_ctx: ActivityContext, input: String| async move {
                let parsed: DoubleInput = serde_json::from_str(&input).unwrap();
                Ok(serde_json::to_string(&(parsed.value * 2)).unwrap())
            },
        )
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "TypedSessionOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                let result: i32 = ctx
                    .schedule_activity_on_session_typed(
                        "Double",
                        &DoubleInput { value: 21 },
                        "typed-sess",
                    )
                    .await?;
                Ok(result.to_string())
            },
        )
        .build();

    let rt = runtime::Runtime::start_with_store(store.clone(), activities, orchestrations).await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-typed-session", "TypedSessionOrch", "")
        .await
        .unwrap();
    match client
        .wait_for_orchestration("test-typed-session", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "42");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

// ============================================================================
// Process-level session identity E2E tests
// ============================================================================

/// With worker_node_id set, multiple different sessions can be served in parallel
/// by different worker slots sharing the same session identity.
#[tokio::test]
async fn test_session_worker_node_id_multiple_sessions_parallel() {
    init_test_logging();
    use std::sync::atomic::{AtomicUsize, Ordering};

    let (store, container) = common::create_cosmos_store().await;

    let counter = Arc::new(AtomicUsize::new(0));
    let counter_clone = counter.clone();

    let activities = ActivityRegistry::builder()
        .register("Count", move |_ctx: ActivityContext, _input: String| {
            let c = counter_clone.clone();
            async move {
                c.fetch_add(1, Ordering::SeqCst);
                Ok("counted".to_string())
            }
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "ParallelSessions",
            |ctx: OrchestrationContext, _input: String| async move {
                // Schedule activities on 3 different sessions
                let f1 = ctx.schedule_activity_on_session("Count", "x", "sess-1");
                let f2 = ctx.schedule_activity_on_session("Count", "y", "sess-2");
                let f3 = ctx.schedule_activity_on_session("Count", "z", "sess-3");
                let results = ctx.join3(f1, f2, f3).await;
                let r1 = results.0?;
                let r2 = results.1?;
                let r3 = results.2?;
                Ok(format!("{r1}|{r2}|{r3}"))
            },
        )
        .build();

    let options = RuntimeOptions {
        worker_concurrency: 4,
        worker_node_id: Some("multi-sess-pod".to_string()),
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-parallel-sess", "ParallelSessions", "")
        .await
        .unwrap();
    match client
        .wait_for_orchestration("test-parallel-sess", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "counted|counted|counted");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    // At-least-once: counter may exceed 3 if an ack fails and the activity retries
    assert!(
        counter.load(Ordering::SeqCst) >= 3,
        "All 3 session activities should have executed"
    );
    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

/// Ephemeral mode (worker_node_id=None) with worker_concurrency=1 still works.
/// Regression test for the per-slot identity path.
#[tokio::test]
async fn test_ephemeral_session_still_works() {
    init_test_logging();
    let (store, container) = common::create_cosmos_store().await;

    let activities = ActivityRegistry::builder()
        .register("Echo", |_ctx: ActivityContext, input: String| async move {
            Ok(input)
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "EphemeralOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                let r = ctx
                    .schedule_activity_on_session("Echo", "ephemeral-val", "eph-sess")
                    .await?;
                Ok(r)
            },
        )
        .build();

    let options = RuntimeOptions {
        worker_concurrency: 1,
        worker_node_id: None,
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-ephemeral", "EphemeralOrch", "")
        .await
        .unwrap();
    match client
        .wait_for_orchestration("test-ephemeral", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "ephemeral-val");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

/// With worker_node_id set, ActivityContext::session_id() returns the session ID
/// (not the worker node identity).
#[tokio::test]
async fn test_session_with_worker_node_id_activity_context_has_session_id() {
    init_test_logging();

    let (store, container) = common::create_cosmos_store().await;

    let correct_session = Arc::new(AtomicBool::new(false));
    let correct_session_clone = correct_session.clone();

    let activities = ActivityRegistry::builder()
        .register("CheckSess", move |ctx: ActivityContext, _input: String| {
            let flag = correct_session_clone.clone();
            async move {
                // session_id() should return "my-session", NOT "k8s-pod-name"
                if ctx.session_id() == Some("my-session") {
                    flag.store(true, Ordering::SeqCst);
                }
                Ok("ok".to_string())
            }
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "NodeIdSessionOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                ctx.schedule_activity_on_session("CheckSess", "", "my-session")
                    .await?;
                Ok("done".to_string())
            },
        )
        .build();

    let options = RuntimeOptions {
        worker_concurrency: 2,
        worker_node_id: Some("k8s-pod-name".to_string()),
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-node-ctx", "NodeIdSessionOrch", "")
        .await
        .unwrap();
    match client
        .wait_for_orchestration("test-node-ctx", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { .. } => {}
        other => panic!("Expected completed, got {:?}", other),
    }

    assert!(
        correct_session.load(Ordering::SeqCst),
        "ActivityContext::session_id() should return the session ID, not the worker_node_id"
    );

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

/// Proves that with process-level session identity (worker_node_id set),
/// two worker slots can concurrently serve the same session.
#[tokio::test]
async fn test_two_slots_serve_same_session_concurrently() {
    init_test_logging();
    use std::sync::atomic::{AtomicI32, Ordering};

    let (store, container) = common::create_cosmos_store().await;

    let in_flight = Arc::new(AtomicI32::new(0));
    let max_concurrent = Arc::new(AtomicI32::new(0));

    let in_flight_a = in_flight.clone();
    let max_concurrent_a = max_concurrent.clone();
    let in_flight_b = in_flight.clone();
    let max_concurrent_b = max_concurrent.clone();

    let activities = ActivityRegistry::builder()
        .register("SlowTask", move |_ctx: ActivityContext, input: String| {
            let inf = in_flight_a.clone();
            let maxc = max_concurrent_a.clone();
            async move {
                let current = inf.fetch_add(1, Ordering::SeqCst) + 1;
                // Update max if this is a new high
                maxc.fetch_max(current, Ordering::SeqCst);
                // Hold the slot long enough for the other activity to also start
                tokio::time::sleep(Duration::from_millis(1000)).await;
                inf.fetch_sub(1, Ordering::SeqCst);
                Ok(format!("slow:{input}"))
            }
        })
        .register("FastTask", move |_ctx: ActivityContext, input: String| {
            let inf = in_flight_b.clone();
            let maxc = max_concurrent_b.clone();
            async move {
                let current = inf.fetch_add(1, Ordering::SeqCst) + 1;
                maxc.fetch_max(current, Ordering::SeqCst);
                // Brief sleep to overlap with SlowTask
                tokio::time::sleep(Duration::from_millis(400)).await;
                inf.fetch_sub(1, Ordering::SeqCst);
                Ok(format!("fast:{input}"))
            }
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "ConcurrentSessionOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                // Both on the SAME session, scheduled in parallel
                let f1 = ctx.schedule_activity_on_session("SlowTask", "a", "same-session");
                let f2 = ctx.schedule_activity_on_session("FastTask", "b", "same-session");
                let (r1, r2) = ctx.join2(f1, f2).await;
                Ok(format!("{}|{}", r1?, r2?))
            },
        )
        .build();

    // Process-level identity: all slots share "my-node"
    let options = RuntimeOptions {
        worker_concurrency: 2,
        worker_node_id: Some("my-node".to_string()),
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-concurrent-session", "ConcurrentSessionOrch", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-concurrent-session", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "slow:a|fast:b");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    assert_eq!(
        max_concurrent.load(Ordering::SeqCst),
        2,
        "Both activities should have been in-flight simultaneously, \
         proving two slots served the same session concurrently"
    );

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

/// Counterpart to `test_two_slots_serve_same_session_concurrently`:
/// WITHOUT worker_node_id (ephemeral per-slot identity), two activities
/// on the same session are serialized because only one slot owns the session.
/// max_concurrent must be 1.
#[tokio::test]
async fn test_ephemeral_same_session_serialized() {
    init_test_logging();
    use std::sync::atomic::{AtomicI32, Ordering};

    let (store, container) = common::create_cosmos_store().await;

    let in_flight = Arc::new(AtomicI32::new(0));
    let max_concurrent = Arc::new(AtomicI32::new(0));

    let in_flight_a = in_flight.clone();
    let max_concurrent_a = max_concurrent.clone();
    let in_flight_b = in_flight.clone();
    let max_concurrent_b = max_concurrent.clone();

    let activities = ActivityRegistry::builder()
        .register("SlowTask", move |_ctx: ActivityContext, input: String| {
            let inf = in_flight_a.clone();
            let maxc = max_concurrent_a.clone();
            async move {
                let current = inf.fetch_add(1, Ordering::SeqCst) + 1;
                maxc.fetch_max(current, Ordering::SeqCst);
                tokio::time::sleep(Duration::from_millis(1000)).await;
                inf.fetch_sub(1, Ordering::SeqCst);
                Ok(format!("slow:{input}"))
            }
        })
        .register("FastTask", move |_ctx: ActivityContext, input: String| {
            let inf = in_flight_b.clone();
            let maxc = max_concurrent_b.clone();
            async move {
                let current = inf.fetch_add(1, Ordering::SeqCst) + 1;
                maxc.fetch_max(current, Ordering::SeqCst);
                tokio::time::sleep(Duration::from_millis(400)).await;
                inf.fetch_sub(1, Ordering::SeqCst);
                Ok(format!("fast:{input}"))
            }
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "SerialSessionOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                let f1 = ctx.schedule_activity_on_session("SlowTask", "a", "same-session");
                let f2 = ctx.schedule_activity_on_session("FastTask", "b", "same-session");
                let (r1, r2) = ctx.join2(f1, f2).await;
                Ok(format!("{}|{}", r1?, r2?))
            },
        )
        .build();

    // Ephemeral per-slot identity: each slot gets a different worker_id
    let options = RuntimeOptions {
        worker_concurrency: 2,
        worker_node_id: None, // <-- no stable identity
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-serial-session", "SerialSessionOrch", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-serial-session", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "slow:a|fast:b");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    assert_eq!(
        max_concurrent.load(Ordering::SeqCst),
        1,
        "Without stable worker_node_id, only one slot owns the session, \
         so activities must execute sequentially (max_concurrent == 1)"
    );

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

// ============================================================================
// Fan-out / Fan-in with Sessions
// ============================================================================

/// Fan-out/fan-in: multiple activities on different sessions execute in parallel,
/// then results are collected. Verifies that ctx.join works with session activities.
#[tokio::test]
async fn test_session_fan_out_fan_in() {
    init_test_logging();
    let (store, container) = common::create_cosmos_store().await;

    let activities = ActivityRegistry::builder()
        .register(
            "Process",
            |_ctx: ActivityContext, input: String| async move { Ok(format!("processed:{input}")) },
        )
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "FanOutOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                // Fan-out: schedule activities across 3 different sessions
                let futures: Vec<_> = (0..3)
                    .map(|i| {
                        let session = format!("session-{i}");
                        ctx.schedule_activity_on_session("Process", i.to_string(), session)
                    })
                    .collect();

                // Fan-in: wait for all to complete
                let results = ctx.join(futures).await;
                let outputs: Vec<String> = results.into_iter().collect::<Result<Vec<_>, _>>()?;
                Ok(outputs.join("|"))
            },
        )
        .build();

    let options = RuntimeOptions {
        worker_concurrency: 4,
        worker_node_id: Some("fan-pod".to_string()),
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-fan-out", "FanOutOrch", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-fan-out", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "processed:0|processed:1|processed:2");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

/// Fan-out/fan-in mixing session and non-session activities in the same join.
#[tokio::test]
async fn test_session_fan_out_mixed_with_regular() {
    init_test_logging();
    let (store, container) = common::create_cosmos_store().await;

    let activities = ActivityRegistry::builder()
        .register(
            "SessionWork",
            |_ctx: ActivityContext, input: String| async move { Ok(format!("sess:{input}")) },
        )
        .register(
            "RegularWork",
            |_ctx: ActivityContext, input: String| async move { Ok(format!("reg:{input}")) },
        )
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "MixedFanOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                let f1 = ctx.schedule_activity_on_session("SessionWork", "a", "s1");
                let f2 = ctx.schedule_activity("RegularWork", "b");
                let f3 = ctx.schedule_activity_on_session("SessionWork", "c", "s2");
                let f4 = ctx.schedule_activity("RegularWork", "d");

                let results = ctx.join(vec![f1, f2, f3, f4]).await;
                let outputs: Vec<String> = results.into_iter().collect::<Result<Vec<_>, _>>()?;
                Ok(outputs.join("|"))
            },
        )
        .build();

    let rt = runtime::Runtime::start_with_store(store.clone(), activities, orchestrations).await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-mixed-fan", "MixedFanOrch", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-mixed-fan", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "sess:a|reg:b|sess:c|reg:d");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

/// Fan-out with multiple activities per session: 2 on session-A, 2 on session-B,
/// and 2 non-session activities, all scheduled in parallel via ctx.join.
#[tokio::test]
async fn test_fan_out_multiple_per_session_mixed() {
    init_test_logging();
    let (store, container) = common::create_cosmos_store().await;

    let activities = ActivityRegistry::builder()
        .register("Tag", |_ctx: ActivityContext, input: String| async move {
            Ok(format!("tag:{input}"))
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "MultiMixOrch",
            |ctx: OrchestrationContext, _input: String| async move {
                let f1 = ctx.schedule_activity_on_session("Tag", "s1-a", "session-1");
                let f2 = ctx.schedule_activity_on_session("Tag", "s1-b", "session-1");
                let f3 = ctx.schedule_activity_on_session("Tag", "s2-a", "session-2");
                let f4 = ctx.schedule_activity_on_session("Tag", "s2-b", "session-2");
                let f5 = ctx.schedule_activity("Tag", "no-sess-a");
                let f6 = ctx.schedule_activity("Tag", "no-sess-b");

                let results = ctx.join(vec![f1, f2, f3, f4, f5, f6]).await;
                let outputs: Vec<String> = results.into_iter().collect::<Result<Vec<_>, _>>()?;
                Ok(outputs.join("|"))
            },
        )
        .build();

    let options = RuntimeOptions {
        worker_concurrency: 4,
        worker_node_id: Some("mix-pod".to_string()),
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-multi-mix", "MultiMixOrch", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-multi-mix", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(
                output,
                "tag:s1-a|tag:s1-b|tag:s2-a|tag:s2-b|tag:no-sess-a|tag:no-sess-b"
            );
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

// ============================================================================
// Sessions across continue-as-new with version bumps
// ============================================================================

/// Session survives continue-as-new within the same version.
#[tokio::test]
async fn test_session_survives_continue_as_new() {
    init_test_logging();
    let (store, container) = common::create_cosmos_store().await;

    let activities = ActivityRegistry::builder()
        .register("Track", |_ctx: ActivityContext, input: String| async move {
            Ok(format!("tracked:{input}"))
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "SessionCAN",
            |ctx: OrchestrationContext, input: String| async move {
                let iteration: u32 = input.parse().unwrap_or(0);
                let r = ctx
                    .schedule_activity_on_session(
                        "Track",
                        format!("iter-{iteration}"),
                        "persistent-session",
                    )
                    .await?;
                if iteration == 0 {
                    // First execution: CAN to iteration 1
                    ctx.continue_as_new("1").await
                } else {
                    // Second execution: complete with both results
                    Ok(r)
                }
            },
        )
        .build();

    let options = RuntimeOptions {
        worker_concurrency: 1,
        orchestration_concurrency: 1,
        worker_node_id: Some("can-pod".to_string()),
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-session-can", "SessionCAN", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-session-can", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "tracked:iter-1");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

/// Continue-as-new with versioned upgrade: v1 schedules session activity then
/// explicitly continues to v2.
#[tokio::test]
async fn test_session_continue_as_new_versioned_upgrade() {
    init_test_logging();
    use semver::Version;

    let (store, container) = common::create_cosmos_store().await;

    let activities = ActivityRegistry::builder()
        .register("Work", |_ctx: ActivityContext, input: String| async move {
            Ok(format!("done:{input}"))
        })
        .build();

    let v1 = |ctx: OrchestrationContext, _input: String| async move {
        let r = ctx
            .schedule_activity_on_session("Work", "from-v1", "upgrade-session")
            .await?;
        ctx.continue_as_new_versioned("2.0.0", r).await
    };

    let v2 = |ctx: OrchestrationContext, input: String| async move {
        let r = ctx
            .schedule_activity_on_session("Work", "from-v2", "upgrade-session")
            .await?;
        Ok(format!("{input}+{r}"))
    };

    let orchestrations = OrchestrationRegistry::builder()
        .register("UpgradeSession", v1)
        .register_versioned("UpgradeSession", "2.0.0", v2)
        .set_policy(
            "UpgradeSession",
            duroxide::runtime::VersionPolicy::Exact(Version::parse("1.0.0").unwrap()),
        )
        .build();

    let options = RuntimeOptions {
        worker_concurrency: 1,
        orchestration_concurrency: 1,
        worker_node_id: Some("upgrade-pod".to_string()),
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-session-can-ver", "UpgradeSession", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-session-can-ver", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "done:from-v1+done:from-v2");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

/// Validates that `start_with_options` panics when `session_idle_timeout` is not
/// greater than the worker lock renewal interval.
#[tokio::test]
#[should_panic(expected = "session_idle_timeout")]
async fn test_session_idle_timeout_must_exceed_worker_renewal_interval() {
    init_test_logging();
    let (store, _container) = common::create_cosmos_store().await;

    let activities = ActivityRegistry::builder().build();
    let orchestrations = OrchestrationRegistry::builder().build();

    // worker_lock_timeout=30s, buffer=5s -> renewal interval = 25s
    // session_idle_timeout=25s (equal, not greater) -> should panic
    let options = RuntimeOptions {
        session_idle_timeout: Duration::from_secs(50),
        worker_lock_timeout: Duration::from_secs(60),
        worker_lock_renewal_buffer: Duration::from_secs(10),
        ..Default::default()
    };

    // This should panic
    let _rt =
        runtime::Runtime::start_with_options(store, activities, orchestrations, options).await;
}

// ============================================================================
// Session capacity enforcement
// ============================================================================

/// Verify that max_sessions_per_runtime is enforced via runtime-side ref counting.
#[tokio::test]
async fn test_max_sessions_per_runtime_enforced() {
    init_test_logging();
    use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};

    let (store, container) = common::create_cosmos_store().await;

    let concurrent = Arc::new(AtomicUsize::new(0));
    let peak = Arc::new(AtomicUsize::new(0));

    let concurrent_c = concurrent.clone();
    let peak_c = peak.clone();

    let activities = ActivityRegistry::builder()
        .register(
            "SlowSession",
            move |_ctx: ActivityContext, _input: String| {
                let conc = concurrent_c.clone();
                let pk = peak_c.clone();
                async move {
                    let cur = conc.fetch_add(1, AOrdering::SeqCst) + 1;
                    pk.fetch_max(cur, AOrdering::SeqCst);
                    tokio::time::sleep(Duration::from_millis(400)).await;
                    conc.fetch_sub(1, AOrdering::SeqCst);
                    Ok("done".to_string())
                }
            },
        )
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "TwoSessions",
            |ctx: OrchestrationContext, _input: String| async move {
                let f1 = ctx.schedule_activity_on_session("SlowSession", "a", "session-A");
                let f2 = ctx.schedule_activity_on_session("SlowSession", "b", "session-B");
                let results = ctx.join(vec![f1, f2]).await;
                let r1 = results[0].as_ref().map_err(|e| e.clone())?;
                let r2 = results[1].as_ref().map_err(|e| e.clone())?;
                Ok(format!("{r1}|{r2}"))
            },
        )
        .build();

    let options = RuntimeOptions {
        worker_concurrency: 2,
        max_sessions_per_runtime: 1,
        orchestration_concurrency: 1,
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-max-sessions", "TwoSessions", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-max-sessions", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "done|done");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    assert_eq!(
        peak.load(AOrdering::SeqCst),
        1,
        "With max_sessions_per_runtime=1, activities on different sessions should not run concurrently"
    );

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

/// Verify that multiple activities on the SAME session count as 1 distinct session.
#[tokio::test]
async fn test_same_session_shares_one_slot() {
    init_test_logging();
    use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};

    let (store, container) = common::create_cosmos_store().await;

    let concurrent = Arc::new(AtomicUsize::new(0));
    let peak = Arc::new(AtomicUsize::new(0));

    let concurrent_c = concurrent.clone();
    let peak_c = peak.clone();

    let activities = ActivityRegistry::builder()
        .register("SlowSame", move |_ctx: ActivityContext, _input: String| {
            let conc = concurrent_c.clone();
            let pk = peak_c.clone();
            async move {
                let cur = conc.fetch_add(1, AOrdering::SeqCst) + 1;
                pk.fetch_max(cur, AOrdering::SeqCst);
                tokio::time::sleep(Duration::from_millis(600)).await;
                conc.fetch_sub(1, AOrdering::SeqCst);
                Ok("ok".to_string())
            }
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "SameSessionFanOut",
            |ctx: OrchestrationContext, _input: String| async move {
                let f1 = ctx.schedule_activity_on_session("SlowSame", "a", "shared-session");
                let f2 = ctx.schedule_activity_on_session("SlowSame", "b", "shared-session");
                let results = ctx.join(vec![f1, f2]).await;
                let r1 = results[0].as_ref().map_err(|e| e.clone())?;
                let r2 = results[1].as_ref().map_err(|e| e.clone())?;
                Ok(format!("{r1}|{r2}"))
            },
        )
        .build();

    let options = RuntimeOptions {
        worker_concurrency: 2,
        max_sessions_per_runtime: 1,
        orchestration_concurrency: 1,
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-same-session-slot", "SameSessionFanOut", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("test-same-session-slot", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "ok|ok");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

/// Verify that a session-bound activity is blocked when at capacity, then
/// unblocked once the blocking session completes.
///
/// Both activities block until explicitly released so the test is
/// order-independent — whichever the provider dispatches first will hold
/// the single session slot while we verify the other is blocked.
#[tokio::test]
async fn test_session_cap_blocks_then_unblocks() {
    init_test_logging();
    use std::sync::Mutex;
    use tokio::sync::Notify;

    let (store, container) = common::create_cosmos_store().await;

    let log: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let release_a: Arc<Notify> = Arc::new(Notify::new());
    let release_b: Arc<Notify> = Arc::new(Notify::new());

    let log_c = log.clone();
    let ra_c = release_a.clone();
    let rb_c = release_b.clone();

    let activities = ActivityRegistry::builder()
        .register("Tracked", move |_ctx: ActivityContext, input: String| {
            let lg = log_c.clone();
            let ra = ra_c.clone();
            let rb = rb_c.clone();
            async move {
                lg.lock().unwrap().push(format!("{input}-started"));

                // Both activities hold their session slot until released
                match input.as_str() {
                    "A" => ra.notified().await,
                    "B" => rb.notified().await,
                    _ => {}
                }

                lg.lock().unwrap().push(format!("{input}-finished"));
                Ok(format!("result-{input}"))
            }
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "BlockUnblock",
            |ctx: OrchestrationContext, _input: String| async move {
                let fa = ctx.schedule_activity_on_session("Tracked", "A", "session-A");
                let fb = ctx.schedule_activity_on_session("Tracked", "B", "session-B");
                let results = ctx.join(vec![fa, fb]).await;
                let ra = results[0].as_ref().map_err(|e| e.clone())?;
                let rb = results[1].as_ref().map_err(|e| e.clone())?;
                Ok(format!("{ra}|{rb}"))
            },
        )
        .build();

    let options = RuntimeOptions {
        worker_concurrency: 2,
        max_sessions_per_runtime: 1,
        orchestration_concurrency: 1,
        ..Default::default()
    };

    let rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, options)
            .await;
    let client = Client::new(store.clone());

    client
        .start_orchestration("test-block-unblock", "BlockUnblock", "")
        .await
        .unwrap();

    // Wait for either activity to start (whichever the provider dispatches first)
    let first = {
        let mut found: Option<&str> = None;
        for _ in 0..100 {
            tokio::time::sleep(Duration::from_millis(100)).await;
            let events = log.lock().unwrap().clone();
            if events.contains(&"A-started".to_string()) {
                found = Some("A");
                break;
            }
            if events.contains(&"B-started".to_string()) {
                found = Some("B");
                break;
            }
        }
        found
    };
    let first = first.expect("Timed out waiting for any activity to start");
    let second = if first == "A" { "B" } else { "A" };

    // Give the other activity a chance to start (it shouldn't with cap=1)
    tokio::time::sleep(Duration::from_millis(500)).await;

    {
        let events = log.lock().unwrap().clone();
        assert!(
            !events.contains(&format!("{second}-started")),
            "{second} should NOT have started while {first} holds the session cap, got: {events:?}"
        );
    }

    // Release the first activity — this frees the session slot
    match first {
        "A" => release_a.notify_one(),
        "B" => release_b.notify_one(),
        _ => unreachable!(),
    }

    // Wait for the second activity to start
    {
        let mut found = false;
        for _ in 0..100 {
            tokio::time::sleep(Duration::from_millis(100)).await;
            let events = log.lock().unwrap().clone();
            if events.contains(&format!("{second}-started")) {
                found = true;
                break;
            }
        }
        assert!(
            found,
            "Timed out waiting for {second} to start after {first} finished"
        );
    }

    // Release the second activity
    match second {
        "A" => release_a.notify_one(),
        "B" => release_b.notify_one(),
        _ => unreachable!(),
    }

    match client
        .wait_for_orchestration("test-block-unblock", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            assert_eq!(output, "result-A|result-B");
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    // Verify ordering: first must have finished before second started
    let events = log.lock().unwrap().clone();
    let first_finished = events
        .iter()
        .position(|e| *e == format!("{first}-finished"))
        .unwrap_or_else(|| panic!("{first}-finished missing"));
    let second_started_pos = events
        .iter()
        .position(|e| *e == format!("{second}-started"))
        .unwrap_or_else(|| panic!("{second}-started missing"));
    assert!(
        first_finished < second_started_pos,
        "{second} should start only after {first} finishes. Event log: {events:?}"
    );

    rt.shutdown(None).await;
    common::cleanup_container(&container).await;
}

// ============================================================================
// Multi-worker E2E tests (two runtimes, shared store)
// ============================================================================

/// Complex orchestration across 2 worker runtimes sharing the same store.
#[tokio::test]
async fn test_multi_worker_complex_orchestration() {
    init_test_logging();
    use std::sync::atomic::{AtomicUsize, Ordering};

    let (store, container) = common::create_cosmos_store().await;

    let worker_a_count = Arc::new(AtomicUsize::new(0));
    let worker_b_count = Arc::new(AtomicUsize::new(0));

    fn build_activities(counter: Arc<AtomicUsize>) -> ActivityRegistry {
        ActivityRegistry::builder()
            .register("SessionWork", move |ctx: ActivityContext, input: String| {
                let c = counter.clone();
                async move {
                    c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    assert!(
                        ctx.session_id().is_some(),
                        "SessionWork must have a session_id"
                    );
                    tokio::time::sleep(Duration::from_millis(100)).await;
                    Ok(format!("session-result:{input}"))
                }
            })
            .register(
                "PlainWork",
                |_ctx: ActivityContext, input: String| async move {
                    tokio::time::sleep(Duration::from_millis(60)).await;
                    Ok(format!("plain-result:{input}"))
                },
            )
            .build()
    }

    fn build_orchestrations() -> OrchestrationRegistry {
        OrchestrationRegistry::builder()
            .register(
                "MultiWorkerOrch",
                |ctx: OrchestrationContext, input: String| async move {
                    let parts: Vec<&str> = input.splitn(2, '|').collect();
                    let cycle: u32 = parts[0].parse().unwrap_or(0);
                    let prev = parts.get(1).unwrap_or(&"").to_string();

                    match cycle {
                        0 => {
                            let s1 =
                                ctx.schedule_activity_on_session("SessionWork", "a", "sess-alpha");
                            let s2 =
                                ctx.schedule_activity_on_session("SessionWork", "b", "sess-alpha");
                            let s3 =
                                ctx.schedule_activity_on_session("SessionWork", "c", "sess-beta");
                            let p1 = ctx.schedule_activity("PlainWork", "d");
                            let results = ctx.join(vec![s1, s2, s3, p1]).await;
                            let combined: Vec<String> = results
                                .into_iter()
                                .map(|r| r.unwrap_or_else(|e| format!("ERR:{e}")))
                                .collect();

                            ctx.continue_as_new(format!("1|{}", combined.join(";")))
                                .await
                        }
                        1 => {
                            let r1 = ctx
                                .schedule_activity_on_session("SessionWork", "e", "sess-alpha")
                                .await?;
                            let r2 = ctx
                                .schedule_activity_on_session("SessionWork", "f", "sess-beta")
                                .await?;
                            Ok(format!("{prev};{r1};{r2}"))
                        }
                        _ => Ok(format!("unexpected cycle {cycle}")),
                    }
                },
            )
            .build()
    }

    let rt_a = runtime::Runtime::start_with_options(
        store.clone(),
        build_activities(worker_a_count.clone()),
        build_orchestrations(),
        RuntimeOptions {
            worker_concurrency: 2,
            orchestration_concurrency: 2,
            worker_node_id: Some("node-A".to_string()),
            max_sessions_per_runtime: 4,
            ..Default::default()
        },
    )
    .await;

    let rt_b = runtime::Runtime::start_with_options(
        store.clone(),
        build_activities(worker_b_count.clone()),
        build_orchestrations(),
        RuntimeOptions {
            worker_concurrency: 2,
            orchestration_concurrency: 2,
            worker_node_id: Some("node-B".to_string()),
            max_sessions_per_runtime: 4,
            ..Default::default()
        },
    )
    .await;

    let client = Client::new(store.clone());

    client
        .start_orchestration("multi-worker-complex", "MultiWorkerOrch", "0|")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("multi-worker-complex", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            let parts: Vec<&str> = output.split(';').collect();
            assert_eq!(parts.len(), 6, "Should have 6 results total, got: {output}");

            let session_results: Vec<&&str> = parts
                .iter()
                .filter(|p| p.contains("session-result:"))
                .collect();
            assert_eq!(
                session_results.len(),
                5,
                "Should have 5 session results, got: {output}"
            );

            assert!(
                output.contains("plain-result:d"),
                "Plain activity result missing: {output}"
            );
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    let a = worker_a_count.load(Ordering::SeqCst);
    let b = worker_b_count.load(Ordering::SeqCst);
    assert_eq!(
        a + b,
        5,
        "Total session activities should be 5 (3 + 2 from CAN), got A={a} B={b}"
    );

    rt_a.shutdown(None).await;
    rt_b.shutdown(None).await;
    common::cleanup_container(&container).await;
}

/// Heterogeneous multi-worker test: different max_sessions and session_lock_timeout.
#[tokio::test]
async fn test_multi_worker_heterogeneous_config() {
    init_test_logging();
    use std::sync::atomic::{AtomicUsize, Ordering};

    let (store, container) = common::create_cosmos_store().await;

    let worker_a_sessions = Arc::new(AtomicUsize::new(0));
    let worker_b_sessions = Arc::new(AtomicUsize::new(0));

    fn build_activities(counter: Arc<AtomicUsize>) -> ActivityRegistry {
        ActivityRegistry::builder()
            .register("Work", move |_ctx: ActivityContext, input: String| {
                let c = counter.clone();
                async move {
                    c.fetch_add(1, Ordering::SeqCst);
                    tokio::time::sleep(Duration::from_millis(1600)).await;
                    Ok(format!("done:{input}"))
                }
            })
            .build()
    }

    fn build_orchestrations() -> OrchestrationRegistry {
        OrchestrationRegistry::builder()
            .register(
                "HeteroOrch",
                |ctx: OrchestrationContext, _input: String| async move {
                    let f1 = ctx.schedule_activity_on_session("Work", "1", "sess-X");
                    let f2 = ctx.schedule_activity_on_session("Work", "2", "sess-Y");
                    let f3 = ctx.schedule_activity_on_session("Work", "3", "sess-Z");
                    let results = ctx.join(vec![f1, f2, f3]).await;
                    let combined: String = results
                        .into_iter()
                        .map(|r| r.unwrap_or_else(|e| format!("ERR:{e}")))
                        .collect::<Vec<_>>()
                        .join("|");
                    Ok(combined)
                },
            )
            .build()
    }

    let rt_a = runtime::Runtime::start_with_options(
        store.clone(),
        build_activities(worker_a_sessions.clone()),
        build_orchestrations(),
        RuntimeOptions {
            worker_concurrency: 2,
            orchestration_concurrency: 2,
            worker_node_id: Some("constrained-node".to_string()),
            max_sessions_per_runtime: 1,
            session_lock_timeout: Duration::from_secs(10),
            session_lock_renewal_buffer: Duration::from_secs(2),
            session_idle_timeout: Duration::from_secs(60),
            ..Default::default()
        },
    )
    .await;

    let rt_b = runtime::Runtime::start_with_options(
        store.clone(),
        build_activities(worker_b_sessions.clone()),
        build_orchestrations(),
        RuntimeOptions {
            worker_concurrency: 2,
            orchestration_concurrency: 2,
            worker_node_id: Some("unconstrained-node".to_string()),
            max_sessions_per_runtime: 10,
            session_lock_timeout: Duration::from_secs(60),
            session_lock_renewal_buffer: Duration::from_secs(10),
            session_idle_timeout: Duration::from_secs(120),
            ..Default::default()
        },
    )
    .await;

    let client = Client::new(store.clone());

    client
        .start_orchestration("hetero-test", "HeteroOrch", "")
        .await
        .unwrap();

    match client
        .wait_for_orchestration("hetero-test", Duration::from_secs(60))
        .await
        .unwrap()
    {
        runtime::OrchestrationStatus::Completed { output, .. } => {
            let parts: Vec<&str> = output.split('|').collect();
            assert_eq!(parts.len(), 3, "Should have 3 results, got: {output}");
            for p in &parts {
                assert!(
                    p.starts_with("done:"),
                    "Each result should start with 'done:', got: {p}"
                );
            }
        }
        other => panic!("Expected completed, got {:?}", other),
    }

    let a = worker_a_sessions.load(Ordering::SeqCst);
    let b = worker_b_sessions.load(Ordering::SeqCst);
    assert_eq!(a + b, 3, "Total should be 3, got A={a} B={b}");
    assert!(
        b >= 1,
        "Worker B should handle at least 1 session (overflow from A's max_sessions=1), got A={a} B={b}"
    );

    rt_a.shutdown(None).await;
    rt_b.shutdown(None).await;
    common::cleanup_container(&container).await;
}