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
//! Batch tasks: the items one `START_BATCH` carries, and the per-item results
//! a handler answers with.
//!
//! A batch task is an ordinary task that the engine **buffers**: concurrent
//! runs of it are held until the batch fills up or its interval runs out, and
//! the whole group is then handed to one worker as a single action. The handler
//! is called **once** with every buffered input and answers with one output per
//! input, keyed by [`BatchMemberId`].
//!
//! Declare one with
//! [`TaskBuilder::batch_handler`](crate::TaskBuilder::batch_handler) or
//! [`batch_broadcast_handler`](crate::TaskBuilder::batch_broadcast_handler) and
//! a [`BatchConfig`](crate::BatchConfig).
//!
//! The rules a batch handler lives by:
//!
//! * it is called **once** per batch, with every buffered input;
//! * every member needs an answer — one left out of the [`BatchOutput`] is
//!   reported failed, because the run behind it is waiting;
//! * a member's failure is that member's alone; an error or panic out of
//!   the handler itself fails **all** of them;
//! * the batch is one unit of work for the worker: it takes one slot, not
//!   one per member.

use std::collections::BTreeMap;

use hatchet_proto::root::AssignedAction;
use serde::Deserialize;
use serde::de::DeserializeOwned;
use serde_json::Value;

use crate::TaskError;

/// Identifies one buffered run inside a batch: the **task run external id** of
/// that run, which is how the engine keys the items it sends.
///
/// A plain `String` alias, exactly as the official Go SDK defines it
/// (`sdks/go/batch.go:5-7`), so the ids a handler reads out of a [`BatchInput`]
/// go straight back into a [`BatchOutput`] without conversion.
pub type BatchMemberId = String;

/// What a batch handler ends up reporting: one outcome per member, already
/// serialized.
pub(crate) type BatchReport = BTreeMap<BatchMemberId, Result<Value, TaskError>>;

/// One buffered item as the engine sends it.
///
/// The value of each entry in the `START_BATCH` action payload. The engine
/// sends the **whole** ordinary action payload under `payload` — `input`,
/// `parents`, `triggers`, `overrides`, `user_data`, `triggered_by` — and this
/// reads the two parts a batch handler can use; the rest is ignored, as it is
/// by the official Go and Python SDKs.
#[derive(Deserialize)]
struct WireItem {
    #[serde(default)]
    workflow_run_id: String,
    #[serde(default)]
    payload: WirePayload,
}

/// The `payload` of one buffered item, of which only `input` is read.
#[derive(Default, Deserialize)]
struct WirePayload {
    #[serde(default)]
    input: Value,
}

/// One member of a [`BatchInput`]: its input, and the workflow run it came
/// from.
#[derive(Clone, Debug)]
pub struct BatchItem<I> {
    input: I,
    workflow_run_id: String,
}

impl<I> BatchItem<I> {
    /// The buffered run's input.
    #[must_use]
    pub fn input(&self) -> &I {
        &self.input
    }

    /// The workflow run this item belongs to, as the engine sent it alongside
    /// the input. The only per-item identifier a batch carries besides the
    /// [`BatchMemberId`] itself.
    #[must_use]
    pub fn workflow_run_id(&self) -> &str {
        &self.workflow_run_id
    }

    /// Takes the input, dropping the rest.
    #[must_use]
    pub fn into_input(self) -> I {
        self.input
    }
}

/// The buffered inputs of one batch, keyed by [`BatchMemberId`].
///
/// Iteration is in id order and stable: the items live in a `BTreeMap`, so a
/// handler that folds over a batch sees the same order every time.
///
/// **Everything batch-specific is here, not on the [`Context`](crate::Context)
/// the handler is given.** A `START_BATCH` carries no per-run identifiers at
/// all — measured on v0.98.0 through v0.107.0, `task_run_external_id`,
/// `workflow_run_id`, `job_id`, `job_run_id`, `job_name`, `task_id` and
/// `task_name` all arrive as **empty strings** and `retry_count` as `0` — so
/// `Context::task_run_id`, `Context::workflow_run_id` and
/// `Context::retry_count` are empty rather than pointing at some arbitrary
/// member. Use [`items`](Self::items) for a member's workflow run, and
/// [`batch_id`](Self::batch_id) for something to put in a log line.
#[derive(Clone, Debug)]
pub struct BatchInput<I> {
    batch_id: Option<String>,
    batch_key: Option<String>,
    batch_index: Option<i32>,
    batch_size: Option<i32>,
    trigger_reason: Option<String>,
    expected_size: Option<i32>,
    items: BTreeMap<BatchMemberId, BatchItem<I>>,
}

