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
//! Durable tasks: the `V1Dispatcher.DurableTask` stream and the handler-facing
//! pieces built on it.
//!
//! A durable task's handler is re-executed from the top every time the engine
//! assigns the task — after a worker dies, say — but the durable steps it
//! already got through are *not* waited for again: the engine keeps an event
//! log per run and replays the entries this attempt reaches in the same order.
//! All the SDK guarantees is that it makes **the same requests in the same
//! order**; diverging from the log is
//! [`Error::Nondeterminism`](crate::Error::Nondeterminism), and that failure is
//! not retried.

pub(crate) mod eviction;
pub(crate) mod stream;

pub use eviction::EvictionPolicy;

use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, SystemTime};

use hatchet_proto::v1::DurableEventLogEntryRef;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
use tracing::{Instrument, Span};

use crate::declare::condition::to_durable_proto;
use crate::durable::stream::DurableStream;
use crate::trigger::ParentRef;
use crate::{Condition, ConditionSet, Context, Error, RunOpts, Task, TaskError, otel};

/// How a durable failure reaches the engine.
///
/// The blanket `From<E: std::error::Error> for TaskError` makes every `?`
/// retryable, which would be wrong for exactly one case: a run that diverged
/// from its event log fails the same way however often it is retried, so it is
/// reported with `should_not_retry`.
pub(crate) fn task_error(error: Error) -> TaskError {
    match error {
        // A run that diverged from its log fails the same way however often it
        // is retried…
        Error::Nondeterminism { .. }
        // …and so does a call the engine is too old for: a retry reaches the
        // same engine.
        | Error::UnsupportedFeature { .. } => TaskError::non_retryable(error.to_string()),
        other => TaskError::new(other.to_string()),
    }
}

/// One assignment of one durable task run: the stream it talks to, which
/// attempt it is, and the two pieces of per-attempt state the durable
/// operations keep.
///
/// Built by the runner when it dispatches a durable action, and reachable only
/// through a [`DurableContext`].
pub(crate) struct DurableInvocation {
    stream: DurableStream,
    /// `AssignedAction.task_run_external_id`: the durable task run the engine
    /// keeps an event log for.
    task_id: String,
    /// `AssignedAction.durable_task_invocation_count`, never below 1.
    invocation_count: i32,
    /// Held across "queue the request, wait for its ack".
    ///
    /// The engine's ack names only `(task, invocation)`, so two requests in
    /// flight for one invocation could not be told apart — and the node ids
    /// would be handed out in whichever order won the race, which the next
    /// attempt could not repeat.
    sending: tokio::sync::Mutex<()>,
    /// The memo values this attempt has already seen, by key. The engine makes
    /// a fresh log entry for every `memo` request, even for a key it was asked
    /// about a moment ago, so asking twice would leave the attempts unable to
    /// match: this is the dedup.
    memos: Mutex<HashMap<String, Vec<u8>>>,
    /// What `Dispatcher/GetVersion` said when this worker was built.
    ///
    /// Kept per invocation because the gate that needs it —
    /// [`DurableContext::spawn`] — can only be checked when it is called:
    /// whether a handler ever spawns is not knowable from its declaration.
    engine_version: Arc<str>,
    /// The worker's eviction ledger, when this worker keeps one. Every durable
    /// wait tells it that this run has stopped working, so a run that is only
    /// parked can be handed back.
    book: Option<Arc<eviction::EvictionBook>>,
}

impl DurableInvocation {
    pub(crate) fn new(
        stream: DurableStream,
        task_id: String,
        invocation_count: i32,
        engine_version: Arc<str>,
        book: Option<Arc<eviction::EvictionBook>>,
    ) -> Self {
        Self {
            stream,
            task_id,
            invocation_count,
            sending: tokio::sync::Mutex::new(()),
            memos: Mutex::new(HashMap::new()),
            engine_version,
            book,
        }
    }

    /// Marks this run as waiting for as long as the guard is held.
    ///
    /// `None` on a worker with no eviction policy anywhere, which keeps no
    /// ledger at all: there would be nothing to read it.
    fn mark_waiting(&self, kind: &'static str, resource: &str) -> Option<eviction::WaitingGuard> {
        self.book
            .as_ref()
            .map(|book| book.mark_waiting(&self.task_id, kind, resource))
    }

    /// The value this attempt already has for `key`, if it has one.
    fn cached(&self, key: &str) -> Option<Vec<u8>> {
        self.memos
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(key)
            .cloned()
    }

    /// Remembers `payload` as this attempt's value for `key`.
    fn remember(&self, key: &str, payload: &[u8]) {
        self.memos
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(key.to_string(), payload.to_vec());
    }
}

