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
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
//! The context handed to a task handler.

mod wire;

use std::collections::{BTreeMap, HashMap};
use std::sync::atomic::{AtomicI32, AtomicI64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, SystemTime};

use hatchet_proto::prost_types::Timestamp;
use hatchet_proto::root::{
    AssignedAction, PutLogRequest, PutStreamEventRequest, RefreshTimeoutRequest,
    ReleaseSlotRequest, UpsertWorkerLabelsRequest,
};
use serde::Deserialize;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
use tokio::sync::OwnedSemaphorePermit;
use tokio_util::sync::CancellationToken;
use tonic::{Request, Response, Status};
use tracing::{Instrument, Span};

use crate::durable::DurableInvocation;
use crate::trigger::{ParentRef, RunOpts};
use crate::{Client, Error, LabelValue, Task, Workflow, otel, retry, trigger};

/// The level every [`Context::log`] line is filed under. The engine takes a
/// free-form string; a handler that wants levels of its own can put them in
/// the message.
const LOG_LEVEL: &str = "INFO";

/// What a running task knows about itself and can ask of the engine.
///
/// A handler receives its own context; cloning one is cheap and every clone
/// observes the same cancellation — and shares the counters behind
/// [`put_stream`](Context::put_stream) and [`spawn`](Context::spawn), so
/// handing a clone to a helper does not restart either sequence.
///
/// The calls a context makes to the engine do *not* observe the run's
/// cancellation: a cancelled run can still log, stream, and spawn, exactly as
/// it can in the official SDKs — it is up to the handler to check
/// [`is_cancelled`](Context::is_cancelled) and stop.
///
/// A handler is handed one; there is no way to build one yourself.
///
/// # In a batch handler
///
/// A batch task's handler is given a `Context` for the **batch**, not for any
/// one of the runs buffered into it, and the engine's `START_BATCH` carries no
/// per-run identifiers to build one from: measured on every engine that
/// batches (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
/// [`task_run_id`](Self::task_run_id),
/// [`workflow_run_id`](Self::workflow_run_id),
/// [`retry_count`](Self::retry_count), [`input_raw`](Self::input_raw),
/// [`parent_output`](Self::parent_output) and everything else that describes
/// one run are meaningless there — empty rather than some arbitrary member's —
/// and the calls that name a run to the engine ([`log`](Self::log),
/// [`put_stream`](Self::put_stream),
/// [`refresh_timeout`](Self::refresh_timeout),
/// [`release_slot`](Self::release_slot)) have no run to name. Everything about
/// the batch is on [`BatchInput`](crate::BatchInput) instead: its members and
/// their inputs, its id, its key, and why it was flushed.
///
/// What does work is what belongs to the batch as a whole:
/// [`action_id`](Self::action_id), [`worker_id`](Self::worker_id),
/// [`spawn`](Self::spawn) and the client accessors — and
/// [`is_cancelled`](Self::is_cancelled) and [`cancelled`](Self::cancelled),
/// which fire when the worker is shutting down. A cancelled batch reports no
/// outcome for any member, and one member of a running batch cannot be
/// cancelled on its own.
///
/// ```no_run
/// use std::time::Duration;
///
/// use hatchet_client::{Context, TaskBuilder, TaskError};
///
/// # fn example() {
/// let crunch = TaskBuilder::<u32, u32>::new("crunch").handler(
///     |ctx: Context, iterations: u32| async move {
///         for i in 0..iterations {
///             // A log line that does not reach the engine is not worth
///             // failing — and retrying — the whole task over, so no `?`.
///             if let Err(error) = ctx.log(format!("step {i}")).await {
///                 tracing::warn!(%error, "the log line was not delivered");
///             }
///             // Buy more time before the engine's timeout runs out.
///             ctx.refresh_timeout(Duration::from_secs(60)).await?;
///
///             tokio::select! {
///                 () = ctx.cancelled() => return Err(TaskError::new("cancelled")),
///                 () = tokio::time::sleep(Duration::from_secs(1)) => {}
///             }
///         }
///         Ok(iterations)
///     },
/// );
/// # let _ = crunch;
/// # }
/// ```
#[derive(Clone)]
pub struct Context {
    inner: Arc<Inner>,
}

/// A [`Context`]'s `Debug` output is deliberately thin: the task's input,
/// parent outputs, and additional metadata may carry secrets a handler was
/// given for its own use, not for a log line, so only identifying ids and
/// the retry count are shown.
impl std::fmt::Debug for Context {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Context")
            .field("workflow_run_id", &self.workflow_run_id())
            .field("task_run_id", &self.task_run_id())
            .field("action_id", &self.action_id())
            .field("retry_count", &self.retry_count())
            .field("cancelled", &self.is_cancelled())
            .finish()
    }
}

struct Inner {
    action: AssignedAction,
    payload: ActionPayload,
    /// `action.additional_metadata`, parsed once at construction so
    /// `additional_metadata()` can hand back a reference rather than
    /// reparsing (and re-failing) on every call.
    metadata: Map<String, Value>,
    worker_id: String,
    client: Option<Client>,
    cancel: CancellationToken,
    /// The worker slot this run occupies, so [`Context::release_slot`] can
    /// give it back while the handler carries on.
    slot: Slot,
    /// The durable invocation this run belongs to, for a durable action only.
    /// `None` for every ordinary run, which is what keeps
    /// [`DurableContext`](crate::DurableContext) out of an ordinary handler's
    /// reach.
    durable: Option<Arc<DurableInvocation>>,
    /// The `event_index` the next [`Context::put_stream`] claims. It lives
    /// here, behind the `Arc`, so every clone of a context numbers one
    /// sequence rather than one each.
    next_event_index: AtomicI64,
    /// The `child_index` the next [`Context::spawn`] claims, shared the same
    /// way. The engine deduplicates a retried parent's children on it, so the
    /// same handler code must produce the same indexes in the same order.
    next_child_index: AtomicI32,
}

/// The engine's `action_payload`, as far as this SDK reads it today. Unknown
/// fields are ignored so a newer engine does not break a running worker.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub(crate) struct ActionPayload {
    /// The task's own input.
    pub(crate) input: Value,
    /// Outputs of the parent tasks, by task name.
    #[serde(deserialize_with = "null_as_default")]
    pub(crate) parents: HashMap<String, Value>,
    /// Errors of the tasks that already failed in this run, by task name.
    /// Only an on-failure task's payload carries these; the values are
    /// whatever the SDK that ran the failing task reported, decoded once
    /// here (see [`decode_step_run_errors`]).
    #[serde(deserialize_with = "decode_step_run_errors")]
    pub(crate) step_run_errors: BTreeMap<String, String>,
}

