hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
//! Conditions: when a task may start, when it is skipped, and when it is
//! cancelled.
//!
//! All three gates travel in one wire field — `CreateTaskOpts.conditions`,
//! a [`TaskConditions`](hatchet_proto::v1::TaskConditions) split by *kind*
//! (sleep, user event, parent) rather than by gate. What separates them is
//! `BaseMatchCondition.action`: `QUEUE` for `wait_for`, `SKIP` for `skip_if`,
//! `CANCEL` for `cancel_if`.

use std::collections::HashSet;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use hatchet_proto::v1;
use rand::Rng;

use super::task::Task;
use crate::config::namespace;

/// Which gate a condition belongs to, as the engine's `Action` enum.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ConditionAction {
    Queue,
    Skip,
    Cancel,
}

impl ConditionAction {
    fn to_proto(self) -> i32 {
        let action = match self {
            Self::Queue => v1::Action::Queue,
            Self::Skip => v1::Action::Skip,
            Self::Cancel => v1::Action::Cancel,
        };
        action as i32
    }

    /// The builder method this gate is set with, for error messages.
    fn gate(self) -> &'static str {
        match self {
            Self::Queue => "wait_for",
            Self::Skip => "skip_if",
            Self::Cancel => "cancel_if",
        }
    }
}

/// What a condition waits on.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Kind {
    Sleep(Duration),
    Event(String),
    Parent(String),
}

/// One thing a task can wait on, be skipped by, or be cancelled by.
///
/// Build one with [`sleep`](Condition::sleep),
/// [`on_event`](Condition::on_event) or [`parent`](Condition::parent), then
/// give it to [`TaskBuilder::wait_for`](crate::TaskBuilder::wait_for),
/// [`skip_if`](crate::TaskBuilder::skip_if) or
/// [`cancel_if`](crate::TaskBuilder::cancel_if). Several conditions on one
/// gate must *all* be satisfied; wrap them in [`any_of`] for "any one of
/// these".
///
/// A sleep or event condition is a gate on *queueing*, so a task whose only
/// conditions are a `skip_if` or `cancel_if` of that kind would never start
/// at all; one is always paired with a `wait_for` that is itself a sleep or
/// an event. A `wait_for` made only of parent conditions does not release it
/// — that was measured, and is why the declaration is rejected.
///
/// Mistakes — an option that does not fit the kind, two conditions on one
/// task sharing a readable key, a `skip_if` that could never be reached —
/// are reported as
/// [`Error::InvalidDeclaration`](crate::Error::InvalidDeclaration) when the
/// task is registered, never as a panic.
///
/// ```
/// use std::time::Duration;
///
/// use hatchet_client::{Condition, TaskBuilder, any_of};
///
/// let review = TaskBuilder::<(), ()>::new("review")
///     // Start when the reviewer approves, or after an hour, whichever
///     // comes first.
///     .wait_for(any_of([
///         Condition::on_event("review.approved"),
///         Condition::sleep(Duration::from_secs(3600)),
///     ]))
///     // Never run at all if the change was withdrawn first.
///     .skip_if(Condition::on_event("review.withdrawn"))
///     .handler(|_ctx, _input| async { Ok(()) });
/// # let _ = review;
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use = "a condition gates nothing until it is given to wait_for, skip_if or cancel_if"]
pub struct Condition {
    kind: Kind,
    expression: Option<String>,
    readable_key: Option<String>,
    scope: Option<String>,
    since: Option<SystemTime>,
}

impl Condition {
    fn of(kind: Kind) -> Self {
        Self {
            kind,
            expression: None,
            readable_key: None,
            scope: None,
            since: None,
        }
    }

    /// Satisfied once `duration` has passed since the task became eligible.
    ///
    /// For a task with no parents that is the moment the run was *triggered*,
    /// not the moment the engine got round to it: a six-second sleep was
    /// measured firing about six seconds after the trigger even though an
    /// unconditioned sibling in the same run did not start until four
    /// seconds in.
    ///
    /// The engine takes the duration as a string; this SDK sends whole
    /// milliseconds, as the official Go SDK does, so a duration under one
    /// millisecond is rejected rather than rounded away. Short sleeps are not
    /// dependable: against both v0.80.0 and v0.107.0 a one-second sleep
    /// condition was observed never to fire, while a five-second one fired
    /// as expected. Prefer a few seconds or more.
    pub fn sleep(duration: Duration) -> Self {
        Self::of(Kind::Sleep(duration))
    }

    /// Satisfied by an event pushed under `key`.
    ///
    /// The key is namespaced exactly as
    /// [`EventsClient::push`](crate::EventsClient::push) namespaces it, so
    /// `Condition::on_event("go")` is satisfied by `push("go", …)` from a
    /// client with the same namespace. (The official Go SDK does not
    /// namespace condition keys; the official Python SDK does, and so does
    /// this one — otherwise a namespaced client could never satisfy its own
    /// condition.) A key that already starts with the namespace is left
    /// alone, so another namespace's events can be waited on by full key.
    ///
    /// A condition still waiting is weighed against every later push of the
    /// same key, not only the first: an [`expression`](Condition::expression)
    /// that a push failed to satisfy leaves the condition pending, and a
    /// subsequent push that does satisfy it releases the task (measured on
    /// both supported engines).
    pub fn on_event(key: impl Into<String>) -> Self {
        Self::of(Kind::Event(key.into()))
    }

    /// Satisfied by what `parent` produced, judged by
    /// [`expression`](Condition::expression) over `output`.
    ///
    /// `parent` must be a parent of the task this condition is put on.
    pub fn parent<I, O>(parent: &Task<I, O>) -> Self {
        Self::parent_by_name(parent.name())
    }

    /// Like [`Condition::parent`], but naming the parent rather than
    /// borrowing its handle — for a parent declared elsewhere.
    pub fn parent_by_name(name: impl Into<String>) -> Self {
        Self::of(Kind::Parent(name.into()))
    }

