skilj 0.2.0

Event sourcing on Postgres with Dynamic Consistency Boundaries: consistency per command instead of per aggregate, with GraphQL and REST APIs generated from your types.
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
//! End-to-end proof of issue #20's native one-shot, per-entity
//! deadline mechanism (`skilj_core::plugin::ScheduleDeadline`/
//! `CancelDeadline`): a real `OrderPlaced` event, directly created,
//! schedules a deadline via the background poll task
//! `SkiljBuilder::build()` spawns for it; that deadline either fires a
//! real `CancelOrder` command once due, or never does when a same-tagged
//! `OrderPaid` event cancels it first - proof the wiring from
//! `skilj_core::db::catch_up_schedule_deadline`/`catch_up_cancel_deadline`/
//! `fire_due_deadlines` all the way through `SkiljBuilder::schedule_deadline::<S>()`/
//! `.cancel_deadline::<C>()` is real and running, not just the
//! persistence layer in isolation. Same `DATABASE_URL`-then-embedded-
//! Postgres-then-skip harness as `skilj/tests/cross_context_route.rs` -
//! see its own doc comment for the details, not repeated a third time
//! here.
//!
//! One bounded context, one test function, three orders as sub-scenarios,
//! the same "several sub-scenarios in one shared harness" shape
//! `cross_context_route.rs`'s own main test already uses. Chosen here to
//! keep this file's own share of the pre-existing embedded-Postgres
//! connection-pool pressure (see `CONTRIBUTING.md`) as small as
//! reasonably possible: every additional `#[test]` fn builds its own
//! `Skilj` instance, and this feature alone adds three more perpetual
//! background poll tasks per instance on top of the five every other
//! test file's instance already carries.
//!
//! **Not covered here**: a dedicated crash/redelivery simulation proving
//! `ON CONFLICT (id) DO NOTHING` makes a redelivered schedule-catch-up
//! tick a safe no-op. That property is structural, not incidental - the
//! identical mechanism (a deterministic id/idempotency key,
//! `Deduplicated` handled as a warning not an error) `CrossContextRoute`
//! already relies on and which docs/architecture.md §36/§37 reasoned
//! about at length - and `cross_context_route.rs`'s own three tests don't
//! carry a dedicated crash-simulation test for it either, for the same
//! reason this file doesn't: the black-box, full-`Skilj` harness every
//! test file here uses has no fault-injection hook to force a real
//! redelivery, only ever exercising the ordinary, non-redelivered path.

use axum::body::Body;
use axum::http::{Request, StatusCode};
use chrono::{SubsecRound, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use skilj::{CancelDeadline, CommandType, EventType, Projection, ScheduleDeadline, Skilj};
use skilj_core::access_control::{self, AccessLevel, Role, RoleAccessMapping, RoleStatus};
use skilj_core::bootstrap::ContextCreator;
use skilj_core::db::{self, Pool};
use skilj_core::event_store::{BoundedContext, BoundedContextStatus, Event};
use skilj_core::plugin::{BoundedContextEvent, DeadlineSpec};
use skilj_core::shared::{
    generate_token_id, generate_token_secret, CommandDecision, EventSpec, Tag,
};
use tower::ServiceExt;

const ORDERS_BOUNDED_CONTEXT: &str = "skilj_deadlines_test_orders";

// --- source events ---

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct OrderPlacedPayload {
    order_id: String,
    deadline_at: chrono::DateTime<chrono::Utc>,
    /// Exercises `ScheduleOrderCancelDeadline::schedule` returning
    /// `None` (the occurrence this schedule itself decided doesn't
    /// apply) when `false` - `ScheduleReminderDeadline` below ignores
    /// this field entirely and always schedules its own reminder
    /// regardless, proving one schedule's own skip has no bearing on a
    /// sibling schedule reacting to the identical event.
    schedule_cancel_deadline: bool,
}

struct OrderPlaced;

impl EventType for OrderPlaced {
    type Payload = OrderPlacedPayload;
    const NAME: &'static str = "OrderPlaced";
    const BOUNDED_CONTEXT: &'static str = ORDERS_BOUNDED_CONTEXT;
    fn direct_creation_allowed() -> bool {
        true
    }
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct OrderPaidPayload {
    order_id: String,
}

struct OrderPaid;

impl EventType for OrderPaid {
    type Payload = OrderPaidPayload;
    const NAME: &'static str = "OrderPaid";
    const BOUNDED_CONTEXT: &'static str = ORDERS_BOUNDED_CONTEXT;
    fn direct_creation_allowed() -> bool {
        true
    }
}

// --- fired commands + the events they produce ---

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct CancelOrderPayload {
    order_id: String,
}

struct CancelOrder;

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct OrderCancelledPayload {
    order_id: String,
}

struct OrderCancelled;

impl EventType for OrderCancelled {
    type Payload = OrderCancelledPayload;
    const NAME: &'static str = "OrderCancelled";
    const BOUNDED_CONTEXT: &'static str = ORDERS_BOUNDED_CONTEXT;
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct SendReminderPayload {
    order_id: String,
}

struct SendReminder;

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct ReminderSentPayload {
    order_id: String,
}

struct ReminderSent;

impl EventType for ReminderSent {
    type Payload = ReminderSentPayload;
    const NAME: &'static str = "ReminderSent";
    const BOUNDED_CONTEXT: &'static str = ORDERS_BOUNDED_CONTEXT;
}

enum OrdersEvent {
    OrderCancelled(OrderCancelledPayload),
    ReminderSent(ReminderSentPayload),
}

impl BoundedContextEvent for OrdersEvent {
    fn try_from_event(event: &Event) -> Option<Result<Self, serde_json::Error>> {
        match event.event_type.name.as_str() {
            "OrderCancelled" => {
                Some(serde_json::from_str(&event.payload).map(OrdersEvent::OrderCancelled))
            }
            "ReminderSent" => {
                Some(serde_json::from_str(&event.payload).map(OrdersEvent::ReminderSent))
            }
            _ => None,
        }
    }
}

impl CommandType for CancelOrder {
    type Payload = CancelOrderPayload;
    type Event = OrdersEvent;
    const NAME: &'static str = "CancelOrder";
    const BOUNDED_CONTEXT: &'static str = ORDERS_BOUNDED_CONTEXT;
    fn decide(payload: &Self::Payload, _matching_events: &[Self::Event]) -> CommandDecision {
        CommandDecision::Accepted {
            events: vec![EventSpec {
                event_type: "OrderCancelled".to_string(),
                payload: serde_json::json!({ "order_id": payload.order_id }),
            }],
        }
    }
}

impl CommandType for SendReminder {
    type Payload = SendReminderPayload;
    type Event = OrdersEvent;
    const NAME: &'static str = "SendReminder";
    const BOUNDED_CONTEXT: &'static str = ORDERS_BOUNDED_CONTEXT;
    fn decide(payload: &Self::Payload, _matching_events: &[Self::Event]) -> CommandDecision {
        CommandDecision::Accepted {
            events: vec![EventSpec {
                event_type: "ReminderSent".to_string(),
                payload: serde_json::json!({ "order_id": payload.order_id }),
            }],
        }
    }
}

// --- projections ---

#[derive(Debug, Default, Serialize, Deserialize, JsonSchema)]
struct OrderCancellationsState {
    cancelled_order_ids: Vec<String>,
}

/// `sync: true` - the assertions below are already only waiting on the
/// deadline background tasks' own poll cycles; no reason to also make
/// them wait on a second, independent projection poll task on top (same
/// reasoning `cross_context_route.rs`'s own `ReservedTotal` gives).
struct OrderCancellations;

impl Projection for OrderCancellations {
    type State = OrderCancellationsState;
    type Event = OrdersEvent;
    const NAME: &'static str = "OrderCancellations";
    const BOUNDED_CONTEXT: &'static str = ORDERS_BOUNDED_CONTEXT;
    fn consumed_event_types() -> Vec<&'static str> {
        vec!["OrderCancelled"]
    }
    fn sync() -> bool {
        true
    }
    fn project(state: &mut Self::State, event: &Self::Event, _key: &str) {
        if let OrdersEvent::OrderCancelled(payload) = event {
            state.cancelled_order_ids.push(payload.order_id.clone());
        }
    }
}

#[derive(Debug, Default, Serialize, Deserialize, JsonSchema)]
struct RemindersSentState {
    reminded_order_ids: Vec<String>,
}

struct RemindersSent;

impl Projection for RemindersSent {
    type State = RemindersSentState;
    type Event = OrdersEvent;
    const NAME: &'static str = "RemindersSent";
    const BOUNDED_CONTEXT: &'static str = ORDERS_BOUNDED_CONTEXT;
    fn consumed_event_types() -> Vec<&'static str> {
        vec!["ReminderSent"]
    }
    fn sync() -> bool {
        true
    }
    fn project(state: &mut Self::State, event: &Self::Event, _key: &str) {
        if let OrdersEvent::ReminderSent(payload) = event {
            state.reminded_order_ids.push(payload.order_id.clone());
        }
    }
}

// --- the deadline reactors themselves ---

fn order_tag(order_id: &str) -> Tag {
    Tag {
        key: "order".to_string(),
        value: Some(order_id.to_string()),
    }
}

struct ScheduleOrderCancelDeadline;

impl ScheduleDeadline for ScheduleOrderCancelDeadline {
    type Source = OrderPlaced;
    type Target = CancelOrder;
    const NAME: &'static str = "ScheduleOrderCancelDeadline";
    fn schedule(source_payload: &OrderPlacedPayload) -> Option<DeadlineSpec<CancelOrderPayload>> {
        if !source_payload.schedule_cancel_deadline {
            return None;
        }
        Some(DeadlineSpec {
            fire_at: source_payload.deadline_at,
            expires_at: None,
            tags: vec![order_tag(&source_payload.order_id)],
            payload: CancelOrderPayload {
                order_id: source_payload.order_id.clone(),
            },
            recurrence: None,
        })
    }
}

/// Shares `order_tag(...)` with `ScheduleOrderCancelDeadline` above -
/// deliberately, to prove `CancelDeadline::Deadline`'s own
/// `schedule_name` scoping: cancelling one schedule's rows for a given
/// tag must never touch a different schedule's own rows for that
/// identical tag.
struct ScheduleReminderDeadline;

impl ScheduleDeadline for ScheduleReminderDeadline {
    type Source = OrderPlaced;
    type Target = SendReminder;
    const NAME: &'static str = "ScheduleReminderDeadline";
    fn schedule(source_payload: &OrderPlacedPayload) -> Option<DeadlineSpec<SendReminderPayload>> {
        Some(DeadlineSpec {
            fire_at: source_payload.deadline_at,
            expires_at: None,
            tags: vec![order_tag(&source_payload.order_id)],
            payload: SendReminderPayload {
                order_id: source_payload.order_id.clone(),
            },
            recurrence: None,
        })
    }
}

struct CancelOrderDeadlineOnPaid;

impl CancelDeadline for CancelOrderDeadlineOnPaid {
    type Source = OrderPaid;
    type Deadline = ScheduleOrderCancelDeadline;
    const NAME: &'static str = "CancelOrderDeadlineOnPaid";
    fn cancel_tags(source_payload: &OrderPaidPayload) -> Option<Vec<Tag>> {
        Some(vec![order_tag(&source_payload.order_id)])
    }
}

// --- provisioning: DATABASE_URL, else embedded Postgres, else skip ---
// (identical shape to `cross_context_route.rs`'s own harness - see that
// file's doc comment)

struct TestDb {
    database_url: String,
    pool: Pool,
}

static TEST_DB: tokio::sync::OnceCell<Option<TestDb>> = tokio::sync::OnceCell::const_new();

fn runtime() -> &'static tokio::runtime::Runtime {
    static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
    RUNTIME.get_or_init(|| {
        tokio::runtime::Runtime::new().expect("failed to build a tokio runtime for deadline tests")
    })
}

