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
//! Declaring a task: options, a typed handler, and its type-erased form.

use std::collections::BTreeMap;
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;

use hatchet_proto::root::AssignedAction;

use super::{
    BatchConfig, Concurrency, ConditionSet, DesiredLabel, Idempotency, Priority, RateLimit,
    StickyStrategy,
};
use crate::batch::{BatchInput, BatchMemberId, BatchOutput, BatchReport, reconcile};
use crate::{Context, DurableContext, EvictionPolicy, TaskError};

/// A handler with its input and output types erased at the JSON boundary,
/// so the worker can run any task without knowing its types.
// The function-pointer-like trait object is inherent to type erasure here;
// splitting it up would not make it clearer.
#[allow(clippy::type_complexity)]
pub(crate) type ErasedHandler = Arc<
    dyn Fn(Context, Value) -> Pin<Box<dyn Future<Output = Result<Value, TaskError>> + Send>>
        + Send
        + Sync,
>;

/// A batch handler with its types erased at the JSON boundary: it takes the
/// `START_BATCH` action whole and answers with one outcome per member of it.
///
/// Taking the assignment rather than a parsed shape is what keeps the parsing
/// next to the types it parses into: only this closure knows `I`.
// Same reason as [`ErasedHandler`]: the trait object is the erasure.
#[allow(clippy::type_complexity)]
pub(crate) type ErasedBatchHandler = Arc<
    dyn Fn(
            Context,
            AssignedAction,
        ) -> Pin<Box<dyn Future<Output = Result<BatchReport, TaskError>> + Send>>
        + Send
        + Sync,
>;

/// What a batch task adds to a declaration.
#[derive(Clone)]
pub(crate) struct BatchDef {
    pub(crate) config: BatchConfig,
    /// Whether the handler answers with one value for the whole batch, which
    /// is decided by which builder method attached it.
    pub(crate) broadcast: bool,
    pub(crate) handler: ErasedBatchHandler,
}

/// Per-task scheduling options.
#[derive(Clone, Default)]
pub(crate) struct TaskOptions {
    pub(crate) retries: u32,
    /// `(factor, max_seconds)`.
    pub(crate) backoff: Option<(f32, u32)>,
    pub(crate) execution_timeout: Option<Duration>,
    pub(crate) schedule_timeout: Option<Duration>,
    pub(crate) concurrency: Vec<Concurrency>,
    pub(crate) rate_limits: Vec<RateLimit>,
    pub(crate) worker_labels: BTreeMap<String, DesiredLabel>,
    /// What holds the task back, what skips it and what cancels it. All
    /// three leave as one `CreateTaskOpts.conditions`, told apart by the
    /// engine's `Action`.
    pub(crate) wait_for: ConditionSet,
    pub(crate) skip_if: ConditionSet,
    pub(crate) cancel_if: ConditionSet,
    /// When a waiting run of this task may be handed back to the engine.
    /// Worker-side only: it is never sent anywhere.
    pub(crate) eviction_policy: Option<EvictionPolicy>,
}

/// Options that belong to a workflow as a whole: how it is triggered and
/// described. A standalone task carries them for its implicit workflow.
#[derive(Clone, Default)]
pub(crate) struct WorkflowOptions {
    pub(crate) description: Option<String>,
    pub(crate) version: Option<String>,
    pub(crate) on_events: Vec<String>,
    pub(crate) on_crons: Vec<String>,
    pub(crate) cron_input: Option<Value>,
    pub(crate) default_priority: Option<Priority>,
    pub(crate) concurrency: Vec<Concurrency>,
    pub(crate) sticky: Option<StickyStrategy>,
    pub(crate) idempotency: Option<Idempotency>,
}

impl WorkflowOptions {
    pub(crate) fn is_empty(&self) -> bool {
        self.description.is_none()
            && self.version.is_none()
            && self.on_events.is_empty()
            && self.on_crons.is_empty()
            && self.cron_input.is_none()
            && self.default_priority.is_none()
            && self.concurrency.is_empty()
            && self.sticky.is_none()
            && self.idempotency.is_none()
    }
}

/// A task with its types erased: what a workflow and the worker hold.
#[derive(Clone)]
pub(crate) struct TaskDef {
    pub(crate) name: String,
    pub(crate) options: TaskOptions,
    pub(crate) parents: Vec<String>,
    pub(crate) handler: ErasedHandler,
    /// Set by [`TaskBuilder::durable_handler`]: the engine sends this action a
    /// durable invocation, and it asks for a `durable` slot rather than a
    /// `default` one.
    pub(crate) durable: bool,
    /// Set by [`TaskBuilder::batch_handler`] or
    /// [`TaskBuilder::batch_broadcast_handler`]: the engine buffers this task's
    /// runs and assigns the whole group as one `START_BATCH`.
    pub(crate) batch: Option<BatchDef>,
}

/// One action a worker serves: its handler, and whether the engine will send
/// it a durable invocation.
#[derive(Clone)]
pub(crate) struct RegisteredAction {
    pub(crate) handler: ErasedHandler,
    pub(crate) durable: bool,
    /// The policy the task declared, if any: the worker's eviction book reads
    /// it when this action is assigned.
    pub(crate) eviction_policy: Option<EvictionPolicy>,
    /// The batch handler, when this action is a batch task: what a
    /// `START_BATCH` assignment for it is run with.
    pub(crate) batch: Option<ErasedBatchHandler>,
}