    /// The CEL expression that decides whether the condition is satisfied.
    ///
    /// A parent condition reads the parent's output as `output`
    /// (`output.count > 0`); an event condition reads the event's payload as
    /// `input` (`input.ok == true`). A sleep condition takes no expression.
    ///
    /// The engine does not check the expression when the workflow is
    /// registered: a malformed or never-true expression shows up as a task
    /// that never starts, not as an error.
    pub fn expression(mut self, expression: impl Into<String>) -> Self {
        self.expression = Some(expression.into());
        self
    }

    /// Overrides the key this condition is known by — the key the engine
    /// tells one task's conditions apart by, and which must therefore be
    /// unique among them.
    ///
    /// The default is `sleep:<duration>` for a sleep, the event key (before
    /// namespacing) for an event, and the parent's name for a parent
    /// condition — plus `:<expression>` when a parent condition has one, so
    /// that two conditions reading the same parent through different
    /// expressions do not collide. (The official Python SDK folds the
    /// expression *and* the current time into that key; the time is left out
    /// here so that the same declaration always maps to the same request.)
    pub fn readable_key(mut self, key: impl Into<String>) -> Self {
        self.readable_key = Some(key.into());
        self
    }

    /// Only matches events pushed with this scope
    /// ([`PushOpts::scope`](crate::PushOpts::scope)). Event conditions only.
    pub fn scope(mut self, scope: impl Into<String>) -> Self {
        self.scope = Some(scope.into());
        self
    }

    /// Also matches events pushed after `at` but before the task started
    /// waiting. Event conditions only, and only together with
    /// [`scope`](Condition::scope) — the official Go SDK documents the
    /// engine as requiring both.
    pub fn since(mut self, at: SystemTime) -> Self {
        self.since = Some(at);
        self
    }

    /// The key this condition is known by: the override, or the default for
    /// its kind.
    fn readable_data_key(&self) -> String {
        if let Some(key) = &self.readable_key {
            return key.clone();
        }
        match &self.kind {
            Kind::Sleep(duration) => format!("sleep:{}", duration_expr(*duration)),
            Kind::Event(key) => key.clone(),
            Kind::Parent(name) => match &self.expression {
                Some(expression) => format!("{name}:{expression}"),
                None => name.clone(),
            },
        }
    }

    /// The parent this condition reads, if it is a parent condition.
    pub(crate) fn parent_name(&self) -> Option<&str> {
        match &self.kind {
            Kind::Parent(name) => Some(name.as_str()),
            _ => None,
        }
    }

    /// Whether the engine only ever evaluates this condition while the task
    /// is waiting to be queued. A parent condition is evaluated as soon as
    /// the parent finishes; a sleep or an event is not, so on a `skip_if` or
    /// a `cancel_if` it leaves the task waiting for a `wait_for` that must
    /// be there too.
    fn only_gates_queueing(&self) -> bool {
        matches!(self.kind, Kind::Sleep(_) | Kind::Event(_))
    }

    /// The name of the first string this condition carries that is blank —
    /// empty or nothing but whitespace — if any.
    fn blank_field(&self) -> Option<&'static str> {
        let blank = |value: &str| value.trim().is_empty();
        match &self.kind {
            Kind::Event(key) if blank(key) => return Some("event key"),
            Kind::Parent(name) if blank(name) => return Some("parent name"),
            _ => {}
        }
        if self.readable_key.as_deref().is_some_and(blank) {
            return Some("readable key");
        }
        if self.expression.as_deref().is_some_and(blank) {
            return Some("expression");
        }
        if self.scope.as_deref().is_some_and(blank) {
            return Some("event scope");
        }
        None
    }

    /// Why this condition cannot be sent, if any.
    fn invalid_reason(&self) -> Option<String> {
        let key = self.readable_data_key();
        // Every string a condition carries names something the engine has to
        // match on, so a blank one can only ever be a mistake — and one that
        // shows up as a task that silently never starts rather than as an
        // error, since the engine checks none of them.
        if let Some(blank) = self.blank_field() {
            return Some(if blank == "expression" {
                "a condition was given a blank expression; leave `expression` off \
                 to match unconditionally"
                    .to_string()
            } else {
                format!(
                    "a condition was given a blank {blank}; the engine matches on it \
                     verbatim, so a blank one leaves the task waiting for ever"
                )
            });
        }
        match &self.kind {
            Kind::Event(_) => {
                if self.since.is_some() && self.scope.is_none() {
                    return Some(format!(
                        "the event condition `{key}` sets `since` without `scope`; the \
                         engine considers earlier events only within a scope"
                    ));
                }
                // `scope` and `since` belong to an event condition, so the
                // checks below do not apply to one.
                return None;
            }
            Kind::Sleep(duration) => {
                if self.expression.is_some() {
                    return Some(format!(
                        "the sleep condition `{key}` sets an expression, which only a \
                         parent or event condition can use"
                    ));
                }
                // Whole milliseconds are what goes on the wire, so anything
                // under one of them *is* a zero-duration sleep to the engine.
                if duration.as_millis() == 0 {
                    return Some(format!(
                        "the sleep condition `{key}` rounds to zero milliseconds, which \
                         is what the engine is sent; a sleep condition must wait for \
                         some time"
                    ));
                }
            }
            Kind::Parent(_) => {}
        }
        if self.scope.is_some() {
            return Some(format!(
                "the condition `{key}` sets a scope, which only an event condition has"
            ));
        }
        if self.since.is_some() {
            return Some(format!(
                "the condition `{key}` sets `since`, which only an event condition has"
            ));
        }
        None
    }
}

/// A group of conditions of which *any one* satisfies the gate. Made by
/// [`any_of`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use = "an or-group gates nothing until it is given to wait_for, skip_if or cancel_if"]
pub struct OrGroup(Vec<Condition>);

/// Satisfied as soon as *any* of `conditions` is.
///
/// Conditions given separately must all be satisfied (the engine ANDs them);
/// the ones in one `any_of` are ORed together, because they share an or-group
/// id on the wire.
///
/// ```
/// use std::time::Duration;
///
/// use hatchet_client::{Condition, TaskBuilder, any_of};
///
/// let ship = TaskBuilder::<(), ()>::new("ship")
///     .wait_for(any_of([
///         Condition::on_event("qa.signed-off"),
///         Condition::sleep(Duration::from_secs(24 * 3600)),
///     ]))
///     .handler(|_ctx, _input| async { Ok(()) });
/// # let _ = ship;
/// ```
pub fn any_of(conditions: impl IntoIterator<Item = Condition>) -> OrGroup {
    OrGroup(conditions.into_iter().collect())
}

