legit-streams 0.1.4

A Redis Streams work contract for task and result envelopes, with a worker loop that leases, reclaims and replies, a producer and a result reader
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
//! The worker side of the contract: read tasks from a consumer group, run them, reply.

use std::collections::HashMap;
use std::fmt;
use std::panic::{self, AssertUnwindSafe};
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::thread::{self, JoinHandle};
use std::time::Duration;

use crate::clock::{Clock, Signal};
use crate::entry::{Entry, EntryId, LostLease, Renewal};
use crate::error::{Error, Result};
use crate::fields::{self, Limits};
use crate::result::{ResultBuilder, Status, TaskResult};
use crate::streams::Streams;
use crate::task::{Task, is_valid_reply_to};

/// The error type of a task that asks for a model or method the worker doesn't serve; add a
/// `supported_models` field. A worker never substitutes another model.
///
/// ```
/// assert_eq!(legit_streams::UNSUPPORTED_MODEL, "unsupported_model");
/// ```
pub const UNSUPPORTED_MODEL: &str = "unsupported_model";
/// The error type of a task that asks for an output width the model can't give; add
/// `dimensions_requested` and `supported_dimensions` fields.
///
/// ```
/// assert_eq!(legit_streams::INVALID_DIMENSIONS, "invalid_dimensions");
/// ```
pub const INVALID_DIMENSIONS: &str = "invalid_dimensions";
/// The error type of a task with a malformed payload option. A missing required payload is
/// [`INVALID_TASK`] instead.
///
/// ```
/// assert_eq!(legit_streams::INVALID_OPTIONS, "invalid_options");
/// ```
pub const INVALID_OPTIONS: &str = "invalid_options";
/// The error type of a task whose `embed_role` is neither `query` nor `passage`.
///
/// ```
/// assert_eq!(legit_streams::INVALID_EMBED_ROLE, "invalid_embed_role");
/// ```
pub const INVALID_EMBED_ROLE: &str = "invalid_embed_role";
/// The error type of a task for a model the worker serves but can't run now; add an
/// `unavailable_reason` field, and `retry_after_s` when a retry may succeed.
///
/// ```
/// assert_eq!(legit_streams::MODEL_UNAVAILABLE, "model_unavailable");
/// ```
pub const MODEL_UNAVAILABLE: &str = "model_unavailable";
/// The error type of a task whose payload, given by reference, couldn't be fetched.
///
/// ```
/// assert_eq!(legit_streams::DOWNLOAD_FAILED, "download_failed");
/// ```
pub const DOWNLOAD_FAILED: &str = "download_failed";
/// The error type of a task whose payload, given by reference, couldn't be fetched because the
/// URL's credential was refused, such as an expired presigned URL.
///
/// ```
/// assert_eq!(legit_streams::URL_EXPIRED, "url_expired");
/// ```
pub const URL_EXPIRED: &str = "url_expired";
/// The error type of a task whose payload was fetched or received but couldn't be decoded, for
/// any kind of task.
///
/// ```
/// assert_eq!(legit_streams::DECODE_FAILED, "decode_failed");
/// ```
pub const DECODE_FAILED: &str = "decode_failed";
/// The error type of an audio task whose speaker separation failed.
///
/// ```
/// assert_eq!(legit_streams::DIARIZE_FAILED, "diarize_failed");
/// ```
pub const DIARIZE_FAILED: &str = "diarize_failed";
/// The error type of an audio task whose transcription failed.
///
/// ```
/// assert_eq!(legit_streams::ASR_FAILED, "asr_failed");
/// ```
pub const ASR_FAILED: &str = "asr_failed";
/// The error type of an entry the worker can't read as a task, and of a task whose kind's
/// required payload is missing.
///
/// A worker sets it for an entry with a field of the envelope missing or empty, a `task_id` outside
/// the rules, a name given twice, a field name or value that isn't UTF-8, or over the [`Limits`],
/// once the entry's delivery count is within [`WorkerConfig::max_deliveries`]. It answers such an
/// entry when its `task_id` isn't empty and is UTF-8 of at most 256 bytes, carrying the id exactly
/// as sent, and removes it either way: with no such `task_id`, unanswered. A handler returns it for
/// a task without the payload its kind requires, such as a text task with no `text_data`.
///
/// ```
/// assert_eq!(legit_streams::INVALID_TASK, "invalid_task");
/// ```
pub const INVALID_TASK: &str = "invalid_task";
/// The error type of a task whose `v` is present and isn't `1`. The worker doesn't run it.
///
/// ```
/// assert_eq!(legit_streams::UNSUPPORTED_VERSION, "unsupported_version");
/// ```
pub const UNSUPPORTED_VERSION: &str = "unsupported_version";
/// The error type of a task delivered more than [`WorkerConfig::max_deliveries`] times.
///
/// ```
/// assert_eq!(legit_streams::MAX_DELIVERIES_EXCEEDED, "max_deliveries_exceeded");
/// ```
pub const MAX_DELIVERIES_EXCEEDED: &str = "max_deliveries_exceeded";
/// The error type of a task whose handler panicked or returned an unusable reply.
///
/// ```
/// assert_eq!(legit_streams::INTERNAL, "internal");
/// ```
pub const INTERNAL: &str = "internal";
/// The error type of a task whose handler's reply is over the worker's [`Limits`]. A task the
/// worker refuses keeps its own error type, such as [`INVALID_TASK`], whatever it echoes.
///
/// ```
/// assert_eq!(legit_streams::RESULT_TOO_LARGE, "result_too_large");
/// ```
pub const RESULT_TOO_LARGE: &str = "result_too_large";

/// How long the read loop waits after a failed read before it tries again.
const READ_RETRY: Duration = Duration::from_secs(1);

/// The settings of a [`Worker`]. The defaults are the contract's reference values, where it gives
/// one; a deployment may change them. What the contract fixes is that the heartbeat is at most a
/// third of the claim threshold and that every worker on a group uses the same threshold.
///
/// ```
/// use std::time::Duration;
/// use legit_streams::WorkerConfig;
///
/// let config = WorkerConfig {
///     concurrency: 4,
///     ..WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results")
/// };
/// assert_eq!(config.lease_heartbeat, Duration::from_secs(60));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkerConfig {
    /// The task stream, such as `hash_tasks`. It can't begin with `results:` or `dead:`, the
    /// names of result streams and of tasks an operator has set aside.
    pub stream: String,
    /// The consumer group the worker reads it with, such as `hash_workers`, created when missing.
    pub group: String,
    /// This worker's consumer name, unique within the group, and the `worker_id` of its results.
    pub consumer: String,
    /// Where the result of a task that names no valid `reply_to` goes, such as `hash_results`, and
    /// every result when [`WorkerConfig::route_results_per_app`] is off.
    pub result_stream: String,
    /// Send each result to the stream its task's `reply_to` names. On by default, as the contract
    /// asks: a worker honours a task's `reply_to`, and uses `result_stream` only for a task that
    /// names none. A task whose `reply_to` fails [`is_valid_reply_to`] still runs, and its result,
    /// success or error, goes to `result_stream`, with a warning in the log.
    ///
    /// Turn it off only on an instance with a single application: with more than one, every
    /// producer must send `reply_to` and every worker must honour it.
    pub route_results_per_app: bool,
    /// How many tasks run at once, each on a thread of its own. 1 by default.
    pub concurrency: usize,
    /// How long one read waits for a task; also the longest a stop waits for a read in progress.
    /// 5 s by default.
    pub read_block: Duration,
    /// How often the worker renews the lease on each task it runs, so no other worker claims it.
    /// 60 s by default, the contract's reference value; at most a third of
    /// [`WorkerConfig::claim_idle`], so a worker can miss two renewals before another claims its
    /// task.
    pub lease_heartbeat: Duration,
    /// How long an entry must sit unrenewed before this worker claims it from another, presumed
    /// dead. 300 s by default, the contract's reference value. It belongs to the group, not the
    /// worker: every worker reading a group must use the same value, or one with a shorter
    /// threshold claims tasks that another's heartbeat keeps alive.
    pub claim_idle: Duration,
    /// How many deliveries a task may have: it runs on deliveries 1 to `max_deliveries`. A task
    /// whose delivery count is more than this when a worker takes it is answered with a
    /// `max_deliveries_exceeded` error rather than run again. 3 by default, the contract's default.
    pub max_deliveries: u64,
    /// How long a stop waits for running tasks before it releases them to other workers. 30 s by
    /// default.
    pub shutdown_grace: Duration,
    /// How many times the worker tries to write a result, and then to acknowledge the task, before
    /// it leaves the task pending for another worker. 5 by default.
    pub flush_attempts: u32,
    /// The wait before the second attempt; each later one waits that much longer. 2 s by
    /// default.
    pub flush_backoff: Duration,
    /// The bounds on a task the worker reads and a result it writes.
    pub limits: Limits,
}

