hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
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
//! The worker's `DurableTask` stream: one per worker, for every durable run it
//! is executing.
//!
//! Network-agnostic on purpose, exactly like [`crate::runs::listener`]: [`run`]
//! is handed a function that opens one stream, so the register-on-connect rule,
//! the two tables and the completion buffer can be tested against a scripted
//! stream rather than a socket.
//!
//! Five rules matter more than the rest:
//!
//! * **The engine assigns `node_id` and `branch_id`, not this SDK.** No request
//!   carries them (`api-contracts/v1/dispatcher.proto:99-141`); every ack hands
//!   one back (`:39-60`). What the SDK must get right is the *order* of its
//!   requests, which is why one invocation's requests are serialised by its
//!   caller rather than here.
//! * **Every connection starts with `register_worker`, queued before the call
//!   is awaited** — unlike `ListenV2`, whose one request opens the stream for
//!   good. Queuing first is not a nicety: both supported engines send no
//!   response headers on this RPC until the worker has said something, so
//!   awaiting the call with an empty request stream never returns.
//! * **`worker_status` goes out every second, not once.** It is how the engine
//!   learns which entries this worker is still waiting for, and a single
//!   announcement after a reconnect was measured to deliver *nothing*: a
//!   completed entry then sat in the engine's log for as long as the worker
//!   cared to wait. The ticker is correctness, not insurance. Re-sending the
//!   `wait_for` instead would not recover it either — that makes a *second* log
//!   entry and breaks the next attempt's determinism.
//! * **An ack does not survive a reconnect; a wait does.** A request that was
//!   in flight may or may not have reached the engine, and sending it again
//!   would make a second log entry — so the attempt fails. A wait lives in the
//!   engine's event log, so the new connection announces it with
//!   `worker_status` and carries on waiting.
//! * **A completion can arrive before anything waits for it** — between an ack
//!   and the caller registering, and for the node an inline-payload `memo`
//!   creates, which is completed at once and which nobody ever waits for.
//!   Unclaimed completions are kept for [`COMPLETION_TTL`] and then dropped.

use std::collections::{HashMap, VecDeque};
use std::pin::Pin;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;

use hatchet_proto::v1::DurableTaskEvictInvocationRequest;
use hatchet_proto::v1::v1_dispatcher_client::V1DispatcherClient;
use hatchet_proto::v1::{
    DurableEventListenerConditions, DurableEventLogEntryRef, DurableTaskAwaitedCompletedEntry,
    DurableTaskCompleteMemoRequest, DurableTaskErrorResponse, DurableTaskErrorType,
    DurableTaskEventLogEntryCompletedResponse, DurableTaskEventMemoAckResponse,
    DurableTaskMemoRequest, DurableTaskRequest, DurableTaskRequestRegisterWorker,
    DurableTaskResponse, DurableTaskRunAckEntry, DurableTaskServerEvictNotice,
    DurableTaskTriggerRunsRequest, DurableTaskWaitForRequest, DurableTaskWorkerStatusRequest,
    TriggerWorkflowRequest, durable_task_request, durable_task_response,
};
use tokio::sync::{Notify, mpsc, oneshot};
use tokio::time::Instant;
use tokio_stream::wrappers::ReceiverStream;
use tokio_stream::{Stream, StreamExt};
use tokio_util::sync::CancellationToken;
use tonic::Status;
use tonic::codec::CompressionEncoding;

use crate::Error;
use crate::retry::{
    STREAM_MAX_CONSECUTIVE_OTHER_FAILURES, StreamErrorClass, classify_stream_end, full_jitter,
    stream_backoff_cap,
};
use crate::transport::GrpcService;

/// How long a caller waits for the engine to acknowledge a durable request
/// before the attempt is failed.
///
/// The same sixty seconds the official Python SDK uses
/// (`durable_event_listener.py:587`), for the same reason: a request lost on
/// the stream would otherwise stop the handler for ever.
const ACK_TIMEOUT: Duration = Duration::from_secs(60);

/// How long the worker waits for the engine to acknowledge an eviction before
/// giving up on it.
///
/// The official Python SDK's value for this one request
/// (`durable_event_listener.py:792-812`), and deliberately shorter than
/// [`ACK_TIMEOUT`]: an eviction that is not acknowledged must not keep a durable
/// slot occupied for a whole minute — the run it would have freed is still
/// parked. Measured against both supported engines the ack comes back in under
/// six milliseconds (P7 Task 0 probe C).
const EVICTION_ACK_TIMEOUT: Duration = Duration::from_secs(30);

/// How long a completion nobody is waiting for is kept, in case its waiter is
/// still being registered. The official Go SDK's value
/// (`durable_task_listener.go:22`).
///
/// It doubles as the window in which a *consumed* entry's ref is remembered, so
/// the engine's re-deliveries of it are dropped rather than buffered — see
/// [`State::consumed`].
const COMPLETION_TTL: Duration = Duration::from_secs(10);

/// How often the worker re-announces what it is waiting for. Go and Python both
/// use one second (`durable_task_listener.go:21`,
/// `durable_event_listener.py:313-318`), and both supported engines were
/// measured needing it: one announcement per connection delivered nothing at
/// all.
const WORKER_STATUS_INTERVAL: Duration = Duration::from_secs(1);

/// How many durable requests may sit unsent on one connection.
///
/// Bounded for the same reason as the run listener's queue: a connection the
/// engine has stopped reading errors the reserve, which ends the stream and
/// reconnects.
const REQUEST_BUFFER: usize = 64;

/// The requests one connection is handed.
pub(crate) type RequestStream = ReceiverStream<DurableTaskRequest>;

/// The responses one connection is answered with.
type ResponseStream =
    Pin<Box<dyn Stream<Item = Result<DurableTaskResponse, Status>> + Send + 'static>>;

/// The connect function [`DurableStream::new`] is handed against a real engine:
/// it opens one `DurableTask` stream, with `requests` as the worker's half.
///
/// No `set_timeout` and no [`crate::retry::unary`], for the same reasons as the
/// worker's action stream: a deadline would cut off a durable wait that is
/// simply taking its time, and reconnecting is the loop's own job.
pub(crate) fn connect(
    service: GrpcService,
    gzip: bool,
) -> impl FnMut(RequestStream) -> Pin<Box<dyn Future<Output = Result<ResponseStream, Status>> + Send>>
{
    move |requests| {
        let dispatcher =
            V1DispatcherClient::new(service.clone()).accept_compressed(CompressionEncoding::Gzip);
        let mut dispatcher = if gzip {
            dispatcher.send_compressed(CompressionEncoding::Gzip)
        } else {
            dispatcher
        };
        Box::pin(async move {
            let responses = dispatcher.durable_task(requests).await?.into_inner();
            Ok(Box::pin(responses) as ResponseStream)
        })
    }
}

/// The loop, built at construction and spawned by [`DurableStream::start`].
type LoopFuture = Pin<Box<dyn Future<Output = ()> + Send>>;

/// What the worker does when the engine evicts one invocation.
type EvictHook = Arc<dyn Fn(&str, i32) + Send + Sync>;

/// Sends durable requests and answers durable waits for one worker.
///
/// Cheap to clone; every clone talks to the same stream.
#[derive(Clone)]
pub(crate) struct DurableStream {
    shared: Arc<Shared>,
    /// The loop, until [`start`](DurableStream::start) spawns it.
    ///
    /// Held beside `shared` rather than inside it: the future owns an
    /// `Arc<Shared>`, so parking it *in* `Shared` would be a cycle that never
    /// frees a worker which never started.
    task: Arc<Mutex<Option<LoopFuture>>>,
}

impl DurableStream {
    /// Builds a stream that opens its connections with `connect` and ends for
    /// good when `stop` fires.
    ///
    /// Nothing is spawned here: a worker with no durable tasks holds no stream.
    pub(crate) fn new<C, Fut, S>(worker_id: String, connect: C, stop: CancellationToken) -> Self
    where
        C: FnMut(RequestStream) -> Fut + Send + 'static,
        Fut: Future<Output = Result<S, Status>> + Send + 'static,
        S: Stream<Item = Result<DurableTaskResponse, Status>> + Send + Unpin + 'static,
    {
        Self::with_backoff(worker_id, connect, stop, |attempt| {
            full_jitter(stream_backoff_cap(attempt), &mut rand::rng())
        })
    }

    /// [`new`](DurableStream::new) with the delay before reconnect number
    /// `attempt` (0-based) chosen by `backoff` rather than by the SDK's policy.
    ///
    /// The seam exists for the tests: under full jitter the real delay may be
    /// any length including zero, so no assertion on elapsed time can tell a
    /// backoff that is there from one that was deleted.
    fn with_backoff<C, Fut, S, B>(
        worker_id: String,
        connect: C,
        stop: CancellationToken,
        backoff: B,
    ) -> Self
    where
        C: FnMut(RequestStream) -> Fut + Send + 'static,
        Fut: Future<Output = Result<S, Status>> + Send + 'static,
        S: Stream<Item = Result<DurableTaskResponse, Status>> + Send + Unpin + 'static,
        B: FnMut(u32) -> Duration + Send + 'static,
    {
        let shared = Arc::new(Shared::new(worker_id));
        let task: LoopFuture = Box::pin(run(connect, Arc::clone(&shared), stop, backoff));
        Self {
            shared,
            task: Arc::new(Mutex::new(Some(task))),
        }
    }

    /// Spawns the loop, which opens the stream and holds it open. Called by the
    /// worker; calling it again does nothing.
    pub(crate) fn start(&self) {
        // Taken out of the lock before spawning: `tokio::spawn` may poll the
        // future straight away, and it must not find this lock held.
        let task = lock(&self.task).take();
        if let Some(task) = task {
            tokio::spawn(task);
        }
    }

    /// Sends `wait_for` and hands back the log entry the engine made for it.
    ///
    /// Bounded by [`ACK_TIMEOUT`]; waiting for that entry to *complete* is
    /// [`wait_for_entry`](DurableStream::wait_for_entry), which is not bounded
    /// — a durable wait may take as long as its condition takes.
    ///
    /// The caller serialises one invocation's requests: the engine's ack says
    /// only which `(task, invocation)` it belongs to, so two requests in flight
    /// for one invocation cannot be told apart. A second one that arrives while
    /// the first is unanswered is refused rather than allowed to steal its ack.
    pub(crate) async fn send_wait_for(
        &self,
        task_id: String,
        invocation_count: i32,
        conditions: DurableEventListenerConditions,
        label: Option<String>,
    ) -> crate::Result<DurableEventLogEntryRef> {
        let request = request(durable_task_request::Message::WaitFor(
            DurableTaskWaitForRequest {
                invocation_count,
                durable_task_external_id: task_id.clone(),
                wait_for_conditions: Some(conditions),
                label,
            },
        ));
        match self.acked(&task_id, invocation_count, request).await? {
            Ack::Wait(reference) => Ok(reference),
            Ack::Memo(_) | Ack::Trigger(_) => Err(mismatched_ack(&task_id, invocation_count)),
        }
    }