impl<I: DeserializeOwned> BatchInput<I> {
    /// Types the items of one `START_BATCH`.
    ///
    /// An item whose input does not deserialize into `I` is **not** passed to
    /// the handler: it comes back in the second half of the pair as a
    /// non-retryable failure of its own, so one malformed input cannot take the
    /// rest of the batch down with it.
    ///
    /// # Errors
    ///
    /// [`TaskError::non_retryable`] when the action payload is not a JSON
    /// object of items — there is then no member id to report anything
    /// against, so the batch as a whole has failed.
    pub(crate) fn decode(action: &AssignedAction) -> Result<(Self, BatchReport), TaskError> {
        let start = action.batch_start_payload.as_ref();
        let mut decoded = Self {
            batch_id: action.batch_id.clone(),
            batch_key: action.batch_key.clone(),
            batch_index: action.batch_index,
            batch_size: action.batch_size,
            trigger_reason: start
                .map(|start| start.trigger_reason.clone())
                .filter(|reason| !reason.is_empty()),
            expected_size: start.map(|start| start.expected_size),
            items: BTreeMap::new(),
        };
        let mut rejected = BatchReport::new();

        // An empty payload is an empty batch, not a malformed one: the official
        // Go SDK skips parsing altogether in that case
        // (`pkg/client/action_listener.go:272-279`).
        if action.action_payload.trim().is_empty() {
            return Ok((decoded, rejected));
        }
        let wire: BTreeMap<BatchMemberId, WireItem> = serde_json::from_str(&action.action_payload)
            .map_err(|e| {
                TaskError::non_retryable(format!(
                    "the batch action payload is not a JSON object of items keyed by task run \
                     id: {e}"
                ))
            })?;

        for (id, item) in wire {
            match serde_json::from_value::<I>(item.payload.input) {
                Ok(input) => {
                    decoded.items.insert(
                        id,
                        BatchItem {
                            input,
                            workflow_run_id: item.workflow_run_id,
                        },
                    );
                }
                Err(e) => {
                    rejected.insert(
                        id,
                        Err(TaskError::non_retryable(format!(
                            "the input does not match the task's input type: {e}"
                        ))),
                    );
                }
            }
        }
        Ok((decoded, rejected))
    }
}

impl<I> BatchInput<I> {
    /// How many items the handler was given.
    ///
    /// Items whose input did not deserialize into `I` are not counted: they
    /// never reach the handler and have already failed on their own.
    #[must_use]
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Whether the batch has no item the handler can read.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Every member's id and input, in id order.
    pub fn iter(&self) -> impl Iterator<Item = (&BatchMemberId, &I)> {
        self.items.iter().map(|(id, item)| (id, &item.input))
    }

    /// Every member, in id order, with the workflow run it came from.
    pub fn items(&self) -> impl Iterator<Item = (&BatchMemberId, &BatchItem<I>)> {
        self.items.iter()
    }

    /// Every member id, in order.
    pub fn ids(&self) -> impl Iterator<Item = &BatchMemberId> {
        self.items.keys()
    }

    /// One member's input, if the batch has it.
    #[must_use]
    pub fn get(&self, id: &str) -> Option<&I> {
        self.items.get(id).map(|item| &item.input)
    }

    /// The engine's id for this batch, for logs and traces.
    #[must_use]
    pub fn batch_id(&self) -> Option<&str> {
        self.batch_id.as_deref()
    }

    /// The partition this batch was grouped into: the **value** a
    /// [`BatchConfig::group_key`](crate::BatchConfig::group_key) expression
    /// evaluated to, such as `"acme"` for `"input.tenant"`. Engines send the
    /// literal `"default"` when the task declared no group key.
    #[must_use]
    pub fn batch_key(&self) -> Option<&str> {
        self.batch_key.as_deref()
    }

    /// Why the engine handed this batch over now, in the engine's own words.
    ///
    /// Two forms were measured on v0.98.0 through v0.107.0: `"batch size
    /// threshold 5 reached"` and `"batch max interval 5s elapsed"`. It is a
    /// human-readable string that the engine may change — log it, do not parse
    /// it.
    #[must_use]
    pub fn trigger_reason(&self) -> Option<&str> {
        self.trigger_reason.as_deref()
    }