/// Reads an explicit `null` as the type's default. The engine writes `null`
/// for payload keys it has nothing for (`"overrides": null`), and the
/// container's `#[serde(default)]` only covers a key that is absent.
fn null_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    D: serde::Deserializer<'de>,
    T: Default + Deserialize<'de>,
{
    Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
}

/// Decodes `step_run_errors` as the engine sends it. A real engine was
/// observed sending each value JSON-string-encoded — e.g.
/// `{"boom": "\"boom went the task\""}` — because the worker that ran the
/// failing task reports its failure message as a JSON string. A value that
/// parses as a JSON string is decoded to that string; anything else (plain
/// text, or JSON that is not a string) is kept verbatim.
fn decode_step_run_errors<'de, D>(deserializer: D) -> Result<BTreeMap<String, String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw: BTreeMap<String, String> = null_as_default(deserializer)?;
    Ok(raw
        .into_iter()
        .map(|(task, value)| {
            let decoded = serde_json::from_str::<String>(&value).unwrap_or(value);
            (task, decoded)
        })
        .collect())
}

/// The worker slot one run occupies, shared between the run itself and every
/// clone of its [`Context`].
///
/// The permit lives behind a mutex rather than in the run's own frame so that
/// either side can give it back: the handler early, through
/// [`Context::release_slot`], or the runner when the run ends. Whoever gets
/// there first takes the permit out; the other finds an empty slot and has
/// nothing to do, so the worker's semaphore can never be credited twice for
/// one run.
///
/// Cloning shares the same slot. A clone that outlives its run — one a
/// handler leaked into a detached task — therefore holds nothing, because the
/// runner empties the slot as the run ends rather than waiting for the last
/// clone to be dropped.
///
/// [`Slot::default`] is an empty one, for a context with no worker behind it.
#[derive(Clone, Default)]
pub(crate) struct Slot {
    permit: Arc<Mutex<Option<OwnedSemaphorePermit>>>,
}

impl Slot {
    /// A slot holding `permit` until someone releases it.
    pub(crate) fn holding(permit: OwnedSemaphorePermit) -> Self {
        Self {
            permit: Arc::new(Mutex::new(Some(permit))),
        }
    }

    /// Hands the permit back to the worker, if this slot still holds one.
    /// Calling it again is a no-op rather than a second release.
    pub(crate) fn release(&self) {
        // Taken out under the lock and dropped after it, so nothing else can
        // observe the slot as held while the permit is being given back.
        let permit = self
            .permit
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take();
        drop(permit);
    }
}

impl Context {
    /// Whether the engine has asked for this task to stop, or the worker is
    /// shutting down.
    pub fn is_cancelled(&self) -> bool {
        self.inner.cancel.is_cancelled()
    }

    /// Completes once this task is cancelled; never completes otherwise.
    ///
    /// Long-running handlers should select on this so a cancelled run stops
    /// promptly — the worker never aborts a handler outright.
    pub async fn cancelled(&self) {
        self.inner.cancel.cancelled().await;
    }
}

/// Read-only lookups over the task's own input, its parents' outputs, and
/// its identity. None of these talk to the engine — they only read what the
/// engine sent along with the action.
impl Context {
    /// The task's input, exactly as the engine sent it — before this SDK
    /// tries to deserialize it into the handler's typed input.
    pub fn input_raw(&self) -> &Value {
        self.input()
    }

    /// The typed output of a parent task in the same workflow, looked up
    /// through the [`Task`] handle itself so the return type is inferred
    /// from what `parent` actually produces.
    ///
    /// # Errors
    ///
    /// [`Error::ParentOutput`] when `parent` has no output recorded for this
    /// task (it is not declared as a parent, or has not run yet) or its
    /// recorded output does not deserialize into `O`.
    pub fn parent_output<PI, O>(&self, parent: &Task<PI, O>) -> crate::Result<O>
    where
        O: DeserializeOwned,
    {
        self.parent_output_by_name(parent.name())
    }

    /// Like [`Context::parent_output`], but looked up by name rather than by
    /// a [`Task`] handle — for a parent declared in another crate, where no
    /// handle is available to borrow.
    ///
    /// # Errors
    ///
    /// [`Error::ParentOutput`], on the same terms as
    /// [`Context::parent_output`]: no output is recorded under `task_name`,
    /// or it does not deserialize into `T`. A skipped parent (see
    /// [`Context::was_skipped`]) is reported the same way, with a reason that
    /// says so — check `was_skipped` first if that distinction matters to the
    /// caller.
    pub fn parent_output_by_name<T>(&self, task_name: &str) -> crate::Result<T>
    where
        T: DeserializeOwned,
    {
        let output = self
            .parents()
            .get(task_name)
            .ok_or_else(|| Error::ParentOutput {
                task: task_name.to_string(),
                reason: "no output is recorded for this task; check that it is declared as a \
                         parent and has run"
                    .to_string(),
            })?;
        if is_skipped(output) {
            return Err(Error::ParentOutput {
                task: task_name.to_string(),
                reason: "the task was skipped, so it produced no output; check \
                         `Context::was_skipped` before reading it"
                    .to_string(),
            });
        }
        serde_json::from_value(output.clone()).map_err(|error| Error::ParentOutput {
            task: task_name.to_string(),
            reason: error.to_string(),
        })
    }

    /// The errors of the tasks that failed before this one, by task name.
    ///
    /// Only a task declared with [`Workflow::on_failure`] receives these; for
    /// any other task the map is empty. The values are the failure messages
    /// as the SDK that ran the failing task reported them, decoded once when
    /// this SDK parses the payload: a value that a real engine sent
    /// JSON-string-encoded (observed as e.g. `"\"boom went the task\""`,
    /// because the worker reports a failure message as a JSON string) is
    /// decoded to the plain string; anything else is kept verbatim.
    ///
    /// ```
    /// # use hatchet_client::{Context, TaskBuilder, TaskError};
    /// let cleanup = TaskBuilder::<(), String>::new("cleanup").handler(
    ///     |ctx: Context, _input: ()| async move {
    ///         let summary: Vec<String> = ctx
    ///             .step_run_errors()
    ///             .iter()
    ///             .map(|(task, error)| format!("{task}: {error}"))
    ///             .collect();
    ///         Ok(summary.join("; "))
    ///     },
    /// );
    /// # let _ = cleanup;
    /// ```
    pub fn step_run_errors(&self) -> &BTreeMap<String, String> {
        &self.inner.payload.step_run_errors
    }