/// The context a durable task's handler is given.
///
/// Everything a [`Context`] can do — it derefs to one — plus the durable
/// operations. Only
/// [`TaskBuilder::durable_handler`](crate::TaskBuilder::durable_handler) can
/// produce one, so an ordinary handler cannot reach them by accident.
///
/// # Determinism
///
/// A durable handler is re-run **from the top** every time its task is
/// assigned again: the SDK skips nothing. What makes that cheap is the
/// engine's event log — every durable step this attempt reaches is answered
/// from the log if the previous attempt already got through it, so a sleep
/// that is over returns at once and a memo that was computed comes back with
/// its recorded value.
///
/// The bargain is that the handler must reach the same durable operations in
/// the same order on every attempt. Diverge from the log and the engine
/// answers [`Error::Nondeterminism`](crate::Error::Nondeterminism), which
/// fails the run **without a retry**. So:
///
/// * anything that must not be recomputed — a payment, a random number, the
///   clock — goes through [`memo`](Self::memo) or [`now`](Self::now);
/// * never branch on [`invocation_count`](Self::invocation_count) or on
///   [`retry_count`](Context::retry_count);
/// * never cut a durable wait short with `tokio::time::timeout` or a
///   `select!` arm that goes somewhere else — express the alternative as a
///   condition of the wait itself
///   ([`wait_for`](Self::wait_for) with [`any_of`](crate::any_of)).
///
/// A spawn is a durable operation like any other: reach the same spawns, in
/// the same order, on every attempt. The engine hands a replayed spawn the
/// runs it started the first time, so the children are not started twice —
/// but only if the spawn is in the same place in the log.
///
/// A durable request is also **irreversible the moment it is queued**:
/// dropping the future that was waiting for it does not un-make the engine's
/// log entry.
///
/// A run that is only *waiting* — for a sleep, an event, a child — can be
/// evicted: handed back to the engine so its worker's durable slot can run
/// something else ([`TaskBuilder::eviction_policy`](crate::TaskBuilder::eviction_policy)).
/// Eviction cancels the handler right where it was waiting, and when the
/// engine assigns the run again it starts from the top like any other
/// re-assignment. So a policy belongs only on a handler whose replay is
/// already safe — eviction adds no new way to be non-deterministic, but it
/// does make replay happen more often.
///
/// # Cancellation
///
/// A durable wait ends with an error as soon as the run is cancelled — by the
/// engine, by an eviction, or by a worker shutting down — so a handler parked
/// on the engine stops rather than standing there. That failure is not
/// reported: a cancelled run belongs to the engine, and the worker suppresses
/// its terminal event exactly as it does for an ordinary one.
#[derive(Clone)]
pub struct DurableContext {
    context: Context,
    durable: Arc<DurableInvocation>,
}

/// As thin as [`Context`]'s, and for the same reason: a durable handler's
/// input and metadata are no more printable than an ordinary one's.
impl std::fmt::Debug for DurableContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DurableContext")
            .field("task_run_id", &self.context.task_run_id())
            .field("invocation_count", &self.durable.invocation_count)
            .finish_non_exhaustive()
    }
}

impl std::ops::Deref for DurableContext {
    type Target = Context;

    fn deref(&self) -> &Context {
        &self.context
    }
}

impl DurableContext {
    /// Wraps the context the runner built for a durable action.
    ///
    /// Fails when there is no durable invocation attached, which is a worker
    /// bug rather than a user error — so it is reported as a failed run rather
    /// than panicked on.
    pub(crate) fn attach(context: Context) -> Result<Self, TaskError> {
        let durable = context.durable().cloned().ok_or_else(|| {
            TaskError::non_retryable(
                "this task is declared durable, but the action it was given carries no durable \
                 invocation; the worker has no durable stream",
            )
        })?;
        Ok(Self { context, durable })
    }

    /// Which attempt at this task run is executing.
    ///
    /// `1` on the first, and one more each time the engine assigns the task
    /// again — after an eviction, or a worker that went away. Useful in a log
    /// line; **never branch on it**, or the attempts stop matching each other.
    #[must_use]
    pub fn invocation_count(&self) -> i32 {
        self.durable.invocation_count
    }

    /// Waits `duration` on the engine, not on this worker.
    ///
    /// The wait survives a worker that dies: the engine records it in the
    /// task run's event log, so the task is assigned again and the handler
    /// re-runs with this sleep answered as soon as it is reached — the
    /// remaining time is not restarted.
    ///
    /// Sleeps under a second are not dependable: the engine polls, and a
    /// six-second sleep was measured completing between 6.3 and 7.5 seconds
    /// after the request on both supported engines. Prefer a few seconds or
    /// more.
    ///
    /// # Errors
    ///
    /// [`TaskError`], non-retryable when the engine answers
    /// [`Error::Nondeterminism`] — this attempt reached a different durable
    /// step than the log records, and retrying would reach the same one.
    /// Retryable for anything else: a stream that ended, an ack that never
    /// came, an eviction.
    ///
    /// ```
    /// # use std::time::Duration;
    /// # use hatchet_client::TaskBuilder;
    /// let wait = TaskBuilder::<(), ()>::new("wait")
    ///     .durable_handler(|ctx, _input| async move {
    ///         ctx.sleep_for(Duration::from_secs(60)).await?;
    ///         Ok(())
    ///     });
    /// # let _ = wait;
    /// ```
    pub async fn sleep_for(&self, duration: Duration) -> Result<(), TaskError> {
        self.wait(Condition::sleep(duration).into(), None).await?;
        Ok(())
    }

    /// Waits for an event pushed under `key`, namespaced exactly as
    /// [`EventsClient::push`](crate::EventsClient::push) namespaces it, and
    /// hands back what was pushed.
    ///
    /// Unlike a task condition — which the engine answers with nothing but the
    /// fact that it matched — a durable event wait carries the event's body,
    /// measured on both supported engines.
    ///
    /// # Errors
    ///
    /// [`TaskError`], on the same terms as [`sleep_for`](Self::sleep_for).
    /// Also an error when the engine completed the wait with no match at all,
    /// which would otherwise be an empty [`DurableEvent`] the handler could
    /// not tell from a real one.
    ///
    /// ```
    /// # use hatchet_client::TaskBuilder;
    /// let approve = TaskBuilder::<(), String>::new("approve")
    ///     .durable_handler(|ctx, _input| async move {
    ///         let event = ctx.wait_for_event("approval.granted").await?;
    ///         Ok(event.payload.to_string())
    ///     });
    /// # let _ = approve;
    /// ```
    pub async fn wait_for_event(&self, key: &str) -> Result<DurableEvent, TaskError> {
        let matched = self.wait(Condition::on_event(key).into(), None).await?;
        matched.into_iter().next().ok_or_else(|| {
            TaskError::new(format!(
                "the engine completed the durable wait for the event `{key}` without naming \
                 what matched"
            ))
        })
    }