async fn test_db() -> Option<(String, Pool)> {
    TEST_DB
        .get_or_init(provision)
        .await
        .as_ref()
        .map(|db| (db.database_url.clone(), db.pool.clone()))
}

async fn connect_and_migrate(database_url: &str, label: &str) -> Option<Pool> {
    let pool = match db::connect(database_url).await {
        Ok(pool) => pool,
        Err(e) => {
            eprintln!("skipping: connecting to {label} failed: {e}");
            return None;
        }
    };
    if let Err(e) = db::migrate(&pool).await {
        eprintln!("skipping: migrating {label} failed: {e}");
        return None;
    }
    Some(pool)
}

async fn provision() -> Option<TestDb> {
    let database_url = skilj_test_support::database_url("skilj_deadlines_e2e_test").await?;

    let pool = connect_and_migrate(&database_url, "the test database").await?;
    Some(TestDb { database_url, pool })
}

/// Held by every test in this file for its whole run. Each `Skilj` built
/// here runs a background deadline tick - at least the one it runs straight
/// away - and that tick scans *every* bounded context in the shared test
/// database, so while one test's `Skilj` is ticking, another test's due
/// deadline can be claimed out from under it (seen as a deadline left
/// `firing` instead of `fired`). Run one at a time, each stopping its
/// `Skilj` before it lets go, no test sees another's ticks
/// (docs/architecture.md §146).
static ONE_DEADLINE_TEST_AT_A_TIME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

/// A built `Skilj`'s dispatchers, with its background tasks stopped - for
/// a test that fires deadlines with its own ticks. An hour-long interval
/// isn't enough on its own: the background deadline task ticks once
/// straight away, on a spawned task that can run late, after the test has
/// inserted a due deadline (docs/architecture.md §146). `shutdown` waits
/// for that tick to finish.
async fn dispatchers_without_background_ticks(
    skilj: Skilj,
) -> (
    std::sync::Arc<dyn skilj_core::plugin::CommandDispatcher>,
    std::sync::Arc<dyn skilj_core::plugin::ProjectionDispatcher>,
    std::sync::Arc<dyn skilj_core::plugin::SnapshotDispatcher>,
) {
    let dispatchers = (
        skilj.command_dispatcher(),
        skilj.projection_dispatcher(),
        skilj.snapshot_dispatcher(),
    );
    skilj.shutdown(std::time::Duration::from_secs(20)).await;
    dispatchers
}

fn unique_name(prefix: &str) -> String {
    format!("{prefix}_{}", generate_token_id())
}

fn test_now() -> chrono::DateTime<Utc> {
    Utc::now().trunc_subsecs(6)
}