impl WorkerConfig {
    /// The default settings for reading `stream` with `group` as `consumer`, replying to
    /// `result_stream`.
    ///
    /// ```
    /// use legit_streams::WorkerConfig;
    ///
    /// let config = WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results");
    /// assert_eq!(config.concurrency, 1);
    /// assert!(config.route_results_per_app);
    /// assert_eq!(config.max_deliveries, 3);
    /// ```
    #[must_use]
    pub fn new(
        stream: impl Into<String>,
        group: impl Into<String>,
        consumer: impl Into<String>,
        result_stream: impl Into<String>,
    ) -> Self {
        Self {
            stream: stream.into(),
            group: group.into(),
            consumer: consumer.into(),
            result_stream: result_stream.into(),
            route_results_per_app: true,
            concurrency: 1,
            read_block: Duration::from_secs(5),
            lease_heartbeat: Duration::from_secs(60),
            claim_idle: Duration::from_secs(300),
            max_deliveries: 3,
            shutdown_grace: Duration::from_secs(30),
            flush_attempts: 5,
            flush_backoff: Duration::from_secs(2),
            limits: Limits::default(),
        }
    }

    fn validate(&self) -> Result<()> {
        let invalid = |message: &str| Err(Error::InvalidConfig(message.to_owned()));
        for (name, value) in [
            ("stream", &self.stream),
            ("group", &self.group),
            ("consumer", &self.consumer),
            ("result_stream", &self.result_stream),
        ] {
            if value.is_empty() {
                return Err(Error::InvalidConfig(format!("`{name}` is empty")));
            }
        }
        check_task_stream(&self.stream)?;
        if self.concurrency == 0 {
            return invalid("`concurrency` is 0; a worker runs at least one task at once");
        }
        if self.read_block.is_zero() {
            return invalid("`read_block` is 0; Redis reads `BLOCK 0` as forever");
        }
        if self.lease_heartbeat.is_zero() || self.lease_heartbeat.saturating_mul(3) > self.claim_idle {
            return invalid(
                "`lease_heartbeat` must be above 0 and at most a third of `claim_idle`, so a worker can miss two \
                 renewals before another claims its task",
            );
        }
        if self.max_deliveries == 0 {
            return invalid("`max_deliveries` is 0; a task needs one delivery to run");
        }
        if self.flush_attempts == 0 {
            return invalid("`flush_attempts` is 0; a result needs one attempt to be written");
        }
        Ok(())
    }
}

/// Refuse a task stream name the contract keeps for other keys: one beginning with `results:`,
/// the result streams and reply keys, or `dead:`, tasks an operator has set aside.
pub(crate) fn check_task_stream(stream: &str) -> Result<()> {
    for reserved in ["results:", "dead:"] {
        if stream.starts_with(reserved) {
            return Err(Error::InvalidConfig(format!(
                "the task stream `{stream}` begins with `{reserved}`, which no task stream may"
            )));
        }
    }
    Ok(())
}

/// The longest `task_id` a worker carries back on an error result for an entry it can't read, in
/// bytes. A longer one, or one that isn't UTF-8, counts as none: the entry is removed unanswered.
const ANSWERED_TASK_ID_MAX_LEN: usize = 256;

/// The `task_id` a worker answers an unreadable entry with: the last one, exactly as sent, when it
/// isn't empty and is UTF-8 of at most 256 bytes.
pub(crate) fn answerable_task_id(raw: &[(Vec<u8>, Vec<u8>)]) -> Option<&str> {
    fields::last(raw, "task_id").filter(|id| !id.is_empty() && id.len() <= ANSWERED_TASK_ID_MAX_LEN)
}

/// What a [`Handler`] returns for a task that succeeded: the fields of its output, which the
/// worker adds to the result after the envelope's own.
///
/// ```
/// use legit_streams::Reply;
///
/// let reply = Reply::new().field("result", "{\"ok\":true}").model_name("example-model");
/// assert_eq!(reply.fields(), [("result".to_owned(), "{\"ok\":true}".to_owned())]);
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Reply {
    model_name: Option<String>,
    fields: Vec<(String, String)>,
}

impl Reply {
    /// A reply with no fields.
    ///
    /// ```
    /// assert!(legit_streams::Reply::new().fields().is_empty());
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an output field, such as `result` or `embedding`.
    ///
    /// ```
    /// let reply = legit_streams::Reply::new().field("embedding_format", "base64_fp32");
    /// assert_eq!(reply.fields().len(), 1);
    /// ```
    #[must_use]
    pub fn field(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.fields.push((name.into(), value.into()));
        self
    }

    /// Name the model that ran in the result's `model_name`, rather than echoing the task's: on a
    /// success something ran, and its name may be fuller than the one the task asked for.
    ///
    /// ```
    /// let reply = legit_streams::Reply::new().model_name("example-model");
    /// # let _ = reply;
    /// ```
    #[must_use]
    pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
        self.model_name = Some(model_name.into());
        self
    }

    /// The output fields, in order.
    ///
    /// ```
    /// assert!(legit_streams::Reply::default().fields().is_empty());
    /// ```
    #[must_use]
    pub fn fields(&self) -> &[(String, String)] {
        &self.fields
    }
}

