cruster 0.0.27

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

#[cfg(test)]
mod tests {
    use crate::entity_client::EntityClient;
    use crate::envelope::{AckChunk, EnvelopeRequest, Interrupt};
    use crate::hash::shard_for_entity;
    use crate::message::ReplyReceiver;
    use crate::prelude::*;
    use crate::reply::{ExitResult, Reply, ReplyWithExit};
    use crate::sharding::{Sharding, ShardingRegistrationEvent};
    use crate::singleton::SingletonContext;
    use crate::snowflake::{Snowflake, SnowflakeGenerator};
    use crate::types::{EntityAddress, EntityId, EntityType, RunnerAddress, ShardId};
    use async_trait::async_trait;
    use futures::future::BoxFuture;
    use std::collections::HashMap;
    use std::pin::Pin;
    use std::sync::atomic::Ordering;
    use std::sync::Arc;
    use std::sync::Mutex;
    use tokio_stream::Stream;

    fn test_ctx(entity_type: &str, entity_id: &str) -> EntityContext {
        EntityContext {
            address: EntityAddress {
                shard_id: ShardId::new("default", 0),
                entity_type: EntityType::new(entity_type),
                entity_id: EntityId::new(entity_id),
            },
            runner_address: RunnerAddress::new("127.0.0.1", 9000),
            snowflake: Arc::new(SnowflakeGenerator::new()),
            cancellation: tokio_util::sync::CancellationToken::new(),
            state_storage: None,
            workflow_engine: None,
            sharding: None,
            message_storage: None,
        }
    }

    // --- Stateless entity ---

    #[entity(krate = "crate")]
    #[derive(Clone)]
    struct Ping;

    #[entity_impl(krate = "crate")]
    impl Ping {
        #[rpc]
        async fn ping(&self) -> Result<String, ClusterError> {
            Ok("pong".to_string())
        }
    }

    #[test]
    fn stateless_entity_type_name() {
        let e = Ping;
        assert_eq!(e.entity_type().0, "Ping");
    }

    #[tokio::test]
    async fn stateless_entity_dispatch() {
        let e = Ping;
        let ctx = test_ctx("Ping", "p-1");
        let handler = e.spawn(ctx).await.unwrap();
        let result = handler
            .handle_request("ping", &[], &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "pong");
    }

    #[tokio::test]
    async fn stateless_entity_unknown_tag() {
        let e = Ping;
        let ctx = test_ctx("Ping", "p-1");
        let handler = e.spawn(ctx).await.unwrap();
        let err = handler
            .handle_request("unknown", &[], &HashMap::new())
            .await
            .unwrap_err();
        assert!(matches!(err, ClusterError::MalformedMessage { .. }));
    }

    #[entity(name = "CustomPing", krate = "crate")]
    #[derive(Clone)]
    struct CustomNamePing;

    #[entity_impl(krate = "crate")]
    impl CustomNamePing {
        #[rpc]
        async fn ping(&self) -> Result<String, ClusterError> {
            Ok("custom-pong".to_string())
        }
    }

    #[test]
    fn custom_name_entity() {
        let e = CustomNamePing;
        assert_eq!(e.entity_type().0, "CustomPing");
    }

    // --- Entity with #[rpc(persisted)] ---

    #[entity(krate = "crate")]
    #[derive(Clone)]
    struct PersistedRpcEntity;

    #[entity_impl(krate = "crate")]
    impl PersistedRpcEntity {
        #[rpc]
        async fn read_data(&self) -> Result<String, ClusterError> {
            Ok("data".to_string())
        }

        #[rpc(persisted)]
        async fn write_data(&self, value: String) -> Result<String, ClusterError> {
            Ok(format!("wrote: {value}"))
        }
    }

    #[test]
    fn persisted_rpc_entity_type_name() {
        let e = PersistedRpcEntity;
        assert_eq!(e.entity_type().0, "PersistedRpcEntity");
    }

    #[tokio::test]
    async fn persisted_rpc_entity_dispatch() {
        let e = PersistedRpcEntity;
        let ctx = test_ctx("PersistedRpcEntity", "pr-1");
        let handler = e.spawn(ctx).await.unwrap();

        // Non-persisted RPC
        let result = handler
            .handle_request("read_data", &[], &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "data");

        // Persisted RPC — dispatch works the same, persistence is a client-side concern
        let payload = rmp_serde::to_vec(&"hello".to_string()).unwrap();
        let result = handler
            .handle_request("write_data", &payload, &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "wrote: hello");
    }

    #[tokio::test]
    async fn persisted_rpc_client_uses_send_persisted() {
        // This test verifies that the generated client for `#[rpc(persisted)]`
        // methods uses `send_persisted()` while `#[rpc]` uses `send()`.
        //
        // We construct the client manually and verify the method signatures
        // compile correctly — the actual network behavior is tested at the
        // integration level.
        //
        // The fact that `PersistedRpcEntityClient` compiles with both
        // `read_data` (non-persisted) and `write_data` (persisted) methods
        // is the test.
        let _client_type_check = |client: &PersistedRpcEntityClient| {
            let eid = EntityId::new("test");
            let val = "value".to_string();
            // Non-persisted: `send()`
            let _read = client.read_data(&eid);
            // Persisted: `send_persisted()` — different code path
            let _write = client.write_data(&eid, &val);
        };
    }

    // --- Persisted RPC entity (uses #[rpc(persisted)] for at-least-once delivery) ---

    #[entity(krate = "crate")]
    #[derive(Clone)]
    struct PersistedMethodEntity;

    #[entity_impl(krate = "crate")]
    impl PersistedMethodEntity {
        #[rpc(persisted)]
        async fn important_action(&self, data: String) -> Result<String, ClusterError> {
            Ok(format!("processed: {data}"))
        }

        #[rpc]
        async fn regular_action(&self) -> Result<String, ClusterError> {
            Ok("regular".to_string())
        }
    }

    #[tokio::test]
    async fn persisted_method_entity_dispatches() {
        let e = PersistedMethodEntity;
        let ctx = test_ctx("PersistedMethodEntity", "pm-1");
        let handler = e.spawn(ctx).await.unwrap();

        // Persisted RPC dispatches the same as non-persisted
        let payload = rmp_serde::to_vec(&"hello".to_string()).unwrap();
        let result = handler
            .handle_request("important_action", &payload, &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "processed: hello");

        let result = handler
            .handle_request("regular_action", &[], &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "regular");
    }

    // Test that the generated client uses send_persisted for #[rpc(persisted)] methods
    // (This is a compile-time check — the client struct should exist with the right methods)
    #[test]
    fn persisted_method_client_exists() {
        // Just verify the client struct exists and has the expected methods.
        // We can't fully test send_persisted without a Sharding mock, but we can
        // verify the types compile.
        fn _assert_client_has_methods(_c: &PersistedMethodEntityClient) {
            // important_action and regular_action should exist on the client
        }
    }

    // --- Mixed entity (#[rpc(persisted)] + #[rpc]) ---

    #[entity(krate = "crate")]
    #[derive(Clone)]
    struct MixedEntity;

    #[entity_impl(krate = "crate")]
    impl MixedEntity {
        #[rpc(persisted)]
        async fn persisted_action(&self, value: String) -> Result<String, ClusterError> {
            Ok(format!("persisted:{value}"))
        }

        #[rpc]
        async fn regular_action(&self, value: i32) -> Result<i32, ClusterError> {
            Ok(value * 2)
        }
    }