async fn create_direct_event(
    router: &axum::Router,
    credential: &str,
    payload: serde_json::Value,
) -> StatusCode {
    let body = serde_json::to_vec(&serde_json::json!({ "payload": payload })).unwrap();
    let request = Request::builder()
        .method("POST")
        .uri("/v1/events/direct")
        .header("authorization", format!("Bearer {credential}"))
        .header("content-type", "application/json")
        .body(Body::from(body))
        .unwrap();
    let response = router.clone().oneshot(request).await.unwrap();
    response.status()
}

#[test]
fn a_deadline_fires_when_due_and_never_fires_once_cancelled_by_tag() {
    runtime().block_on(async {
        let _one_at_a_time = ONE_DEADLINE_TEST_AT_A_TIME.lock().await;
        let Some((database_url, pool)) = test_db().await else {
            return;
        };

        let external_subject = unique_name("subject");
        let role = Role {
            id: generate_token_id(),
            external_subject: external_subject.clone(),
            name: "Reconciliation Role".to_string(),
            superadmin: false,
            status: RoleStatus::Active,
            created_at: test_now(),
            revoked_at: None,
        };
        db::insert_role(&pool, &role).await.unwrap();

        let orders_bc = BoundedContext {
            name: ORDERS_BOUNDED_CONTEXT.to_string(),
            status: BoundedContextStatus::Active,
            created_at: test_now(),
            created_by: ContextCreator::SystemCreator,
            template: None,
        };
        db::insert_bounded_context(&pool, &orders_bc).await.unwrap();

        let orders_mapping = RoleAccessMapping {
            role: role.clone(),
            bounded_context: orders_bc.clone(),
            level: AccessLevel::Admin,
            can_read_sensitive: false,
            scope: None,
            capabilities: Default::default(),
            delegable: Default::default(),
            status: RoleStatus::Active,
            created_at: test_now(),
            revoked_at: None,
        };
        db::insert_role_access_mapping(&pool, &orders_mapping)
            .await
            .unwrap();

        let (skilj, report) = Skilj::builder(database_url)
            .bounded_context(ORDERS_BOUNDED_CONTEXT)
            .event_type::<OrderPlaced>()
            .event_type::<OrderPaid>()
            .event_type::<OrderCancelled>()
            .event_type::<ReminderSent>()
            .command_type::<CancelOrder>()
            .command_type::<SendReminder>()
            .projection::<OrderCancellations>()
            .projection::<RemindersSent>()
            .schedule_deadline::<ScheduleOrderCancelDeadline>()
            .cancel_deadline::<CancelOrderDeadlineOnPaid>()
            .schedule_deadline::<ScheduleReminderDeadline>()
            .deadline_poll_interval(std::time::Duration::from_millis(30))
            .reconciliation_role(external_subject)
            .build()
            .await
            .unwrap();
        assert_eq!(report.skipped_no_access, Vec::<String>::new());

        let order_placed_type = db::get_event_type(&pool, ORDERS_BOUNDED_CONTEXT, "OrderPlaced")
            .await
            .unwrap()
            .unwrap();
        let order_placed_token = access_control::create_direct_creation_token(
            &orders_mapping,
            &order_placed_type,
            generate_token_id(),
            generate_token_secret(),
            None,
            test_now(),
        )
        .unwrap();
        db::insert_direct_creation_token(&pool, &order_placed_token)
            .await
            .unwrap();
        let order_placed_credential =
            format!("{}.{}", order_placed_token.id, order_placed_token.secret);

        let order_paid_type = db::get_event_type(&pool, ORDERS_BOUNDED_CONTEXT, "OrderPaid")
            .await
            .unwrap()
            .unwrap();
        let order_paid_token = access_control::create_direct_creation_token(
            &orders_mapping,
            &order_paid_type,
            generate_token_id(),
            generate_token_secret(),
            None,
            test_now(),
        )
        .unwrap();
        db::insert_direct_creation_token(&pool, &order_paid_token)
            .await
            .unwrap();
        let order_paid_credential = format!("{}.{}", order_paid_token.id, order_paid_token.secret);

        let router = skilj.rest_router();

        // Three orders, one shared deadline window (`deadline_at`, 300ms
        // out - several multiples of the 30ms poll interval above, so
        // every background task gets several ticks' worth of margin on
        // both sides of it):
        //
        //   order-A: paid immediately, before its own deadline - the
        //     `CancelOrder` deadline must be cancelled and must never
        //     fire, but the *reminder* deadline (a different schedule,
        //     sharing the identical `order` tag) must still fire -
        //     `CancelDeadline::Deadline`'s own scoping at work.
        //   order-B: never paid - its `CancelOrder` deadline fires
        //     normally, same as its reminder.
        //   order-C: `schedule_cancel_deadline: false` - `ScheduleOrderCancelDeadline::schedule`
        //     itself decides this occurrence doesn't apply, so no
        //     `CancelOrder` deadline is ever scheduled at all; its
        //     reminder still fires, unaffected by the sibling schedule's
        //     own skip.
        let deadline_at = test_now() + chrono::Duration::milliseconds(300);

        for (order_id, schedule_cancel_deadline) in
            [("order-A", true), ("order-B", true), ("order-C", false)]
        {
            let status = create_direct_event(
                &router,
                &order_placed_credential,
                serde_json::json!({
                    "order_id": order_id,
                    "deadline_at": deadline_at,
                    "schedule_cancel_deadline": schedule_cancel_deadline,
                }),
            )
            .await;
            assert_eq!(status, StatusCode::CREATED);
        }

        let status = create_direct_event(
            &router,
            &order_paid_credential,
            serde_json::json!({ "order_id": "order-A" }),
        )
        .await;
        assert_eq!(status, StatusCode::CREATED);

        // Wait for every reminder to have fired - the longest-running
        // path here (it never gets cancelled for any of the three
        // orders), so once it's settled, `deadline_at` plus many poll
        // intervals' worth of margin has also long since passed for the
        // `CancelOrder` deadlines, making the negative assertions below
        // (order-A and order-C must never appear as cancelled)
        // meaningful rather than merely "didn't wait long enough."
        let mut reminders: Vec<String> = Vec::new();
        for _ in 0..80 {
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
            let state =
                db::get_projection_state(&pool, ORDERS_BOUNDED_CONTEXT, "RemindersSent", "")
                    .await
                    .unwrap();
            if let Some(state) = state {
                let parsed: RemindersSentState = serde_json::from_str(&state).unwrap();
                reminders = parsed.reminded_order_ids;
                if reminders.len() >= 3 {
                    break;
                }
            }
        }
        reminders.sort();
        assert_eq!(
            reminders,
            vec![
                "order-A".to_string(),
                "order-B".to_string(),
                "order-C".to_string()
            ],
            "every order's own reminder deadline must fire, regardless of what happened to its \
             (differently-scheduled) CancelOrder deadline"
        );

        // Polled rather than read once: the reminders loop above only waits
        // on `RemindersSent`, and under a loaded machine the
        // `OrderCancellations` projection's own catch-up tick can land a
        // moment later than that one's.
        let mut cancellations_state = None;
        for _ in 0..80 {
            cancellations_state =
                db::get_projection_state(&pool, ORDERS_BOUNDED_CONTEXT, "OrderCancellations", "")
                    .await
                    .unwrap();
            if cancellations_state
                .as_deref()
                .and_then(|s| serde_json::from_str::<OrderCancellationsState>(s).ok())
                .is_some_and(|c| !c.cancelled_order_ids.is_empty())
            {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        let cancellations_state = cancellations_state
            .expect("OrderCancellations projection state never appeared within 2s");
        let cancellations: OrderCancellationsState =
            serde_json::from_str(&cancellations_state).unwrap();
        assert_eq!(
            cancellations.cancelled_order_ids,
            vec!["order-B".to_string()],
            "order-A must have been cancelled by its own OrderPaid event before it came due, \
             and order-C must never have been scheduled at all - only order-B's CancelOrder \
             deadline should ever have fired"
        );
        // docs/architecture.md §162: a resolved deadline keeps no payload -
        // it was the target command's plaintext.
        let resolved: Vec<(String, String)> = sqlx::query_as(sqlx::AssertSqlSafe(format!(
            "SELECT status, payload FROM {}.deadlines WHERE status NOT IN ('pending', 'firing')",
            race_schema(ORDERS_BOUNDED_CONTEXT)
        )))
        .fetch_all(&pool)
        .await
        .unwrap();
        for status in ["fired", "cancelled"] {
            assert!(
                resolved.iter().any(|(s, _)| s == status),
                "no {status} deadline: {resolved:?}"
            );
        }
        for (status, payload) in &resolved {
            assert_eq!(payload, "{}", "a {status} deadline kept its payload");
        }
        // Stopped before the lock is released - see `ONE_DEADLINE_TEST_AT_A_TIME`.
        skilj.shutdown(std::time::Duration::from_secs(20)).await;
    });
}

// --- fire-vs-cancel race regression (issue #25 review,
// docs/architecture.md §55) ---
//
// Deliberately doesn't go through `ScheduleDeadline`/`CancelDeadline` at
// all - the property under test is `db::fire_due_deadlines`'s own
// claim-then-submit ordering against a concurrent `status = 'pending'`-
// guarded cancel, which is exactly `catch_up_cancel_deadline`'s own
// `UPDATE`'s shape regardless of which schedule/tag logic decided to run
// it. A hand-inserted `deadlines` row and a hand-issued cancel `UPDATE`
// exercise that shape directly and deterministically, rather than
// relying on `catch_up_cancel_deadline`'s own background poll tick to
// land inside a race window by chance.

const DEADLINE_RACE_BOUNDED_CONTEXT: &str = "skilj_deadlines_test_race";

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct RaceCommandPayload {
    order_id: String,
}

struct RaceCommand;

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct RaceFiredPayload {
    order_id: String,
}

struct RaceFired;

impl EventType for RaceFired {
    type Payload = RaceFiredPayload;
    const NAME: &'static str = "RaceFired";
    const BOUNDED_CONTEXT: &'static str = DEADLINE_RACE_BOUNDED_CONTEXT;
}

enum RaceEvent {
    RaceFired(RaceFiredPayload),
}

impl BoundedContextEvent for RaceEvent {
    fn try_from_event(event: &Event) -> Option<Result<Self, serde_json::Error>> {
        match event.event_type.name.as_str() {
            "RaceFired" => Some(serde_json::from_str(&event.payload).map(RaceEvent::RaceFired)),
            _ => None,
        }
    }
}

impl CommandType for RaceCommand {
    type Payload = RaceCommandPayload;
    type Event = RaceEvent;
    const NAME: &'static str = "RaceCommand";
    const BOUNDED_CONTEXT: &'static str = DEADLINE_RACE_BOUNDED_CONTEXT;
    fn decide(payload: &Self::Payload, _matching_events: &[Self::Event]) -> CommandDecision {
        CommandDecision::Accepted {
            events: vec![EventSpec {
                event_type: "RaceFired".to_string(),
                payload: serde_json::json!({ "order_id": payload.order_id }),
            }],
        }
    }
}

#[derive(Debug, Default, Serialize, Deserialize, JsonSchema)]
struct RaceFiredOrdersState {
    order_ids: Vec<String>,
}

/// `sync: true` - the test below reads this state immediately after
/// `fire_due_deadlines` returns, with no poll loop of its own to wait
/// out.
struct RaceFiredOrders;

impl Projection for RaceFiredOrders {
    type State = RaceFiredOrdersState;
    type Event = RaceEvent;
    const NAME: &'static str = "RaceFiredOrders";
    const BOUNDED_CONTEXT: &'static str = DEADLINE_RACE_BOUNDED_CONTEXT;
    fn consumed_event_types() -> Vec<&'static str> {
        vec!["RaceFired"]
    }
    fn sync() -> bool {
        true
    }
    fn project(state: &mut Self::State, event: &Self::Event, _key: &str) {
        let RaceEvent::RaceFired(payload) = event;
        state.order_ids.push(payload.order_id.clone());
    }
}

fn race_schema(bounded_context: &str) -> String {
    format!("\"bc_{bounded_context}\"")
}

#[test]
fn fire_due_deadlines_never_lets_a_claimed_row_also_get_cancelled() {
    runtime().block_on(async {
        let _one_at_a_time = ONE_DEADLINE_TEST_AT_A_TIME.lock().await;
        let Some((database_url, pool)) = test_db().await else {
            return;
        };

        let external_subject = unique_name("subject");
        let role = Role {
            id: generate_token_id(),
            external_subject: external_subject.clone(),
            name: "Reconciliation Role".to_string(),
            superadmin: false,
            status: RoleStatus::Active,
            created_at: test_now(),
            revoked_at: None,
        };
        db::insert_role(&pool, &role).await.unwrap();

        let race_bc = BoundedContext {
            name: DEADLINE_RACE_BOUNDED_CONTEXT.to_string(),
            status: BoundedContextStatus::Active,
            created_at: test_now(),
            created_by: ContextCreator::SystemCreator,
            template: None,
        };
        db::insert_bounded_context(&pool, &race_bc).await.unwrap();

        let race_mapping = RoleAccessMapping {
            role: role.clone(),
            bounded_context: race_bc.clone(),
            level: AccessLevel::Admin,
            can_read_sensitive: false,
            scope: None,
            capabilities: Default::default(),
            delegable: Default::default(),
            status: RoleStatus::Active,
            created_at: test_now(),
            revoked_at: None,
        };
        db::insert_role_access_mapping(&pool, &race_mapping)
            .await
            .unwrap();

        let (skilj, report) = Skilj::builder(database_url)
            // Only this test's own ticks fire deadlines: the background one
            // scans every bounded context and would race them - stopped
            // below (`dispatchers_without_background_ticks`).
            .deadline_poll_interval(std::time::Duration::from_secs(3600))
            .bounded_context(DEADLINE_RACE_BOUNDED_CONTEXT)
            .event_type::<RaceFired>()
            .command_type::<RaceCommand>()
            .projection::<RaceFiredOrders>()
            .reconciliation_role(external_subject)
            .build()
            .await
            .unwrap();
        assert_eq!(report.skipped_no_access, Vec::<String>::new());
        let (command_dispatcher, projection_dispatcher, snapshot_dispatcher) =
            dispatchers_without_background_ticks(skilj).await;

        // A real due-and-`pending` row, inserted directly - see this
        // section's own doc comment for why `catch_up_schedule_deadline`
        // isn't used to create it here.
        let schema = race_schema(DEADLINE_RACE_BOUNDED_CONTEXT);
        let deadline_id = unique_name("race-deadline");
        let now = test_now();
        sqlx::query(sqlx::AssertSqlSafe(format!(
            "INSERT INTO {schema}.deadlines \
             (id, schedule_name, fire_at, tags, correlation_id, target_bounded_context, \
              target_command_type, payload, status, created_at) \
             VALUES ($1, 'race-schedule', $2, '[]'::jsonb, NULL, $3, $4, $5, 'pending', $6)"
        )))
        .bind(&deadline_id)
        .bind(now - chrono::Duration::seconds(1))
        .bind(DEADLINE_RACE_BOUNDED_CONTEXT)
        .bind(RaceCommand::NAME)
        .bind(serde_json::json!({ "order_id": "race-order" }).to_string())
        .bind(now)
        .execute(&pool)
        .await
        .unwrap();

        let broadcaster = skilj_core::event_store::EventBroadcaster::new(16);
        let event_cache = skilj_core::event_cache::EventCache::new(0);

        // The real `fire_due_deadlines` racing against a hand-issued
        // `UPDATE` shaped exactly like `catch_up_cancel_deadline`'s own
        // cancel - concurrent, via `tokio::join!`, not sequenced with a
        // sleep. Whichever the database's own row-level locking lets win,
        // the assertion below holds either way (see this section's own
        // doc comment) - this isn't a race the test is trying to land
        // inside a narrow window, it's an invariant that must survive
        // either ordering.
        let retry_policy = skilj_retry::RetryPolicy::default();
        let fire = db::fire_due_deadlines(
            &pool,
            &*command_dispatcher,
            &*projection_dispatcher,
            &*snapshot_dispatcher,
            &broadcaster,
            &event_cache,
            DEADLINE_RACE_BOUNDED_CONTEXT,
            now,
            None,
            &retry_policy,
            &[],
        );
        let cancel = sqlx::query(sqlx::AssertSqlSafe(format!(
            "UPDATE {schema}.deadlines SET status = 'cancelled', resolved_at = $1 \
             WHERE id = $2 AND status = 'pending'"
        )))
        .bind(now)
        .bind(&deadline_id)
        .execute(&pool);

        let (fire_result, cancel_result) = tokio::join!(fire, cancel);
        fire_result.unwrap();
        cancel_result.unwrap();

        let (status,): (String,) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
            "SELECT status FROM {schema}.deadlines WHERE id = $1"
        )))
        .bind(&deadline_id)
        .fetch_one(&pool)
        .await
        .unwrap();

        let fired_state =
            db::get_projection_state(&pool, DEADLINE_RACE_BOUNDED_CONTEXT, "RaceFiredOrders", "")
                .await
                .unwrap();
        let command_ran = fired_state
            .map(|s| {
                let parsed: RaceFiredOrdersState = serde_json::from_str(&s).unwrap();
                !parsed.order_ids.is_empty()
            })
            .unwrap_or(false);

        match status.as_str() {
            "cancelled" => assert!(
                !command_ran,
                "the row ended cancelled but its target command still ran - the \
                 fire-vs-cancel race is not closed"
            ),
            "fired" => assert!(
                command_ran,
                "the row ended fired but its target command never actually ran"
            ),
            other => panic!(
                "deadline ended in unexpected status {other:?} - claim/resolve did not \
                 complete on either side of the race"
            ),
        }
    });
}