    /// How many items the engine put in this batch.
    ///
    /// The count actually buffered, not the configured
    /// [`max_size`](crate::BatchConfig::max_size): a batch flushed on its
    /// interval reports what it managed to collect. It may still be larger than
    /// [`len`](Self::len), which leaves out the items whose input did not
    /// deserialize into `I`.
    #[must_use]
    pub fn expected_size(&self) -> Option<i32> {
        self.expected_size
    }

    /// This batch's index, as the engine numbers them.
    ///
    /// **Always `None` in practice.** The field exists on the wire, but no
    /// engine measured (v0.98.0 through v0.107.0) has ever set it. Use
    /// [`batch_id`](Self::batch_id) to tell batches apart.
    #[must_use]
    pub fn batch_index(&self) -> Option<i32> {
        self.batch_index
    }

    /// How many items the engine says are in this batch, as the assignment's
    /// own field rather than the start payload's.
    ///
    /// **Always `None` in practice**, even for a batch that filled up: no
    /// engine measured (v0.98.0 through v0.107.0) sets it. Use
    /// [`expected_size`](Self::expected_size) for the engine's count and
    /// [`len`](Self::len) for what the handler was actually given.
    #[must_use]
    pub fn batch_size(&self) -> Option<i32> {
        self.batch_size
    }
}

/// One output per batch member, as a batch handler answers.
///
/// Every member of the [`BatchInput`] needs an entry. A member left out is
/// reported **failed**, with a message saying the handler omitted it: measured
/// against a real engine, a member that is never reported stays `Running` for
/// as long as the task's timeout allows and is never assigned again, so
/// silence is the one outcome that must not be possible. Entries for ids that
/// were not in the batch are dropped with a warning.
///
/// ```
/// use hatchet_client::{BatchOutput, TaskError};
///
/// let output = BatchOutput::new()
///     .ok("018f-a", 42)
///     .fail("018f-b", TaskError::non_retryable("no such account"));
/// assert_eq!(output.len(), 2);
/// ```
#[must_use = "a batch output is the handler's answer; return it"]
#[derive(Clone, Debug)]
pub struct BatchOutput<O> {
    items: BTreeMap<BatchMemberId, Result<O, TaskError>>,
}

impl<O> BatchOutput<O> {
    /// An empty answer, to be filled in with [`ok`](Self::ok) and
    /// [`fail`](Self::fail).
    pub fn new() -> Self {
        Self {
            items: BTreeMap::new(),
        }
    }

    /// This member's run succeeded with `value`.
    ///
    /// Answering for the same id twice keeps the last answer.
    pub fn ok(mut self, id: impl Into<BatchMemberId>, value: O) -> Self {
        self.items.insert(id.into(), Ok(value));
        self
    }

    /// This member's run failed. Whether the engine retries it follows
    /// [`TaskError::non_retryable`], exactly as for an ordinary task.
    pub fn fail(mut self, id: impl Into<BatchMemberId>, error: TaskError) -> Self {
        self.items.insert(id.into(), Err(error));
        self
    }

    /// How many members have an answer.
    #[must_use]
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Whether no member has an answer yet.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    pub(crate) fn into_items(self) -> BTreeMap<BatchMemberId, Result<O, TaskError>> {
        self.items
    }
}

impl<O> Default for BatchOutput<O> {
    fn default() -> Self {
        Self::new()
    }
}

/// Collects a handler's per-member results, so the common shape is one line:
/// `batch.iter().map(|(id, input)| (id.clone(), f(input))).collect()`.
///
/// ```
/// use hatchet_client::{BatchMemberId, BatchOutput};
///
/// let lengths: BatchOutput<usize> = [("a".to_string(), "xy"), ("b".to_string(), "xyz")]
///     .into_iter()
///     .map(|(id, text): (BatchMemberId, &str)| (id, text.len()))
///     .collect();
/// assert_eq!(lengths.len(), 2);
/// ```
impl<O> FromIterator<(BatchMemberId, O)> for BatchOutput<O> {
    fn from_iter<T: IntoIterator<Item = (BatchMemberId, O)>>(iter: T) -> Self {
        Self {
            items: iter
                .into_iter()
                .map(|(id, value)| (id, Ok(value)))
                .collect(),
        }
    }
}