/// Configures a task before its handler is attached.
///
/// `I` is the input the handler receives and `O` the output it returns; both
/// cross the wire as JSON. [`handler`](TaskBuilder::handler) finishes the
/// declaration and hands back a [`Task`], which a worker registers and a
/// client triggers.
///
/// The options set here are per task. The ones marked "standalone
/// registration only" — [`on_events`](TaskBuilder::on_events),
/// [`cron`](TaskBuilder::cron), [`cron_input`](TaskBuilder::cron_input),
/// [`description`](TaskBuilder::description),
/// [`version`](TaskBuilder::version),
/// [`default_priority`](TaskBuilder::default_priority),
/// [`workflow_concurrency`](TaskBuilder::workflow_concurrency),
/// [`sticky`](TaskBuilder::sticky), [`idempotency`](TaskBuilder::idempotency)
/// — belong to the
/// workflow a standalone task implies; setting them on a task that is then
/// added to a [`Workflow`](crate::Workflow) is an
/// [`Error::InvalidDeclaration`](crate::Error::InvalidDeclaration) at
/// registration.
///
/// ```
/// use std::time::Duration;
///
/// use hatchet_client::{Concurrency, ConcurrencyLimitStrategy, DesiredLabel, TaskBuilder};
///
/// let agent_run = TaskBuilder::<String, String>::new("agent-run")
///     .retries(1)
///     .retry_backoff(2.0, 60)
///     .execution_timeout(Duration::from_secs(2 * 3600))
///     .concurrency(
///         Concurrency::expr("input.device_id")
///             .max_runs(1)
///             .strategy(ConcurrencyLimitStrategy::GroupRoundRobin),
///     )
///     .worker_label("os", DesiredLabel::eq("macos").required())
///     .on_events(["approval.granted"])
///     .handler(|_ctx, repo: String| async move { Ok(format!("reviewed {repo}")) });
///
/// assert_eq!(agent_run.name(), "agent-run");
/// ```
#[must_use = "a task builder declares nothing until `handler` is called"]
pub struct TaskBuilder<I, O> {
    name: String,
    options: TaskOptions,
    standalone: WorkflowOptions,
    _types: PhantomData<fn(I) -> O>,
}

/// Shows what a declaration is, not what it does: the handler is a closure
/// with nothing to print, and the options are the caller's own values.
impl<I, O> fmt::Debug for TaskBuilder<I, O> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TaskBuilder")
            .field("name", &self.name)
            .field("retries", &self.options.retries)
            .finish_non_exhaustive()
    }
}