/// docs/architecture.md §96: a deadline lives in its source bounded
/// context, whose fire tick keeps running - but its target is archived.
/// Archiving stops new commands, so the deadline must be resolved without
/// submitting, not left to be reclaimed and refused every few minutes
/// forever (and, before `process_command` checked, not submitted into the
/// archived context either).
#[test]
fn a_deadline_whose_target_is_archived_resolves_without_submitting() {
    runtime().block_on(async {
        let _one_at_a_time = ONE_DEADLINE_TEST_AT_A_TIME.lock().await;
        let Some((database_url, pool)) = test_db().await else {
            return;
        };
        let external_subject = unique_name("subject");
        let role = Role {
            id: generate_token_id(),
            external_subject: external_subject.clone(),
            name: "Reconciliation Role".to_string(),
            superadmin: false,
            status: RoleStatus::Active,
            created_at: test_now(),
            revoked_at: None,
        };
        db::insert_role(&pool, &role).await.unwrap();
        let mut contexts = Vec::new();
        for prefix in ["source", "target"] {
            let bc = BoundedContext {
                name: unique_name(prefix),
                status: BoundedContextStatus::Active,
                created_at: test_now(),
                created_by: ContextCreator::SystemCreator,
                template: None,
            };
            db::insert_bounded_context(&pool, &bc).await.unwrap();
            db::insert_role_access_mapping(
                &pool,
                &RoleAccessMapping {
                    role: role.clone(),
                    bounded_context: bc.clone(),
                    level: AccessLevel::Admin,
                    can_read_sensitive: false,
                    scope: None,
                    capabilities: Default::default(),
                    delegable: Default::default(),
                    status: RoleStatus::Active,
                    created_at: test_now(),
                    revoked_at: None,
                },
            )
            .await
            .unwrap();
            contexts.push(bc.name);
        }
        let (source, target) = (contexts[0].clone(), contexts[1].clone());

        let (skilj, report) = Skilj::builder(database_url)
            // Only this test's own ticks fire deadlines: the background one
            // scans every bounded context and would race them - stopped
            // below (`dispatchers_without_background_ticks`).
            .deadline_poll_interval(std::time::Duration::from_secs(3600))
            .bounded_context(target.clone())
            .event_type::<RaceFired>()
            .command_type::<RaceCommand>()
            .reconciliation_role(external_subject)
            .build()
            .await
            .unwrap();
        assert_eq!(report.skipped_no_access, Vec::<String>::new());
        let (command_dispatcher, projection_dispatcher, snapshot_dispatcher) =
            dispatchers_without_background_ticks(skilj).await;
        db::update_bounded_context_status(&pool, &target, BoundedContextStatus::Archived)
            .await
            .unwrap();

        let deadline_id = unique_name("deadline");
        let now = test_now();
        sqlx::query(sqlx::AssertSqlSafe(format!(
            "INSERT INTO {}.deadlines \
             (id, schedule_name, fire_at, tags, correlation_id, target_bounded_context, \
              target_command_type, payload, status, created_at) \
             VALUES ($1, 'schedule', $2, '[]'::jsonb, NULL, $3, $4, $5, 'pending', $6)",
            race_schema(&source)
        )))
        .bind(&deadline_id)
        .bind(now - chrono::Duration::seconds(1))
        .bind(&target)
        .bind(RaceCommand::NAME)
        .bind(serde_json::json!({ "order_id": "order-1" }).to_string())
        .bind(now)
        .execute(&pool)
        .await
        .unwrap();

        db::fire_due_deadlines(
            &pool,
            &*command_dispatcher,
            &*projection_dispatcher,
            &*snapshot_dispatcher,
            &skilj_core::event_store::EventBroadcaster::new(16),
            &skilj_core::event_cache::EventCache::new(0),
            &source,
            now,
            None,
            &skilj_retry::RetryPolicy::default(),
            &[],
        )
        .await
        .unwrap();

        let (status,): (String,) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
            "SELECT status FROM {}.deadlines WHERE id = $1",
            race_schema(&source)
        )))
        .bind(&deadline_id)
        .fetch_one(&pool)
        .await
        .unwrap();
        assert_eq!(status, "fired");
        assert!(db::list_events_for_bounded_context(&pool, &target)
            .await
            .unwrap()
            .is_empty());
    });
}