    /// Sends `memo` and hands back what the engine knows about that key.
    ///
    /// `payload` is `None` for a lookup — "do you already have this?" — and
    /// `Some` to record the value in the same breath, which the engine
    /// completes straight away.
    pub(crate) async fn send_memo(
        &self,
        task_id: String,
        invocation_count: i32,
        key: &str,
        payload: Option<Vec<u8>>,
    ) -> crate::Result<MemoAck> {
        let request = request(durable_task_request::Message::Memo(
            DurableTaskMemoRequest {
                invocation_count,
                durable_task_external_id: task_id.clone(),
                // The user's string, byte for byte, as the Go SDK sends it
                // (`pkg/worker/context.go:1285`).
                key: key.as_bytes().to_vec(),
                payload,
            },
        ));
        match self.acked(&task_id, invocation_count, request).await? {
            Ack::Memo(ack) => Ok(ack),
            Ack::Wait(_) | Ack::Trigger(_) => Err(mismatched_ack(&task_id, invocation_count)),
        }
    }

    /// Sends `trigger_runs` and hands back the log entries the engine made, one
    /// per trigger and in the order they were sent.
    ///
    /// The engine was measured consuming **one log node per `trigger_opts`
    /// entry** and answering with `run_entries` in the same order (P7 Task 0
    /// probe A), which is what lets the caller pair its handles up by position.
    ///
    /// Bounded by [`ACK_TIMEOUT`] like every other ack. Waiting for those
    /// entries to *complete* — which is how a durable child's result comes back
    /// — is [`claim_entry`](DurableStream::claim_entry).
    pub(crate) async fn send_trigger_runs(
        &self,
        task_id: String,
        invocation_count: i32,
        trigger_opts: Vec<TriggerWorkflowRequest>,
    ) -> crate::Result<Vec<DurableTaskRunAckEntry>> {
        let request = request(durable_task_request::Message::TriggerRuns(
            DurableTaskTriggerRunsRequest {
                invocation_count,
                durable_task_external_id: task_id.clone(),
                trigger_opts,
            },
        ));
        match self.acked(&task_id, invocation_count, request).await? {
            Ack::Trigger(entries) => Ok(entries),
            Ack::Wait(_) | Ack::Memo(_) => Err(mismatched_ack(&task_id, invocation_count)),
        }
    }

    /// Sends `complete_memo`: the value for an entry an earlier
    /// [`send_memo`](DurableStream::send_memo) opened.
    ///
    /// Fire and forget, as in both official SDKs: the engine sends no ack for
    /// it, and the handler has the value already.
    pub(crate) fn send_complete_memo(
        &self,
        reference: DurableEventLogEntryRef,
        key: &str,
        payload: Vec<u8>,
    ) {
        self.queue(request(durable_task_request::Message::CompleteMemo(
            DurableTaskCompleteMemoRequest {
                r#ref: Some(reference),
                payload,
                memo_key: key.as_bytes().to_vec(),
            },
        )));
    }

    /// Sends `evict_invocation` — this worker is giving up one invocation's
    /// place — and waits for the engine to record it.
    ///
    /// The caller cancels the run only once this returns: evicting locally
    /// while the engine still believes the worker holds the invocation would
    /// leave the run parked on nothing at all. Bounded by
    /// [`EVICTION_ACK_TIMEOUT`]; a timeout leaves the run alone.
    ///
    /// The request survives a reconnect ([`Shared::fail_acks`] keeps it), and
    /// so does this waiter: the engine may well answer it on the next
    /// connection.
    ///
    /// Its one caller is the worker's eviction manager
    /// ([`crate::durable::eviction::run`]), as in the official SDKs
    /// (`sdks/go/client.go:294`, `sdks/python/…/runner/runner.py:270`): an
    /// eviction is a decision about the *worker's* slots, so nothing a handler
    /// can reach makes one.
    pub(crate) async fn send_evict(
        &self,
        task_id: &str,
        invocation_count: i32,
        reason: Option<String>,
    ) -> crate::Result<()> {
        let key = (task_id.to_string(), invocation_count);
        let answered = {
            let mut state = self.shared.lock();
            if state.stopped {
                return Err(stopped());
            }
            if state.evictions.contains_key(&key) {
                return Err(overlapping_eviction(task_id, invocation_count));
            }
            let (answer, answered) = oneshot::channel();
            state.evictions.insert(key.clone(), answer);
            state
                .outgoing
                .push_back(request(durable_task_request::Message::EvictInvocation(
                    DurableTaskEvictInvocationRequest {
                        invocation_count,
                        durable_task_external_id: task_id.to_string(),
                        reason,
                    },
                )));
            answered
        };
        self.shared.work.notify_one();
        let _registered = EvictionGuard {
            shared: Arc::clone(&self.shared),
            key,
        };
        match tokio::time::timeout(EVICTION_ACK_TIMEOUT, answered).await {
            Ok(Ok(())) => Ok(()),
            Ok(Err(_)) => Err(stopped()),
            Err(_) => Err(eviction_timed_out(task_id, invocation_count)),
        }
    }

    /// Registers a waiter for one log entry **now**, and hands back the future
    /// that yields its payload.
    ///
    /// Splitting registration from the wait is what makes several outstanding
    /// children safe: a caller that spawns three and then awaits them one at a
    /// time would otherwise be registering the second waiter long after its
    /// completion arrived, and an unclaimed completion only lives
    /// [`COMPLETION_TTL`].
    ///
    /// Dropping the returned [`EntryWait`] gives the wait up — but **not** the
    /// log entry, which the engine has already made; a completion that arrives
    /// for it afterwards expires out of the buffer.
    pub(crate) fn claim_entry(
        &self,
        reference: DurableEventLogEntryRef,
    ) -> crate::Result<EntryWait> {
        let answered = {
            let mut state = self.shared.lock();
            if state.stopped {
                return Err(stopped());
            }
            state.prune_expired();
            // The buffer first: for an inline memo the engine completes the
            // entry before the ack is even read, and for anything else the
            // completion can overtake the caller between the two.
            if let Some((completed, _)) = state.unclaimed.remove(&reference) {
                state.consume(&reference);
                return Ok(EntryWait::Completed(Box::new(
                    completed.into_payload(&reference),
                )));
            }
            if state.waits.contains_key(&reference) || state.consumed.contains_key(&reference) {
                // A log entry completes once, so a second waiter for it would
                // wait for ever; refusing loudly is the kinder answer.
                return Err(duplicate_wait(&reference));
            }
            let (answer, answered) = oneshot::channel();
            state.waits.insert(reference.clone(), answer);
            // The new entry goes into the next `worker_status`, which is how
            // the engine learns to deliver its completion here.
            state.announce = true;
            answered
        };
        self.shared.work.notify_one();
        Ok(EntryWait::Pending {
            answered,
            reference: reference.clone(),
            _registered: WaitGuard {
                shared: Arc::clone(&self.shared),
                reference,
            },
        })
    }

    /// [`claim_entry`](DurableStream::claim_entry) and the wait in one, for the
    /// callers that do nothing in between.
    ///
    /// No time limit: a durable wait takes as long as its condition takes.
    pub(crate) async fn wait_for_entry(
        &self,
        reference: DurableEventLogEntryRef,
    ) -> crate::Result<Vec<u8>> {
        self.claim_entry(reference)?.completed().await
    }

    /// Ends every wait and ack for `task_id` at or below `invocation_count`,
    /// and forgets the completions buffered for them.
    ///
    /// What an eviction means for this table: that invocation is stale, so
    /// nothing it is waiting for will ever be delivered here.
    ///
    /// The live path into this is [`Shared::cleanup`], which the `server_evict`
    /// branch calls as the response arrives; this wrapper is what lets a test
    /// exercise the same table without a response to deliver.
    #[cfg(test)]
    pub(crate) fn cleanup(&self, task_id: &str, invocation_count: i32, reason: &str) {
        self.shared.cleanup(task_id, invocation_count, reason);
    }

    /// What to do when the engine evicts an invocation. Set once by the worker;
    /// the runner's cancellation is what it reaches.
    pub(crate) fn on_server_evict(&self, hook: impl Fn(&str, i32) + Send + Sync + 'static) {
        *lock(&self.shared.evict) = Some(Arc::new(hook));
    }

    /// Completes with the error that ended this stream for good, and never
    /// completes otherwise — including when the worker stopped it on purpose.
    ///
    /// The worker selects on it beside the action stream: a durable stream
    /// that has been given up on has already failed every wait on it, and
    /// every durable task assigned from then on would fail on its first step,
    /// so it is as fatal to the worker as an action stream that ended.
    pub(crate) fn given_up(&self) -> impl Future<Output = Error> + Send + 'static {
        let shared = Arc::clone(&self.shared);
        async move {
            shared.gave_up.cancelled().await;
            let status = lock(&shared.fatal)
                .clone()
                .unwrap_or_else(|| Status::unknown("the durable task stream ended"));
            Error::Grpc(Box::new(status))
        }
    }

    /// Queues a request that has no ack of its own.
    fn queue(&self, request: DurableTaskRequest) {
        {
            let mut state = self.shared.lock();
            if state.stopped {
                return;
            }
            state.outgoing.push_back(request);
        }
        self.shared.work.notify_one();
    }

    /// Queues `request` and waits for the engine to name the entry it made.
    async fn acked(
        &self,
        task_id: &str,
        invocation_count: i32,
        request: DurableTaskRequest,
    ) -> crate::Result<Ack> {
        let key = (task_id.to_string(), invocation_count);
        let answered = {
            let mut state = self.shared.lock();
            if state.stopped {
                return Err(stopped());
            }
            if state.acks.contains_key(&key) {
                return Err(overlapping_request(task_id, invocation_count));
            }
            let (answer, answered) = oneshot::channel();
            // Registered before the request is queued: an ack that comes back
            // before the caller is in the table would have nowhere to go.
            state.acks.insert(key.clone(), answer);
            state.outgoing.push_back(request);
            answered
        };
        self.shared.work.notify_one();
        let _registered = AckGuard {
            shared: Arc::clone(&self.shared),
            key,
        };
        match tokio::time::timeout(ACK_TIMEOUT, answered).await {
            Ok(Ok(ack)) => ack,
            Ok(Err(_)) => Err(stopped()),
            Err(_) => Err(ack_timed_out(task_id, invocation_count)),
        }
    }

    /// How many completions nobody has claimed are still live. Expired ones are
    /// dropped as they are counted, exactly as a waiter arriving would.
    #[cfg(test)]
    fn buffered_completions(&self) -> usize {
        let mut state = self.shared.lock();
        state.prune_expired();
        state.unclaimed.len()
    }
}

/// What the engine knows about one memo key.
#[derive(Debug)]
pub(crate) struct MemoAck {
    /// The log entry the engine made for this memo.
    pub(crate) reference: DurableEventLogEntryRef,
    /// The value an earlier invocation recorded, if there is one.
    pub(crate) existing: Option<Vec<u8>>,
}