    /// Whether `parent` was skipped by its own
    /// [`skip_if`](crate::TaskBuilder::skip_if) conditions.
    ///
    /// A skipped task does not fail the workflow, and reading its output with
    /// [`parent_output`](Context::parent_output) is an
    /// [`Error::ParentOutput`] that says it was skipped.
    ///
    /// Skipping cascades, so the handler asking this is usually *beside* the
    /// skipped task rather than below it: a task declared downstream of a
    /// skipped one is skipped too and never runs to ask. That works because
    /// the map this reads is not limited to the tasks declared as parents —
    /// on both supported engines it carried tasks of the same run that the
    /// reader had not declared at all.
    ///
    /// A parent is read as skipped when its recorded value is the JSON object
    /// `{"skipped": true}` — the marker the official Go
    /// (`pkg/worker/context.go:395-406`) and Python (`context/context.py:298-304`)
    /// SDKs also key on. A parent whose real output happens to be exactly
    /// that object is, by construction, indistinguishable from a skip.
    ///
    /// ```
    /// # use hatchet_client::{Context, TaskBuilder, TaskError};
    /// # fn example(optional: hatchet_client::Task<(), u32>) {
    /// let report = TaskBuilder::<(), u32>::new("report").handler(move |ctx: Context, _: ()| {
    ///     let optional = optional.clone();
    ///     async move {
    ///         let extra = if ctx.was_skipped(&optional) {
    ///             0
    ///         } else {
    ///             ctx.parent_output(&optional)?
    ///         };
    ///         Ok(extra)
    ///     }
    /// });
    /// # let _ = report;
    /// # }
    /// ```
    pub fn was_skipped<PI, O>(&self, parent: &Task<PI, O>) -> bool {
        self.was_skipped_by_name(parent.name())
    }

    /// Like [`Context::was_skipped`], but by name — for a parent declared in
    /// another crate, where no handle is available to borrow.
    pub fn was_skipped_by_name(&self, task_name: &str) -> bool {
        self.parents().get(task_name).is_some_and(is_skipped)
    }

    /// Additional metadata attached to the workflow run, as a JSON object.
    /// Empty when the engine sent none, or sent something that is not a
    /// JSON object.
    pub fn additional_metadata(&self) -> &Map<String, Value> {
        &self.inner.metadata
    }

    /// How many times this task has already been retried; `0` on the first
    /// attempt.
    ///
    /// The engine sends this as a signed integer. A negative count is not
    /// something it should ever send, and it is read as `0` rather than
    /// surfaced — the same value [`log`](Context::log) files its lines under.
    pub fn retry_count(&self) -> u32 {
        u32::try_from(self.retry_count_wire()).unwrap_or(0)
    }

    /// The id of the workflow run this task belongs to.
    pub fn workflow_run_id(&self) -> &str {
        &self.action().workflow_run_id
    }

    /// This task run's external id — the key every later RPC that acts on
    /// this specific run (refreshing its timeout, releasing its slot,
    /// logging, streaming, triggering a child) addresses it by.
    pub fn task_run_id(&self) -> &str {
        &self.action().task_run_external_id
    }

    /// The task's own name, as declared.
    pub fn task_name(&self) -> &str {
        &self.action().task_name
    }

    /// The action id this task is running: `lower(<workflow>:<task>)`.
    pub fn action_id(&self) -> &str {
        &self.action().action_id
    }

    /// The id of the worker running this task.
    pub fn worker_id(&self) -> &str {
        &self.inner.worker_id
    }
}

/// What a running task can ask of the engine.
///
/// Every call here goes out under the SDK's unary retry policy, with a
/// deadline on the wire, and every one of them needs a context that came from
/// a running worker: a context built without one fails them with
/// [`Error::Detached`] rather than panicking.
impl Context {
    /// Asks the engine for `increment` more time before this run is timed
    /// out. The extension is relative to the deadline the run already has,
    /// and it may be asked for as often as the work needs.
    ///
    /// The engine only accepts an increment in whole hours, minutes or
    /// seconds, so `increment` is rounded up to the next whole second and
    /// sent in the largest unit that divides it exactly: 90 minutes goes out
    /// as `"90m"`.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`] when `increment` is zero,
    /// [`Error::Detached`] when this context has no engine behind it, and
    /// [`Error::Grpc`] when the call fails.
    pub async fn refresh_timeout(&self, increment: Duration) -> crate::Result<()> {
        let client = self.engine("refresh_timeout")?;
        let request = RefreshTimeoutRequest {
            task_run_external_id: self.task_run_id().to_string(),
            increment_timeout_by: wire::timeout_increment(increment)?,
        };
        send(request, |request| {
            let mut dispatcher = client.dispatcher_grpc();
            async move { dispatcher.refresh_timeout(request).await }
        })
        .await?;
        Ok(())
    }

    /// Gives this run's slot back while the handler carries on: it tells the
    /// engine that the run no longer occupies a slot on this worker, and then
    /// frees the worker's own slot, so this process is free to start another
    /// run rather than waiting for this handler to return — see
    /// "What the engine does with it" below for how much of that the engine
    /// actually acts on.
    ///
    /// For a handler that is mostly waiting on something outside this process
    /// — a long-running job elsewhere, a child run, a human — and is not the
    /// reason the worker's concurrency is bounded. The handler keeps running;
    /// the run itself is unaffected, still reported and still subject to its
    /// timeout.
    ///
    /// Calling it more than once is harmless: the engine is told again, and
    /// the local slot — already given back — is left alone. Every other way a
    /// run can end frees the slot too, so a handler that never calls this
    /// loses nothing.
    ///
    /// After a release the worker may be running more handlers at once than
    /// its `slots` — that is the point, when the engine assigns the freed
    /// slot to another run; see below for when it does not.
    ///
    /// # What the engine does with it
    ///
    /// Less than the name promises, on the engines this SDK supports. Both
    /// `hatchet-lite` v0.80.0 and v0.107.0 answer `ReleaseSlot` with `OK` and
    /// then go on counting the run against the worker: a queued run that
    /// needs this worker's last slot is not assigned until the releasing run
    /// itself ends. The integration test
    /// `release_slot_is_accepted_but_does_not_free_the_worker` pins that
    /// behaviour and fails if a future engine starts honouring the release.
    /// That observation is from `hatchet-lite` specifically, at those two
    /// versions; slot accounting is an engine-side decision, so a different
    /// deployment or configuration may assign the freed slot differently.
    ///
    /// So the *local* half is what you can count on today: this process stops
    /// holding a slot for a handler that is only waiting. A worker that must
    /// be able to start a child run while its parent waits needs slots for
    /// both, or a second worker.
    ///
    /// # Errors
    ///
    /// [`Error::Detached`] when this context has no engine behind it, and
    /// [`Error::Grpc`] when the call fails. A failed call leaves the local
    /// slot held, so the worker's concurrency still matches what the engine
    /// believes.
    pub async fn release_slot(&self) -> crate::Result<()> {
        let client = self.engine("release_slot")?;
        let request = ReleaseSlotRequest {
            task_run_external_id: self.task_run_id().to_string(),
        };
        send(request, |request| {
            let mut dispatcher = client.dispatcher_grpc();
            async move { dispatcher.release_slot(request).await }
        })
        .await?;
        // Only once the engine has agreed: a worker that freed its slot while
        // the engine still counted the run would take on more work than the
        // engine thinks it is holding.
        self.release_local_slot();
        Ok(())
    }

