duroxide 0.1.32

Durable code execution framework for Rust
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Runtime-level queue cancellation and event-version preservation checks.

use super::{Event, EventKind, ExecutionMetadata, ProviderFactory, start_item};
use crate::providers::WorkItem;
use crate::runtime::registry::ActivityRegistry;
use crate::runtime::{Runtime, RuntimeOptions};
use crate::{Client, Either3, OrchestrationContext, OrchestrationRegistry, OrchestrationStatus};
use std::time::Duration;

/// Duplicate client starts cannot switch a running execution to the latest
/// handler, another handler name, or a replacement input.
pub async fn test_duplicate_start_preserves_pinned_handler<F: ProviderFactory>(factory: &F) {
    for duplicate_name in ["Original", "WrongHandler"] {
        let provider = factory.create_provider().await;
        let instance = format!("provider-pinned-handler-{duplicate_name}");
        provider
            .enqueue_for_orchestrator(start_item(&instance), None)
            .await
            .expect("seed start");
        let (_, lock, _) = provider
            .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
            .await
            .expect("seed fetch")
            .expect("visible seed");
        provider
            .ack_orchestration_item(
                &lock,
                1,
                vec![
                    Event::with_event_id(
                        1,
                        &instance,
                        1,
                        None,
                        EventKind::OrchestrationStarted {
                            name: "Original".into(),
                            version: "1.0.0".into(),
                            input: "original-input".into(),
                            parent_instance: None,
                            parent_id: None,
                            parent_execution_id: None,
                            carry_forward_events: None,
                            initial_custom_status: None,
                        },
                    ),
                    Event::with_event_id(
                        2,
                        &instance,
                        1,
                        None,
                        EventKind::ActivityScheduled {
                            name: "tick".into(),
                            input: "v1".into(),
                            session_id: None,
                            tag: None,
                        },
                    ),
                ],
                vec![],
                vec![
                    WorkItem::StartOrchestration {
                        instance: instance.clone(),
                        orchestration: duplicate_name.into(),
                        input: "wrong-input".into(),
                        version: None,
                        execution_id: 1,
                        parent_instance: None,
                        parent_id: None,
                        parent_execution_id: None,
                    },
                    WorkItem::ActivityCompleted {
                        instance: instance.clone(),
                        execution_id: 1,
                        id: 2,
                        result: "ok".into(),
                    },
                ],
                ExecutionMetadata {
                    status: Some("Running".into()),
                    orchestration_name: Some("Original".into()),
                    orchestration_version: Some("1.0.0".into()),
                    ..Default::default()
                },
                vec![],
            )
            .await
            .expect("seed running pinned history and duplicate batch");
        let registry = OrchestrationRegistry::builder()
            .register_versioned(
                "Original",
                "1.0.0",
                |ctx: OrchestrationContext, input: String| async move {
                    ctx.schedule_activity("tick", "v1").await?;
                    Ok(format!("v1:{input}"))
                },
            )
            .register_versioned("Original", "2.0.0", |ctx: OrchestrationContext, _: String| async move {
                ctx.schedule_activity("tick", "v2").await?;
                Ok("v2".into())
            })
            .register("WrongHandler", |ctx: OrchestrationContext, _: String| async move {
                ctx.schedule_activity("tick", "wrong").await?;
                Ok("wrong".into())
            })
            .build();
        let runtime = Runtime::start_with_options(
            provider.clone(),
            ActivityRegistry::builder().build(),
            registry,
            RuntimeOptions {
                dispatcher_min_poll_interval: Duration::from_millis(10),
                ..Default::default()
            },
        )
        .await;
        let result = Client::new(provider)
            .wait_for_orchestration(&instance, Duration::from_secs(10))
            .await;
        runtime.shutdown(None).await;
        assert!(matches!(result.expect("duplicate client start must be inert"),
            OrchestrationStatus::Completed { ref output, .. } if output == "v1:original-input"));
    }
}

/// During rolling upgrades an unregistered successor can hide its CAN start
/// through backoff. New inputs must survive until a compatible runtime resumes it.
pub async fn test_continue_as_new_unregistered_backoff<F: ProviderFactory>(factory: &F) {
    let provider = factory.create_provider().await;
    let instance = "provider-can-unregistered-backoff";
    provider
        .enqueue_for_orchestrator(start_item(instance), None)
        .await
        .expect("seed start");
    let (_, lock, _) = provider
        .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
        .await
        .expect("seed fetch")
        .expect("visible seed");
    provider
        .ack_orchestration_item(
            &lock,
            1,
            vec![
                Event::with_event_id(
                    1,
                    instance,
                    1,
                    None,
                    EventKind::OrchestrationStarted {
                        name: "RollingSuccessor".into(),
                        version: "1.0.0".into(),
                        input: "old".into(),
                        parent_instance: None,
                        parent_id: None,
                        parent_execution_id: None,
                        carry_forward_events: None,
                        initial_custom_status: None,
                    },
                ),
                Event::with_event_id(
                    2,
                    instance,
                    1,
                    None,
                    EventKind::OrchestrationContinuedAsNew { input: "next".into() },
                ),
            ],
            vec![],
            vec![WorkItem::ContinueAsNew {
                instance: instance.into(),
                orchestration: "RollingSuccessor".into(),
                input: "next".into(),
                version: Some("1.0.0".into()),
                parent_instance: None,
                parent_id: None,
                parent_execution_id: None,
                carry_forward_events: vec![("q".into(), "carried".into())],
                initial_custom_status: None,
            }],
            ExecutionMetadata {
                status: Some("ContinuedAsNew".into()),
                ..Default::default()
            },
            vec![],
        )
        .await
        .expect("seed terminal and immediately visible successor atomically");
    let old_runtime = Runtime::start_with_options(
        provider.clone(),
        ActivityRegistry::builder().build(),
        OrchestrationRegistry::builder().build(),
        RuntimeOptions {
            orchestration_concurrency: 1,
            dispatcher_min_poll_interval: Duration::from_millis(10),
            unregistered_backoff: crate::runtime::UnregisteredBackoffConfig {
                base_delay: Duration::from_secs(2),
                max_delay: Duration::from_secs(2),
            },
            ..Default::default()
        },
    )
    .await;
    let hidden = tokio::time::timeout(Duration::from_secs(10), async {
        let mut tick = tokio::time::interval(Duration::from_millis(20));
        loop {
            tick.tick().await;
            match provider
                .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
                .await
            {
                Ok(None) => break,
                Ok(Some((item, lock, _))) => {
                    assert!(
                        item.messages
                            .iter()
                            .any(|item| matches!(item, WorkItem::ContinueAsNew { .. }))
                    );
                    // The runtime fetches from the same store at the same time, so the
                    // provider may report a retryable conflict (SQLite's shared-cache
                    // "database is deadlocked"). A failed abandon leaves the lock in
                    // place, so retry it.
                    let mut attempt = 0u64;
                    loop {
                        match provider.abandon_orchestration_item(&lock, None, true).await {
                            Ok(()) => break,
                            Err(error) if error.retryable && attempt < 5 => {
                                attempt += 1;
                                tracing::warn!(%error, attempt, "Retrying release of competing inspection fetch");
                                tokio::time::sleep(Duration::from_millis(10 * attempt)).await;
                            }
                            Err(error) => panic!("release competing inspection fetch: {error}"),
                        }
                    }
                }
                Err(error) if error.retryable => {
                    tracing::warn!(%error, "Retrying backoff-test visibility inspection");
                }
                Err(error) => panic!("backoff-test fetch failed: {error}"),
            }
        }
    })
    .await;
    old_runtime.shutdown(None).await;
    hidden.expect("unregistered runtime must fetch and hide the start");
    assert!(
        provider
            .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
            .await
            .expect("inspect after runtime stopped")
            .is_none(),
        "start must be delayed by unregistered-handler backoff, not merely locked"
    );
    assert_eq!(
        provider
            .read_with_execution(instance, 1)
            .await
            .expect("predecessor history")
            .len(),
        2
    );
    let client = Client::new(provider.clone());
    client
        .enqueue_event(instance, "q", "late")
        .await
        .expect("input during successor backoff");
    let registry = OrchestrationRegistry::builder()
        .register("RollingSuccessor", |ctx: OrchestrationContext, _: String| async move {
            assert_eq!(ctx.execution_id(), 2);
            let first = ctx.dequeue_event("q").await;
            let second = ctx.dequeue_event("q").await;
            Ok(format!("{first},{second}"))
        })
        .build();
    let new_runtime = Runtime::start_with_options(
        provider.clone(),
        ActivityRegistry::builder().build(),
        registry,
        RuntimeOptions {
            dispatcher_min_poll_interval: Duration::from_millis(10),
            ..Default::default()
        },
    )
    .await;
    let result = client.wait_for_orchestration(instance, Duration::from_secs(10)).await;
    new_runtime.shutdown(None).await;
    assert!(
        matches!(result.expect("successor and window input must survive rolling-node backoff"),
        OrchestrationStatus::Completed { ref output, .. } if output == "carried,late")
    );
}