/// One answered durable request.
#[derive(Debug)]
enum Ack {
    Wait(DurableEventLogEntryRef),
    Memo(MemoAck),
    /// The entries the engine made for one `trigger_runs`: one per trigger, in
    /// the order they were sent.
    Trigger(Vec<DurableTaskRunAckEntry>),
}

/// One registered wait for a log entry, until its payload is asked for.
///
/// Dropping it gives the wait up — the engine's entry is untouched, and a
/// completion that arrives afterwards expires out of the buffer.
pub(crate) enum EntryWait {
    /// The engine had already completed the entry when it was claimed.
    Completed(Box<crate::Result<Vec<u8>>>),
    /// The usual case: registered in the table, waiting to be answered.
    Pending {
        answered: oneshot::Receiver<crate::Result<Completed>>,
        reference: DurableEventLogEntryRef,
        _registered: WaitGuard,
    },
}

impl EntryWait {
    /// The entry's payload, or the failure the engine recorded for it.
    ///
    /// No time limit: a durable wait takes as long as its condition takes.
    pub(crate) async fn completed(self) -> crate::Result<Vec<u8>> {
        match self {
            Self::Completed(payload) => *payload,
            Self::Pending {
                answered,
                reference,
                _registered,
            } => match answered.await {
                Ok(completed) => completed?.into_payload(&reference),
                Err(_) => Err(stopped()),
            },
        }
    }
}

/// One completed log entry.
pub(crate) struct Completed {
    payload: Vec<u8>,
    is_failure: bool,
    error_message: Option<String>,
}

impl Completed {
    /// The payload, or the failure the engine reported instead of it.
    ///
    /// A failed entry is never quietly turned into an empty success: the engine
    /// is saying the thing that was waited for went wrong.
    fn into_payload(self, reference: &DurableEventLogEntryRef) -> crate::Result<Vec<u8>> {
        if self.is_failure {
            return Err(Error::DurableEntryFailed {
                task_run_id: reference.durable_task_external_id.clone(),
                invocation_count: reference.invocation_count,
                node_id: reference.node_id,
                message: self
                    .error_message
                    .unwrap_or_else(|| "the engine reported no reason".to_string()),
            });
        }
        Ok(self.payload)
    }
}

/// Everything the loop and the callers share.
struct Shared {
    worker_id: String,
    state: Mutex<State>,
    /// Wakes the loop when there is a request to send or a wait to announce.
    work: Notify,
    evict: Mutex<Option<EvictHook>>,
    /// Fires when the loop gives up for good — a fatal status, or too many
    /// unclassified failures in a row. A `stop` that the worker asked for does
    /// **not** fire it: there is nothing to report about a clean shutdown.
    gave_up: CancellationToken,
    /// What ended it, read once `gave_up` has fired.
    fatal: Mutex<Option<Status>>,
}

#[derive(Default)]
struct State {
    /// Requests queued for the current connection, in order.
    outgoing: VecDeque<DurableTaskRequest>,
    /// Whether the outstanding waits are due to be announced again.
    announce: bool,
    /// Waiting for the engine to name the log entry: one per
    /// `(task, invocation)`, because that is all the engine's ack carries to
    /// route by (`dispatcher.proto:39-53`).
    acks: HashMap<(String, i32), oneshot::Sender<crate::Result<Ack>>>,
    /// Waiting for the engine to confirm an eviction, by `(task, invocation)`.
    ///
    /// A table of its own rather than a variant of `acks`, for two reasons:
    /// `eviction_ack` carries no `ref`
    /// (`api-contracts/v1/dispatcher.proto:69-72`), so it cannot be routed the
    /// way every other ack is; and an eviction is sent by the worker's eviction
    /// manager, which knows nothing about the durable request the handler may
    /// be in the middle of — sharing one slot would let them steal each other's
    /// answers.
    evictions: HashMap<(String, i32), oneshot::Sender<()>>,
    /// Waiting for a log entry to complete, by the ref the engine gave.
    waits: HashMap<DurableEventLogEntryRef, oneshot::Sender<crate::Result<Completed>>>,
    /// Completions nobody has asked for yet, with the instant they expire.
    unclaimed: HashMap<DurableEventLogEntryRef, (Completed, Instant)>,
    /// Entries whose completion has already been handed to a caller, with the
    /// instant they may be forgotten.
    ///
    /// The engine's delivery is **level-triggered**: for as long as a
    /// `worker_status` lists an entry it completes the entry again on every
    /// announcement, once a second (P7 Task 0 probe B). Taking the waiter out
    /// of `waits` drops the entry from the next announcement, but the ones
    /// already in flight still arrive — and re-delivered payloads come back
    /// `jsonb`-normalised rather than byte-identical, so they must not be
    /// mistaken for a second, different completion. This table is what makes
    /// those copies a no-op instead of ten seconds of buffered rubbish.
    consumed: HashMap<DurableEventLogEntryRef, Instant>,
    /// The stream has ended for good: its worker is gone, or it was given up
    /// on.
    stopped: bool,
}

impl State {
    /// Forgets the completions whose waiter never came, and the consumed
    /// entries whose re-deliveries are long over.
    fn prune_expired(&mut self) {
        let now = Instant::now();
        self.unclaimed.retain(|_, (_, expires)| *expires > now);
        self.consumed.retain(|_, expires| *expires > now);
    }

    /// Records that `reference`'s completion has been handed to its caller, so
    /// the engine's re-deliveries of it are dropped.
    fn consume(&mut self, reference: &DurableEventLogEntryRef) {
        self.consumed
            .insert(reference.clone(), Instant::now() + COMPLETION_TTL);
    }

    /// Whether there is anything to put on the wire right now.
    fn has_pending(&self) -> bool {
        !self.outgoing.is_empty() || (self.announce && !self.waits.is_empty())
    }
}

impl Shared {
    fn new(worker_id: String) -> Self {
        Self {
            worker_id,
            state: Mutex::new(State::default()),
            work: Notify::new(),
            evict: Mutex::new(None),
            gave_up: CancellationToken::new(),
            fatal: Mutex::new(None),
        }
    }

    fn lock(&self) -> MutexGuard<'_, State> {
        lock(&self.state)
    }

    fn has_pending(&self) -> bool {
        self.lock().has_pending()
    }

    /// The next request to put on the wire: the announcement first, because a
    /// completion the engine is holding is worth more than anything queued
    /// behind it.
    fn take_pending(&self) -> Option<DurableTaskRequest> {
        let mut state = self.lock();
        if state.announce && !state.waits.is_empty() {
            state.announce = false;
            return Some(self.status_from(&state));
        }
        state.outgoing.pop_front()
    }

    /// Asks for the outstanding waits to be announced again, and drops the
    /// completions that expired in the meantime.
    fn announce(&self) {
        let mut state = self.lock();
        state.prune_expired();
        state.announce = true;
    }

    /// The `worker_status` a freshly opened connection starts with, or `None`
    /// when nothing is being waited for.
    fn worker_status(&self) -> Option<DurableTaskRequest> {
        let state = self.lock();
        (!state.waits.is_empty()).then(|| self.status_from(&state))
    }

    fn status_from(&self, state: &State) -> DurableTaskRequest {
        let mut waiting_entries: Vec<DurableTaskAwaitedCompletedEntry> = state
            .waits
            .keys()
            .map(|reference| DurableTaskAwaitedCompletedEntry {
                durable_task_external_id: reference.durable_task_external_id.clone(),
                branch_id: reference.branch_id,
                node_id: reference.node_id,
                invocation_count: reference.invocation_count,
            })
            .collect();
        // Sorted so the same set of waits always produces the same message,
        // whatever order the table happens to be in.
        waiting_entries.sort_by(|left, right| {
            (
                &left.durable_task_external_id,
                left.invocation_count,
                left.branch_id,
                left.node_id,
            )
                .cmp(&(
                    &right.durable_task_external_id,
                    right.invocation_count,
                    right.branch_id,
                    right.node_id,
                ))
        });
        request(durable_task_request::Message::WorkerStatus(
            DurableTaskWorkerStatusRequest {
                worker_id: self.worker_id.clone(),
                waiting_entries,
            },
        ))
    }

    /// Fails every request still waiting for an ack, because the connection it
    /// went out on is gone.
    ///
    /// The requests themselves are dropped rather than re-sent: one that did
    /// reach the engine made a log entry, and a second copy would make another.
    /// Only the requests with no ack of their own — `complete_memo`, which
    /// names an entry that already exists, and `evict_invocation` — are kept
    /// for the next connection.
    ///
    /// The `evictions` table is deliberately left alone: the
    /// `evict_invocation` request itself survives the reconnect, so the waiter
    /// for its ack survives with it and the engine may well answer it on the
    /// next connection.
    fn fail_acks(&self, status: Option<&Status>) {
        let acks = {
            let mut state = self.lock();
            state.outgoing.retain(|request| {
                matches!(
                    request.message,
                    Some(
                        durable_task_request::Message::CompleteMemo(_)
                            | durable_task_request::Message::EvictInvocation(_)
                    )
                )
            });
            std::mem::take(&mut state.acks)
        };
        if acks.is_empty() {
            return;
        }
        let status = status.cloned().unwrap_or_else(|| {
            Status::unavailable("the durable task stream ended before the engine answered")
        });
        for answer in acks.into_values() {
            drop(answer.send(Err(Error::Grpc(Box::new(status.clone())))));
        }
    }

    /// Fails everything, because the stream was given up on.
    fn fail_all(&self, status: &Status) {
        let (acks, waits) = {
            let mut state = self.lock();
            state.outgoing.clear();
            state.unclaimed.clear();
            state.consumed.clear();
            // Dropping the senders is the answer: an eviction waiter reads a
            // closed channel as the stream having ended, which it has.
            state.evictions.clear();
            (
                std::mem::take(&mut state.acks),
                std::mem::take(&mut state.waits),
            )
        };
        for answer in acks.into_values() {
            drop(answer.send(Err(Error::Grpc(Box::new(status.clone())))));
        }
        for answer in waits.into_values() {
            drop(answer.send(Err(Error::Grpc(Box::new(status.clone())))));
        }
    }

    /// Ends the stream: nothing will ever answer again.
    fn stop(&self) {
        {
            let mut state = self.lock();
            state.stopped = true;
        }
        self.fail_all(&Status::cancelled(GONE));
    }

    fn cleanup(&self, task_id: &str, invocation_count: i32, reason: &str) {
        let (acks, waits) = {
            let mut state = self.lock();
            state
                .unclaimed
                .retain(|reference, _| !stale(reference, task_id, invocation_count));
            state
                .consumed
                .retain(|reference, _| !stale(reference, task_id, invocation_count));
            // The engine has finished with this invocation, so there is no ack
            // left to wait for on an eviction of it; dropping the sender ends
            // the wait.
            state
                .evictions
                .retain(|(id, invocation), _| id != task_id || *invocation > invocation_count);
            let acks: Vec<_> = state
                .acks
                .keys()
                .filter(|(id, invocation)| id == task_id && *invocation <= invocation_count)
                .cloned()
                .collect();
            let acks: Vec<_> = acks
                .into_iter()
                .filter_map(|key| state.acks.remove(&key))
                .collect();
            let refs: Vec<_> = state
                .waits
                .keys()
                .filter(|reference| stale(reference, task_id, invocation_count))
                .cloned()
                .collect();
            let waits: Vec<_> = refs
                .into_iter()
                .filter_map(|reference| state.waits.remove(&reference))
                .collect();
            (acks, waits)
        };
        for answer in acks {
            drop(answer.send(Err(evicted(reason))));
        }
        for answer in waits {
            drop(answer.send(Err(evicted(reason))));
        }
    }
}