impl<I, O> TaskBuilder<I, O> {
    /// Starts declaring a task. Registered on its own, the task name is also
    /// the workflow name used to trigger it.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            options: TaskOptions::default(),
            standalone: WorkflowOptions::default(),
            _types: PhantomData,
        }
    }

    /// How many times Hatchet retries the task after a retryable failure.
    pub fn retries(mut self, retries: u32) -> Self {
        self.options.retries = retries;
        self
    }

    /// Exponential backoff between retries: multiply the delay by `factor`
    /// each time, up to `max_seconds`.
    pub fn retry_backoff(mut self, factor: f32, max_seconds: u32) -> Self {
        self.options.backoff = Some((factor, max_seconds));
        self
    }

    /// How long a run may execute before the engine times it out.
    pub fn execution_timeout(mut self, timeout: Duration) -> Self {
        self.options.execution_timeout = Some(timeout);
        self
    }

    /// How long a run may wait for a worker before the engine gives up.
    pub fn schedule_timeout(mut self, timeout: Duration) -> Self {
        self.options.schedule_timeout = Some(timeout);
        self
    }

    /// Adds a concurrency limit on this task.
    pub fn concurrency(mut self, concurrency: Concurrency) -> Self {
        self.options.concurrency.push(concurrency);
        self
    }

    /// Holds the task back until these conditions are satisfied.
    ///
    /// May be called repeatedly; everything given must be satisfied for the
    /// task to start. Use [`any_of`](crate::any_of) for "whichever comes
    /// first".
    ///
    /// A [`Condition::parent`](crate::Condition::parent) condition may only
    /// name a task this one runs after — set the parents with
    /// [`Task::parent`](crate::Task::parent) after the handler, as usual:
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use hatchet_client::{Condition, TaskBuilder, Workflow, any_of};
    ///
    /// let fetch = TaskBuilder::<(), u32>::new("fetch").handler(|_ctx, _input| async { Ok(1) });
    /// let publish = TaskBuilder::<(), ()>::new("publish")
    ///     .wait_for(any_of([
    ///         Condition::on_event("publish.approved"),
    ///         Condition::sleep(Duration::from_secs(600)),
    ///     ]))
    ///     .skip_if(Condition::parent(&fetch).expression("output == 0"))
    ///     .handler(|_ctx, _input| async { Ok(()) })
    ///     .parent(&fetch);
    ///
    /// let pipeline = Workflow::new("pipeline").task(&fetch).task(&publish);
    /// # let _ = pipeline;
    /// ```
    pub fn wait_for(mut self, conditions: impl Into<ConditionSet>) -> Self {
        self.options.wait_for.extend(conditions.into());
        self
    }

    /// Skips the task — without failing the workflow — when these
    /// conditions are satisfied.
    ///
    /// A skipped task runs nothing and produces no output of its own: the
    /// engine records `{"skipped": true}` for it instead, and skips
    /// everything downstream of it too, including the
    /// [`on_success`](crate::Workflow::on_success) task; the run itself
    /// still succeeds. Read that marker rather than the output — a
    /// downstream handler tells a skipped parent apart from one that ran with
    /// [`Context::was_skipped`](crate::Context::was_skipped), and a caller
    /// waiting on the run does the same with
    /// [`WorkflowResult::was_skipped`](crate::WorkflowResult::was_skipped).
    ///
    /// A sleep or event condition here is weighed only while the task waits
    /// to be queued, so it must be paired with a
    /// [`wait_for`](TaskBuilder::wait_for) *on a sleep or an event* —
    /// otherwise the task would wait for ever, and the declaration is
    /// rejected. Neither having parents nor a `wait_for` made only of parent
    /// conditions counts: a task in that shape was measured, on both
    /// supported engines, never to start while an otherwise identical
    /// sibling did. A parent condition needs no pairing at all: it is weighed
    /// as soon as the parent finishes.
    ///
    /// May be called repeatedly; everything given must be satisfied.
    ///
    /// ```
    /// use hatchet_client::{Condition, TaskBuilder, Workflow};
    ///
    /// let fetch = TaskBuilder::<(), u32>::new("fetch").handler(|_ctx, _input| async { Ok(0) });
    /// let publish = TaskBuilder::<(), ()>::new("publish")
    ///     // Nothing was fetched, so there is nothing to publish.
    ///     .skip_if(Condition::parent(&fetch).expression("output == 0"))
    ///     .handler(|_ctx, _input| async { Ok(()) })
    ///     .parent(&fetch);
    ///
    /// let pipeline = Workflow::new("pipeline").task(&fetch).task(&publish);
    /// # let _ = pipeline;
    /// ```
    pub fn skip_if(mut self, conditions: impl Into<ConditionSet>) -> Self {
        self.options.skip_if.extend(conditions.into());
        self
    }

    /// Cancels the task when these conditions are satisfied.
    ///
    /// What was measured, on both supported engines: the engine weighs the
    /// condition while the task is *waiting to start*, and when it fired the
    /// task was cancelled before its handler ever ran — so the handler's
    /// [`Context::cancelled`](crate::Context::cancelled) token never
    /// triggered either. A caller waiting on the run then gets
    /// [`Error::RunCancelled`](crate::Error::RunCancelled).
    ///
    /// **This is a queuing gate, not a stop button.** A condition that
    /// becomes true *after* the handler has started does not interrupt it:
    /// measured on both supported engines, a task that had reported itself
    /// started ran to completion and its run succeeded, with
    /// `Context::cancelled` never triggering. For a handler that has to be
    /// able to stop what it is doing, cancel the run —
    /// [`RunHandle::cancel`](crate::RunHandle::cancel),
    /// [`RunsClient::cancel`](crate::RunsClient::cancel), or the dashboard —
    /// and watch `Context::cancelled`.
    ///
    /// The same pairing rule as [`skip_if`](TaskBuilder::skip_if) applies,
    /// and for the same reason.
    ///
    /// The current official Go SDK exposes no equivalent option — only
    /// `WithWaitFor` and `WithSkipIf`; a `CancelIf` field survives on the
    /// deprecated `pkg/client/create` task struct. This follows the official
    /// Python SDK.
    ///
    /// May be called repeatedly; everything given must be satisfied.
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use hatchet_client::{Condition, TaskBuilder};
    ///
    /// let deploy = TaskBuilder::<(), ()>::new("deploy")
    ///     // Deploy five minutes from now, unless someone calls it off.
    ///     .wait_for(Condition::sleep(Duration::from_secs(300)))
    ///     .cancel_if(Condition::on_event("deploy.aborted"))
    ///     .handler(|_ctx, _input| async { Ok(()) });
    /// # let _ = deploy;
    /// ```
    pub fn cancel_if(mut self, conditions: impl Into<ConditionSet>) -> Self {
        self.options.cancel_if.extend(conditions.into());
        self
    }

    /// Adds a concurrency limit across *runs of this task as a workflow*,
    /// rather than on the task itself — `CreateWorkflowVersionRequest`'s
    /// `concurrency_arr` instead of `CreateTaskOpts.concurrency`. Standalone
    /// registration only; inside a [`Workflow`](crate::Workflow), use
    /// [`Workflow::concurrency`](crate::Workflow::concurrency).
    ///
    /// ```
    /// use hatchet_client::{Concurrency, ConcurrencyLimitStrategy, TaskBuilder};
    ///
    /// // One run per tenant at a time; the rest wait their turn.
    /// let agent_run = TaskBuilder::<(), ()>::new("agent-run")
    ///     .workflow_concurrency(
    ///         Concurrency::expr("input.tenant")
    ///             .max_runs(1)
    ///             .strategy(ConcurrencyLimitStrategy::GroupRoundRobin),
    ///     )
    ///     .handler(|_ctx, _input| async move { Ok(()) });
    /// ```
    pub fn workflow_concurrency(mut self, concurrency: Concurrency) -> Self {
        self.standalone.concurrency.push(concurrency);
        self
    }

    /// Makes each run consume units of a static rate limit.
    pub fn rate_limit(mut self, rate_limit: RateLimit) -> Self {
        self.options.rate_limits.push(rate_limit);
        self
    }

    /// Asks for a worker whose label `key` satisfies `label`.
    pub fn worker_label(mut self, key: impl Into<String>, label: DesiredLabel) -> Self {
        self.options.worker_labels.insert(key.into(), label);
        self
    }

    /// Describes the task. Standalone registration only.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.standalone.description = Some(description.into());
        self
    }

    /// Labels this version of the task. Standalone registration only.
    pub fn version(mut self, version: impl Into<String>) -> Self {
        self.standalone.version = Some(version.into());
        self
    }

    /// Runs the task whenever one of these event keys is pushed. May be
    /// called repeatedly; event keys accumulate. Standalone registration
    /// only; inside a workflow, set triggers on the workflow.
    pub fn on_events(mut self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.standalone
            .on_events
            .extend(keys.into_iter().map(Into::into));
        self
    }

    /// Runs the task on a cron schedule. May be called repeatedly; cron
    /// expressions accumulate. Standalone registration only.
    pub fn cron(mut self, expression: impl Into<String>) -> Self {
        self.standalone.on_crons.push(expression.into());
        self
    }

    /// The input given to cron-triggered runs. Standalone registration only.
    pub fn cron_input(mut self, input: Value) -> Self {
        self.standalone.cron_input = Some(input);
        self
    }

    /// The priority of runs that do not specify one. Standalone registration only.
    pub fn default_priority(mut self, priority: Priority) -> Self {
        self.standalone.default_priority = Some(priority);
        self
    }

    /// Pins this task's runs to one worker. Standalone registration only;
    /// inside a [`Workflow`](crate::Workflow), use
    /// [`Workflow::sticky`](crate::Workflow::sticky).
    ///
    /// ```
    /// use hatchet_client::{StickyStrategy, TaskBuilder};
    ///
    /// let warm = TaskBuilder::<(), ()>::new("warm")
    ///     .sticky(StickyStrategy::Soft)
    ///     .handler(|_ctx, _input| async { Ok(()) });
    /// # let _ = warm;
    /// ```
    pub fn sticky(mut self, strategy: StickyStrategy) -> Self {
        self.standalone.sticky = Some(strategy);
        self
    }

    /// Makes the engine refuse a second run whose key matches a claimed one.
    /// Standalone registration only; inside a [`Workflow`](crate::Workflow),
    /// use [`Workflow::idempotency`](crate::Workflow::idempotency).
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use hatchet_client::{Idempotency, TaskBuilder};
    ///
    /// let send = TaskBuilder::<(), ()>::new("send-receipt")
    ///     .idempotency(Idempotency::until_run_ends("input.order_id", Duration::from_secs(60)))
    ///     .handler(|_ctx, _input| async { Ok(()) });
    /// # let _ = send;
    /// ```
    pub fn idempotency(mut self, idempotency: Idempotency) -> Self {
        self.standalone.idempotency = Some(idempotency);
        self
    }

    /// Lets this task's runs be handed back to the engine while they wait.
    ///
    /// **Durable tasks only.** A policy on an ordinary
    /// [`handler`](Self::handler) is an
    /// [`Error::InvalidDeclaration`](crate::Error::InvalidDeclaration) at
    /// registration rather than a policy that silently never fires: an
    /// ordinary run is never parked on the engine, so a policy on one nearly
    /// always means the handler was meant to be a
    /// [`durable_handler`](Self::durable_handler).
    ///
    /// Nothing about the policy is sent anywhere — the registration request is
    /// byte for byte the one this task would send without it. See
    /// [`EvictionPolicy`] for what the worker does with it.
    ///
    /// A [`ttl`](EvictionPolicy::ttl) of [`Duration::ZERO`] is refused for the
    /// same reason: it would leave a policy that can only ever fire under
    /// capacity pressure, which is not what a zero usually means.
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use hatchet_client::{EvictionPolicy, TaskBuilder};
    ///
    /// let approve = TaskBuilder::<(), ()>::new("approve")
    ///     .eviction_policy(EvictionPolicy::ttl(Duration::from_secs(60)))
    ///     .durable_handler(|ctx, _input| async move {
    ///         ctx.wait_for_event("approved").await?;
    ///         Ok(())
    ///     });
    /// # let _ = approve;
    /// ```
    pub fn eviction_policy(mut self, policy: EvictionPolicy) -> Self {
        self.options.eviction_policy = Some(policy);
        self
    }

    /// Attaches the handler and finishes the declaration.
    pub fn handler<F, Fut>(self, handler: F) -> Task<I, O>
    where
        F: Fn(Context, I) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<O, TaskError>> + Send + 'static,
        I: DeserializeOwned + Send + 'static,
        O: Serialize + 'static,
    {
        let handler = Arc::new(handler);
        let erased: ErasedHandler = Arc::new(move |context, input| {
            let handler = Arc::clone(&handler);
            Box::pin(async move {
                let input: I = match serde_json::from_value(input) {
                    Ok(input) => input,
                    Err(e) => {
                        return Err(TaskError::non_retryable(format!(
                            "the input does not match the task's input type: {e}"
                        )));
                    }
                };
                let output = handler(context, input).await?;
                serde_json::to_value(output).map_err(|e| {
                    TaskError::non_retryable(format!(
                        "the output could not be serialized to JSON: {e}"
                    ))
                })
            })
        });
        Task {
            def: TaskDef {
                name: self.name,
                options: self.options,
                parents: Vec::new(),
                handler: erased,
                durable: false,
                batch: None,
            },
            standalone: self.standalone,
            _types: PhantomData,
        }
    }

    /// Attaches a **durable** handler and finishes the declaration.
    ///
    /// A durable task may pause on the engine rather than on the worker:
    /// [`DurableContext::sleep_for`](crate::DurableContext::sleep_for) and
    /// [`wait_for_event`](crate::DurableContext::wait_for_event) record the
    /// wait in the engine's event log, so a worker that dies while waiting
    /// does not lose it — the task is assigned again and the handler is run
    /// **from the top**, with the waits that already finished answered at
    /// once.
    ///
    /// That replay is what makes determinism a rule rather than a nicety: the
    /// handler must reach the same durable operations in the same order on
    /// every attempt, or the engine answers
    /// [`Error::Nondeterminism`](crate::Error::Nondeterminism) and the run
    /// fails without a retry. Anything that must not be recomputed goes
    /// through [`memo`](crate::DurableContext::memo) or
    /// [`now`](crate::DurableContext::now); see [`DurableContext`] for the
    /// whole of the bargain.
    ///
    /// The task asks the engine for a `durable` slot rather than a `default`
    /// one, and its worker registers a durable slot pool
    /// ([`WorkerBuilder::durable_slots`](crate::WorkerBuilder::durable_slots),
    /// 1000 by default) — a waiting durable task is not doing any work, so
    /// those slots are cheap.
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use hatchet_client::TaskBuilder;
    ///
    /// let approve = TaskBuilder::<(), String>::new("approve")
    ///     .durable_handler(|ctx, _input| async move {
    ///         ctx.sleep_for(Duration::from_secs(60)).await?;
    ///         let event = ctx.wait_for_event("approved").await?;
    ///         Ok(event.key)
    ///     });
    /// # let _ = approve;
    /// ```
    ///
    /// [`DurableContext`]: crate::DurableContext
    pub fn durable_handler<F, Fut>(self, handler: F) -> Task<I, O>
    where
        F: Fn(DurableContext, I) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<O, TaskError>> + Send + 'static,
        I: DeserializeOwned + Send + 'static,
        O: Serialize + 'static,
    {
        let handler = Arc::new(handler);
        let erased: ErasedHandler = Arc::new(move |context, input| {
            let handler = Arc::clone(&handler);
            Box::pin(async move {
                // The only place a `DurableContext` is ever made, which is
                // what keeps the durable operations out of an ordinary
                // handler's reach. A durable action always arrives with a
                // durable invocation attached; anything else is a worker bug,
                // so it is reported rather than panicked on.
                let context = DurableContext::attach(context)?;
                let input: I = match serde_json::from_value(input) {
                    Ok(input) => input,
                    Err(e) => {
                        return Err(TaskError::non_retryable(format!(
                            "the input does not match the task's input type: {e}"
                        )));
                    }
                };
                let output = handler(context, input).await?;
                serde_json::to_value(output).map_err(|e| {
                    TaskError::non_retryable(format!(
                        "the output could not be serialized to JSON: {e}"
                    ))
                })
            })
        });
        Task {
            def: TaskDef {
                name: self.name,
                options: self.options,
                parents: Vec::new(),
                handler: erased,
                durable: true,
                batch: None,
            },
            standalone: self.standalone,
            _types: PhantomData,
        }
    }

    /// Attaches a **batch** handler and finishes the declaration.
    ///
    /// The engine buffers concurrent runs of this task and hands the whole
    /// group to one worker at once: the handler is called **once** with every
    /// buffered input, keyed by [`BatchMemberId`], and answers with one output
    /// per input. Each member's output is reported separately, so the runs
    /// behind them complete — or fail — independently.
    ///
    /// Three rules keep a member from waiting on an answer that never comes:
    ///
    /// - A member whose input does not deserialize into `I` fails on its own,
    ///   without being shown to the handler and without touching the rest.
    /// - A member the handler leaves out of the [`BatchOutput`] is reported
    ///   **failed** rather than left alone. Measured against a real engine, an
    ///   unreported member stays `Running` until the task times out and is
    ///   never assigned again.
    /// - A handler that returns `Err` fails **every** member of the batch with
    ///   that error, since there is no way to tell which member it was about.
    ///
    /// Both official SDKs instead fail the whole batch when a member is
    /// missing, throwing away the outputs the handler did produce; this SDK
    /// keeps them. A handler that panics fails every member the same way an
    /// `Err` does.
    ///
    /// # How a batch runs on the worker
    ///
    /// A batch is **one** run of the worker, however many task runs it answers
    /// for: it takes one `default` slot, and the STARTED naming every member is
    /// reported before the handler is called. What comes back is at most two
    /// reports — the members that succeeded, then the ones that failed —
    /// because one event type covers a whole report.
    ///
    /// The [`Context`] the handler is given is the **batch's**: its per-run
    /// accessors are empty, as [`Context`]'s own documentation sets out, and
    /// everything about the batch is on [`BatchInput`]. Cancellation is the
    /// batch's too: the worker shutting down cancels the whole batch and
    /// nothing terminal is reported for any member, and there is no way to
    /// cancel one member of a batch that is already running.
    ///
    /// # Rules a batch task is held to
    ///
    /// - It needs an engine of at least
    ///   [`BATCH_MIN_ENGINE_VERSION`](crate::BATCH_MIN_ENGINE_VERSION);
    ///   [`WorkerBuilder::build`](crate::WorkerBuilder::build) refuses an older
    ///   one, which would take the registration and then never batch anything.
    /// - It cannot set [`retries`](Self::retries): the declaration is refused
    ///   with [`Error::InvalidDeclaration`](crate::Error::InvalidDeclaration)
    ///   rather than quietly forced to zero, as the official SDKs do. Failing a
    ///   member with a retryable [`TaskError`] still has the engine re-batch
    ///   that member on its own.
    /// - It cannot be an [`on_failure`](crate::Workflow::on_failure) or
    ///   [`on_success`](crate::Workflow::on_success) hook: a hook runs because
    ///   one particular run ended, so there is nothing to batch it with.
    /// - It cannot be durable — a durable handler is a different method, so
    ///   that one is a compile error rather than a rule.
    ///
    /// ```
    /// use hatchet_client::{BatchConfig, BatchOutput, TaskBuilder, TaskError};
    ///
    /// let lengths = TaskBuilder::<String, usize>::new("lengths").batch_handler(
    ///     BatchConfig::max_size(16),
    ///     |_ctx, batch| async move {
    ///         let mut output = BatchOutput::new();
    ///         for (id, text) in batch.iter() {
    ///             if text.is_empty() {
    ///                 output = output.fail(id.clone(), TaskError::non_retryable("empty"));
    ///             } else {
    ///                 output = output.ok(id.clone(), text.len());
    ///             }
    ///         }
    ///         Ok(output)
    ///     },
    /// );
    /// # let _ = lengths;
    /// ```
    pub fn batch_handler<F, Fut>(self, config: BatchConfig, handler: F) -> Task<I, O>
    where
        F: Fn(Context, BatchInput<I>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<BatchOutput<O>, TaskError>> + Send + 'static,
        I: DeserializeOwned + Send + 'static,
        O: Serialize + Send + 'static,
    {
        let handler = Arc::new(handler);
        let name = self.name.clone();
        let erased: ErasedBatchHandler = Arc::new(move |context, action| {
            let handler = Arc::clone(&handler);
            let name = name.clone();
            Box::pin(async move {
                let (input, mut report) = BatchInput::<I>::decode(&action)?;
                let members: Vec<BatchMemberId> = input.ids().cloned().collect();
                // Called even when every input was rejected, so "the handler
                // runs exactly once per batch" holds without exceptions.
                let output = handler(context, input).await?;
                reconcile(&name, &members, output.into_items(), &mut report);
                Ok(report)
            })
        });
        self.into_batch_task(config, false, erased)
    }

    /// Attaches a batch handler that answers with **one value for the whole
    /// batch**, which every buffered run then receives as its own output.
    ///
    /// For work that is the same for every caller — a cache warm-up, a shared
    /// lookup — where per-member outputs would be one value repeated. The
    /// registration says so (`broadcast_output`), so the engine and the handler
    /// can never disagree about the shape of the answer: which of the two
    /// builder methods was called decides both.
    ///
    /// A member whose input does not deserialize into `I` still fails on its
    /// own and does **not** receive the broadcast value. Everything else in
    /// [`batch_handler`](Self::batch_handler) — the engine floor, no retries,
    /// no hooks — applies here too.
    ///
    /// ```
    /// use hatchet_client::{BatchConfig, TaskBuilder};
    ///
    /// let refresh = TaskBuilder::<String, String>::new("refresh").batch_broadcast_handler(
    ///     BatchConfig::max_size(64),
    ///     |_ctx, batch| async move { Ok(format!("refreshed for {} callers", batch.len())) },
    /// );
    /// # let _ = refresh;
    /// ```
    pub fn batch_broadcast_handler<F, Fut>(self, config: BatchConfig, handler: F) -> Task<I, O>
    where
        F: Fn(Context, BatchInput<I>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<O, TaskError>> + Send + 'static,
        I: DeserializeOwned + Send + 'static,
        O: Serialize + Send + 'static,
    {
        let handler = Arc::new(handler);
        let name = self.name.clone();
        let erased: ErasedBatchHandler = Arc::new(move |context, action| {
            let handler = Arc::clone(&handler);
            let name = name.clone();
            Box::pin(async move {
                let (input, mut report) = BatchInput::<I>::decode(&action)?;
                let members: Vec<BatchMemberId> = input.ids().cloned().collect();
                let output = handler(context, input).await?;
                let value = serde_json::to_value(output).map_err(|e| {
                    TaskError::non_retryable(format!(
                        "the output could not be serialized to JSON: {e}"
                    ))
                })?;
                // Serialized once and copied, rather than left to `reconcile`
                // to serialize per member: the value is the same for all of
                // them, so a failure to serialize it is a failure of the whole
                // batch and is raised above instead.
                let answered = members
                    .iter()
                    .map(|id| (id.clone(), Ok(value.clone())))
                    .collect();
                reconcile(&name, &members, answered, &mut report);
                Ok(report)
            })
        });
        self.into_batch_task(config, true, erased)
    }

    /// The half both batch handlers share: a [`Task`] whose ordinary handler
    /// can only ever be reached by mistake.
    fn into_batch_task(
        self,
        config: BatchConfig,
        broadcast: bool,
        handler: ErasedBatchHandler,
    ) -> Task<I, O> {
        let name = self.name;
        // A batch task is assigned as `START_BATCH`, never as `START_STEP_RUN`
        // — the engine even re-batches a failed member into a batch of one
        // rather than assigning it singly. If an ordinary run arrives anyway,
        // the engine took the registration and ignored the batch config, and
        // saying so by name is far better than running a handler written for a
        // whole batch against one input.
        let stub_name = name.clone();
        let stub: ErasedHandler = Arc::new(move |_context, _input| {
            let name = stub_name.clone();
            Box::pin(async move {
                Err(TaskError::non_retryable(format!(
                    "`{name}` is a batch task, but this run was assigned as an ordinary task run; \
                     the engine this worker is connected to does not batch it"
                )))
            })
        });
        Task {
            def: TaskDef {
                name,
                options: self.options,
                parents: Vec::new(),
                handler: stub,
                durable: false,
                batch: Some(BatchDef {
                    config,
                    broadcast,
                    handler,
                }),
            },
            standalone: self.standalone,
            _types: PhantomData,
        }
    }
}

/// A declared task: register it on a worker by itself, or add it to a
/// [`Workflow`](crate::Workflow).
#[must_use = "a declared task runs nothing until it is registered on a worker"]
pub struct Task<I, O> {
    pub(crate) def: TaskDef,
    pub(crate) standalone: WorkflowOptions,
    _types: PhantomData<fn(I) -> O>,
}

impl<I, O> fmt::Debug for Task<I, O> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Task")
            .field("name", &self.def.name)
            .field("parents", &self.def.parents)
            .finish_non_exhaustive()
    }
}