    /// Waits for `conditions` — a sleep, an event, or an
    /// [`any_of`](crate::any_of) of them.
    ///
    /// Everything given must be satisfied; the matches come back in
    /// readable-key order, which is stable from attempt to attempt. A
    /// [`Condition::parent`](crate::Condition::parent) cannot be waited for
    /// here: the engine takes only sleeps and events on a durable wait.
    ///
    /// # Errors
    ///
    /// [`TaskError`], on the same terms as [`sleep_for`](Self::sleep_for), and
    /// non-retryable when the conditions themselves cannot be sent — no
    /// condition at all, a parent condition, or two conditions sharing a
    /// readable key (the engine indexes the result by that key, so one of the
    /// matches would be lost).
    ///
    /// ```
    /// # use std::time::Duration;
    /// # use hatchet_client::{Condition, TaskBuilder, any_of};
    /// let approve = TaskBuilder::<(), bool>::new("approve")
    ///     .durable_handler(|ctx, _input| async move {
    ///         // Whoever gets there first: the reviewer, or the deadline.
    ///         let matched = ctx
    ///             .wait_for(any_of([
    ///                 Condition::on_event("approval.granted"),
    ///                 Condition::sleep(Duration::from_secs(24 * 3600)),
    ///             ]))
    ///             .await?;
    ///         Ok(matched.iter().any(|event| event.key == "approval.granted"))
    ///     });
    /// # let _ = approve;
    /// ```
    pub async fn wait_for(
        &self,
        conditions: impl Into<ConditionSet>,
    ) -> Result<Vec<DurableEvent>, TaskError> {
        self.wait(conditions.into(), None).await
    }

    /// [`wait_for`](Self::wait_for) with a label the dashboard shows beside
    /// the wait, e.g. `"Waiting for payment confirmation"`.
    ///
    /// The label is a Python-SDK feature: the official Go SDK always sends an
    /// empty one (`pkg/worker/context.go:1207`). Both supported engines accept
    /// a filled one; what the dashboard does with it was not observed from
    /// here.
    ///
    /// # Errors
    ///
    /// The same as [`wait_for`](Self::wait_for).
    pub async fn wait_for_labeled(
        &self,
        label: &str,
        conditions: impl Into<ConditionSet>,
    ) -> Result<Vec<DurableEvent>, TaskError> {
        self.wait(conditions.into(), Some(label)).await
    }

    /// Waits until `at`, using [`now`](Self::now) as the clock so this
    /// attempt and its replays agree on how long is left.
    ///
    /// A deadline that has already passed sends nothing at all and returns —
    /// the same as the official Go SDK
    /// (`pkg/worker/context.go:1352-1362`). That branch is safe to replay
    /// because it depends only on the memoised `now`: every attempt reads the
    /// same clock and so takes the same path.
    ///
    /// # Errors
    ///
    /// [`TaskError`], on the same terms as [`sleep_for`](Self::sleep_for).
    /// The memo behind [`now`](Self::now) may fail the same way.
    pub async fn sleep_until(&self, at: SystemTime) -> Result<(), TaskError> {
        let now = self.now().await?;
        match at.duration_since(now) {
            Ok(remaining) if !remaining.is_zero() => self.sleep_for(remaining).await,
            // Already past, so there is nothing to wait for.
            _ => Ok(()),
        }
    }

    /// Computes a value once per task run, however often the handler is
    /// re-run.
    ///
    /// The engine is asked about `key` first. If it has a value recorded —
    /// because an earlier attempt computed one — that value comes back and
    /// **`f` is not called**; otherwise `f` runs and its result is recorded
    /// for the attempts that follow. Asking for the same key twice in one
    /// attempt is answered from memory, so it makes one log entry rather than
    /// two (the engine makes a fresh entry per request, so a second one would
    /// leave the attempts unable to match).
    ///
    /// This is where anything that cannot be repeated belongs: charging a
    /// card, drawing a random number, reading the clock (see
    /// [`now`](Self::now)), calling an API that is not idempotent. A value is
    /// recorded **per task run**, not per workflow: two tasks cannot share a
    /// memo.
    ///
    /// The key is sent as bytes exactly as written, as the official Go SDK
    /// sends it (`pkg/worker/context.go:1285`; the Python SDK hashes the
    /// arguments instead), and must be unique within the task.
    ///
    /// Recording the computed value is fire and forget, as in both official
    /// SDKs: a notification that does not reach the engine costs a
    /// recomputation on the next attempt, not correctness.
    ///
    /// # Errors
    ///
    /// [`TaskError`], on the same terms as [`sleep_for`](Self::sleep_for),
    /// plus whatever `f` itself returns, and non-retryable when the value
    /// cannot be serialized or the recorded one does not deserialize into `T`.
    ///
    /// ```
    /// # use hatchet_client::TaskBuilder;
    /// # use serde_json::Value;
    /// let charge = TaskBuilder::<Value, Value>::new("charge")
    ///     .durable_handler(|ctx, _input| async move {
    ///         let receipt: String = ctx
    ///             .memo("charge-the-card", || async { Ok("receipt-1".to_string()) })
    ///             .await?;
    ///         Ok(Value::String(receipt))
    ///     });
    /// # let _ = charge;
    /// ```
    pub async fn memo<T, F, Fut>(&self, key: &str, f: F) -> Result<T, TaskError>
    where
        T: Serialize + DeserializeOwned,
        F: FnOnce() -> Fut,
        Fut: Future<Output = Result<T, TaskError>>,
    {
        // 1. This attempt's own cache: one log entry per key, however many
        //    calls. The engine has no dedup of its own — asking twice was
        //    measured making a second node on both supported engines.
        if let Some(cached) = self.durable.cached(key) {
            return decode(key, &cached);
        }
        // 2. Ask the engine. One durable request at a time per invocation.
        let ack = {
            let _sending = self.durable.sending.lock().await;
            self.durable
                .stream
                .send_memo(
                    self.durable.task_id.clone(),
                    self.durable.invocation_count,
                    key,
                    None,
                )
                .await
        }
        .map_err(task_error)?;
        // 3. The engine already has it: nothing is computed, and `f` is
        //    dropped un-called.
        if let Some(recorded) = ack.existing {
            self.durable.remember(key, &recorded);
            return decode(key, &recorded);
        }
        // 4. It does not: compute, remember locally, and tell the engine.
        let value = f().await?;
        let payload = serde_json::to_vec(&value).map_err(|error| {
            TaskError::non_retryable(format!(
                "the memo `{key}` could not be serialized to JSON: {error}"
            ))
        })?;
        self.durable.remember(key, &payload);
        self.durable
            .stream
            .send_complete_memo(ack.reference, key, payload);
        Ok(value)
    }