/// Whether `reference` belongs to an invocation of `task_id` at or below
/// `invocation_count`, which an eviction of that invocation makes stale.
fn stale(reference: &DurableEventLogEntryRef, task_id: &str, invocation_count: i32) -> bool {
    reference.durable_task_external_id == task_id && reference.invocation_count <= invocation_count
}

/// Keeps one pending ack in the table for as long as its caller is waiting.
struct AckGuard {
    shared: Arc<Shared>,
    key: (String, i32),
}

impl Drop for AckGuard {
    fn drop(&mut self) {
        self.shared.lock().acks.remove(&self.key);
    }
}

/// Keeps one waiter in the table for as long as its future lives.
pub(crate) struct WaitGuard {
    shared: Arc<Shared>,
    reference: DurableEventLogEntryRef,
}

impl Drop for WaitGuard {
    fn drop(&mut self) {
        self.shared.lock().waits.remove(&self.reference);
    }
}

/// Keeps one pending eviction in its table for as long as its caller is
/// waiting.
struct EvictionGuard {
    shared: Arc<Shared>,
    key: (String, i32),
}

impl Drop for EvictionGuard {
    fn drop(&mut self) {
        self.shared.lock().evictions.remove(&self.key);
    }
}

/// What a caller is told when the stream it was waiting on has ended.
const GONE: &str = "the worker holding the durable task stream is gone";

fn stopped() -> Error {
    Error::Grpc(Box::new(Status::cancelled(GONE)))
}

fn evicted(reason: &str) -> Error {
    Error::Grpc(Box::new(Status::cancelled(format!(
        "the engine evicted this durable invocation: {reason}"
    ))))
}

fn ack_timed_out(task_id: &str, invocation_count: i32) -> Error {
    Error::Grpc(Box::new(Status::deadline_exceeded(format!(
        "the engine did not acknowledge a durable request for task run {task_id} (invocation \
         {invocation_count}) within {ACK_TIMEOUT:?}; the request may have been lost on the stream, \
         so this attempt fails rather than sending it again"
    ))))
}

fn eviction_timed_out(task_id: &str, invocation_count: i32) -> Error {
    Error::Grpc(Box::new(Status::deadline_exceeded(format!(
        "the engine did not acknowledge the eviction of task run {task_id} (invocation \
         {invocation_count}) within {EVICTION_ACK_TIMEOUT:?}; the run keeps its durable slot \
         rather than being cancelled behind the engine's back"
    ))))
}

fn overlapping_eviction(task_id: &str, invocation_count: i32) -> Error {
    Error::Grpc(Box::new(Status::failed_precondition(format!(
        "an eviction of task run {task_id} (invocation {invocation_count}) is already waiting to \
         be acknowledged"
    ))))
}

fn overlapping_request(task_id: &str, invocation_count: i32) -> Error {
    Error::Grpc(Box::new(Status::failed_precondition(format!(
        "a durable request for task run {task_id} (invocation {invocation_count}) is already \
         waiting to be acknowledged; one invocation's requests must go out one at a time"
    ))))
}

fn mismatched_ack(task_id: &str, invocation_count: i32) -> Error {
    Error::Grpc(Box::new(Status::internal(format!(
        "the engine acknowledged a durable request for task run {task_id} (invocation \
         {invocation_count}) with an ack of the wrong kind"
    ))))
}

fn duplicate_wait(reference: &DurableEventLogEntryRef) -> Error {
    Error::Grpc(Box::new(Status::failed_precondition(format!(
        "durable log entry {}:{} of task run {} is already being waited for",
        reference.node_id, reference.branch_id, reference.durable_task_external_id
    ))))
}

/// A poisoned lock means another thread panicked while holding it; the state
/// behind it is a plain table, so carrying on with it is better than failing
/// every caller over someone else's panic.
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

fn request(message: durable_task_request::Message) -> DurableTaskRequest {
    DurableTaskRequest {
        message: Some(message),
    }
}

fn register(worker_id: &str) -> DurableTaskRequest {
    request(durable_task_request::Message::RegisterWorker(
        DurableTaskRequestRegisterWorker {
            worker_id: worker_id.to_string(),
        },
    ))
}

/// How one connection ended.
enum Outcome {
    /// `stop` fired: the worker is gone.
    Stopped,
    /// The stream ended; `status` is `None` when it ended cleanly.
    Ended {
        status: Option<Status>,
        /// Whether this connection delivered at least one response.
        received: bool,
    },
}

/// Holds one `DurableTask` stream open, reopening it for as long as the engine
/// keeps dropping it, until `stop` fires.
///
/// Unlike the run listener this never goes idle: a worker with durable tasks
/// holds the stream from the moment it starts, because the engine will not
/// assign it a durable task otherwise, and because a handler that reaches its
/// first durable step should not also have to wait for a connection.
///
/// A failure that reconnecting cannot fix — or too many unclassified ones in a
/// row — fails every ack *and* every wait and ends the loop for good; the
/// durable runs in flight then fail as ordinary, retryable task failures and
/// the engine assigns them again.
async fn run<C, Fut, S, B>(
    mut connect: C,
    shared: Arc<Shared>,
    stop: CancellationToken,
    mut backoff: B,
) where
    C: FnMut(RequestStream) -> Fut,
    Fut: Future<Output = Result<S, Status>>,
    S: Stream<Item = Result<DurableTaskResponse, Status>> + Unpin,
    B: FnMut(u32) -> Duration,
{
    // The backoff exponent and the run of unclassified failures. Both are reset
    // by a single received response: a stream the engine answered on was
    // healthy, whatever it did afterwards.
    let mut attempt: u32 = 0;
    let mut consecutive_other: u32 = 0;

    while !stop.is_cancelled() {
        let (requests, received_by_engine) = mpsc::channel(REQUEST_BUFFER);
        // Queued *before* the call is awaited, and first of all: the engine
        // sends no response headers until the worker has said something, so
        // awaiting an empty stream would hang for ever. Every connection is
        // registered again — unlike `ListenV2`, one registration does not last.
        let _ = requests.try_send(register(&shared.worker_id));
        // And straight after it, what this worker is still waiting for, so the
        // new connection can be handed the completions the old one missed.
        if let Some(status) = shared.worker_status() {
            let _ = requests.try_send(status);
        }

        let outcome = tokio::select! {
            () = stop.cancelled() => Outcome::Stopped,
            connected = connect(ReceiverStream::new(received_by_engine)) => match connected {
                Ok(responses) => serve(responses, &requests, &shared, &stop).await,
                // No difference, for what happens next, between "the stream
                // could not be opened" and "it closed immediately".
                Err(status) => Outcome::Ended { status: Some(status), received: false },
            }
        };
        // Half-closing the request stream is what tells the engine this
        // connection is over.
        drop(requests);

        let (status, received) = match outcome {
            Outcome::Stopped => break,
            Outcome::Ended { status, received } => (status, received),
        };
        shared.fail_acks(status.as_ref());
        if received {
            attempt = 0;
            consecutive_other = 0;
        }

        let give_up = match classify_stream_end(status.as_ref()) {
            // `Cancelled` is another stream's clean stop, and
            // `classify_stream_end` is shared with it: a cancelled durable
            // stream with waits still on it is just one more to reopen.
            StreamErrorClass::StopClean | StreamErrorClass::Transient => false,
            StreamErrorClass::Fatal => true,
            StreamErrorClass::Other => {
                consecutive_other += 1;
                consecutive_other >= STREAM_MAX_CONSECUTIVE_OTHER_FAILURES
            }
        };
        if give_up {
            let status = status.unwrap_or_else(|| Status::unknown("the durable task stream ended"));
            tracing::warn!(
                code = ?status.code(),
                message = status.message(),
                consecutive_other,
                "giving up on the durable task stream; every durable wait fails",
            );
            shared.fail_all(&status);
            *lock(&shared.fatal) = Some(status);
            shared.gave_up.cancel();
            break;
        }

        let delay = backoff(attempt);
        attempt = attempt.saturating_add(1);
        log_reconnect(attempt, consecutive_other, delay, status.as_ref());

        tokio::select! {
            () = stop.cancelled() => break,
            () = tokio::time::sleep(delay) => {}
        }
    }
    shared.stop();
}

/// Hands every response to the tables, every queued request to the engine, and
/// the outstanding waits to the engine once a second, until the stream ends or
/// `stop` fires.
async fn serve<S>(
    mut responses: S,
    requests: &mpsc::Sender<DurableTaskRequest>,
    shared: &Shared,
    stop: &CancellationToken,
) -> Outcome
where
    S: Stream<Item = Result<DurableTaskResponse, Status>> + Unpin,
{
    let mut received = false;
    let mut ticker = tokio::time::interval(WORKER_STATUS_INTERVAL);
    ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
    // The first tick is immediate, and this connection already carries a
    // `worker_status`; taking it here starts the second from now.
    ticker.tick().await;

    loop {
        if !send_pending(shared, requests, stop).await {
            return if stop.is_cancelled() {
                Outcome::Stopped
            } else {
                // The engine stopped reading; nothing more can be sent on this
                // connection, so it is worth no more than a reconnect.
                Outcome::Ended {
                    status: None,
                    received,
                }
            };
        }
        tokio::select! {
            () = stop.cancelled() => return Outcome::Stopped,
            () = shared.work.notified() => {}
            _ = ticker.tick() => shared.announce(),
            item = responses.next() => match item {
                Some(Ok(response)) => {
                    received = true;
                    deliver(shared, response);
                }
                Some(Err(status)) => return Outcome::Ended { status: Some(status), received },
                None => return Outcome::Ended { status: None, received },
            }
        }
    }
}

/// Sends everything queued for this connection. `false` means the connection is
/// gone or `stop` fired.
async fn send_pending(
    shared: &Shared,
    requests: &mpsc::Sender<DurableTaskRequest>,
    stop: &CancellationToken,
) -> bool {
    while shared.has_pending() {
        // Room first, then the request: taking one out of the queue and finding
        // nowhere to put it would lose it.
        let permit = tokio::select! {
            () = stop.cancelled() => return false,
            reserved = requests.reserve() => match reserved {
                Ok(permit) => permit,
                Err(_) => return false,
            }
        };
        let Some(request) = shared.take_pending() else {
            return true;
        };
        permit.send(request);
    }
    true
}