/// docs/architecture.md §115: a deadline whose command fails with an
/// error (here a payload its command can't deserialize) is retried with
/// backoff and then parked - not re-fired every few minutes forever
/// behind a stale `firing` claim, and not allowed to stop the rest of
/// the tick. A valid deadline due right after it still fires.
#[test]
fn a_failing_deadline_is_retried_then_parked_without_blocking_others() {
    runtime().block_on(async {
        let _one_at_a_time = ONE_DEADLINE_TEST_AT_A_TIME.lock().await;
        let Some((database_url, pool)) = test_db().await else {
            return;
        };
        let external_subject = unique_name("subject");
        let role = Role {
            id: generate_token_id(),
            external_subject: external_subject.clone(),
            name: "Reconciliation Role".to_string(),
            superadmin: false,
            status: RoleStatus::Active,
            created_at: test_now(),
            revoked_at: None,
        };
        db::insert_role(&pool, &role).await.unwrap();
        let mut contexts = Vec::new();
        for prefix in ["source", "target"] {
            let bc = BoundedContext {
                name: unique_name(prefix),
                status: BoundedContextStatus::Active,
                created_at: test_now(),
                created_by: ContextCreator::SystemCreator,
                template: None,
            };
            db::insert_bounded_context(&pool, &bc).await.unwrap();
            db::insert_role_access_mapping(
                &pool,
                &RoleAccessMapping {
                    role: role.clone(),
                    bounded_context: bc.clone(),
                    level: AccessLevel::Admin,
                    can_read_sensitive: false,
                    scope: None,
                    capabilities: Default::default(),
                    delegable: Default::default(),
                    status: RoleStatus::Active,
                    created_at: test_now(),
                    revoked_at: None,
                },
            )
            .await
            .unwrap();
            contexts.push(bc.name);
        }
        let (source, target) = (contexts[0].clone(), contexts[1].clone());
        let (skilj, _) = Skilj::builder(database_url)
            // Only this test's own ticks fire deadlines: the background one
            // scans every bounded context and would race them - stopped
            // below (`dispatchers_without_background_ticks`).
            .deadline_poll_interval(std::time::Duration::from_secs(3600))
            .bounded_context(target.clone())
            .event_type::<RaceFired>()
            .command_type::<RaceCommand>()
            .reconciliation_role(external_subject)
            .build()
            .await
            .unwrap();
        let (command_dispatcher, projection_dispatcher, snapshot_dispatcher) =
            dispatchers_without_background_ticks(skilj).await;

        let now = test_now();
        let insert = |id: String, fire_at: chrono::DateTime<Utc>, payload: serde_json::Value| {
            let (pool, source, target) = (pool.clone(), source.clone(), target.clone());
            async move {
                sqlx::query(sqlx::AssertSqlSafe(format!(
                    "INSERT INTO {}.deadlines \
                     (id, schedule_name, fire_at, tags, correlation_id, target_bounded_context, \
                      target_command_type, payload, status, created_at) \
                     VALUES ($1, 'schedule', $2, '[]'::jsonb, NULL, $3, $4, $5, 'pending', $6)",
                    race_schema(&source)
                )))
                .bind(&id)
                .bind(fire_at)
                .bind(&target)
                .bind(RaceCommand::NAME)
                .bind(payload.to_string())
                .bind(now)
                .execute(&pool)
                .await
                .unwrap();
            }
        };
        let failing = unique_name("failing");
        let valid = unique_name("valid");
        insert(
            failing.clone(),
            now - chrono::Duration::seconds(2),
            serde_json::json!({ "not_an_order_id": 1 }),
        )
        .await;
        insert(
            valid.clone(),
            now - chrono::Duration::seconds(1),
            serde_json::json!({ "order_id": "order-1" }),
        )
        .await;
        let status = |id: String| {
            let (pool, source) = (pool.clone(), source.clone());
            async move {
                let (status,): (String,) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
                    "SELECT status FROM {}.deadlines WHERE id = $1",
                    race_schema(&source)
                )))
                .bind(&id)
                .fetch_one(&pool)
                .await
                .unwrap();
                status
            }
        };

        let tick = |at: chrono::DateTime<Utc>| {
            let (pool, source) = (pool.clone(), source.clone());
            let (c, p, s) = (
                command_dispatcher.clone(),
                projection_dispatcher.clone(),
                snapshot_dispatcher.clone(),
            );
            async move {
                db::fire_due_deadlines(
                    &pool,
                    &*c,
                    &*p,
                    &*s,
                    &skilj_core::event_store::EventBroadcaster::new(16),
                    &skilj_core::event_cache::EventCache::new(0),
                    &source,
                    at,
                    None,
                    &skilj_retry::RetryPolicy {
                        initial_backoff: std::time::Duration::from_secs(60),
                        multiplier: 1.0,
                        max_backoff: std::time::Duration::from_secs(60),
                        max_attempts: Some(2),
                        max_elapsed: None,
                    },
                    &[],
                )
                .await
            }
        };

        // First attempt fails: the tick still succeeds, the valid deadline
        // behind it fires, and the failing one waits for its retry.
        tick(now).await.unwrap();
        assert_eq!(status(valid.clone()).await, "fired");
        assert_eq!(status(failing.clone()).await, "pending");

        // Not before its backoff has passed.
        tick(now + chrono::Duration::seconds(30)).await.unwrap();
        assert_eq!(status(failing.clone()).await, "pending");
        assert!(db::list_parked_deliveries(&pool, &target)
            .await
            .unwrap()
            .is_empty());

        // The second attempt exhausts the policy: parked in the target
        // context, redrivable under the deadline's own idempotency key.
        tick(now + chrono::Duration::seconds(61)).await.unwrap();
        assert_eq!(status(failing.clone()).await, "parked");
        let (payload,): (String,) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
            "SELECT payload FROM {}.deadlines WHERE id = $1",
            race_schema(&source)
        )))
        .bind(&failing)
        .fetch_one(&pool)
        .await
        .unwrap();
        assert_eq!(payload, "{}", "a parked deadline kept its payload (§162)");
        let parked = db::list_parked_deliveries(&pool, &target).await.unwrap();
        assert_eq!(parked.len(), 1);
        let parked = &parked[0];
        assert_eq!(parked.kind, db::ParkedDeliveryKind::Deadline);
        assert_eq!(parked.identifier, failing);
        assert_eq!(parked.source, "deadline:schedule");
        assert_eq!(parked.attempt_count, 2);
        assert_eq!(
            parked.target_bounded_context.as_deref(),
            Some(target.as_str())
        );
        assert_eq!(
            parked.target_command_type.as_deref(),
            Some(RaceCommand::NAME)
        );
        assert!(parked.error.contains("order_id"), "{}", parked.error);
        assert_eq!(
            db::parked_delivery_redrive_identity(parked, "unused", None),
            Some((
                db::DEADLINE_CLIENT_ID.to_string(),
                format!("skilj-deadline:{failing}")
            ))
        );

        // Parked is final for the deadline: later ticks leave it alone.
        tick(now + chrono::Duration::hours(1)).await.unwrap();
        assert_eq!(status(failing.clone()).await, "parked");
        assert_eq!(
            db::list_parked_deliveries(&pool, &target)
                .await
                .unwrap()
                .len(),
            1
        );
    });
}