/// What a [`Handler`] returns for a task that failed: an error result, or, with
/// [`Failure::abandon`], no result at all and the task left to another worker.
///
/// ```
/// use legit_streams::Failure;
///
/// let failure = Failure::new("unsupported_model", "no model `x`").field("supported_models", "[\"a\"]");
/// assert_eq!(failure.error_type(), Some("unsupported_model"));
/// assert!(!failure.is_abandon());
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Failure {
    kind: FailureKind,
    model_name: Option<String>,
    fields: Vec<(String, String)>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum FailureKind {
    Error { error_type: String, message: String },
    Abandon { reason: String },
}

impl Failure {
    /// An error result with this `error_type`, such as [`UNSUPPORTED_MODEL`], and message. Error
    /// types are an open set in lowercase snake case: a type that isn't becomes an [`INTERNAL`]
    /// error, as an unusable reply does.
    ///
    /// ```
    /// let failure = legit_streams::Failure::new("decode_failed", "not an image");
    /// assert_eq!(failure.message(), "not an image");
    /// ```
    #[must_use]
    pub fn new(error_type: impl Into<String>, message: impl Into<String>) -> Self {
        Self::of(FailureKind::Error {
            error_type: error_type.into(),
            message: message.into(),
        })
    }

    /// No result, on the bulk lane: the worker leaves the task pending and releases it so another
    /// worker claims it at once. For a handler that notices the worker stopping or its lease lost,
    /// as [`Context::checkpoint`] does, or that can't run the task now; releasing is this crate's
    /// feature, allowed at any time.
    ///
    /// Each release is followed by a claim, and each claim counts a delivery: a task released
    /// three times reaches the default delivery limit, and its next claim is answered with
    /// `max_deliveries_exceeded`. A task that shouldn't run at all is answered with an error, never
    /// released.
    ///
    /// A [`FastWorker`](crate::FastWorker) never releases: it answers an abandoned task with an
    /// [`INTERNAL`] error, so its caller falls back at once.
    ///
    /// ```
    /// assert!(legit_streams::Failure::abandon("shutting down").is_abandon());
    /// ```
    #[must_use]
    pub fn abandon(reason: impl Into<String>) -> Self {
        Self::of(FailureKind::Abandon { reason: reason.into() })
    }

    const fn of(kind: FailureKind) -> Self {
        Self {
            kind,
            model_name: None,
            fields: Vec::new(),
        }
    }

    /// Add a field to the error result, such as `supported_models`.
    ///
    /// ```
    /// let failure = legit_streams::Failure::new("unsupported_model", "no").field("supported_models", "[]");
    /// # let _ = failure;
    /// ```
    #[must_use]
    pub fn field(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.fields.push((name.into(), value.into()));
        self
    }

    /// Name the model that ran in the error result's `model_name`, rather than echoing the task's.
    ///
    /// Only for a failure of a stage after the model was chosen, when something ran. A task
    /// refused before anything ran, such as one answered [`UNSUPPORTED_MODEL`] or [`INVALID_TASK`],
    /// echoes the name it asked for: don't set another there.
    ///
    /// ```
    /// let failure = legit_streams::Failure::new("decode_failed", "failed").model_name("example-model");
    /// # let _ = failure;
    /// ```
    #[must_use]
    pub fn model_name(mut self, model_name: impl Into<String>) -> Self {
        self.model_name = Some(model_name.into());
        self
    }

    /// Whether this abandons the task rather than answering it.
    ///
    /// ```
    /// assert!(!legit_streams::Failure::new("decode_failed", "failed").is_abandon());
    /// ```
    #[must_use]
    pub const fn is_abandon(&self) -> bool {
        matches!(self.kind, FailureKind::Abandon { .. })
    }

    /// The error type, when the failure is an error with one.
    ///
    /// ```
    /// assert_eq!(legit_streams::Failure::abandon("stop").error_type(), None);
    /// ```
    #[must_use]
    pub fn error_type(&self) -> Option<&str> {
        match &self.kind {
            FailureKind::Error { error_type, .. } => Some(error_type),
            FailureKind::Abandon { .. } => None,
        }
    }

    /// The error message, or the reason for abandoning.
    ///
    /// ```
    /// assert_eq!(legit_streams::Failure::abandon("stop").message(), "stop");
    /// ```
    #[must_use]
    pub fn message(&self) -> &str {
        match &self.kind {
            FailureKind::Error { message, .. } => message,
            FailureKind::Abandon { reason } => reason,
        }
    }
}

/// Runs a task. A worker calls it on a thread of its own for each task, so it must be `Sync`;
/// a closure `Fn(&Task, &Context) -> Result<Reply, Failure>` is one.
///
/// A panic is caught and answered with an `internal` error result; the worker goes on.
///
/// ```
/// use legit_streams::{Context, Failure, Handler, Reply, Task};
///
/// struct Upper;
///
/// impl Handler for Upper {
///     fn handle(&self, task: &Task, _context: &Context) -> Result<Reply, Failure> {
///         let text = task.get("text_data").ok_or_else(|| Failure::new("invalid_task", "no `text_data`"))?;
///         Ok(Reply::new().field("result", text.to_uppercase()))
///     }
/// }
/// ```
pub trait Handler: Send + Sync + 'static {
    /// Run `task`.
    ///
    /// # Errors
    ///
    /// A [`Failure`], which the worker answers with an error result, or for
    /// [`Failure::abandon`], releases to another worker on the bulk lane and answers with an
    /// [`INTERNAL`] error on the fast lane.
    ///
    /// ```
    /// use legit_streams::{Context, Failure, Reply, Task};
    ///
    /// fn handle(_task: &Task, _context: &Context) -> Result<Reply, Failure> {
    ///     Err(Failure::new("unsupported_model", "no such model"))
    /// }
    /// # let _ = handle;
    /// ```
    fn handle(&self, task: &Task, context: &Context) -> std::result::Result<Reply, Failure>;
}

impl<F> Handler for F
where
    F: Fn(&Task, &Context) -> std::result::Result<Reply, Failure> + Send + Sync + 'static,
{
    fn handle(&self, task: &Task, context: &Context) -> std::result::Result<Reply, Failure> {
        self(task, context)
    }
}

/// What a handler can ask about the task it runs and the worker running it.
///
/// ```
/// use legit_streams::{Context, Failure, Reply, Task};
///
/// fn handle(task: &Task, context: &Context) -> Result<Reply, Failure> {
///     let text = task.get("text_data").ok_or_else(|| Failure::new("invalid_task", "no `text_data`"))?;
///     for chunk in text.split('\n') {
///         context.checkpoint()?;
///         let _ = chunk;
///     }
///     Ok(Reply::new())
/// }
/// # let _ = handle;
/// ```
pub struct Context {
    entry_id: EntryId,
    deliveries: u64,
    reclaimed: bool,
    flight: Arc<Flight>,
    control: Arc<Control>,
    clock: Clock,
    /// When the worker took the task, on `clock`'s monotonic time.
    started: Duration,
}

impl Context {
    pub(crate) const fn new(
        entry_id: EntryId,
        deliveries: u64,
        reclaimed: bool,
        flight: Arc<Flight>,
        control: Arc<Control>,
        clock: Clock,
        started: Duration,
    ) -> Self {
        Self {
            entry_id,
            deliveries,
            reclaimed,
            flight,
            control,
            clock,
            started,
        }
    }

    /// How long since the worker took the task, on the worker's clock: what the result's
    /// `processing_ms` reports if the handler returns now, to the nanosecond rather than the
    /// millisecond. It counts the worker's own steps before the handler ran, such as reading the
    /// delivery count and renewing the lease, as `processing_ms` does.
    ///
    /// ```
    /// # fn f(context: &legit_streams::Context) {
    /// let so_far = context.elapsed();
    /// # let _ = so_far;
    /// # }
    /// ```
    #[must_use]
    pub fn elapsed(&self) -> Duration {
        self.clock.monotonic().saturating_sub(self.started)
    }

    /// The task's stream entry.
    ///
    /// ```
    /// # fn f(context: &legit_streams::Context) {
    /// println!("running entry {}", context.entry_id());
    /// # }
    /// ```
    #[must_use]
    pub const fn entry_id(&self) -> EntryId {
        self.entry_id
    }

    /// How many times the task has been delivered, this time included, as the group's pending
    /// list gave it when the worker took the task.
    ///
    /// It is 0 when the entry was no longer pending when its count was read, such as a task another
    /// worker had already acknowledged, and 1 when the count couldn't be read. A
    /// [`FastWorker`](crate::FastWorker) always gives 1.
    ///
    /// ```
    /// # fn f(context: &legit_streams::Context) {
    /// let retry = context.deliveries() > 1;
    /// # let _ = retry;
    /// # }
    /// ```
    #[must_use]
    pub const fn deliveries(&self) -> u64 {
        self.deliveries
    }

    /// Whether this worker claimed the task from another that stopped renewing it.
    ///
    /// ```
    /// # fn f(context: &legit_streams::Context) {
    /// let _ = context.is_reclaimed();
    /// # }
    /// ```
    #[must_use]
    pub const fn is_reclaimed(&self) -> bool {
        self.reclaimed
    }

    /// Whether the worker has been asked to stop. A long task can abandon at a convenient point;
    /// one that runs past the shutdown grace is released to another worker and its result
    /// discarded.
    ///
    /// ```
    /// # fn f(context: &legit_streams::Context) {
    /// if context.is_stopping() { /* save progress */ }
    /// # }
    /// ```
    #[must_use]
    pub fn is_stopping(&self) -> bool {
        self.control.stopping.load(Ordering::SeqCst)
    }

    /// Whether the worker lost the task's lease: another worker claimed it, or it was
    /// acknowledged elsewhere. The worker discards the result of a task whose lease it lost.
    ///
    /// ```
    /// # fn f(context: &legit_streams::Context) {
    /// if context.is_lease_lost() { /* stop early */ }
    /// # }
    /// ```
    #[must_use]
    pub fn is_lease_lost(&self) -> bool {
        self.flight.lost.load(Ordering::SeqCst)
    }