/// Routes one response from the engine.
fn deliver(shared: &Shared, response: DurableTaskResponse) {
    match response.message {
        // Informational: the engine echoing the worker id back.
        Some(durable_task_response::Message::RegisterWorker(_)) => {}
        Some(durable_task_response::Message::WaitForAck(ack)) => {
            answer_ack(shared, ack.r#ref.clone(), |_| {
                ack.r#ref.clone().map(Ack::Wait)
            });
        }
        Some(durable_task_response::Message::MemoAck(ack)) => {
            answer_ack(shared, ack.r#ref.clone(), |_| memo_ack(&ack));
        }
        Some(durable_task_response::Message::EntryCompleted(done)) => complete(shared, done),
        Some(durable_task_response::Message::Error(error)) => fail_ref(shared, &error),
        Some(durable_task_response::Message::ServerEvict(notice)) => evict(shared, &notice),
        Some(durable_task_response::Message::TriggerRunsAck(ack)) => {
            // No `ref` on this one: it is routed by the pair the request named,
            // and each entry carries its own node
            // (`api-contracts/v1/dispatcher.proto:45-49`).
            answer_by_key(
                shared,
                (ack.durable_task_external_id, ack.invocation_count),
                Ok(Ack::Trigger(ack.run_entries)),
            );
        }
        Some(durable_task_response::Message::EvictionAck(ack)) => {
            let key = (ack.durable_task_external_id, ack.invocation_count);
            let answer = shared.lock().evictions.remove(&key);
            match answer {
                Some(answer) => drop(answer.send(())),
                None => tracing::debug!(
                    task_run_id = %key.0,
                    invocation_count = key.1,
                    "an eviction ack arrived for an eviction nobody is waiting for",
                ),
            }
        }
        None => tracing::debug!("ignoring an empty durable response"),
    }
}

/// What a `memo_ack` tells the caller: the entry it made, and the value an
/// earlier invocation recorded under that key, if there is one.
fn memo_ack(ack: &DurableTaskEventMemoAckResponse) -> Option<Ack> {
    if ack.memo_already_existed && ack.memo_result_payload.is_none() {
        // The engine knows the key but has no value for it; the caller will
        // compute and record it again, which is worth noticing.
        tracing::warn!(reference = ?ack.r#ref, "a memo exists on the engine but carries no payload");
    }
    Some(Ack::Memo(MemoAck {
        reference: ack.r#ref.clone()?,
        existing: ack
            .memo_already_existed
            .then(|| ack.memo_result_payload.clone())
            .flatten(),
    }))
}

/// Hands one ack to whoever is waiting for it. The engine's ack says only which
/// `(task, invocation)` it belongs to, which is why only one request per
/// invocation may be in flight.
fn answer_ack(
    shared: &Shared,
    reference: Option<DurableEventLogEntryRef>,
    ack: impl FnOnce(&DurableEventLogEntryRef) -> Option<Ack>,
) {
    let Some(reference) = reference else {
        tracing::warn!("the engine acknowledged a durable request without a log entry ref");
        return;
    };
    let key = (
        reference.durable_task_external_id.clone(),
        reference.invocation_count,
    );
    let answer = match ack(&reference) {
        Some(ack) => Ok(ack),
        None => Err(mismatched_ack(
            &reference.durable_task_external_id,
            reference.invocation_count,
        )),
    };
    answer_by_key(shared, key, answer);
}

/// [`answer_ack`] for the acks that carry no `ref` at all and so name their
/// `(task, invocation)` themselves — `trigger_runs_ack`
/// (`api-contracts/v1/dispatcher.proto:45-49`).
fn answer_by_key(shared: &Shared, key: (String, i32), ack: crate::Result<Ack>) {
    let Some(answer) = shared.lock().acks.remove(&key) else {
        tracing::debug!(
            task_run_id = %key.0,
            invocation_count = key.1,
            "a durable ack arrived for a request nobody is waiting for",
        );
        return;
    };
    drop(answer.send(ack));
}

/// Wakes the waiter for one completed entry, or keeps the completion for the
/// waiter that has not arrived yet.
fn complete(shared: &Shared, done: DurableTaskEventLogEntryCompletedResponse) {
    let Some(reference) = done.r#ref else {
        tracing::warn!("the engine completed a durable log entry without a ref");
        return;
    };
    let completed = Completed {
        payload: done.payload,
        is_failure: done.is_failure,
        error_message: done.error_message,
    };
    let mut state = shared.lock();
    state.prune_expired();
    if state.consumed.contains_key(&reference) {
        // The engine re-completes an entry on every announcement that still
        // lists it, so a copy of one already handed over is expected rather
        // than exceptional: drop it, and above all do not buffer it.
        tracing::trace!(
            task_run_id = %reference.durable_task_external_id,
            invocation_count = reference.invocation_count,
            node_id = reference.node_id,
            "ignoring a re-delivered completion for an entry that has been consumed",
        );
        return;
    }
    if let Some(answer) = state.waits.remove(&reference) {
        state.consume(&reference);
        drop(state);
        drop(answer.send(Ok(completed)));
    } else {
        state
            .unclaimed
            .insert(reference, (completed, Instant::now() + COMPLETION_TTL));
    }
}

/// Hands the engine's error to the request and the wait it names — either may
/// be the one that is outstanding, and non-determinism can land on both.
fn fail_ref(shared: &Shared, error: &DurableTaskErrorResponse) {
    let Some(reference) = error.r#ref.clone() else {
        tracing::warn!(
            message = %error.error_message,
            "the engine sent a durable error without a log entry ref",
        );
        return;
    };
    let nondeterminism = error.error_type == DurableTaskErrorType::Nondeterminism as i32;
    let make = || {
        if nondeterminism {
            Error::Nondeterminism {
                task_run_id: reference.durable_task_external_id.clone(),
                invocation_count: reference.invocation_count,
                node_id: reference.node_id,
                message: error.error_message.clone(),
            }
        } else {
            Error::Grpc(Box::new(Status::internal(error.error_message.clone())))
        }
    };
    let (ack, wait) = {
        let mut state = shared.lock();
        let key = (
            reference.durable_task_external_id.clone(),
            reference.invocation_count,
        );
        state.unclaimed.remove(&reference);
        (state.acks.remove(&key), state.waits.remove(&reference))
    };
    if let Some(answer) = ack {
        drop(answer.send(Err(make())));
    }
    if let Some(answer) = wait {
        drop(answer.send(Err(make())));
    }
}

/// The engine says one invocation is stale: everything it is waiting for ends,
/// and the worker is told so it can cancel the run.
fn evict(shared: &Shared, notice: &DurableTaskServerEvictNotice) {
    tracing::warn!(
        task_run_id = %notice.durable_task_external_id,
        invocation_count = notice.invocation_count,
        reason = %notice.reason,
        "the engine evicted a durable invocation",
    );
    shared.cleanup(
        &notice.durable_task_external_id,
        notice.invocation_count,
        &notice.reason,
    );
    let hook = lock(&shared.evict).clone();
    if let Some(hook) = hook {
        hook(&notice.durable_task_external_id, notice.invocation_count);
    }
}