/// What one gate waits on: or-groups that must *all* be satisfied.
///
/// Never built literally — a [`Condition`], an [`OrGroup`], or a collection
/// of either converts into one, and [`ConditionSet::and`] adds to it.
///
/// ```
/// use std::time::Duration;
///
/// use hatchet_client::{Condition, ConditionSet, TaskBuilder, any_of};
///
/// // "after the sleep, and once either event has arrived"
/// let gate = ConditionSet::from(Condition::sleep(Duration::from_secs(30))).and(any_of([
///     Condition::on_event("ready"),
///     Condition::on_event("forced"),
/// ]));
/// let publish = TaskBuilder::<(), ()>::new("publish")
///     .wait_for(gate)
///     .handler(|_ctx, _input| async { Ok(()) });
/// # let _ = publish;
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[must_use = "a condition set gates nothing until it is given to wait_for, skip_if or cancel_if"]
pub struct ConditionSet {
    /// Each inner vector is one or-group; a lone condition is a group of
    /// one. Groups AND together, members of a group OR together.
    groups: Vec<Vec<Condition>>,
}

impl ConditionSet {
    /// Adds another condition or group that must *also* be satisfied.
    pub fn and(mut self, more: impl Into<ConditionSet>) -> Self {
        self.groups.extend(more.into().groups);
        self
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.groups.is_empty()
    }

    pub(crate) fn extend(&mut self, more: ConditionSet) {
        self.groups.extend(more.groups);
    }

    /// The parents every parent condition in this set reads.
    pub(crate) fn parent_names(&self) -> impl Iterator<Item = &str> {
        self.conditions().filter_map(Condition::parent_name)
    }

    fn conditions(&self) -> impl Iterator<Item = &Condition> {
        self.groups.iter().flatten()
    }

    /// What a durable wait on this set is waiting on, as a kind and one
    /// resource — `("user_event", "approve")`, `("sleep", "sleep:5000ms")`.
    ///
    /// It goes into the reason an eviction carries, which is what a dashboard
    /// and the engine's log show, so the official SDKs' words are used:
    /// `sleep`, `user_event`, `parent`, and `wait_for` for a set that mixes
    /// them (`sdks/go/pkg/worker/context.go:1203`). The resource is the first
    /// readable key in sorted order — a stable choice rather than an arbitrary
    /// one, since a set has no order the handler chose.
    pub(crate) fn wait_kind(&self) -> (&'static str, String) {
        let mut kind: Option<&'static str> = None;
        let mut keys: Vec<String> = Vec::new();
        for condition in self.conditions() {
            let this = match condition.kind {
                Kind::Sleep(_) => "sleep",
                Kind::Event(_) => "user_event",
                Kind::Parent(_) => "parent",
            };
            kind = Some(match kind {
                Some(seen) if seen != this => "wait_for",
                Some(seen) => seen,
                None => this,
            });
            keys.push(condition.readable_data_key());
        }
        keys.sort();
        (
            kind.unwrap_or("wait_for"),
            keys.into_iter().next().unwrap_or_default(),
        )
    }
}

impl From<Condition> for ConditionSet {
    fn from(condition: Condition) -> Self {
        Self {
            groups: vec![vec![condition]],
        }
    }
}

impl From<OrGroup> for ConditionSet {
    fn from(group: OrGroup) -> Self {
        Self {
            groups: vec![group.0],
        }
    }
}

impl From<Vec<Condition>> for ConditionSet {
    fn from(conditions: Vec<Condition>) -> Self {
        Self {
            groups: conditions
                .into_iter()
                .map(|condition| vec![condition])
                .collect(),
        }
    }
}

impl<const N: usize> From<[Condition; N]> for ConditionSet {
    fn from(conditions: [Condition; N]) -> Self {
        Vec::from(conditions).into()
    }
}

impl From<Vec<OrGroup>> for ConditionSet {
    fn from(groups: Vec<OrGroup>) -> Self {
        Self {
            groups: groups.into_iter().map(|group| group.0).collect(),
        }
    }
}

impl<const N: usize> From<[OrGroup; N]> for ConditionSet {
    fn from(groups: [OrGroup; N]) -> Self {
        Vec::from(groups).into()
    }
}

/// The gates of one task: `wait_for`, `skip_if`, `cancel_if`, in that order.
pub(crate) type Gates<'a> = [(ConditionAction, &'a ConditionSet); 3];

/// Why this task's conditions cannot be sent, if any. The caller adds the
/// task and workflow names.
pub(crate) fn validate(gates: Gates<'_>) -> Result<(), String> {
    let mut keys: HashSet<String> = HashSet::new();
    for (_, set) in gates {
        for group in &set.groups {
            if group.is_empty() {
                return Err(
                    "an or-group has no conditions; `any_of` needs at least one".to_string()
                );
            }
        }
        for condition in set.conditions() {
            if let Some(reason) = condition.invalid_reason() {
                return Err(reason);
            }
            if let Some(at) = condition.since
                && at.duration_since(UNIX_EPOCH).is_err()
            {
                return Err(format!(
                    "the condition `{}` sets `since` to a time before 1970",
                    condition.readable_data_key()
                ));
            }
            let key = condition.readable_data_key();
            if !keys.insert(key.clone()) {
                return Err(format!(
                    "two conditions on this task share the readable key `{key}`; the \
                     engine tells them apart by that key, so give one of them its own \
                     with `Condition::readable_key(..)`"
                ));
            }
        }
    }

    // A sleep or an event on `skip_if`/`cancel_if` gates queueing: with
    // nothing of that kind on `wait_for` to queue on, the task never starts
    // and the run never finishes (observed on both v0.80.0 and v0.107.0).
    // Neither parents nor a `wait_for` made only of parent conditions
    // release it — measured, see
    // `hatchet-integration-tests`' `conditions::a_parent_condition_wait_for_
    // does_not_release_an_event_skip_if`.
    let waits = gates.iter().any(|(action, set)| {
        *action == ConditionAction::Queue && set.conditions().any(Condition::only_gates_queueing)
    });
    if !waits {
        for (action, set) in gates {
            if action == ConditionAction::Queue {
                continue;
            }
            if let Some(condition) = set.conditions().find(|c| c.only_gates_queueing()) {
                return Err(format!(
                    "the `{}` condition `{}` waits on a sleep or an event, but the task \
                     has no `wait_for` that does; the engine only weighs such a \
                     condition while the task waits to be queued, so the task would \
                     never start — add a `wait_for` on a sleep or an event (parents, \
                     and a `wait_for` made only of parent conditions, do not count; a \
                     `skip_if` or `cancel_if` on a parent condition needs no pairing at \
                     all)",
                    action.gate(),
                    condition.readable_data_key()
                ));
            }
        }
    }

    Ok(())
}