/// An instance that declares no command types at all - an older version,
/// mid rolling deploy, next to one that declares the deadline's target.
struct OlderInstance;

impl skilj_core::plugin::CommandDispatcher for OlderInstance {
    fn dispatch(
        &self,
        _bounded_context: &str,
        _command_type: &str,
        _payload: &str,
        _matching_events: &[skilj_core::event_store::Event],
    ) -> Option<skilj_core::error::Result<skilj_core::shared::CommandDecision>> {
        None
    }
    fn required_role(&self, _: &str, _: &str) -> Option<Option<&'static str>> {
        None
    }
    fn snapshot_name(&self, _: &str, _: &str) -> Option<Option<&'static str>> {
        None
    }
    fn dispatch_from_snapshot(
        &self,
        _bounded_context: &str,
        _command_type: &str,
        _payload: &str,
        _snapshot_state_json: &str,
        _events_since_snapshot: &[skilj_core::event_store::Event],
        _context: &skilj_core::plugin::DecisionContext,
    ) -> Option<skilj_core::error::Result<skilj_core::shared::CommandDecision>> {
        None
    }
}

/// docs/architecture.md §161: an instance that doesn't declare a due
/// deadline's target command type leaves it for one that does - no
/// attempt spent, never parked, however often it's the one to claim it.
/// It used to count as an ordinary failure, so a rolling deploy could
/// park a deadline nothing was wrong with.
#[test]
fn a_deadline_an_instance_cannot_fire_waits_for_one_that_can() {
    runtime().block_on(async {
        let _one_at_a_time = ONE_DEADLINE_TEST_AT_A_TIME.lock().await;
        let Some((database_url, pool)) = test_db().await else {
            return;
        };
        let external_subject = unique_name("subject");
        let role = Role {
            id: generate_token_id(),
            external_subject: external_subject.clone(),
            name: "Reconciliation Role".to_string(),
            superadmin: false,
            status: RoleStatus::Active,
            created_at: test_now(),
            revoked_at: None,
        };
        db::insert_role(&pool, &role).await.unwrap();
        let mut contexts = Vec::new();
        for prefix in ["source", "target"] {
            let bc = BoundedContext {
                name: unique_name(prefix),
                status: BoundedContextStatus::Active,
                created_at: test_now(),
                created_by: ContextCreator::SystemCreator,
                template: None,
            };
            db::insert_bounded_context(&pool, &bc).await.unwrap();
            db::insert_role_access_mapping(
                &pool,
                &RoleAccessMapping {
                    role: role.clone(),
                    bounded_context: bc.clone(),
                    level: AccessLevel::Admin,
                    can_read_sensitive: false,
                    scope: None,
                    capabilities: Default::default(),
                    delegable: Default::default(),
                    status: RoleStatus::Active,
                    created_at: test_now(),
                    revoked_at: None,
                },
            )
            .await
            .unwrap();
            contexts.push(bc.name);
        }
        let (source, target) = (contexts[0].clone(), contexts[1].clone());
        let (skilj, _) = Skilj::builder(database_url)
            .deadline_poll_interval(std::time::Duration::from_secs(3600))
            .bounded_context(target.clone())
            .event_type::<RaceFired>()
            .command_type::<RaceCommand>()
            .reconciliation_role(external_subject)
            .build()
            .await
            .unwrap();
        let (newer, projection_dispatcher, snapshot_dispatcher) =
            dispatchers_without_background_ticks(skilj).await;
        let older: std::sync::Arc<dyn skilj_core::plugin::CommandDispatcher> =
            std::sync::Arc::new(OlderInstance);

        let now = test_now();
        let id = unique_name("deadline");
        sqlx::query(sqlx::AssertSqlSafe(format!(
            "INSERT INTO {}.deadlines \
             (id, schedule_name, fire_at, tags, correlation_id, target_bounded_context, \
              target_command_type, payload, status, created_at) \
             VALUES ($1, 'schedule', $2, '[]'::jsonb, NULL, $3, $4, $5, 'pending', $2)",
            race_schema(&source)
        )))
        .bind(&id)
        .bind(now - chrono::Duration::seconds(1))
        .bind(&target)
        .bind(RaceCommand::NAME)
        .bind(serde_json::json!({ "order_id": "order-1" }).to_string())
        .execute(&pool)
        .await
        .unwrap();
        let state = || {
            let (pool, source, id) = (pool.clone(), source.clone(), id.clone());
            async move {
                let row: (String, i32) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
                    "SELECT status, attempt_count FROM {}.deadlines WHERE id = $1",
                    race_schema(&source)
                )))
                .bind(&id)
                .fetch_one(&pool)
                .await
                .unwrap();
                row
            }
        };
        let tick = |dispatcher: std::sync::Arc<dyn skilj_core::plugin::CommandDispatcher>,
                    at: chrono::DateTime<Utc>| {
            let (pool, source) = (pool.clone(), source.clone());
            let (p, s) = (projection_dispatcher.clone(), snapshot_dispatcher.clone());
            async move {
                db::fire_due_deadlines(
                    &pool,
                    &*dispatcher,
                    &*p,
                    &*s,
                    &skilj_core::event_store::EventBroadcaster::new(16),
                    &skilj_core::event_cache::EventCache::new(0),
                    &source,
                    at,
                    None,
                    // One attempt would park an ordinary failure at once.
                    &skilj_retry::RetryPolicy {
                        initial_backoff: std::time::Duration::from_secs(60),
                        multiplier: 1.0,
                        max_backoff: std::time::Duration::from_secs(60),
                        max_attempts: Some(1),
                        max_elapsed: None,
                    },
                    &[],
                )
                .await
                .unwrap();
            }
        };

        // The older instance claims it three times over: each time it's
        // handed back, with no attempt spent and nothing parked.
        let retry = chrono::Duration::from_std(db::ANOTHER_INSTANCE_RETRY_DELAY).unwrap();
        let mut at = now;
        for _ in 0..3 {
            tick(older.clone(), at).await;
            assert_eq!(state().await, ("pending".to_string(), 0));
            at += retry + chrono::Duration::seconds(1);
        }
        assert!(db::list_parked_deliveries(&pool, &target)
            .await
            .unwrap()
            .is_empty());

        // The instance that declares it fires it.
        tick(newer, at).await;
        assert_eq!(state().await.0, "fired");
    });
}