/// Reconnecting is normal, so only the first attempt and every fifth one are
/// worth a warning; the rest would drown a long outage in log lines.
fn log_reconnect(attempt: u32, consecutive_other: u32, delay: Duration, status: Option<&Status>) {
    let code = status.map(Status::code);
    let message = status.map(Status::message).unwrap_or_default();
    if attempt == 1 || attempt.is_multiple_of(5) {
        tracing::warn!(
            attempt,
            consecutive_other,
            ?delay,
            ?code,
            message,
            "reconnecting to the engine's durable task stream",
        );
    } else {
        tracing::debug!(
            attempt,
            consecutive_other,
            ?delay,
            ?code,
            message,
            "reconnecting to the engine's durable task stream",
        );
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use hatchet_proto::v1::{
        DurableTaskErrorResponse, DurableTaskEventMemoAckResponse,
        DurableTaskEventTriggerRunsAckResponse, DurableTaskEventWaitForAckResponse,
        DurableTaskEvictionAckResponse,
    };
    use hatchet_testkit::MockEngine;
    use tokio::sync::mpsc;
    use tonic::Code;

    use super::*;
    use crate::{Client, TlsStrategy};

    /// Nothing here may block for ever: a regression should fail the test
    /// rather than hang the suite. The clock is paused, so a wait that is going
    /// to be answered costs no real time, and one that is not jumps straight
    /// here.
    const NEVER: Duration = Duration::from_secs(10 * 60);

    /// How long a condition the loop is not going to notify about is given, in
    /// *real* time, before the test gives up on it.
    const SETTLE_BUDGET: Duration = Duration::from_secs(5);

    const WORKER: &str = "worker-1";

    /// The responses of one scripted connection.
    type ScriptedStream = ReceiverStream<Result<DurableTaskResponse, Status>>;
    /// What the test pushes them in through; taking one out ends its stream.
    type ScriptedSender = mpsc::Sender<Result<DurableTaskResponse, Status>>;
    /// Every connection the scripted `connect` has opened, by number.
    type Connections = Arc<Mutex<Vec<Option<ScriptedSender>>>>;

    /// A `connect` function that hands every connection to the test, and
    /// records every request the stream sends on it.
    #[derive(Clone)]
    struct Script {
        calls: Arc<AtomicUsize>,
        responses: Connections,
        requests: mpsc::UnboundedSender<(usize, DurableTaskRequest)>,
    }

    impl Script {
        async fn connect(self, requests: RequestStream) -> Result<ScriptedStream, Status> {
            let connection = self.calls.fetch_add(1, Ordering::SeqCst);
            let (responses, received) = mpsc::channel(32);
            lock(&self.responses).push(Some(responses));
            tokio::spawn(record(connection, requests, self.requests.clone()));
            Ok(ReceiverStream::new(received))
        }
    }

    /// Records every request one connection was sent, tagged with its number.
    async fn record(
        connection: usize,
        mut requests: RequestStream,
        recorder: mpsc::UnboundedSender<(usize, DurableTaskRequest)>,
    ) {
        while let Some(request) = requests.next().await {
            let _ = recorder.send((connection, request));
        }
    }

    /// The connections the scripted `connect` opened, and what was sent on
    /// them.
    struct Opened {
        responses: Connections,
        incoming: mpsc::UnboundedReceiver<(usize, DurableTaskRequest)>,
        seen: Vec<(usize, DurableTaskRequest)>,
        calls: Arc<AtomicUsize>,
    }

    impl Opened {
        /// Waits until connection `n` has been sent at least `count` requests,
        /// and returns them in order.
        async fn requests(&mut self, n: usize, count: usize) -> Vec<DurableTaskRequest> {
            loop {
                let sent: Vec<DurableTaskRequest> = self
                    .seen
                    .iter()
                    .filter(|(connection, _)| *connection == n)
                    .map(|(_, request)| request.clone())
                    .collect();
                if sent.len() >= count {
                    return sent;
                }
                let item = tokio::time::timeout(NEVER, self.incoming.recv())
                    .await
                    .expect("timed out waiting for a durable request")
                    .expect("the durable stream dropped the recorder");
                self.seen.push(item);
            }
        }

        /// Sends one response down connection `n`.
        fn push(&self, n: usize, response: DurableTaskResponse) {
            lock(&self.responses)[n]
                .as_ref()
                .expect("the connection is still open")
                .try_send(Ok(response))
                .expect("room in the connection's buffer");
        }

        /// Ends connection `n`, with `status` if given.
        fn end(&self, n: usize, status: Option<Status>) {
            let responses = lock(&self.responses)[n]
                .take()
                .expect("the connection is still open");
            if let Some(status) = status {
                let _ = responses.try_send(Err(status));
            }
        }

        fn calls(&self) -> usize {
            self.calls.load(Ordering::SeqCst)
        }
    }

    /// A stream over scripted connections, with a token that ends it. The
    /// reconnect delay is zero so a test never waits for one.
    fn scripted() -> (DurableStream, Opened, CancellationToken) {
        let calls = Arc::new(AtomicUsize::new(0));
        let responses = Arc::new(Mutex::new(Vec::new()));
        let (requests, incoming) = mpsc::unbounded_channel();
        let script = Script {
            calls: Arc::clone(&calls),
            responses: Arc::clone(&responses),
            requests,
        };
        let stop = CancellationToken::new();
        let stream = DurableStream::with_backoff(
            WORKER.to_string(),
            move |requests| script.clone().connect(requests),
            stop.clone(),
            |_| Duration::ZERO,
        );
        (
            stream,
            Opened {
                responses,
                incoming,
                seen: Vec::new(),
                calls,
            },
            stop,
        )
    }

    /// Waits for `condition` by handing the runtime back to the tasks that
    /// could make it true. Used only for the few conditions the stream does not
    /// notify about, such as a completion landing in the buffer.
    ///
    /// The budget is real time and no tokio timer is involved, so a paused
    /// clock cannot cut the wait short.
    ///
    /// # Panics
    ///
    /// If `condition` does not hold within [`SETTLE_BUDGET`].
    async fn until(what: &str, condition: impl Fn() -> bool) {
        let started = std::time::Instant::now();
        while !condition() {
            assert!(
                started.elapsed() < SETTLE_BUDGET,
                "timed out waiting for {what}"
            );
            tokio::task::yield_now().await;
        }
    }

    /// What a spawned task returned, or a failed test rather than a hung one.
    async fn joined<T>(handle: tokio::task::JoinHandle<T>) -> T {
        tokio::time::timeout(NEVER, handle)
            .await
            .expect("timed out waiting for a durable caller")
            .expect("the waiting task panicked")
    }

    fn reference(
        task_id: &str,
        invocation: i32,
        branch: i64,
        node: i64,
    ) -> DurableEventLogEntryRef {
        DurableEventLogEntryRef {
            durable_task_external_id: task_id.to_string(),
            invocation_count: invocation,
            branch_id: branch,
            node_id: node,
        }
    }

    fn conditions() -> DurableEventListenerConditions {
        DurableEventListenerConditions::default()
    }

    fn response(message: durable_task_response::Message) -> DurableTaskResponse {
        DurableTaskResponse {
            message: Some(message),
        }
    }

    fn wait_for_ack(reference: DurableEventLogEntryRef) -> DurableTaskResponse {
        response(durable_task_response::Message::WaitForAck(
            DurableTaskEventWaitForAckResponse {
                r#ref: Some(reference),
            },
        ))
    }

    fn memo_ack(
        reference: DurableEventLogEntryRef,
        existing: Option<&[u8]>,
    ) -> DurableTaskResponse {
        response(durable_task_response::Message::MemoAck(
            DurableTaskEventMemoAckResponse {
                r#ref: Some(reference),
                memo_already_existed: existing.is_some(),
                memo_result_payload: existing.map(<[u8]>::to_vec),
            },
        ))
    }

    fn entry_completed(reference: DurableEventLogEntryRef, payload: &[u8]) -> DurableTaskResponse {
        response(durable_task_response::Message::EntryCompleted(
            DurableTaskEventLogEntryCompletedResponse {
                r#ref: Some(reference),
                payload: payload.to_vec(),
                is_failure: false,
                error_message: None,
            },
        ))
    }

    fn trigger_runs_ack(
        task_id: &str,
        invocation: i32,
        entries: &[(i64, i64, &str)],
    ) -> DurableTaskResponse {
        response(durable_task_response::Message::TriggerRunsAck(
            DurableTaskEventTriggerRunsAckResponse {
                durable_task_external_id: task_id.to_string(),
                invocation_count: invocation,
                run_entries: entries
                    .iter()
                    .map(|(node, branch, run_id)| DurableTaskRunAckEntry {
                        node_id: *node,
                        branch_id: *branch,
                        workflow_run_external_id: (*run_id).to_string(),
                    })
                    .collect(),
            },
        ))
    }

    fn eviction_ack(task_id: &str, invocation: i32) -> DurableTaskResponse {
        response(durable_task_response::Message::EvictionAck(
            DurableTaskEvictionAckResponse {
                invocation_count: invocation,
                durable_task_external_id: task_id.to_string(),
            },
        ))
    }

    fn trigger(name: &str) -> TriggerWorkflowRequest {
        TriggerWorkflowRequest {
            name: name.to_string(),
            ..Default::default()
        }
    }

    fn nondeterminism(reference: DurableEventLogEntryRef) -> DurableTaskResponse {
        response(durable_task_response::Message::Error(
            DurableTaskErrorResponse {
                r#ref: Some(reference),
                error_type: DurableTaskErrorType::Nondeterminism as i32,
                error_message: "expected: sleep(10m0s)\n  received: memo".to_string(),
            },
        ))
    }

    fn server_evict(task_id: &str, invocation: i32) -> DurableTaskResponse {
        response(durable_task_response::Message::ServerEvict(
            DurableTaskServerEvictNotice {
                durable_task_external_id: task_id.to_string(),
                invocation_count: invocation,
                reason: "a newer invocation took over".to_string(),
            },
        ))
    }

    fn is_register(request: &DurableTaskRequest, worker_id: &str) -> bool {
        matches!(
            &request.message,
            Some(durable_task_request::Message::RegisterWorker(register))
                if register.worker_id == worker_id
        )
    }

    /// The tasks named in every `worker_status` `request` carries, if it is
    /// one.
    fn announced(request: &DurableTaskRequest) -> Option<Vec<String>> {
        match &request.message {
            Some(durable_task_request::Message::WorkerStatus(status)) => Some(
                status
                    .waiting_entries
                    .iter()
                    .map(|entry| entry.durable_task_external_id.clone())
                    .collect(),
            ),
            _ => None,
        }
    }

    #[tokio::test(start_paused = true)]
    async fn the_first_message_on_every_connection_registers_the_worker() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();

        let first = opened.requests(0, 1).await;
        assert!(is_register(&first[0], WORKER), "{:?}", first[0].message);

        // A dropped connection is reopened, and the new one is registered too:
        // unlike `ListenV2`, one registration does not last.
        opened.end(0, Some(Status::unavailable("gone")));
        let second = opened.requests(1, 1).await;
        assert!(is_register(&second[0], WORKER), "{:?}", second[0].message);
        assert_eq!(opened.calls(), 2);
    }

    /// The engine's ref is deliberately surprising — node 41 on branch 7 — so
    /// nothing here could have produced it: the SDK never invents node ids.
    #[tokio::test(start_paused = true)]
    async fn a_wait_is_answered_with_the_ref_the_engine_chose() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        opened.requests(0, 1).await;

        let chosen = reference("run-1", 1, 7, 41);
        let waiting = tokio::spawn({
            let stream = stream.clone();
            let chosen = chosen.clone();
            async move {
                let reference = stream
                    .send_wait_for("run-1".to_string(), 1, conditions(), None)
                    .await
                    .expect("the engine acknowledged the wait");
                assert_eq!(reference, chosen, "the SDK must use the engine's ref");
                stream.wait_for_entry(reference).await
            }
        });

        let sent = opened.requests(0, 2).await;
        assert!(matches!(
            sent[1].message,
            Some(durable_task_request::Message::WaitFor(_))
        ));
        opened.push(0, wait_for_ack(chosen.clone()));

        // The ack is not the answer: the new entry is announced and then
        // waited for.
        let announcing = opened.requests(0, 3).await;
        assert_eq!(
            announced(&announcing[2]).as_deref(),
            Some(&["run-1".to_string()][..])
        );
        assert!(
            !waiting.is_finished(),
            "nothing is answered until it completes"
        );

        opened.push(0, entry_completed(chosen, br#"{"CREATE":{}}"#));
        let payload = joined(waiting).await.expect("the wait is answered");
        assert_eq!(payload, br#"{"CREATE":{}}"#.to_vec());
    }

    /// The memo path: the engine completes the node while the SDK is still
    /// deciding to wait for it (Task 0 conclusion (b)).
    #[tokio::test(start_paused = true)]
    async fn a_completion_that_arrives_before_its_waiter_is_kept_for_it() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        opened.requests(0, 1).await;

        let early = reference("run-1", 1, 1, 1);
        opened.push(0, entry_completed(early.clone(), b"{\"amount\":7}"));
        until("the completion to be buffered", || {
            stream.buffered_completions() == 1
        })
        .await;

        let payload = stream
            .wait_for_entry(early)
            .await
            .expect("answered from the buffer");
        assert_eq!(payload, b"{\"amount\":7}".to_vec());
        assert_eq!(stream.buffered_completions(), 0, "and taken out of it");
    }

    #[tokio::test(start_paused = true)]
    async fn an_unclaimed_completion_is_forgotten_after_its_ttl() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        opened.requests(0, 1).await;

        opened.push(0, entry_completed(reference("run-1", 1, 1, 1), b"{}"));
        until("the completion to be buffered", || {
            stream.buffered_completions() == 1
        })
        .await;

        tokio::time::advance(COMPLETION_TTL + Duration::from_secs(1)).await;

        assert_eq!(stream.buffered_completions(), 0);
    }

    #[tokio::test(start_paused = true)]
    async fn a_reconnect_fails_the_acks_and_keeps_the_waits() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        opened.requests(0, 1).await;

        // A wait the engine has already named, which lives in its event log.
        let kept = reference("run-2", 1, 1, 1);
        let waiting = tokio::spawn({
            let stream = stream.clone();
            let kept = kept.clone();
            async move { stream.wait_for_entry(kept).await }
        });
        opened.requests(0, 2).await;
        // And a request that has not been acknowledged yet.
        let acking = tokio::spawn({
            let stream = stream.clone();
            async move {
                stream
                    .send_wait_for("run-1".to_string(), 1, conditions(), None)
                    .await
            }
        });
        opened.requests(0, 3).await;

        opened.end(0, Some(Status::unavailable("gone")));

        // The request may never have reached the engine, so the attempt fails
        // rather than being sent again — a second send would make a second
        // log entry and break the next attempt's determinism.
        let failed = joined(acking)
            .await
            .expect_err("the ack cannot survive the stream");
        let Error::Grpc(status) = &failed else {
            panic!("{failed:?}")
        };
        assert_eq!(status.code(), Code::Unavailable);
        assert!(!waiting.is_finished(), "the wait survives the reconnect");

        // The new connection registers and announces what is still waited for.
        let announcing = opened.requests(1, 2).await;
        assert!(is_register(&announcing[0], WORKER));
        assert!(
            announcing
                .iter()
                .any(|request| announced(request).is_some_and(|tasks| tasks == ["run-2"])),
            "{announcing:?}",
        );
        // And nothing re-sends the `wait_for` that was lost.
        assert!(
            !announcing.iter().any(|request| matches!(
                request.message,
                Some(durable_task_request::Message::WaitFor(_))
            )),
            "{announcing:?}",
        );

        opened.push(1, entry_completed(kept, b"{}"));
        assert_eq!(joined(waiting).await.expect("answered"), b"{}".to_vec());
    }

    /// Both tables are keyed off the same ref, and the engine's error can land
    /// on either one.
    #[tokio::test(start_paused = true)]
    async fn a_nondeterminism_error_answers_the_ack_and_the_wait_for_that_ref() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        opened.requests(0, 1).await;

        // On a request still waiting for its ack.
        let acking = tokio::spawn({
            let stream = stream.clone();
            async move {
                stream
                    .send_wait_for("run-1".to_string(), 2, conditions(), None)
                    .await
            }
        });
        opened.requests(0, 2).await;
        opened.push(0, nondeterminism(reference("run-1", 2, 1, 3)));
        let failed = joined(acking).await.expect_err("the engine refused it");
        let Error::Nondeterminism {
            task_run_id,
            invocation_count,
            node_id,
            ..
        } = &failed
        else {
            panic!("{failed:?}")
        };
        assert_eq!(
            (task_run_id.as_str(), *invocation_count, *node_id),
            ("run-1", 2, 3)
        );

        // And on a wait that is already registered.
        let diverged = reference("run-1", 2, 1, 4);
        let waiting = tokio::spawn({
            let stream = stream.clone();
            let diverged = diverged.clone();
            async move { stream.wait_for_entry(diverged).await }
        });
        opened.requests(0, 3).await;
        opened.push(0, nondeterminism(diverged));
        let failed = joined(waiting).await.expect_err("the engine refused it");
        assert!(
            matches!(failed, Error::Nondeterminism { node_id: 4, .. }),
            "{failed:?}"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn a_server_evict_ends_the_invocations_waits_and_tells_the_worker() {
        let (stream, mut opened, _stop) = scripted();
        let evicted: Arc<Mutex<Vec<(String, i32)>>> = Arc::new(Mutex::new(Vec::new()));
        stream.on_server_evict({
            let evicted = Arc::clone(&evicted);
            move |task_id, invocation| lock(&evicted).push((task_id.to_string(), invocation))
        });
        stream.start();
        opened.requests(0, 1).await;

        let stale = reference("run-1", 1, 1, 1);
        let current = reference("run-1", 2, 1, 1);
        let ending = tokio::spawn({
            let stream = stream.clone();
            let stale = stale.clone();
            async move { stream.wait_for_entry(stale).await }
        });
        let surviving = tokio::spawn({
            let stream = stream.clone();
            let current = current.clone();
            async move { stream.wait_for_entry(current).await }
        });
        opened.requests(0, 2).await;
        until("both waits to be registered", || {
            lock(&stream.shared.state).waits.len() == 2
        })
        .await;

        opened.push(0, server_evict("run-1", 1));

        let failed = joined(ending).await.expect_err("the invocation is stale");
        let Error::Grpc(status) = &failed else {
            panic!("{failed:?}")
        };
        assert_eq!(status.code(), Code::Cancelled);
        // Only that invocation's waits: the one that took over is untouched.
        assert!(!surviving.is_finished());
        until("the worker to be told", || !lock(&evicted).is_empty()).await;
        assert_eq!(*lock(&evicted), [("run-1".to_string(), 1)]);

        opened.push(0, entry_completed(current, b"{}"));
        assert_eq!(joined(surviving).await.expect("answered"), b"{}".to_vec());
    }

    /// One invocation's requests go out one at a time, because the engine's ack
    /// says only which `(task, invocation)` it belongs to. A second one that
    /// slipped through would steal the first one's ack.
    #[tokio::test(start_paused = true)]
    async fn a_second_request_for_one_invocation_is_refused_rather_than_stealing_the_ack() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        opened.requests(0, 1).await;

        let first = tokio::spawn({
            let stream = stream.clone();
            async move {
                stream
                    .send_wait_for("run-1".to_string(), 1, conditions(), None)
                    .await
            }
        });
        opened.requests(0, 2).await;

        let refused = stream
            .send_memo("run-1".to_string(), 1, "key", None)
            .await
            .expect_err("one ack at a time");
        assert!(matches!(refused, Error::Grpc(_)), "{refused:?}");

        opened.push(0, wait_for_ack(reference("run-1", 1, 1, 1)));
        assert_eq!(
            joined(first).await.expect("acknowledged"),
            reference("run-1", 1, 1, 1),
        );
    }

    /// A memo the engine already has hands the recorded value back; a fresh one
    /// hands back only the entry it made.
    #[tokio::test(start_paused = true)]
    async fn a_memo_ack_carries_the_value_an_earlier_invocation_recorded() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        opened.requests(0, 1).await;

        let asking = tokio::spawn({
            let stream = stream.clone();
            async move { stream.send_memo("run-1".to_string(), 2, "now", None).await }
        });
        opened.requests(0, 2).await;
        opened.push(
            0,
            memo_ack(reference("run-1", 2, 1, 1), Some(b"{\"value\":1}")),
        );

        let ack = joined(asking).await.expect("acknowledged");
        assert_eq!(ack.reference, reference("run-1", 2, 1, 1));
        assert_eq!(ack.existing.as_deref(), Some(&b"{\"value\":1}"[..]));

        // The same key on a fresh run: nothing recorded yet.
        let asking = tokio::spawn({
            let stream = stream.clone();
            async move { stream.send_memo("run-2".to_string(), 1, "now", None).await }
        });
        opened.requests(0, 3).await;
        opened.push(0, memo_ack(reference("run-2", 1, 1, 1), None));
        assert!(
            joined(asking)
                .await
                .expect("acknowledged")
                .existing
                .is_none()
        );
    }

    #[tokio::test(start_paused = true)]
    async fn an_unacknowledged_request_gives_up_after_the_ack_timeout() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        opened.requests(0, 1).await;

        // The engine never answers, and the clock is paused, so the whole
        // minute costs nothing.
        let failed = stream
            .send_wait_for("run-1".to_string(), 1, conditions(), None)
            .await
            .expect_err("the request was lost on the stream");
        let Error::Grpc(status) = &failed else {
            panic!("{failed:?}")
        };
        assert_eq!(status.code(), Code::DeadlineExceeded);
    }

    #[tokio::test(start_paused = true)]
    async fn a_fatal_status_fails_every_wait_and_ends_the_loop() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        opened.requests(0, 1).await;

        let waiting = tokio::spawn({
            let stream = stream.clone();
            async move { stream.wait_for_entry(reference("run-1", 1, 1, 1)).await }
        });
        opened.requests(0, 2).await;

        opened.end(0, Some(Status::unauthenticated("revoked")));

        let failed = joined(waiting).await.expect_err("a fatal stream error");
        let Error::Grpc(status) = &failed else {
            panic!("{failed:?}")
        };
        assert_eq!(status.code(), Code::Unauthenticated);
        // And nothing reopens: the loop is over.
        let refused = stream
            .wait_for_entry(reference("run-1", 1, 1, 2))
            .await
            .expect_err("the stream has ended");
        assert!(matches!(refused, Error::Grpc(_)), "{refused:?}");
        assert_eq!(opened.calls(), 1);
    }

    /// `complete_memo` has no ack of its own: nothing waits for an answer.
    #[tokio::test(start_paused = true)]
    async fn complete_memo_is_sent_and_not_waited_for() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        opened.requests(0, 1).await;

        stream.send_complete_memo(reference("run-1", 1, 1, 1), "now", b"{\"at\":1}".to_vec());

        let sent = opened.requests(0, 2).await;
        let Some(durable_task_request::Message::CompleteMemo(completed)) = &sent[1].message else {
            panic!("{:?}", sent[1].message)
        };
        assert_eq!(completed.r#ref, Some(reference("run-1", 1, 1, 1)));
        assert_eq!(completed.memo_key, b"now".to_vec());
        assert_eq!(completed.payload, b"{\"at\":1}".to_vec());
    }

    /// What a reconnect does to the queue, without a loop in the way: the
    /// requests waiting for an ack are failed *and dropped* — sending one again
    /// would make a second log entry — while the ones with no ack of their own
    /// stay queued for the next connection.
    #[test]
    fn a_reconnect_drops_the_unanswered_requests_and_keeps_the_rest() {
        let shared = Shared::new(WORKER.to_string());
        let (answer, mut answered) = oneshot::channel();
        {
            let mut state = shared.lock();
            state.acks.insert(("run-1".to_string(), 1), answer);
            state
                .outgoing
                .push_back(request(durable_task_request::Message::WaitFor(
                    DurableTaskWaitForRequest {
                        invocation_count: 1,
                        durable_task_external_id: "run-1".to_string(),
                        wait_for_conditions: Some(conditions()),
                        label: None,
                    },
                )));
            state
                .outgoing
                .push_back(request(durable_task_request::Message::CompleteMemo(
                    DurableTaskCompleteMemoRequest {
                        r#ref: Some(reference("run-1", 1, 1, 1)),
                        payload: b"{}".to_vec(),
                        memo_key: b"now".to_vec(),
                    },
                )));
        }

        shared.fail_acks(Some(&Status::unavailable("gone")));

        let failed = answered
            .try_recv()
            .expect("the ack was answered")
            .expect_err("with the status the stream ended with");
        assert!(matches!(failed, Error::Grpc(_)), "{failed:?}");
        let state = shared.lock();
        assert!(state.acks.is_empty());
        assert_eq!(state.outgoing.len(), 1);
        assert!(matches!(
            state.outgoing[0].message,
            Some(durable_task_request::Message::CompleteMemo(_))
        ));
    }

    /// The worker giving up on an invocation itself: every wait at or below it
    /// ends, so the handler stops rather than waiting for a completion the
    /// engine will send to whoever took over.
    #[tokio::test(start_paused = true)]
    async fn cleanup_ends_the_waits_of_the_invocations_it_names() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        opened.requests(0, 1).await;

        let ending = tokio::spawn({
            let stream = stream.clone();
            async move { stream.wait_for_entry(reference("run-1", 1, 1, 1)).await }
        });
        let untouched = tokio::spawn({
            let stream = stream.clone();
            async move { stream.wait_for_entry(reference("run-9", 1, 1, 1)).await }
        });
        until("both waits to be registered", || {
            lock(&stream.shared.state).waits.len() == 2
        })
        .await;

        stream.cleanup("run-1", 1, "the worker is shutting down");

        let failed = joined(ending).await.expect_err("that invocation is over");
        assert!(matches!(failed, Error::Grpc(_)), "{failed:?}");
        assert!(!untouched.is_finished(), "another run is not touched");
    }

    /// Against a real socket: the worker registers on the connection it opens,
    /// and on every one it opens after that.
    #[tokio::test]
    async fn the_engine_sees_a_register_on_every_connection() {
        let engine = MockEngine::start().await;
        let client = client_for(&engine);
        let stop = CancellationToken::new();
        let stream = DurableStream::with_backoff(
            WORKER.to_string(),
            connect(client.grpc_service(), client.config().gzip()),
            stop.clone(),
            |_| Duration::ZERO,
        );
        stream.start();

        engine.wait_for_calls("DurableTask", 1).await;
        engine.disconnect_durable_streams_with(Status::unavailable("gone"));
        engine.wait_for_calls("DurableTask", 2).await;
        engine
            .wait_until("two register_worker requests", |engine| {
                engine
                    .durable_requests()
                    .iter()
                    .filter(|request| is_register(request, WORKER))
                    .count()
                    >= 2
            })
            .await;

        stop.cancel();
    }

    /// Against a real socket: the outstanding waits are announced again every
    /// second, not once per connection. One announcement per connection was
    /// measured to deliver *nothing* on both supported engines — a completed
    /// entry then sat in the log for as long as the worker cared to wait.
    #[tokio::test(start_paused = true)]
    async fn the_outstanding_waits_are_announced_every_second() {
        let _clock = hatchet_testkit::pin_paused_clock();
        let engine = MockEngine::start().await;
        let client = client_for(&engine);
        let stop = CancellationToken::new();
        let stream = DurableStream::new(
            WORKER.to_string(),
            connect(client.grpc_service(), client.config().gzip()),
            stop.clone(),
        );
        stream.start();
        engine.wait_for_durable_streams(1).await;

        let waiting = tokio::spawn({
            let stream = stream.clone();
            async move { stream.wait_for_entry(reference("run-1", 1, 1, 1)).await }
        });

        // One for registering the wait, and then one per second.
        engine
            .wait_until("three worker_status requests", |engine| {
                engine
                    .durable_requests()
                    .iter()
                    .filter(|request| announced(request).is_some_and(|tasks| tasks == ["run-1"]))
                    .count()
                    >= 3
            })
            .await;

        assert!(!waiting.is_finished(), "and it is still waiting");
        waiting.abort();
        stop.cancel();
    }

    /// One request carries every trigger, and the engine's entries come back in
    /// the order they were sent — which is how the caller pairs its handles up.
    #[tokio::test(start_paused = true)]
    async fn trigger_runs_is_answered_with_the_entries_the_engine_named() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        let spawning = tokio::spawn({
            let stream = stream.clone();
            async move {
                stream
                    .send_trigger_runs(
                        "run-1".to_string(),
                        1,
                        vec![trigger("dev_child"), trigger("dev_child")],
                    )
                    .await
            }
        });

        // The request goes out as one `trigger_runs` carrying both triggers —
        // one log entry's worth of work, as both official SDKs send it
        // (`sdks/go/durable_child.go:111-137`).
        let sent = opened.requests(0, 2).await;
        let Some(durable_task_request::Message::TriggerRuns(request)) = &sent[1].message else {
            panic!(
                "the second request is a trigger_runs: {:?}",
                sent[1].message
            );
        };
        assert_eq!(request.durable_task_external_id, "run-1");
        assert_eq!(request.invocation_count, 1);
        assert_eq!(request.trigger_opts.len(), 2);

        opened.push(
            0,
            trigger_runs_ack("run-1", 1, &[(7, 1, "child-a"), (8, 1, "child-b")]),
        );
        let entries = joined(spawning).await.expect("the ack answers the caller");
        let ids: Vec<&str> = entries
            .iter()
            .map(|entry| entry.workflow_run_external_id.as_str())
            .collect();
        assert_eq!(ids, ["child-a", "child-b"]);
        assert_eq!(entries[0].node_id, 7);
        assert_eq!(entries[1].node_id, 8);
    }

    /// The ack table is keyed by `(task, invocation)` and nothing else, so an
    /// ack of the wrong *kind* must be an error rather than a silent hang or a
    /// wrong value handed to the caller.
    #[tokio::test(start_paused = true)]
    async fn a_wait_ack_does_not_answer_a_trigger_runs_request() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        let spawning = tokio::spawn({
            let stream = stream.clone();
            async move {
                stream
                    .send_trigger_runs("run-1".to_string(), 1, vec![trigger("dev_child")])
                    .await
            }
        });
        let _ = opened.requests(0, 2).await;
        opened.push(0, wait_for_ack(reference("run-1", 1, 1, 1)));
        let error = joined(spawning).await.unwrap_err();
        assert!(error.to_string().contains("wrong kind"), "{error}");
    }

    #[tokio::test(start_paused = true)]
    async fn evict_waits_for_the_engines_eviction_ack() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        let evicting = tokio::spawn({
            let stream = stream.clone();
            async move {
                stream
                    .send_evict("run-1", 2, Some("Worker at capacity".to_string()))
                    .await
            }
        });
        let sent = opened.requests(0, 2).await;
        let Some(durable_task_request::Message::EvictInvocation(request)) = &sent[1].message else {
            panic!(
                "the second request is an evict_invocation: {:?}",
                sent[1].message
            );
        };
        assert_eq!(request.durable_task_external_id, "run-1");
        assert_eq!(request.invocation_count, 2);
        assert_eq!(request.reason.as_deref(), Some("Worker at capacity"));

        // An ack for another invocation is not this one's.
        opened.push(0, eviction_ack("run-1", 1));
        tokio::task::yield_now().await;
        assert!(
            !evicting.is_finished(),
            "an ack for invocation 1 answered invocation 2"
        );

        opened.push(0, eviction_ack("run-1", 2));
        joined(evicting).await.expect("the ack answers the evictor");
    }

    #[tokio::test(start_paused = true)]
    async fn an_eviction_that_is_never_acknowledged_fails_rather_than_hangs() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        let evicting = tokio::spawn({
            let stream = stream.clone();
            async move { stream.send_evict("run-1", 1, None).await }
        });
        let _ = opened.requests(0, 2).await;
        tokio::time::advance(EVICTION_ACK_TIMEOUT + Duration::from_secs(1)).await;
        let error = joined(evicting).await.unwrap_err();
        assert!(error.to_string().contains("evict"), "{error}");
    }

    /// What `spawn_many` needs: the waiters are registered while the ack is
    /// being read, so a completion that arrives for the *second* child while
    /// the caller is still awaiting the first is delivered rather than left to
    /// expire in the ten-second buffer.
    #[tokio::test(start_paused = true)]
    async fn claimed_entries_are_waited_for_from_the_moment_they_are_claimed() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        let first = stream
            .claim_entry(reference("run-1", 1, 1, 7))
            .expect("a fresh entry");
        let second = stream
            .claim_entry(reference("run-1", 1, 1, 8))
            .expect("a fresh entry");
        // Both are announced: the engine only delivers what the worker says it
        // is waiting for (P6 conclusion (d)).
        let sent = opened.requests(0, 2).await;
        let announced: Vec<i64> = match &sent[1].message {
            Some(durable_task_request::Message::WorkerStatus(status)) => {
                let mut nodes: Vec<i64> = status
                    .waiting_entries
                    .iter()
                    .map(|entry| entry.node_id)
                    .collect();
                nodes.sort_unstable();
                nodes
            }
            other => panic!("the second request announces the waits: {other:?}"),
        };
        assert_eq!(announced, [7, 8]);

        // The second completes first, and well past the buffer's TTL: with the
        // waiter already registered that is fine.
        opened.push(
            0,
            entry_completed(reference("run-1", 1, 1, 8), br#"{"n":2}"#),
        );
        until("the second completion to be delivered", || {
            !lock(&stream.shared.state)
                .waits
                .contains_key(&reference("run-1", 1, 1, 8))
        })
        .await;
        tokio::time::advance(COMPLETION_TTL * 3).await;
        opened.push(
            0,
            entry_completed(reference("run-1", 1, 1, 7), br#"{"n":1}"#),
        );
        assert_eq!(second.completed().await.unwrap(), br#"{"n":2}"#.to_vec());
        assert_eq!(first.completed().await.unwrap(), br#"{"n":1}"#.to_vec());
    }

    #[tokio::test(start_paused = true)]
    async fn a_dropped_claim_stops_waiting() {
        let (stream, _opened, _stop) = scripted();
        stream.start();
        let claimed = stream
            .claim_entry(reference("run-1", 1, 1, 7))
            .expect("a fresh entry");
        drop(claimed);
        // The same entry can be claimed again, which it could not be if the
        // first claim were still in the table.
        stream
            .claim_entry(reference("run-1", 1, 1, 7))
            .expect("the dropped claim gave the entry up");
    }

    /// The engine's delivery is level-triggered: it completes an entry again on
    /// every `worker_status` that still lists it (P7 Task 0 probe B). Taking the
    /// waiter out drops it from the next announcement, but the copies already
    /// in flight must not be buffered as if they were fresh — and their payload
    /// comes back `jsonb`-normalised, so byte equality would not spot them.
    #[tokio::test(start_paused = true)]
    async fn a_re_delivered_completion_is_ignored_rather_than_buffered() {
        let (stream, mut opened, _stop) = scripted();
        stream.start();
        opened.requests(0, 1).await;

        let entry = reference("run-1", 1, 1, 1);
        let claimed = stream.claim_entry(entry.clone()).expect("a fresh entry");
        opened.push(
            0,
            entry_completed(entry.clone(), br#"{"from":"child","n":0}"#),
        );
        assert_eq!(
            claimed.completed().await.expect("the first delivery"),
            br#"{"from":"child","n":0}"#.to_vec(),
        );
        // The entry is out of the announcement the moment it is consumed.
        assert!(
            !lock(&stream.shared.state).waits.contains_key(&entry),
            "a consumed entry is still announced",
        );

        // The re-delivery, `jsonb`-normalised as the engine sends it.
        opened.push(
            0,
            entry_completed(entry.clone(), br#"{"n": 0, "from": "child"}"#),
        );
        until("the re-delivery to be read", || {
            lock(&stream.shared.state).consumed.contains_key(&entry)
        })
        .await;
        assert_eq!(
            stream.buffered_completions(),
            0,
            "a re-delivered completion must not sit in the unclaimed buffer",
        );
        // And a second claim is refused loudly rather than waiting for ever.
        let Err(refused) = stream.claim_entry(entry) else {
            panic!("a second claim on a spent entry would wait for ever");
        };
        assert!(matches!(refused, Error::Grpc(_)), "{refused:?}");
    }

    fn client_for(engine: &MockEngine) -> Client {
        Client::builder()
            .token(engine.token())
            .namespace("dev")
            .tls(TlsStrategy::None)
            .build()
            .expect("a client pointed at the mock engine")
    }
}