/// Folds what the handler answered into `report`, which already holds the
/// members whose input could not be decoded.
///
/// This is the whole of reconciliation, and it runs on the worker rather than
/// being left to the engine, because the engine leaves an unreported member
/// `Running` for ever. `members` is every id the handler was shown.
pub(crate) fn reconcile<O: serde::Serialize>(
    task: &str,
    members: &[BatchMemberId],
    answered: BTreeMap<BatchMemberId, Result<O, TaskError>>,
    report: &mut BatchReport,
) {
    for (id, result) in answered {
        if !members.contains(&id) && !report.contains_key(&id) {
            // Not a member of this batch: reporting it would name a run this
            // action says nothing about.
            tracing::warn!(
                task,
                member = %id,
                "a batch handler answered for an id that was not in the batch; dropping it",
            );
            continue;
        }
        let value = result.and_then(|value| {
            serde_json::to_value(value).map_err(|e| {
                TaskError::non_retryable(format!("the output could not be serialized to JSON: {e}"))
            })
        });
        report.insert(id, value);
    }
    for id in members {
        if report.contains_key(id) {
            continue;
        }
        tracing::warn!(
            task,
            member = %id,
            "a batch handler returned no output for one of its members; failing it",
        );
        report.insert(
            id.clone(),
            Err(TaskError::non_retryable(format!(
                "the batch handler of `{task}` returned no output for this member of the batch; \
                 a member that is never reported is left running by the engine until it times \
                 out, so it is failed here instead"
            ))),
        );
    }
}

/// Every member a `START_BATCH` names, in id order, whether or not its item can
/// be read.
///
/// The worker needs the ids before it knows whether anything else about the
/// batch makes sense: a handler that panics, or a payload whose items are of
/// some shape this SDK cannot read, still has to be answered for — a member the
/// engine never hears about is left `Running` until it times out. Only the keys
/// are read here, so an item this SDK could not parse still yields the id of
/// the run behind it.
///
/// A payload that is not a JSON object at all names nobody, and the batch has
/// to be dropped: there is no run to report anything against.
pub(crate) fn member_ids(action: &AssignedAction) -> Vec<BatchMemberId> {
    let raw = action.action_payload.trim();
    if raw.is_empty() {
        return Vec::new();
    }
    match serde_json::from_str::<BTreeMap<BatchMemberId, serde::de::IgnoredAny>>(raw) {
        Ok(items) => items.into_keys().collect(),
        Err(_) => Vec::new(),
    }
}

/// Every member fails the same way: the handler returned an error or panicked,
/// or the batch payload could not be read at all.
pub(crate) fn fail_all(members: &[BatchMemberId], error: &TaskError) -> BatchReport {
    members
        .iter()
        .map(|id| (id.clone(), Err(error.clone())))
        .collect()
}