/// docs/architecture.md §163: `SkiljBuilder::deadline_retention` runs a
/// background task deleting resolved deadlines past it - a pending one
/// stays. Holds `ONE_DEADLINE_TEST_AT_A_TIME` and stops its `Skilj`: with a
/// one-second retention it would delete the other tests' resolved rows.
#[test]
fn resolved_deadlines_are_deleted_after_their_retention() {
    runtime().block_on(async {
        let _one_at_a_time = ONE_DEADLINE_TEST_AT_A_TIME.lock().await;
        let Some((database_url, pool)) = test_db().await else {
            return;
        };
        let bc = BoundedContext {
            name: unique_name("retention"),
            status: BoundedContextStatus::Active,
            created_at: test_now(),
            created_by: ContextCreator::SystemCreator,
            template: None,
        };
        db::insert_bounded_context(&pool, &bc).await.unwrap();
        let old = test_now() - chrono::Duration::hours(1);
        for (id, status, resolved_at) in
            [("fired", "fired", Some(old)), ("pending", "pending", None)]
        {
            sqlx::query(sqlx::AssertSqlSafe(format!(
                "INSERT INTO {}.deadlines \
                 (id, schedule_name, fire_at, tags, target_bounded_context, target_command_type, \
                  payload, status, created_at, resolved_at) \
                 VALUES ($1, 's', $2, '[]'::jsonb, 'x', 'C', '{{}}', $3, $2, $4)",
                race_schema(&bc.name)
            )))
            .bind(id)
            .bind(old)
            .bind(status)
            .bind(resolved_at)
            .execute(&pool)
            .await
            .unwrap();
        }

        let (skilj, _) = Skilj::builder(database_url)
            .deadline_poll_interval(std::time::Duration::from_secs(3600))
            .deadline_retention(std::time::Duration::from_secs(1))
            .build()
            .await
            .unwrap();
        let ids = || {
            let (pool, bc_name) = (pool.clone(), bc.name.clone());
            async move {
                let mut ids: Vec<String> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
                    "SELECT id FROM {}.deadlines",
                    race_schema(&bc_name)
                )))
                .fetch_all(&pool)
                .await
                .unwrap();
                ids.sort();
                ids
            }
        };
        let mut remaining = ids().await;
        for _ in 0..100 {
            if remaining == vec!["pending".to_string()] {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
            remaining = ids().await;
        }
        skilj.shutdown(std::time::Duration::from_secs(20)).await;
        assert_eq!(remaining, vec!["pending".to_string()]);
    });
}

