pgtask-worker 0.2.0

Worker and scheduler runtime for pgtask
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
use std::{
    net::TcpListener as StdTcpListener,
    num::NonZeroU16,
    str::FromStr,
    sync::{
        Arc, OnceLock,
        atomic::{AtomicUsize, Ordering},
    },
    time::Duration,
};

use chrono::{TimeDelta, Utc};
use pgtask_core::{
    EnqueueRequest, HandlerVersion, QueueConfig, QueueName, RetryPolicy, ScheduleConfig, ScheduleDefinition,
    ScheduleName, SignalName, StepName, TaskName, TaskState,
};
use pgtask_postgres::{PostgresError, Store};
use pgtask_worker::{HandlerError, HandlerRegistry, Worker, WorkerConfig, WorkerError};
use serde_json::json;
use sqlx::{
    PgPool,
    postgres::{PgConnectOptions, PgPoolOptions},
};
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt},
    net::TcpStream,
    sync::{Mutex, MutexGuard, Notify, Semaphore},
};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;

const TEST_TIMEOUT: Duration = Duration::from_secs(10);

fn database_url() -> Option<String> {
    std::env::var("PGTASK_DATABASE_URL").ok()
}

async fn database_fault_guard() -> MutexGuard<'static, ()> {
    static GUARD: OnceLock<Mutex<()>> = OnceLock::new();
    GUARD.get_or_init(|| Mutex::new(())).lock().await
}

async fn drop_runtime_role(admin: &Store, role: &str) {
    sqlx::query("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = $1")
        .bind(role)
        .execute(admin.pool())
        .await
        .unwrap();
    sqlx::query(sqlx::AssertSqlSafe(format!("DROP OWNED BY {role}")))
        .execute(admin.pool())
        .await
        .unwrap();
    sqlx::query(sqlx::AssertSqlSafe(format!("DROP ROLE {role}")))
        .execute(admin.pool())
        .await
        .unwrap();
}

struct DropNotification(Arc<Notify>);

impl Drop for DropNotification {
    fn drop(&mut self) {
        self.0.notify_one();
    }
}

async fn health_status(address: std::net::SocketAddr, path: &str) -> u16 {
    let mut stream = TcpStream::connect(address).await.unwrap();
    stream
        .write_all(format!("GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").as_bytes())
        .await
        .unwrap();
    let mut response = String::new();
    stream.read_to_string(&mut response).await.unwrap();
    response.split_ascii_whitespace().nth(1).unwrap().parse().unwrap()
}

fn successful_registry(task_name: &TaskName) -> HandlerRegistry {
    let mut registry = HandlerRegistry::new();
    registry.register(
        task_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_| async move { Ok(json!(null)) },
    );
    registry
}

async fn complete_ready_child(store: &Store, queue_name: &QueueName, task_name: &TaskName) -> Result<(), HandlerError> {
    let child = store
        .claim(
            queue_name,
            pgtask_core::WorkerId::new(),
            &[(task_name.clone(), HandlerVersion::default())],
            1,
            Duration::from_secs(30),
        )
        .await
        .map_err(|error| HandlerError::terminal(error.to_string()))?
        .pop()
        .unwrap();
    store
        .complete(
            child.id,
            child.attempt,
            child.lease_token.unwrap(),
            Some(&json!({"ready": true})),
        )
        .await
        .map_err(|error| HandlerError::terminal(error.to_string()))?;
    Ok(())
}

struct DatabaseFaultWorker {
    admin: Store,
    fault_queue: QueueName,
    owner: String,
    release: Arc<Semaphore>,
    role: String,
    shutdown: CancellationToken,
    worker_task: tokio::task::JoinHandle<Result<(), WorkerError>>,
}

impl DatabaseFaultWorker {
    async fn start(database_url: &str) -> Self {
        let admin = Store::connect(database_url).await.unwrap();
        admin.migrate().await.unwrap();
        let suffix = Uuid::new_v4().simple();
        let role = format!("pgtask_fault_{suffix}");
        sqlx::query(sqlx::AssertSqlSafe(format!(
            "CREATE ROLE {role} LOGIN PASSWORD 'fault-test'"
        )))
        .execute(admin.pool())
        .await
        .unwrap();
        let owner: String = sqlx::query_scalar("SELECT current_user")
            .fetch_one(admin.pool())
            .await
            .unwrap();
        admin
            .configure_grants(&owner, &role, &role, &role, &role)
            .await
            .unwrap();

        let options = PgConnectOptions::from_str(database_url)
            .unwrap()
            .username(&role)
            .password("fault-test")
            .application_name(&role);
        let worker_store = Store::from_pool(
            PgPoolOptions::new()
                .acquire_timeout(Duration::from_secs(1))
                .connect_with(options)
                .await
                .unwrap(),
        );
        let fault_queue = QueueName::new(format!("database-fault-{suffix}")).unwrap();
        let task_name = TaskName::new(format!("database-fault-task-{suffix}")).unwrap();
        let started = Arc::new(Semaphore::new(0));
        let release = Arc::new(Semaphore::new(0));
        let handler_started = Arc::clone(&started);
        let handler_release = Arc::clone(&release);
        let mut registry = HandlerRegistry::new();
        registry.register(
            task_name.clone(),
            HandlerVersion::default(),
            RetryPolicy::Never,
            move |task| {
                let started = Arc::clone(&handler_started);
                let release = Arc::clone(&handler_release);
                async move {
                    started.add_permits(1);
                    if task.payload == json!("release") {
                        release.acquire().await.unwrap().forget();
                        Ok(json!(null))
                    } else {
                        std::future::pending().await
                    }
                }
            },
        );
        for payload in [json!("release"), json!("block"), json!("block")] {
            let mut request = EnqueueRequest::new(task_name.clone(), payload);
            request.queue_name = fault_queue.clone();
            request.max_attempts = 1;
            admin.enqueue(&request).await.unwrap();
        }
        let mut config = WorkerConfig::new(fault_queue.clone());
        config.concurrency = NonZeroU16::new(3).unwrap();
        config.claim_batch_size = NonZeroU16::new(3).unwrap();
        config.lease_duration = Duration::from_millis(90);
        config.poll_interval = Duration::from_millis(20);
        config.worker_heartbeat_interval = Duration::from_millis(20);
        config.worker_ttl = Duration::from_millis(200);
        config.schedule_reconciliation_interval = Duration::from_millis(20);
        // Retention must tick inside the fault windows below, or its failure path is never exercised.
        config.retention_interval = Duration::from_millis(20);
        config.supervisor_interval = Duration::from_millis(20);
        config.shutdown_grace = Duration::from_millis(20);
        let worker = Worker::new(worker_store, registry, config).unwrap();
        let shutdown = CancellationToken::new();
        let worker_shutdown = shutdown.clone();
        let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });
        started.acquire_many(3).await.unwrap().forget();
        Self {
            admin,
            fault_queue,
            owner,
            release,
            role,
            shutdown,
            worker_task,
        }
    }

    async fn restore_grants(&self) {
        self.admin
            .configure_grants(&self.owner, &self.role, &self.role, &self.role, &self.role)
            .await
            .unwrap();
    }

    async fn stop(self) {
        self.shutdown.cancel();
        self.worker_task.await.unwrap().unwrap();
        drop_runtime_role(&self.admin, &self.role).await;
    }
}

#[test]
fn handler_registry_and_errors_expose_explicit_public_values() {
    let task_name = TaskName::new("public-handler").unwrap();
    let mut registry = HandlerRegistry::new();
    assert!(registry.register(
        task_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_| async { Ok(json!(null)) },
    ));
    assert!(!registry.register(
        task_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_| async { Ok(json!(null)) },
    ));
    assert_eq!(registry.capabilities(), vec![(task_name, HandlerVersion::default())]);

    let retryable = HandlerError::retryable("again");
    assert!(retryable.retryable);
    assert_eq!(retryable.error["message"], "again");
    assert!(!retryable.is_suspended());
    let terminal = HandlerError::terminal("stop");
    assert!(!terminal.retryable);
    assert_eq!(terminal.error["message"], "stop");
    let suspended = HandlerError::suspended();
    assert!(suspended.is_suspended());
}

