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
//! TaskContext — runtime context for functional API tasks.
//!
//! Provides access to state, checkpointing, interrupts, and streaming.
//! Passed to `#[entrypoint]` and `#[task]` annotated functions.
use std::collections::HashMap;
use std::sync::Arc;
use serde::de::DeserializeOwned;
use serde_json::Value;
use tokio::sync::RwLock;
use tokio_util::sync::CancellationToken;
use crate::checkpoint::Checkpointer;
use crate::error::Result;
use crate::state::{State, StateSchema};
use crate::stream::StreamEvent;
use super::error::FunctionalError;
use super::execution_log::ExecutionLog;
use super::schema::StateSchemaValidator;
/// Runtime context passed to `#[entrypoint]` and `#[task]` functions.
///
/// Provides access to workflow state, checkpointing, interrupt/resume,
/// and progress streaming. Each task function receives a mutable reference
/// to `TaskContext` enabling state reads, writes, event emission, and
/// interrupt requests.
///
/// # Example
///
/// ```rust,ignore
/// use adk_graph::functional::TaskContext;
///
/// #[task]
/// async fn my_step(ctx: &mut TaskContext) -> Result<Value> {
/// // Read state
/// let count: i64 = ctx.get("counter").unwrap_or(0);
///
/// // Write state
/// ctx.set("counter", serde_json::json!(count + 1));
///
/// // Emit progress
/// ctx.emit(StreamEvent::custom("my_step", "progress", serde_json::json!({"count": count + 1})));
///
/// Ok(serde_json::json!({"new_count": count + 1}))
/// }
/// ```
pub struct TaskContext {
/// Thread identifier for checkpoint scoping.
thread_id: String,
/// Current workflow state.
state: State,
/// Checkpointer for persistence.
checkpointer: Arc<dyn Checkpointer>,
/// Stream event sender.
event_tx: tokio::sync::broadcast::Sender<StreamEvent>,
/// Task execution tracker (for skip-on-resume).
execution_log: Arc<RwLock<ExecutionLog>>,
/// Cancellation token.
cancel_token: CancellationToken,
/// State schema for validation.
schema: Option<StateSchema>,
/// State schema validator for functional API validation.
schema_validator: Option<StateSchemaValidator>,
/// Iteration counters for loop checkpoint keying.
/// Maps task_name -> current iteration index.
iteration_counters: HashMap<String, usize>,
/// Route targets set by `route_to`, read back by `take_pending_route`.
pending_route: Option<Vec<String>>,
/// Values supplied for interrupt sites, keyed by continuation key.
///
/// Without this there was no resume channel at all: `interrupt` always returned an error and
/// nothing outside the method consumed a resume value, so the typed-resumption contract in
/// its signature could not be honoured.
resume_values: HashMap<String, Value>,
/// Counts interrupt calls so each site gets a stable key across a replay.
interrupt_ordinal: Arc<RwLock<usize>>,
/// Calls made so far of each `#[task]`, keyed by task name, so each call
/// gets its own execution-log key; see [`super::task_call_id`].
task_call_counters: std::sync::Mutex<HashMap<String, usize>>,
/// The thread's newest checkpoint version and open pauses, once read. Held across
/// each save, so parallel tasks write their checkpoints one at a time, in version
/// order.
head: tokio::sync::Mutex<Option<Head>>,
/// The checkpoint this run resumed from, whose pause it answers.
resumed_from: Option<String>,
}
/// What a functional run knows of its thread's newest checkpoint.
struct Head {
version: u64,
/// The thread's checkpoints where a run paused and no run has resumed
/// ([`OPEN_PAUSES_METADATA_KEY`](crate::record::OPEN_PAUSES_METADATA_KEY)).
open_pauses: std::collections::BTreeSet<String>,
}
impl TaskContext {
/// Create a new `TaskContext`.
///
/// Typically constructed by the macro-generated entrypoint, not by user code.
pub fn new(
thread_id: String,
state: State,
checkpointer: Arc<dyn Checkpointer>,
event_tx: tokio::sync::broadcast::Sender<StreamEvent>,
execution_log: Arc<RwLock<ExecutionLog>>,
cancel_token: CancellationToken,
schema: Option<StateSchema>,
) -> Self {
Self {
thread_id,
state,
checkpointer,
event_tx,
execution_log,
cancel_token,
schema,
schema_validator: None,
iteration_counters: HashMap::new(),
pending_route: None,
resume_values: HashMap::new(),
interrupt_ordinal: Arc::new(RwLock::new(0)),
task_call_counters: std::sync::Mutex::new(HashMap::new()),
head: tokio::sync::Mutex::new(None),
resumed_from: None,
}
}
// ─── Public Methods ──────────────────────────────────────────────────
/// Get the current workflow state (read-only).
pub fn state(&self) -> &State {
&self.state
}
/// Get a typed value from state.
///
/// Attempts to deserialize the value stored at `key` into type `T`.
/// Returns `None` if the key does not exist or deserialization fails.
///
/// # Example
///
/// ```rust,ignore
/// let count: Option<i64> = ctx.get("counter");
/// ```
pub fn get<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
self.state.get(key).and_then(|v| serde_json::from_value(v.clone()).ok())
}
/// Set a value in state.
///
/// If a [`StateSchema`] is configured, the update is applied using the
/// appropriate reducer for the key. Otherwise the value is set directly
/// (overwrite semantics).
///
/// # Example
///
/// ```rust,ignore
/// ctx.set("counter", serde_json::json!(42));
/// ```
pub fn set(&mut self, key: &str, value: impl Into<Value>) {
let value = value.into();
if let Some(schema) = &self.schema {
schema.apply_update(&mut self.state, key, value);
} else {
self.state.insert(key.to_string(), value);
}
}
/// Emit a progress event to stream listeners.
///
/// Events are broadcast to all registered receivers. If no listeners
/// are active the event is silently dropped.
///
/// # Example
///
/// ```rust,ignore
/// ctx.emit(StreamEvent::custom("my_task", "progress", json!({"pct": 50})));
/// ```
pub fn emit(&self, event: StreamEvent) {
// Ignore send errors — they indicate no active receivers.
let _ = self.event_tx.send(event);
}
/// Interrupt execution and wait for external input.
///
/// Persists the current state as an interrupt checkpoint, emits an
/// interrupted event, and suspends execution. When the workflow is
/// resumed with an interrupt value, the value is deserialized into `T`
/// and returned.
///
/// The first answer an interrupt receives is recorded in the execution log
/// and checkpointed before it is returned. A run resumed from any later
/// checkpoint, such as one written before a crash, replays the recorded
/// answer without it being supplied again. A recorded answer takes
/// precedence over a different value supplied later, because the tasks that
/// ran after the interrupt already acted on it.
///
/// # Errors
///
/// Returns [`FunctionalError::InterruptTypeMismatch`] if the resume
/// value cannot be deserialized into `T`.
///
/// Returns [`FunctionalError::CheckpointFailed`] if persisting the
/// interrupt checkpoint, or the checkpoint that records an answer, fails.
///
/// # Example
///
/// ```rust,ignore
/// let approval: bool = ctx.interrupt("Please approve this action").await?;
/// ```
pub async fn interrupt<T: DeserializeOwned>(&self, message: &str) -> Result<T> {
// Each interrupt site gets a key from its position in the run. Replaying the same
// workflow reaches the same interrupts in the same order, so the key a caller was told
// to supply is the key the site looks for.
let continuation_key = {
let mut ordinal = self.interrupt_ordinal.write().await;
*ordinal += 1;
format!("interrupt-{ordinal}")
};
// Resume: an answer recorded by an earlier run wins, then a value supplied for this
// site. Either is returned to the call site, as the signature promises.
let recorded = self.execution_log.read().await.interrupt_answer(&continuation_key).cloned();
let supplied = self.resume_values.get(&continuation_key);
let answer = match (recorded, supplied) {
(Some(recorded), supplied) => {
if supplied.is_some_and(|value| *value != recorded) {
tracing::warn!(
interrupt.key = %continuation_key,
"ignoring a resume value that differs from the answer this interrupt \
already recorded"
);
}
Some((recorded, false))
}
(None, Some(value)) => Some((value.clone(), true)),
(None, None) => None,
};
if let Some((value, newly_supplied)) = answer {
let typed: T = serde_json::from_value(value.clone()).map_err(|e| {
FunctionalError::InterruptTypeMismatch {
task: continuation_key.clone(),
message: format!(
"the value supplied for {continuation_key} does not deserialize into the \
type this interrupt expects: {e}"
),
}
})?;
if newly_supplied {
self.record_interrupt_answer(&continuation_key, value).await?;
}
return Ok(typed);
}
// Emit the interrupt event for stream listeners.
self.emit(StreamEvent::interrupted("functional_task", message));
// Persist the interrupt checkpoint. It carries the execution log so a run
// resumed from it replays the tasks that completed before the interrupt.
let checkpoint = {
let log = self.execution_log.read().await;
crate::state::Checkpoint::new(
&self.thread_id,
self.state.clone(),
log.current_step(),
vec![],
)
.with_metadata("interrupt_message", Value::String(message.to_string()))
.with_metadata("continuation_key", Value::String(continuation_key.clone()))
.with_metadata("execution_log", serde_json::to_value(&*log)?)
};
self.save(checkpoint, true).await.map_err(|e| FunctionalError::CheckpointFailed {
task: "interrupt".to_string(),
message: e.to_string(),
})?;
// Mark the current task as interrupted in the execution log.
{
let mut log = self.execution_log.write().await;
log.tasks.entry("__interrupt__".to_string()).or_insert(
super::execution_log::TaskRecord {
status: super::execution_log::TaskStatus::Interrupted,
result: None,
error: None,
started_at: chrono::Utc::now().to_rfc3339(),
completed_at: None,
attempt: 1,
},
);
}
Err(FunctionalError::Suspended { continuation_key, message: message.to_string() }.into())
}
/// Supplies values for interrupt sites, keyed by continuation key.
///
/// Re-invoke the entrypoint with these set to resume: an interrupt whose key is present
/// returns the deserialized value instead of suspending.
///
/// # Example
///
/// ```rust,ignore
/// // First run suspends and reports its continuation key.
/// let Err(e) = run(ctx).await else { unreachable!() };
///
/// // Second run supplies the value under that key.
/// let ctx = ctx.with_resume_values(HashMap::from([
/// ("interrupt-1".to_string(), serde_json::json!({ "approved": true })),
/// ]));
/// let output = run(ctx).await?;
/// ```
pub fn with_resume_values(mut self, resume_values: HashMap<String, Value>) -> Self {
self.resume_values = resume_values;
self
}
/// Names the checkpoint this run resumes from, so the pause it holds is answered.
///
/// Each checkpoint the run writes then lists the thread's other open pauses but not
/// that one, and retention may remove it. The `#[entrypoint]` macro passes
/// [`ExecutionConfig::resume_from`](crate::node::ExecutionConfig::resume_from).
///
/// # Example
///
/// ```rust,ignore
/// let ctx = ctx.with_resumed_from(execution_config.resume_from.clone());
/// ```
pub fn with_resumed_from(mut self, checkpoint_id: Option<String>) -> Self {
self.resumed_from = checkpoint_id;
self
}
/// The values available to interrupt sites in this context.
pub fn resume_values(&self) -> &HashMap<String, Value> {
&self.resume_values
}
/// Get the thread identifier for this context.
pub fn thread_id(&self) -> &str {
&self.thread_id
}
/// Get a reference to the cancellation token.
pub fn cancel_token(&self) -> &CancellationToken {
&self.cancel_token
}
/// Check if the workflow has been cancelled.
pub fn is_cancelled(&self) -> bool {
self.cancel_token.is_cancelled()
}
/// Get the current step number from the execution log.
pub async fn current_step(&self) -> usize {
self.execution_log.read().await.current_step()
}
/// Set a [`StateSchemaValidator`] for this context.
///
/// When set, the validator is used to validate initial state at
/// workflow start and task output before applying reducers.
pub fn with_schema_validator(mut self, validator: StateSchemaValidator) -> Self {
self.schema_validator = Some(validator);
self
}
/// Get the schema validator, if configured.
pub fn schema_validator(&self) -> Option<&StateSchemaValidator> {
self.schema_validator.as_ref()
}
/// Validate the current state against the schema validator.
///
/// Called at workflow start to validate initial state.
///
/// # Errors
///
/// Returns [`FunctionalError::SchemaValidation`] if validation fails.
pub fn validate_state(&self) -> std::result::Result<(), FunctionalError> {
if let Some(validator) = &self.schema_validator {
validator.validate_state(&self.state)?;
}
Ok(())
}
/// Validate task output against the schema validator.
///
/// Called after a task produces output, before applying reducers.
///
/// # Errors
///
/// Returns [`FunctionalError::SchemaValidation`] if validation fails.
pub fn validate_task_output(&self, output: &State) -> std::result::Result<(), FunctionalError> {
if let Some(validator) = &self.schema_validator {
validator.validate_task_output(output)?;
}
Ok(())
}
// ─── Loop Iteration Checkpoint Keying ────────────────────────────────
/// Generate a unique checkpoint key for a task inside a loop.
///
/// Each call to this method for the same `task_name` increments the
/// iteration counter, producing keys like `"step_a::iter_0"`,
/// `"step_a::iter_1"`, etc. Keys are deterministic from task name
/// and iteration index.
///
/// # Example
///
/// ```rust,ignore
/// for item in items {
/// let key = ctx.iteration_key("process_item");
/// // key = "process_item::iter_0", "process_item::iter_1", ...
/// }
/// ```
pub fn iteration_key(&mut self, task_name: &str) -> String {
let counter = self.iteration_counters.entry(task_name.to_string()).or_insert(0);
let key = format!("{task_name}::iter_{counter}");
*counter += 1;
key
}
/// Get the current iteration index for a task without incrementing.
///
/// Returns `None` if the task has not been called in a loop yet.
pub fn current_iteration(&self, task_name: &str) -> Option<usize> {
self.iteration_counters.get(task_name).copied()
}
/// Reset the iteration counter for a task.
///
/// Useful when re-entering a loop (e.g., nested loops or retry).
pub fn reset_iteration(&mut self, task_name: &str) {
self.iteration_counters.remove(task_name);
}
/// Reset all iteration counters.
pub fn reset_all_iterations(&mut self) {
self.iteration_counters.clear();
}
// ─── Route Hand-off ──────────────────────────────────────────────────
/// Records the task names this task chose, for its caller to read.
///
/// Nothing in this crate acts on the value. The functional API runs your
/// own control flow: `#[entrypoint]` calls your function once, and the
/// awaits inside it are the order of execution. So a task states its
/// choice here and the surrounding code reads it with
/// [`Self::take_pending_route`] and calls what it names.
///
/// For routing the framework performs, build the workflow with
/// [`StateGraph::add_conditional_edges`](crate::graph::StateGraph::add_conditional_edges),
/// which resolves a route key against declared targets and dispatches to
/// them.
///
/// # Example
///
/// ```
/// use std::collections::HashMap;
/// use std::sync::Arc;
///
/// use adk_graph::checkpoint::{Checkpointer, MemoryCheckpointer};
/// use adk_graph::functional::{ExecutionLog, TaskContext};
/// use tokio::sync::{RwLock, broadcast};
/// use tokio_util::sync::CancellationToken;
///
/// # fn main() {
/// let (event_tx, _rx) = broadcast::channel(8);
/// let mut ctx = TaskContext::new(
/// "thread-1".to_string(),
/// HashMap::new(),
/// Arc::new(MemoryCheckpointer::new()) as Arc<dyn Checkpointer>,
/// event_tx,
/// Arc::new(RwLock::new(ExecutionLog::new())),
/// CancellationToken::new(),
/// None,
/// );
///
/// // A task states which branches it chose.
/// ctx.route_to(&["process_a", "process_b"]);
///
/// // The surrounding code reads the choice and calls those tasks itself.
/// let chosen = ctx.take_pending_route().expect("a route was set");
/// assert_eq!(chosen, vec!["process_a".to_string(), "process_b".to_string()]);
///
/// // Reading it clears it, so the next task starts with no choice pending.
/// assert_eq!(ctx.take_pending_route(), None);
/// # }
/// ```
pub fn route_to(&mut self, targets: &[&str]) {
self.pending_route = Some(targets.iter().map(|s| s.to_string()).collect());
}
/// Takes the task names recorded by [`Self::route_to`], clearing them.
///
/// Returns `None` when no task set a route. Call this from the code that
/// sequences your tasks; nothing in this crate calls it for you.
pub fn take_pending_route(&mut self) -> Option<Vec<String>> {
self.pending_route.take()
}
// ─── Internal Methods (pub(crate)) ───────────────────────────────────
// These methods are used by the macro-generated task wrappers
// (`#[entrypoint]` and `#[task]`), not directly by user code.
/// Returns the execution-log key for the next call of `task_name`.
///
/// Advances the task's call ordinal, so two calls in one run never share a
/// key. `args` holds each argument as JSON, or `None` for one that does not
/// implement `Serialize`. The key format is documented on
/// [`super::task_call_id`].
#[doc(hidden)]
pub fn next_task_call_id(&self, task_name: &str, args: &[Option<Value>]) -> String {
let ordinal = {
let mut counters = self.task_call_counters.lock().unwrap_or_else(|e| e.into_inner());
let counter = counters.entry(task_name.to_string()).or_insert(0);
let ordinal = *counter;
*counter += 1;
ordinal
};
super::task_call_id(task_name, ordinal, args)
}
/// Check if a task was already completed in a prior run (for resume-skip).
///
/// Uses `try_read()` for synchronous non-blocking access. If the lock
/// is held, conservatively returns `false` (the task will re-execute).
/// For reliable resume-skip in async contexts, prefer [`Self::is_completed_async`].
#[allow(dead_code)]
#[doc(hidden)]
pub fn is_completed(&self, task_id: &str) -> bool {
// We need synchronous access here; use try_read to avoid blocking.
// If the lock is held, conservatively return false (task will re-execute).
match self.execution_log.try_read() {
Ok(log) => log.is_completed(task_id),
Err(_) => false,
}
}
/// Async version of [`Self::is_completed`] for reliable resume-skip behavior.
///
/// Awaits the read lock on the execution log to guarantee accurate
/// completion status. Use this in async task wrappers where blocking
/// is acceptable and correctness is required.
#[allow(dead_code)]
#[doc(hidden)]
pub async fn is_completed_async(&self, task_id: &str) -> bool {
self.execution_log.read().await.is_completed(task_id)
}
/// Get a cached result for a completed task (async).
///
/// If the task is recorded as completed, returns a clone of its
/// result value. Used by the resume-skip logic to return cached
/// results without re-executing the task.
#[allow(dead_code)]
#[doc(hidden)]
pub async fn get_cached_result(&self, task_id: &str) -> Option<Value> {
self.execution_log.read().await.get_result(task_id).cloned()
}
/// Record task completion for checkpoint tracking.
///
/// Marks the task as completed in the execution log, persists the
/// current state to the checkpointer, and advances the step counter.
/// Each task gets its own checkpoint record regardless of sibling
/// task status (parallel task independence).
#[allow(dead_code)]
#[doc(hidden)]
pub async fn record_completion(&self, task_id: &str, result: &Value) -> Result<()> {
// Update execution log — each task is recorded independently.
{
let mut log = self.execution_log.write().await;
log.record_completion(task_id, result.clone());
log.advance_step();
}
// Persist checkpoint with current state and full execution log.
let step = self.execution_log.read().await.current_step();
let checkpoint =
crate::state::Checkpoint::new(&self.thread_id, self.state.clone(), step, vec![])
.with_metadata("completed_task", Value::String(task_id.to_string()))
.with_metadata(
"execution_log",
serde_json::to_value(&*self.execution_log.read().await).unwrap_or(Value::Null),
);
self.save_checkpoint(checkpoint).await.map_err(|e| FunctionalError::CheckpointFailed {
task: task_id.to_string(),
message: e.to_string(),
})?;
Ok(())
}
/// Saves a checkpoint as the thread's next version.
///
/// Every checkpoint of a functional run goes through here, including the
/// entrypoint's own, so parallel tasks never race for one version.
#[doc(hidden)]
pub async fn save_checkpoint(
&self,
checkpoint: crate::state::Checkpoint,
) -> crate::error::Result<String> {
self.save(checkpoint, false).await
}
/// Saves `checkpoint` as the thread's next version, listing the thread's open pauses;
/// a `pause` checkpoint lists itself, so retention keeps it until a run resumes it.
async fn save(
&self,
mut checkpoint: crate::state::Checkpoint,
pause: bool,
) -> crate::error::Result<String> {
let mut head = self.head.lock().await;
let mut next = match head.take() {
Some(head) => head,
None => {
let newest = self.checkpointer.load(&self.thread_id).await?;
let mut open_pauses: std::collections::BTreeSet<String> = match &newest {
Some(newest) => newest.open_pauses()?.into_iter().collect(),
None => Default::default(),
};
if let Some(resumed) = &self.resumed_from {
open_pauses.remove(resumed);
}
Head { version: newest.map_or(0, |newest| newest.version), open_pauses }
}
};
let known = Head { version: next.version, open_pauses: next.open_pauses.clone() };
next.version += 1;
if pause {
next.open_pauses.insert(checkpoint.checkpoint_id.clone());
}
if !next.open_pauses.is_empty() {
checkpoint.metadata.insert(
crate::record::OPEN_PAUSES_METADATA_KEY.to_string(),
serde_json::to_value(&next.open_pauses)?,
);
}
match self.checkpointer.save(&checkpoint.with_version(next.version)).await {
Ok(id) => {
*head = Some(next);
Ok(id)
}
Err(error) => {
*head = Some(known);
Err(error)
}
}
}
/// Records an interrupt's answer in the execution log and checkpoints it, so a
/// crash before the next task completes cannot lose it.
async fn record_interrupt_answer(&self, continuation_key: &str, value: Value) -> Result<()> {
let checkpoint = {
let mut log = self.execution_log.write().await;
log.record_interrupt_answer(continuation_key, value);
crate::state::Checkpoint::new(
&self.thread_id,
self.state.clone(),
log.current_step(),
vec![],
)
.with_metadata("answered_interrupt", Value::String(continuation_key.to_string()))
.with_metadata("execution_log", serde_json::to_value(&*log)?)
};
self.save_checkpoint(checkpoint).await.map_err(|e| FunctionalError::CheckpointFailed {
task: continuation_key.to_string(),
message: e.to_string(),
})?;
Ok(())
}
/// Record task failure.
///
/// Marks the task as failed in the execution log and persists a
/// failure checkpoint containing the error details. Each task failure
/// is recorded independently (parallel task independence).
#[allow(dead_code)]
#[doc(hidden)]
pub async fn record_failure(&self, task_id: &str, error: &str) -> Result<()> {
// Update execution log — each task failure is independent.
{
let mut log = self.execution_log.write().await;
log.record_failure(task_id, error);
}
// Persist failure checkpoint with error context.
let step = self.execution_log.read().await.current_step();
let checkpoint =
crate::state::Checkpoint::new(&self.thread_id, self.state.clone(), step, vec![])
.with_metadata("failed_task", Value::String(task_id.to_string()))
.with_metadata("error", Value::String(error.to_string()))
.with_metadata(
"execution_log",
serde_json::to_value(&*self.execution_log.read().await).unwrap_or(Value::Null),
);
self.save_checkpoint(checkpoint).await.map_err(|e| FunctionalError::CheckpointFailed {
task: task_id.to_string(),
message: e.to_string(),
})?;
Ok(())
}
/// Record that a task has started executing.
///
/// Marks the task as running in the execution log. Used by the
/// macro-generated task wrapper before executing the task body.
#[allow(dead_code)]
#[doc(hidden)]
pub async fn record_start(&self, task_id: &str) {
let mut log = self.execution_log.write().await;
log.record_start(task_id);
}
}