    // mixed_entity_client_calls_persisted_and_regular moved to tests/macro_integration.rs
    // persisted_method_replay_returns_cached_reply moved to tests/macro_integration.rs

    // --- Workflow with custom key extraction (migrated from entity #[workflow(key(...))] to standalone workflow) ---

    #[derive(Clone, serde::Serialize, serde::Deserialize)]
    struct UpdateRequest {
        id: String,
        value: i32,
    }

    #[workflow(krate = "crate")]
    #[derive(Clone)]
    struct UpdateWorkflow;

    #[workflow_impl(krate = "crate", key = |req: &UpdateRequest| req.id.clone())]
    impl UpdateWorkflow {
        async fn execute(&self, req: UpdateRequest) -> Result<String, ClusterError> {
            Ok(format!("{}:{}", req.id, req.value))
        }
    }

    struct MockSharding {
        snowflake: SnowflakeGenerator,
        shards_per_group: i32,
    }

    impl MockSharding {
        fn new() -> Self {
            Self {
                snowflake: SnowflakeGenerator::new(),
                shards_per_group: 300,
            }
        }
    }

    struct CapturingSharding {
        inner: MockSharding,
        captured: Arc<Mutex<Vec<EnvelopeRequest>>>,
    }

    #[async_trait]
    impl Sharding for MockSharding {
        fn get_shard_id(&self, _entity_type: &EntityType, entity_id: &EntityId) -> ShardId {
            let shard = shard_for_entity(entity_id.as_ref(), self.shards_per_group);
            ShardId::new("default", shard)
        }

        fn has_shard_id(&self, _shard_id: &ShardId) -> bool {
            true
        }

        fn snowflake(&self) -> &SnowflakeGenerator {
            &self.snowflake
        }

        fn is_shutdown(&self) -> bool {
            false
        }

        async fn register_entity(&self, _entity: Arc<dyn Entity>) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn register_singleton(
            &self,
            _name: &str,
            _shard_group: Option<&str>,
            _run: Arc<
                dyn Fn(SingletonContext) -> BoxFuture<'static, Result<(), ClusterError>>
                    + Send
                    + Sync,
            >,
        ) -> Result<(), ClusterError> {
            Ok(())
        }

        fn make_client(self: Arc<Self>, entity_type: EntityType) -> EntityClient {
            EntityClient::new(self, entity_type)
        }

        async fn send(&self, envelope: EnvelopeRequest) -> Result<ReplyReceiver, ClusterError> {
            let (tx, rx) = tokio::sync::mpsc::channel(1);
            let response = rmp_serde::to_vec(&"ok".to_string()).unwrap();
            let reply = Reply::WithExit(ReplyWithExit {
                request_id: envelope.request_id,
                id: self.snowflake.next_async().await?,
                exit: ExitResult::Success(response),
            });
            tx.send(reply)
                .await
                .map_err(|_| ClusterError::MalformedMessage {
                    reason: "reply channel closed".into(),
                    source: None,
                })?;
            Ok(rx)
        }

        async fn notify(&self, _envelope: EnvelopeRequest) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn ack_chunk(&self, _ack: AckChunk) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn interrupt(&self, _interrupt: Interrupt) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn poll_storage(&self) -> Result<(), ClusterError> {
            Ok(())
        }

        fn active_entity_count(&self) -> usize {
            0
        }

        async fn registration_events(
            &self,
        ) -> Pin<Box<dyn Stream<Item = ShardingRegistrationEvent> + Send>> {
            Box::pin(tokio_stream::empty())
        }

        async fn shutdown(&self) -> Result<(), ClusterError> {
            Ok(())
        }
    }

    #[async_trait]
    impl Sharding for CapturingSharding {
        fn get_shard_id(&self, entity_type: &EntityType, entity_id: &EntityId) -> ShardId {
            self.inner.get_shard_id(entity_type, entity_id)
        }

        fn has_shard_id(&self, shard_id: &ShardId) -> bool {
            self.inner.has_shard_id(shard_id)
        }

        fn snowflake(&self) -> &SnowflakeGenerator {
            self.inner.snowflake()
        }

        fn is_shutdown(&self) -> bool {
            false
        }

        async fn register_entity(&self, _entity: Arc<dyn Entity>) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn register_singleton(
            &self,
            _name: &str,
            _shard_group: Option<&str>,
            _run: Arc<
                dyn Fn(SingletonContext) -> BoxFuture<'static, Result<(), ClusterError>>
                    + Send
                    + Sync,
            >,
        ) -> Result<(), ClusterError> {
            Ok(())
        }

        fn make_client(self: Arc<Self>, entity_type: EntityType) -> EntityClient {
            EntityClient::new(self, entity_type)
        }

        async fn send(&self, envelope: EnvelopeRequest) -> Result<ReplyReceiver, ClusterError> {
            self.captured.lock().unwrap().push(envelope.clone());
            self.inner.send(envelope).await
        }

        async fn notify(&self, envelope: EnvelopeRequest) -> Result<(), ClusterError> {
            self.captured.lock().unwrap().push(envelope);
            Ok(())
        }

        async fn ack_chunk(&self, _ack: AckChunk) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn interrupt(&self, _interrupt: Interrupt) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn poll_storage(&self) -> Result<(), ClusterError> {
            Ok(())
        }

        fn active_entity_count(&self) -> usize {
            0
        }

        async fn registration_events(
            &self,
        ) -> Pin<Box<dyn Stream<Item = ShardingRegistrationEvent> + Send>> {
            Box::pin(tokio_stream::empty())
        }

        async fn shutdown(&self) -> Result<(), ClusterError> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn workflow_key_override_uses_custom_idempotency_key() {
        // Migrated from PersistedKeyEntity — tests that custom key extraction
        // produces the same entity_id for requests with the same key field.
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = UpdateWorkflowClient::new(Arc::clone(&sharding));

        let req1 = UpdateRequest {
            id: "same".to_string(),
            value: 1,
        };
        let req2 = UpdateRequest {
            id: "same".to_string(),
            value: 2,
        };

        // Dispatch works correctly
        let w = UpdateWorkflow;
        let ctx = test_ctx("Workflow/UpdateWorkflow", "pk-handler");
        let handler = w.spawn(ctx).await.unwrap();
        let payload = rmp_serde::to_vec(&req1).unwrap();
        let result = handler
            .handle_request("execute", &payload, &HashMap::new())
            .await
            .unwrap();
        let response: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(response, "same:1");

        // Client calls with same key field produce same entity_id
        let _: String = client.execute(&req1).await.unwrap();
        let _: String = client.execute(&req2).await.unwrap();

        let captured = captured.lock().unwrap();
        assert_eq!(captured.len(), 2);
        assert_eq!(
            captured[0].address.entity_id, captured[1].address.entity_id,
            "same key field should produce same entity_id"
        );
    }

    // --- Multiple request parameters ---

    #[entity(krate = "crate")]
    #[derive(Clone)]
    struct MultiParamEntity;

    #[entity_impl(krate = "crate")]
    impl MultiParamEntity {
        #[rpc]
        async fn add(&self, left: i32, right: i32) -> Result<i32, ClusterError> {
            Ok(left + right)
        }
    }

    #[tokio::test]
    async fn multi_param_entity_dispatches() {
        let entity = MultiParamEntity;
        let ctx = test_ctx("MultiParamEntity", "mp-1");
        let handler = entity.spawn(ctx).await.unwrap();

        let payload = rmp_serde::to_vec(&(2i32, 3i32)).unwrap();
        let result = handler
            .handle_request("add", &payload, &HashMap::new())
            .await
            .unwrap();
        let value: i32 = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, 5);
    }