impl<I, O> Clone for Task<I, O> {
    fn clone(&self) -> Self {
        Self {
            def: self.def.clone(),
            standalone: self.standalone.clone(),
            _types: PhantomData,
        }
    }
}

impl<I, O> Task<I, O> {
    /// The task's name as declared.
    pub fn name(&self) -> &str {
        &self.def.name
    }

    /// Makes this task run after `parent` within a workflow. Call once per
    /// parent. The parent must be added to the same workflow.
    ///
    /// `parent` is taken by reference, so parents must be attached *before*
    /// the parent task is moved into the workflow (or cloned first):
    ///
    /// ```
    /// # use hatchet_client::{TaskBuilder, Workflow};
    /// let fetch = TaskBuilder::<(), u32>::new("fetch").handler(|_ctx, _input| async { Ok(1) });
    /// let report = TaskBuilder::<(), ()>::new("report")
    ///     .handler(|_ctx, _input| async { Ok(()) })
    ///     .parent(&fetch);
    /// let workflow = Workflow::new("pipeline").task(&fetch).task(&report);
    /// ```
    pub fn parent<PI, PO>(mut self, parent: &Task<PI, PO>) -> Self {
        self.def.parents.push(parent.def.name.clone());
        self
    }
}

#[cfg(test)]
mod tests {
    use super::super::Condition;
    use super::*;
    use serde::{Deserialize, Serialize};
    use serde_json::json;
    use std::time::Duration;