    /// The current time, fixed for this task run.
    ///
    /// A replayed attempt gets the time the **first** attempt read, so a
    /// deadline computed from it does not move. Memoised under the key
    /// `__now__` — the official Go SDK's key
    /// (`pkg/worker/context.go:1332-1334`) — which is therefore reserved.
    ///
    /// The recorded value is `serde`'s own encoding of [`SystemTime`]
    /// (`{"secs_since_epoch": …, "nanos_since_epoch": …}`). Nothing else reads
    /// it, so there is no cross-SDK compatibility to keep.
    ///
    /// # Errors
    ///
    /// [`TaskError`], on the same terms as [`memo`](Self::memo).
    ///
    /// ```
    /// # use std::time::Duration;
    /// # use hatchet_client::TaskBuilder;
    /// let deadline = TaskBuilder::<(), ()>::new("deadline")
    ///     .durable_handler(|ctx, _input| async move {
    ///         // The same instant on every attempt, so the deadline is fixed.
    ///         let started = ctx.now().await?;
    ///         ctx.sleep_until(started + Duration::from_secs(3600)).await?;
    ///         Ok(())
    ///     });
    /// # let _ = deadline;
    /// ```
    pub async fn now(&self) -> Result<SystemTime, TaskError> {
        self.memo(NOW_KEY, || async { Ok(SystemTime::now()) }).await
    }

    /// Starts a run of `task` as a child of this one, deterministically.
    ///
    /// Unlike [`Context::spawn`](crate::Context::spawn) — which triggers the
    /// run over the workflow service — this goes through the durable event
    /// log: the engine records which runs this spawn started, and an attempt
    /// that reaches the same spawn again is handed **the same runs** rather
    /// than starting new ones. That is also why the result comes back on
    /// [`DurableRunHandle::result`] rather than on a run subscription: a
    /// subscription is this process's, and the log is the run's.
    ///
    /// What the engine replays on is the spawn's **position** in this
    /// invocation's log — measured, and measured to hold even when the
    /// `child_index` changes. So the rule is the one every durable operation
    /// keeps: a replay must reach the same durable calls, in the same order,
    /// with the same number of children each. The `child_index` claimed here —
    /// from the same sequence [`Context::spawn`] draws on — is the second
    /// safety net rather than the first.
    ///
    /// # Errors
    ///
    /// [`TaskError`], non-retryable when the engine is older than
    /// [`DURABLE_SPAWN_MIN_ENGINE_VERSION`](crate::DURABLE_SPAWN_MIN_ENGINE_VERSION)
    /// (nothing is sent: an older engine acknowledges the request without
    /// telling the SDK which run it started), when `input` cannot be
    /// serialized, or when the options are not usable for a child; retryable
    /// for a stream that ended or an ack that never came.
    ///
    /// ```
    /// # use hatchet_client::{RunOpts, TaskBuilder};
    /// # use serde_json::{Value, json};
    /// let child = TaskBuilder::<Value, Value>::new("child")
    ///     .handler(|_ctx, _input| async { Ok(json!({"ok": true})) });
    /// let parent = TaskBuilder::<Value, Value>::new("parent").durable_handler({
    ///     let child = child.clone();
    ///     move |ctx, _input| {
    ///         let child = child.clone();
    ///         async move {
    ///             let handle = ctx.spawn(&child, &json!({"n": 1}), RunOpts::default()).await?;
    ///             let output: Value = handle.result().await?;
    ///             Ok(output)
    ///         }
    ///     }
    /// });
    /// # let _ = parent;
    /// ```
    pub async fn spawn<I, O>(
        &self,
        task: &Task<I, O>,
        input: &I,
        opts: RunOpts,
    ) -> Result<DurableRunHandle<O>, TaskError>
    where
        I: Serialize,
        O: DeserializeOwned,
    {
        let span = otel::run_workflow(task.name());
        let spawned = self
            .spawn_all(task.name(), std::slice::from_ref(input), &opts, &span)
            .instrument(span.clone())
            .await;
        otel::record_result(&span, &spawned);
        let mut handles = spawned?;
        let handle = handles.pop().expect("one input, one handle");
        span.record("hatchet.child_workflow_run_id", handle.run_id());
        Ok(handle)
    }