    /// `Err(Failure::abandon(..))` when the worker is stopping or has lost the lease, so a handler
    /// can return early with `?` between stages. A [`Worker`] releases the task to another; a
    /// [`FastWorker`](crate::FastWorker) answers it with an [`INTERNAL`] error.
    ///
    /// # Errors
    ///
    /// The abandoning [`Failure`], as above.
    ///
    /// ```
    /// # fn f(context: &legit_streams::Context) -> Result<(), legit_streams::Failure> {
    /// context.checkpoint()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn checkpoint(&self) -> std::result::Result<(), Failure> {
        if self.is_stopping() {
            return Err(Failure::abandon("the worker is stopping"));
        }
        if self.is_lease_lost() {
            return Err(Failure::abandon("the lease on the task was lost"));
        }
        Ok(())
    }
}

impl fmt::Debug for Context {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Context")
            .field("entry_id", &self.entry_id)
            .field("deliveries", &self.deliveries)
            .field("reclaimed", &self.reclaimed)
            .finish_non_exhaustive()
    }
}

/// Asks a running [`Worker`] to stop. Cheap to clone.
///
/// ```
/// use legit_streams::{MemoryStreams, Reply, Worker, WorkerConfig};
///
/// let config = WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results");
/// let worker = Worker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?;
/// let stopper = worker.stopper();
/// stopper.stop();
/// assert!(stopper.is_stopped());
/// # Ok::<(), legit_streams::Error>(())
/// ```
#[derive(Clone)]
pub struct Stopper {
    control: Arc<Control>,
}

impl Stopper {
    pub(crate) const fn new(control: Arc<Control>) -> Self {
        Self { control }
    }

    /// Ask the worker to stop: it takes no new task, waits up to
    /// [`WorkerConfig::shutdown_grace`] for the tasks it runs, and releases the rest. A read in
    /// progress finishes first, which takes up to [`WorkerConfig::read_block`].
    ///
    /// ```
    /// # fn f(stopper: &legit_streams::Stopper) {
    /// stopper.stop();
    /// # }
    /// ```
    pub fn stop(&self) {
        self.control.stopping.store(true, Ordering::SeqCst);
        self.control.wake.raise();
    }

    /// Whether a stop was asked for.
    ///
    /// ```
    /// # fn f(stopper: &legit_streams::Stopper) {
    /// let _ = stopper.is_stopped();
    /// # }
    /// ```
    #[must_use]
    pub fn is_stopped(&self) -> bool {
        self.control.stopping.load(Ordering::SeqCst)
    }
}

impl fmt::Debug for Stopper {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Stopper").field("stopped", &self.is_stopped()).finish()
    }
}

/// What a worker did before it stopped.
///
/// ```
/// use legit_streams::Report;
///
/// let report = Report::default();
/// assert_eq!(report.results, 0);
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Report {
    /// How many results the worker wrote, errors included.
    pub results: u64,
    /// The entries the worker released to other workers rather than answering: tasks still
    /// running when the shutdown grace ran out, tasks delivered after the stop, and tasks its
    /// handler abandoned. Always empty for a [`FastWorker`](crate::FastWorker), which never
    /// releases.
    pub released: Vec<EntryId>,
    /// Fast-lane entries deleted unanswered because their `deadline_ms` had passed when they were
    /// read. Always 0 for a [`Worker`].
    pub expired: u64,
    /// Fast-lane entries deleted unanswered because their `reply_to` isn't the reply key of their
    /// `task_id`. Always 0 for a [`Worker`].
    pub invalid: u64,
    /// Fast-lane tasks answered with an [`INTERNAL`] error because their handler abandoned them,
    /// or because no thread could be started to run them; [`Report::results`] counts their
    /// replies too. Always 0 for a [`Worker`].
    pub abandoned: u64,
}

/// The worker side of the contract. It reads tasks from a stream with a consumer group, runs
/// each with a [`Handler`] and writes the result to the reply stream, then acknowledges and
/// deletes the task:
///
/// - It creates the group when missing.
/// - Before each read it claims entries other consumers left idle past
///   [`WorkerConfig::claim_idle`], and runs them first.
/// - A task delivered more than [`WorkerConfig::max_deliveries`] times gets a
///   `max_deliveries_exceeded` error result instead of another run.
/// - While a task runs, a heartbeat renews its lease every [`WorkerConfig::lease_heartbeat`] with
///   [`Streams::renew_lease`]: one atomic step that restarts the entry's idle time only if this
///   worker still owns it. A lease found lost (the entry is another consumer's, or no longer
///   pending, or the group is gone) is never taken back: the handler sees
///   [`Context::is_lease_lost`], and its result is discarded. A renewal the server doesn't answer
///   says nothing about the lease, and is tried again at the next heartbeat.
/// - Before each try of writing a result, and of acknowledging the task, retries included, the
///   worker checks the lease: the heartbeat's finding, then a renewal. Once it's lost, the worker
///   writes nothing more and acknowledges nothing.
/// - An entry that isn't a valid task, a handler error or panic, and a result over the limits
///   each become an error result; none stops the loop.
/// - A result goes to the stream its task's `reply_to` names; when that isn't a valid reply
///   stream, the task still runs and its result goes to [`WorkerConfig::result_stream`].
/// - The result goes to the stream before the task is acknowledged, so a crash between the two
///   repeats a result rather than losing one.
/// - On [`Stopper::stop`] it takes no new task, waits for running tasks up to
///   [`WorkerConfig::shutdown_grace`], then releases the rest with [`Streams::release_lease`],
///   setting their idle time to `claim_idle` so another worker claims them at once rather than
///   after the idle threshold, and removes its consumer when it owns nothing.
///
/// Results are at least once. A worker that lost its lease between two renewals finds out at the
/// next one, or right before its write; but a worker that stalls for a whole `claim_idle` between
/// that last renewal and its write, or crashes between the write and the acknowledgement, writes a
/// result another run writes too. A reader of results must treat a second result for a `task_id`
/// as a repeat.
///
/// ```
/// use std::time::Duration;
/// use legit_streams::{Clock, Failure, MemoryStreams, Reply, Streams, Task, Worker, WorkerConfig};
///
/// let clock = Clock::manual(1_000);
/// let streams = MemoryStreams::with_clock(clock.clone());
/// let task = Task::builder("app", "post", "42").field("text_data", "hello").build()?;
/// let fields: Vec<(&[u8], &[u8])> = task.fields().iter().map(|(k, v)| (k.as_bytes(), v.as_bytes())).collect();
/// streams.xadd("hash_tasks", &fields)?;
///
/// let config = WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results");
/// let worker = Worker::new(config, streams.clone(), |task: &Task, _: &_| {
///     let text = task.get("text_data").ok_or_else(|| Failure::new("invalid_task", "no `text_data`"))?;
///     Ok(Reply::new().field("result", text.to_uppercase()))
/// })?
/// .clock(clock.clone());
/// let running = worker.spawn()?;
///
/// while streams.xlen("hash_results")? == 0 {
///     std::thread::sleep(Duration::from_millis(1));
/// }
/// running.stop();
/// clock.advance(Duration::from_secs(5));
/// let report = running.join()?;
///
/// assert_eq!(report.results, 1);
/// assert_eq!(streams.entries("hash_results")[0].field("result"), Some(&b"HELLO"[..]));
/// assert_eq!(streams.xlen("hash_tasks")?, 0);
/// # Ok::<(), legit_streams::Error>(())
/// ```
pub struct Worker {
    config: Arc<WorkerConfig>,
    streams: Arc<dyn Streams>,
    handler: Arc<dyn Handler>,
    clock: Clock,
    control: Arc<Control>,
}

pub(crate) struct Control {
    pub(crate) stopping: AtomicBool,
    pub(crate) wake: Signal,
}

impl Control {
    pub(crate) fn new(clock: &Clock) -> Arc<Self> {
        Arc::new(Self {
            stopping: AtomicBool::new(false),
            wake: Signal::new(clock),
        })
    }
}