/// The key a batch is booked under in the runner's ledger of runs in flight.
///
/// A `START_BATCH` carries no `task_run_external_id` — every scalar identifier
/// on it is an empty string — so the engine's batch id stands in, prefixed so
/// that it can never collide with a run's own id. One consequence is
/// deliberate: a cancellation naming a **single member** matches no entry and
/// is ignored, because a member of a batch that is already running cannot be
/// cancelled on its own. Shutdown still reaches the batch, which is cancelled
/// as a whole like any other run.
///
/// The counter is only for the batch an engine sent without an id, which no
/// measured engine does: two such batches must still be told apart, or the
/// second would cancel the first.
pub(crate) fn run_key(action: &AssignedAction) -> String {
    use std::sync::atomic::{AtomicU64, Ordering};

    static NEXT: AtomicU64 = AtomicU64::new(1);
    match action.batch_id.as_deref() {
        Some(id) if !id.is_empty() => format!("batch:{id}"),
        _ => format!("batch:anonymous:{}", NEXT.fetch_add(1, Ordering::Relaxed)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use hatchet_proto::root::BatchStartPayload;
    use serde_json::json;

    /// An action shaped exactly as a real engine sends one: the payload is a
    /// map keyed by task run id whose values carry the *whole* ordinary action
    /// payload under `payload`.
    fn 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,
                            "parents": {},
                            "triggers": {"filter_payload": null},
                            "overrides": null,
                            "user_data": null,
                            "triggered_by": "manual",
                        },
                    }),
                )
            })
            .collect();
        AssignedAction {
            action_id: "dev_t:t".to_string(),
            action_payload: Value::Object(payload).to_string(),
            batch_id: Some("b-1".to_string()),
            batch_key: Some("acme".to_string()),
            batch_start_payload: Some(BatchStartPayload {
                trigger_reason: "batch size threshold 2 reached".to_string(),
                trigger_time: None,
                expected_size: i32::try_from(items.len()).unwrap(),
            }),
            ..AssignedAction::default()
        }
    }

    #[test]
    fn decoding_types_every_item_and_keeps_the_ids() {
        let (input, rejected) =
            BatchInput::<u32>::decode(&action(&[("a", json!(1)), ("b", json!(2))])).unwrap();

        assert!(rejected.is_empty());
        assert_eq!(input.len(), 2);
        assert!(!input.is_empty());
        assert_eq!(input.get("a"), Some(&1));
        assert_eq!(input.get("missing"), None);
        assert_eq!(
            input
                .iter()
                .map(|(id, value)| (id.as_str(), *value))
                .collect::<Vec<_>>(),
            vec![("a", 1), ("b", 2)],
        );
        assert_eq!(
            input.ids().map(String::as_str).collect::<Vec<_>>(),
            vec!["a", "b"],
        );
        assert_eq!(
            input
                .items()
                .map(|(_, item)| item.workflow_run_id())
                .collect::<Vec<_>>(),
            vec!["a-run", "b-run"],
        );
    }

    #[test]
    fn decoding_carries_the_batch_wide_facts_and_says_what_the_engine_never_sends() {
        let (input, _) = BatchInput::<u32>::decode(&action(&[("a", json!(1))])).unwrap();

        assert_eq!(input.batch_id(), Some("b-1"));
        assert_eq!(input.batch_key(), Some("acme"));
        assert_eq!(
            input.trigger_reason(),
            Some("batch size threshold 2 reached")
        );
        assert_eq!(input.expected_size(), Some(1));
        // Measured: no engine fills these in, on any version that batches.
        assert_eq!(input.batch_index(), None);
        assert_eq!(input.batch_size(), None);
    }

    #[test]
    fn a_nested_input_survives_the_round_trip() {
        let (input, _) = BatchInput::<Value>::decode(&action(&[(
            "a",
            json!({"n": 0, "nested": {"k": [1, 2]}}),
        )]))
        .unwrap();
        assert_eq!(
            input.get("a"),
            Some(&json!({"n": 0, "nested": {"k": [1, 2]}}))
        );
    }

    /// One malformed input must not cost the other members their outputs: they
    /// are independent runs that happened to be buffered together.
    #[test]
    fn an_item_that_does_not_match_the_input_type_fails_alone() {
        let (input, rejected) =
            BatchInput::<u32>::decode(&action(&[("a", json!(1)), ("b", json!("not a number"))]))
                .unwrap();

        assert_eq!(input.len(), 1);
        assert!(input.get("b").is_none());
        let error = rejected
            .get("b")
            .expect("b was rejected")
            .as_ref()
            .unwrap_err();
        assert!(!error.is_retryable(), "{error}");
        assert!(error.message().contains("input type"), "{error}");
    }

    #[test]
    fn an_empty_payload_is_an_empty_batch_and_a_malformed_one_is_an_error() {
        let empty = AssignedAction {
            action_payload: String::new(),
            ..AssignedAction::default()
        };
        let (input, rejected) = BatchInput::<u32>::decode(&empty).unwrap();
        assert!(input.is_empty());
        assert!(rejected.is_empty());
        assert_eq!(input.batch_id(), None);
        assert_eq!(input.trigger_reason(), None);
        assert_eq!(input.expected_size(), None);

        let malformed = AssignedAction {
            action_payload: "[1, 2]".to_string(),
            ..AssignedAction::default()
        };
        let error = BatchInput::<u32>::decode(&malformed).unwrap_err();
        assert!(!error.is_retryable(), "{error}");
        assert!(error.message().contains("JSON object of items"), "{error}");
    }

    #[test]
    fn an_output_is_collected_or_built() {
        let built = BatchOutput::new()
            .ok("a", 1)
            .fail("b", TaskError::new("no"));
        assert_eq!(built.len(), 2);
        assert!(!built.is_empty());
        assert!(BatchOutput::<u32>::default().is_empty());

        let collected: BatchOutput<u32> = [("a".to_string(), 1), ("b".to_string(), 2)]
            .into_iter()
            .collect();
        assert_eq!(collected.len(), 2);
        assert_eq!(
            collected.into_items().get("a").unwrap().as_ref().unwrap(),
            &1
        );
    }

    #[test]
    fn answering_for_a_member_twice_keeps_the_last_answer() {
        let output = BatchOutput::new().ok("a", 1).ok("a", 2);
        assert_eq!(output.len(), 1);
        assert_eq!(output.into_items().get("a").unwrap().as_ref().unwrap(), &2);
    }

    #[test]
    fn reconciling_fails_the_members_the_handler_left_out_and_drops_strangers() {
        let members = vec!["a".to_string(), "b".to_string()];
        let mut report = BatchReport::new();
        let answered = BTreeMap::from([
            ("a".to_string(), Ok(1_u32)),
            ("stranger".to_string(), Ok(9)),
        ]);

        reconcile("t", &members, answered, &mut report);

        assert_eq!(report.len(), 2, "the stranger is not reported: {report:?}");
        assert_eq!(report["a"].as_ref().unwrap(), &json!(1));
        let omitted = report["b"].as_ref().unwrap_err();
        assert!(!omitted.is_retryable(), "{omitted}");
        assert!(omitted.message().contains("no output"), "{omitted}");
    }

    #[test]
    fn reconciling_keeps_an_already_rejected_member_and_its_own_answer() {
        let members = vec!["a".to_string()];
        let mut report = BatchReport::from([(
            "bad".to_string(),
            Err(TaskError::non_retryable("the input does not match")),
        )]);
        // The handler never saw `bad`, but an answer for it is still honoured
        // rather than dropped as a stranger: it names a real member of the
        // batch.
        let answered = BTreeMap::from([
            ("a".to_string(), Err(TaskError::new("retry me"))),
            ("bad".to_string(), Ok(1_u32)),
        ]);

        reconcile("t", &members, answered, &mut report);

        assert!(report["a"].as_ref().unwrap_err().is_retryable());
        assert_eq!(report["bad"].as_ref().unwrap(), &json!(1));
    }

    /// The ids come off the payload's keys alone, so a batch whose items this
    /// SDK cannot read still has someone to report to.
    #[test]
    fn the_members_are_named_even_when_their_items_cannot_be_read() {
        assert_eq!(
            member_ids(&action(&[("b", json!(1)), ("a", json!(2))])),
            vec!["a".to_string(), "b".to_string()],
            "in id order, as the handler sees them",
        );

        let unreadable = AssignedAction {
            action_payload: json!({"a": 1, "b": "not an item"}).to_string(),
            ..AssignedAction::default()
        };
        assert_eq!(
            member_ids(&unreadable),
            vec!["a".to_string(), "b".to_string()],
        );

        for nobody in ["", "   ", "[1, 2]", "not json at all", "null"] {
            let action = AssignedAction {
                action_payload: nobody.to_string(),
                ..AssignedAction::default()
            };
            assert!(member_ids(&action).is_empty(), "{nobody:?}");
        }
    }

    #[test]
    fn failing_the_whole_batch_gives_every_member_the_same_error() {
        let members = vec!["a".to_string(), "b".to_string()];
        let report = fail_all(&members, &TaskError::non_retryable("the model is down"));

        assert_eq!(report.len(), 2);
        for id in &members {
            let error = report[id].as_ref().unwrap_err();
            assert_eq!(error.message(), "the model is down");
            assert!(!error.is_retryable());
        }
        // Retryability is the handler's to decide, not this function's.
        let retryable = fail_all(&members, &TaskError::new("try again"));
        assert!(retryable["a"].as_ref().unwrap_err().is_retryable());
    }

    #[test]
    fn a_batch_is_booked_under_its_batch_id() {
        assert_eq!(run_key(&action(&[("a", json!(1))])), "batch:b-1");

        // No engine measured leaves the id out, but two batches that did would
        // still have to be told apart.
        let anonymous = AssignedAction::default();
        let first = run_key(&anonymous);
        assert!(first.starts_with("batch:anonymous:"), "{first}");
        assert_ne!(first, run_key(&anonymous));
    }

    #[test]
    fn an_output_that_cannot_be_serialized_fails_only_its_own_member() {
        use std::collections::HashMap;

        let members = vec!["a".to_string(), "b".to_string()];
        let mut report = BatchReport::new();
        let answered = BTreeMap::from([
            ("a".to_string(), Ok(HashMap::from([((1, 2), 3)]))),
            ("b".to_string(), Ok(HashMap::new())),
        ]);

        reconcile("t", &members, answered, &mut report);

        let error = report["a"].as_ref().unwrap_err();
        assert!(!error.is_retryable(), "{error}");
        assert!(error.message().contains("output"), "{error}");
        assert!(report["b"].is_ok());
    }
}