    /// [`spawn`](Self::spawn) for several children of the same task, in
    /// **one** request — one round trip, and one ack.
    ///
    /// The handles come back in the order of `inputs`, and every one of them
    /// is already waiting for its result: awaiting them one after another is
    /// safe, whatever order the children finish in.
    ///
    /// # Errors
    ///
    /// Those of [`spawn`](Self::spawn), plus non-retryable when `inputs` is
    /// empty, when there is more than one input and `opts` carries a
    /// [`child_key`](crate::RunOpts::child_key) —
    /// one key for several children is how the engine is asked to fold them
    /// into one run (`api-contracts/v1/shared/trigger.proto:56-63`), which is
    /// never what this method means — or when the engine answers with a
    /// different number of entries than it was given triggers.
    ///
    /// ```
    /// # use hatchet_client::{RunOpts, TaskBuilder};
    /// # use serde_json::{Value, json};
    /// let child = TaskBuilder::<Value, Value>::new("child")
    ///     .handler(|_ctx, input| async move { Ok(input) });
    /// let fanout = TaskBuilder::<Value, Value>::new("fanout").durable_handler({
    ///     let child = child.clone();
    ///     move |ctx, _input| {
    ///         let child = child.clone();
    ///         async move {
    ///             let handles = ctx
    ///                 .spawn_many(&child, &[json!({"n": 0}), json!({"n": 1})], RunOpts::default())
    ///                 .await?;
    ///             let mut outputs = Vec::new();
    ///             for handle in handles {
    ///                 outputs.push(handle.result().await?);
    ///             }
    ///             Ok(Value::Array(outputs))
    ///         }
    ///     }
    /// });
    /// # let _ = fanout;
    /// ```
    pub async fn spawn_many<I, O>(
        &self,
        task: &Task<I, O>,
        inputs: &[I],
        opts: RunOpts,
    ) -> Result<Vec<DurableRunHandle<O>>, TaskError>
    where
        I: Serialize,
        O: DeserializeOwned,
    {
        // Go's `RunMany` opens `hatchet.run_workflows` whatever the count
        // (`sdks/go/workflow.go:1070-1077`).
        let span = otel::run_workflows(task.name(), inputs.len());
        let spawned = self
            .spawn_all(task.name(), inputs, &opts, &span)
            .instrument(span.clone())
            .await;
        otel::record_result(&span, &spawned);
        spawned
    }

    /// The one path both spawns take. The order of the steps is the whole
    /// point, so it is numbered. Every child's trigger carries `span`'s
    /// traceparent (with the `otel` feature).
    async fn spawn_all<I, O>(
        &self,
        name: &str,
        inputs: &[I],
        opts: &RunOpts,
        span: &Span,
    ) -> Result<Vec<DurableRunHandle<O>>, TaskError>
    where
        I: Serialize,
        O: DeserializeOwned,
    {
        // 1. The gate, before anything is built: an engine below it answers
        //    the request without saying which runs it started, which is worse
        //    than a refusal because nothing shows up as wrong.
        crate::version::ensure_feature(
            SPAWN_FEATURE,
            crate::version::DURABLE_SPAWN_MIN_ENGINE_VERSION,
            &self.durable.engine_version,
        )
        .map_err(task_error)?;
        if inputs.is_empty() {
            return Err(TaskError::non_retryable(
                "`DurableContext::spawn_many` was given no inputs; a request with no triggers \
                 would still make a log entry that the next attempt has to reproduce",
            ));
        }
        if inputs.len() > 1 && opts.has_child_key() {
            return Err(TaskError::non_retryable(format!(
                "`DurableContext::spawn_many` was given {} inputs and one `child_key`; the \
                 engine deduplicates children on `(parent run, parent task run, child key)`, so \
                 they would all fold into a single run. Call `spawn` once per child instead.",
                inputs.len()
            )));
        }

        // 2. The requests, with one child index each, claimed in order.
        let namespace = self.namespace()?;
        let mut requests = Vec::with_capacity(inputs.len());
        for input in inputs {
            let mut request = crate::trigger::request(
                &namespace,
                name,
                input,
                opts,
                Some(ParentRef {
                    workflow_run_id: self.context.workflow_run_id(),
                    task_run_external_id: self.context.task_run_id(),
                    child_index: self.context.claim_child_index(),
                    worker_id: self.context.worker_id(),
                }),
            )
            .map_err(task_error)?;
            // The spawn's own span, as Go injects before its durable path
            // (`sdks/go/workflow.go:1000`, `:1021`). A replay sends a
            // different one: the engine leaves metadata out of a log entry's
            // determinism check (v0.107.0: `pkg/repository/durable_events.go:784-785`),
            // and the P10 spike measured a replay being handed the same child
            // on v0.107.0 (v0.85.0-v0.106.x unmeasured). The child keeps the
            // first attempt's traceparent.
            otel::inject(span, &mut request.additional_metadata);
            requests.push(request);
        }

        // 3. One request, one ack — under the same lock every durable request
        //    takes, for the same reason (the ack names only
        //    `(task, invocation)`).
        let entries = {
            let _sending = self.durable.sending.lock().await;
            self.durable
                .stream
                .send_trigger_runs(
                    self.durable.task_id.clone(),
                    self.durable.invocation_count,
                    requests,
                )
                .await
        }
        .map_err(task_error)?;
        if entries.len() != inputs.len() {
            return Err(TaskError::non_retryable(format!(
                "the engine answered a durable spawn of {} child run(s) with {} log entr(ies); \
                 the SDK pairs handles with entries by position and cannot do so",
                inputs.len(),
                entries.len(),
            )));
        }

        // 4. Claim every waiter **now**, before any of them is awaited: an
        //    unclaimed completion only lives a few seconds, and the caller may
        //    well await the children one at a time.
        entries
            .into_iter()
            .map(|entry| {
                let reference = DurableEventLogEntryRef {
                    durable_task_external_id: self.durable.task_id.clone(),
                    invocation_count: self.durable.invocation_count,
                    branch_id: entry.branch_id,
                    node_id: entry.node_id,
                };
                Ok(DurableRunHandle {
                    run_id: entry.workflow_run_external_id,
                    task_name: name.to_string(),
                    wait: self
                        .durable
                        .stream
                        .claim_entry(reference)
                        .map_err(task_error)?,
                    context: self.context.clone(),
                    _output: PhantomData,
                })
            })
            .collect()
    }