/// A poisoned continue-as-new successor is committed as its own execution: the
/// poison ack creates execution 2 with a start row and the failure, and execution 1
/// still ends in ContinuedAsNew.
pub async fn test_continue_as_new_poisoned_successor_is_own_execution<F: ProviderFactory>(factory: &F) {
    let provider = factory.create_provider().await;
    let instance = "provider-can-poisoned-successor";
    provider
        .enqueue_for_orchestrator(start_item(instance), None)
        .await
        .expect("seed start");
    let (_, lock, _) = provider
        .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
        .await
        .expect("seed fetch")
        .expect("visible seed");
    provider
        .ack_orchestration_item(
            &lock,
            1,
            vec![
                Event::with_event_id(
                    1,
                    instance,
                    1,
                    None,
                    EventKind::OrchestrationStarted {
                        name: "PoisonedSuccessor".into(),
                        version: "1.0.0".into(),
                        input: "old".into(),
                        parent_instance: None,
                        parent_id: None,
                        parent_execution_id: None,
                        carry_forward_events: None,
                        initial_custom_status: None,
                    },
                ),
                Event::with_event_id(
                    2,
                    instance,
                    1,
                    None,
                    EventKind::OrchestrationContinuedAsNew { input: "next".into() },
                ),
            ],
            vec![],
            vec![WorkItem::ContinueAsNew {
                instance: instance.into(),
                orchestration: "PoisonedSuccessor".into(),
                input: "next".into(),
                version: Some("1.0.0".into()),
                parent_instance: None,
                parent_id: None,
                parent_execution_id: None,
                carry_forward_events: vec![],
                initial_custom_status: None,
            }],
            ExecutionMetadata {
                status: Some("ContinuedAsNew".into()),
                ..Default::default()
            },
            vec![],
        )
        .await
        .expect("seed terminal and successor atomically");
    // No handler is registered, so the successor's batch is poisoned after one attempt.
    let runtime = Runtime::start_with_options(
        provider.clone(),
        ActivityRegistry::builder().build(),
        OrchestrationRegistry::builder().build(),
        RuntimeOptions {
            max_attempts: 1,
            orchestration_concurrency: 1,
            dispatcher_min_poll_interval: Duration::from_millis(10),
            unregistered_backoff: crate::runtime::UnregisteredBackoffConfig {
                base_delay: Duration::from_millis(20),
                max_delay: Duration::from_millis(20),
            },
            ..Default::default()
        },
    )
    .await;
    let client = Client::new(provider.clone());
    let result = client.wait_for_orchestration(instance, Duration::from_secs(10)).await;
    client.enqueue_event(instance, "q", "late").await.expect("late input");
    tokio::time::sleep(Duration::from_millis(500)).await;
    runtime.shutdown(None).await;
    assert!(matches!(
        result.expect("poison must end the successor"),
        OrchestrationStatus::Failed {
            details: crate::ErrorDetails::Poison { .. },
            ..
        }
    ));
    let previous = provider
        .read_with_execution(instance, 1)
        .await
        .expect("previous execution");
    assert!(matches!(
        previous.last().map(|e| &e.kind),
        Some(EventKind::OrchestrationContinuedAsNew { .. })
    ));
    let successor = provider.read(instance).await.expect("latest execution");
    assert_eq!(
        successor,
        provider
            .read_with_execution(instance, 2)
            .await
            .expect("successor execution"),
        "the poisoned successor must be the latest execution"
    );
    let kinds: Vec<&EventKind> = successor.iter().map(|e| &e.kind).collect();
    assert!(
        matches!(
            kinds.as_slice(),
            [
                EventKind::OrchestrationStarted { .. },
                EventKind::OrchestrationFailed {
                    details: crate::ErrorDetails::Poison { .. }
                }
            ]
        ),
        "successor history: {successor:?}"
    );
    assert!(
        provider
            .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
            .await
            .expect("inspect after runtime stopped")
            .is_none(),
        "a late input to the failed successor is acknowledged, not left waiting"
    );
}