impl Worker {
    /// A worker with these settings, on the system clock.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidConfig`] for settings that can't work, such as an empty stream name, a task
    /// stream beginning with `results:` or `dead:`, a concurrency of 0, or a lease heartbeat no
    /// shorter than the claim idle time.
    ///
    /// ```
    /// use legit_streams::{Error, MemoryStreams, Reply, Worker, WorkerConfig};
    ///
    /// let config = WorkerConfig { concurrency: 0, ..WorkerConfig::new("hash_tasks", "hash_workers", "w", "hash_results") };
    /// let worker = Worker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()));
    /// assert!(matches!(worker, Err(Error::InvalidConfig(_))));
    ///
    /// let config = WorkerConfig::new("results:app:hash", "hash_workers", "w", "hash_results");
    /// let worker = Worker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()));
    /// assert!(matches!(worker, Err(Error::InvalidConfig(_))));
    /// ```
    pub fn new(config: WorkerConfig, streams: impl Streams + 'static, handler: impl Handler) -> Result<Self> {
        config.validate()?;
        let clock = Clock::system();
        Ok(Self {
            config: Arc::new(config),
            streams: Arc::new(streams),
            handler: Arc::new(handler),
            control: Control::new(&clock),
            clock,
        })
    }

    /// Run on `clock` rather than the system clock, such as a manual clock in tests. Take
    /// [`Worker::stopper`] after this.
    ///
    /// ```
    /// use legit_streams::{Clock, MemoryStreams, Reply, Worker, WorkerConfig};
    ///
    /// let config = WorkerConfig::new("hash_tasks", "hash_workers", "w", "hash_results");
    /// let worker = Worker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?.clock(Clock::manual(0));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn clock(mut self, clock: Clock) -> Self {
        self.control = Control::new(&clock);
        self.clock = clock;
        self
    }

    /// The handle that stops this worker.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Reply, Worker, WorkerConfig};
    ///
    /// let config = WorkerConfig::new("hash_tasks", "hash_workers", "w", "hash_results");
    /// let worker = Worker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?;
    /// assert!(!worker.stopper().is_stopped());
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn stopper(&self) -> Stopper {
        Stopper::new(Arc::clone(&self.control))
    }

    /// The worker's settings.
    ///
    /// ```
    /// use legit_streams::{MemoryStreams, Reply, Worker, WorkerConfig};
    ///
    /// let config = WorkerConfig::new("hash_tasks", "hash_workers", "w", "hash_results");
    /// let worker = Worker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?;
    /// assert_eq!(worker.config().consumer, "w");
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn config(&self) -> &WorkerConfig {
        &self.config
    }

    /// Run the worker on a thread of its own.
    ///
    /// # Errors
    ///
    /// [`Error::Thread`] when the thread can't be started.
    ///
    /// ```no_run
    /// use legit_streams::{RedisStreams, Reply, Worker, WorkerConfig};
    ///
    /// let config = WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results");
    /// let streams = RedisStreams::open("redis://127.0.0.1:6379")?;
    /// let running = Worker::new(config, streams, |_: &_, _: &_| Ok(Reply::new()))?.spawn()?;
    /// running.stop();
    /// running.join()?;
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    pub fn spawn(self) -> Result<Running> {
        let stopper = self.stopper();
        let thread = thread::Builder::new()
            .name("legit-streams-worker".to_owned())
            .spawn(move || self.run())
            .map_err(|error| Error::Thread(error.to_string()))?;
        Ok(Running::new(stopper, thread))
    }

    /// Run the worker on this thread until [`Stopper::stop`].
    ///
    /// # Errors
    ///
    /// [`Error::Redis`] when the group can't be created at the start, and [`Error::Thread`] when
    /// the lease heartbeat's thread can't be started. Once running, a failed command is logged
    /// and retried, never returned.
    ///
    /// ```no_run
    /// use legit_streams::{RedisStreams, Reply, Worker, WorkerConfig};
    ///
    /// let config = WorkerConfig::new("hash_tasks", "hash_workers", "worker-1", "hash_results");
    /// let streams = RedisStreams::open("redis://127.0.0.1:6379")?;
    /// let worker = Worker::new(config, streams, |_: &_, _: &_| Ok(Reply::new()))?;
    /// let report = worker.run()?;
    /// println!("{} results", report.results);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    pub fn run(&self) -> Result<Report> {
        let party = self.clock.party();
        party.bind();
        let config = &self.config;
        self.streams.xgroup_create(&config.stream, &config.group)?;
        let run = Arc::new(Run {
            config: Arc::clone(config),
            streams: Arc::clone(&self.streams),
            handler: Arc::clone(&self.handler),
            clock: self.clock.clone(),
            control: Arc::clone(&self.control),
            flights: Mutex::new(HashMap::new()),
            results: AtomicU64::new(0),
            released: Mutex::new(Vec::new()),
            lease_stop: AtomicBool::new(false),
            lease_wake: Signal::new(&self.clock),
        });
        let lease_party = self.clock.party();
        let lease_run = Arc::clone(&run);
        let lease = thread::Builder::new()
            .name("legit-streams-lease".to_owned())
            .spawn(move || {
                lease_party.bind();
                lease_run.lease_loop();
            })
            .map_err(|error| Error::Thread(error.to_string()))?;
        tracing::info!(stream = %config.stream, group = %config.group, consumer = %config.consumer, "Worker started");
        run.read_loop();
        run.shut_down();
        run.lease_stop.store(true, Ordering::SeqCst);
        run.lease_wake.raise();
        if lease.join().is_err() {
            tracing::error!("The lease heartbeat thread panicked");
        }
        run.remove_consumer();
        let report = Report {
            results: run.results.load(Ordering::SeqCst),
            released: run.lock_released().clone(),
            ..Report::default()
        };
        tracing::info!(
            results = report.results,
            released = report.released.len(),
            "Worker stopped"
        );
        Ok(report)
    }
}

impl fmt::Debug for Worker {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Worker")
            .field("config", &self.config)
            .field("streams", &self.streams)
            .field("clock", &self.clock)
            .finish_non_exhaustive()
    }
}

/// A worker running on a thread of its own, from [`Worker::spawn`].
///
/// ```no_run
/// # fn f(running: legit_streams::Running) -> legit_streams::Result<()> {
/// running.stop();
/// let report = running.join()?;
/// # let _ = report;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Running {
    stopper: Stopper,
    thread: JoinHandle<Result<Report>>,
}

impl Running {
    pub(crate) const fn new(stopper: Stopper, thread: JoinHandle<Result<Report>>) -> Self {
        Self { stopper, thread }
    }

    /// Ask the worker to stop; see [`Stopper::stop`].
    ///
    /// ```no_run
    /// # fn f(running: &legit_streams::Running) {
    /// running.stop();
    /// # }
    /// ```
    pub fn stop(&self) {
        self.stopper.stop();
    }

    /// The handle that stops the worker.
    ///
    /// ```no_run
    /// # fn f(running: &legit_streams::Running) {
    /// let stopper = running.stopper();
    /// # let _ = stopper;
    /// # }
    /// ```
    #[must_use]
    pub fn stopper(&self) -> Stopper {
        self.stopper.clone()
    }

    /// Whether the worker has stopped, so [`Running::join`] won't wait.
    ///
    /// ```no_run
    /// # fn f(running: &legit_streams::Running) {
    /// if running.is_finished() { /* join */ }
    /// # }
    /// ```
    #[must_use]
    pub fn is_finished(&self) -> bool {
        self.thread.is_finished()
    }

    /// Wait for the worker to stop.
    ///
    /// # Errors
    ///
    /// The errors of [`Worker::run`].
    ///
    /// # Panics
    ///
    /// When the worker's thread panicked, with its panic.
    ///
    /// ```no_run
    /// # fn f(running: legit_streams::Running) -> legit_streams::Result<()> {
    /// let report = running.join()?;
    /// # let _ = report;
    /// # Ok(())
    /// # }
    /// ```
    pub fn join(self) -> Result<Report> {
        self.thread.join().unwrap_or_else(|panic| panic::resume_unwind(panic))
    }
}

/// A task taken from the stream: running, being answered, or released.
#[derive(Default)]
pub(crate) struct Flight {
    pub(crate) state: AtomicU8,
    leased: AtomicBool,
    lost: AtomicBool,
    /// Set once the worker starts to acknowledge the entry: from then on, an entry no longer
    /// pending may be one this worker has acknowledged.
    acking: AtomicBool,
    /// Held across a heartbeat and across a release, so a renewal can't land after a release
    /// and undo it.
    lease: Mutex<()>,
}