/// issue #98: a deadline whose target command type requires
/// approval must not submit it - it becomes a pending proposal, the same as
/// a REST or GraphQL submission would. Otherwise whoever can cause the
/// scheduling event gets the command executed without an approver. A
/// re-fire of the same deadline (a crash between proposing and marking the
/// row fired) finds the same proposal by its reserved idempotency key
/// rather than proposing twice.
#[test]
fn a_deadline_targeting_an_approval_required_command_proposes_it() {
    runtime().block_on(async {
        let _one_at_a_time = ONE_DEADLINE_TEST_AT_A_TIME.lock().await;
        let Some((database_url, pool)) = test_db().await else {
            return;
        };
        let external_subject = unique_name("subject");
        let role = Role {
            id: generate_token_id(),
            external_subject: external_subject.clone(),
            name: "Reconciliation Role".to_string(),
            superadmin: false,
            status: RoleStatus::Active,
            created_at: test_now(),
            revoked_at: None,
        };
        db::insert_role(&pool, &role).await.unwrap();
        let mut contexts = Vec::new();
        for prefix in ["source", "target"] {
            let bc = BoundedContext {
                name: unique_name(prefix),
                status: BoundedContextStatus::Active,
                created_at: test_now(),
                created_by: ContextCreator::SystemCreator,
                template: None,
            };
            db::insert_bounded_context(&pool, &bc).await.unwrap();
            db::insert_role_access_mapping(
                &pool,
                &RoleAccessMapping {
                    role: role.clone(),
                    bounded_context: bc.clone(),
                    level: AccessLevel::Admin,
                    can_read_sensitive: false,
                    scope: None,
                    capabilities: Default::default(),
                    delegable: Default::default(),
                    status: RoleStatus::Active,
                    created_at: test_now(),
                    revoked_at: None,
                },
            )
            .await
            .unwrap();
            contexts.push(bc.name);
        }
        let (source, target) = (contexts[0].clone(), contexts[1].clone());

        let (skilj, report) = Skilj::builder(database_url)
            .deadline_poll_interval(std::time::Duration::from_secs(3600))
            .bounded_context(target.clone())
            .event_type::<RaceFired>()
            .command_type::<RaceCommand>()
            .reconciliation_role(external_subject)
            .build()
            .await
            .unwrap();
        assert_eq!(report.skipped_no_access, Vec::<String>::new());
        let (command_dispatcher, projection_dispatcher, snapshot_dispatcher) =
            dispatchers_without_background_ticks(skilj).await;
        let policy = skilj_core::approvals::CommandApprovalPolicy::new(None, None);
        db::set_command_approval_policy(&pool, &target, RaceCommand::NAME, Some(&policy))
            .await
            .unwrap();

        let deadline_id = unique_name("deadline");
        let now = test_now();
        sqlx::query(sqlx::AssertSqlSafe(format!(
            "INSERT INTO {}.deadlines \
             (id, schedule_name, fire_at, tags, correlation_id, target_bounded_context, \
              target_command_type, payload, status, created_at) \
             VALUES ($1, 'schedule', $2, '[]'::jsonb, NULL, $3, $4, $5, 'pending', $6)",
            race_schema(&source)
        )))
        .bind(&deadline_id)
        .bind(now - chrono::Duration::seconds(1))
        .bind(&target)
        .bind(RaceCommand::NAME)
        .bind(serde_json::json!({ "order_id": "order-1" }).to_string())
        .bind(now)
        .execute(&pool)
        .await
        .unwrap();

        let broadcaster = skilj_core::event_store::EventBroadcaster::new(16);
        let event_cache = skilj_core::event_cache::EventCache::new(0);
        let retry_policy = skilj_retry::RetryPolicy::default();
        let fire = || {
            db::fire_due_deadlines(
                &pool,
                &*command_dispatcher,
                &*projection_dispatcher,
                &*snapshot_dispatcher,
                &broadcaster,
                &event_cache,
                &source,
                now,
                None,
                &retry_policy,
                &[],
            )
        };
        fire().await.unwrap();

        let deadline_status = || async {
            let (status,): (String,) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
                "SELECT status FROM {}.deadlines WHERE id = $1",
                race_schema(&source)
            )))
            .bind(&deadline_id)
            .fetch_one(&pool)
            .await
            .unwrap();
            status
        };
        assert_eq!(deadline_status().await, "fired");
        assert!(
            db::list_events_for_bounded_context(&pool, &target)
                .await
                .unwrap()
                .is_empty(),
            "an approval-required command must not run on its own"
        );
        let proposals = db::list_command_proposals(&pool, &target, None, None, None, now)
            .await
            .unwrap();
        assert_eq!(proposals.len(), 1);
        assert_eq!(
            proposals[0].status,
            skilj_core::approvals::CommandProposalStatus::Pending
        );
        assert_eq!(proposals[0].metadata.client_id, db::DEADLINE_CLIENT_ID);

        // A crash before the row was marked fired: the next tick fires it
        // again, and must find the same proposal, not make a second one.
        sqlx::query(sqlx::AssertSqlSafe(format!(
            "UPDATE {}.deadlines SET status = 'pending', resolved_at = NULL WHERE id = $1",
            race_schema(&source)
        )))
        .bind(&deadline_id)
        .execute(&pool)
        .await
        .unwrap();
        fire().await.unwrap();
        assert_eq!(deadline_status().await, "fired");
        assert_eq!(
            db::list_command_proposals(&pool, &target, None, None, None, now)
                .await
                .unwrap()
                .len(),
            1
        );
        assert!(db::list_events_for_bounded_context(&pool, &target)
            .await
            .unwrap()
            .is_empty());
    });
}