    // --- Workflow with key extraction from a subset of fields (migrated from MultiParamPersisted entity) ---

    #[derive(Clone, serde::Serialize, serde::Deserialize)]
    struct SendEmailRequest {
        order_id: String,
        body: String,
    }

    #[workflow(krate = "crate")]
    #[derive(Clone)]
    struct SendEmailWorkflow;

    #[workflow_impl(krate = "crate", key = |req: &SendEmailRequest| req.order_id.clone())]
    impl SendEmailWorkflow {
        async fn execute(&self, req: SendEmailRequest) -> Result<String, ClusterError> {
            Ok(format!("{}:{}", req.order_id, req.body))
        }
    }

    #[tokio::test]
    async fn workflow_key_uses_subset_of_fields() {
        // Migrated from MultiParamPersisted — tests that key extraction uses
        // only a subset of request fields for idempotency.
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = SendEmailWorkflowClient::new(Arc::clone(&sharding));

        let order_id = "order-1".to_string();
        let body1 = "first".to_string();
        let body2 = "second".to_string();

        // Dispatch works correctly
        let w = SendEmailWorkflow;
        let ctx = test_ctx("Workflow/SendEmailWorkflow", "mp-handler");
        let handler = w.spawn(ctx).await.unwrap();
        let req1 = SendEmailRequest {
            order_id: order_id.clone(),
            body: body1.clone(),
        };
        let payload = rmp_serde::to_vec(&req1).unwrap();
        let result = handler
            .handle_request("execute", &payload, &HashMap::new())
            .await
            .unwrap();
        let response: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(response, format!("{order_id}:{body1}"));

        // Client calls with same order_id but different body produce same entity_id
        let req_a = SendEmailRequest {
            order_id: order_id.clone(),
            body: body1,
        };
        let req_b = SendEmailRequest {
            order_id: order_id.clone(),
            body: body2,
        };
        let _: String = client.execute(&req_a).await.unwrap();
        let _: String = client.execute(&req_b).await.unwrap();

        let captured = captured.lock().unwrap();
        assert_eq!(captured.len(), 2);
        assert_eq!(
            captured[0].address.entity_id, captured[1].address.entity_id,
            "same order_id should produce same entity_id regardless of body"
        );
    }

    // --- Private method entity ---

    #[entity(krate = "crate")]
    #[derive(Clone)]
    struct OrderEntity;

    #[entity_impl(krate = "crate")]
    impl OrderEntity {
        #[rpc]
        async fn get_order(&self, id: String) -> Result<String, ClusterError> {
            Ok(format!("order:{id}"))
        }

        #[rpc]
        #[private]
        #[allow(dead_code)]
        async fn internal_validate(&self, id: String) -> Result<String, ClusterError> {
            Ok(format!("validated:{id}"))
        }
    }

    #[tokio::test]
    async fn private_method_is_not_dispatchable() {
        let e = OrderEntity;
        let ctx = test_ctx("OrderEntity", "o-1");
        let handler = e.spawn(ctx).await.unwrap();

        let payload = rmp_serde::to_vec(&"abc".to_string()).unwrap();
        let err = handler
            .handle_request("internal_validate", &payload, &HashMap::new())
            .await
            .unwrap_err();
        assert!(matches!(err, ClusterError::MalformedMessage { .. }));
    }

    #[test]
    fn private_method_not_on_client() {
        // Verify the generated client has get_order but NOT internal_validate.
        // We use a compile-time assertion: if internal_validate existed on the client,
        // this function signature check would need updating.
        fn _assert_client_methods(c: &OrderEntityClient) {
            // get_order should exist — this is a type-level check
            let _ = &c.inner;
        }
        // Note: OrderEntityClient::internal_validate does NOT exist — calling it
        // would be a compile error. The test passing proves private methods are
        // omitted from the client.
    }

    // ==========================================================================
    // Standalone Workflow Macro Tests
    // ==========================================================================

    // ==========================================================================
    // #[workflow] / #[workflow_impl] Macro Tests
    // ==========================================================================

    use crate::workflow_impl;

    // --- Basic workflow using new macros ---

    #[derive(Clone, serde::Serialize, serde::Deserialize)]
    struct NewWfRequest {
        name: String,
    }

    #[workflow(krate = "crate")]
    #[derive(Clone)]
    struct NewSimpleWorkflow;

    #[workflow_impl(krate = "crate")]
    impl NewSimpleWorkflow {
        async fn execute(&self, request: NewWfRequest) -> Result<String, ClusterError> {
            Ok(format!("new-hello, {}", request.name))
        }
    }

    #[test]
    fn new_workflow_entity_type() {
        let w = NewSimpleWorkflow;
        assert_eq!(w.entity_type().0, "Workflow/NewSimpleWorkflow");
    }

    #[tokio::test]
    async fn new_workflow_dispatch() {
        let w = NewSimpleWorkflow;
        let ctx = test_ctx("Workflow/NewSimpleWorkflow", "exec-1");
        let handler = w.spawn(ctx).await.unwrap();

        let req = NewWfRequest {
            name: "world".to_string(),
        };
        let payload = rmp_serde::to_vec(&req).unwrap();
        let result = handler
            .handle_request("execute", &payload, &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "new-hello, world");
    }

    #[tokio::test]
    async fn new_workflow_unknown_tag() {
        let w = NewSimpleWorkflow;
        let ctx = test_ctx("Workflow/NewSimpleWorkflow", "exec-1");
        let handler = w.spawn(ctx).await.unwrap();

        let err = handler
            .handle_request("unknown", &[], &HashMap::new())
            .await
            .unwrap_err();
        assert!(matches!(err, ClusterError::MalformedMessage { .. }));
    }

    // --- Workflow with activities using new macros ---

    #[derive(Clone, serde::Serialize, serde::Deserialize)]
    struct NewOrderRequest {
        order_id: String,
        amount: i32,
    }

    // Workflow activity dispatch tests moved to tests/macro_integration.rs

    // --- Client generation with new macros ---

    #[test]
    fn new_workflow_client_exists() {
        fn _assert_client_methods(_c: &NewSimpleWorkflowClient) {
            // execute, start, with_key, with_key_raw should exist
        }
    }

    #[tokio::test]
    async fn new_workflow_start_returns_execution_id() {
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = NewSimpleWorkflow
            .register(Arc::clone(&sharding))
            .await
            .unwrap();

        let req = NewWfRequest {
            name: "fire-and-forget".to_string(),
        };
        let exec_id = client.start(&req).await.unwrap();

        // The execution ID should be a non-empty string (the derived entity ID)
        assert!(!exec_id.is_empty(), "execution ID should not be empty");

        // The message should have been sent via notify (not send)
        let captured = captured.lock().unwrap();
        assert_eq!(captured.len(), 1, "exactly one message should be captured");
        assert_eq!(captured[0].tag, "execute");
    }

    #[tokio::test]
    async fn new_workflow_with_key_hashes() {
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = NewSimpleWorkflowClient::new(Arc::clone(&sharding));

        let req = NewWfRequest {
            name: "keyed".to_string(),
        };

        // execute via with_key — should hash the key
        let _: String = client.with_key("my-key").execute(&req).await.unwrap();

        let captured_msgs = captured.lock().unwrap();
        assert_eq!(captured_msgs.len(), 1);

        // The entity_id should be the SHA-256 hash of "my-key", not "my-key" itself
        let entity_id = &captured_msgs[0].address.entity_id.0;
        assert_ne!(entity_id, "my-key", "key should be hashed");
        assert_eq!(
            entity_id,
            &crate::hash::sha256_hex("my-key".as_bytes()),
            "entity_id should match SHA-256 of key"
        );
    }