/// Folds the three gates into the one wire field, or `None` when there is
/// nothing to send. Call [`validate`] first.
pub(crate) fn to_proto(namespace: &str, gates: Gates<'_>) -> Option<v1::TaskConditions> {
    let mut conditions = v1::TaskConditions::default();
    let mut any = false;
    for (action, set) in gates {
        for group in &set.groups {
            let or_group_id = or_group_id();
            for condition in group {
                any = true;
                let base = v1::BaseMatchCondition {
                    readable_data_key: condition.readable_data_key(),
                    action: action.to_proto(),
                    or_group_id: or_group_id.clone(),
                    expression: condition.expression.clone().unwrap_or_default(),
                };
                match &condition.kind {
                    Kind::Sleep(duration) => {
                        conditions.sleep_conditions.push(v1::SleepMatchCondition {
                            base: Some(base),
                            sleep_for: duration_expr(*duration),
                        });
                    }
                    Kind::Event(key) => {
                        conditions
                            .user_event_conditions
                            .push(v1::UserEventMatchCondition {
                                base: Some(base),
                                user_event_key: namespace::apply(namespace, key),
                                event_scope: condition.scope.clone(),
                                consider_events_since: condition.since.map(timestamp),
                            });
                    }
                    Kind::Parent(name) => {
                        conditions.parent_override_conditions.push(
                            v1::ParentOverrideMatchCondition {
                                base: Some(base),
                                parent_readable_id: name.clone(),
                            },
                        );
                    }
                }
            }
        }
    }
    any.then_some(conditions)
}

/// The conditions of one durable wait.
///
/// Three things differ from [`to_proto`], which maps a *task's* gates:
///
/// * every condition is a `CREATE` condition — a durable wait is not a gate on
///   queueing, it is a point the handler is standing on
///   (`pkg/worker/context.go:1186`);
/// * a parent condition cannot be expressed
///   (`DurableEventListenerConditions` has no parent field —
///   `api-contracts/v1/shared/condition.proto:46-49`), so it is rejected with
///   an explanation rather than dropped;
/// * the pairing rule [`validate`] enforces for task conditions (a sleep or an
///   event on `skip_if`/`cancel_if` needs one on `wait_for`) does not apply:
///   there is only one gate here.
///
/// The readable key still has to be unique, and for a stronger reason than on
/// a task: the engine indexes the wait's result by it
/// (`{"CREATE": {"<readable key>": [payload, …]}}`, measured on both supported
/// engines), so two conditions sharing a key would lose one of the matches.
///
/// The event key is namespaced exactly as
/// [`EventsClient::push`](crate::EventsClient::push) namespaces it; the
/// *readable* key is not, because that is the key the engine echoes back and
/// the handler should recognise the one it asked for.
pub(crate) fn to_durable_proto(
    namespace: &str,
    conditions: &ConditionSet,
) -> Result<v1::DurableEventListenerConditions, String> {
    if conditions.is_empty() {
        return Err("a durable wait needs at least one condition".to_string());
    }

    let mut keys: HashSet<String> = HashSet::new();
    let mut mapped = v1::DurableEventListenerConditions::default();
    for group in &conditions.groups {
        if group.is_empty() {
            return Err("an or-group has no conditions; `any_of` needs at least one".to_string());
        }
        let or_group_id = or_group_id();
        for condition in group {
            if let Some(reason) = condition.invalid_reason() {
                return Err(reason);
            }
            if let Some(at) = condition.since
                && at.duration_since(UNIX_EPOCH).is_err()
            {
                return Err(format!(
                    "the condition `{}` sets `since` to a time before 1970",
                    condition.readable_data_key()
                ));
            }
            let key = condition.readable_data_key();
            if !keys.insert(key.clone()) {
                return Err(format!(
                    "two conditions of one durable wait share the readable_key `{key}`; the \
                     engine indexes the wait's result by that key, so one of the matches \
                     would be lost — give one of them its own with \
                     `Condition::readable_key(..)`"
                ));
            }
            let base = v1::BaseMatchCondition {
                readable_data_key: key,
                action: v1::Action::Create as i32,
                or_group_id: or_group_id.clone(),
                expression: condition.expression.clone().unwrap_or_default(),
            };
            match &condition.kind {
                Kind::Sleep(duration) => mapped.sleep_conditions.push(v1::SleepMatchCondition {
                    base: Some(base),
                    sleep_for: duration_expr(*duration),
                }),
                Kind::Event(event) => {
                    mapped
                        .user_event_conditions
                        .push(v1::UserEventMatchCondition {
                            base: Some(base),
                            user_event_key: namespace::apply(namespace, event),
                            event_scope: condition.scope.clone(),
                            consider_events_since: condition.since.map(timestamp),
                        });
                }
                Kind::Parent(name) => {
                    return Err(format!(
                        "the durable wait names the parent task `{name}`, but a durable wait \
                         cannot read a parent: the engine takes only sleep and event \
                         conditions here. Read the parent's output with \
                         `Context::parent_output` instead, or gate the task itself with \
                         `TaskBuilder::wait_for`"
                    ));
                }
            }
        }
    }
    Ok(mapped)
}

/// How the engine takes a sleep duration: whole milliseconds, which is what
/// the official Go SDK sends. The official Python SDK sends
/// `"<n>h"`/`"<n>m"`/`"<n>s"` instead, which cannot express a sub-second
/// wait; the engine accepts either.
fn duration_expr(duration: Duration) -> String {
    format!("{}ms", duration.as_millis())
}