#[tokio::test]
async fn worker_configuration_rejects_every_invalid_invariant() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    let queue_name = QueueName::new(format!("worker-validation-{}", Uuid::new_v4())).unwrap();
    let task_name = TaskName::new("worker-validation").unwrap();

    assert!(matches!(
        Worker::new(
            store.clone(),
            HandlerRegistry::new(),
            WorkerConfig::new(queue_name.clone())
        ),
        Err(WorkerError::MissingHandlers)
    ));

    assert!(matches!(
        Worker::new(
            store.clone(),
            successful_registry(&task_name),
            WorkerConfig::with_queues(Vec::new())
        ),
        Err(WorkerError::MissingQueues)
    ));

    assert!(matches!(
        Worker::new(
            store.clone(),
            successful_registry(&task_name),
            WorkerConfig::with_queues(vec![queue_name.clone(), queue_name.clone()])
        ),
        Err(WorkerError::DuplicateQueues)
    ));

    let mut config = WorkerConfig::new(queue_name.clone());
    config.lease_duration = Duration::from_millis(2);
    assert!(matches!(
        Worker::new(store.clone(), successful_registry(&task_name), config),
        Err(WorkerError::InvalidLeaseDuration)
    ));

    let mut config = WorkerConfig::new(queue_name.clone());
    config.poll_interval = Duration::ZERO;
    assert!(matches!(
        Worker::new(store.clone(), successful_registry(&task_name), config),
        Err(WorkerError::InvalidPollInterval)
    ));

    for heartbeat in [Duration::ZERO, Duration::from_secs(30)] {
        let mut config = WorkerConfig::new(queue_name.clone());
        config.worker_heartbeat_interval = heartbeat;
        assert!(matches!(
            Worker::new(store.clone(), successful_registry(&task_name), config),
            Err(WorkerError::InvalidWorkerHeartbeat)
        ));
    }

    let mut config = WorkerConfig::new(queue_name.clone());
    config.schedule_reconciliation_interval = Duration::ZERO;
    assert!(matches!(
        Worker::new(store.clone(), successful_registry(&task_name), config),
        Err(WorkerError::InvalidScheduleReconciliationInterval)
    ));

    let mut config = WorkerConfig::new(queue_name.clone());
    config.retention_interval = Duration::ZERO;
    assert!(matches!(
        Worker::new(store.clone(), successful_registry(&task_name), config),
        Err(WorkerError::InvalidRetentionInterval)
    ));

    let mut config = WorkerConfig::new(queue_name.clone());
    config.supervisor_interval = Duration::ZERO;
    assert!(matches!(
        Worker::new(store.clone(), successful_registry(&task_name), config),
        Err(WorkerError::InvalidSupervisorInterval)
    ));

    let mut config = WorkerConfig::new(queue_name.clone());
    config.concurrency = NonZeroU16::new(1).unwrap();
    config.overload_protection.minimum_concurrency = NonZeroU16::new(2).unwrap();
    assert!(matches!(
        Worker::new(store.clone(), successful_registry(&task_name), config),
        Err(WorkerError::InvalidMinimumConcurrency)
    ));

    let mut config = WorkerConfig::new(queue_name);
    let mut request = EnqueueRequest::new(task_name.clone(), json!({}));
    request.queue_name = QueueName::new("another-queue").unwrap();
    config.declared_schedules.push(ScheduleConfig::new(
        ScheduleName::new("invalid-worker-schedule").unwrap(),
        ScheduleDefinition::interval(Duration::from_secs(1)).unwrap(),
        request,
    ));
    assert!(matches!(
        Worker::new(store, successful_registry(&task_name), config),
        Err(WorkerError::InvalidDeclaredSchedule(_))
    ));
}

#[tokio::test]
async fn worker_rejects_an_incompatible_storage_protocol() {
    let Some(database_url) = database_url() else {
        return;
    };
    let database_name = format!("pgtask_protocol_{}", Uuid::new_v4().simple());
    let options = PgConnectOptions::from_str(&database_url).unwrap();
    let maintenance = PgPool::connect_with(options.clone().database("postgres"))
        .await
        .unwrap();
    sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {database_name}")))
        .execute(&maintenance)
        .await
        .unwrap();
    let store = Store::from_pool(PgPool::connect_with(options.database(&database_name)).await.unwrap());
    store.migrate().await.unwrap();
    sqlx::query(
        r"
        CREATE OR REPLACE FUNCTION pgtask.storage_protocol_range()
        RETURNS TABLE(minimum integer, maximum integer)
        LANGUAGE sql
        IMMUTABLE
        AS $$ SELECT 2, 3 $$
        ",
    )
    .execute(store.pool())
    .await
    .unwrap();
    assert!(matches!(
        store.ensure_storage_protocol(pgtask_core::STORAGE_PROTOCOL_RANGE).await,
        Err(PostgresError::IncompatibleStorageProtocol {
            database_minimum: 2,
            database_maximum: 3,
            client_minimum: pgtask_core::STORAGE_PROTOCOL_MIN_VERSION,
            client_maximum: pgtask_core::STORAGE_PROTOCOL_MAX_VERSION,
        })
    ));
    let queue_name = QueueName::new(format!("incompatible-{}", Uuid::new_v4())).unwrap();
    let task_name = TaskName::new("incompatible-task").unwrap();
    let worker = Worker::new(store, successful_registry(&task_name), WorkerConfig::new(queue_name)).unwrap();

    assert!(matches!(
        worker.run(CancellationToken::new()).await,
        Err(WorkerError::IncompatibleStorageProtocol {
            database_minimum: 2,
            database_maximum: 3,
            worker_minimum: pgtask_core::STORAGE_PROTOCOL_MIN_VERSION,
            worker_maximum: pgtask_core::STORAGE_PROTOCOL_MAX_VERSION,
        })
    ));
    sqlx::query(
        r"
        CREATE OR REPLACE FUNCTION pgtask.storage_protocol_range()
        RETURNS TABLE(minimum integer, maximum integer)
        LANGUAGE sql
        IMMUTABLE
        AS $$ SELECT 1, 2 $$
        ",
    )
    .execute(
        &PgPool::connect_with(
            PgConnectOptions::from_str(&database_url)
                .unwrap()
                .database(&database_name),
        )
        .await
        .unwrap(),
    )
    .await
    .unwrap();
    let normal_store = Store::from_pool(
        PgPool::connect_with(
            PgConnectOptions::from_str(&database_url)
                .unwrap()
                .database(&database_name),
        )
        .await
        .unwrap(),
    );
    let queue_name = QueueName::new(format!("compatible-{}", Uuid::new_v4())).unwrap();
    let task_name = TaskName::new("compatible-task").unwrap();
    let mut config = WorkerConfig::new(queue_name);
    config.poll_interval = Duration::from_millis(20);
    config.schedule_reconciliation_interval = Duration::from_millis(20);
    config.supervisor_interval = Duration::from_millis(20);
    config.overload_protection.enabled = false;
    let worker = Worker::new(normal_store, successful_registry(&task_name), config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });
    tokio::time::sleep(Duration::from_millis(60)).await;
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
    sqlx::query(sqlx::AssertSqlSafe(format!(
        "DROP DATABASE {database_name} WITH (FORCE)"
    )))
    .execute(&maintenance)
    .await
    .unwrap();
}