    #[tokio::test]
    async fn new_workflow_with_key_raw_no_hash() {
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = NewSimpleWorkflowClient::new(Arc::clone(&sharding));

        let req = NewWfRequest {
            name: "raw-keyed".to_string(),
        };

        // execute via with_key_raw — should use key as-is
        let _: String = client
            .with_key_raw("raw-id-42")
            .execute(&req)
            .await
            .unwrap();

        let captured_msgs = captured.lock().unwrap();
        assert_eq!(captured_msgs.len(), 1);
        assert_eq!(
            captured_msgs[0].address.entity_id.0, "raw-id-42",
            "raw key should be used directly as entity_id"
        );
    }

    #[tokio::test]
    async fn new_workflow_with_key_start() {
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = NewSimpleWorkflowClient::new(Arc::clone(&sharding));

        let req = NewWfRequest {
            name: "start-keyed".to_string(),
        };

        // start via with_key_raw — fire-and-forget with raw key
        let exec_id = client
            .with_key_raw("start-raw-1")
            .start(&req)
            .await
            .unwrap();
        assert_eq!(exec_id, "start-raw-1");

        let captured_msgs = captured.lock().unwrap();
        assert_eq!(captured_msgs.len(), 1);
        assert_eq!(captured_msgs[0].address.entity_id.0, "start-raw-1");
        assert_eq!(captured_msgs[0].tag, "execute");
    }