    /// The one path every durable wait takes.
    async fn wait(
        &self,
        conditions: ConditionSet,
        label: Option<&str>,
    ) -> Result<Vec<DurableEvent>, TaskError> {
        let namespace = self.namespace()?;
        // From here to the end of this call the run is waiting rather than
        // working, which is the whole of what an eviction policy acts on. The
        // guard covers the ack as well as the completion: a request that is
        // on the wire is already a run that has stopped doing anything.
        let (kind, resource) = conditions.wait_kind();
        let _waiting = self.durable.mark_waiting(kind, &resource);
        let conditions =
            to_durable_proto(&namespace, &conditions).map_err(TaskError::non_retryable)?;
        // One durable request at a time per invocation: the engine's ack
        // carries only `(task, invocation)` to route by, so two in flight
        // would race for one slot — and their node ids would be handed out in
        // whichever order won, which the next attempt could not repeat. The
        // lock is given up as soon as the engine has named the entry; waiting
        // for that entry to *complete* happens outside it, so several waits
        // can be outstanding at once.
        let reference = {
            let _sending = self.durable.sending.lock().await;
            self.durable
                .stream
                .send_wait_for(
                    self.durable.task_id.clone(),
                    self.durable.invocation_count,
                    conditions,
                    label.map(str::to_string),
                )
                .await
        }
        .map_err(task_error)?;
        // A cancelled run wakes out of its wait rather than standing there
        // until the worker's drain drops it. The stream's own eviction
        // handling fails the waits it can find, but a wait registered in the
        // moment *between* the ack and here would not be among them — and a
        // run cancelled from the engine or by a shutdown has no eviction at
        // all. Either way the run is over and its terminal event is
        // suppressed, so ending the wait takes nothing away.
        let payload = tokio::select! {
            () = self.context.cancelled() => {
                return Err(TaskError::new(
                    "the run was cancelled while it waited on the engine",
                ));
            }
            payload = self.durable.stream.wait_for_entry(reference) => payload,
        }
        .map_err(task_error)?;
        Ok(matches(&payload))
    }

    /// The namespace this worker's client applies to event keys.
    fn namespace(&self) -> Result<String, TaskError> {
        Ok(self
            .context
            .client()
            .ok_or_else(|| {
                TaskError::non_retryable(
                    "a durable wait talks to the engine, and this context was built without a \
                     connection to one",
                )
            })?
            .config()
            .namespace()
            .to_string())
    }
}

/// What the version gate calls the thing it is gating, in the error and in the
/// worker's warning, so the two always read the same.
pub(crate) const SPAWN_FEATURE: &str = "spawning a child run from a durable handler";

/// A child run a durable handler started, and the result it is already waiting
/// for.
///
/// Dropping it gives that wait up; the child goes on running.
#[must_use = "a durable run handle waits for nothing until `result` is awaited"]
pub struct DurableRunHandle<O> {
    run_id: String,
    task_name: String,
    wait: crate::durable::stream::EntryWait,
    context: Context,
    _output: PhantomData<fn() -> O>,
}

/// As thin as [`DurableContext`]'s: the wait behind it has nothing printable,
/// and the child's output does not exist yet.
impl<O> std::fmt::Debug for DurableRunHandle<O> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DurableRunHandle")
            .field("run_id", &self.run_id)
            .field("task_name", &self.task_name)
            .finish_non_exhaustive()
    }
}

impl<O> DurableRunHandle<O> {
    /// The engine's id for the child run.
    ///
    /// Readable before the result is waited for — logging it is the point.
    #[must_use]
    pub fn run_id(&self) -> &str {
        &self.run_id
    }
}

impl<O: DeserializeOwned> DurableRunHandle<O> {
    /// Waits for the child to finish and hands back its output.
    ///
    /// Takes `self` rather than `&self` — unlike
    /// [`RunHandle::result`](crate::RunHandle::result) — because a log entry
    /// completes **once**: the wait was registered when the child was spawned,
    /// and there is nothing for a second call to wait for.
    ///
    /// There is no time limit. A child that must not be waited for for ever
    /// needs a deadline of its own, not a `tokio::time::timeout` here: cutting
    /// a durable wait short changes what the next attempt does and is answered
    /// with [`Error::Nondeterminism`](crate::Error::Nondeterminism).
    ///
    /// # Errors
    ///
    /// [`TaskError`] — the child failed (carrying the engine's message), the
    /// run was cancelled while it waited, the stream ended, or the child's
    /// output is not an `O`.
    pub async fn result(self) -> Result<O, TaskError> {
        let Self {
            run_id,
            task_name,
            wait,
            context,
            _output,
        } = self;
        // Waiting for a child is waiting, as far as an eviction policy is
        // concerned — and it is named the way both official SDKs name it
        // (`durable_child.go:216`, `context.py:1085-1086`), so the reason on
        // an eviction reads the same whichever SDK sent it.
        let _waiting = context
            .durable()
            .and_then(|durable| durable.mark_waiting("spawn_child", &task_name));
        // The same cancellation `select!` every durable wait takes, and for
        // the same reason: a cancelled run wakes out of its wait rather than
        // standing there until the worker's drain drops it.
        let payload = tokio::select! {
            () = context.cancelled() => {
                return Err(TaskError::new(format!(
                    "the run was cancelled while it waited for the child run {run_id}",
                )));
            }
            payload = wait.completed() => payload,
        }
        .map_err(task_error)?;
        child_output(&run_id, &task_name, &payload)
    }
}