    /// Records a log line against this run, for the engine's dashboard.
    ///
    /// Long messages are truncated to 10,000 *characters* (never split
    /// mid-character), which is what the engine stores. The line is filed at
    /// level `INFO` and carries this attempt's retry count, so retries are
    /// told apart in the dashboard.
    ///
    /// Whether a log line that will not go through should fail the task is
    /// the handler's call, which is why this returns a `Result` rather than
    /// swallowing the error. Weigh that before writing `?`: the official SDKs
    /// send logs fire-and-forget, and propagating this error out of a handler
    /// turns a moment of log trouble into a failed — and retried — task.
    /// Tracing the error and carrying on is usually what a handler wants.
    ///
    /// # Errors
    ///
    /// [`Error::Detached`] when this context has no engine behind it, and
    /// [`Error::Grpc`] when the call fails.
    pub async fn log(&self, message: impl AsRef<str>) -> crate::Result<()> {
        let client = self.engine("log")?;
        let message = message.as_ref();
        let kept = wire::truncate_log(message);
        if kept.len() < message.len() {
            // Never the message itself: it is the handler's data, and this
            // line goes wherever the worker's logs go.
            tracing::warn!(
                task_run_external_id = %self.task_run_id(),
                original_chars = message.chars().count(),
                kept_chars = kept.chars().count(),
                "a log message was longer than the engine accepts and was truncated",
            );
        }
        let request = PutLogRequest {
            task_run_external_id: self.task_run_id().to_string(),
            created_at: Some(Timestamp::from(SystemTime::now())),
            message: kept.to_string(),
            level: Some(LOG_LEVEL.to_string()),
            metadata: String::new(),
            task_retry_count: Some(self.retry_count_wire()),
        };
        send(request, |request| {
            let mut events = client.events_grpc();
            async move { events.put_log(request).await }
        })
        .await?;
        Ok(())
    }

    /// Publishes a chunk on this run's result stream, for a caller that is
    /// subscribed to it — token-by-token output, progress, anything the run
    /// has before it has an answer.
    ///
    /// Chunks are numbered from zero, in call order, so a subscriber can put
    /// them back in order. The numbering belongs to the run rather than to
    /// one `Context` value: clones share it, so a helper handed a clone keeps
    /// adding to the same stream.
    ///
    /// The other end is [`RunsClient::stream`](crate::RunsClient::stream) (or
    /// [`RunHandle::stream`](crate::RunHandle::stream)), which puts the chunks
    /// back in this order for the reader. Chunks are not stored: only a
    /// subscription that is already open when a chunk is published receives
    /// it, and delivery is not guaranteed even then — a gap reaches the reader
    /// as [`Error::StreamGap`](crate::Error::StreamGap).
    ///
    /// # Send text
    ///
    /// A chunk goes out as bytes and comes back as text: the wire types differ
    /// on the two sides (`PutStreamEventRequest.message` is `bytes`,
    /// `WorkflowEvent.event_payload` is `string`). **Bytes that are not UTF-8
    /// poison the run's whole output stream**, which was observed on a real
    /// engine: every subscriber is ended with `Internal: grpc: error while
    /// marshaling: string field contains invalid UTF-8`, and subscribing again
    /// breaks on the same event, so the rest of that run's output is
    /// unreachable. A reader on
    /// [`RunsClient::stream`](crate::RunsClient::stream) sees that as a
    /// handful of reconnects — `Internal` is worth retrying in general — and
    /// then one [`Error::ResultStream`](crate::Error::ResultStream) carrying
    /// that status, after which the stream ends. This signature takes
    /// `impl Into<Vec<u8>>` and so cannot refuse them for you — pass text (a
    /// `String`, a `&str`, or [`serde_json::to_vec`]) unless you have measured
    /// otherwise.
    ///
    /// # Errors
    ///
    /// [`Error::Detached`] when this context has no engine behind it, and
    /// [`Error::Grpc`] when the call fails.
    pub async fn put_stream(&self, data: impl Into<Vec<u8>>) -> crate::Result<()> {
        let client = self.engine("put_stream")?;
        let request = PutStreamEventRequest {
            task_run_external_id: self.task_run_id().to_string(),
            created_at: Some(Timestamp::from(SystemTime::now())),
            message: data.into(),
            metadata: String::new(),
            // Claimed once, outside the retries below, so every attempt at
            // this chunk carries the same index — a retry that renumbered
            // itself would reach a subscriber as a second chunk.
            event_index: Some(self.inner.next_event_index.fetch_add(1, Ordering::Relaxed)),
        };
        send(request, |request| {
            let mut events = client.events_grpc();
            async move { events.put_stream_event(request).await }
        })
        .await?;
        Ok(())
    }

    /// Adds or replaces labels on the worker running this task, so later runs
    /// can be routed by what this one learned — marking a worker busy while
    /// it holds a scarce resource, for instance.
    ///
    /// Only the keys given are touched; the worker's other labels stay as
    /// they were registered.
    ///
    /// ```no_run
    /// # use hatchet_client::{Context, LabelValue};
    /// # async fn example(ctx: Context) -> hatchet_client::Result<()> {
    /// ctx.upsert_labels([("busy", LabelValue::from("true"))]).await
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// [`Error::Detached`] when this context has no engine behind it, and
    /// [`Error::Grpc`] when the call fails.
    pub async fn upsert_labels<K, V>(
        &self,
        labels: impl IntoIterator<Item = (K, V)>,
    ) -> crate::Result<()>
    where
        K: Into<String>,
        V: Into<LabelValue>,
    {
        let client = self.engine("upsert_labels")?;
        let request = UpsertWorkerLabelsRequest {
            worker_id: self.worker_id().to_string(),
            labels: labels
                .into_iter()
                .map(|(key, value)| (key.into(), value.into().to_proto()))
                .collect(),
        };
        send(request, |request| {
            let mut dispatcher = client.dispatcher_grpc();
            async move { dispatcher.upsert_worker_labels(request).await }
        })
        .await?;
        Ok(())
    }