    #[derive(Deserialize, Serialize)]
    struct In {
        repo: String,
    }

    #[derive(Deserialize, Serialize, Debug, PartialEq)]
    struct Out {
        pr: Option<String>,
    }

    fn echo_task(name: &str) -> Task<In, Out> {
        TaskBuilder::<In, Out>::new(name).handler(|_ctx, input: In| async move {
            Ok(Out {
                pr: Some(input.repo),
            })
        })
    }

    #[test]
    fn builder_collects_task_options() {
        let task = TaskBuilder::<In, Out>::new("agent-run")
            .retries(3)
            .retry_backoff(2.0, 60)
            .execution_timeout(Duration::from_secs(7200))
            .schedule_timeout(Duration::from_secs(300))
            .concurrency(Concurrency::expr("input.device_id").max_runs(1))
            .rate_limit(RateLimit::new("github-api", 1))
            .worker_label("os", DesiredLabel::eq("macos").required())
            .handler(|_ctx, _input: In| async move { Ok(Out { pr: None }) });

        assert_eq!(task.name(), "agent-run");
        let options = &task.def.options;
        assert_eq!(options.retries, 3);
        assert_eq!(options.backoff, Some((2.0, 60)));
        assert_eq!(options.execution_timeout, Some(Duration::from_secs(7200)));
        assert_eq!(options.schedule_timeout, Some(Duration::from_secs(300)));
        assert_eq!(
            options.concurrency,
            [Concurrency::expr("input.device_id").max_runs(1)]
        );
        assert_eq!(options.rate_limits, [RateLimit::new("github-api", 1)]);
        assert_eq!(
            options.worker_labels["os"],
            DesiredLabel::eq("macos").required()
        );
        assert!(task.standalone.is_empty());
        assert!(task.def.parents.is_empty());
    }