/// A duplicate start must not replace the durable CAN successor, even when it
/// precedes that successor in queue order. A colliding parent must be notified.
pub async fn test_continue_as_new_duplicate_start<F: ProviderFactory>(factory: &F) {
    for (stamp, collision) in [("0.1.30", false), ("0.1.30", true), ("0.1.31", false), ("0.1.31", true)] {
        let provider = factory.create_provider().await;
        let parent = "provider-can-duplicate-parent";
        let instance = format!("{parent}::can-child");
        let persist = |instance: String, history: Vec<Event>, messages: Vec<WorkItem>, status: &str| {
            let provider = provider.clone();
            let status = status.to_string();
            async move {
                provider
                    .enqueue_for_orchestrator(start_item(&instance), None)
                    .await
                    .expect("seed start");
                let (_, lock, _) = provider
                    .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
                    .await
                    .expect("seed fetch")
                    .expect("visible seed");
                provider
                    .ack_orchestration_item(
                        &lock,
                        1,
                        history,
                        vec![],
                        messages,
                        ExecutionMetadata {
                            status: Some(status),
                            ..Default::default()
                        },
                        vec![],
                    )
                    .await
                    .expect("seed acknowledgement");
            }
        };
        let started = |instance: &str, name: &str| {
            let mut event = Event::with_event_id(
                1,
                instance,
                1,
                None,
                EventKind::OrchestrationStarted {
                    name: name.into(),
                    version: "1.0.0".into(),
                    input: "".into(),
                    parent_instance: None,
                    parent_id: None,
                    parent_execution_id: None,
                    carry_forward_events: None,
                    initial_custom_status: None,
                },
            );
            event.duroxide_version = stamp.into();
            event
        };
        if collision {
            persist(
                parent.into(),
                vec![
                    started(parent, "CollisionParent"),
                    Event::with_event_id(
                        2,
                        parent,
                        1,
                        None,
                        EventKind::SubOrchestrationScheduled {
                            name: "Transition".into(),
                            instance: "can-child".into(),
                            input: "duplicate".into(),
                        },
                    ),
                ],
                vec![],
                "Running",
            )
            .await;
        }
        let messages = vec![
            WorkItem::StartOrchestration {
                instance: instance.clone(),
                orchestration: "WrongHandler".into(),
                input: "duplicate".into(),
                version: None,
                execution_id: 1,
                parent_instance: collision.then(|| parent.into()),
                parent_id: collision.then_some(2),
                parent_execution_id: collision.then_some(1),
            },
            WorkItem::ContinueAsNew {
                instance: instance.clone(),
                orchestration: "Transition".into(),
                input: "next".into(),
                version: Some("1.0.0".into()),
                parent_instance: None,
                parent_id: None,
                parent_execution_id: None,
                carry_forward_events: vec![("q".into(), "carried".into())],
                initial_custom_status: None,
            },
            WorkItem::QueueMessage {
                instance: instance.clone(),
                name: "q".into(),
                data: "late".into(),
            },
        ];
        persist(
            instance.clone(),
            vec![
                started(&instance, "Transition"),
                Event::with_event_id(
                    2,
                    &instance,
                    1,
                    None,
                    EventKind::OrchestrationContinuedAsNew { input: "next".into() },
                ),
            ],
            messages,
            "ContinuedAsNew",
        )
        .await;
        let registry = OrchestrationRegistry::builder()
            .register("Transition", |ctx: OrchestrationContext, _: String| async move {
                assert_eq!(ctx.execution_id(), 2);
                let first = ctx.dequeue_event("q").await;
                let second = ctx.dequeue_event("q").await;
                Ok(format!("{first},{second}"))
            })
            .register("CollisionParent", |ctx: OrchestrationContext, _: String| async move {
                match ctx
                    .schedule_sub_orchestration_with_id("Transition", "can-child", "duplicate")
                    .await
                {
                    Ok(value) => Err(format!("collision unexpectedly resolved: {value}")),
                    Err(error) => Ok(error),
                }
            })
            .build();
        let runtime = Runtime::start_with_options(
            provider.clone(),
            ActivityRegistry::builder().build(),
            registry,
            RuntimeOptions {
                dispatcher_min_poll_interval: Duration::from_millis(10),
                ..Default::default()
            },
        )
        .await;
        let client = Client::new(provider.clone());
        let result = client.wait_for_orchestration(&instance, Duration::from_secs(10)).await;
        let parent_result = if collision {
            Some(client.wait_for_orchestration(parent, Duration::from_secs(10)).await)
        } else {
            None
        };
        runtime.shutdown(None).await;
        assert!(
            matches!(result.expect("CAN successor must not livelock behind duplicate start"),
            OrchestrationStatus::Completed { ref output, .. } if output == "carried,late")
        );
        if let Some(parent_result) = parent_result {
            assert!(
                matches!(parent_result.expect("colliding parent must receive a notification"),
                OrchestrationStatus::Completed { ref output, .. }
                if output.contains("already exists") && !output.contains("is terminal")),
                "collision notification must describe an existing logical instance, not a dead successor"
            );
        }
        let old = provider
            .read_with_execution(&instance, 1)
            .await
            .expect("predecessor history");
        assert_eq!(old.len(), 2, "duplicate start must not mutate old recorded history");
        let next = provider
            .read_with_execution(&instance, 2)
            .await
            .expect("successor history");
        assert!(
            matches!(&next[0].kind, EventKind::OrchestrationStarted { name, input, .. }
            if name == "Transition" && input == "next")
        );
    }
}