    /// Triggers a run of `task` as a child of this one and returns its
    /// workflow run id, without waiting for it to finish.
    ///
    /// The child is recorded against this task run, so the engine can show
    /// the tree and, on a retry of *this* task, hand back the children it
    /// already started rather than starting them again — which is why the
    /// spawn order matters: children are deduplicated on their index within
    /// this run, or on [`RunOpts::child_key`] when one is given.
    ///
    /// What is triggered is the workflow named after `task`, which is the
    /// right thing for a standalone task — a task declared on its own *is* a
    /// one-task workflow of the same name. A task declared inside a
    /// multi-task [`Workflow`] is not addressable on its own, so triggering
    /// one that way would name a workflow the engine does not know: trigger
    /// its workflow with [`spawn_workflow`](Context::spawn_workflow) instead.
    ///
    /// # Errors
    ///
    /// [`Error::Json`] when `input` cannot be serialized,
    /// [`Error::Detached`] when this context has no engine behind it,
    /// [`Error::IdempotencyCollision`] when `task` declares
    /// [`idempotency`](crate::Workflow::idempotency) and the computed key is
    /// already claimed by another run, and [`Error::Grpc`] when the call
    /// fails for any other reason.
    pub async fn spawn<I, O>(
        &self,
        task: &Task<I, O>,
        input: &I,
        opts: RunOpts,
    ) -> crate::Result<String>
    where
        I: serde::Serialize,
    {
        let span = otel::run_workflow(task.name());
        let run_id = self
            .trigger_child("spawn", task.name(), input, &opts, &span)
            .instrument(span.clone())
            .await;
        otel::record_result(&span, &run_id);
        run_id
    }

    /// [`spawn`](Context::spawn), for a whole [`Workflow`] rather than a
    /// standalone task. The input is the workflow's, not any one task's.
    ///
    /// # Errors
    ///
    /// The same as [`spawn`](Context::spawn).
    pub async fn spawn_workflow<I>(
        &self,
        workflow: &Workflow,
        input: &I,
        opts: RunOpts,
    ) -> crate::Result<String>
    where
        I: serde::Serialize,
    {
        let span = otel::run_workflow(workflow.name());
        let run_id = self
            .trigger_child("spawn_workflow", workflow.name(), input, &opts, &span)
            .instrument(span.clone())
            .await;
        otel::record_result(&span, &run_id);
        run_id
    }

    /// Triggers a run of `task` as a child of this one and waits for its
    /// output.
    ///
    /// The child is recorded against this task run exactly as with
    /// [`spawn`](Context::spawn) — same tree, same deduplication on the
    /// child's index or [`RunOpts::child_key`] — and this handler then waits
    /// for it on the client's shared result subscription.
    ///
    /// # Slots
    ///
    /// **A parent that waits for a child holds its slot while it waits.** On a
    /// worker whose slots are all taken, and where the child can only run on
    /// *this* worker, that is a deadlock: the child cannot start until a slot
    /// frees up, and no slot frees up until the child finishes.
    ///
    /// [`release_slot`](Context::release_slot) reads like the answer and is
    /// worth calling for what it does locally, but it does not break this
    /// deadlock on the engines this SDK supports — see its own documentation
    /// for what they do with it. What actually avoids the deadlock is giving
    /// the worker room for both runs, by declaring more slots than the
    /// deepest chain of waiting parents, or by letting the child run on a
    /// worker of its own:
    ///
    /// ```no_run
    /// # use hatchet_client::{Client, Context, RunOpts, TaskBuilder};
    /// # async fn example(client: Client) -> hatchet_client::Result<()> {
    /// let child = TaskBuilder::<(), u32>::new("child")
    ///     .handler(|_ctx, _input| async { Ok(1) });
    /// let child_for_parent = child.clone();
    /// let parent = TaskBuilder::<(), u32>::new("parent").handler(move |ctx: Context, _input: ()| {
    ///     let child = child_for_parent.clone();
    ///     async move {
    ///         let counted = ctx.run(&child, &(), RunOpts::default()).await?;
    ///         Ok(counted)
    ///     }
    /// });
    ///
    /// // Two slots on one worker: room for the parent to wait while the
    /// // child it started runs alongside it, so neither is stuck behind the
    /// // other.
    /// let worker = client
    ///     .worker("example")
    ///     .slots(2)
    ///     .register(&parent)
    ///     .register(&child)
    ///     .build()
    ///     .await?;
    /// worker.run_until_shutdown().await
    /// # }
    /// ```
    ///
    /// There is no time limit on the wait, just as with
    /// [`RunHandle::result`](crate::RunHandle::result).
    ///
    /// # Errors
    ///
    /// Those of [`spawn`](Context::spawn), plus
    /// [`Error::RunFailed`](crate::Error::RunFailed) when the child failed,
    /// [`Error::RunCancelled`](crate::Error::RunCancelled) when the child was
    /// cancelled before it finished,
    /// [`Error::RunOutput`](crate::Error::RunOutput) when its output is not an
    /// `O`, and [`Error::ResultStream`](crate::Error::ResultStream) when the
    /// subscription the result would have arrived on was given up on.
    pub async fn run<I, O>(&self, task: &Task<I, O>, input: &I, opts: RunOpts) -> crate::Result<O>
    where
        I: serde::Serialize,
        O: serde::de::DeserializeOwned,
    {
        // Triggered first and subscribed to second, as everywhere else: the
        // engine answers a subscription for a run that has already finished
        // straight away. One span over both, as Go's `Run` holds it
        // (`sdks/go/workflow.go:932-963`).
        let span = otel::run_workflow(task.name());
        let output = async {
            let run_id = self
                .trigger_child("run", task.name(), input, &opts, &span)
                .await?;
            let event = self.engine("run")?.run_listener().wait(run_id).await?;
            crate::runs::output_of(&event, task.name())
        }
        .instrument(span.clone())
        .await;
        otel::record_result(&span, &output);
        output
    }

    /// Triggers the workflow declared as `name` as a child of this run, on
    /// behalf of the public `method` that asked for it.
    ///
    /// The request carries `span`'s traceparent (with the `otel` feature), so
    /// the child continues this run's trace — on v0.80.0, which passes a
    /// parent's metadata on to no child, that is the only way it does — and
    /// the child's id is recorded on `span`.
    async fn trigger_child<I: serde::Serialize>(
        &self,
        method: &str,
        name: &str,
        input: &I,
        opts: &RunOpts,
        span: &Span,
    ) -> crate::Result<String> {
        let client = self.engine(method)?;
        let mut request = trigger::request(
            client.config().namespace(),
            name,
            input,
            opts,
            Some(ParentRef {
                workflow_run_id: self.workflow_run_id(),
                task_run_external_id: self.task_run_id(),
                // As with a stream chunk's index, claimed once so the retries
                // below all carry the index this child was first sent under.
                child_index: self.claim_child_index(),
                worker_id: self.worker_id(),
            }),
        )?;
        otel::inject(span, &mut request.additional_metadata);
        let response = send(request, |request| {
            let mut workflows = client.workflows_grpc();
            async move { workflows.trigger_workflow(request).await }
        })
        .await
        .map_err(crate::collision::from_trigger)?;
        span.record(
            "hatchet.child_workflow_run_id",
            response.workflow_run_id.as_str(),
        );
        Ok(response.workflow_run_id)
    }
}