/// A `SystemTime` at or after the epoch, as the engine's timestamp.
///
/// A time before 1970 is rejected by [`validate`], so the `unwrap_or` below
/// is belt and braces; the nanosecond conversion cannot fail at all, since
/// `subsec_nanos` is under a billion.
fn timestamp(at: SystemTime) -> hatchet_proto::prost_types::Timestamp {
    let since_epoch = at.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO);
    hatchet_proto::prost_types::Timestamp {
        seconds: i64::try_from(since_epoch.as_secs()).unwrap_or(i64::MAX),
        nanos: i32::try_from(since_epoch.subsec_nanos()).unwrap_or(0),
    }
}

/// A random UUID v4 in the canonical 36-character form.
///
/// The engine documents `or_group_id` as a UUID
/// (`api-contracts/v1/shared/condition.proto:19`) and rejects anything else
/// that is not empty. This is the only place the SDK needs a UUID, so it is
/// made from `rand` — already a dependency — rather than by adding a crate.
fn or_group_id() -> String {
    let mut bytes = rand::rng().random::<u128>().to_be_bytes();
    bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
    bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant RFC 4122
    let hex = |part: &[u8]| -> String { part.iter().map(|byte| format!("{byte:02x}")).collect() };
    format!(
        "{}-{}-{}-{}-{}",
        hex(&bytes[0..4]),
        hex(&bytes[4..6]),
        hex(&bytes[6..8]),
        hex(&bytes[8..10]),
        hex(&bytes[10..16])
    )
}

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

    fn gates<'a>(
        wait_for: &'a ConditionSet,
        skip_if: &'a ConditionSet,
        cancel_if: &'a ConditionSet,
    ) -> Gates<'a> {
        [
            (ConditionAction::Queue, wait_for),
            (ConditionAction::Skip, skip_if),
            (ConditionAction::Cancel, cancel_if),
        ]
    }

    fn only(set: ConditionSet) -> v1::TaskConditions {
        let empty = ConditionSet::default();
        to_proto("dev_", gates(&set, &empty, &empty)).expect("the set is not empty")
    }

    #[test]
    fn durable_conditions_are_create_conditions_without_parents() {
        let set = ConditionSet::from(Condition::sleep(Duration::from_secs(30)))
            .and(Condition::on_event("go"));
        let conditions = to_durable_proto("dev_", &set).expect("a valid durable wait");

        let sleep = &conditions.sleep_conditions[0];
        assert_eq!(sleep.sleep_for, "30000ms");
        let base = sleep.base.as_ref().expect("a base condition");
        assert_eq!(base.readable_data_key, "sleep:30000ms");
        assert_eq!(base.action, v1::Action::Create as i32);

        let event = &conditions.user_event_conditions[0];
        assert_eq!(event.user_event_key, "dev_go");
        // The readable key is *not* namespaced — it is what comes back in the
        // result map, and the handler should recognise the key it asked for.
        let base = event.base.as_ref().expect("a base condition");
        assert_eq!(base.readable_data_key, "go");
        assert_eq!(base.action, v1::Action::Create as i32);
    }

    #[test]
    fn a_durable_or_group_shares_one_group_id() {
        let set = ConditionSet::from(any_of([
            Condition::on_event("go"),
            Condition::sleep(Duration::from_secs(5)),
        ]));
        let conditions = to_durable_proto("dev_", &set).expect("a valid durable wait");
        let event = conditions.user_event_conditions[0]
            .base
            .as_ref()
            .expect("a base condition");
        let sleep = conditions.sleep_conditions[0]
            .base
            .as_ref()
            .expect("a base condition");
        assert_eq!(event.or_group_id, sleep.or_group_id);
        assert!(!event.or_group_id.is_empty());
    }

    #[test]
    fn a_parent_condition_cannot_be_waited_for_durably() {
        let reason = to_durable_proto(
            "dev_",
            &ConditionSet::from(Condition::parent_by_name("fetch")),
        )
        .expect_err("parents are not durable conditions");
        assert!(reason.contains("parent"), "{reason}");
    }

    #[test]
    fn a_durable_wait_needs_at_least_one_condition_and_unique_keys() {
        assert!(to_durable_proto("dev_", &ConditionSet::default()).is_err());
        let twice = ConditionSet::from(Condition::sleep(Duration::from_secs(5)))
            .and(Condition::sleep(Duration::from_secs(5)));
        let reason = to_durable_proto("dev_", &twice).expect_err("duplicate readable keys");
        assert!(reason.contains("readable_key"), "{reason}");

        // …and the same two are fine once one of them is renamed.
        let renamed = ConditionSet::from(Condition::sleep(Duration::from_secs(5)))
            .and(Condition::sleep(Duration::from_secs(5)).readable_key("second"));
        assert!(to_durable_proto("dev_", &renamed).is_ok());
    }

    #[test]
    fn a_durable_wait_rejects_what_an_invalid_condition_would_hide() {
        let blank = to_durable_proto("dev_", &ConditionSet::from(Condition::on_event(" ")))
            .expect_err("a blank event key is a mistake");
        assert!(blank.contains("blank"), "{blank}");
    }

    #[test]
    fn a_sleep_condition_maps_to_a_sleep_match_condition() {
        let conditions = only(Condition::sleep(Duration::from_secs(30)).into());
        assert!(conditions.user_event_conditions.is_empty());
        assert!(conditions.parent_override_conditions.is_empty());
        let [sleep] = conditions.sleep_conditions.as_slice() else {
            panic!("exactly one sleep condition: {conditions:?}");
        };
        assert_eq!(sleep.sleep_for, "30000ms");
        let base = sleep.base.as_ref().expect("a base condition");
        assert_eq!(base.action, v1::Action::Queue as i32);
        assert_eq!(base.readable_data_key, "sleep:30000ms");
        assert_eq!(base.expression, "");
        assert!(
            !base.or_group_id.is_empty(),
            "every condition gets a group id"
        );
    }

    #[test]
    fn a_sub_second_sleep_keeps_its_milliseconds() {
        let conditions = only(Condition::sleep(Duration::from_millis(1500)).into());
        assert_eq!(conditions.sleep_conditions[0].sleep_for, "1500ms");
    }

    #[test]
    fn an_event_condition_is_namespaced_but_its_readable_key_is_not() {
        let conditions = only(
            Condition::on_event("approval.granted")
                .expression("input.ok == true")
                .scope("tenant-1")
                .into(),
        );
        let [event] = conditions.user_event_conditions.as_slice() else {
            panic!("exactly one user event condition: {conditions:?}");
        };
        assert_eq!(event.user_event_key, "dev_approval.granted");
        assert_eq!(event.event_scope.as_deref(), Some("tenant-1"));
        assert_eq!(event.consider_events_since, None);
        let base = event.base.as_ref().expect("a base condition");
        assert_eq!(base.readable_data_key, "approval.granted");
        assert_eq!(base.expression, "input.ok == true");
    }

    #[test]
    fn an_event_key_that_already_carries_the_namespace_is_not_prefixed_twice() {
        let conditions = only(Condition::on_event("dev_go").into());
        let [event] = conditions.user_event_conditions.as_slice() else {
            panic!("one condition: {conditions:?}");
        };
        assert_eq!(event.user_event_key, "dev_go");
    }

    #[test]
    fn an_events_since_is_sent_as_a_timestamp() {
        let at = UNIX_EPOCH + Duration::new(1_700_000_000, 250);
        let conditions = only(Condition::on_event("go").scope("s").since(at).into());
        assert_eq!(
            conditions.user_event_conditions[0].consider_events_since,
            Some(hatchet_proto::prost_types::Timestamp {
                seconds: 1_700_000_000,
                nanos: 250,
            })
        );
    }

    #[test]
    fn a_parent_condition_names_the_parent_and_folds_its_expression_into_its_key() {
        let fetch = TaskBuilder::<(), u32>::new("fetch").handler(|_ctx, _input| async { Ok(1) });
        let conditions = only(
            Condition::parent(&fetch)
                .expression("output.count > 0")
                .into(),
        );
        let [parent] = conditions.parent_override_conditions.as_slice() else {
            panic!("exactly one parent condition: {conditions:?}");
        };
        assert_eq!(parent.parent_readable_id, "fetch");
        let base = parent.base.as_ref().expect("a base condition");
        assert_eq!(base.readable_data_key, "fetch:output.count > 0");
        assert_eq!(base.expression, "output.count > 0");
    }

    #[test]
    fn an_explicit_readable_key_wins_over_the_default() {
        let conditions = only(
            Condition::sleep(Duration::from_secs(1))
                .readable_key("first-wait")
                .into(),
        );
        let base = conditions.sleep_conditions[0]
            .base
            .as_ref()
            .expect("a base condition");
        assert_eq!(base.readable_data_key, "first-wait");
    }

    #[test]
    fn the_three_gates_map_to_their_own_actions_in_one_task_conditions() {
        let wait_for: ConditionSet = Condition::sleep(Duration::from_secs(5)).into();
        let skip_if: ConditionSet = Condition::on_event("skip").into();
        let cancel_if: ConditionSet = Condition::on_event("stop").into();
        let conditions =
            to_proto("", gates(&wait_for, &skip_if, &cancel_if)).expect("three non-empty gates");

        assert_eq!(conditions.sleep_conditions.len(), 1);
        assert_eq!(
            conditions.sleep_conditions[0].base.as_ref().unwrap().action,
            v1::Action::Queue as i32
        );
        assert_eq!(conditions.user_event_conditions.len(), 2);
        let actions: Vec<i32> = conditions
            .user_event_conditions
            .iter()
            .map(|condition| condition.base.as_ref().unwrap().action)
            .collect();
        assert_eq!(
            actions,
            [v1::Action::Skip as i32, v1::Action::Cancel as i32]
        );
    }

    #[test]
    fn no_conditions_at_all_send_no_task_conditions() {
        let empty = ConditionSet::default();
        assert_eq!(to_proto("", gates(&empty, &empty, &empty)), None);
        assert!(validate(gates(&empty, &empty, &empty)).is_ok());
    }

    /// Acceptance criterion 4: an or-group shares one id, and everything
    /// else gets its own.
    #[test]
    fn an_or_group_shares_one_id_and_lone_conditions_do_not() {
        let set = ConditionSet::from(any_of([
            Condition::sleep(Duration::from_secs(60)),
            Condition::on_event("go"),
        ]))
        .and(Condition::on_event("other"));
        let conditions = only(set);

        let sleep_group = conditions.sleep_conditions[0]
            .base
            .as_ref()
            .unwrap()
            .or_group_id
            .clone();
        let groups: Vec<String> = conditions
            .user_event_conditions
            .iter()
            .map(|condition| condition.base.as_ref().unwrap().or_group_id.clone())
            .collect();

        assert_eq!(groups[0], sleep_group, "the or-group members share an id");
        assert_ne!(groups[1], sleep_group, "a lone condition gets its own id");
        assert_eq!(sleep_group.len(), 36, "a UUID string: {sleep_group}");
        assert!(
            sleep_group
                .chars()
                .all(|c| c.is_ascii_hexdigit() || c == '-'),
            "a UUID string: {sleep_group}"
        );
        let version = sleep_group.as_bytes()[14] as char;
        assert_eq!(version, '4', "a version 4 UUID: {sleep_group}");
    }

    #[test]
    fn a_list_of_conditions_ands_them_but_any_of_ors_them() {
        let anded = ConditionSet::from([
            Condition::on_event("a"),
            Condition::on_event("b"),
            Condition::on_event("c"),
        ]);
        let ids: Vec<String> = only(anded)
            .user_event_conditions
            .iter()
            .map(|condition| condition.base.as_ref().unwrap().or_group_id.clone())
            .collect();
        let distinct: HashSet<&String> = ids.iter().collect();
        assert_eq!(distinct.len(), 3, "each gets its own group: {ids:?}");

        let ored = ConditionSet::from(any_of([
            Condition::on_event("a"),
            Condition::on_event("b"),
            Condition::on_event("c"),
        ]));
        let ids: Vec<String> = only(ored)
            .user_event_conditions
            .iter()
            .map(|condition| condition.base.as_ref().unwrap().or_group_id.clone())
            .collect();
        let distinct: HashSet<&String> = ids.iter().collect();
        assert_eq!(distinct.len(), 1, "one group for all of them: {ids:?}");
    }

    #[test]
    fn a_list_of_or_groups_ands_the_groups() {
        let set = ConditionSet::from([
            any_of([Condition::on_event("a"), Condition::on_event("b")]),
            any_of([Condition::on_event("c")]),
        ]);
        let ids: Vec<String> = only(set)
            .user_event_conditions
            .iter()
            .map(|condition| condition.base.as_ref().unwrap().or_group_id.clone())
            .collect();
        assert_eq!(ids[0], ids[1], "the first group's members share an id");
        assert_ne!(ids[2], ids[0], "the second group is its own: {ids:?}");
    }

    #[test]
    fn two_mappings_of_the_same_set_use_different_group_ids() {
        let set: ConditionSet = Condition::sleep(Duration::from_secs(1)).into();
        let first = only(set.clone());
        let second = only(set);
        assert_ne!(
            first.sleep_conditions[0].base.as_ref().unwrap().or_group_id,
            second.sleep_conditions[0]
                .base
                .as_ref()
                .unwrap()
                .or_group_id,
        );
    }

    #[test]
    fn duplicate_readable_keys_are_rejected_across_all_three_gates() {
        let wait_for: ConditionSet = Condition::sleep(Duration::from_secs(5)).into();
        let skip_if: ConditionSet = Condition::sleep(Duration::from_secs(5)).into();
        let empty = ConditionSet::default();
        let Err(reason) = validate(gates(&wait_for, &skip_if, &empty)) else {
            panic!("two conditions with the same key should be rejected");
        };
        assert!(reason.contains("sleep:5000ms"), "{reason}");
        assert!(reason.contains("readable_key"), "{reason}");
    }

    #[test]
    fn a_readable_key_of_its_own_settles_a_duplicate() {
        let wait_for: ConditionSet = Condition::sleep(Duration::from_secs(5)).into();
        let skip_if: ConditionSet = Condition::sleep(Duration::from_secs(5))
            .readable_key("give-up")
            .into();
        let empty = ConditionSet::default();
        assert!(validate(gates(&wait_for, &skip_if, &empty)).is_ok());
    }

    #[test]
    fn a_condition_option_that_does_not_fit_its_kind_is_rejected() {
        let empty = ConditionSet::default();
        for (set, expected) in [
            (
                ConditionSet::from(Condition::sleep(Duration::from_secs(1)).expression("x")),
                "expression",
            ),
            (
                ConditionSet::from(Condition::parent_by_name("fetch").scope("s")),
                "scope",
            ),
            (
                ConditionSet::from(
                    Condition::sleep(Duration::from_secs(1)).since(SystemTime::UNIX_EPOCH),
                ),
                "since",
            ),
            (
                ConditionSet::from(Condition::on_event("go").since(SystemTime::UNIX_EPOCH)),
                "scope",
            ),
            (ConditionSet::from(Condition::sleep(Duration::ZERO)), "zero"),
            // Rounds to `"0ms"` on the wire, which is the very value the
            // zero-duration rule exists to keep off it.
            (
                ConditionSet::from(Condition::sleep(Duration::from_micros(500))),
                "zero",
            ),
            (
                ConditionSet::from(Condition::sleep(Duration::from_nanos(1))),
                "zero",
            ),
            (ConditionSet::from(any_of([])), "at least one"),
        ] {
            let Err(reason) = validate(gates(&set, &empty, &empty)) else {
                panic!("expected a rejection mentioning {expected}");
            };
            assert!(reason.contains(expected), "{reason} (expected {expected})");
        }
    }

    #[test]
    fn a_since_before_the_epoch_is_rejected() {
        let set = ConditionSet::from(
            Condition::on_event("go")
                .scope("s")
                .since(UNIX_EPOCH - Duration::from_secs(1)),
        );
        let empty = ConditionSet::default();
        let Err(reason) = validate(gates(&set, &empty, &empty)) else {
            panic!("a `since` before 1970 should be rejected");
        };
        assert!(reason.contains("1970"), "{reason}");
    }

    /// The engine weighs a sleep or event `skip_if`/`cancel_if` only while
    /// the task waits to be queued, so on its own it leaves the task waiting
    /// for ever (seen on both supported engines).
    #[test]
    fn a_sleep_or_event_skip_or_cancel_without_a_wait_for_is_rejected() {
        let empty = ConditionSet::default();
        for (skip_if, cancel_if, expected) in [
            (
                ConditionSet::from(Condition::on_event("skip")),
                ConditionSet::default(),
                "skip_if",
            ),
            (
                ConditionSet::default(),
                ConditionSet::from(Condition::sleep(Duration::from_secs(5))),
                "cancel_if",
            ),
        ] {
            let Err(reason) = validate(gates(&empty, &skip_if, &cancel_if)) else {
                panic!("expected a rejection mentioning {expected}");
            };
            assert!(reason.contains(expected), "{reason}");
            assert!(reason.contains("wait_for"), "{reason}");

            let wait_for = ConditionSet::from(Condition::sleep(Duration::from_secs(9)));
            assert!(
                validate(gates(&wait_for, &skip_if, &cancel_if)).is_ok(),
                "a wait_for settles it"
            );
        }
    }

    #[test]
    fn a_parent_skip_or_cancel_needs_no_wait_for() {
        let empty = ConditionSet::default();
        let skip_if = ConditionSet::from(Condition::parent_by_name("fetch").expression("output.x"));
        assert!(validate(gates(&empty, &skip_if, &empty)).is_ok());
    }

    /// Measured on both supported engines: a `wait_for` made only of parent
    /// conditions does not release a task that also carries a sleep or event
    /// `skip_if`/`cancel_if` — it hangs exactly as one with no `wait_for` at
    /// all does. Only a sleep or an event counts towards the pairing.
    #[test]
    fn a_wait_for_of_parent_conditions_alone_does_not_pair_with_an_event_skip_if() {
        let empty = ConditionSet::default();
        let wait_for =
            ConditionSet::from(Condition::parent_by_name("start").expression("output.n"));
        let skip_if = ConditionSet::from(Condition::on_event("never"));
        let Err(reason) = validate(gates(&wait_for, &skip_if, &empty)) else {
            panic!("a parent-only `wait_for` does not release an event `skip_if`");
        };
        assert!(reason.contains("skip_if"), "{reason}");
        assert!(
            reason.contains("sleep or an event"),
            "the message must say what to add: {reason}"
        );
    }

    #[test]
    fn a_sleep_or_event_wait_for_does_pair_with_a_sleep_or_event_skip_or_cancel() {
        let empty = ConditionSet::default();

        let sleeping = ConditionSet::from(Condition::sleep(Duration::from_secs(9)));
        let skip_if = ConditionSet::from(Condition::on_event("never"));
        assert!(validate(gates(&sleeping, &skip_if, &empty)).is_ok());

        let on_event = ConditionSet::from(Condition::on_event("go"));
        let cancel_if = ConditionSet::from(Condition::sleep(Duration::from_secs(30)));
        assert!(validate(gates(&on_event, &empty, &cancel_if)).is_ok());

        // A parent condition beside a sleep in the same `wait_for` does not
        // spoil the pairing.
        let mixed = ConditionSet::from(Condition::parent_by_name("start"))
            .and(Condition::sleep(Duration::from_secs(9)));
        assert!(validate(gates(&mixed, &skip_if, &empty)).is_ok());
    }

    /// Two conditions on one parent, told apart by their expressions rather
    /// than colliding on the bare parent name.
    #[test]
    fn parent_conditions_on_one_parent_with_different_expressions_get_different_keys() {
        let wait_for =
            ConditionSet::from(Condition::parent_by_name("fetch").expression("output.a"));
        let skip_if = ConditionSet::from(Condition::parent_by_name("fetch").expression("output.b"));
        let empty = ConditionSet::default();
        assert!(
            validate(gates(&wait_for, &skip_if, &empty)).is_ok(),
            "the expression is part of the default key"
        );

        let conditions =
            to_proto("", gates(&wait_for, &skip_if, &empty)).expect("two parent conditions");
        let keys: Vec<&str> = conditions
            .parent_override_conditions
            .iter()
            .map(|condition| condition.base.as_ref().unwrap().readable_data_key.as_str())
            .collect();
        assert_eq!(keys, ["fetch:output.a", "fetch:output.b"]);
        for condition in &conditions.parent_override_conditions {
            assert_eq!(condition.parent_readable_id, "fetch");
        }
    }

    #[test]
    fn a_parent_condition_without_an_expression_keeps_the_bare_parent_name() {
        let conditions = only(Condition::parent_by_name("fetch").into());
        let base = conditions.parent_override_conditions[0]
            .base
            .as_ref()
            .expect("a base condition");
        assert_eq!(base.readable_data_key, "fetch");
    }

    #[test]
    fn two_identical_parent_conditions_still_need_a_readable_key_of_their_own() {
        let wait_for =
            ConditionSet::from(Condition::parent_by_name("fetch").expression("output.a"));
        let skip_if = ConditionSet::from(Condition::parent_by_name("fetch").expression("output.a"));
        let empty = ConditionSet::default();
        let Err(reason) = validate(gates(&wait_for, &skip_if, &empty)) else {
            panic!("the same parent and the same expression is still one key");
        };
        assert!(reason.contains("fetch:output.a"), "{reason}");
        assert!(reason.contains("readable_key"), "{reason}");
    }

    #[test]
    fn a_blank_string_on_a_condition_is_rejected() {
        let empty = ConditionSet::default();
        for (set, expected) in [
            (ConditionSet::from(Condition::on_event("")), "event key"),
            (ConditionSet::from(Condition::on_event("  ")), "event key"),
            (
                ConditionSet::from(Condition::parent_by_name("")),
                "parent name",
            ),
            (
                ConditionSet::from(Condition::on_event("go").readable_key("")),
                "readable key",
            ),
            (
                ConditionSet::from(Condition::parent_by_name("fetch").expression("")),
                "expression",
            ),
            (
                ConditionSet::from(Condition::on_event("go").expression(" \t")),
                "expression",
            ),
        ] {
            let Err(reason) = validate(gates(&set, &empty, &empty)) else {
                panic!("expected a rejection mentioning {expected}");
            };
            assert!(reason.contains(expected), "{reason} (expected {expected})");
            assert!(reason.contains("blank"), "{reason}");
        }
    }

    #[test]
    fn a_wait_is_named_after_what_it_is_waiting_on() {
        assert_eq!(
            ConditionSet::from(Condition::on_event("approve")).wait_kind(),
            ("user_event", "approve".to_string()),
        );
        assert_eq!(
            ConditionSet::from(Condition::sleep(Duration::from_secs(5))).wait_kind(),
            ("sleep", "sleep:5000ms".to_string()),
        );
        assert_eq!(
            ConditionSet::from(Condition::parent_by_name("fetch")).wait_kind(),
            ("parent", "fetch".to_string()),
        );
        // Two of a kind stay that kind, and the resource is the first key in
        // sorted order however the set was written.
        assert_eq!(
            ConditionSet::from(any_of([
                Condition::on_event("zebra"),
                Condition::on_event("aardvark"),
            ]))
            .wait_kind(),
            ("user_event", "aardvark".to_string()),
        );
        // A mixed set is neither.
        assert_eq!(
            ConditionSet::from(any_of([
                Condition::on_event("approve"),
                Condition::sleep(Duration::from_secs(5)),
            ]))
            .wait_kind()
            .0,
            "wait_for",
        );
        assert_eq!(
            ConditionSet::default().wait_kind(),
            ("wait_for", String::new()),
        );
    }

    #[test]
    fn parent_names_lists_only_the_parent_conditions() {
        let set = ConditionSet::from(any_of([
            Condition::parent_by_name("a"),
            Condition::on_event("go"),
        ]))
        .and(Condition::parent_by_name("b"));
        assert_eq!(set.parent_names().collect::<Vec<_>>(), ["a", "b"]);
    }
}