/// One child run's output, as the handler's own type.
///
/// The engine completes a spawned child's log entry with the child's output
/// **verbatim** — no envelope at all, measured on both supported engines
/// (`{"from":"child","n":0}` for a child that returned exactly that) — so the
/// whole payload is the value, and nothing is unwrapped by task name.
///
/// An **empty** payload is an error of its own rather than a panic or a quiet
/// default. A child that returns nothing at all still completes its entry with
/// `null`, four bytes of JSON; no bytes means something else went wrong — on
/// v0.107.0 a failed child arrives as `is_failure` with the worker's message
/// and never reaches here, but on v0.80.0 the *same* failure arrives as a
/// success with an empty payload. Turning that into a made-up `O` — `null` is
/// a perfectly good [`Value`], after all — would hand the handler a result its
/// child never produced.
fn child_output<O: DeserializeOwned>(
    run_id: &str,
    task_name: &str,
    payload: &[u8],
) -> Result<O, TaskError> {
    if payload.is_empty() {
        return Err(TaskError::non_retryable(format!(
            "the durable child run {run_id} of `{task_name}` completed with an empty payload, so \
             there is no output to read; on engines below {min} a child that *failed* is reported \
             this way, which is why that is also the oldest engine this SDK spawns children on",
            min = crate::version::DURABLE_SPAWN_MIN_ENGINE_VERSION,
        )));
    }
    serde_json::from_slice(payload).map_err(|error| {
        TaskError::non_retryable(format!(
            "the output of the durable child run {run_id} of `{task_name}` does not match the \
             type it was asked for: {error}"
        ))
    })
}

/// The memo key [`DurableContext::now`] uses, as the official Go SDK spells
/// it. Reserved: a handler that memoises under it would fight the clock.
const NOW_KEY: &str = "__now__";

/// One recorded memo value, as the handler's own type.
fn decode<T: DeserializeOwned>(key: &str, payload: &[u8]) -> Result<T, TaskError> {
    serde_json::from_slice(payload).map_err(|error| {
        TaskError::non_retryable(format!(
            "the value recorded for the memo `{key}` does not match the type it was asked for: \
             {error}"
        ))
    })
}

/// One condition that was satisfied, and what satisfied it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DurableEvent {
    /// The condition's readable key: the event key as asked for — *before*
    /// namespacing, which is how the engine echoes it back — or
    /// `sleep:<n>ms` for a sleep, or whatever
    /// [`Condition::readable_key`](crate::Condition::readable_key) set.
    ///
    /// Empty when the engine answered in a shape this SDK does not recognise;
    /// `payload` then holds the whole answer, so nothing is lost.
    pub key: String,
    /// What the engine recorded for that match: the event's payload, exactly
    /// as it was pushed. A sleep is answered with the engine's own note
    /// (`{"sleep_duration": "6000ms"}` on both supported engines).
    pub payload: Value,
}

/// The matches in one completed durable wait.
///
/// The engine answers with `{"<Action>": {"<readable key>": [payload, …]}}` —
/// the outer key is the condition action (`CREATE`), which the SDK does not
/// need. Anything that does not have that shape is handed back whole under an
/// empty key rather than dropped: a newer engine that changes the wrapping
/// must not silently lose the handler's answer.
///
/// The matches are sorted by key, so the same answer always reaches the
/// handler in the same order.
fn matches(payload: &[u8]) -> Vec<DurableEvent> {
    let whole = |payload: Value| {
        vec![DurableEvent {
            key: String::new(),
            payload,
        }]
    };

    let Ok(value) = serde_json::from_slice::<Value>(payload) else {
        return whole(Value::String(String::from_utf8_lossy(payload).into_owned()));
    };
    let Some(inner) = unwrap_action(&value) else {
        return whole(value);
    };
    let mut keys: Vec<&String> = inner.keys().collect();
    keys.sort();
    let mut events = Vec::new();
    for key in keys {
        match &inner[key] {
            // The usual shape: one entry per thing that matched this key.
            Value::Array(payloads) if !payloads.is_empty() => {
                events.extend(payloads.iter().map(|payload| DurableEvent {
                    key: key.clone(),
                    payload: payload.clone(),
                }));
            }
            // It matched, but the engine recorded nothing for it.
            Value::Array(_) => events.push(DurableEvent {
                key: key.clone(),
                payload: Value::Object(Map::new()),
            }),
            other => events.push(DurableEvent {
                key: key.clone(),
                payload: other.clone(),
            }),
        }
    }
    events
}