/// Sends one unary RPC under the SDK's retry policy — up to five attempts,
/// each carrying the per-attempt deadline as a `grpc-timeout` header — and
/// hands back the response body.
///
/// `call` receives the whole request rather than just the message so that
/// every attempt is a fresh one with its own deadline.
async fn send<T, C, Fut, R>(request: T, mut call: C) -> crate::Result<R>
where
    T: Clone,
    C: FnMut(Request<T>) -> Fut,
    Fut: Future<Output = std::result::Result<Response<R>, Status>>,
{
    let response = retry::unary(|| call(retry::timed(request.clone()))).await?;
    Ok(response.into_inner())
}

/// Construction and the private accessors the query methods above, and
/// the RPCs, build on.
impl Context {
    /// Builds the context for one assigned action. Fails, with an explanation,
    /// when the action's payload is not the JSON object the engine promises;
    /// the worker reports that as a failed task rather than dying.
    pub(crate) fn new(
        action: AssignedAction,
        worker_id: String,
        client: Option<Client>,
        cancel: CancellationToken,
        slot: Slot,
        durable: Option<Arc<DurableInvocation>>,
    ) -> Result<Self, String> {
        let payload = parse_payload(&action.action_payload)?;
        let metadata = wire::parse_metadata(action.additional_metadata.as_deref());
        Ok(Self {
            inner: Arc::new(Inner {
                action,
                payload,
                metadata,
                worker_id,
                client,
                cancel,
                slot,
                durable,
                next_event_index: AtomicI64::new(0),
                next_child_index: AtomicI32::new(0),
            }),
        })
    }

    /// Frees the worker's local slot for this run, without telling the engine
    /// anything. [`release_slot`](Context::release_slot) does this once the
    /// engine has agreed; the runner does it again when the run ends, which
    /// is a no-op if the handler got there first.
    pub(crate) fn release_local_slot(&self) {
        self.inner.slot.release();
    }

    /// This attempt's retry count as the engine's own signed integer, clamped
    /// exactly as [`retry_count`](Context::retry_count) clamps it so the two
    /// can never disagree.
    fn retry_count_wire(&self) -> i32 {
        self.action().retry_count.max(0)
    }

    /// The task's input, as the engine sent it.
    pub(crate) fn input(&self) -> &Value {
        &self.inner.payload.input
    }

    /// Outputs of the parent tasks, by task name.
    pub(crate) fn parents(&self) -> &HashMap<String, Value> {
        &self.inner.payload.parents
    }

    /// The action this task is running.
    pub(crate) fn action(&self) -> &AssignedAction {
        &self.inner.action
    }

    /// The client the worker was built from, when it has one.
    pub(crate) fn client(&self) -> Option<&Client> {
        self.inner.client.as_ref()
    }

    /// The durable invocation this run belongs to, for a durable action only.
    pub(crate) fn durable(&self) -> Option<&Arc<DurableInvocation>> {
        self.inner.durable.as_ref()
    }

    /// The `child_index` the next child run claims, and moves the sequence on.
    ///
    /// One sequence per task run, shared by [`Context::spawn`],
    /// [`Context::run`] and
    /// [`DurableContext::spawn`](crate::DurableContext::spawn): the engine
    /// deduplicates a child on `(parent run, parent task run, index)`
    /// (`api-contracts/v1/shared/trigger.proto:56-63`), so two children of one
    /// run must never claim the same one.
    pub(crate) fn claim_child_index(&self) -> i32 {
        self.inner.next_child_index.fetch_add(1, Ordering::Relaxed)
    }

    /// The connection every RPC below goes out on, or an explanation of why
    /// there is none: a context built for a test has no worker behind it, and
    /// calling the engine from one is a mistake worth an error rather than a
    /// panic.
    fn engine(&self, method: &str) -> crate::Result<&Client> {
        self.client().ok_or_else(|| {
            Error::Detached(format!(
                "`{method}` talks to the engine, and this context was built without a connection \
                 to one"
            ))
        })
    }

    /// A context with nothing behind it, for exercising handlers in tests
    /// without a worker: no engine, and no slot to give back.
    #[cfg(test)]
    pub(crate) fn placeholder() -> Self {
        Self::new(
            AssignedAction::default(),
            String::new(),
            None,
            CancellationToken::new(),
            Slot::default(),
            None,
        )
        .expect("an empty payload parses")
    }
}

/// Whether a parent's recorded value is the engine's "this task was skipped"
/// marker rather than an output: a JSON object with `"skipped": true`. This
/// is how the official Go (`pkg/worker/context.go:395-406`) and Python
/// (`context/context.py:298-304`) SDKs read it. A task whose own output is
/// `{"skipped": true}` is indistinguishable from a skipped one.
fn is_skipped(value: &Value) -> bool {
    value.get("skipped") == Some(&Value::Bool(true))
}