/// Persistent inputs must survive a CAN-terminal fetch without the successor's start item.
/// The delayed start deterministically exposes the provider's visibility-cutoff window.
pub async fn test_continue_as_new_transition_delivery<F: ProviderFactory>(factory: &F, stamp: &str) {
    for shape in [
        "queue",
        "race",
        "mixed-stale",
        "signal",
        "cancel",
        "future-completion",
        "stale-only",
    ] {
        let race = shape == "race";
        let provider = factory.create_provider().await;
        let instance = format!("provider-can-window-{stamp}-{shape}");
        let mut start = Event::with_event_id(
            1,
            &instance,
            1,
            None,
            EventKind::OrchestrationStarted {
                name: "Transition".into(),
                version: "1.0.0".into(),
                input: "old".into(),
                parent_instance: None,
                parent_id: None,
                parent_execution_id: None,
                carry_forward_events: None,
                initial_custom_status: None,
            },
        );
        start.duroxide_version = stamp.into();
        provider
            .enqueue_for_orchestrator(start_item(&instance), None)
            .await
            .expect("must enqueue the seed execution");
        let (_, lock, _) = provider
            .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
            .await
            .expect("must fetch the seed execution")
            .expect("seed execution must be visible");
        let mut inputs = vec![WorkItem::QueueMessage {
            instance: instance.clone(),
            name: "q".into(),
            data: "late".into(),
        }];
        if shape == "mixed-stale" {
            inputs.extend([
                WorkItem::ActivityCompleted {
                    instance: instance.clone(),
                    execution_id: 1,
                    id: 99,
                    result: "stale".into(),
                },
                WorkItem::TimerFired {
                    instance: instance.clone(),
                    execution_id: 1,
                    id: 100,
                    fire_at_ms: 1,
                },
                WorkItem::SubOrchCompleted {
                    parent_instance: instance.clone(),
                    parent_execution_id: 1,
                    parent_id: 101,
                    result: "stale".into(),
                },
            ]);
        }
        if shape == "future-completion" || shape == "stale-only" {
            inputs = vec![WorkItem::ActivityCompleted {
                instance: instance.clone(),
                execution_id: if shape == "future-completion" { 2 } else { 1 },
                id: 99,
                result: "unmatched".into(),
            }];
        }
        if shape == "signal" {
            inputs.push(WorkItem::ExternalRaised {
                instance: instance.clone(),
                name: "signal".into(),
                data: "answer".into(),
            });
        }
        if shape == "cancel" {
            inputs.push(WorkItem::CancelInstance {
                instance: instance.clone(),
                reason: "requested-during-CAN".into(),
            });
        }
        provider
            .ack_orchestration_item(
                &lock,
                1,
                vec![
                    start,
                    Event::with_event_id(
                        2,
                        &instance,
                        1,
                        None,
                        EventKind::OrchestrationContinuedAsNew { input: "next".into() },
                    ),
                ],
                vec![],
                inputs,
                ExecutionMetadata {
                    status: Some("ContinuedAsNew".into()),
                    output: Some("next".into()),
                    orchestration_name: Some("Transition".into()),
                    orchestration_version: Some("1.0.0".into()),
                    pinned_duroxide_version: Some(stamp.parse().expect("test stamp must parse")),
                    ..Default::default()
                },
                vec![],
            )
            .await
            .expect("must persist the CAN-terminal seed and arrival atomically");
        let successor_start = WorkItem::ContinueAsNew {
            instance: instance.clone(),
            orchestration: "Transition".into(),
            input: "next".into(),
            version: Some("1.0.0".into()),
            parent_instance: None,
            parent_id: None,
            parent_execution_id: None,
            carry_forward_events: vec![("q".into(), "carried".into())],
            initial_custom_status: None,
        };
        provider
            .enqueue_for_orchestrator(successor_start, Some(Duration::from_secs(2)))
            .await
            .expect("must enqueue the delayed successor start");
        let registry = OrchestrationRegistry::builder()
            .register("Transition", move |ctx: OrchestrationContext, _: String| async move {
                if ctx.execution_id() == 1 {
                    return ctx.continue_as_new("next").await;
                }
                if shape == "stale-only" {
                    return Ok(ctx.dequeue_event("q").await);
                }
                if shape == "signal" {
                    let answer = ctx.schedule_wait("signal").await;
                    let first = ctx.dequeue_event("q").await;
                    let second = ctx.dequeue_event("q").await;
                    return Ok(format!("{first},{second}|{answer}"));
                }
                let mut values = Vec::new();
                while values.len() < 2 {
                    if race {
                        if let crate::Either2::First(value) = ctx
                            .select2(ctx.dequeue_event("q"), ctx.schedule_timer(Duration::from_millis(10)))
                            .await
                        {
                            values.push(value);
                        }
                    } else {
                        values.push(ctx.dequeue_event("q").await);
                    }
                }
                Ok(values.join(","))
            })
            .build();
        let runtime = Runtime::start_with_options(
            provider.clone(),
            ActivityRegistry::builder().build(),
            registry,
            RuntimeOptions {
                dispatcher_min_poll_interval: Duration::from_millis(10),
                // Waiting inputs back off and count attempts like an unregistered handler;
                // the 2 s hidden start must arrive well inside the default poison budget.
                unregistered_backoff: crate::runtime::UnregisteredBackoffConfig {
                    base_delay: Duration::from_millis(250),
                    max_delay: Duration::from_secs(1),
                },
                ..Default::default()
            },
        )
        .await;
        if shape == "signal" {
            tokio::time::timeout(Duration::from_secs(10), async {
                let mut tick = tokio::time::interval(Duration::from_millis(20));
                loop {
                    tick.tick().await;
                    let history = provider
                        .read_with_execution(&instance, 2)
                        .await
                        .expect("observe successor signal binding");
                    if history
                        .iter()
                        .any(|event| matches!(&event.kind, EventKind::ExternalSubscribed { name } if name == "signal"))
                        && history.iter().any(|event| {
                            matches!(&event.kind, EventKind::ExternalEvent { name, data }
                                if name == "signal" && data == "answer")
                        })
                    {
                        break;
                    }
                }
            })
            .await
            .expect("successor must audit the preserved window signal and bind its wait");
            Client::new(provider.clone())
                .raise_event(&instance, "signal", "fresh")
                .await
                .expect("fresh answer after subscription");
        }
        let result = Client::new(provider.clone())
            .wait_for_orchestration(&instance, Duration::from_secs(10))
            .await;
        runtime.shutdown(None).await;
        let successor = provider
            .read_with_execution(&instance, 2)
            .await
            .expect("must read the successor history");
        let old = provider
            .read_with_execution(&instance, 1)
            .await
            .expect("predecessor history");
        assert_eq!(old.len(), 2, "{stamp}/{shape}: admission cannot mutate execution 1");
        assert!(matches!(old[0].kind, EventKind::OrchestrationStarted { .. }));
        assert!(matches!(old[1].kind, EventKind::OrchestrationContinuedAsNew { .. }));
        assert!(
            !successor.is_empty(),
            "{stamp}/{shape}: successor never started; this does not prove arrival loss"
        );
        assert_eq!(
            successor[0]
                .duroxide_version
                .parse::<semver::Version>()
                .expect("successor stamp must parse"),
            crate::providers::current_build_version(),
            "the predecessor stamp does not select the successor's policy"
        );
        let result = result.unwrap_or_else(|error| {
            panic!("{stamp}/{shape}: terminal CAN must preserve the queued input: {error:?}; history={successor:?}")
        });
        if shape == "future-completion" {
            assert!(
                matches!(
                    &result,
                    OrchestrationStatus::Failed {
                        details: crate::ErrorDetails::Configuration {
                            kind: crate::ConfigErrorKind::Nondeterminism,
                            ..
                        },
                        ..
                    }
                ),
                "{stamp}/{shape}: a future-scoped malformed completion must be validated, not silently ACKed: {result:?}"
            );
            continue;
        }
        if shape == "stale-only" {
            assert!(
                matches!(&result, OrchestrationStatus::Completed { output, .. } if output == "carried"),
                "{stamp}/{shape}: stale-only batch must not obstruct the successor: {result:?}"
            );
            continue;
        }
        if shape == "cancel" {
            assert!(
                matches!(&result, OrchestrationStatus::Failed { details: crate::ErrorDetails::Application {
                    kind: crate::AppErrorKind::Cancelled { reason }, ..
                }, .. } if reason == "requested-during-CAN"),
                "{stamp}/{shape}: logical instance cancellation must reach the successor: {result:?}"
            );
            continue;
        }
        let expected_output = if shape == "signal" {
            let binding = successor
                .iter()
                .find(|event| matches!(&event.kind, EventKind::ExternalSubscribed { name } if name == "signal"))
                .expect("successor must bind its signal wait")
                .event_id;
            let answer = successor
                .iter()
                .find(|event| {
                    matches!(&event.kind, EventKind::ExternalEvent { name, data } if name == "signal" && data == "answer")
                })
                .expect("preserved window signal must reach the successor audit history")
                .event_id;
            // Abandon visibility may split the CAN start and window inputs into
            // separate fetches. Bound admission is defined at event application,
            // not by the time the test enqueued the signal.
            if answer < binding {
                "carried,late|fresh"
            } else {
                "carried,late|answer"
            }
        } else {
            "carried,late"
        };
        assert!(
            matches!(result, OrchestrationStatus::Completed { ref output, .. } if output == expected_output),
            "{stamp}/{shape}: carried input must precede the preserved window arrival: {result:?}"
        );
        if shape == "signal" {
            let OrchestrationStatus::Completed { output, .. } = &result else {
                unreachable!("completion was asserted above");
            };
            let consumed = output
                .strip_prefix("carried,late|")
                .expect("signal output must preserve queued values");
            if expected_output == "carried,late|fresh" {
                assert_eq!(consumed, "fresh", "the audited answer before binding must be skipped");
                assert_ne!(
                    consumed, "answer",
                    "an early answer must not resolve the successor's wait"
                );
            } else {
                assert_eq!(
                    consumed, "answer",
                    "the answer applied after binding must resolve that wait"
                );
                assert_ne!(
                    consumed, "fresh",
                    "fresh must not be consumed after the bound answer resolved"
                );
            }
        }
        let delivered: Vec<_> = successor
            .iter()
            .filter_map(|event| match &event.kind {
                EventKind::QueueEventDelivered { name, data } if name == "q" => Some(data.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(
            delivered,
            ["carried", "late"],
            "{stamp}/{shape}: no loss or duplication"
        );
        if shape == "signal" {
            assert_eq!(
                successor
                    .iter()
                    .filter(|event| matches!(&event.kind, EventKind::ExternalEvent { name, data }
                    if name == "signal" && data == "answer"))
                    .count(),
                1,
                "positional input must reach successor admission exactly once"
            );
        }
        // Only mixed-stale injects stale completions (ids 99-101 of execution 1). In the race
        // shape the successor's own timers can legitimately reach those ids while it waits.
        if shape == "mixed-stale" {
            assert!(
                !successor.iter().any(|event| matches!(
                    event.kind,
                    EventKind::ActivityCompleted { .. }
                        | EventKind::TimerFired { .. }
                        | EventKind::SubOrchestrationCompleted { .. }
                ) && event.source_event_id.is_some_and(|id| id >= 99)),
                "{stamp}/{shape}: stale execution completions must not be applied to the successor"
            );
        }
    }
}

/// Queue Q1/Q2/Q6 FIFO and replay checks on every provider.
pub async fn test_queue_race_cancellation_replay<F: ProviderFactory>(factory: &F) {
    for shape in ["q1", "q2", "q6"] {
        let provider = factory.create_provider().await;
        let instance = format!("provider-queue-race-{shape}");
        let event = |id, source, kind| Event::with_event_id(id, &instance, 1, source, kind);
        let mut start = event(
            1,
            None,
            EventKind::OrchestrationStarted {
                name: "QueueRace".into(),
                version: "1.0.0".into(),
                input: shape.into(),
                parent_instance: None,
                parent_id: None,
                parent_execution_id: None,
                carry_forward_events: None,
                initial_custom_status: None,
            },
        );
        start.duroxide_version = "0.1.31".into();
        let mut history = vec![start];
        match shape {
            "q1" => {
                history.extend([
                    event(2, None, EventKind::QueueSubscribed { name: "q".into() }),
                    event(3, None, EventKind::QueueSubscribed { name: "q".into() }),
                    event(4, None, EventKind::TimerCreated { fire_at_ms: 1000 }),
                    event(5, Some(4), EventKind::TimerFired { fire_at_ms: 1000 }),
                    event(
                        6,
                        None,
                        EventKind::QueueEventDelivered {
                            name: "q".into(),
                            data: "first".into(),
                        },
                    ),
                    event(
                        7,
                        None,
                        EventKind::QueueEventDelivered {
                            name: "q".into(),
                            data: "second".into(),
                        },
                    ),
                    event(8, None, EventKind::QueueSubscribed { name: "q".into() }),
                    event(9, None, EventKind::QueueSubscribed { name: "q".into() }),
                    event(
                        10,
                        Some(2),
                        EventKind::QueueSubscriptionCancelled {
                            reason: "dropped_future".into(),
                        },
                    ),
                    event(
                        11,
                        Some(3),
                        EventKind::QueueSubscriptionCancelled {
                            reason: "dropped_future".into(),
                        },
                    ),
                ]);
            }
            "q2" => {
                history.extend([
                    event(2, None, EventKind::QueueSubscribed { name: "q".into() }),
                    event(3, None, EventKind::QueueSubscribed { name: "q".into() }),
                    event(4, None, EventKind::TimerCreated { fire_at_ms: 1000 }),
                    event(
                        5,
                        None,
                        EventKind::QueueEventDelivered {
                            name: "q".into(),
                            data: "first".into(),
                        },
                    ),
                    event(
                        6,
                        None,
                        EventKind::QueueEventDelivered {
                            name: "q".into(),
                            data: "second".into(),
                        },
                    ),
                    event(7, None, EventKind::QueueSubscribed { name: "q".into() }),
                    event(
                        8,
                        Some(3),
                        EventKind::QueueSubscriptionCancelled {
                            reason: "dropped_future".into(),
                        },
                    ),
                ]);
            }
            "q6" => {
                history.extend([
                    event(2, None, EventKind::QueueSubscribed { name: "q".into() }),
                    event(3, None, EventKind::TimerCreated { fire_at_ms: 1000 }),
                    event(4, None, EventKind::TimerCreated { fire_at_ms: 1100 }),
                    event(5, Some(4), EventKind::TimerFired { fire_at_ms: 1100 }),
                    event(
                        6,
                        None,
                        EventKind::QueueEventDelivered {
                            name: "q".into(),
                            data: "first".into(),
                        },
                    ),
                    event(7, None, EventKind::QueueSubscribed { name: "q".into() }),
                    event(
                        8,
                        Some(2),
                        EventKind::QueueSubscriptionCancelled {
                            reason: "dropped_future".into(),
                        },
                    ),
                ]);
            }
            _ => unreachable!(),
        }
        let checkpoint_id = history.last().unwrap().event_id + 1;
        let expected = if shape == "q6" { "first" } else { "first,second" };
        history.push(event(
            checkpoint_id,
            None,
            EventKind::ActivityScheduled {
                name: "checkpoint".into(),
                input: expected.into(),
                session_id: None,
                tag: None,
            },
        ));
        provider
            .enqueue_for_orchestrator(start_item(&instance), None)
            .await
            .unwrap();
        let (_, lock, _) = provider
            .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
            .await
            .unwrap()
            .unwrap();
        provider
            .ack_orchestration_item(
                &lock,
                1,
                history.clone(),
                vec![],
                vec![WorkItem::ActivityCompleted {
                    instance: instance.clone(),
                    execution_id: 1,
                    id: checkpoint_id,
                    result: "ok".into(),
                }],
                ExecutionMetadata {
                    orchestration_name: Some("QueueRace".into()),
                    orchestration_version: Some("1.0.0".into()),
                    ..Default::default()
                },
                vec![],
            )
            .await
            .unwrap();
        assert_eq!(
            provider.read_with_execution(&instance, 1).await.unwrap(),
            history,
            "provider must preserve full event metadata and pinned semantic version"
        );
        let registry = OrchestrationRegistry::builder()
            .register("QueueRace", |ctx: OrchestrationContext, input: String| async move {
                let mut values = Vec::new();
                if input == "q6" {
                    let inner = ctx.select2(ctx.dequeue_event("q"), ctx.schedule_timer(Duration::from_millis(10)));
                    let _ = ctx.select2(inner, ctx.schedule_timer(Duration::from_millis(100))).await;
                    values.push(ctx.dequeue_event("q").await);
                } else {
                    match ctx
                        .select3(
                            ctx.dequeue_event("q"),
                            ctx.dequeue_event("q"),
                            ctx.schedule_timer(Duration::from_millis(10)),
                        )
                        .await
                    {
                        Either3::First(value) | Either3::Second(value) => values.push(value),
                        Either3::Third(()) => {}
                    }
                    while values.len() < 2 {
                        values.push(ctx.dequeue_event("q").await);
                    }
                }
                let output = values.join(",");
                ctx.schedule_activity("checkpoint", &output).await?;
                Ok(output)
            })
            .build();
        let runtime = Runtime::start_with_options(
            provider.clone(),
            ActivityRegistry::builder().build(),
            registry,
            RuntimeOptions {
                dispatcher_min_poll_interval: Duration::from_millis(5),
                ..Default::default()
            },
        )
        .await;
        let result = Client::new(provider)
            .wait_for_orchestration(&instance, Duration::from_secs(30))
            .await;
        runtime.shutdown(None).await;
        let result = result.unwrap_or_else(|error| panic!("{shape}: queue replay did not complete: {error:?}"));
        assert!(
            matches!(result,OrchestrationStatus::Completed{ref output,..}if output==expected),
            "{shape}: {result:?}"
        );
    }
}

/// Continue-as-new must carry unread arrivals, including held and non-prefix cases.
pub async fn test_continue_as_new_queue_race_replay<F: ProviderFactory>(factory: &F) {
    for shape in ["can", "can-drain", "can-held", "can-held-nonprefix"] {
        let provider = factory.create_provider().await;
        let instance = format!("provider-combined-race-{shape}");
        let event = |id, source, kind| Event::with_event_id(id, &instance, 1, source, kind);
        let mut start = event(
            1,
            None,
            EventKind::OrchestrationStarted {
                name: "CombinedRace".into(),
                version: "1.0.0".into(),
                input: shape.into(),
                parent_instance: None,
                parent_id: None,
                parent_execution_id: None,
                carry_forward_events: None,
                initial_custom_status: None,
            },
        );
        start.duroxide_version = "0.1.31".into();
        let mut history = vec![start];
        let incoming = {
            history.extend([
                event(2, None, EventKind::QueueSubscribed { name: "q".into() }),
                event(3, None, EventKind::TimerCreated { fire_at_ms: 1000 }),
            ]);
            let mut messages = vec![
                WorkItem::TimerFired {
                    instance: instance.clone(),
                    execution_id: 1,
                    id: 3,
                    fire_at_ms: 1000,
                },
                WorkItem::QueueMessage {
                    instance: instance.clone(),
                    name: "q".into(),
                    data: "m1".into(),
                },
            ];
            if shape == "can-drain" || shape == "can-held-nonprefix" {
                messages.push(WorkItem::QueueMessage {
                    instance: instance.clone(),
                    name: "q".into(),
                    data: "m2".into(),
                });
            }
            messages
        };
        provider
            .enqueue_for_orchestrator(start_item(&instance), None)
            .await
            .unwrap();
        let (_, lock, _) = provider
            .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
            .await
            .unwrap()
            .unwrap();
        provider
            .ack_orchestration_item(
                &lock,
                1,
                history,
                vec![],
                incoming,
                ExecutionMetadata {
                    orchestration_name: Some("CombinedRace".into()),
                    orchestration_version: Some("1.0.0".into()),
                    ..Default::default()
                },
                vec![],
            )
            .await
            .unwrap();
        let registry = OrchestrationRegistry::builder()
            .register("CombinedRace", |ctx: OrchestrationContext, input: String| async move {
                if ctx.execution_id() == 1 {
                    if input.starts_with("can-held") {
                        let mut held = ctx.dequeue_event("q");
                        let _ = ctx
                            .select2(&mut held, ctx.schedule_timer(Duration::from_millis(10)))
                            .await;
                        if input == "can-held-nonprefix" {
                            ctx.dequeue_event("q").await;
                        }
                        return ctx.continue_as_new(input).await;
                    }
                    let _ = ctx
                        .select2(ctx.dequeue_event("q"), ctx.schedule_timer(Duration::from_millis(10)))
                        .await;
                    if input == "can-drain" {
                        ctx.dequeue_event("q").await;
                    }
                    ctx.continue_as_new(input).await
                } else {
                    Ok(ctx.dequeue_event("q").await)
                }
            })
            .build();
        let runtime = Runtime::start_with_options(
            provider.clone(),
            ActivityRegistry::builder().build(),
            registry,
            RuntimeOptions {
                dispatcher_min_poll_interval: Duration::from_millis(5),
                ..Default::default()
            },
        )
        .await;
        let result = Client::new(provider)
            .wait_for_orchestration(&instance, Duration::from_secs(30))
            .await;
        runtime.shutdown(None).await;
        let result = result.unwrap_or_else(|error| panic!("{shape}: unread CAN arrivals did not complete: {error:?}"));
        let expected = match shape {
            "can-drain" => "m2",
            _ => "m1",
        };
        assert!(
            matches!(result,OrchestrationStatus::Completed{ref output,..}if output==expected),
            "{shape}: {result:?}"
        );
    }
}

/// An old semantic version must round-trip without being restamped by a newer reader.
pub async fn test_queue_replay_version_stamp_roundtrip<F: ProviderFactory>(factory: &F) {
    let provider = factory.create_provider().await;
    let instance = "queue-version-roundtrip";
    let mut event = Event::with_event_id(
        1,
        instance,
        1,
        None,
        EventKind::OrchestrationStarted {
            name: "TestOrch".into(),
            version: "1.0.0".into(),
            input: "{}".into(),
            parent_instance: None,
            parent_id: None,
            parent_execution_id: None,
            carry_forward_events: None,
            initial_custom_status: None,
        },
    );
    event.duroxide_version = "0.1.30".into();
    provider
        .enqueue_for_orchestrator(start_item(instance), None)
        .await
        .unwrap();
    let (_, lock, _) = provider
        .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
        .await
        .unwrap()
        .unwrap();
    provider
        .ack_orchestration_item(
            &lock,
            1,
            vec![event.clone()],
            vec![],
            vec![],
            ExecutionMetadata {
                orchestration_name: Some("TestOrch".into()),
                orchestration_version: Some("1.0.0".into()),
                ..Default::default()
            },
            vec![],
        )
        .await
        .unwrap();
    assert_eq!(provider.read_with_execution(instance, 1).await.unwrap(), vec![event]);
    provider
        .enqueue_for_orchestrator(
            WorkItem::ExternalRaised {
                instance: instance.into(),
                name: "fetch-stamp".into(),
                data: "wake".into(),
            },
            None,
        )
        .await
        .expect("enqueue fetch-path stamp probe");
    let (fetched, lock, _) = provider
        .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
        .await
        .expect("fetch old-stamped execution")
        .expect("old-stamped execution was not fetchable");
    assert_eq!(
        fetched.history[0].duroxide_version, "0.1.30",
        "fetch path restamped history"
    );
    provider
        .abandon_orchestration_item(&lock, None, true)
        .await
        .expect("release stamp probe lock");
}

/// Sequential positional round trips with a long timer loser, then identical replay.
/// The binding barrier deliberately serializes signals; this is not competitive
/// signal-race coverage. Engine tests cover same-batch signal/timer races.
pub async fn test_positional_wait_race_replay<F: ProviderFactory>(factory: &F) {
    let provider = factory.create_provider().await;
    let registry = OrchestrationRegistry::builder()
        .register("LiveSignalRace", |ctx: OrchestrationContext, _: String| async move {
            let first = ctx
                .select2(
                    ctx.schedule_wait("s"),
                    ctx.schedule_timer(Duration::from_secs(30))
                        .map(|()| "timeout".to_string()),
                )
                .await
                .into_tuple()
                .1;
            Ok(format!("{first:?}:{}", ctx.schedule_wait("s").await))
        })
        .build();
    let handler = registry
        .resolve_handler("LiveSignalRace")
        .expect("registered live signal handler")
        .1;
    let runtime = Runtime::start_with_options(
        provider.clone(),
        ActivityRegistry::builder().build(),
        registry,
        RuntimeOptions::default(),
    )
    .await;
    let client = Client::new(provider.clone());
    client
        .start_orchestration("provider-live-signal", "LiveSignalRace", "")
        .await
        .expect("start live signal race");
    tokio::time::timeout(Duration::from_secs(10), async {
        let mut tick = tokio::time::interval(Duration::from_millis(20));
        loop {
            tick.tick().await;
            let history = provider
                .read("provider-live-signal")
                .await
                .expect("read live signal history");
            if history
                .iter()
                .any(|e| matches!(e.kind, EventKind::ExternalSubscribed { .. }))
            {
                break;
            }
        }
    })
    .await
    .expect("signal subscription never appeared");
    client
        .raise_event("provider-live-signal", "s", "one")
        .await
        .expect("raise first signal");
    tokio::time::timeout(Duration::from_secs(10), async {
        let mut tick = tokio::time::interval(Duration::from_millis(20));
        loop {
            tick.tick().await;
            let history = provider
                .read("provider-live-signal")
                .await
                .expect("read replacement signal binding");
            if history
                .iter()
                .filter(|event| matches!(&event.kind, EventKind::ExternalSubscribed { name } if name == "s"))
                .count()
                >= 2
            {
                break;
            }
        }
    })
    .await
    .expect("replacement signal subscription never appeared");
    client
        .raise_event("provider-live-signal", "s", "two")
        .await
        .expect("raise second signal");
    let result = client
        .wait_for_orchestration("provider-live-signal", Duration::from_secs(10))
        .await;
    runtime.shutdown(None).await;
    let output = match result.unwrap_or_else(|error| {
        panic!("live signal race did not finish after both subscriptions were bound: {error:?}")
    }) {
        OrchestrationStatus::Completed { output, .. } => output,
        other => panic!("live signal race failed: {other:?}"),
    };
    let history = provider
        .read("provider-live-signal")
        .await
        .expect("read recorded live signal turns");
    // Terminal histories short-circuit to Continue. Replay the recorded body
    // without its terminal marker, as the runtime would before completion.
    let history: Vec<_> = history
        .into_iter()
        .filter(|event| !matches!(event.kind, EventKind::OrchestrationCompleted { .. }))
        .collect();
    for _ in 0..2 {
        let mut engine =
            crate::runtime::replay_engine::ReplayEngine::new("provider-live-signal".into(), 1, history.clone());
        let result = engine.execute_orchestration(
            handler.clone(),
            "".into(),
            "LiveSignalRace".into(),
            "1.0.0".into(),
            "validation",
        );
        assert!(
            matches!(result, crate::runtime::replay_engine::TurnResult::Completed(ref value) if *value == output),
            "provider live/replay differs: {result:?}, live={output}, history={history:?}"
        );
        assert!(engine.history_delta().is_empty(), "replay appended history");
    }
}

/// A fetched 0.1.30 execution must take a legacy decision that differs from the new policy.
pub async fn test_legacy_queue_race_decision_preserved<F: ProviderFactory>(factory: &F) {
    use crate::runtime::replay_engine::{ReplayEngine, TurnResult};
    for stamp in ["0.1.30", "0.1.31"] {
        let provider = factory.create_provider().await;
        let instance = format!("provider-legacy-decision-{stamp}");
        let registry = OrchestrationRegistry::builder()
            .register("LegacyCompetition", |ctx: OrchestrationContext, _: String| async move {
                let first = ctx.dequeue_event("q");
                let second = ctx.dequeue_event("q");
                let t0 = ctx.schedule_timer(Duration::from_secs(30));
                let t1 = ctx.schedule_timer(Duration::from_secs(60));
                let _ = ctx.select2(first, t0).await;
                let value = match ctx.select2(second, t1).await {
                    crate::Either2::First(value) => value,
                    crate::Either2::Second(()) => "second-timeout".into(),
                };
                ctx.schedule_activity("checkpoint", &value).await?;
                Ok(value)
            })
            .build();
        let handler = registry
            .resolve_handler("LegacyCompetition")
            .expect("registered competition handler")
            .1;
        let mut start = Event::with_event_id(
            1,
            &instance,
            1,
            None,
            EventKind::OrchestrationStarted {
                name: "LegacyCompetition".into(),
                version: "1.0.0".into(),
                input: "".into(),
                parent_instance: None,
                parent_id: None,
                parent_execution_id: None,
                carry_forward_events: None,
                initial_custom_status: None,
            },
        );
        start.duroxide_version = stamp.into();
        let mut engine = ReplayEngine::new(instance.clone(), 1, vec![start.clone()]);
        assert!(matches!(
            engine.execute_orchestration(
                handler.clone(),
                "".into(),
                "LegacyCompetition".into(),
                "1.0.0".into(),
                "validation"
            ),
            TurnResult::Continue
        ));
        let mut history = vec![start];
        history.extend_from_slice(engine.history_delta());
        // Timer completions must already be visible in the provider's queue.
        // Matching checks the schedule identity, not its wall-clock deadline.
        for event in &mut history {
            if let EventKind::TimerCreated { fire_at_ms } = &mut event.kind {
                *fire_at_ms = 1;
            }
        }
        let timers: Vec<_> = history
            .iter()
            .filter_map(|e| {
                if let EventKind::TimerCreated { fire_at_ms } = e.kind {
                    Some(WorkItem::TimerFired {
                        instance: instance.clone(),
                        execution_id: 1,
                        id: e.event_id(),
                        fire_at_ms,
                    })
                } else {
                    None
                }
            })
            .collect();
        assert_eq!(timers.len(), 2);
        provider
            .enqueue_for_orchestrator(start_item(&instance), None)
            .await
            .expect("seed competition");
        let (_, lock, _) = provider
            .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
            .await
            .expect("fetch competition seed")
            .expect("missing competition seed");
        provider
            .ack_orchestration_item(
                &lock,
                1,
                history,
                vec![],
                vec![
                    timers[0].clone(),
                    WorkItem::QueueMessage {
                        instance: instance.clone(),
                        name: "q".into(),
                        data: "first".into(),
                    },
                    timers[1].clone(),
                ],
                ExecutionMetadata {
                    orchestration_name: Some("LegacyCompetition".into()),
                    orchestration_version: Some("1.0.0".into()),
                    ..Default::default()
                },
                vec![],
            )
            .await
            .expect("persist competition prefix");
        let (fetched, lock, _) = provider
            .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None)
            .await
            .expect("fetch competition prefix")
            .expect("missing competition turn");
        assert_eq!(
            fetched.history[0].duroxide_version, stamp,
            "fetch path changed the execution policy"
        );
        let mut turn = ReplayEngine::new(instance.clone(), 1, fetched.history.clone());
        turn.prep_completions(fetched.messages);
        let live = turn.execute_orchestration(
            handler,
            "".into(),
            "LegacyCompetition".into(),
            "1.0.0".into(),
            "validation",
        );
        assert!(
            matches!(live, TurnResult::Continue),
            "competition evaluation failed: {live:?}"
        );
        let checkpoint = turn
            .history_delta()
            .iter()
            .find_map(|event| match &event.kind {
                EventKind::ActivityScheduled { name, .. } if name == "checkpoint" => Some(event.event_id()),
                _ => None,
            })
            .expect("competition did not schedule checkpoint");
        provider
            .ack_orchestration_item(
                &lock,
                1,
                turn.history_delta().to_vec(),
                vec![],
                vec![WorkItem::ActivityCompleted {
                    instance: instance.clone(),
                    execution_id: 1,
                    id: checkpoint,
                    result: "ok".into(),
                }],
                ExecutionMetadata::default(),
                vec![],
            )
            .await
            .expect("persist fetched competition decisions");
        let runtime = Runtime::start_with_options(
            provider.clone(),
            ActivityRegistry::builder()
                .register("checkpoint", |_: crate::ActivityContext, input: String| async move {
                    Ok(input)
                })
                .build(),
            registry,
            RuntimeOptions::default(),
        )
        .await;
        let result = Client::new(provider.clone())
            .wait_for_orchestration(&instance, Duration::from_secs(10))
            .await;
        let history = provider
            .read(&instance)
            .await
            .expect("read competition diagnostic history");
        runtime.shutdown(None).await;
        let result = result
            .unwrap_or_else(|error| panic!("{stamp}: competition did not finish: {error:?}, history={history:?}"));
        let expected = if stamp == "0.1.30" { "second-timeout" } else { "first" };
        assert!(
            matches!(result,OrchestrationStatus::Completed{ref output,..}if output==expected),
            "{stamp}: legacy-discriminating competition returned {result:?}"
        );
    }
}