pub(crate) const ACTIVE: u8 = 0;
pub(crate) const FINISHING: u8 = 1;
pub(crate) const RELEASED: u8 = 2;

impl Flight {
    pub(crate) fn moves(&self, from: u8, to: u8) -> bool {
        self.state
            .compare_exchange(from, to, Ordering::SeqCst, Ordering::SeqCst)
            .is_ok()
    }

    fn lock_lease(&self) -> MutexGuard<'_, ()> {
        self.lease.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// One run of a worker: what the read loop, the lease heartbeat and the task threads share.
struct Run {
    config: Arc<WorkerConfig>,
    streams: Arc<dyn Streams>,
    handler: Arc<dyn Handler>,
    clock: Clock,
    control: Arc<Control>,
    flights: Mutex<HashMap<EntryId, Arc<Flight>>>,
    results: AtomicU64,
    released: Mutex<Vec<EntryId>>,
    lease_stop: AtomicBool,
    lease_wake: Signal,
}

impl Run {
    fn stopping(&self) -> bool {
        self.control.stopping.load(Ordering::SeqCst)
    }

    fn lock_flights(&self) -> MutexGuard<'_, HashMap<EntryId, Arc<Flight>>> {
        self.flights.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn lock_released(&self) -> MutexGuard<'_, Vec<EntryId>> {
        self.released.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn read_loop(self: &Arc<Self>) {
        let config = &self.config;
        let mut cursor = EntryId::ZERO;
        while !self.stopping() {
            let seen = self.control.wake.seen();
            let free = config.concurrency.saturating_sub(self.lock_flights().len());
            if free == 0 {
                self.clock.wait(Some((&self.control.wake, seen)), None);
                continue;
            }
            match self.streams.xautoclaim(
                &config.stream,
                &config.group,
                &config.consumer,
                config.claim_idle,
                cursor,
                free,
            ) {
                Ok(claim) => {
                    cursor = claim.next;
                    if !claim.deleted.is_empty()
                        && let Err(error) = self.streams.xack_xdel(&config.stream, &config.group, &claim.deleted)
                    {
                        tracing::warn!(%error, "Couldn't acknowledge claimed entries that were deleted");
                    }
                    if !claim.claimed.is_empty() {
                        for entry in claim.claimed {
                            // Our own entry, idle after missed heartbeats: its handler still runs,
                            // and the claim renewed its lease...
                            if self.lock_flights().contains_key(&entry.id) {
                                tracing::warn!(entry = %entry.id, "Claimed back an entry this worker still runs");
                                continue;
                            }
                            tracing::info!(entry = %entry.id, "Claimed an entry another consumer left idle");
                            self.dispatch(entry, true);
                        }
                        continue;
                    }
                }
                Err(error) => {
                    cursor = EntryId::ZERO;
                    tracing::warn!(%error, "Couldn't claim idle entries");
                }
            }
            if self.stopping() {
                break;
            }
            match self.streams.xreadgroup(
                &config.stream,
                &config.group,
                &config.consumer,
                free,
                Some(config.read_block),
            ) {
                Ok(entries) => {
                    for entry in entries {
                        if self.stopping() {
                            self.release(entry.id, "delivered after the stop");
                        } else {
                            self.dispatch(entry, false);
                        }
                    }
                }
                Err(error) => {
                    tracing::error!(%error, "Couldn't read tasks");
                    if matches!(error, Error::NoGroup { .. })
                        && let Err(error) = self.streams.xgroup_create(&config.stream, &config.group)
                    {
                        tracing::error!(%error, "Couldn't create the consumer group again");
                    }
                    let deadline = self.clock.monotonic().saturating_add(READ_RETRY);
                    self.clock.wait(Some((&self.control.wake, seen)), Some(deadline));
                }
            }
        }
    }

    fn dispatch(self: &Arc<Self>, entry: Entry, reclaimed: bool) {
        let id = entry.id;
        // Leased from now: the heartbeat covers the entry before its thread first runs...
        let flight = Arc::new(Flight {
            leased: AtomicBool::new(true),
            ..Flight::default()
        });
        self.lock_flights().insert(id, Arc::clone(&flight));
        let run = Arc::clone(self);
        let running = Arc::clone(&flight);
        let spawned = thread::Builder::new()
            .name("legit-streams-task".to_owned())
            .spawn(move || {
                run.process(&entry, reclaimed, &running);
                run.remove_flight(entry.id, &running);
                run.control.wake.raise();
            });
        if let Err(error) = spawned {
            tracing::error!(entry = %id, %error, "Couldn't start a thread for a task");
            self.remove_flight(id, &flight);
            self.release(id, "no thread to run it on");
        }
    }

    /// Forget a flight, unless the entry's id has since been given to another one.
    fn remove_flight(&self, id: EntryId, flight: &Arc<Flight>) {
        let mut flights = self.lock_flights();
        if flights.get(&id).is_some_and(|current| Arc::ptr_eq(current, flight)) {
            flights.remove(&id);
        }
    }

    fn process(&self, entry: &Entry, reclaimed: bool, flight: &Arc<Flight>) {
        let config = &self.config;
        let started = self.clock.monotonic();
        let deliveries = match self.streams.xpending_entry(&config.stream, &config.group, entry.id) {
            Ok(Some(pending)) => pending.deliveries,
            Ok(None) => 0,
            Err(error) => {
                tracing::warn!(entry = %entry.id, %error, "Couldn't read the delivery count; taking it as the first");
                1
            }
        };
        if deliveries > config.max_deliveries {
            let message = format!(
                "delivered {deliveries} times (max {}); earlier attempts died mid-task",
                config.max_deliveries
            );
            self.refuse(entry, flight, message, MAX_DELIVERIES_EXCEEDED, started);
            return;
        }
        let task = match Task::from_raw(&entry.fields, &config.limits) {
            Ok(task) => task,
            Err(error) => {
                tracing::warn!(entry = %entry.id, %error, "The entry isn't a valid task");
                let error_type = if matches!(error, Error::UnsupportedVersion(_)) {
                    UNSUPPORTED_VERSION
                } else {
                    INVALID_TASK
                };
                self.refuse(entry, flight, error.to_string(), error_type, started);
                return;
            }
        };
        if flight.state.load(Ordering::SeqCst) == RELEASED {
            return;
        }
        self.beat(entry.id, flight);
        let context = Context::new(
            entry.id,
            deliveries,
            reclaimed,
            Arc::clone(flight),
            Arc::clone(&self.control),
            self.clock.clone(),
            started,
        );
        tracing::debug!(task_id = task.task_id(), entry = %entry.id, deliveries, "Running a task");
        let outcome = panic::catch_unwind(AssertUnwindSafe(|| self.handler.handle(&task, &context)));
        if let Ok(Err(failure)) = &outcome
            && failure.is_abandon()
        {
            tracing::info!(
                task_id = task.task_id(),
                reason = failure.message(),
                "The handler abandoned a task"
            );
            self.release_flight(entry.id, flight, "abandoned by the handler");
            return;
        }
        if flight.lost.load(Ordering::SeqCst) {
            tracing::warn!(task_id = task.task_id(), entry = %entry.id, "The task finished after its lease was lost; its result is discarded");
            return;
        }
        let Some(result) = answer(&task, outcome) else {
            return;
        };
        self.finish(
            entry,
            flight,
            result,
            Origin::Handler,
            task.reply_to().map(str::to_owned),
            started,
        );
    }

    /// Answer an entry that isn't run with an error of this type, carrying its `task_id` exactly as
    /// sent and routed as any result is; or, when it has no `task_id` to answer with (none, an
    /// empty one, or one that isn't UTF-8 of at most 256 bytes), remove it unanswered.
    fn refuse(&self, entry: &Entry, flight: &Flight, message: String, error_type: &str, started: Duration) {
        let Some(task_id) = answerable_task_id(&entry.fields) else {
            tracing::warn!(entry = %entry.id, error_type, "The entry has no `task_id` to answer with; it's removed without a result");
            self.remove(entry, flight);
            return;
        };
        let result =
            ResultBuilder::for_raw(&entry.fields, Some(task_id), Status::Error, message).error_type(error_type);
        self.finish(
            entry,
            flight,
            result,
            Origin::Refusal,
            fields::last(&entry.fields, "reply_to").map(str::to_owned),
            started,
        );
    }