/// An empty payload means an empty object: the engine sends `""` rather than
/// `"{}"` for actions that carry nothing.
fn parse_payload(raw: &str) -> Result<ActionPayload, String> {
    if raw.is_empty() {
        return Ok(ActionPayload::default());
    }
    serde_json::from_str(raw).map_err(|error| format!("could not read the action payload: {error}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use hatchet_proto::root::AssignedAction;
    use serde_json::json;
    use tokio_util::sync::CancellationToken;

    fn action_with_payload(payload: &str) -> AssignedAction {
        AssignedAction {
            action_payload: payload.to_string(),
            action_id: "pipeline:step".to_string(),
            ..AssignedAction::default()
        }
    }

    fn context_for(payload: &str, cancel: CancellationToken) -> Result<Context, String> {
        Context::new(
            action_with_payload(payload),
            "worker-1".to_string(),
            None,
            cancel,
            Slot::default(),
            None,
        )
    }

    #[test]
    fn parses_input_and_parents_from_the_payload() {
        let payload = json!({
            "input": {"repo": "hatchet-rs"},
            "parents": {"fetch": {"count": 3}},
        })
        .to_string();
        let ctx = context_for(&payload, CancellationToken::new()).unwrap();
        assert_eq!(ctx.input(), &json!({"repo": "hatchet-rs"}));
        assert_eq!(ctx.parents().get("fetch"), Some(&json!({"count": 3})));
        assert_eq!(ctx.worker_id(), "worker-1");
        assert_eq!(ctx.action().action_id, "pipeline:step");
        assert!(ctx.client().is_none());
    }

    #[test]
    fn an_empty_payload_is_an_empty_object() {
        let ctx = context_for("", CancellationToken::new()).unwrap();
        assert_eq!(ctx.input(), &serde_json::Value::Null);
        assert!(ctx.parents().is_empty());
    }

    #[test]
    fn step_run_errors_are_read_from_the_payload() {
        let payload = json!({
            "input": {},
            "step_run_errors": {"fetch": "boom", "build": "nope"}
        })
        .to_string();
        let ctx = context_for(&payload, CancellationToken::new()).unwrap();
        let errors = ctx.step_run_errors();
        assert_eq!(errors.len(), 2);
        assert_eq!(errors.get("fetch").map(String::as_str), Some("boom"));
        assert_eq!(errors.get("build").map(String::as_str), Some("nope"));
    }

    #[test]
    fn null_parents_and_step_run_errors_read_as_empty() {
        let payload = json!({"input": {}, "parents": null, "step_run_errors": null}).to_string();
        let ctx = context_for(&payload, CancellationToken::new()).unwrap();
        assert!(ctx.parents().is_empty());
        assert!(ctx.step_run_errors().is_empty());
    }

    #[test]
    fn a_payload_without_step_run_errors_reports_none() {
        let ctx = context_for(r#"{"input":{}}"#, CancellationToken::new()).unwrap();
        assert!(ctx.step_run_errors().is_empty());
        let ctx = context_for("", CancellationToken::new()).unwrap();
        assert!(ctx.step_run_errors().is_empty());
    }

    /// A real engine sends a failing task's error message JSON-string-encoded
    /// (P1 real-engine spike: `{"boom": "\"boom went the task\""}`)
    /// because the worker that ran it reports the message as a JSON string.
    /// `step_run_errors` decodes that once, here.
    #[test]
    fn a_json_string_encoded_step_run_error_is_decoded() {
        let payload = json!({
            "input": {},
            "step_run_errors": {"boom": "\"boom went the task\""}
        })
        .to_string();
        let ctx = context_for(&payload, CancellationToken::new()).unwrap();
        assert_eq!(
            ctx.step_run_errors().get("boom").map(String::as_str),
            Some("boom went the task")
        );
    }

    #[test]
    fn a_step_run_error_that_is_not_a_json_string_is_kept_verbatim() {
        let payload = json!({
            "input": {},
            "step_run_errors": {"plain": "boom", "structured": "{\"a\":1}"}
        })
        .to_string();
        let ctx = context_for(&payload, CancellationToken::new()).unwrap();
        assert_eq!(
            ctx.step_run_errors().get("plain").map(String::as_str),
            Some("boom")
        );
        assert_eq!(
            ctx.step_run_errors().get("structured").map(String::as_str),
            Some(r#"{"a":1}"#)
        );
    }

    #[test]
    fn a_payload_that_is_not_json_is_an_error() {
        let error = context_for("not json at all", CancellationToken::new()).unwrap_err();
        assert!(error.contains("payload"), "{error}");
    }

    #[test]
    fn unknown_payload_fields_are_ignored() {
        let payload = json!({
            "input": 7,
            "triggers": ["cron"],
            "user_data": {"anything": true},
        })
        .to_string();
        let ctx = context_for(&payload, CancellationToken::new()).unwrap();
        assert_eq!(ctx.input(), &json!(7));
        assert!(ctx.parents().is_empty());
    }

    #[tokio::test]
    async fn cancellation_is_observable() {
        let cancel = CancellationToken::new();
        let ctx = context_for("", cancel.clone()).unwrap();
        assert!(!ctx.is_cancelled());
        let clone = ctx.clone();
        let waiting = tokio::spawn(async move {
            clone.cancelled().await;
            clone.is_cancelled()
        });
        cancel.cancel();
        assert!(waiting.await.unwrap());
        assert!(ctx.is_cancelled());
        // Awaiting an already-cancelled context returns at once.
        ctx.cancelled().await;
    }

    /// An action carrying every identifying field the query accessors read,
    /// plus a payload and metadata a test can shape as it likes.
    fn full_action(payload: &str, metadata: Option<&str>) -> AssignedAction {
        AssignedAction {
            action_payload: payload.to_string(),
            action_id: "pipeline:step".to_string(),
            task_name: "step".to_string(),
            workflow_run_id: "run-1".to_string(),
            task_run_external_id: "task-run-1".to_string(),
            retry_count: 2,
            additional_metadata: metadata.map(str::to_string),
            ..AssignedAction::default()
        }
    }

    fn context_with(action: AssignedAction) -> Context {
        Context::new(
            action,
            "worker-1".to_string(),
            None,
            CancellationToken::new(),
            Slot::default(),
            None,
        )
        .expect("a valid payload parses")
    }

    #[test]
    fn ids_and_retry_count_come_from_the_action() {
        let ctx = context_with(full_action("", None));
        assert_eq!(ctx.workflow_run_id(), "run-1");
        assert_eq!(ctx.task_run_id(), "task-run-1");
        assert_eq!(ctx.task_name(), "step");
        assert_eq!(ctx.action_id(), "pipeline:step");
        assert_eq!(ctx.worker_id(), "worker-1");
        assert_eq!(ctx.retry_count(), 2);
    }

    #[test]
    fn input_raw_is_the_unparsed_input() {
        let payload = json!({"input": {"repo": "hatchet-rs"}}).to_string();
        let ctx = context_with(full_action(&payload, None));
        assert_eq!(ctx.input_raw(), &json!({"repo": "hatchet-rs"}));
    }

    #[test]
    fn additional_metadata_parses_the_actions_json_object() {
        let ctx = context_with(full_action("", Some(r#"{"a":"b","n":1}"#)));
        let metadata = ctx.additional_metadata();
        assert_eq!(metadata.len(), 2);
        assert_eq!(metadata.get("a"), Some(&json!("b")));
        assert_eq!(metadata.get("n"), Some(&json!(1)));
    }

    #[test]
    fn additional_metadata_is_empty_when_the_action_has_none() {
        let ctx = context_with(full_action("", None));
        assert!(ctx.additional_metadata().is_empty());
    }

    #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
    struct FetchOutput {
        n: i32,
    }

    fn fetch_task() -> Task<(), FetchOutput> {
        crate::TaskBuilder::new("fetch")
            .handler(|_ctx, _input: ()| async { Ok(FetchOutput { n: 0 }) })
    }

    #[test]
    fn parent_output_deserializes_a_recorded_parent() {
        let payload = json!({"parents": {"fetch": {"n": 3}}}).to_string();
        let ctx = context_with(full_action(&payload, None));
        let output: FetchOutput = ctx.parent_output(&fetch_task()).unwrap();
        assert_eq!(output, FetchOutput { n: 3 });
    }

    #[test]
    fn parent_output_of_a_missing_parent_names_the_task() {
        let ctx = context_with(full_action("", None));
        let error = ctx.parent_output(&fetch_task()).unwrap_err();
        let Error::ParentOutput { task, .. } = &error else {
            panic!("{error:?}")
        };
        assert_eq!(task, "fetch");
    }

    #[test]
    fn parent_output_of_the_wrong_type_names_the_task_and_the_serde_error() {
        let payload = json!({"parents": {"fetch": "not an object"}}).to_string();
        let ctx = context_with(full_action(&payload, None));
        let error = ctx.parent_output(&fetch_task()).unwrap_err();
        let Error::ParentOutput { task, reason } = &error else {
            panic!("{error:?}")
        };
        assert_eq!(task, "fetch");
        assert!(!reason.is_empty(), "{error:?}");
    }

    #[test]
    fn parent_output_by_name_looks_up_by_string_rather_than_a_task_handle() {
        let payload = json!({"parents": {"fetch": {"n": 5}}}).to_string();
        let ctx = context_with(full_action(&payload, None));
        let output: FetchOutput = ctx.parent_output_by_name("fetch").unwrap();
        assert_eq!(output, FetchOutput { n: 5 });
    }

    #[test]
    fn a_skipped_parent_is_reported_as_skipped() {
        let payload = json!({
            "input": {},
            "parents": {
                "maybe": {"skipped": true},
                "fetch": {"count": 3},
            },
        })
        .to_string();
        let ctx = context_for(&payload, CancellationToken::new()).unwrap();
        assert!(ctx.was_skipped_by_name("maybe"));
        assert!(!ctx.was_skipped_by_name("fetch"));
        assert!(
            !ctx.was_skipped_by_name("never-heard-of-it"),
            "a task that is not a parent at all was not skipped either"
        );
    }

    #[test]
    fn was_skipped_matches_by_task_handle() {
        let maybe: Task<(), ()> =
            crate::TaskBuilder::new("maybe").handler(|_ctx, _input: ()| async { Ok(()) });
        let payload = json!({"input": {}, "parents": {"maybe": {"skipped": true}}}).to_string();
        let ctx = context_for(&payload, CancellationToken::new()).unwrap();
        assert!(ctx.was_skipped(&maybe));
    }

    /// The trap this API exists to close: `{"skipped": true}` would
    /// otherwise be handed to the caller's `DeserializeOwned` and come back
    /// as a serde message about a missing field.
    #[test]
    fn reading_a_skipped_parents_output_says_it_was_skipped() {
        #[derive(Debug, serde::Deserialize)]
        struct Count {
            #[allow(dead_code)]
            count: u32,
        }

        let payload = json!({"input": {}, "parents": {"maybe": {"skipped": true}}}).to_string();
        let ctx = context_for(&payload, CancellationToken::new()).unwrap();
        let error = ctx.parent_output_by_name::<Count>("maybe").unwrap_err();
        let Error::ParentOutput { task, reason } = &error else {
            panic!("expected ParentOutput: {error:?}");
        };
        assert_eq!(task, "maybe");
        assert!(reason.contains("skipped"), "{reason}");
        assert!(
            !reason.contains("missing field"),
            "the serde message must not be what the caller sees: {reason}"
        );
    }

    /// A parent whose real output happens to look like a skip marker is
    /// indistinguishable, and `()` output is not a skip.
    #[test]
    fn only_a_skipped_true_marker_counts_as_skipped() {
        let payload = json!({
            "input": {},
            "parents": {"a": {"skipped": false}, "b": {"skipped": "yes"}, "c": null},
        })
        .to_string();
        let ctx = context_for(&payload, CancellationToken::new()).unwrap();
        assert!(!ctx.was_skipped_by_name("a"));
        assert!(!ctx.was_skipped_by_name("b"));
        assert!(!ctx.was_skipped_by_name("c"));
    }

    /// A placeholder context has nothing to call: every RPC says so, by name,
    /// instead of panicking somewhere inside the transport.
    #[tokio::test]
    async fn rpcs_on_a_context_without_an_engine_are_detached_errors() {
        let ctx = Context::placeholder();
        let child = fetch_task();
        let pipeline = Workflow::new("pipeline");

        let calls: [(&str, crate::Result<()>); 5] = [
            (
                "refresh_timeout",
                ctx.refresh_timeout(Duration::from_secs(60)).await,
            ),
            ("release_slot", ctx.release_slot().await),
            ("log", ctx.log("anything").await),
            (
                "spawn",
                ctx.spawn(&child, &(), RunOpts::default()).await.map(drop),
            ),
            (
                "spawn_workflow",
                ctx.spawn_workflow(&pipeline, &(), RunOpts::default())
                    .await
                    .map(drop),
            ),
        ];
        for (method, result) in calls {
            let error = result.expect_err("a placeholder context reaches no engine");
            let Error::Detached(reason) = &error else {
                panic!("{method}: {error:?}")
            };
            assert!(reason.contains(method), "{method}: {reason}");
        }
    }

    /// The slot is the one place a worker's concurrency can be miscounted:
    /// giving one permit back twice would let the worker run one more task
    /// than it has slots, for ever after.
    #[test]
    fn a_slot_gives_its_permit_back_once_however_often_it_is_released() {
        let semaphore = Arc::new(tokio::sync::Semaphore::new(1));
        let permit = Arc::clone(&semaphore)
            .try_acquire_owned()
            .expect("the semaphore has a permit");
        let slot = Slot::holding(permit);
        assert_eq!(semaphore.available_permits(), 0);

        let clone = slot.clone();
        slot.release();
        assert_eq!(semaphore.available_permits(), 1);

        // The handler released it; the runner releases it again when the run
        // ends, through a clone. The permit is already gone.
        clone.release();
        slot.release();
        assert_eq!(semaphore.available_permits(), 1);

        // And a context with no worker behind it has nothing to release.
        Slot::default().release();
    }

    #[test]
    fn a_negative_retry_count_reads_as_zero_everywhere() {
        let ctx = context_with(AssignedAction {
            retry_count: -1,
            ..AssignedAction::default()
        });
        assert_eq!(ctx.retry_count(), 0);
        assert_eq!(ctx.retry_count_wire(), 0);
    }

    #[test]
    fn debug_hides_input_and_metadata_but_shows_the_task_run_id() {
        let payload = json!({"input": {"token": "s3cr3t"}}).to_string();
        let ctx = context_with(full_action(&payload, Some(r#"{"key": "s3cr3t"}"#)));
        let debug = format!("{ctx:?}");
        assert!(!debug.contains("s3cr3t"), "{debug}");
        assert!(debug.contains("task-run-1"), "{debug}");
    }
}