adk_graph/functional/context.rs
1//! TaskContext — runtime context for functional API tasks.
2//!
3//! Provides access to state, checkpointing, interrupts, and streaming.
4//! Passed to `#[entrypoint]` and `#[task]` annotated functions.
5
6use std::collections::HashMap;
7use std::sync::Arc;
8
9use serde::de::DeserializeOwned;
10use serde_json::Value;
11use tokio::sync::RwLock;
12use tokio_util::sync::CancellationToken;
13
14use crate::checkpoint::Checkpointer;
15use crate::error::Result;
16use crate::state::{State, StateSchema};
17use crate::stream::StreamEvent;
18
19use super::error::FunctionalError;
20use super::execution_log::ExecutionLog;
21use super::schema::StateSchemaValidator;
22
23/// Runtime context passed to `#[entrypoint]` and `#[task]` functions.
24///
25/// Provides access to workflow state, checkpointing, interrupt/resume,
26/// and progress streaming. Each task function receives a mutable reference
27/// to `TaskContext` enabling state reads, writes, event emission, and
28/// interrupt requests.
29///
30/// # Example
31///
32/// ```rust,ignore
33/// use adk_graph::functional::TaskContext;
34///
35/// #[task]
36/// async fn my_step(ctx: &mut TaskContext) -> Result<Value> {
37/// // Read state
38/// let count: i64 = ctx.get("counter").unwrap_or(0);
39///
40/// // Write state
41/// ctx.set("counter", serde_json::json!(count + 1));
42///
43/// // Emit progress
44/// ctx.emit(StreamEvent::custom("my_step", "progress", serde_json::json!({"count": count + 1})));
45///
46/// Ok(serde_json::json!({"new_count": count + 1}))
47/// }
48/// ```
49pub struct TaskContext {
50 /// Thread identifier for checkpoint scoping.
51 thread_id: String,
52 /// Current workflow state.
53 state: State,
54 /// Checkpointer for persistence.
55 checkpointer: Arc<dyn Checkpointer>,
56 /// Stream event sender.
57 event_tx: tokio::sync::broadcast::Sender<StreamEvent>,
58 /// Task execution tracker (for skip-on-resume).
59 execution_log: Arc<RwLock<ExecutionLog>>,
60 /// Cancellation token.
61 cancel_token: CancellationToken,
62 /// State schema for validation.
63 schema: Option<StateSchema>,
64 /// State schema validator for functional API validation.
65 schema_validator: Option<StateSchemaValidator>,
66 /// Iteration counters for loop checkpoint keying.
67 /// Maps task_name -> current iteration index.
68 iteration_counters: HashMap<String, usize>,
69 /// Route targets set by `route_to`, read back by `take_pending_route`.
70 pending_route: Option<Vec<String>>,
71 /// Values supplied for interrupt sites, keyed by continuation key.
72 ///
73 /// Without this there was no resume channel at all: `interrupt` always returned an error and
74 /// nothing outside the method consumed a resume value, so the typed-resumption contract in
75 /// its signature could not be honoured.
76 resume_values: HashMap<String, Value>,
77 /// Counts interrupt calls so each site gets a stable key across a replay.
78 interrupt_ordinal: Arc<RwLock<usize>>,
79 /// Calls made so far of each `#[task]`, keyed by task name, so each call
80 /// gets its own execution-log key; see [`super::task_call_id`].
81 task_call_counters: std::sync::Mutex<HashMap<String, usize>>,
82 /// The thread's newest checkpoint version and open pauses, once read. Held across
83 /// each save, so parallel tasks write their checkpoints one at a time, in version
84 /// order.
85 head: tokio::sync::Mutex<Option<Head>>,
86 /// The checkpoint this run resumed from, whose pause it answers.
87 resumed_from: Option<String>,
88}
89
90/// What a functional run knows of its thread's newest checkpoint.
91struct Head {
92 version: u64,
93 /// The thread's checkpoints where a run paused and no run has resumed
94 /// ([`OPEN_PAUSES_METADATA_KEY`](crate::record::OPEN_PAUSES_METADATA_KEY)).
95 open_pauses: std::collections::BTreeSet<String>,
96}
97
98impl TaskContext {
99 /// Create a new `TaskContext`.
100 ///
101 /// Typically constructed by the macro-generated entrypoint, not by user code.
102 pub fn new(
103 thread_id: String,
104 state: State,
105 checkpointer: Arc<dyn Checkpointer>,
106 event_tx: tokio::sync::broadcast::Sender<StreamEvent>,
107 execution_log: Arc<RwLock<ExecutionLog>>,
108 cancel_token: CancellationToken,
109 schema: Option<StateSchema>,
110 ) -> Self {
111 Self {
112 thread_id,
113 state,
114 checkpointer,
115 event_tx,
116 execution_log,
117 cancel_token,
118 schema,
119 schema_validator: None,
120 iteration_counters: HashMap::new(),
121 pending_route: None,
122 resume_values: HashMap::new(),
123 interrupt_ordinal: Arc::new(RwLock::new(0)),
124 task_call_counters: std::sync::Mutex::new(HashMap::new()),
125 head: tokio::sync::Mutex::new(None),
126 resumed_from: None,
127 }
128 }
129
130 // ─── Public Methods ──────────────────────────────────────────────────
131
132 /// Get the current workflow state (read-only).
133 pub fn state(&self) -> &State {
134 &self.state
135 }
136
137 /// Get a typed value from state.
138 ///
139 /// Attempts to deserialize the value stored at `key` into type `T`.
140 /// Returns `None` if the key does not exist or deserialization fails.
141 ///
142 /// # Example
143 ///
144 /// ```rust,ignore
145 /// let count: Option<i64> = ctx.get("counter");
146 /// ```
147 pub fn get<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
148 self.state.get(key).and_then(|v| serde_json::from_value(v.clone()).ok())
149 }
150
151 /// Set a value in state.
152 ///
153 /// If a [`StateSchema`] is configured, the update is applied using the
154 /// appropriate reducer for the key. Otherwise the value is set directly
155 /// (overwrite semantics).
156 ///
157 /// # Example
158 ///
159 /// ```rust,ignore
160 /// ctx.set("counter", serde_json::json!(42));
161 /// ```
162 pub fn set(&mut self, key: &str, value: impl Into<Value>) {
163 let value = value.into();
164 if let Some(schema) = &self.schema {
165 schema.apply_update(&mut self.state, key, value);
166 } else {
167 self.state.insert(key.to_string(), value);
168 }
169 }
170
171 /// Emit a progress event to stream listeners.
172 ///
173 /// Events are broadcast to all registered receivers. If no listeners
174 /// are active the event is silently dropped.
175 ///
176 /// # Example
177 ///
178 /// ```rust,ignore
179 /// ctx.emit(StreamEvent::custom("my_task", "progress", json!({"pct": 50})));
180 /// ```
181 pub fn emit(&self, event: StreamEvent) {
182 // Ignore send errors — they indicate no active receivers.
183 let _ = self.event_tx.send(event);
184 }
185
186 /// Interrupt execution and wait for external input.
187 ///
188 /// Persists the current state as an interrupt checkpoint, emits an
189 /// interrupted event, and suspends execution. When the workflow is
190 /// resumed with an interrupt value, the value is deserialized into `T`
191 /// and returned.
192 ///
193 /// The first answer an interrupt receives is recorded in the execution log
194 /// and checkpointed before it is returned. A run resumed from any later
195 /// checkpoint, such as one written before a crash, replays the recorded
196 /// answer without it being supplied again. A recorded answer takes
197 /// precedence over a different value supplied later, because the tasks that
198 /// ran after the interrupt already acted on it.
199 ///
200 /// # Errors
201 ///
202 /// Returns [`FunctionalError::InterruptTypeMismatch`] if the resume
203 /// value cannot be deserialized into `T`.
204 ///
205 /// Returns [`FunctionalError::CheckpointFailed`] if persisting the
206 /// interrupt checkpoint, or the checkpoint that records an answer, fails.
207 ///
208 /// # Example
209 ///
210 /// ```rust,ignore
211 /// let approval: bool = ctx.interrupt("Please approve this action").await?;
212 /// ```
213 pub async fn interrupt<T: DeserializeOwned>(&self, message: &str) -> Result<T> {
214 // Each interrupt site gets a key from its position in the run. Replaying the same
215 // workflow reaches the same interrupts in the same order, so the key a caller was told
216 // to supply is the key the site looks for.
217 let continuation_key = {
218 let mut ordinal = self.interrupt_ordinal.write().await;
219 *ordinal += 1;
220 format!("interrupt-{ordinal}")
221 };
222
223 // Resume: an answer recorded by an earlier run wins, then a value supplied for this
224 // site. Either is returned to the call site, as the signature promises.
225 let recorded = self.execution_log.read().await.interrupt_answer(&continuation_key).cloned();
226 let supplied = self.resume_values.get(&continuation_key);
227 let answer = match (recorded, supplied) {
228 (Some(recorded), supplied) => {
229 if supplied.is_some_and(|value| *value != recorded) {
230 tracing::warn!(
231 interrupt.key = %continuation_key,
232 "ignoring a resume value that differs from the answer this interrupt \
233 already recorded"
234 );
235 }
236 Some((recorded, false))
237 }
238 (None, Some(value)) => Some((value.clone(), true)),
239 (None, None) => None,
240 };
241 if let Some((value, newly_supplied)) = answer {
242 let typed: T = serde_json::from_value(value.clone()).map_err(|e| {
243 FunctionalError::InterruptTypeMismatch {
244 task: continuation_key.clone(),
245 message: format!(
246 "the value supplied for {continuation_key} does not deserialize into the \
247 type this interrupt expects: {e}"
248 ),
249 }
250 })?;
251 if newly_supplied {
252 self.record_interrupt_answer(&continuation_key, value).await?;
253 }
254 return Ok(typed);
255 }
256
257 // Emit the interrupt event for stream listeners.
258 self.emit(StreamEvent::interrupted("functional_task", message));
259
260 // Persist the interrupt checkpoint. It carries the execution log so a run
261 // resumed from it replays the tasks that completed before the interrupt.
262 let checkpoint = {
263 let log = self.execution_log.read().await;
264 crate::state::Checkpoint::new(
265 &self.thread_id,
266 self.state.clone(),
267 log.current_step(),
268 vec![],
269 )
270 .with_metadata("interrupt_message", Value::String(message.to_string()))
271 .with_metadata("continuation_key", Value::String(continuation_key.clone()))
272 .with_metadata("execution_log", serde_json::to_value(&*log)?)
273 };
274
275 self.save(checkpoint, true).await.map_err(|e| FunctionalError::CheckpointFailed {
276 task: "interrupt".to_string(),
277 message: e.to_string(),
278 })?;
279
280 // Mark the current task as interrupted in the execution log.
281 {
282 let mut log = self.execution_log.write().await;
283 log.tasks.entry("__interrupt__".to_string()).or_insert(
284 super::execution_log::TaskRecord {
285 status: super::execution_log::TaskStatus::Interrupted,
286 result: None,
287 error: None,
288 started_at: chrono::Utc::now().to_rfc3339(),
289 completed_at: None,
290 attempt: 1,
291 },
292 );
293 }
294
295 Err(FunctionalError::Suspended { continuation_key, message: message.to_string() }.into())
296 }
297
298 /// Supplies values for interrupt sites, keyed by continuation key.
299 ///
300 /// Re-invoke the entrypoint with these set to resume: an interrupt whose key is present
301 /// returns the deserialized value instead of suspending.
302 ///
303 /// # Example
304 ///
305 /// ```rust,ignore
306 /// // First run suspends and reports its continuation key.
307 /// let Err(e) = run(ctx).await else { unreachable!() };
308 ///
309 /// // Second run supplies the value under that key.
310 /// let ctx = ctx.with_resume_values(HashMap::from([
311 /// ("interrupt-1".to_string(), serde_json::json!({ "approved": true })),
312 /// ]));
313 /// let output = run(ctx).await?;
314 /// ```
315 pub fn with_resume_values(mut self, resume_values: HashMap<String, Value>) -> Self {
316 self.resume_values = resume_values;
317 self
318 }
319
320 /// Names the checkpoint this run resumes from, so the pause it holds is answered.
321 ///
322 /// Each checkpoint the run writes then lists the thread's other open pauses but not
323 /// that one, and retention may remove it. The `#[entrypoint]` macro passes
324 /// [`ExecutionConfig::resume_from`](crate::node::ExecutionConfig::resume_from).
325 ///
326 /// # Example
327 ///
328 /// ```rust,ignore
329 /// let ctx = ctx.with_resumed_from(execution_config.resume_from.clone());
330 /// ```
331 pub fn with_resumed_from(mut self, checkpoint_id: Option<String>) -> Self {
332 self.resumed_from = checkpoint_id;
333 self
334 }
335
336 /// The values available to interrupt sites in this context.
337 pub fn resume_values(&self) -> &HashMap<String, Value> {
338 &self.resume_values
339 }
340
341 /// Get the thread identifier for this context.
342 pub fn thread_id(&self) -> &str {
343 &self.thread_id
344 }
345
346 /// Get a reference to the cancellation token.
347 pub fn cancel_token(&self) -> &CancellationToken {
348 &self.cancel_token
349 }
350
351 /// Check if the workflow has been cancelled.
352 pub fn is_cancelled(&self) -> bool {
353 self.cancel_token.is_cancelled()
354 }
355
356 /// Get the current step number from the execution log.
357 pub async fn current_step(&self) -> usize {
358 self.execution_log.read().await.current_step()
359 }
360
361 /// Set a [`StateSchemaValidator`] for this context.
362 ///
363 /// When set, the validator is used to validate initial state at
364 /// workflow start and task output before applying reducers.
365 pub fn with_schema_validator(mut self, validator: StateSchemaValidator) -> Self {
366 self.schema_validator = Some(validator);
367 self
368 }
369
370 /// Get the schema validator, if configured.
371 pub fn schema_validator(&self) -> Option<&StateSchemaValidator> {
372 self.schema_validator.as_ref()
373 }
374
375 /// Validate the current state against the schema validator.
376 ///
377 /// Called at workflow start to validate initial state.
378 ///
379 /// # Errors
380 ///
381 /// Returns [`FunctionalError::SchemaValidation`] if validation fails.
382 pub fn validate_state(&self) -> std::result::Result<(), FunctionalError> {
383 if let Some(validator) = &self.schema_validator {
384 validator.validate_state(&self.state)?;
385 }
386 Ok(())
387 }
388
389 /// Validate task output against the schema validator.
390 ///
391 /// Called after a task produces output, before applying reducers.
392 ///
393 /// # Errors
394 ///
395 /// Returns [`FunctionalError::SchemaValidation`] if validation fails.
396 pub fn validate_task_output(&self, output: &State) -> std::result::Result<(), FunctionalError> {
397 if let Some(validator) = &self.schema_validator {
398 validator.validate_task_output(output)?;
399 }
400 Ok(())
401 }
402
403 // ─── Loop Iteration Checkpoint Keying ────────────────────────────────
404
405 /// Generate a unique checkpoint key for a task inside a loop.
406 ///
407 /// Each call to this method for the same `task_name` increments the
408 /// iteration counter, producing keys like `"step_a::iter_0"`,
409 /// `"step_a::iter_1"`, etc. Keys are deterministic from task name
410 /// and iteration index.
411 ///
412 /// # Example
413 ///
414 /// ```rust,ignore
415 /// for item in items {
416 /// let key = ctx.iteration_key("process_item");
417 /// // key = "process_item::iter_0", "process_item::iter_1", ...
418 /// }
419 /// ```
420 pub fn iteration_key(&mut self, task_name: &str) -> String {
421 let counter = self.iteration_counters.entry(task_name.to_string()).or_insert(0);
422 let key = format!("{task_name}::iter_{counter}");
423 *counter += 1;
424 key
425 }
426
427 /// Get the current iteration index for a task without incrementing.
428 ///
429 /// Returns `None` if the task has not been called in a loop yet.
430 pub fn current_iteration(&self, task_name: &str) -> Option<usize> {
431 self.iteration_counters.get(task_name).copied()
432 }
433
434 /// Reset the iteration counter for a task.
435 ///
436 /// Useful when re-entering a loop (e.g., nested loops or retry).
437 pub fn reset_iteration(&mut self, task_name: &str) {
438 self.iteration_counters.remove(task_name);
439 }
440
441 /// Reset all iteration counters.
442 pub fn reset_all_iterations(&mut self) {
443 self.iteration_counters.clear();
444 }
445
446 // ─── Route Hand-off ──────────────────────────────────────────────────
447
448 /// Records the task names this task chose, for its caller to read.
449 ///
450 /// Nothing in this crate acts on the value. The functional API runs your
451 /// own control flow: `#[entrypoint]` calls your function once, and the
452 /// awaits inside it are the order of execution. So a task states its
453 /// choice here and the surrounding code reads it with
454 /// [`Self::take_pending_route`] and calls what it names.
455 ///
456 /// For routing the framework performs, build the workflow with
457 /// [`StateGraph::add_conditional_edges`](crate::graph::StateGraph::add_conditional_edges),
458 /// which resolves a route key against declared targets and dispatches to
459 /// them.
460 ///
461 /// # Example
462 ///
463 /// ```
464 /// use std::collections::HashMap;
465 /// use std::sync::Arc;
466 ///
467 /// use adk_graph::checkpoint::{Checkpointer, MemoryCheckpointer};
468 /// use adk_graph::functional::{ExecutionLog, TaskContext};
469 /// use tokio::sync::{RwLock, broadcast};
470 /// use tokio_util::sync::CancellationToken;
471 ///
472 /// # fn main() {
473 /// let (event_tx, _rx) = broadcast::channel(8);
474 /// let mut ctx = TaskContext::new(
475 /// "thread-1".to_string(),
476 /// HashMap::new(),
477 /// Arc::new(MemoryCheckpointer::new()) as Arc<dyn Checkpointer>,
478 /// event_tx,
479 /// Arc::new(RwLock::new(ExecutionLog::new())),
480 /// CancellationToken::new(),
481 /// None,
482 /// );
483 ///
484 /// // A task states which branches it chose.
485 /// ctx.route_to(&["process_a", "process_b"]);
486 ///
487 /// // The surrounding code reads the choice and calls those tasks itself.
488 /// let chosen = ctx.take_pending_route().expect("a route was set");
489 /// assert_eq!(chosen, vec!["process_a".to_string(), "process_b".to_string()]);
490 ///
491 /// // Reading it clears it, so the next task starts with no choice pending.
492 /// assert_eq!(ctx.take_pending_route(), None);
493 /// # }
494 /// ```
495 pub fn route_to(&mut self, targets: &[&str]) {
496 self.pending_route = Some(targets.iter().map(|s| s.to_string()).collect());
497 }
498
499 /// Takes the task names recorded by [`Self::route_to`], clearing them.
500 ///
501 /// Returns `None` when no task set a route. Call this from the code that
502 /// sequences your tasks; nothing in this crate calls it for you.
503 pub fn take_pending_route(&mut self) -> Option<Vec<String>> {
504 self.pending_route.take()
505 }
506
507 // ─── Internal Methods (pub(crate)) ───────────────────────────────────
508 // These methods are used by the macro-generated task wrappers
509 // (`#[entrypoint]` and `#[task]`), not directly by user code.
510
511 /// Returns the execution-log key for the next call of `task_name`.
512 ///
513 /// Advances the task's call ordinal, so two calls in one run never share a
514 /// key. `args` holds each argument as JSON, or `None` for one that does not
515 /// implement `Serialize`. The key format is documented on
516 /// [`super::task_call_id`].
517 #[doc(hidden)]
518 pub fn next_task_call_id(&self, task_name: &str, args: &[Option<Value>]) -> String {
519 let ordinal = {
520 let mut counters = self.task_call_counters.lock().unwrap_or_else(|e| e.into_inner());
521 let counter = counters.entry(task_name.to_string()).or_insert(0);
522 let ordinal = *counter;
523 *counter += 1;
524 ordinal
525 };
526 super::task_call_id(task_name, ordinal, args)
527 }
528
529 /// Check if a task was already completed in a prior run (for resume-skip).
530 ///
531 /// Uses `try_read()` for synchronous non-blocking access. If the lock
532 /// is held, conservatively returns `false` (the task will re-execute).
533 /// For reliable resume-skip in async contexts, prefer [`Self::is_completed_async`].
534 #[allow(dead_code)]
535 #[doc(hidden)]
536 pub fn is_completed(&self, task_id: &str) -> bool {
537 // We need synchronous access here; use try_read to avoid blocking.
538 // If the lock is held, conservatively return false (task will re-execute).
539 match self.execution_log.try_read() {
540 Ok(log) => log.is_completed(task_id),
541 Err(_) => false,
542 }
543 }
544
545 /// Async version of [`Self::is_completed`] for reliable resume-skip behavior.
546 ///
547 /// Awaits the read lock on the execution log to guarantee accurate
548 /// completion status. Use this in async task wrappers where blocking
549 /// is acceptable and correctness is required.
550 #[allow(dead_code)]
551 #[doc(hidden)]
552 pub async fn is_completed_async(&self, task_id: &str) -> bool {
553 self.execution_log.read().await.is_completed(task_id)
554 }
555
556 /// Get a cached result for a completed task (async).
557 ///
558 /// If the task is recorded as completed, returns a clone of its
559 /// result value. Used by the resume-skip logic to return cached
560 /// results without re-executing the task.
561 #[allow(dead_code)]
562 #[doc(hidden)]
563 pub async fn get_cached_result(&self, task_id: &str) -> Option<Value> {
564 self.execution_log.read().await.get_result(task_id).cloned()
565 }
566
567 /// Record task completion for checkpoint tracking.
568 ///
569 /// Marks the task as completed in the execution log, persists the
570 /// current state to the checkpointer, and advances the step counter.
571 /// Each task gets its own checkpoint record regardless of sibling
572 /// task status (parallel task independence).
573 #[allow(dead_code)]
574 #[doc(hidden)]
575 pub async fn record_completion(&self, task_id: &str, result: &Value) -> Result<()> {
576 // Update execution log — each task is recorded independently.
577 {
578 let mut log = self.execution_log.write().await;
579 log.record_completion(task_id, result.clone());
580 log.advance_step();
581 }
582
583 // Persist checkpoint with current state and full execution log.
584 let step = self.execution_log.read().await.current_step();
585 let checkpoint =
586 crate::state::Checkpoint::new(&self.thread_id, self.state.clone(), step, vec![])
587 .with_metadata("completed_task", Value::String(task_id.to_string()))
588 .with_metadata(
589 "execution_log",
590 serde_json::to_value(&*self.execution_log.read().await).unwrap_or(Value::Null),
591 );
592
593 self.save_checkpoint(checkpoint).await.map_err(|e| FunctionalError::CheckpointFailed {
594 task: task_id.to_string(),
595 message: e.to_string(),
596 })?;
597
598 Ok(())
599 }
600
601 /// Saves a checkpoint as the thread's next version.
602 ///
603 /// Every checkpoint of a functional run goes through here, including the
604 /// entrypoint's own, so parallel tasks never race for one version.
605 #[doc(hidden)]
606 pub async fn save_checkpoint(
607 &self,
608 checkpoint: crate::state::Checkpoint,
609 ) -> crate::error::Result<String> {
610 self.save(checkpoint, false).await
611 }
612
613 /// Saves `checkpoint` as the thread's next version, listing the thread's open pauses;
614 /// a `pause` checkpoint lists itself, so retention keeps it until a run resumes it.
615 async fn save(
616 &self,
617 mut checkpoint: crate::state::Checkpoint,
618 pause: bool,
619 ) -> crate::error::Result<String> {
620 let mut head = self.head.lock().await;
621 let mut next = match head.take() {
622 Some(head) => head,
623 None => {
624 let newest = self.checkpointer.load(&self.thread_id).await?;
625 let mut open_pauses: std::collections::BTreeSet<String> = match &newest {
626 Some(newest) => newest.open_pauses()?.into_iter().collect(),
627 None => Default::default(),
628 };
629 if let Some(resumed) = &self.resumed_from {
630 open_pauses.remove(resumed);
631 }
632 Head { version: newest.map_or(0, |newest| newest.version), open_pauses }
633 }
634 };
635 let known = Head { version: next.version, open_pauses: next.open_pauses.clone() };
636 next.version += 1;
637 if pause {
638 next.open_pauses.insert(checkpoint.checkpoint_id.clone());
639 }
640 if !next.open_pauses.is_empty() {
641 checkpoint.metadata.insert(
642 crate::record::OPEN_PAUSES_METADATA_KEY.to_string(),
643 serde_json::to_value(&next.open_pauses)?,
644 );
645 }
646 match self.checkpointer.save(&checkpoint.with_version(next.version)).await {
647 Ok(id) => {
648 *head = Some(next);
649 Ok(id)
650 }
651 Err(error) => {
652 *head = Some(known);
653 Err(error)
654 }
655 }
656 }
657
658 /// Records an interrupt's answer in the execution log and checkpoints it, so a
659 /// crash before the next task completes cannot lose it.
660 async fn record_interrupt_answer(&self, continuation_key: &str, value: Value) -> Result<()> {
661 let checkpoint = {
662 let mut log = self.execution_log.write().await;
663 log.record_interrupt_answer(continuation_key, value);
664 crate::state::Checkpoint::new(
665 &self.thread_id,
666 self.state.clone(),
667 log.current_step(),
668 vec![],
669 )
670 .with_metadata("answered_interrupt", Value::String(continuation_key.to_string()))
671 .with_metadata("execution_log", serde_json::to_value(&*log)?)
672 };
673
674 self.save_checkpoint(checkpoint).await.map_err(|e| FunctionalError::CheckpointFailed {
675 task: continuation_key.to_string(),
676 message: e.to_string(),
677 })?;
678 Ok(())
679 }
680
681 /// Record task failure.
682 ///
683 /// Marks the task as failed in the execution log and persists a
684 /// failure checkpoint containing the error details. Each task failure
685 /// is recorded independently (parallel task independence).
686 #[allow(dead_code)]
687 #[doc(hidden)]
688 pub async fn record_failure(&self, task_id: &str, error: &str) -> Result<()> {
689 // Update execution log — each task failure is independent.
690 {
691 let mut log = self.execution_log.write().await;
692 log.record_failure(task_id, error);
693 }
694
695 // Persist failure checkpoint with error context.
696 let step = self.execution_log.read().await.current_step();
697 let checkpoint =
698 crate::state::Checkpoint::new(&self.thread_id, self.state.clone(), step, vec![])
699 .with_metadata("failed_task", Value::String(task_id.to_string()))
700 .with_metadata("error", Value::String(error.to_string()))
701 .with_metadata(
702 "execution_log",
703 serde_json::to_value(&*self.execution_log.read().await).unwrap_or(Value::Null),
704 );
705
706 self.save_checkpoint(checkpoint).await.map_err(|e| FunctionalError::CheckpointFailed {
707 task: task_id.to_string(),
708 message: e.to_string(),
709 })?;
710
711 Ok(())
712 }
713
714 /// Record that a task has started executing.
715 ///
716 /// Marks the task as running in the execution log. Used by the
717 /// macro-generated task wrapper before executing the task body.
718 #[allow(dead_code)]
719 #[doc(hidden)]
720 pub async fn record_start(&self, task_id: &str) {
721 let mut log = self.execution_log.write().await;
722 log.record_start(task_id);
723 }
724}