#[tokio::test]
async fn worker_executes_registered_task_and_shuts_down() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let queue_name = QueueName::new(format!("worker-{}", Uuid::new_v4())).unwrap();
    let task_name = TaskName::new("echo").unwrap();
    let mut request = EnqueueRequest::new(task_name.clone(), json!({"value": 42}));
    request.queue_name = queue_name.clone();
    let task_id = store.enqueue(&request).await.unwrap().task_id;

    let mut registry = HandlerRegistry::new();
    assert!(registry.register(
        task_name,
        HandlerVersion::default(),
        RetryPolicy::Never,
        |task| async move { Ok(json!({"echo": task.payload})) }
    ));

    let mut config = WorkerConfig::new(queue_name);
    config.concurrency = NonZeroU16::new(1).unwrap();
    config.claim_batch_size = NonZeroU16::new(1).unwrap();
    config.lease_duration = Duration::from_millis(30);
    config.poll_interval = Duration::from_millis(5);
    config.retention_enabled = false;
    config.shutdown_grace = Duration::from_secs(1);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let task = store.get_task(task_id).await.unwrap().unwrap();
            if task.state == TaskState::Succeeded {
                assert_eq!(task.result, Some(json!({"echo": {"value": 42}})));
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();

    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn worker_drains_earlier_queues_before_later_ones() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let high = QueueName::new(format!("multi-high-{}", Uuid::new_v4())).unwrap();
    let low = QueueName::new(format!("multi-low-{}", Uuid::new_v4())).unwrap();
    let task_name = TaskName::new("multi-queue-order").unwrap();

    let mut task_ids = Vec::new();
    for queue_name in [&low, &high, &low, &high] {
        let mut request = EnqueueRequest::new(task_name.clone(), json!(queue_name.as_str()));
        request.queue_name = queue_name.clone();
        task_ids.push(store.enqueue(&request).await.unwrap().task_id);
    }

    let executed = Arc::new(Mutex::new(Vec::new()));
    let mut registry = HandlerRegistry::new();
    let recorded = Arc::clone(&executed);
    registry.register(task_name, HandlerVersion::default(), RetryPolicy::Never, move |task| {
        let recorded = Arc::clone(&recorded);
        async move {
            recorded.lock().await.push(task.queue_name.clone());
            Ok(json!(null))
        }
    });

    let mut config = WorkerConfig::with_queues(vec![high.clone(), low.clone()]);
    config.concurrency = NonZeroU16::new(1).unwrap();
    config.claim_batch_size = NonZeroU16::new(1).unwrap();
    // Long enough that a slow runner cannot expire a lease mid-handler and run a task twice, which
    // would say nothing about the order queues are drained in.
    config.lease_duration = TEST_TIMEOUT;
    config.poll_interval = Duration::from_millis(5);
    config.retention_enabled = false;
    config.shutdown_grace = Duration::from_secs(1);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let mut done = true;
            for task_id in &task_ids {
                done &= store.get_task(*task_id).await.unwrap().unwrap().state == TaskState::Succeeded;
            }
            if done {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();

    shutdown.cancel();
    worker_task.await.unwrap().unwrap();

    let order = executed.lock().await.clone();
    assert_eq!(order, vec![high.clone(), high, low.clone(), low]);
}

#[tokio::test]
async fn worker_records_handler_panics_without_crashing() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let queue_name = QueueName::new(format!("panic-{}", Uuid::new_v4())).unwrap();
    let task_name = TaskName::new("panic-task").unwrap();
    let mut request = EnqueueRequest::new(task_name.clone(), json!({}));
    request.queue_name = queue_name.clone();
    let task_id = store.enqueue(&request).await.unwrap().task_id;

    let mut registry = HandlerRegistry::new();
    registry.register(
        task_name,
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_| async move { panic!("synthetic handler panic") },
    );

    let mut config = WorkerConfig::new(queue_name);
    config.lease_duration = Duration::from_millis(30);
    config.poll_interval = Duration::from_millis(5);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let task = store.get_task(task_id).await.unwrap().unwrap();
            if task.state == TaskState::Failed {
                assert_eq!(task.error, Some(json!({"type": "handler_panic"})));
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();

    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn stale_success_and_panic_results_do_not_overwrite_cancellation() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("stale-results-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("stale-results-handler-{suffix}")).unwrap();
    let started = Arc::new(Semaphore::new(0));
    let release = Arc::new(Semaphore::new(0));
    let finished = Arc::new(Semaphore::new(0));
    let handler_started = Arc::clone(&started);
    let handler_release = Arc::clone(&release);
    let handler_finished = Arc::clone(&finished);
    let mut registry = HandlerRegistry::new();
    registry.register(
        task_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        move |task| {
            let started = Arc::clone(&handler_started);
            let release = Arc::clone(&handler_release);
            let finished = Arc::clone(&handler_finished);
            async move {
                started.add_permits(1);
                release.acquire().await.unwrap().forget();
                finished.add_permits(1);
                assert_ne!(task.payload, json!("panic"), "expected stale panic");
                Ok(json!({"late": true}))
            }
        },
    );
    let mut task_ids = Vec::new();
    for payload in [json!("success"), json!("panic")] {
        let mut request = EnqueueRequest::new(task_name.clone(), payload);
        request.queue_name = queue_name.clone();
        request.max_attempts = 1;
        task_ids.push(store.enqueue(&request).await.unwrap().task_id);
    }
    let mut config = WorkerConfig::new(queue_name);
    config.concurrency = NonZeroU16::new(2).unwrap();
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    started.acquire_many(2).await.unwrap().forget();
    for task_id in &task_ids {
        assert!(store.cancel(*task_id).await.unwrap());
    }
    release.add_permits(2);
    finished.acquire_many(2).await.unwrap().forget();
    tokio::time::sleep(Duration::from_millis(20)).await;
    for task_id in task_ids {
        assert_eq!(
            store.get_task(task_id).await.unwrap().unwrap().state,
            TaskState::Cancelled
        );
    }
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn lease_renewal_propagates_database_cancellation_to_the_handler() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("renewal-cancellation-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("renewal-cancellation-handler-{suffix}")).unwrap();
    let mut request = EnqueueRequest::new(task_name.clone(), json!({}));
    request.queue_name = queue_name.clone();
    let task_id = store.enqueue(&request).await.unwrap().task_id;
    let started = Arc::new(Notify::new());
    let dropped = Arc::new(Notify::new());
    let handler_started = Arc::clone(&started);
    let handler_dropped = Arc::clone(&dropped);
    let mut registry = HandlerRegistry::new();
    registry.register(task_name, HandlerVersion::default(), RetryPolicy::Never, move |_task| {
        let started = Arc::clone(&handler_started);
        let dropped = DropNotification(Arc::clone(&handler_dropped));
        async move {
            started.notify_one();
            let _dropped = dropped;
            std::future::pending::<Result<serde_json::Value, HandlerError>>().await
        }
    });
    let mut config = WorkerConfig::new(queue_name);
    config.lease_duration = Duration::from_millis(90);
    config.poll_interval = Duration::from_millis(5);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, started.notified()).await.unwrap();
    assert!(store.cancel(task_id).await.unwrap());
    tokio::time::timeout(TEST_TIMEOUT, dropped.notified()).await.unwrap();
    assert_eq!(
        store.get_task(task_id).await.unwrap().unwrap().state,
        TaskState::Cancelled
    );
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn another_worker_recovers_a_task_after_runtime_termination() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let queue_name = QueueName::new(format!("worker-crash-{}", Uuid::new_v4())).unwrap();
    let task_name = TaskName::new("crashing-worker-task").unwrap();
    let mut request = EnqueueRequest::new(task_name.clone(), json!({}));
    request.queue_name = queue_name.clone();
    let task_id = store.enqueue(&request).await.unwrap().task_id;

    let started = std::sync::Arc::new(Notify::new());
    let mut first_registry = HandlerRegistry::new();
    first_registry.register(task_name.clone(), HandlerVersion::default(), RetryPolicy::Never, {
        let started = std::sync::Arc::clone(&started);
        move |_| {
            let started = std::sync::Arc::clone(&started);
            async move {
                started.notify_one();
                std::future::pending().await
            }
        }
    });
    let mut config = WorkerConfig::new(queue_name.clone());
    config.concurrency = NonZeroU16::new(1).unwrap();
    config.claim_batch_size = NonZeroU16::new(1).unwrap();
    config.lease_duration = Duration::from_secs(1);
    config.poll_interval = Duration::from_millis(5);
    let first_worker = Worker::new(store.clone(), first_registry, config.clone()).unwrap();
    let first_worker_task = tokio::spawn(async move { first_worker.run(CancellationToken::new()).await });

    tokio::time::timeout(TEST_TIMEOUT, started.notified()).await.unwrap();
    first_worker_task.abort();
    assert!(first_worker_task.await.unwrap_err().is_cancelled());

    let mut second_registry = HandlerRegistry::new();
    second_registry.register(
        task_name,
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_| async move { Ok(json!({"recovered": true})) },
    );
    let second_worker = Worker::new(store.clone(), second_registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let second_worker_task = tokio::spawn(async move { second_worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let task = store.get_task(task_id).await.unwrap().unwrap();
            if task.state == TaskState::Succeeded {
                assert_eq!(task.attempt, 2);
                assert_eq!(task.result, Some(json!({"recovered": true})));
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();

    shutdown.cancel();
    second_worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn queue_runtimes_have_independent_concurrency() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let suffix = Uuid::new_v4();
    let blocked_queue = QueueName::new(format!("blocked-{suffix}")).unwrap();
    let ready_queue = QueueName::new(format!("ready-{suffix}")).unwrap();
    let blocked_name = TaskName::new("blocked-task").unwrap();
    let ready_name = TaskName::new("ready-task").unwrap();
    let mut blocked_request = EnqueueRequest::new(blocked_name.clone(), json!({}));
    blocked_request.queue_name = blocked_queue.clone();
    store.enqueue(&blocked_request).await.unwrap();
    let mut ready_request = EnqueueRequest::new(ready_name.clone(), json!({}));
    ready_request.queue_name = ready_queue.clone();
    let ready_id = store.enqueue(&ready_request).await.unwrap().task_id;

    let blocked_started = std::sync::Arc::new(Notify::new());
    let mut blocked_registry = HandlerRegistry::new();
    blocked_registry.register(blocked_name, HandlerVersion::default(), RetryPolicy::Never, {
        let blocked_started = std::sync::Arc::clone(&blocked_started);
        move |_| {
            let blocked_started = std::sync::Arc::clone(&blocked_started);
            async move {
                blocked_started.notify_one();
                std::future::pending().await
            }
        }
    });
    let mut ready_registry = HandlerRegistry::new();
    ready_registry.register(
        ready_name,
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_| async move { Ok(json!({"ran": true})) },
    );
    let mut blocked_config = WorkerConfig::new(blocked_queue);
    blocked_config.concurrency = NonZeroU16::new(1).unwrap();
    blocked_config.claim_batch_size = NonZeroU16::new(1).unwrap();
    blocked_config.lease_duration = Duration::from_millis(100);
    blocked_config.poll_interval = Duration::from_millis(5);
    let mut ready_config = WorkerConfig::new(ready_queue);
    ready_config.concurrency = NonZeroU16::new(1).unwrap();
    ready_config.claim_batch_size = NonZeroU16::new(1).unwrap();
    ready_config.lease_duration = Duration::from_millis(100);
    ready_config.poll_interval = Duration::from_millis(5);

    let blocked_worker = Worker::new(store.clone(), blocked_registry, blocked_config).unwrap();
    let blocked_task = tokio::spawn(async move { blocked_worker.run(CancellationToken::new()).await });
    let ready_worker = Worker::new(store.clone(), ready_registry, ready_config).unwrap();
    let ready_shutdown = CancellationToken::new();
    let worker_shutdown = ready_shutdown.clone();
    let ready_task = tokio::spawn(async move { ready_worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, blocked_started.notified())
        .await
        .unwrap();
    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            if store.get_task(ready_id).await.unwrap().unwrap().state == TaskState::Succeeded {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();

    blocked_task.abort();
    assert!(blocked_task.await.unwrap_err().is_cancelled());
    ready_shutdown.cancel();
    ready_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn worker_renews_a_long_running_handler_automatically() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let queue_name = QueueName::new(format!("renewal-{}", Uuid::new_v4())).unwrap();
    let task_name = TaskName::new("long-task").unwrap();
    let mut request = EnqueueRequest::new(task_name.clone(), json!({}));
    request.queue_name = queue_name.clone();
    let task_id = store.enqueue(&request).await.unwrap().task_id;
    let mut registry = HandlerRegistry::new();
    registry.register(
        task_name,
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_| async move {
            tokio::time::sleep(Duration::from_secs(2)).await;
            Ok(json!({"done": true}))
        },
    );
    let mut config = WorkerConfig::new(queue_name);
    config.concurrency = NonZeroU16::new(4).unwrap();
    config.claim_batch_size = NonZeroU16::new(4).unwrap();
    config.lease_duration = Duration::from_secs(1);
    config.poll_interval = Duration::from_millis(5);
    config.supervisor_interval = Duration::from_millis(10);
    config.overload_protection.event_loop_lag_threshold = Duration::ZERO;
    config.overload_protection.sustained_samples = NonZeroU16::MIN;
    config.overload_protection.enforce = true;
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let task = store.get_task(task_id).await.unwrap().unwrap();
            if task.state == TaskState::Succeeded {
                assert_eq!(task.attempt, 1);
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();

    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn effective_concurrency_stops_new_claims_without_cancelling_handlers() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let queue_name = QueueName::new(format!("admission-{}", Uuid::new_v4())).unwrap();
    let task_name = TaskName::new("admission-task").unwrap();
    let mut task_ids = Vec::new();
    for sequence in 0..3 {
        let mut request = EnqueueRequest::new(task_name.clone(), json!({"sequence": sequence}));
        request.queue_name = queue_name.clone();
        task_ids.push(store.enqueue(&request).await.unwrap().task_id);
    }
    let active = Arc::new(AtomicUsize::new(0));
    let maximum = Arc::new(AtomicUsize::new(0));
    let started = Arc::new(AtomicUsize::new(0));
    let permits = Arc::new(Semaphore::new(0));
    let mut registry = HandlerRegistry::new();
    registry.register(task_name, HandlerVersion::default(), RetryPolicy::Never, {
        let active = Arc::clone(&active);
        let maximum = Arc::clone(&maximum);
        let started = Arc::clone(&started);
        let permits = Arc::clone(&permits);
        move |_| {
            let active = Arc::clone(&active);
            let maximum = Arc::clone(&maximum);
            let started = Arc::clone(&started);
            let permits = Arc::clone(&permits);
            async move {
                let current = active.fetch_add(1, Ordering::SeqCst) + 1;
                maximum.fetch_max(current, Ordering::SeqCst);
                started.fetch_add(1, Ordering::SeqCst);
                permits.acquire().await.unwrap().forget();
                active.fetch_sub(1, Ordering::SeqCst);
                Ok(json!({"done": true}))
            }
        }
    });
    let mut config = WorkerConfig::new(queue_name);
    config.concurrency = NonZeroU16::new(2).unwrap();
    config.claim_batch_size = NonZeroU16::new(2).unwrap();
    config.lease_duration = Duration::from_secs(10);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let control = worker.control();
    assert_eq!(control.configured_concurrency().get(), 2);
    assert_eq!(control.effective_concurrency().get(), 2);
    assert!(control.set_effective_concurrency(NonZeroU16::new(3).unwrap()).is_err());
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        while started.load(Ordering::SeqCst) < 2 {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    control.set_effective_concurrency(NonZeroU16::new(1).unwrap()).unwrap();
    permits.add_permits(1);
    tokio::time::sleep(Duration::from_millis(100)).await;
    assert_eq!(started.load(Ordering::SeqCst), 2);
    assert_eq!(active.load(Ordering::SeqCst), 1);

    permits.add_permits(1);
    tokio::time::timeout(TEST_TIMEOUT, async {
        while started.load(Ordering::SeqCst) < 3 {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    permits.add_permits(1);
    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let mut complete = true;
            for task_id in &task_ids {
                complete &= store.get_task(*task_id).await.unwrap().unwrap().state == TaskState::Succeeded;
            }
            if complete {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    assert_eq!(maximum.load(Ordering::SeqCst), 2);
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn dedicated_supervisor_serves_worker_liveness_and_readiness() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let queue_name = QueueName::new(format!("health-{}", Uuid::new_v4())).unwrap();
    let task_name = TaskName::new("health-task").unwrap();
    let mut registry = HandlerRegistry::new();
    registry.register(
        task_name,
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_| async move { Ok(json!(null)) },
    );
    let socket = StdTcpListener::bind("127.0.0.1:0").unwrap();
    let address = socket.local_addr().unwrap();
    drop(socket);
    let mut config = WorkerConfig::new(queue_name);
    config.health_address = Some(address);
    config.supervisor_interval = Duration::from_millis(10);
    config.overload_protection.enabled = false;
    let worker = Worker::new(store, registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            if TcpStream::connect(address).await.is_ok() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    assert_eq!(health_status(address, "/livez").await, 200);
    tokio::time::timeout(TEST_TIMEOUT, async {
        while health_status(address, "/readyz").await != 200 {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn supervisor_binding_failure_is_reported() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let queue_name = QueueName::new(format!("health-conflict-{}", Uuid::new_v4())).unwrap();
    let task_name = TaskName::new("health-conflict-task").unwrap();
    let socket = StdTcpListener::bind("127.0.0.1:0").unwrap();
    let mut config = WorkerConfig::new(queue_name);
    config.health_address = Some(socket.local_addr().unwrap());
    let worker = Worker::new(store, successful_registry(&task_name), config).unwrap();

    assert!(matches!(
        worker.run(CancellationToken::new()).await,
        Err(WorkerError::Supervisor(_))
    ));
}

#[tokio::test]
async fn worker_recovers_from_revoked_database_protocols() {
    let Some(database_url) = database_url() else {
        return;
    };
    let _guard = database_fault_guard().await;
    let fixture = DatabaseFaultWorker::start(&database_url).await;

    sqlx::query(sqlx::AssertSqlSafe(format!(
        "REVOKE EXECUTE ON FUNCTION pgtask.complete_task(uuid, integer, uuid, jsonb) FROM {}",
        fixture.role
    )))
    .execute(fixture.admin.pool())
    .await
    .unwrap();
    fixture.release.add_permits(1);
    tokio::time::sleep(Duration::from_millis(80)).await;
    fixture.restore_grants().await;

    let revoke_background = format!(
        "REVOKE EXECUTE ON FUNCTION \
         pgtask.renew_leases(uuid[], integer[], uuid[], bigint), \
         pgtask.heartbeat_worker(uuid, bigint, boolean), \
         pgtask.claim_due_schedules(integer), \
         pgtask.recover_wait_timeouts(integer) FROM {}",
        fixture.role
    );
    sqlx::query(sqlx::AssertSqlSafe(revoke_background))
        .execute(fixture.admin.pool())
        .await
        .unwrap();
    tokio::time::sleep(Duration::from_millis(150)).await;
    fixture.restore_grants().await;
    tokio::time::sleep(Duration::from_millis(100)).await;
    fixture.admin.recover_expired(&fixture.fault_queue, 10).await.unwrap();

    for (function, delay) in [
        ("pgtask.delete_expired_terminal(text, integer)", 150),
        ("pgtask.delete_expired_idempotency_keys(text, integer)", 150),
        ("pgtask.recover_expired(text, integer)", 150),
        ("pgtask.claim(text, uuid, text[], integer[], integer, bigint)", 150),
        ("pgtask.next_task_delay_milliseconds(text, text[], integer[])", 150),
        ("pgtask.next_schedule_delay_milliseconds()", 100),
        ("pgtask.next_wait_delay_milliseconds()", 100),
    ] {
        sqlx::query(sqlx::AssertSqlSafe(format!(
            "REVOKE EXECUTE ON FUNCTION {function} FROM {}",
            fixture.role
        )))
        .execute(fixture.admin.pool())
        .await
        .unwrap();
        tokio::time::sleep(Duration::from_millis(delay)).await;
        fixture.restore_grants().await;
    }

    sqlx::query(sqlx::AssertSqlSafe(format!(
        "REVOKE EXECUTE ON FUNCTION pgtask.heartbeat_worker(uuid, bigint, boolean) FROM {}",
        fixture.role
    )))
    .execute(fixture.admin.pool())
    .await
    .unwrap();
    fixture.stop().await;
}

#[tokio::test]
async fn worker_recovers_from_database_disconnects_and_registration_loss() {
    let Some(database_url) = database_url() else {
        return;
    };
    let _guard = database_fault_guard().await;
    let fixture = DatabaseFaultWorker::start(&database_url).await;

    sqlx::query(sqlx::AssertSqlSafe(format!(
        "ALTER ROLE {} CONNECTION LIMIT 0",
        fixture.role
    )))
    .execute(fixture.admin.pool())
    .await
    .unwrap();
    sqlx::query("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name = $1")
        .bind(&fixture.role)
        .execute(fixture.admin.pool())
        .await
        .unwrap();
    tokio::time::sleep(Duration::from_millis(300)).await;
    sqlx::query(sqlx::AssertSqlSafe(format!(
        "ALTER ROLE {} CONNECTION LIMIT -1",
        fixture.role
    )))
    .execute(fixture.admin.pool())
    .await
    .unwrap();
    tokio::time::sleep(Duration::from_millis(300)).await;
    sqlx::query("DELETE FROM pgtask.workers WHERE queue_name = $1")
        .bind(fixture.fault_queue.as_str())
        .execute(fixture.admin.pool())
        .await
        .unwrap();
    tokio::time::sleep(Duration::from_millis(60)).await;
    fixture.stop().await;
}

#[tokio::test]
async fn notification_listener_reports_failure_and_recovers() {
    let Some(database_url) = database_url() else {
        return;
    };
    let _guard = database_fault_guard().await;
    let admin = Store::connect(&database_url).await.unwrap();
    admin.migrate().await.unwrap();
    let suffix = Uuid::new_v4().simple();
    let role = format!("pgtask_listener_{suffix}");
    sqlx::query(sqlx::AssertSqlSafe(format!(
        "CREATE ROLE {role} LOGIN PASSWORD 'listener-test'"
    )))
    .execute(admin.pool())
    .await
    .unwrap();
    let owner: String = sqlx::query_scalar("SELECT current_user")
        .fetch_one(admin.pool())
        .await
        .unwrap();
    admin
        .configure_grants(&owner, &role, &role, &role, &role)
        .await
        .unwrap();
    let options = PgConnectOptions::from_str(&database_url)
        .unwrap()
        .username(&role)
        .password("listener-test")
        .application_name(&role);
    let store = Store::from_pool(
        PgPoolOptions::new()
            .acquire_timeout(Duration::from_secs(1))
            .connect_with(options)
            .await
            .unwrap(),
    );
    let queue_name = QueueName::new(format!("listener-recovery-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("listener-recovery-handler-{suffix}")).unwrap();
    let socket = StdTcpListener::bind("127.0.0.1:0").unwrap();
    let address = socket.local_addr().unwrap();
    drop(socket);
    let mut config = WorkerConfig::new(queue_name);
    config.health_address = Some(address);
    config.poll_interval = Duration::from_secs(5);
    config.supervisor_interval = Duration::from_millis(10);
    let worker = Worker::new(store, successful_registry(&task_name), config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        while TcpStream::connect(address).await.is_err() {}
    })
    .await
    .unwrap();
    tokio::time::timeout(TEST_TIMEOUT, async {
        while health_status(address, "/readyz").await != 200 {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    sqlx::query("SELECT pg_notify('pgtask_ready', 'another-queue')")
        .execute(admin.pool())
        .await
        .unwrap();
    tokio::time::sleep(Duration::from_millis(20)).await;
    sqlx::query(sqlx::AssertSqlSafe(format!("ALTER ROLE {role} CONNECTION LIMIT 0")))
        .execute(admin.pool())
        .await
        .unwrap();
    sqlx::query("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name = $1")
        .bind(&role)
        .execute(admin.pool())
        .await
        .unwrap();
    tokio::time::timeout(TEST_TIMEOUT, async {
        while health_status(address, "/readyz").await != 503 {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    tokio::time::sleep(Duration::from_millis(1_200)).await;
    sqlx::query(sqlx::AssertSqlSafe(format!("ALTER ROLE {role} CONNECTION LIMIT -1")))
        .execute(admin.pool())
        .await
        .unwrap();
    tokio::time::timeout(TEST_TIMEOUT, async {
        while health_status(address, "/readyz").await != 200 {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();

    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
    drop_runtime_role(&admin, &role).await;
}

#[tokio::test]
async fn idle_worker_recovers_from_claim_and_deadline_protocol_failures() {
    let Some(database_url) = database_url() else {
        return;
    };
    let _guard = database_fault_guard().await;
    let admin = Store::connect(&database_url).await.unwrap();
    admin.migrate().await.unwrap();
    let suffix = Uuid::new_v4().simple();
    let role = format!("pgtask_fault_{suffix}");
    sqlx::query(sqlx::AssertSqlSafe(format!(
        "CREATE ROLE {role} LOGIN PASSWORD 'fault-test'"
    )))
    .execute(admin.pool())
    .await
    .unwrap();
    let owner: String = sqlx::query_scalar("SELECT current_user")
        .fetch_one(admin.pool())
        .await
        .unwrap();
    admin
        .configure_grants(&owner, &role, &role, &role, &role)
        .await
        .unwrap();
    let options = PgConnectOptions::from_str(&database_url)
        .unwrap()
        .username(&role)
        .password("fault-test")
        .application_name(&role);
    let store = Store::from_pool(PgPool::connect_with(options).await.unwrap());
    let queue_name = QueueName::new(format!("idle-database-fault-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("idle-database-fault-task-{suffix}")).unwrap();
    let socket = StdTcpListener::bind("127.0.0.1:0").unwrap();
    let address = socket.local_addr().unwrap();
    drop(socket);
    let mut config = WorkerConfig::new(queue_name.clone());
    config.health_address = Some(address);
    config.poll_interval = Duration::from_millis(20);
    config.supervisor_interval = Duration::from_millis(2);
    config.overload_protection.enabled = false;
    let worker = Worker::new(store, successful_registry(&task_name), config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });
    tokio::time::timeout(TEST_TIMEOUT, async {
        while TcpStream::connect(address).await.is_err() {}
    })
    .await
    .unwrap();

    for function in [
        "pgtask.next_task_delay_milliseconds(text, text[], integer[])",
        "pgtask.claim(text, uuid, text[], integer[], integer, bigint)",
    ] {
        sqlx::query(sqlx::AssertSqlSafe(format!(
            "REVOKE EXECUTE ON FUNCTION {function} FROM {role}"
        )))
        .execute(admin.pool())
        .await
        .unwrap();
        let mut request = EnqueueRequest::new(task_name.clone(), json!({}));
        request.queue_name = queue_name.clone();
        admin.enqueue(&request).await.unwrap();
        tokio::time::sleep(Duration::from_millis(80)).await;
        admin
            .configure_grants(&owner, &role, &role, &role, &role)
            .await
            .unwrap();
        tokio::time::timeout(TEST_TIMEOUT, async {
            while health_status(address, "/readyz").await != 200 {}
        })
        .await
        .unwrap();
    }

    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
    sqlx::query(sqlx::AssertSqlSafe(format!("DROP OWNED BY {role}")))
        .execute(admin.pool())
        .await
        .unwrap();
    sqlx::query(sqlx::AssertSqlSafe(format!("DROP ROLE {role}")))
        .execute(admin.pool())
        .await
        .unwrap();
}

#[tokio::test]
async fn supervisor_proposes_overload_reduction_without_enforcing_it() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let queue_name = QueueName::new(format!("observe-overload-{}", Uuid::new_v4())).unwrap();
    let mut registry = HandlerRegistry::new();
    registry.register(
        TaskName::new("observe-overload-task").unwrap(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_| async move { Ok(json!(null)) },
    );
    let mut config = WorkerConfig::new(queue_name);
    config.concurrency = NonZeroU16::new(4).unwrap();
    config.supervisor_interval = Duration::from_millis(10);
    config.overload_protection.event_loop_lag_threshold = Duration::ZERO;
    config.overload_protection.sustained_samples = NonZeroU16::MIN;
    let worker = Worker::new(store, registry, config).unwrap();
    let control = worker.control();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        while control.proposed_concurrency().get() != 2 {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    assert_eq!(control.effective_concurrency().get(), 4);
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn optional_overload_enforcement_reduces_the_effective_limit() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let queue_name = QueueName::new(format!("enforce-overload-{}", Uuid::new_v4())).unwrap();
    let mut registry = HandlerRegistry::new();
    registry.register(
        TaskName::new("enforce-overload-task").unwrap(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_| async move { Ok(json!(null)) },
    );
    let mut config = WorkerConfig::new(queue_name);
    config.concurrency = NonZeroU16::new(4).unwrap();
    config.supervisor_interval = Duration::from_millis(10);
    config.overload_protection.event_loop_lag_threshold = Duration::ZERO;
    config.overload_protection.sustained_samples = NonZeroU16::MIN;
    config.overload_protection.enforce = true;
    let worker = Worker::new(store, registry, config).unwrap();
    let control = worker.control();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        while control.effective_concurrency().get() != 1 {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    assert_eq!(control.proposed_concurrency().get(), 1);
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn overload_enforcement_recovers_additively_to_the_configured_limit() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let queue_name = QueueName::new(format!("recover-overload-{}", Uuid::new_v4())).unwrap();
    let mut registry = HandlerRegistry::new();
    registry.register(
        TaskName::new("recover-overload-task").unwrap(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_| async move { Ok(json!(null)) },
    );
    let mut config = WorkerConfig::new(queue_name);
    config.concurrency = NonZeroU16::new(4).unwrap();
    config.supervisor_interval = Duration::from_millis(10);
    config.overload_protection.event_loop_lag_threshold = Duration::MAX;
    config.overload_protection.recovery_samples = NonZeroU16::new(3).unwrap();
    config.overload_protection.enforce = true;
    let worker = Worker::new(store, registry, config).unwrap();
    let control = worker.control();
    control.set_effective_concurrency(NonZeroU16::MIN).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::sleep(Duration::from_millis(15)).await;
    assert_eq!(control.effective_concurrency().get(), 1);

    tokio::time::timeout(TEST_TIMEOUT, async {
        while control.effective_concurrency().get() != 4 {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    assert_eq!(control.proposed_concurrency().get(), 4);
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn notification_and_database_deadline_wake_a_delayed_task() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let queue_name = QueueName::new(format!("notify-{}", Uuid::new_v4())).unwrap();
    let task_name = TaskName::new("notified-task").unwrap();
    let mut registry = HandlerRegistry::new();
    registry.register(
        task_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_| async move { Ok(json!({})) },
    );
    let mut config = WorkerConfig::new(queue_name.clone());
    config.poll_interval = Duration::from_secs(5);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });
    tokio::time::sleep(Duration::from_millis(100)).await;

    let mut request = EnqueueRequest::new(task_name, json!({}));
    request.queue_name = queue_name;
    request.run_at = Some(Utc::now() + TimeDelta::milliseconds(150));
    let task_id = store.enqueue(&request).await.unwrap().task_id;
    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            if store.get_task(task_id).await.unwrap().unwrap().state == TaskState::Succeeded {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();

    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn schedule_notifications_reset_the_database_deadline_timer() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("schedule-notify-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("scheduled-handler-{suffix}")).unwrap();
    let executed = std::sync::Arc::new(Notify::new());
    let handler_executed = std::sync::Arc::clone(&executed);
    let mut registry = HandlerRegistry::new();
    registry.register(
        task_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        move |_| {
            let handler_executed = std::sync::Arc::clone(&handler_executed);
            async move {
                handler_executed.notify_one();
                Ok(json!({}))
            }
        },
    );
    let mut worker_config = WorkerConfig::new(queue_name.clone());
    worker_config.poll_interval = Duration::from_secs(5);
    worker_config.schedule_reconciliation_interval = Duration::from_secs(5);
    let worker = Worker::new(store.clone(), registry, worker_config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });
    tokio::time::sleep(Duration::from_millis(100)).await;

    let mut request = EnqueueRequest::new(task_name, json!({}));
    request.queue_name = queue_name;
    let mut schedule_config = ScheduleConfig::new(
        ScheduleName::new(format!("schedule-notify-{suffix}")).unwrap(),
        ScheduleDefinition::interval(Duration::from_hours(1)).unwrap(),
        request,
    );
    schedule_config.start_at = Some(Utc::now() + TimeDelta::milliseconds(150));
    let schedule = store.put_schedule(&schedule_config).await.unwrap();

    tokio::time::timeout(TEST_TIMEOUT, executed.notified()).await.unwrap();
    assert!(store.delete_schedule(schedule.config.id).await.unwrap());
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn worker_reconciles_code_declared_schedules_before_starting() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("declared-schedule-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("declared-handler-{suffix}")).unwrap();
    let executed = std::sync::Arc::new(Notify::new());
    let handler_executed = std::sync::Arc::clone(&executed);
    let mut registry = HandlerRegistry::new();
    registry.register(
        task_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        move |_| {
            let handler_executed = std::sync::Arc::clone(&handler_executed);
            async move {
                handler_executed.notify_one();
                Ok(json!({}))
            }
        },
    );
    let mut request = EnqueueRequest::new(task_name, json!({}));
    request.queue_name = queue_name.clone();
    let mut schedule_config = ScheduleConfig::new(
        ScheduleName::new(format!("declared-schedule-{suffix}")).unwrap(),
        ScheduleDefinition::interval(Duration::from_hours(1)).unwrap(),
        request,
    );
    schedule_config.start_at = Some(Utc::now() + TimeDelta::milliseconds(100));
    let schedule_id = schedule_config.id;
    let mut worker_config = WorkerConfig::new(queue_name);
    worker_config.declared_schedules.push(schedule_config);
    let worker = Worker::new(store.clone(), registry, worker_config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, executed.notified()).await.unwrap();
    assert!(store.get_schedule(schedule_id).await.unwrap().is_some());
    assert!(store.delete_schedule(schedule_id).await.unwrap());
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn replicated_workers_delete_expired_terminal_tasks_in_bounded_batches() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("worker-retention-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("worker-retention-{suffix}")).unwrap();
    let mut queue = QueueConfig::new(queue_name.clone());
    queue.terminal_retention = Duration::ZERO;
    queue.idempotency_retention = Duration::ZERO;
    store.put_queue(&queue).await.unwrap();
    let mut request = EnqueueRequest::new(task_name.clone(), json!({}));
    request.queue_name = queue_name.clone();
    request.idempotency_key = Some(format!("worker-retention-{suffix}"));
    let task_id = store.enqueue(&request).await.unwrap().task_id;
    let task = store
        .claim(
            &queue_name,
            pgtask_core::WorkerId::new(),
            &[(task_name.clone(), HandlerVersion::default())],
            1,
            Duration::from_secs(30),
        )
        .await
        .unwrap()
        .pop()
        .unwrap();
    assert!(
        store
            .complete(task_id, task.attempt, task.lease_token.unwrap(), None)
            .await
            .unwrap()
    );

    let mut config = WorkerConfig::new(queue_name);
    config.retention_batch_size = NonZeroU16::MIN;
    config.retention_interval = Duration::from_millis(10);
    let worker = Worker::new(store.clone(), successful_registry(&task_name), config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });
    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let task_exists = store.get_task(task_id).await.unwrap().is_some();
            let key_exists: bool =
                sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM pgtask.idempotency_keys WHERE task_id = $1)")
                    .bind(task_id.as_uuid())
                    .fetch_one(store.pool())
                    .await
                    .unwrap();
            if !task_exists && !key_exists {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .unwrap();
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn durable_handler_replays_a_checkpoint_after_retry() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("durable-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("durable-handler-{suffix}")).unwrap();
    let mut request = EnqueueRequest::new(task_name.clone(), json!({}));
    request.queue_name = queue_name.clone();
    let task_id = store.enqueue(&request).await.unwrap().task_id;
    let operations = std::sync::Arc::new(AtomicUsize::new(0));
    let handler_operations = std::sync::Arc::clone(&operations);
    let mut registry = HandlerRegistry::new();
    registry.register_durable(
        task_name,
        HandlerVersion::default(),
        RetryPolicy::Fixed {
            delay: Duration::from_millis(1),
        },
        move |task, context| {
            let handler_operations = std::sync::Arc::clone(&handler_operations);
            async move {
                assert!(!context.cancellation_token().is_cancelled());
                let value = context
                    .step(&StepName::new("load-value").unwrap(), 0, || async move {
                        handler_operations.fetch_add(1, Ordering::SeqCst);
                        Ok(json!({"value": 42}))
                    })
                    .await?;
                if task.attempt == 1 {
                    return Err(pgtask_worker::HandlerError::retryable("retry after checkpoint"));
                }
                Ok(value)
            }
        },
    );
    let mut config = WorkerConfig::new(queue_name);
    config.poll_interval = Duration::from_millis(50);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let task = store.get_task(task_id).await.unwrap().unwrap();
            if task.state == TaskState::Succeeded {
                assert_eq!(task.attempt, 2);
                assert_eq!(task.result, Some(json!({"value": 42})));
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    assert_eq!(operations.load(Ordering::SeqCst), 1);
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn durable_context_rejects_cancelled_and_malformed_checkpoints() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("durable-validation-{suffix}")).unwrap();
    let cancelled_name = TaskName::new(format!("durable-cancelled-{suffix}")).unwrap();
    let malformed_name = TaskName::new(format!("durable-malformed-{suffix}")).unwrap();

    let mut registry = HandlerRegistry::new();
    registry.register_durable(
        cancelled_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_task, context| async move {
            context.cancellation_token().cancel();
            context
                .step(&StepName::new("cancelled-step").unwrap(), 0, || async {
                    Ok(json!(null))
                })
                .await
        },
    );
    registry.register_durable(
        malformed_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        |task, context| async move {
            let step_name = StepName::new("malformed-signal").unwrap();
            context.step(&step_name, 0, || async { Ok(task.payload) }).await?;
            context
                .wait_for_signal(&step_name, 0, &SignalName::new("unused").unwrap(), 0, None)
                .await
                .map(|_| json!(null))
        },
    );

    let mut task_ids = Vec::new();
    for (task_name, payload) in [
        (cancelled_name, json!(null)),
        (malformed_name.clone(), json!("invalid")),
        (malformed_name, json!({"outcome": "invalid"})),
    ] {
        let mut request = EnqueueRequest::new(task_name, payload);
        request.queue_name = queue_name.clone();
        request.max_attempts = 1;
        task_ids.push(store.enqueue(&request).await.unwrap().task_id);
    }

    let mut config = WorkerConfig::new(queue_name);
    config.concurrency = NonZeroU16::new(3).unwrap();
    config.lease_duration = Duration::from_millis(30);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });
    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let mut terminal = true;
            for task_id in &task_ids {
                terminal &= store.get_task(*task_id).await.unwrap().unwrap().state.is_terminal();
            }
            if terminal {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn external_side_effect_before_checkpoint_commit_is_at_least_once() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("durable-side-effect-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("durable-side-effect-handler-{suffix}")).unwrap();
    let mut request = EnqueueRequest::new(task_name.clone(), json!({}));
    request.queue_name = queue_name.clone();
    let task_id = store.enqueue(&request).await.unwrap().task_id;
    let operations = std::sync::Arc::new(AtomicUsize::new(0));
    let handler_operations = std::sync::Arc::clone(&operations);
    let mut registry = HandlerRegistry::new();
    registry.register_durable(
        task_name,
        HandlerVersion::default(),
        RetryPolicy::Fixed {
            delay: Duration::from_millis(1),
        },
        move |task, context| {
            let handler_operations = std::sync::Arc::clone(&handler_operations);
            async move {
                context
                    .step(&StepName::new("external-effect").unwrap(), 0, || async move {
                        handler_operations.fetch_add(1, Ordering::SeqCst);
                        if task.attempt == 1 {
                            return Err(pgtask_worker::HandlerError::retryable("lost before checkpoint commit"));
                        }
                        Ok(json!({"committed": true}))
                    })
                    .await
            }
        },
    );
    let mut config = WorkerConfig::new(queue_name);
    config.poll_interval = Duration::from_secs(5);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            if store.get_task(task_id).await.unwrap().unwrap().state == TaskState::Succeeded {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    assert_eq!(operations.load(Ordering::SeqCst), 2);
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn durable_sleep_variants_release_the_worker_and_resume_once() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("durable-sleep-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("durable-sleep-handler-{suffix}")).unwrap();
    let mut request = EnqueueRequest::new(task_name.clone(), json!({}));
    request.queue_name = queue_name.clone();
    let task_id = store.enqueue(&request).await.unwrap().task_id;
    let mut registry = HandlerRegistry::new();
    registry.register_durable(
        task_name,
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_task, context| async move {
            assert!(!context.cancellation_token().is_cancelled());
            context
                .sleep_for(&StepName::new("short-sleep").unwrap(), 0, Duration::from_millis(50))
                .await?;
            context
                .sleep_until(
                    &StepName::new("short-sleep-until").unwrap(),
                    0,
                    Utc::now() + TimeDelta::milliseconds(50),
                )
                .await?;
            Ok(json!({"resumed": true}))
        },
    );
    let mut config = WorkerConfig::new(queue_name);
    config.poll_interval = Duration::from_secs(5);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let started_at = std::time::Instant::now();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let task = store.get_task(task_id).await.unwrap().unwrap();
            if task.state == TaskState::Succeeded {
                assert_eq!(task.attempt, 3);
                assert_eq!(task.result, Some(json!({"resumed": true})));
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    assert!(started_at.elapsed() >= Duration::from_millis(80));
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn durable_signal_wait_closes_the_lost_wakeup_race() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("durable-signal-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("durable-signal-handler-{suffix}")).unwrap();
    let mut request = EnqueueRequest::new(task_name.clone(), json!({}));
    request.queue_name = queue_name.clone();
    let task_id = store.enqueue(&request).await.unwrap().task_id;
    let mut registry = HandlerRegistry::new();
    registry.register_durable(
        task_name,
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_task, context| async move {
            let signal = context
                .wait_for_signal(
                    &StepName::new("approval-wait").unwrap(),
                    0,
                    &SignalName::new("approval").unwrap(),
                    0,
                    None,
                )
                .await?;
            Ok(json!({"signal": signal}))
        },
    );
    let mut config = WorkerConfig::new(queue_name);
    config.poll_interval = Duration::from_secs(5);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            if store.get_task(task_id).await.unwrap().unwrap().state == TaskState::Waiting {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    store
        .emit_signal(
            task_id,
            &SignalName::new("approval").unwrap(),
            0,
            &json!({"approved": true}),
        )
        .await
        .unwrap();
    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let task = store.get_task(task_id).await.unwrap().unwrap();
            if task.state == TaskState::Succeeded {
                assert_eq!(task.attempt, 2);
                assert_eq!(task.result, Some(json!({"signal": {"approved": true}})));
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn durable_signal_available_before_execution_completes_without_suspending() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("durable-ready-signal-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("durable-ready-signal-handler-{suffix}")).unwrap();
    let mut request = EnqueueRequest::new(task_name.clone(), json!({}));
    request.queue_name = queue_name.clone();
    let task_id = store.enqueue(&request).await.unwrap().task_id;
    store
        .emit_signal(
            task_id,
            &SignalName::new("approval").unwrap(),
            0,
            &json!({"approved": true}),
        )
        .await
        .unwrap();

    let mut registry = HandlerRegistry::new();
    registry.register_durable(
        task_name,
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_task, context| async move {
            context
                .wait_for_signal(
                    &StepName::new("ready-approval").unwrap(),
                    0,
                    &SignalName::new("approval").unwrap(),
                    0,
                    None,
                )
                .await
                .map(|signal| signal.unwrap_or(json!(null)))
        },
    );
    let worker = Worker::new(store.clone(), registry, WorkerConfig::new(queue_name)).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let task = store.get_task(task_id).await.unwrap().unwrap();
            if task.state == TaskState::Succeeded {
                assert_eq!(task.attempt, 1);
                assert_eq!(task.result, Some(json!({"approved": true})));
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn worker_accepts_shutdown_before_runtime_loops_start() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("pre-cancelled-worker-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("pre-cancelled-handler-{suffix}")).unwrap();
    let worker = Worker::new(store, successful_registry(&task_name), WorkerConfig::new(queue_name)).unwrap();
    let shutdown = CancellationToken::new();
    shutdown.cancel();
    worker.run(shutdown).await.unwrap();
}

#[tokio::test]
async fn durable_signal_timeout_uses_the_database_deadline() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("durable-signal-timeout-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("durable-signal-timeout-handler-{suffix}")).unwrap();
    let mut request = EnqueueRequest::new(task_name.clone(), json!({}));
    request.queue_name = queue_name.clone();
    let task_id = store.enqueue(&request).await.unwrap().task_id;
    let mut registry = HandlerRegistry::new();
    registry.register_durable(
        task_name,
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_task, context| async move {
            let signal = context
                .wait_for_signal(
                    &StepName::new("timeout-wait").unwrap(),
                    0,
                    &SignalName::new("never").unwrap(),
                    0,
                    Some(Duration::from_millis(50)),
                )
                .await?;
            Ok(json!({"signal": signal}))
        },
    );
    let mut config = WorkerConfig::new(queue_name);
    config.poll_interval = Duration::from_secs(5);
    config.schedule_reconciliation_interval = Duration::from_secs(5);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let task = store.get_task(task_id).await.unwrap().unwrap();
            if task.state == TaskState::Succeeded {
                assert_eq!(task.attempt, 2);
                assert_eq!(task.result, Some(json!({"signal": null})));
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn durable_signal_wait_rejects_a_stale_parent_lease() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("durable-stale-signal-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("durable-stale-signal-handler-{suffix}")).unwrap();
    let started = Arc::new(Notify::new());
    let release = Arc::new(Semaphore::new(0));
    let handler_started = Arc::clone(&started);
    let handler_release = Arc::clone(&release);
    let mut registry = HandlerRegistry::new();
    registry.register_durable(
        task_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        move |_task, context| {
            let started = Arc::clone(&handler_started);
            let release = Arc::clone(&handler_release);
            async move {
                started.notify_one();
                release.acquire().await.unwrap().forget();
                context
                    .wait_for_signal(
                        &StepName::new("stale-signal").unwrap(),
                        0,
                        &SignalName::new("unused").unwrap(),
                        0,
                        None,
                    )
                    .await
                    .map(|_| json!(null))
            }
        },
    );
    let mut request = EnqueueRequest::new(task_name, json!({}));
    request.queue_name = queue_name.clone();
    let task_id = store.enqueue(&request).await.unwrap().task_id;
    let worker = Worker::new(store.clone(), registry, WorkerConfig::new(queue_name)).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, started.notified()).await.unwrap();
    assert!(store.cancel(task_id).await.unwrap());
    release.add_permits(1);
    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            if store.get_task(task_id).await.unwrap().unwrap().state == TaskState::Cancelled {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn shutdown_aborts_handlers_after_the_grace_period() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("shutdown-grace-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("shutdown-grace-handler-{suffix}")).unwrap();
    let started = Arc::new(Notify::new());
    let handler_started = Arc::clone(&started);
    let mut registry = HandlerRegistry::new();
    registry.register(
        task_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        move |_task| {
            let started = Arc::clone(&handler_started);
            async move {
                started.notify_one();
                std::future::pending().await
            }
        },
    );
    let mut request = EnqueueRequest::new(task_name, json!({}));
    request.queue_name = queue_name.clone();
    request.max_attempts = 1;
    store.enqueue(&request).await.unwrap();
    let mut config = WorkerConfig::new(queue_name.clone());
    config.lease_duration = Duration::from_millis(30);
    config.shutdown_grace = Duration::from_millis(20);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, started.notified()).await.unwrap();
    shutdown.cancel();
    tokio::time::timeout(Duration::from_secs(1), worker_task)
        .await
        .unwrap()
        .unwrap()
        .unwrap();
    tokio::time::sleep(Duration::from_millis(30)).await;
    store.recover_expired(&queue_name, 1).await.unwrap();
}

#[tokio::test]
async fn shutdown_drains_handlers_that_finish_within_the_grace_period() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("shutdown-drain-{suffix}")).unwrap();
    let task_name = TaskName::new(format!("shutdown-drain-handler-{suffix}")).unwrap();
    let started = Arc::new(Notify::new());
    let release = Arc::new(Semaphore::new(0));
    let handler_started = Arc::clone(&started);
    let handler_release = Arc::clone(&release);
    let mut registry = HandlerRegistry::new();
    registry.register(
        task_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        move |_task| {
            let started = Arc::clone(&handler_started);
            let release = Arc::clone(&handler_release);
            async move {
                started.notify_one();
                release.acquire().await.unwrap().forget();
                Ok(json!({"drained": true}))
            }
        },
    );
    let mut request = EnqueueRequest::new(task_name, json!({}));
    request.queue_name = queue_name.clone();
    let task_id = store.enqueue(&request).await.unwrap().task_id;
    let worker = Worker::new(store.clone(), registry, WorkerConfig::new(queue_name)).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, started.notified()).await.unwrap();
    shutdown.cancel();
    release.add_permits(1);
    worker_task.await.unwrap().unwrap();
    let task = store.get_task(task_id).await.unwrap().unwrap();
    assert_eq!(task.state, TaskState::Succeeded);
    assert_eq!(task.result, Some(json!({"drained": true})));
}

#[tokio::test]
async fn durable_result_wait_releases_the_worker_until_the_child_finishes() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();

    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("durable-result-{suffix}")).unwrap();
    let parent_name = TaskName::new(format!("durable-result-parent-{suffix}")).unwrap();
    let child_name = TaskName::new(format!("durable-result-child-{suffix}")).unwrap();
    let mut parent_request = EnqueueRequest::new(parent_name.clone(), json!({}));
    parent_request.queue_name = queue_name.clone();
    let parent_id = store.enqueue(&parent_request).await.unwrap().task_id;

    let mut registry = HandlerRegistry::new();
    let child_name_for_parent = child_name.clone();
    let queue_name_for_parent = queue_name.clone();
    registry.register_durable(
        parent_name,
        HandlerVersion::default(),
        RetryPolicy::Never,
        move |_task, context| {
            let child_name = child_name_for_parent.clone();
            let queue_name = queue_name_for_parent.clone();
            async move {
                let mut child_request = EnqueueRequest::new(child_name, json!({}));
                child_request.queue_name = queue_name;
                let child_id = context
                    .spawn(&StepName::new("spawn-child").unwrap(), 0, &child_request)
                    .await?;
                context
                    .wait_for_result(&StepName::new("child-result").unwrap(), 0, child_id, None)
                    .await
            }
        },
    );
    registry.register(
        child_name,
        HandlerVersion::default(),
        RetryPolicy::Never,
        |_task| async { Ok(json!({"child": "finished"})) },
    );
    let mut config = WorkerConfig::new(queue_name);
    config.concurrency = NonZeroU16::new(1).unwrap();
    config.poll_interval = Duration::from_secs(5);
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let parent = store.get_task(parent_id).await.unwrap().unwrap();
            if parent.state == TaskState::Succeeded {
                assert_eq!(parent.attempt, 2);
                assert_eq!(
                    parent.result,
                    Some(json!({
                        "state": "succeeded",
                        "result": {"child": "finished"},
                        "error": null
                    }))
                );
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn durable_result_wait_handles_ready_and_stale_parents() {
    let Some(database_url) = database_url() else {
        return;
    };
    let store = Store::connect(&database_url).await.unwrap();
    store.migrate().await.unwrap();
    let suffix = Uuid::new_v4();
    let queue_name = QueueName::new(format!("durable-ready-result-{suffix}")).unwrap();
    // Each parent spawns a child under its own name. Sharing one name lets complete_ready_child
    // claim the other parent's child, leaving the ready parent waiting on a child nobody finishes.
    let child_name = TaskName::new(format!("durable-ready-child-{suffix}")).unwrap();
    let stale_child_name = TaskName::new(format!("durable-stale-child-{suffix}")).unwrap();
    let parent_name = TaskName::new(format!("durable-ready-parent-{suffix}")).unwrap();
    let stale_name = TaskName::new(format!("durable-stale-parent-{suffix}")).unwrap();

    let mut child_request = EnqueueRequest::new(child_name.clone(), json!({}));
    child_request.queue_name = queue_name.clone();
    let mut stale_child_request = EnqueueRequest::new(stale_child_name, json!({}));
    stale_child_request.queue_name = queue_name.clone();

    let mut registry = HandlerRegistry::new();
    let ready_store = store.clone();
    let ready_child_name = child_name.clone();
    let ready_child_request = child_request.clone();
    registry.register_durable(
        parent_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        move |_task, context| {
            let store = ready_store.clone();
            let child_name = ready_child_name.clone();
            let child_request = ready_child_request.clone();
            async move {
                let child_id = context
                    .spawn(&StepName::new("spawn-ready").unwrap(), 0, &child_request)
                    .await?;
                complete_ready_child(&store, &child_request.queue_name, &child_name).await?;
                context
                    .wait_for_result(&StepName::new("already-ready").unwrap(), 0, child_id, None)
                    .await
            }
        },
    );
    let started = Arc::new(Notify::new());
    let release = Arc::new(Semaphore::new(0));
    let handler_started = Arc::clone(&started);
    let handler_release = Arc::clone(&release);
    registry.register_durable(
        stale_name.clone(),
        HandlerVersion::default(),
        RetryPolicy::Never,
        move |_task, context| {
            let started = Arc::clone(&handler_started);
            let release = Arc::clone(&handler_release);
            let child_request = stale_child_request.clone();
            async move {
                let child_id = context
                    .spawn(&StepName::new("spawn-stale").unwrap(), 0, &child_request)
                    .await?;
                started.notify_one();
                release.acquire().await.unwrap().forget();
                context
                    .wait_for_result(&StepName::new("stale-result").unwrap(), 0, child_id, None)
                    .await
            }
        },
    );

    let mut parent_request = EnqueueRequest::new(parent_name, json!({}));
    parent_request.queue_name = queue_name.clone();
    let parent_id = store.enqueue(&parent_request).await.unwrap().task_id;
    let mut stale_request = EnqueueRequest::new(stale_name, json!({}));
    stale_request.queue_name = queue_name.clone();
    let stale_id = store.enqueue(&stale_request).await.unwrap().task_id;
    let mut config = WorkerConfig::new(queue_name);
    config.concurrency = NonZeroU16::new(2).unwrap();
    let worker = Worker::new(store.clone(), registry, config).unwrap();
    let shutdown = CancellationToken::new();
    let worker_shutdown = shutdown.clone();
    let worker_task = tokio::spawn(async move { worker.run(worker_shutdown).await });

    tokio::time::timeout(TEST_TIMEOUT, started.notified()).await.unwrap();
    assert!(store.cancel(stale_id).await.unwrap());
    release.add_permits(1);
    let expected = json!({"state": "succeeded", "result": {"ready": true}, "error": null});
    tokio::time::timeout(TEST_TIMEOUT, async {
        loop {
            let parent = store.get_task(parent_id).await.unwrap().unwrap();
            let stale = store.get_task(stale_id).await.unwrap().unwrap();
            if parent.state == TaskState::Succeeded && stale.state == TaskState::Cancelled {
                assert_eq!(parent.result, Some(expected));
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .unwrap();
    shutdown.cancel();
    worker_task.await.unwrap().unwrap();
}

#[tokio::test]
async fn worker_refuses_to_start_against_an_unmigrated_database() {
    let Some(database_url) = database_url() else {
        return;
    };
    let database_name = format!("pgtask_unmigrated_{}", Uuid::new_v4().simple());
    let options = PgConnectOptions::from_str(&database_url).unwrap();
    let maintenance = PgPool::connect_with(options.clone().database("postgres"))
        .await
        .unwrap();
    sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {database_name}")))
        .execute(&maintenance)
        .await
        .unwrap();

    // Deliberately not migrated: this is a worker that won the race against its migration Job.
    let store = Store::from_pool(PgPool::connect_with(options.database(&database_name)).await.unwrap());
    let task_name = TaskName::new("unmigrated-task").unwrap();
    let queue_name = QueueName::new(format!("unmigrated-{}", Uuid::new_v4())).unwrap();
    let worker = Worker::new(store, successful_registry(&task_name), WorkerConfig::new(queue_name)).unwrap();

    // It must fail rather than idle, because a deployment orders the migration before the workers
    // and a silent worker would look healthy while doing nothing.
    let error = tokio::time::timeout(TEST_TIMEOUT, worker.run(CancellationToken::new()))
        .await
        .expect("worker idled instead of failing")
        .expect_err("worker started without a schema");
    let message = error.to_string();
    assert!(
        message.contains("schema \"pgtask\" does not exist"),
        "the error should say the schema is missing rather than anything vaguer: {message}"
    );

    sqlx::query(sqlx::AssertSqlSafe(format!(
        "DROP DATABASE {database_name} WITH (FORCE)"
    )))
    .execute(&maintenance)
    .await
    .unwrap();
}