    #[test]
    fn builder_collects_standalone_trigger_options() {
        let task = TaskBuilder::<In, Out>::new("nightly")
            .description("Nightly sweep")
            .version("v2")
            .on_events(["approval.granted", "approval.revoked"])
            .cron("0 * * * *")
            .cron("30 2 * * *")
            .cron_input(json!({"repo": "hatchet-rs"}))
            .default_priority(Priority::High)
            .handler(|_ctx, _input: In| async move { Ok(Out { pr: None }) });

        let standalone = &task.standalone;
        assert!(!standalone.is_empty());
        assert_eq!(standalone.description.as_deref(), Some("Nightly sweep"));
        assert_eq!(standalone.version.as_deref(), Some("v2"));
        assert_eq!(
            standalone.on_events,
            ["approval.granted", "approval.revoked"]
        );
        assert_eq!(standalone.on_crons, ["0 * * * *", "30 2 * * *"]);
        assert_eq!(standalone.cron_input, Some(json!({"repo": "hatchet-rs"})));
        assert_eq!(standalone.default_priority, Some(Priority::High));
    }

    #[test]
    fn builder_collects_conditions_per_gate_and_accumulates() {
        let task = TaskBuilder::<In, Out>::new("gated")
            .wait_for(Condition::sleep(Duration::from_secs(5)))
            .wait_for(Condition::on_event("go"))
            .skip_if(Condition::on_event("skip"))
            .cancel_if(Condition::on_event("stop"))
            .handler(|_ctx, _input: In| async move { Ok(Out { pr: None }) });

        let options = &task.def.options;
        assert_eq!(
            options.wait_for,
            ConditionSet::from(Condition::sleep(Duration::from_secs(5)))
                .and(Condition::on_event("go")),
            "repeated calls accumulate rather than replace"
        );
        assert_eq!(options.skip_if, Condition::on_event("skip").into());
        assert_eq!(options.cancel_if, Condition::on_event("stop").into());
    }