    /// Acknowledge and delete an entry without a result, unless the lease on it is lost.
    fn remove(&self, entry: &Entry, flight: &Flight) {
        if !flight.moves(ACTIVE, FINISHING) {
            return;
        }
        self.acknowledge(entry.id, flight, "remove an entry that isn't a task");
    }

    /// Write the result, then acknowledge and delete the task.
    ///
    /// Each try of the write, and of the acknowledgement, first checks the lease: a flag the
    /// heartbeat set, then a renewal. A lease found lost at any of them, before the first write
    /// or while a failed write or acknowledgement is retried, means another worker has the task:
    /// this one stops, writes nothing more, and leaves the entry to it. A renewal that passes also
    /// restarts the idle time, so no other worker can claim the entry for a whole `claim_idle`
    /// before the step it guards.
    fn finish(
        &self,
        entry: &Entry,
        flight: &Flight,
        result: ResultBuilder,
        origin: Origin,
        reply_to: Option<String>,
        started: Duration,
    ) {
        if !flight.moves(ACTIVE, FINISHING) {
            return;
        }
        let config = &self.config;
        let elapsed = self.clock.monotonic().saturating_sub(started);
        let result = result
            .worker_id(&config.consumer)
            .processing_ms(u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX));
        let fields = result_fields(&config.limits, result, origin);
        let stream = match reply_to.filter(|reply_to| config.route_results_per_app && !reply_to.is_empty()) {
            Some(reply_to) if is_valid_reply_to(&reply_to) => reply_to,
            Some(_) => {
                tracing::warn!(entry = %entry.id, stream = %config.result_stream, "The task's `reply_to` isn't a valid reply stream; its result goes to the default result stream");
                config.result_stream.clone()
            }
            None => config.result_stream.clone(),
        };
        let pairs = fields::as_bytes(&fields);
        let written = self.attempt("write the result", || {
            if let Some(lost) = self.check(entry.id, flight) {
                tracing::warn!(entry = %entry.id, reason = %lost, "The lease was lost before the result was written; the result is discarded");
                return Ok(false);
            }
            self.streams.xadd(&stream, &pairs).map(|_| true)
        });
        if !written {
            return;
        }
        self.results.fetch_add(1, Ordering::SeqCst);
        self.acknowledge(entry.id, flight, "acknowledge the task");
    }

    /// Acknowledge and delete an entry, with the lease checked before each try.
    ///
    /// A lease known lost, from the heartbeat or an earlier check, stops every try, and so does a
    /// renewal that finds another consumer owning the entry. Once a try has been sent, part of it
    /// may have landed (`XACK` and `XDEL` are two commands), so a renewal that finds the entry no
    /// longer pending doesn't mark the lease lost: that's this worker's own acknowledgement, and
    /// only its deletion is tried again, for as many tries as are left.
    fn acknowledge(&self, id: EntryId, flight: &Flight, what: &str) {
        let config = &self.config;
        let ids = [id];
        let mut sent = false;
        self.attempt(what, || {
            let lost = if sent {
                // A loss already known stays known, whatever this renewal answers; a renewal
                // that finds the entry no longer pending marks nothing, since that may be this
                // worker's own acknowledgement...
                let _lease = flight.lock_lease();
                if flight.lost.load(Ordering::SeqCst) {
                    Some(Lost::Earlier)
                } else {
                    let lost = self.renew(id);
                    if lost.is_some_and(|lost| !matches!(lost, Lost::Lease(LostLease::NotPending))) {
                        flight.lost.store(true, Ordering::SeqCst);
                    }
                    lost
                }
            } else {
                self.check(id, flight)
            };
            match lost {
                Some(Lost::Lease(LostLease::NotPending)) if sent => {
                    return self.streams.xdel(&config.stream, &ids).map(|_| true);
                }
                Some(lost) => {
                    tracing::warn!(entry = %id, reason = %lost, "The lease was lost before the entry was acknowledged; it's left to its owner");
                    return Ok(false);
                }
                None => {}
            }
            flight.acking.store(true, Ordering::SeqCst);
            sent = true;
            self.streams.xack_xdel(&config.stream, &config.group, &ids).map(|()| true)
        });
    }

    /// The lease right before a step of finishing: `Some` when it's known lost, from the
    /// heartbeat or from a renewal made now. A renewal the server doesn't answer says nothing,
    /// and the step goes ahead.
    fn check(&self, id: EntryId, flight: &Flight) -> Option<Lost> {
        let _lease = flight.lock_lease();
        if flight.lost.load(Ordering::SeqCst) {
            return Some(Lost::Earlier);
        }
        let lost = self.renew(id);
        if lost.is_some() {
            flight.lost.store(true, Ordering::SeqCst);
        }
        lost
    }

    /// Run `step` up to `flush_attempts` times with a growing wait, returning whether it worked.
    /// A step answers `Ok(true)` when done, `Ok(false)` to stop without retrying, such as on a
    /// lost lease, and an error to be tried again.
    fn attempt(&self, what: &str, mut step: impl FnMut() -> Result<bool>) -> bool {
        let attempts = self.config.flush_attempts;
        for attempt in 1..=attempts {
            match step() {
                Ok(done) => return done,
                Err(error) if attempt == attempts => {
                    tracing::error!(%error, attempt, "Couldn't {what}; the task stays pending for another worker");
                }
                Err(error) => {
                    tracing::warn!(%error, attempt, "Couldn't {what}; trying again");
                    self.clock.sleep(self.config.flush_backoff.saturating_mul(attempt));
                }
            }
        }
        false
    }

    fn lease_loop(&self) {
        loop {
            let seen = self.lease_wake.seen();
            if self.lease_stop.load(Ordering::SeqCst) {
                return;
            }
            let leased: Vec<(EntryId, Arc<Flight>)> = self
                .lock_flights()
                .iter()
                .filter(|(_, flight)| flight.leased.load(Ordering::SeqCst))
                .map(|(id, flight)| (*id, Arc::clone(flight)))
                .collect();
            for (id, flight) in &leased {
                self.beat(*id, flight);
            }
            let deadline = self.clock.monotonic().saturating_add(self.config.lease_heartbeat);
            self.clock.wait(Some((&self.lease_wake, seen)), Some(deadline));
        }
    }

    /// Renew the lease on an entry while its task runs, and mark the lease lost when it is.
    fn beat(&self, id: EntryId, flight: &Flight) {
        let _lease = flight.lock_lease();
        // The lease holds until the task is acknowledged, so no one claims it while its result
        // is being written...
        let state = flight.state.load(Ordering::SeqCst);
        if flight.lost.load(Ordering::SeqCst) || state == RELEASED {
            return;
        }
        match self.renew(id) {
            // ...and once this worker has started to acknowledge it, the entry may be gone for
            // that reason.
            Some(Lost::Lease(LostLease::NotPending)) if state == FINISHING && flight.acking.load(Ordering::SeqCst) => {}
            Some(lost) => {
                flight.lost.store(true, Ordering::SeqCst);
                tracing::error!(entry = %id, reason = %lost, "Lost the lease on a task");
            }
            None => {}
        }
    }

    /// Renew the lease on an entry: `None` when it was renewed, or when the server couldn't say,
    /// which leaves the lease as it was until the next try; the reason when it's lost.
    ///
    /// A renewal is [`Streams::renew_lease`], one atomic step on the server. Reading the consumer's
    /// own history with `XREADGROUP … 0` would reset the idle time too, but it counts a delivery on
    /// every read, so a slow task would use up its delivery limit; it isn't a renewal.
    fn renew(&self, id: EntryId) -> Option<Lost> {
        let config = &self.config;
        match self
            .streams
            .renew_lease(&config.stream, &config.group, &config.consumer, id)
        {
            Ok(Renewal::Renewed) => None,
            Ok(Renewal::Lost(lost)) => Some(Lost::Lease(lost)),
            Err(Error::NoGroup { .. }) => Some(Lost::NoGroup),
            Err(error) => {
                tracing::warn!(entry = %id, %error, "Couldn't renew a lease; trying again at the next heartbeat");
                None
            }
        }
    }