/// The `{"<readable key>": …}` map inside the action envelope, or `None` when
/// the answer is not one.
///
/// The envelope's key is matched by *shape* rather than by the name `CREATE`:
/// the SDK does not need which action it was, and an engine that renamed it
/// would otherwise cost every handler its answer.
fn unwrap_action(value: &Value) -> Option<&Map<String, Value>> {
    let outer = value.as_object()?;
    if outer.len() != 1 {
        return None;
    }
    outer.values().next()?.as_object()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_diverged_run_is_never_retried() {
        let error = task_error(Error::Nondeterminism {
            task_run_id: "run-1".to_string(),
            invocation_count: 2,
            node_id: 3,
            message: "expected: sleep(10m0s)\n  received: memo".to_string(),
        });
        assert!(!error.is_retryable());
        assert!(
            error.message().contains("received: memo"),
            "{}",
            error.message()
        );
    }

    /// Retrying reaches the same engine, so the answer would be the same.
    #[test]
    fn a_call_the_engine_is_too_old_for_is_never_retried() {
        let error = task_error(Error::UnsupportedFeature {
            feature: SPAWN_FEATURE.to_string(),
            found: "v0.80.0".to_string(),
            minimum: crate::version::DURABLE_SPAWN_MIN_ENGINE_VERSION.to_string(),
        });
        assert!(!error.is_retryable());
        assert!(error.message().contains("v0.80.0"), "{}", error.message());
        assert!(
            error
                .message()
                .contains(crate::version::DURABLE_SPAWN_MIN_ENGINE_VERSION),
            "{}",
            error.message()
        );
    }

    /// The engine completes a spawned child's entry with the child's output
    /// verbatim: no envelope, nothing keyed by task name (Task 0 probe B).
    #[test]
    fn a_childs_output_is_read_whole_out_of_its_payload() {
        let output: Value =
            child_output("child-a", "child", br#"{"from":"child","n":0}"#).expect("the output");
        assert_eq!(output, serde_json::json!({"from": "child", "n": 0}));
        // …and into the handler's own type, not just `Value`.
        #[derive(serde::Deserialize, Debug, PartialEq)]
        struct Out {
            n: i32,
        }
        assert_eq!(
            child_output::<Out>("child-a", "child", br#"{"n":7}"#).expect("the output"),
            Out { n: 7 }
        );
    }

    /// An output that is not an `O` is the handler's mistake, not the engine's:
    /// retrying would decode the same bytes again.
    #[test]
    fn an_output_of_the_wrong_shape_is_an_error_that_is_not_retried() {
        let error = child_output::<i32>("child-a", "child", br#"{"n":7}"#)
            .expect_err("an object is not an i32");
        assert!(!error.is_retryable());
        assert!(error.message().contains("child-a"), "{}", error.message());
    }

    /// On v0.80.0 a *failed* child arrives as a success with an empty payload.
    /// Inventing an `O` for it — `null` is a perfectly good [`Value`] — would
    /// hand the handler a result its child never produced, so it is an error
    /// for every output type, `()` included.
    #[test]
    fn an_empty_payload_is_an_error_rather_than_a_panic_or_a_made_up_value() {
        for error in [
            child_output::<Value>("child-a", "child", b"").expect_err("nothing to read"),
            child_output::<()>("child-a", "child", b"").expect_err("nothing to read"),
        ] {
            assert!(
                error.message().contains("empty payload"),
                "{}",
                error.message()
            );
            assert!(!error.is_retryable(), "{}", error.message());
        }
        // A child that really returned nothing completes with `null`, which is
        // four bytes rather than none — and reads back as the unit type.
        child_output::<()>("child-a", "child", b"null").expect("a handler that wanted no output");
    }

    #[test]
    fn every_other_durable_failure_may_be_retried() {
        let error = task_error(Error::Grpc(Box::new(tonic::Status::unavailable(
            "engine restarting",
        ))));
        assert!(error.is_retryable());
    }

    fn event(key: &str, payload: Value) -> DurableEvent {
        DurableEvent {
            key: key.to_string(),
            payload,
        }
    }

    #[test]
    fn a_completion_is_unwrapped_out_of_its_action_envelope() {
        // The shape both supported engines were measured sending for a sleep.
        assert_eq!(
            matches(br#"{"CREATE":{"sleep:6000ms":[{"sleep_duration":"6000ms"}]}}"#),
            [event(
                "sleep:6000ms",
                serde_json::json!({"sleep_duration": "6000ms"})
            )]
        );
        // …and for an event, whose body comes back verbatim.
        assert_eq!(
            matches(br#"{"CREATE":{"approve":[{"by":"ops","amount":42}]}}"#),
            [event(
                "approve",
                serde_json::json!({"by": "ops", "amount": 42})
            )]
        );
    }

    #[test]
    fn several_matches_come_back_in_key_order() {
        let matched = matches(br#"{"CREATE":{"go":[{"n":1}],"sleep:5000ms":[{}],"halt":[{}]}}"#);
        let keys: Vec<&str> = matched.iter().map(|event| event.key.as_str()).collect();
        assert_eq!(keys, ["go", "halt", "sleep:5000ms"]);
    }

    #[test]
    fn a_key_with_several_payloads_keeps_every_one_of_them() {
        assert_eq!(
            matches(br#"{"CREATE":{"go":[{"n":1},{"n":2}]}}"#),
            [
                event("go", serde_json::json!({"n": 1})),
                event("go", serde_json::json!({"n": 2})),
            ]
        );
    }

    #[test]
    fn an_empty_envelope_matches_nothing() {
        assert!(matches(br#"{"CREATE":{}}"#).is_empty());
        // A key the engine recorded nothing for still counts as a match.
        assert_eq!(
            matches(br#"{"CREATE":{"go":[]}}"#),
            [event("go", serde_json::json!({}))]
        );
    }

    #[test]
    fn an_answer_in_an_unknown_shape_is_handed_back_whole_rather_than_dropped() {
        // Two envelopes, a bare array, a scalar: none of them is the shape
        // this SDK knows, and none of them may cost the handler its answer.
        for raw in [
            br#"{"CREATE":{"go":[{}]},"QUEUE":{"x":[{}]}}"#.as_slice(),
            br#"["go"]"#.as_slice(),
            br#"42"#.as_slice(),
            br#"{"go":["ok"]}"#.as_slice(),
        ] {
            let matched = matches(raw);
            assert_eq!(matched.len(), 1, "{}", String::from_utf8_lossy(raw));
            assert_eq!(matched[0].key, "");
            assert_eq!(
                matched[0].payload,
                serde_json::from_slice::<Value>(raw).unwrap()
            );
        }
    }

    #[test]
    fn bytes_that_are_not_json_are_handed_back_as_text() {
        let matched = matches(b"not json at all");
        assert_eq!(
            matched,
            [event("", Value::String("not json at all".into()))]
        );
    }
}