    #[test]
    fn a_task_without_conditions_has_three_empty_gates() {
        let task = echo_task("plain");
        assert!(task.def.options.wait_for.is_empty());
        assert!(task.def.options.skip_if.is_empty());
        assert!(task.def.options.cancel_if.is_empty());
    }

    #[test]
    fn parents_are_recorded_by_name_across_input_and_output_types() {
        let a = echo_task("fetch");
        let b =
            TaskBuilder::<(), u32>::new("count").handler(|_ctx, _input: ()| async move { Ok(1) });
        let c = echo_task("report").parent(&a).parent(&b);
        assert_eq!(c.def.parents, ["fetch", "count"]);
    }

    #[tokio::test]
    async fn erased_handler_round_trips_json() {
        let task = echo_task("agent-run");
        let output = (task.def.handler)(Context::placeholder(), json!({"repo": "hatchet-rs"}))
            .await
            .unwrap();
        assert_eq!(output, json!({"pr": "hatchet-rs"}));
    }

    #[tokio::test]
    async fn input_of_the_wrong_shape_is_a_non_retryable_error() {
        let task = echo_task("agent-run");
        let error = (task.def.handler)(Context::placeholder(), json!({"repo": 42}))
            .await
            .unwrap_err();
        assert!(!error.is_retryable());
        assert!(error.message().contains("input"), "{error}");
    }

    #[tokio::test]
    async fn handler_errors_pass_through_unchanged() {
        let task = TaskBuilder::<In, Out>::new("fails")
            .handler(|_ctx, _input: In| async move { Err(TaskError::non_retryable("nope")) });
        let error = (task.def.handler)(Context::placeholder(), json!({"repo": "x"}))
            .await
            .unwrap_err();
        assert_eq!(error, TaskError::non_retryable("nope"));
    }

    #[tokio::test]
    async fn output_that_cannot_be_serialized_is_a_non_retryable_error() {
        use std::collections::HashMap;
        // JSON object keys must be strings; a tuple key cannot be serialized.
        let task = TaskBuilder::<(), HashMap<(i32, i32), i32>>::new("bad-output")
            .handler(|_ctx, _input: ()| async move { Ok(HashMap::from([((1, 2), 3)])) });
        let error = (task.def.handler)(Context::placeholder(), json!(null))
            .await
            .unwrap_err();
        assert!(!error.is_retryable());
        assert!(error.message().contains("output"), "{error}");
    }

    #[test]
    fn debug_names_the_declaration_and_says_it_is_not_all_of_it() {
        let builder = TaskBuilder::<In, Out>::new("agent-run").retries(3);
        let debug = format!("{builder:?}");
        assert!(debug.starts_with("TaskBuilder"), "{debug}");
        assert!(debug.contains("agent-run"), "{debug}");
        assert!(debug.contains(".."), "{debug}");

        let task = echo_task("report").parent(&echo_task("fetch"));
        let debug = format!("{task:?}");
        assert!(debug.starts_with("Task"), "{debug}");
        assert!(debug.contains("report"), "{debug}");
        assert!(debug.contains("fetch"), "{debug}");
        assert!(debug.contains(".."), "{debug}");
    }

    /// A `START_BATCH` for two members, shaped as a real engine sends one.
    fn batch_action(items: &[(&str, Value)]) -> AssignedAction {
        let payload: serde_json::Map<String, Value> = items
            .iter()
            .map(|(id, input)| {
                (
                    (*id).to_string(),
                    json!({"workflow_run_id": format!("{id}-run"), "payload": {"input": input}}),
                )
            })
            .collect();
        AssignedAction {
            action_payload: Value::Object(payload).to_string(),
            batch_id: Some("b-1".to_string()),
            ..AssignedAction::default()
        }
    }