    /// Release a task that hasn't been answered, unless it's being answered already.
    fn release_flight(&self, id: EntryId, flight: &Flight, why: &str) {
        let _lease = flight.lock_lease();
        if flight.moves(ACTIVE, RELEASED) {
            self.release(id, why);
        }
    }

    /// Hand an entry this worker owns to the next worker that claims idle entries. An entry
    /// another worker has claimed meanwhile is left with it: the check and the release are one
    /// step, [`Streams::release_lease`].
    fn release(&self, id: EntryId, why: &str) {
        let config = &self.config;
        match self
            .streams
            .release_lease(&config.stream, &config.group, &config.consumer, id, config.claim_idle)
        {
            Ok(true) => tracing::info!(entry = %id, why, "Released an entry to other workers"),
            Ok(false) => tracing::info!(entry = %id, why, "Didn't release an entry: it's no longer this worker's"),
            Err(error) => {
                tracing::warn!(entry = %id, why, %error, "Couldn't release an entry; it's claimable once idle");
            }
        }
        self.lock_released().push(id);
    }

    /// Wait for running tasks up to the grace, release what's still running, and wait for results
    /// being written.
    fn shut_down(&self) {
        let deadline = self.clock.monotonic().saturating_add(self.config.shutdown_grace);
        loop {
            let seen = self.control.wake.seen();
            if self.lock_flights().is_empty() || self.clock.monotonic() >= deadline {
                break;
            }
            self.clock.wait(Some((&self.control.wake, seen)), Some(deadline));
        }
        let running: Vec<(EntryId, Arc<Flight>)> = self
            .lock_flights()
            .iter()
            .map(|(id, flight)| (*id, Arc::clone(flight)))
            .collect();
        for (id, flight) in running {
            self.release_flight(id, &flight, "still running when the shutdown grace ran out");
        }
        loop {
            let seen = self.control.wake.seen();
            let finishing = self
                .lock_flights()
                .values()
                .any(|flight| flight.state.load(Ordering::SeqCst) == FINISHING);
            if !finishing {
                return;
            }
            self.clock.wait(Some((&self.control.wake, seen)), None);
        }
    }

    /// Remove this worker's consumer from the group, unless it still owns entries.
    fn remove_consumer(&self) {
        let config = &self.config;
        match self
            .streams
            .xpending_consumer(&config.stream, &config.group, &config.consumer, 1)
        {
            Ok(owned) if owned.is_empty() => {
                if let Err(error) = self
                    .streams
                    .xgroup_delconsumer(&config.stream, &config.group, &config.consumer)
                {
                    tracing::debug!(%error, "Couldn't remove the consumer");
                }
            }
            Ok(_) => {}
            Err(error) => tracing::debug!(%error, "Couldn't check what the consumer owns"),
        }
    }
}

/// Why a worker lost a lease.
#[derive(Debug, Clone, Copy)]
enum Lost {
    /// The entry isn't this consumer's any more.
    Lease(LostLease),
    /// The consumer group is gone, and its pending list with it.
    NoGroup,
    /// The heartbeat, or an earlier check, found the lease lost.
    Earlier,
}

impl fmt::Display for Lost {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Lease(lost) => lost.fmt(f),
            Self::NoGroup => f.write_str("the consumer group is gone"),
            Self::Earlier => f.write_str("the lease was found lost earlier"),
        }
    }
}

/// What a handler returned, or how it panicked.
pub(crate) type Outcome = std::thread::Result<std::result::Result<Reply, Failure>>;

/// The result of a task from its handler's outcome; `None` when the handler abandoned it.
pub(crate) fn answer(task: &Task, outcome: Outcome) -> Option<ResultBuilder> {
    let result = match outcome {
        Ok(Ok(reply)) => {
            let mut result = TaskResult::success(task.task_id()).echo(task);
            if let Some(model_name) = reply.model_name {
                result = result.model_name(model_name);
            }
            reply
                .fields
                .into_iter()
                .fold(result, |result, (name, value)| result.field(name, value))
        }
        Ok(Err(failure)) => {
            let FailureKind::Error { error_type, message } = failure.kind else {
                return None;
            };
            let mut result = TaskResult::failure(task.task_id(), message)
                .echo(task)
                .error_type(error_type);
            if let Some(model_name) = failure.model_name {
                result = result.model_name(model_name);
            }
            failure
                .fields
                .into_iter()
                .fold(result, |result, (name, value)| result.field(name, value))
        }
        Err(panic) => {
            tracing::error!(task_id = task.task_id(), "The handler panicked");
            TaskResult::failure(
                task.task_id(),
                format!("the handler panicked: {}", panic_message(panic.as_ref())),
            )
            .echo(task)
            .error_type(INTERNAL)
        }
    };
    Some(result)
}

/// Where a result comes from, which decides how one over the worker's limits is cut down.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Origin {
    /// The handler's reply to a task it ran.
    Handler,
    /// The worker's own error for an entry it didn't run, such as `invalid_task`.
    Refusal,
}

/// The result's fields, within the limits.
///
/// A handler's successful reply over the limits becomes a `result_too_large` error, and one that
/// still doesn't fit is cut down to its identity and error. A refusal, and a handler's own error,
/// keep their error and code whatever they echo: an echo or a field that puts them over the limits
/// is dropped, never reported as a `result_too_large` the reply didn't cause.
pub(crate) fn result_fields(limits: &Limits, result: ResultBuilder, origin: Origin) -> Vec<(String, String)> {
    if origin == Origin::Refusal {
        return refusal_fields(limits, result);
    }
    let fallback = result.clone();
    match result.build_within(limits) {
        Ok(result) => return result.into_fields(),
        // A handler's error keeps its code, shed of what it echoes and carries as a refusal is...
        Err(Error::TooLarge { .. }) if fallback.is_error() => return refusal_fields(limits, fallback),
        Err(Error::TooLarge { what, limit, actual }) => {
            let message = format!("the result's {what} is {actual}, over the limit of {limit}");
            let error = fallback.into_error(message, RESULT_TOO_LARGE);
            let fields = error.clone().into_fields();
            if limits.check(&fields).is_ok() {
                return fields;
            }
            return error.bare().into_fields();
        }
        // An entry that isn't a valid task has no task to build from...
        Err(Error::MissingField(_) | Error::EmptyField(_)) => {}
        Err(error) => {
            let message = format!("the handler's reply isn't a valid result: {error}");
            let error = fallback.into_error(message, INTERNAL);
            if let Ok(result) = error.clone().build_within(limits) {
                return result.into_fields();
            }
            return error.bare().into_fields();
        }
    }
    let fields = fallback.clone().into_fields();
    if fields::check_strings(&fields, limits).is_ok() {
        fields
    } else {
        fallback.bare().into_fields()
    }
}

/// A refusal's fields within the limits, shrunk one step at a time until they fit: all it
/// echoes, then without the optional echoes such as `metadata`, then with each of `model_type`,
/// `model_id` and `task_name` replaced by `unknown` when over 1,024 bytes, then with all three
/// `unknown`. Every step keeps `model_name` as the task asked; it is emptied only last, when it
/// alone doesn't fit. Its status, error and `error_type` are never changed.
fn refusal_fields(limits: &Limits, result: ResultBuilder) -> Vec<(String, String)> {
    let steps = [
        result.clone(),
        result.clone().without_echoes(),
        result.clone().cut(1024, usize::MAX),
        result.clone().cut(0, usize::MAX),
    ];
    for step in steps {
        let fields = step.into_fields();
        if fields::check_strings(&fields, limits).is_ok() {
            return fields;
        }
    }
    result.cut(0, 0).into_fields()
}

fn panic_message(panic: &(dyn std::any::Any + Send)) -> &str {
    panic
        .downcast_ref::<&str>()
        .copied()
        .or_else(|| panic.downcast_ref::<String>().map(String::as_str))
        .unwrap_or("a panic without a message")
}