    #[tokio::test]
    async fn new_workflow_register() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = NewSimpleWorkflow
            .register(Arc::clone(&sharding))
            .await
            .unwrap();
        let req = NewWfRequest {
            name: "test".to_string(),
        };
        let _: String = client.execute(&req).await.unwrap();
    }

    #[test]
    fn new_workflow_implements_client_factory() {
        use crate::entity_client::WorkflowClientFactory;
        fn _assert_factory<T: WorkflowClientFactory>() {}
        _assert_factory::<NewSimpleWorkflow>();
    }

    // --- Workflow poll tests ---

    /// Mock sharding that stores replies and supports `replies_for` for poll testing.
    struct PollableSharding {
        inner: MockSharding,
        replies: Arc<Mutex<HashMap<Snowflake, Vec<Reply>>>>,
    }

    impl PollableSharding {
        fn new() -> Self {
            Self {
                inner: MockSharding::new(),
                replies: Arc::new(Mutex::new(HashMap::new())),
            }
        }
    }

    #[async_trait]
    impl Sharding for PollableSharding {
        fn get_shard_id(&self, et: &EntityType, eid: &EntityId) -> ShardId {
            self.inner.get_shard_id(et, eid)
        }
        fn has_shard_id(&self, sid: &ShardId) -> bool {
            self.inner.has_shard_id(sid)
        }
        fn snowflake(&self) -> &SnowflakeGenerator {
            self.inner.snowflake()
        }
        fn is_shutdown(&self) -> bool {
            false
        }
        async fn register_entity(&self, _: Arc<dyn Entity>) -> Result<(), ClusterError> {
            Ok(())
        }
        async fn register_singleton(
            &self,
            _: &str,
            _: Option<&str>,
            _: Arc<
                dyn Fn(SingletonContext) -> BoxFuture<'static, Result<(), ClusterError>>
                    + Send
                    + Sync,
            >,
        ) -> Result<(), ClusterError> {
            Ok(())
        }
        fn make_client(self: Arc<Self>, et: EntityType) -> EntityClient {
            EntityClient::new(self, et)
        }
        async fn send(&self, envelope: EnvelopeRequest) -> Result<ReplyReceiver, ClusterError> {
            // Build reply
            let response = rmp_serde::to_vec(&"ok".to_string()).unwrap();
            let reply = Reply::WithExit(ReplyWithExit {
                request_id: envelope.request_id,
                id: self.inner.snowflake.next_async().await?,
                exit: ExitResult::Success(response),
            });
            // Store reply for poll
            self.replies
                .lock()
                .unwrap()
                .entry(envelope.request_id)
                .or_default()
                .push(reply.clone());
            // Also send via channel for send_persisted
            let (tx, rx) = tokio::sync::mpsc::channel(1);
            tx.send(reply)
                .await
                .map_err(|_| ClusterError::MalformedMessage {
                    reason: "reply channel closed".into(),
                    source: None,
                })?;
            Ok(rx)
        }
        async fn notify(&self, _envelope: EnvelopeRequest) -> Result<(), ClusterError> {
            Ok(())
        }
        async fn ack_chunk(&self, _: AckChunk) -> Result<(), ClusterError> {
            Ok(())
        }
        async fn interrupt(&self, _: Interrupt) -> Result<(), ClusterError> {
            Ok(())
        }
        async fn poll_storage(&self) -> Result<(), ClusterError> {
            Ok(())
        }
        fn active_entity_count(&self) -> usize {
            0
        }
        async fn registration_events(
            &self,
        ) -> Pin<Box<dyn Stream<Item = ShardingRegistrationEvent> + Send>> {
            Box::pin(tokio_stream::empty())
        }
        async fn replies_for(&self, request_id: Snowflake) -> Result<Vec<Reply>, ClusterError> {
            Ok(self
                .replies
                .lock()
                .unwrap()
                .get(&request_id)
                .cloned()
                .unwrap_or_default())
        }
        async fn await_reply(&self, request_id: Snowflake) -> Result<ReplyReceiver, ClusterError> {
            let (tx, rx) = tokio::sync::mpsc::channel(16);
            let replies = self
                .replies
                .lock()
                .unwrap()
                .get(&request_id)
                .cloned()
                .unwrap_or_default();
            for reply in replies {
                let _ = tx.send(reply).await;
            }
            Ok(rx)
        }
        async fn shutdown(&self) -> Result<(), ClusterError> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn new_workflow_poll_returns_none_when_not_started() {
        let sharding: Arc<dyn Sharding> = Arc::new(PollableSharding::new());
        let client = NewSimpleWorkflowClient::new(Arc::clone(&sharding));

        // Poll for an execution that was never started — should return None
        let result: Option<String> = client.poll("nonexistent-id").await.unwrap();
        assert!(
            result.is_none(),
            "poll should return None for unknown execution"
        );
    }

    #[tokio::test]
    async fn new_workflow_poll_returns_result_after_execute() {
        let sharding: Arc<dyn Sharding> = Arc::new(PollableSharding::new());
        let client = NewSimpleWorkflowClient::new(Arc::clone(&sharding));

        let req = NewWfRequest {
            name: "poll-test".to_string(),
        };

        // Execute the workflow (which stores the reply)
        let result: String = client.execute(&req).await.unwrap();
        assert_eq!(result, "ok");

        // Now poll for the same execution — derive entity_id the same way
        let key_bytes = rmp_serde::to_vec(&req).unwrap();
        let entity_id = crate::hash::sha256_hex(&key_bytes);
        let poll_result: Option<String> = client.poll(&entity_id).await.unwrap();
        assert_eq!(poll_result, Some("ok".to_string()));
    }

    #[tokio::test]
    async fn new_workflow_poll_with_key_returns_result() {
        let sharding: Arc<dyn Sharding> = Arc::new(PollableSharding::new());
        let client = NewSimpleWorkflowClient::new(Arc::clone(&sharding));

        let req = NewWfRequest {
            name: "poll-keyed".to_string(),
        };

        // Execute with a raw key
        let keyed = client.with_key_raw("poll-exec-1");
        let _: String = keyed.execute(&req).await.unwrap();

        // Poll on the ClientWithKey view
        let keyed_again = client.with_key_raw("poll-exec-1");
        let poll_result: Option<String> = keyed_again.poll().await.unwrap();
        assert_eq!(poll_result, Some("ok".to_string()));
    }

    #[test]
    fn new_workflow_poll_method_exists() {
        // Compile-time check that poll exists on both client types
        fn _assert_poll(_c: &NewSimpleWorkflowClient) {
            // client.poll(execution_id) should exist
        }
        fn _assert_poll_with_key(_c: &NewSimpleWorkflowClientWithKey<'_>) {
            // client_with_key.poll() should exist
        }
    }

    // --- Workflow join tests ---

    #[tokio::test]
    async fn new_workflow_join_returns_result_after_execute() {
        let sharding: Arc<dyn Sharding> = Arc::new(PollableSharding::new());
        let client = NewSimpleWorkflowClient::new(Arc::clone(&sharding));

        let req = NewWfRequest {
            name: "join-test".to_string(),
        };

        // Execute the workflow (which stores the reply)
        let result: String = client.execute(&req).await.unwrap();
        assert_eq!(result, "ok");

        // Now join for the same execution — derive entity_id the same way
        let key_bytes = rmp_serde::to_vec(&req).unwrap();
        let entity_id = crate::hash::sha256_hex(&key_bytes);
        let join_result: String = client.join(&entity_id).await.unwrap();
        assert_eq!(join_result, "ok");
    }

    #[tokio::test]
    async fn new_workflow_join_with_key_returns_result() {
        let sharding: Arc<dyn Sharding> = Arc::new(PollableSharding::new());
        let client = NewSimpleWorkflowClient::new(Arc::clone(&sharding));

        let req = NewWfRequest {
            name: "join-keyed".to_string(),
        };

        // Execute with a raw key
        let keyed = client.with_key_raw("join-exec-1");
        let _: String = keyed.execute(&req).await.unwrap();

        // Join on the ClientWithKey view
        let keyed_again = client.with_key_raw("join-exec-1");
        let join_result: String = keyed_again.join().await.unwrap();
        assert_eq!(join_result, "ok");
    }

    #[test]
    fn new_workflow_join_method_exists() {
        // Compile-time check that join exists on both client types
        fn _assert_join(_c: &NewSimpleWorkflowClient) {
            // client.join(execution_id) should exist
        }
        fn _assert_join_with_key(_c: &NewSimpleWorkflowClientWithKey<'_>) {
            // client_with_key.join() should exist
        }
    }

    // --- Workflow with helpers using new macros ---

    #[workflow(krate = "crate")]
    #[derive(Clone)]
    struct NewHelperWorkflow;

    #[workflow_impl(krate = "crate")]
    impl NewHelperWorkflow {
        async fn execute(&self, request: NewWfRequest) -> Result<String, ClusterError> {
            let upper = self.to_upper(&request.name);
            Ok(upper)
        }

        fn to_upper(&self, s: &str) -> String {
            s.to_uppercase()
        }
    }

    #[tokio::test]
    async fn new_workflow_with_helpers() {
        let w = NewHelperWorkflow;
        let ctx = test_ctx("Workflow/NewHelperWorkflow", "exec-1");
        let handler = w.spawn(ctx).await.unwrap();

        let req = NewWfRequest {
            name: "hello".to_string(),
        };
        let payload = rmp_serde::to_vec(&req).unwrap();
        let result = handler
            .handle_request("execute", &payload, &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "HELLO");
    }

    // ==========================================================================
    // #[activity_group] / #[activity_group_impl] Macro Tests
    // ==========================================================================

    use crate::activity_group_impl;

    // --- Basic activity group ---

    #[activity_group(krate = "crate")]
    #[derive(Clone)]
    pub struct TestPayments {
        pub rate: f64,
    }

    #[activity_group_impl(krate = "crate")]
    impl TestPayments {
        #[activity]
        async fn charge(&self, amount: i32) -> Result<String, ClusterError> {
            let total = (amount as f64 * self.rate) as i32;
            Ok(format!("charged:{total}"))
        }

        #[activity]
        async fn refund(&self, tx_id: String) -> Result<String, ClusterError> {
            Ok(format!("refunded:{tx_id}"))
        }

        /// Helper (not an activity)
        fn format_amount(&self, amount: i32) -> String {
            format!("${amount}")
        }
    }

    // --- Activity group composed into a workflow ---

    #[workflow(krate = "crate")]
    #[derive(Clone)]
    struct PaymentWorkflow;

    #[workflow_impl(krate = "crate", activity_groups(TestPayments))]
    impl PaymentWorkflow {
        async fn execute(&self, request: NewOrderRequest) -> Result<String, ClusterError> {
            let charge_result = self.charge(request.amount).await?;
            let refund_result = self.refund(request.order_id.clone()).await?;
            Ok(format!("{charge_result}|{refund_result}"))
        }
    }

    // activity_group_workflow_dispatch moved to tests/macro_integration.rs

    #[tokio::test]
    async fn activity_group_workflow_register() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = PaymentWorkflow
            .register(Arc::clone(&sharding), TestPayments { rate: 2.0 })
            .await
            .unwrap();

        let req = NewOrderRequest {
            order_id: "order-2".to_string(),
            amount: 50,
        };
        let _: String = client.execute(&req).await.unwrap();
    }

    #[test]
    fn activity_group_workflow_entity_type() {
        // When activity_groups are present, Entity is on the WithGroups wrapper
        let bundle = __PaymentWorkflowWithGroups {
            __workflow: PaymentWorkflow,
            __group_test_payments: TestPayments { rate: 1.0 },
        };
        assert_eq!(bundle.entity_type().0, "Workflow/PaymentWorkflow");
    }

    // --- Multiple activity groups ---

    #[activity_group(krate = "crate")]
    #[derive(Clone)]
    pub struct TestInventory;

    #[activity_group_impl(krate = "crate")]
    impl TestInventory {
        #[activity]
        async fn reserve(&self, item_count: i32) -> Result<String, ClusterError> {
            Ok(format!("reserved:{item_count}"))
        }
    }

    #[workflow(krate = "crate")]
    #[derive(Clone)]
    struct MultiGroupWorkflow;

    #[workflow_impl(krate = "crate", activity_groups(TestPayments, TestInventory))]
    impl MultiGroupWorkflow {
        async fn execute(&self, request: NewOrderRequest) -> Result<String, ClusterError> {
            let reserved = self.reserve(request.amount).await?;
            let charged = self.charge(request.amount).await?;
            Ok(format!("{reserved}|{charged}"))
        }
    }

    // multi_activity_group_workflow_dispatch moved to tests/macro_integration.rs

    #[tokio::test]
    async fn multi_activity_group_workflow_register() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = MultiGroupWorkflow
            .register(
                Arc::clone(&sharding),
                TestPayments { rate: 1.0 },
                TestInventory,
            )
            .await
            .unwrap();

        let req = NewOrderRequest {
            order_id: "order-4".to_string(),
            amount: 20,
        };
        let _: String = client.execute(&req).await.unwrap();
    }

    // MixedActivitiesWorkflow + test moved to tests/macro_integration.rs

    // ==========================================================================
    // Activity Retry Support Tests (#[activity(retries = N, backoff = "...")])
    // ==========================================================================

    use std::sync::atomic::AtomicU32;
    use std::time::Duration;

    // InstantWorkflowEngine + test_ctx_with_instant_engine moved to tests/macro_integration.rs

    // --- Workflow with retries (no backoff specified = exponential default) ---

    #[workflow(krate = "crate")]
    #[derive(Clone)]
    struct RetryWorkflow {
        call_count: Arc<AtomicU32>,
    }

    #[workflow_impl(krate = "crate")]
    impl RetryWorkflow {
        async fn execute(&self, request: NewWfRequest) -> Result<String, ClusterError> {
            let result = self.flaky_activity(request.name.clone()).await?;
            Ok(result)
        }

        #[activity(retries = 3)]
        async fn flaky_activity(&self, name: String) -> Result<String, ClusterError> {
            let count = self.call_count.fetch_add(1, Ordering::SeqCst);
            if count < 2 {
                Err(ClusterError::PersistenceError {
                    reason: format!("flaky failure #{count}"),
                    source: None,
                })
            } else {
                Ok(format!("success:{name}:attempt-{count}"))
            }
        }
    }

    #[test]
    fn retry_workflow_entity_type() {
        let w = RetryWorkflow {
            call_count: Arc::new(AtomicU32::new(0)),
        };
        assert_eq!(w.entity_type().0, "Workflow/RetryWorkflow");
    }

    // retry_workflow_activity_succeeds_after_retries moved to tests/macro_integration.rs

    // --- Workflow with constant backoff ---

    // ConstantBackoffWorkflow + test moved to tests/macro_integration.rs

    // --- Workflow where all retries fail ---

    // AlwaysFailWorkflow + test moved to tests/macro_integration.rs

    // --- Activity with retries = 0 (same as no retries) ---

    // NoRetryWorkflow + test moved to tests/macro_integration.rs

    // --- Activity group with retries ---

    // RetryPayments + GroupRetryWorkflow + test moved to tests/macro_integration.rs

    // --- Test compute_retry_backoff utility ---

    #[test]
    fn test_compute_retry_backoff_exponential() {
        use crate::durable::compute_retry_backoff;

        assert_eq!(
            compute_retry_backoff(0, "exponential", 1),
            Duration::from_secs(1)
        );
        assert_eq!(
            compute_retry_backoff(1, "exponential", 1),
            Duration::from_secs(2)
        );
        assert_eq!(
            compute_retry_backoff(2, "exponential", 1),
            Duration::from_secs(4)
        );
        assert_eq!(
            compute_retry_backoff(3, "exponential", 1),
            Duration::from_secs(8)
        );
        assert_eq!(
            compute_retry_backoff(5, "exponential", 1),
            Duration::from_secs(32)
        );
        // Capped at 60 seconds
        assert_eq!(
            compute_retry_backoff(6, "exponential", 1),
            Duration::from_secs(60)
        );
        assert_eq!(
            compute_retry_backoff(10, "exponential", 1),
            Duration::from_secs(60)
        );
    }

    #[test]
    fn test_compute_retry_backoff_constant() {
        use crate::durable::compute_retry_backoff;

        assert_eq!(
            compute_retry_backoff(0, "constant", 1),
            Duration::from_secs(1)
        );
        assert_eq!(
            compute_retry_backoff(1, "constant", 1),
            Duration::from_secs(1)
        );
        assert_eq!(
            compute_retry_backoff(5, "constant", 1),
            Duration::from_secs(1)
        );
        assert_eq!(
            compute_retry_backoff(0, "constant", 5),
            Duration::from_secs(5)
        );
    }

    // =============================================================================
    // Pure-RPC Entity tests (stateless entities, new simplified codegen)
    // =============================================================================

    /// A pure-RPC entity: no #[state], no #[workflow], no #[activity].
    /// Uses the simplified handler codegen without write locks or view structs.
    #[entity(krate = "crate")]
    #[derive(Clone)]
    struct PureRpcEntity {
        prefix: String,
    }

    #[entity_impl(krate = "crate")]
    impl PureRpcEntity {
        #[rpc]
        async fn greet(&self, name: String) -> Result<String, ClusterError> {
            Ok(format!("{}: hello, {}", self.prefix, name))
        }

        #[rpc(persisted)]
        async fn save_data(&self, data: String) -> Result<String, ClusterError> {
            Ok(format!("{}: saved {}", self.prefix, data))
        }

        #[rpc]
        async fn add(&self, a: i32, b: i32) -> Result<i32, ClusterError> {
            Ok(a + b)
        }
    }

    #[test]
    fn pure_rpc_entity_type_name() {
        let e = PureRpcEntity {
            prefix: "test".into(),
        };
        assert_eq!(e.entity_type().0, "PureRpcEntity");
    }

    #[tokio::test]
    async fn pure_rpc_entity_dispatches() {
        let e = PureRpcEntity {
            prefix: "svc".into(),
        };
        let ctx = test_ctx("PureRpcEntity", "pure-1");
        let handler = e.spawn(ctx).await.unwrap();

        // Non-persisted RPC
        let payload = rmp_serde::to_vec(&"world".to_string()).unwrap();
        let result = handler
            .handle_request("greet", &payload, &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "svc: hello, world");

        // Persisted RPC (dispatch is the same)
        let payload = rmp_serde::to_vec(&"item".to_string()).unwrap();
        let result = handler
            .handle_request("save_data", &payload, &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "svc: saved item");
    }

    #[tokio::test]
    async fn pure_rpc_entity_multi_param() {
        let e = PureRpcEntity {
            prefix: "test".into(),
        };
        let ctx = test_ctx("PureRpcEntity", "pure-2");
        let handler = e.spawn(ctx).await.unwrap();

        let payload = rmp_serde::to_vec(&(3i32, 4i32)).unwrap();
        let result = handler
            .handle_request("add", &payload, &HashMap::new())
            .await
            .unwrap();
        let value: i32 = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, 7);
    }

    #[tokio::test]
    async fn pure_rpc_entity_unknown_tag_errors() {
        let e = PureRpcEntity {
            prefix: "test".into(),
        };
        let ctx = test_ctx("PureRpcEntity", "pure-3");
        let handler = e.spawn(ctx).await.unwrap();

        let result = handler
            .handle_request("nonexistent", &[], &HashMap::new())
            .await;
        assert!(result.is_err());
        match result.unwrap_err() {
            ClusterError::MalformedMessage { reason, .. } => {
                assert!(reason.contains("unknown RPC tag"));
            }
            other => panic!("expected MalformedMessage, got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn pure_rpc_entity_register_returns_client() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = PureRpcEntity::register(
            PureRpcEntity {
                prefix: "test".into(),
            },
            Arc::clone(&sharding),
        )
        .await
        .unwrap();

        let entity_id = EntityId::new("pure-4");
        // Client should have entity's own methods
        let response: String = client
            .greet(&entity_id, &"alice".to_string())
            .await
            .unwrap();
        assert_eq!(response, "ok");
    }

    #[tokio::test]
    async fn pure_rpc_entity_client_persisted_method_exists() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = PureRpcEntity::register(
            PureRpcEntity {
                prefix: "test".into(),
            },
            Arc::clone(&sharding),
        )
        .await
        .unwrap();

        let entity_id = EntityId::new("pure-5");
        // save_data uses persisted delivery
        let response: String = client
            .save_data(&entity_id, &"payload".to_string())
            .await
            .unwrap();
        assert_eq!(response, "ok");
    }

    // =============================================================================
    // RPC Group tests
    // =============================================================================

    #[rpc_group(krate = "crate")]
    #[derive(Clone)]
    pub struct HealthCheckGroup;

    #[rpc_group_impl(krate = "crate")]
    impl HealthCheckGroup {
        #[rpc]
        async fn health(&self) -> Result<String, ClusterError> {
            Ok("ok".to_string())
        }
    }

    #[entity(krate = "crate")]
    #[derive(Clone)]
    struct RpcGroupEntity;

    #[entity_impl(krate = "crate", rpc_groups(HealthCheckGroup))]
    impl RpcGroupEntity {
        #[rpc]
        async fn ping(&self) -> Result<String, ClusterError> {
            Ok("pong".to_string())
        }
    }

    #[tokio::test]
    async fn rpc_group_dispatches_via_handler() {
        let entity_with_groups = RpcGroupEntityWithRpcGroups {
            entity: RpcGroupEntity,
            __rpc_group_health_check_group: HealthCheckGroup,
        };
        let ctx = test_ctx("RpcGroupEntity", "rg-1");
        let handler = entity_with_groups.spawn(ctx).await.unwrap();

        // Entity's own RPC
        let result = handler
            .handle_request("ping", &[], &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "pong");

        // RPC from group
        let result = handler
            .handle_request("health", &[], &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "ok");
    }

    #[tokio::test]
    async fn rpc_group_unknown_tag_errors() {
        let entity_with_groups = RpcGroupEntityWithRpcGroups {
            entity: RpcGroupEntity,
            __rpc_group_health_check_group: HealthCheckGroup,
        };
        let ctx = test_ctx("RpcGroupEntity", "rg-2");
        let handler = entity_with_groups.spawn(ctx).await.unwrap();

        let result = handler
            .handle_request("nonexistent", &[], &HashMap::new())
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn rpc_group_register_returns_client() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client =
            RpcGroupEntity::register(RpcGroupEntity, Arc::clone(&sharding), HealthCheckGroup)
                .await
                .unwrap();

        let entity_id = EntityId::new("rg-3");
        // Client should have entity's own methods
        let response: String = client.ping(&entity_id).await.unwrap();
        assert_eq!(response, "ok");
    }

    #[tokio::test]
    async fn rpc_group_client_extension_methods_exist() {
        // Verify that the generated ClientExt trait adds group methods to the entity client
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client =
            RpcGroupEntity::register(RpcGroupEntity, Arc::clone(&sharding), HealthCheckGroup)
                .await
                .unwrap();

        let entity_id = EntityId::new("rg-4");
        // Group method should be callable via client extension
        let response: String = client.health(&entity_id).await.unwrap();
        assert_eq!(response, "ok");
    }

    // --- RPC group with fields ---

    #[rpc_group(krate = "crate")]
    #[derive(Clone)]
    pub struct MetricsGroup {
        pub prefix: String,
    }

    #[rpc_group_impl(krate = "crate")]
    impl MetricsGroup {
        #[rpc]
        async fn get_metrics(&self) -> Result<String, ClusterError> {
            Ok(format!("{}/metrics", self.prefix))
        }
    }

    #[entity(krate = "crate")]
    #[derive(Clone)]
    struct MultiGroupEntity;

    #[entity_impl(krate = "crate", rpc_groups(HealthCheckGroup, MetricsGroup))]
    impl MultiGroupEntity {
        #[rpc]
        async fn status(&self) -> Result<String, ClusterError> {
            Ok("running".to_string())
        }
    }

    #[tokio::test]
    async fn multi_rpc_group_dispatch() {
        let entity_with_groups = MultiGroupEntityWithRpcGroups {
            entity: MultiGroupEntity,
            __rpc_group_health_check_group: HealthCheckGroup,
            __rpc_group_metrics_group: MetricsGroup {
                prefix: "app".to_string(),
            },
        };
        let ctx = test_ctx("MultiGroupEntity", "mg-1");
        let handler = entity_with_groups.spawn(ctx).await.unwrap();

        // Entity's own RPC
        let result = handler
            .handle_request("status", &[], &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "running");

        // First group RPC
        let result = handler
            .handle_request("health", &[], &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "ok");

        // Second group RPC
        let result = handler
            .handle_request("get_metrics", &[], &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "app/metrics");
    }

    #[tokio::test]
    async fn multi_rpc_group_register() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = MultiGroupEntity::register(
            MultiGroupEntity,
            Arc::clone(&sharding),
            HealthCheckGroup,
            MetricsGroup {
                prefix: "test".to_string(),
            },
        )
        .await
        .unwrap();

        let entity_id = EntityId::new("mg-2");
        let response: String = client.status(&entity_id).await.unwrap();
        assert_eq!(response, "ok");
    }

    // --- RPC group with persisted RPC ---

    #[rpc_group(krate = "crate")]
    #[derive(Clone)]
    pub struct PersistedRpcGroup;

    #[rpc_group_impl(krate = "crate")]
    impl PersistedRpcGroup {
        #[rpc(persisted)]
        async fn save_data(&self, data: String) -> Result<String, ClusterError> {
            Ok(format!("saved:{data}"))
        }

        #[rpc]
        async fn read_data(&self) -> Result<String, ClusterError> {
            Ok("data".to_string())
        }
    }

    #[entity(krate = "crate")]
    #[derive(Clone)]
    struct PersistedGroupEntity;

    #[entity_impl(krate = "crate", rpc_groups(PersistedRpcGroup))]
    impl PersistedGroupEntity {
        #[rpc]
        async fn ping(&self) -> Result<String, ClusterError> {
            Ok("pong".to_string())
        }
    }

    #[tokio::test]
    async fn persisted_rpc_group_dispatches() {
        let entity_with_groups = PersistedGroupEntityWithRpcGroups {
            entity: PersistedGroupEntity,
            __rpc_group_persisted_rpc_group: PersistedRpcGroup,
        };
        let ctx = test_ctx("PersistedGroupEntity", "prg-1");
        let handler = entity_with_groups.spawn(ctx).await.unwrap();

        // Non-persisted group RPC
        let result = handler
            .handle_request("read_data", &[], &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "data");

        // Persisted group RPC
        let payload = rmp_serde::to_vec(&"test".to_string()).unwrap();
        let result = handler
            .handle_request("save_data", &payload, &HashMap::new())
            .await
            .unwrap();
        let value: String = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, "saved:test");
    }

    // --- RPC group with parameters ---

    #[rpc_group(krate = "crate")]
    #[derive(Clone)]
    pub struct MathGroup;

    #[rpc_group_impl(krate = "crate")]
    impl MathGroup {
        #[rpc]
        async fn add(&self, a: i32, b: i32) -> Result<i32, ClusterError> {
            Ok(a + b)
        }

        #[rpc]
        async fn multiply(&self, a: i32, b: i32) -> Result<i32, ClusterError> {
            Ok(a * b)
        }
    }

    #[entity(krate = "crate")]
    #[derive(Clone)]
    struct MathEntity;

    #[entity_impl(krate = "crate", rpc_groups(MathGroup))]
    impl MathEntity {
        #[rpc]
        async fn negate(&self, x: i32) -> Result<i32, ClusterError> {
            Ok(-x)
        }
    }

    #[tokio::test]
    async fn rpc_group_with_params_dispatch() {
        let entity_with_groups = MathEntityWithRpcGroups {
            entity: MathEntity,
            __rpc_group_math_group: MathGroup,
        };
        let ctx = test_ctx("MathEntity", "math-1");
        let handler = entity_with_groups.spawn(ctx).await.unwrap();

        // Entity's own RPC with param
        let payload = rmp_serde::to_vec(&5i32).unwrap();
        let result = handler
            .handle_request("negate", &payload, &HashMap::new())
            .await
            .unwrap();
        let value: i32 = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, -5);

        // Group RPC with multiple params
        let payload = rmp_serde::to_vec(&(3i32, 4i32)).unwrap();
        let result = handler
            .handle_request("add", &payload, &HashMap::new())
            .await
            .unwrap();
        let value: i32 = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, 7);

        let result = handler
            .handle_request("multiply", &payload, &HashMap::new())
            .await
            .unwrap();
        let value: i32 = rmp_serde::from_slice(&result).unwrap();
        assert_eq!(value, 12);
    }

    #[tokio::test]
    async fn rpc_group_entity_type_is_struct_name() {
        let entity_with_groups = RpcGroupEntityWithRpcGroups {
            entity: RpcGroupEntity,
            __rpc_group_health_check_group: HealthCheckGroup,
        };
        // Entity type should be the original struct name
        assert_eq!(entity_with_groups.entity_type().0, "RpcGroupEntity");
    }

    // =============================================================================
    // Workflow key extraction tests (#[workflow_impl(key = |req| ..., hash = ...)])
    // =============================================================================

    // --- Workflow with custom key extraction (hashed, default) ---

    #[derive(Clone, serde::Serialize, serde::Deserialize)]
    struct KeyedOrderRequest {
        order_id: String,
        amount: i32,
    }

    #[workflow(krate = "crate")]
    #[derive(Clone)]
    struct KeyedWorkflow;

    #[workflow_impl(krate = "crate", key = |req: &KeyedOrderRequest| req.order_id.clone())]
    impl KeyedWorkflow {
        async fn execute(&self, request: KeyedOrderRequest) -> Result<String, ClusterError> {
            Ok(format!("{}:{}", request.order_id, request.amount))
        }
    }

    #[tokio::test]
    async fn workflow_key_extracts_custom_field_hashed() {
        // Verify that two requests with the same order_id but different amount
        // produce the same entity_id (because key only uses order_id)
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = KeyedWorkflowClient::new(Arc::clone(&sharding));

        let req1 = KeyedOrderRequest {
            order_id: "order-42".to_string(),
            amount: 100,
        };
        let req2 = KeyedOrderRequest {
            order_id: "order-42".to_string(),
            amount: 200,
        };

        let _: String = client.execute(&req1).await.unwrap();
        let _: String = client.execute(&req2).await.unwrap();

        let captured = captured.lock().unwrap();
        assert_eq!(captured.len(), 2);
        // Both should target the same entity_id since key only uses order_id
        assert_eq!(
            captured[0].address.entity_id, captured[1].address.entity_id,
            "same order_id should produce same entity_id"
        );
        // The entity_id should be the SHA-256 hash of the serialized order_id
        let expected_id =
            crate::hash::sha256_hex(&rmp_serde::to_vec(&"order-42".to_string()).unwrap());
        assert_eq!(
            captured[0].address.entity_id.0, expected_id,
            "entity_id should be SHA-256 of serialized key value"
        );
    }

    #[tokio::test]
    async fn workflow_key_different_keys_different_entity_ids() {
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = KeyedWorkflowClient::new(Arc::clone(&sharding));

        let req1 = KeyedOrderRequest {
            order_id: "order-1".to_string(),
            amount: 100,
        };
        let req2 = KeyedOrderRequest {
            order_id: "order-2".to_string(),
            amount: 100,
        };

        let _: String = client.execute(&req1).await.unwrap();
        let _: String = client.execute(&req2).await.unwrap();

        let captured = captured.lock().unwrap();
        assert_eq!(captured.len(), 2);
        assert_ne!(
            captured[0].address.entity_id, captured[1].address.entity_id,
            "different order_ids should produce different entity_ids"
        );
    }

    // --- Workflow with custom key, hash = false ---

    #[workflow(krate = "crate")]
    #[derive(Clone)]
    struct RawKeyWorkflow;

    #[workflow_impl(krate = "crate", key = |req: &KeyedOrderRequest| req.order_id.clone(), hash = false)]
    impl RawKeyWorkflow {
        async fn execute(&self, request: KeyedOrderRequest) -> Result<String, ClusterError> {
            Ok(format!("raw:{}:{}", request.order_id, request.amount))
        }
    }

    #[tokio::test]
    async fn workflow_key_raw_uses_value_directly() {
        // With hash = false, the key closure result is used directly as entity_id
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = RawKeyWorkflowClient::new(Arc::clone(&sharding));

        let req = KeyedOrderRequest {
            order_id: "my-raw-key-123".to_string(),
            amount: 50,
        };

        let _: String = client.execute(&req).await.unwrap();

        let captured = captured.lock().unwrap();
        assert_eq!(captured.len(), 1);
        // Entity ID should be the raw order_id, no hashing
        assert_eq!(
            captured[0].address.entity_id.0, "my-raw-key-123",
            "raw key should be used directly as entity_id"
        );
    }

    #[tokio::test]
    async fn workflow_key_raw_same_key_same_entity_id() {
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = RawKeyWorkflowClient::new(Arc::clone(&sharding));

        let req1 = KeyedOrderRequest {
            order_id: "same-id".to_string(),
            amount: 1,
        };
        let req2 = KeyedOrderRequest {
            order_id: "same-id".to_string(),
            amount: 9999,
        };

        let _: String = client.execute(&req1).await.unwrap();
        let _: String = client.execute(&req2).await.unwrap();

        let captured = captured.lock().unwrap();
        assert_eq!(captured.len(), 2);
        assert_eq!(
            captured[0].address.entity_id, captured[1].address.entity_id,
            "same order_id with raw key should produce same entity_id"
        );
        assert_eq!(captured[0].address.entity_id.0, "same-id");
    }

    // --- Workflow key with start() ---

    #[tokio::test]
    async fn workflow_key_raw_start_returns_raw_id() {
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = RawKeyWorkflowClient::new(Arc::clone(&sharding));

        let req = KeyedOrderRequest {
            order_id: "start-raw-key".to_string(),
            amount: 0,
        };

        let exec_id = client.start(&req).await.unwrap();
        // start() returns the entity_id which should be the raw key
        assert_eq!(exec_id, "start-raw-key");
    }

    #[tokio::test]
    async fn workflow_key_hashed_start_returns_hashed_id() {
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = KeyedWorkflowClient::new(Arc::clone(&sharding));

        let req = KeyedOrderRequest {
            order_id: "order-hashed".to_string(),
            amount: 0,
        };

        let exec_id = client.start(&req).await.unwrap();
        // start() returns the entity_id which should be hashed
        let expected_id =
            crate::hash::sha256_hex(&rmp_serde::to_vec(&"order-hashed".to_string()).unwrap());
        assert_eq!(exec_id, expected_id);
    }

    // --- Verify with_key still overrides custom key extraction ---

    #[tokio::test]
    async fn workflow_with_key_overrides_custom_key() {
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = RawKeyWorkflowClient::new(Arc::clone(&sharding));

        let req = KeyedOrderRequest {
            order_id: "should-be-ignored".to_string(),
            amount: 0,
        };

        // with_key_raw overrides the key extraction from the closure
        let _: String = client
            .with_key_raw("override-key")
            .execute(&req)
            .await
            .unwrap();

        let captured = captured.lock().unwrap();
        assert_eq!(captured.len(), 1);
        assert_eq!(
            captured[0].address.entity_id.0, "override-key",
            "with_key_raw should override the custom key extraction"
        );
    }
}