    async fn run_batch(task: &Task<u32, u32>, action: &AssignedAction) -> BTreeMap<String, Value> {
        let handler = task
            .def
            .batch
            .as_ref()
            .expect("a batch task")
            .handler
            .clone();
        let report = handler(Context::placeholder(), action.clone())
            .await
            .expect("the batch handler answered");
        report
            .into_iter()
            .map(|(id, result)| {
                (
                    id,
                    match result {
                        Ok(value) => value,
                        Err(error) => json!({"failed": error.message()}),
                    },
                )
            })
            .collect()
    }

    #[test]
    fn a_batch_task_carries_its_config_and_says_it_is_not_a_broadcast() {
        let task = TaskBuilder::<u32, u32>::new("double").batch_handler(
            BatchConfig::max_size(4).group_key("input.tenant"),
            |_ctx, _batch| async move { Ok(BatchOutput::new()) },
        );
        let batch = task.def.batch.as_ref().expect("a batch task");
        assert!(!batch.broadcast);
        assert_eq!(
            batch.config,
            BatchConfig::max_size(4).group_key("input.tenant")
        );
        assert!(!task.def.durable, "a batch task asks for a default slot");
    }

    #[tokio::test]
    async fn a_batch_handler_is_called_once_and_answers_for_every_member() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let seen = Arc::clone(&calls);
        let task = TaskBuilder::<u32, u32>::new("double").batch_handler(
            BatchConfig::max_size(4),
            move |_ctx, batch: BatchInput<u32>| {
                let seen = Arc::clone(&seen);
                async move {
                    seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    Ok(batch.iter().map(|(id, n)| (id.clone(), n * 2)).collect())
                }
            },
        );

        let report = run_batch(&task, &batch_action(&[("a", json!(1)), ("b", json!(2))])).await;

        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
        assert_eq!(
            report,
            BTreeMap::from([("a".to_string(), json!(2)), ("b".to_string(), json!(4))]),
        );
    }

    /// The difference from both official SDKs: the members that were answered
    /// keep their outputs, and only the omitted one fails.
    #[tokio::test]
    async fn a_member_the_handler_leaves_out_fails_alone() {
        let task = TaskBuilder::<u32, u32>::new("double").batch_handler(
            BatchConfig::max_size(4),
            |_ctx, batch: BatchInput<u32>| async move {
                Ok(BatchOutput::new().ok(batch.ids().next().unwrap().clone(), 10))
            },
        );

        let report = run_batch(&task, &batch_action(&[("a", json!(1)), ("b", json!(2))])).await;

        assert_eq!(report["a"], json!(10));
        assert!(
            report["b"]["failed"]
                .as_str()
                .unwrap()
                .contains("no output"),
            "{report:?}"
        );
    }

    #[tokio::test]
    async fn a_member_whose_input_is_of_the_wrong_type_never_reaches_the_handler() {
        let task = TaskBuilder::<u32, u32>::new("double").batch_handler(
            BatchConfig::max_size(4),
            |_ctx, batch: BatchInput<u32>| async move {
                assert_eq!(batch.len(), 1, "only the decodable member is shown");
                Ok(batch.iter().map(|(id, n)| (id.clone(), n * 2)).collect())
            },
        );

        let report = run_batch(
            &task,
            &batch_action(&[("a", json!(1)), ("b", json!("not a number"))]),
        )
        .await;

        assert_eq!(report["a"], json!(2));
        assert!(
            report["b"]["failed"]
                .as_str()
                .unwrap()
                .contains("input type"),
            "{report:?}"
        );
    }

    #[tokio::test]
    async fn a_broadcast_handler_gives_every_member_the_same_value() {
        let task = TaskBuilder::<u32, u32>::new("warm").batch_broadcast_handler(
            BatchConfig::max_size(4),
            |_ctx, batch: BatchInput<u32>| async move { Ok(u32::try_from(batch.len()).unwrap()) },
        );

        assert!(task.def.batch.as_ref().unwrap().broadcast);
        let report = run_batch(&task, &batch_action(&[("a", json!(1)), ("b", json!(2))])).await;
        assert_eq!(
            report,
            BTreeMap::from([("a".to_string(), json!(2)), ("b".to_string(), json!(2))]),
        );
    }

    #[tokio::test]
    async fn a_batch_handler_that_fails_says_nothing_about_any_member() {
        let task = TaskBuilder::<u32, u32>::new("double").batch_handler(
            BatchConfig::max_size(4),
            |_ctx, _batch: BatchInput<u32>| async move { Err(TaskError::new("the api is down")) },
        );

        let handler = task.def.batch.as_ref().unwrap().handler.clone();
        let error = handler(Context::placeholder(), batch_action(&[("a", json!(1))]))
            .await
            .unwrap_err();

        // Whose failure it is cannot be told from here: the runner fails every
        // member with it.
        assert_eq!(error, TaskError::new("the api is down"));
    }

    /// The stub: an engine that took the registration and ignored the batch
    /// config assigns ordinary runs, and they must fail loudly rather than
    /// running a whole-batch handler against one input.
    #[tokio::test]
    async fn a_batch_task_assigned_as_an_ordinary_run_fails_by_name() {
        let task = TaskBuilder::<u32, u32>::new("double").batch_handler(
            BatchConfig::max_size(4),
            |_ctx, _batch: BatchInput<u32>| async move { Ok(BatchOutput::new()) },
        );

        let error = (task.def.handler)(Context::placeholder(), json!(1))
            .await
            .unwrap_err();

        assert!(!error.is_retryable(), "{error}");
        assert!(error.message().contains("double"), "{error}");
        assert!(error.message().contains("batch task"), "{error}");
    }

    #[test]
    fn tasks_are_cheap_to_clone_and_share_the_handler() {
        let task = echo_task("agent-run");
        let clone = task.clone();
        assert!(Arc::ptr_eq(&task.def.handler, &clone.def.handler));
    }
}