Skip to main content

adk_server/a2a/v1/
executor.rs

1//! A2A v1.0.0 executor — wraps task lifecycle with TaskStore persistence
2//! and state machine validation.
3//!
4//! The [`V1Executor`] creates tasks in the [`TaskStore`], validates state
5//! transitions via [`can_transition_to`], and persists status updates and
6//! artifacts throughout the task lifecycle.
7
8use std::collections::{HashMap, HashSet};
9use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
10
11use a2a_protocol_types::TaskPushNotificationConfig;
12use a2a_protocol_types::artifact::Artifact;
13use a2a_protocol_types::events::{StreamResponse, TaskArtifactUpdateEvent, TaskStatusUpdateEvent};
14use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};
15use chrono::Utc;
16use serde_json::{Map, Value};
17use tokio::sync::mpsc;
18
19use super::convert::ADK_EXTENSION_URI;
20use super::error::A2aError;
21use super::processor::ArtifactUpdate;
22use super::push::PushNotificationSender;
23use super::state_machine::can_transition_to;
24use super::task_store::{OWNER_METADATA_KEY, TaskStore, TaskStoreEntry};
25
26/// Task lifecycle management for A2A v1.0.0.
27///
28/// Wraps a [`TaskStore`] and validates every state transition against the A2A state
29/// machine. Every change to a task is made under that task's lock, so concurrent requests
30/// and a running agent never overwrite each other's updates. Each status and artifact
31/// update is sent, in order and without loss, to the task's
32/// [`subscribe`](Self::subscribe)rs, and to its push notification configs when a push
33/// sender is set.
34pub struct V1Executor {
35    task_store: Arc<dyn TaskStore>,
36    /// Live update channels by task ID, kept only for tasks that have subscribers.
37    subscribers: Mutex<HashMap<String, Vec<mpsc::UnboundedSender<StreamResponse>>>>,
38    /// One lock per task, held while the task is read and written back.
39    locks: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
40    /// Delivers updates to push notification configs.
41    push_sender: Mutex<Option<Arc<dyn PushNotificationSender>>>,
42    /// Tasks with at least one push notification config.
43    push_tasks: Mutex<HashSet<String>>,
44    /// Each pushed task's delivery queue, drained in order by its own worker.
45    push_queues: Mutex<HashMap<String, mpsc::UnboundedSender<StreamResponse>>>,
46}
47
48impl V1Executor {
49    /// Creates a new executor backed by the given task store.
50    pub fn new(task_store: Arc<dyn TaskStore>) -> Self {
51        Self {
52            task_store,
53            subscribers: Mutex::default(),
54            locks: Mutex::default(),
55            push_sender: Mutex::default(),
56            push_tasks: Mutex::default(),
57            push_queues: Mutex::default(),
58        }
59    }
60
61    /// Delivers every status and artifact update of a task with push notification configs
62    /// through `sender`, in order. A failed delivery is logged, not fatal.
63    pub fn set_push_sender(&self, sender: Arc<dyn PushNotificationSender>) {
64        *lock(&self.push_sender) = Some(sender);
65    }
66
67    /// Receives every update to `task_id` from now on, in order, until the task ends (the
68    /// channel closes after a terminal status). The receiver never misses an update.
69    pub fn subscribe(&self, task_id: &str) -> mpsc::UnboundedReceiver<StreamResponse> {
70        let (sender, receiver) = mpsc::unbounded_channel();
71        lock(&self.subscribers).entry(task_id.to_string()).or_default().push(sender);
72        receiver
73    }
74
75    /// Sends `update` to the subscribers and push notification configs of `task_id`.
76    pub fn publish(&self, task_id: &str, update: StreamResponse) {
77        let terminal = matches!(
78            &update,
79            StreamResponse::StatusUpdate(event) if is_terminal(event.status.state)
80        );
81        {
82            let mut subscribers = lock(&self.subscribers);
83            if let Some(senders) = subscribers.get_mut(task_id) {
84                senders.retain(|sender| sender.send(update.clone()).is_ok());
85                if terminal || senders.is_empty() {
86                    subscribers.remove(task_id);
87                }
88            }
89        }
90        self.dispatch_push(task_id, update, terminal);
91    }
92
93    fn dispatch_push(&self, task_id: &str, update: StreamResponse, terminal: bool) {
94        if !lock(&self.push_tasks).contains(task_id) {
95            return;
96        }
97        let Some(sender) = lock(&self.push_sender).clone() else { return };
98        let mut queues = lock(&self.push_queues);
99        let queue = queues.entry(task_id.to_string()).or_insert_with(|| {
100            spawn_push_worker(self.task_store.clone(), sender, task_id.to_string())
101        });
102        if queue.send(update).is_err() {
103            tracing::warn!(task_id, "push delivery queue closed; update not delivered");
104        }
105        if terminal {
106            // The worker delivers what is queued, then stops.
107            queues.remove(task_id);
108            lock(&self.push_tasks).remove(task_id);
109        }
110    }
111
112    /// Saves `entry` over the version it was read at, one version later.
113    async fn save_versioned(
114        &self,
115        mut entry: TaskStoreEntry,
116        version: u64,
117    ) -> Result<(), A2aError> {
118        entry.version = version + 1;
119        self.task_store.save_task_if_version(entry, version).await
120    }
121
122    /// Holds `task_id`'s lock until the guard drops.
123    async fn lock_task(&self, task_id: &str) -> tokio::sync::OwnedMutexGuard<()> {
124        let task_lock = lock(&self.locks).entry(task_id.to_string()).or_default().clone();
125        task_lock.lock_owned().await
126    }
127
128    /// Creates a new task in `Submitted` state.
129    ///
130    /// # Errors
131    ///
132    /// Returns an error if the task store fails to persist the task.
133    pub async fn create_task(
134        &self,
135        task_id: &str,
136        context_id: &str,
137    ) -> Result<TaskStoreEntry, A2aError> {
138        self.create_task_for(task_id, context_id, None).await
139    }
140
141    /// Creates a new task in `Submitted` state, owned by `owner` when one is given.
142    ///
143    /// # Errors
144    ///
145    /// Returns an error if the task store fails to persist the task.
146    pub async fn create_task_for(
147        &self,
148        task_id: &str,
149        context_id: &str,
150        owner: Option<&str>,
151    ) -> Result<TaskStoreEntry, A2aError> {
152        self.create_task_with_metadata(task_id, context_id, owner, HashMap::new()).await
153    }
154
155    /// Creates a new task in `Submitted` state with `metadata`, owned by `owner` when one
156    /// is given.
157    ///
158    /// # Errors
159    ///
160    /// Returns an error if the task store fails to persist the task.
161    pub async fn create_task_with_metadata(
162        &self,
163        task_id: &str,
164        context_id: &str,
165        owner: Option<&str>,
166        mut metadata: HashMap<String, serde_json::Value>,
167    ) -> Result<TaskStoreEntry, A2aError> {
168        let now = Utc::now();
169        if let Some(owner) = owner {
170            metadata.insert(
171                OWNER_METADATA_KEY.to_string(),
172                serde_json::Value::String(owner.to_string()),
173            );
174        }
175        let entry = TaskStoreEntry {
176            id: task_id.to_string(),
177            context_id: context_id.to_string(),
178            status: TaskStatus::with_timestamp(TaskState::Submitted),
179            artifacts: Vec::new(),
180            history: Vec::new(),
181            metadata,
182            push_configs: Vec::new(),
183            created_at: now,
184            updated_at: now,
185            version: 0,
186        };
187        self.task_store.create_task(entry.clone()).await?;
188        Ok(entry)
189    }
190
191    /// Transitions a task to a new state, with `message` as its status text.
192    ///
193    /// # Errors
194    ///
195    /// Returns [`A2aError::InvalidStateTransition`] if the transition is not allowed,
196    /// [`A2aError::TaskNotFound`] if the task does not exist, or a store error.
197    pub async fn transition_state(
198        &self,
199        task_id: &str,
200        context_id: &str,
201        new_state: TaskState,
202        message: Option<String>,
203    ) -> Result<TaskStatusUpdateEvent, A2aError> {
204        let parts = message.map(a2a_protocol_types::Part::text).into_iter().collect();
205        self.transition_state_with_parts(task_id, context_id, new_state, parts).await
206    }
207
208    /// Transitions a task to a new state, with `parts` (if any) as its status message.
209    ///
210    /// # Errors
211    ///
212    /// Returns [`A2aError::InvalidStateTransition`] if the transition is not allowed,
213    /// [`A2aError::TaskNotFound`] if the task does not exist, or a store error.
214    pub async fn transition_state_with_parts(
215        &self,
216        task_id: &str,
217        context_id: &str,
218        new_state: TaskState,
219        parts: Vec<a2a_protocol_types::Part>,
220    ) -> Result<TaskStatusUpdateEvent, A2aError> {
221        self.update_status(task_id, context_id, new_state, parts, None).await
222    }
223
224    /// Transitions a task to `new_state` with `parts` (if any) as its status message, and
225    /// sends the update with `metadata`, or the task's own metadata when `None`.
226    ///
227    /// The previous status message moves into the task's history, and `metadata` joins the
228    /// task's own, as A2A task managers do. A task an ADK agent runs marks the update with
229    /// the ADK extension.
230    ///
231    /// # Errors
232    ///
233    /// Returns [`A2aError::InvalidStateTransition`] if the transition is not allowed,
234    /// [`A2aError::TaskNotFound`] if the task does not exist, or a store error.
235    pub async fn update_status(
236        &self,
237        task_id: &str,
238        context_id: &str,
239        new_state: TaskState,
240        parts: Vec<a2a_protocol_types::Part>,
241        metadata: Option<Map<String, Value>>,
242    ) -> Result<TaskStatusUpdateEvent, A2aError> {
243        let _guard = self.lock_task(task_id).await;
244        let mut entry = self.task_store.get_task(task_id).await?;
245        let version = entry.version;
246        can_transition_to(entry.status.state, new_state)?;
247
248        let mut status = TaskStatus::with_timestamp(new_state);
249        if !parts.is_empty() {
250            status.message = Some(a2a_protocol_types::Message {
251                id: a2a_protocol_types::MessageId::new(uuid::Uuid::new_v4().to_string()),
252                role: a2a_protocol_types::MessageRole::Agent,
253                parts,
254                task_id: Some(TaskId::new(task_id)),
255                context_id: Some(ContextId::new(context_id)),
256                reference_task_ids: None,
257                extensions: None,
258                metadata: None,
259            });
260        }
261        if let Some(previous) = entry.status.message.take() {
262            entry.history.push(previous);
263        }
264        entry.status = status.clone();
265        entry.updated_at = Utc::now();
266        // The task takes on what each status update says about it, as a2a-go applies one.
267        if let Some(metadata) = &metadata {
268            for (key, value) in metadata.iter().filter(|(key, _)| *key != OWNER_METADATA_KEY) {
269                entry.metadata.insert(key.clone(), value.clone());
270            }
271        }
272        let adk_task = entry.metadata.contains_key(ADK_EXTENSION_URI);
273        let mut metadata = metadata.unwrap_or_else(|| task_metadata(&entry));
274        self.save_versioned(entry, version).await?;
275        if adk_task {
276            metadata.insert(ADK_EXTENSION_URI.to_string(), Value::Bool(true));
277        }
278
279        let event = TaskStatusUpdateEvent {
280            task_id: TaskId::new(task_id),
281            context_id: ContextId::new(context_id),
282            status,
283            metadata: (!metadata.is_empty()).then_some(Value::Object(metadata)),
284        };
285        self.publish(task_id, StreamResponse::StatusUpdate(event.clone()));
286        Ok(event)
287    }
288
289    /// Records an artifact for a task and sends it to the task's subscribers.
290    ///
291    /// Persists the artifact to the task store, sends it to the task's subscribers, and
292    /// returns the corresponding [`TaskArtifactUpdateEvent`].
293    ///
294    /// # Errors
295    ///
296    /// Returns [`A2aError::TaskNotFound`] if the task does not exist, or a store error.
297    pub async fn record_artifact(
298        &self,
299        task_id: &str,
300        context_id: &str,
301        artifact: Artifact,
302    ) -> Result<TaskArtifactUpdateEvent, A2aError> {
303        let event = self.persist_artifact(task_id, context_id, artifact).await?;
304        self.publish(task_id, StreamResponse::ArtifactUpdate(event.clone()));
305        Ok(event)
306    }
307
308    /// Records an artifact for a task without sending it to the task's subscribers.
309    ///
310    /// # Errors
311    ///
312    /// Returns [`A2aError::TaskNotFound`] if the task does not exist, or a store error.
313    pub async fn persist_artifact(
314        &self,
315        task_id: &str,
316        context_id: &str,
317        artifact: Artifact,
318    ) -> Result<TaskArtifactUpdateEvent, A2aError> {
319        let _guard = self.lock_task(task_id).await;
320        let mut entry = self.task_store.get_task(task_id).await?;
321        let version = entry.version;
322        merge_artifact(&mut entry.artifacts, artifact.clone(), false);
323        entry.updated_at = Utc::now();
324        let metadata = task_metadata(&entry);
325        self.save_versioned(entry, version).await?;
326
327        let event = TaskArtifactUpdateEvent {
328            task_id: TaskId::new(task_id),
329            context_id: ContextId::new(context_id),
330            artifact,
331            append: None,
332            last_chunk: None,
333            metadata: (!metadata.is_empty()).then_some(Value::Object(metadata)),
334        };
335        Ok(event)
336    }
337
338    /// Applies one of a run's artifact updates to the task, as A2A task managers do: the
339    /// same artifact ID with `append` adds its parts and metadata, without `append`
340    /// replaces the artifact. Sends the update to the task's subscribers.
341    ///
342    /// # Errors
343    ///
344    /// Returns [`A2aError::TaskNotFound`] if the task does not exist, or a store error.
345    pub(super) async fn apply_artifact_update(
346        &self,
347        task_id: &str,
348        context_id: &str,
349        update: ArtifactUpdate,
350    ) -> Result<TaskArtifactUpdateEvent, A2aError> {
351        {
352            let _guard = self.lock_task(task_id).await;
353            let mut entry = self.task_store.get_task(task_id).await?;
354            let version = entry.version;
355            merge_artifact(&mut entry.artifacts, update.artifact.clone(), update.append);
356            entry.updated_at = Utc::now();
357            self.save_versioned(entry, version).await?;
358        }
359        let event = TaskArtifactUpdateEvent {
360            task_id: TaskId::new(task_id),
361            context_id: ContextId::new(context_id),
362            artifact: update.artifact,
363            append: Some(update.append),
364            last_chunk: Some(update.last_chunk),
365            metadata: update.metadata.filter(|meta| !meta.is_empty()).map(Value::Object),
366        };
367        self.publish(task_id, StreamResponse::ArtifactUpdate(event.clone()));
368        Ok(event)
369    }
370
371    /// Saves `config` on the task, replacing a config with the same ID.
372    ///
373    /// # Errors
374    ///
375    /// Returns [`A2aError::TaskNotFound`] if the task does not exist, or a store error.
376    pub async fn save_push_config(
377        &self,
378        task_id: &str,
379        config: TaskPushNotificationConfig,
380    ) -> Result<TaskPushNotificationConfig, A2aError> {
381        let _guard = self.lock_task(task_id).await;
382        let mut entry = self.task_store.get_task(task_id).await?;
383        let version = entry.version;
384        match entry.push_configs.iter_mut().find(|existing| existing.id == config.id) {
385            Some(existing) => *existing = config.clone(),
386            None => entry.push_configs.push(config.clone()),
387        }
388        entry.updated_at = Utc::now();
389        self.save_versioned(entry, version).await?;
390        lock(&self.push_tasks).insert(task_id.to_string());
391        Ok(config)
392    }
393
394    /// Removes the push config `config_id` from the task. Removing a config the task does
395    /// not have succeeds, as A2A config stores do.
396    ///
397    /// # Errors
398    ///
399    /// Returns [`A2aError::TaskNotFound`] if the task does not exist, or a store error.
400    pub async fn delete_push_config(&self, task_id: &str, config_id: &str) -> Result<(), A2aError> {
401        let _guard = self.lock_task(task_id).await;
402        let mut entry = self.task_store.get_task(task_id).await?;
403        let version = entry.version;
404        entry.push_configs.retain(|config| config.id.as_deref() != Some(config_id));
405        let empty = entry.push_configs.is_empty();
406        entry.updated_at = Utc::now();
407        self.save_versioned(entry, version).await?;
408        if empty {
409            lock(&self.push_tasks).remove(task_id);
410        }
411        Ok(())
412    }
413
414    /// Appends `message` to the task's history.
415    ///
416    /// # Errors
417    ///
418    /// Returns [`A2aError::TaskNotFound`] if the task does not exist, or a store error.
419    pub async fn add_history_message(
420        &self,
421        task_id: &str,
422        message: a2a_protocol_types::Message,
423    ) -> Result<(), A2aError> {
424        let _guard = self.lock_task(task_id).await;
425        let mut entry = self.task_store.get_task(task_id).await?;
426        let version = entry.version;
427        entry.history.push(message);
428        entry.updated_at = Utc::now();
429        self.save_versioned(entry, version).await
430    }
431
432    /// Takes a task that waits on its caller for a run: moves it from `INPUT_REQUIRED` or
433    /// `AUTH_REQUIRED` back to `SUBMITTED` and records `message`, all under the task's
434    /// lock, so a second message that races this one finds the task taken.
435    ///
436    /// # Errors
437    ///
438    /// Returns [`A2aError::UnsupportedOperation`] when the task does not wait on its caller,
439    /// [`A2aError::TaskNotFound`] if the task does not exist, or a store error.
440    pub async fn claim_waiting_task(
441        &self,
442        task_id: &str,
443        message: a2a_protocol_types::Message,
444    ) -> Result<TaskStoreEntry, A2aError> {
445        let _guard = self.lock_task(task_id).await;
446        let mut entry = self.task_store.get_task(task_id).await?;
447        let version = entry.version;
448        if !matches!(entry.status.state, TaskState::InputRequired | TaskState::AuthRequired) {
449            return Err(A2aError::UnsupportedOperation {
450                method: format!("a message to task {task_id} while it is {:?}", entry.status.state),
451            });
452        }
453        if let Some(previous) = entry.status.message.take() {
454            entry.history.push(previous);
455        }
456        entry.history.push(message);
457        entry.status = TaskStatus::with_timestamp(TaskState::Submitted);
458        entry.updated_at = Utc::now();
459        entry.version = version + 1;
460        self.task_store.save_task_if_version(entry.clone(), version).await?;
461        Ok(entry)
462    }
463
464    /// Asks a waiting task's caller again for the call `missing` that `message` left
465    /// unanswered, as adk-go does: records `message`, keeps the task `INPUT_REQUIRED`, and
466    /// sends a status whose message repeats the pending calls and adds
467    /// `no input provided for function call ID "<missing>"`, marked `validation_error`.
468    ///
469    /// # Errors
470    ///
471    /// Returns [`A2aError::TaskNotFound`] if the task does not exist, or a store error.
472    pub async fn ask_again(
473        &self,
474        task_id: &str,
475        message: a2a_protocol_types::Message,
476        missing: &str,
477    ) -> Result<TaskStatusUpdateEvent, A2aError> {
478        let _guard = self.lock_task(task_id).await;
479        let mut entry = self.task_store.get_task(task_id).await?;
480        let version = entry.version;
481        let previous = entry.status.message.take();
482        let mut parts: Vec<a2a_protocol_types::Part> = previous
483            .as_ref()
484            .map(|previous| {
485                previous
486                    .parts
487                    .iter()
488                    .filter(|part| {
489                        part.metadata
490                            .as_ref()
491                            .and_then(|meta| meta.get(VALIDATION_ERROR_METADATA_KEY))
492                            != Some(&Value::Bool(true))
493                    })
494                    .cloned()
495                    .collect()
496            })
497            .unwrap_or_default();
498        let mut notice = a2a_protocol_types::Part::text(format!(
499            "no input provided for function call ID {missing:?}"
500        ));
501        notice.metadata = Some(serde_json::json!({ VALIDATION_ERROR_METADATA_KEY: true }));
502        parts.push(notice);
503        if let Some(previous) = previous {
504            entry.history.push(previous);
505        }
506        entry.history.push(message);
507        let context_id = entry.context_id.clone();
508        let mut status = TaskStatus::with_timestamp(TaskState::InputRequired);
509        status.message = Some(a2a_protocol_types::Message {
510            id: a2a_protocol_types::MessageId::new(uuid::Uuid::new_v4().to_string()),
511            role: a2a_protocol_types::MessageRole::Agent,
512            parts,
513            task_id: Some(TaskId::new(task_id)),
514            context_id: Some(ContextId::new(&context_id)),
515            reference_task_ids: None,
516            extensions: None,
517            metadata: None,
518        });
519        entry.status = status.clone();
520        entry.updated_at = Utc::now();
521        let adk_task = entry.metadata.contains_key(ADK_EXTENSION_URI);
522        self.save_versioned(entry, version).await?;
523        let event = TaskStatusUpdateEvent {
524            task_id: TaskId::new(task_id),
525            context_id: ContextId::new(&context_id),
526            status,
527            metadata: adk_task.then(|| serde_json::json!({ ADK_EXTENSION_URI: true })),
528        };
529        self.publish(task_id, StreamResponse::StatusUpdate(event.clone()));
530        Ok(event)
531    }
532
533    /// Transitions a task to `Failed` with an error message.
534    ///
535    /// # Errors
536    ///
537    /// Returns [`A2aError::InvalidStateTransition`] if the task is already in a terminal
538    /// state, or a store error.
539    pub async fn fail_task(
540        &self,
541        task_id: &str,
542        context_id: &str,
543        error_message: &str,
544    ) -> Result<TaskStatusUpdateEvent, A2aError> {
545        self.transition_state_with_parts(
546            task_id,
547            context_id,
548            TaskState::Failed,
549            vec![super::convert::error_message_part(error_message)],
550        )
551        .await
552    }
553
554    /// Returns a reference to the underlying task store.
555    pub fn task_store(&self) -> &Arc<dyn TaskStore> {
556        &self.task_store
557    }
558}
559
560/// Part metadata `validation_error`: the text says which pending call an answer missed.
561pub const VALIDATION_ERROR_METADATA_KEY: &str = "validation_error";
562
563/// The task's metadata as its updates carry it: without the owner.
564fn task_metadata(entry: &TaskStoreEntry) -> Map<String, Value> {
565    entry
566        .metadata
567        .iter()
568        .filter(|(key, _)| *key != OWNER_METADATA_KEY)
569        .map(|(k, v)| (k.clone(), v.clone()))
570        .collect()
571}
572
573/// Adds `artifact` to `artifacts`: with `append`, its parts and metadata go onto the
574/// artifact with the same ID; otherwise it replaces that artifact. An artifact with a new
575/// ID is added at the end.
576fn merge_artifact(artifacts: &mut Vec<Artifact>, artifact: Artifact, append: bool) {
577    let Some(existing) = artifacts.iter_mut().find(|existing| existing.id == artifact.id) else {
578        artifacts.push(artifact);
579        return;
580    };
581    if !append {
582        *existing = artifact;
583        return;
584    }
585    existing.parts.extend(artifact.parts);
586    if let Some(Value::Object(added)) = artifact.metadata {
587        match &mut existing.metadata {
588            Some(Value::Object(metadata)) => metadata.extend(added),
589            _ => existing.metadata = Some(Value::Object(added)),
590        }
591    }
592}
593
594/// Starts a worker that delivers `task_id`'s queued updates to the task's push configs, in
595/// order, and stops when the queue closes.
596fn spawn_push_worker(
597    store: Arc<dyn TaskStore>,
598    sender: Arc<dyn PushNotificationSender>,
599    task_id: String,
600) -> mpsc::UnboundedSender<StreamResponse> {
601    let (queue, mut updates) = mpsc::unbounded_channel::<StreamResponse>();
602    tokio::spawn(async move {
603        while let Some(update) = updates.recv().await {
604            let configs = match store.get_task(&task_id).await {
605                Ok(entry) => entry.push_configs,
606                Err(_) => return,
607            };
608            for config in &configs {
609                if let Err(error) = sender.send_update(&update, config).await {
610                    tracing::warn!(%task_id, url = %config.url, %error, "push notification not delivered");
611                }
612            }
613        }
614    });
615    queue
616}
617
618fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
619    mutex.lock().unwrap_or_else(PoisonError::into_inner)
620}
621
622fn is_terminal(state: TaskState) -> bool {
623    matches!(
624        state,
625        TaskState::Completed | TaskState::Failed | TaskState::Canceled | TaskState::Rejected
626    )
627}
628
629#[cfg(test)]
630mod tests {
631    use super::super::task_store::InMemoryTaskStore;
632    use super::*;
633
634    fn make_executor() -> V1Executor {
635        V1Executor::new(Arc::new(InMemoryTaskStore::new()))
636    }
637
638    /// Asserts that a timestamp is `Some` and looks like a valid RFC 3339 string.
639    fn assert_valid_timestamp(ts: &Option<String>) {
640        let ts = ts.as_ref().expect("timestamp should be Some");
641        assert!(ts.contains('T'), "timestamp should contain 'T': {ts}");
642        assert!(ts.len() >= 19, "timestamp should be at least 19 chars: {ts}");
643    }
644
645    #[tokio::test]
646    async fn create_task_persists_with_submitted_state() {
647        let executor = make_executor();
648        let entry = executor.create_task("t1", "ctx-1").await.unwrap();
649
650        assert_eq!(entry.id, "t1");
651        assert_eq!(entry.context_id, "ctx-1");
652        assert_eq!(entry.status.state, TaskState::Submitted);
653        assert_valid_timestamp(&entry.status.timestamp);
654
655        // Verify persisted in store
656        let stored = executor.task_store().get_task("t1").await.unwrap();
657        assert_eq!(stored.id, "t1");
658        assert_eq!(stored.status.state, TaskState::Submitted);
659        assert_valid_timestamp(&stored.status.timestamp);
660    }
661
662    #[tokio::test]
663    async fn transition_state_validates_and_persists() {
664        let executor = make_executor();
665        executor.create_task("t1", "ctx-1").await.unwrap();
666
667        let event =
668            executor.transition_state("t1", "ctx-1", TaskState::Working, None).await.unwrap();
669
670        assert_eq!(event.task_id, TaskId::new("t1"));
671        assert_eq!(event.context_id, ContextId::new("ctx-1"));
672        assert_eq!(event.status.state, TaskState::Working);
673        assert_valid_timestamp(&event.status.timestamp);
674
675        // Verify persisted
676        let stored = executor.task_store().get_task("t1").await.unwrap();
677        assert_eq!(stored.status.state, TaskState::Working);
678        assert_valid_timestamp(&stored.status.timestamp);
679    }
680
681    #[tokio::test]
682    async fn transition_state_with_message() {
683        let executor = make_executor();
684        executor.create_task("t1", "ctx-1").await.unwrap();
685
686        let event = executor
687            .transition_state(
688                "t1",
689                "ctx-1",
690                TaskState::Working,
691                Some("processing started".to_string()),
692            )
693            .await
694            .unwrap();
695
696        assert!(event.status.message.is_some());
697        let msg = event.status.message.unwrap();
698        assert_eq!(msg.parts.len(), 1);
699    }
700
701    #[tokio::test]
702    async fn transition_state_rejects_invalid_transition() {
703        let executor = make_executor();
704        executor.create_task("t1", "ctx-1").await.unwrap();
705
706        // SUBMITTED → COMPLETED is not allowed
707        let err =
708            executor.transition_state("t1", "ctx-1", TaskState::Completed, None).await.unwrap_err();
709
710        let msg = err.to_string();
711        assert!(msg.contains("SUBMITTED"));
712        assert!(msg.contains("COMPLETED"));
713    }
714
715    #[tokio::test]
716    async fn transition_state_task_not_found() {
717        let executor = make_executor();
718
719        let err = executor
720            .transition_state("nonexistent", "ctx-1", TaskState::Working, None)
721            .await
722            .unwrap_err();
723
724        let msg = err.to_string();
725        assert!(msg.contains("nonexistent"));
726    }
727
728    #[tokio::test]
729    async fn record_artifact_persists_and_returns_event() {
730        let executor = make_executor();
731        executor.create_task("t1", "ctx-1").await.unwrap();
732
733        let artifact = Artifact::new(
734            a2a_protocol_types::ArtifactId::new("art-1"),
735            vec![a2a_protocol_types::Part::text("result")],
736        );
737
738        let event = executor.record_artifact("t1", "ctx-1", artifact).await.unwrap();
739
740        assert_eq!(event.task_id, TaskId::new("t1"));
741        assert_eq!(event.context_id, ContextId::new("ctx-1"));
742        assert_eq!(event.artifact.id, a2a_protocol_types::ArtifactId::new("art-1"));
743
744        // Verify persisted
745        let stored = executor.task_store().get_task("t1").await.unwrap();
746        assert_eq!(stored.artifacts.len(), 1);
747    }
748
749    #[tokio::test]
750    async fn record_artifact_task_not_found() {
751        let executor = make_executor();
752
753        let artifact = Artifact::new(
754            a2a_protocol_types::ArtifactId::new("art-1"),
755            vec![a2a_protocol_types::Part::text("result")],
756        );
757
758        let err = executor.record_artifact("nonexistent", "ctx-1", artifact).await.unwrap_err();
759
760        let msg = err.to_string();
761        assert!(msg.contains("nonexistent"));
762    }
763
764    #[tokio::test]
765    async fn fail_task_transitions_to_failed() {
766        let executor = make_executor();
767        executor.create_task("t1", "ctx-1").await.unwrap();
768        executor.transition_state("t1", "ctx-1", TaskState::Working, None).await.unwrap();
769
770        let event = executor.fail_task("t1", "ctx-1", "something went wrong").await.unwrap();
771
772        assert_eq!(event.status.state, TaskState::Failed);
773        assert!(event.status.message.is_some());
774
775        // Verify persisted
776        let stored = executor.task_store().get_task("t1").await.unwrap();
777        assert_eq!(stored.status.state, TaskState::Failed);
778    }
779
780    #[tokio::test]
781    async fn fail_task_from_terminal_state_is_rejected() {
782        let executor = make_executor();
783        executor.create_task("t1", "ctx-1").await.unwrap();
784        executor.transition_state("t1", "ctx-1", TaskState::Working, None).await.unwrap();
785        executor.transition_state("t1", "ctx-1", TaskState::Completed, None).await.unwrap();
786
787        // COMPLETED → FAILED is not allowed
788        let err = executor.fail_task("t1", "ctx-1", "late error").await.unwrap_err();
789
790        let msg = err.to_string();
791        assert!(msg.contains("COMPLETED"));
792        assert!(msg.contains("FAILED"));
793    }
794
795    #[tokio::test]
796    async fn full_lifecycle_submitted_working_completed() {
797        let executor = make_executor();
798
799        // Create task (SUBMITTED)
800        let entry = executor.create_task("t1", "ctx-1").await.unwrap();
801        assert_eq!(entry.status.state, TaskState::Submitted);
802        assert_valid_timestamp(&entry.status.timestamp);
803
804        // Transition to WORKING
805        let event =
806            executor.transition_state("t1", "ctx-1", TaskState::Working, None).await.unwrap();
807        assert_eq!(event.status.state, TaskState::Working);
808        assert_valid_timestamp(&event.status.timestamp);
809
810        // Record artifact
811        let artifact = Artifact::new(
812            a2a_protocol_types::ArtifactId::new("art-1"),
813            vec![a2a_protocol_types::Part::text("output")],
814        );
815        let art_event = executor.record_artifact("t1", "ctx-1", artifact).await.unwrap();
816        assert_eq!(art_event.artifact.id, a2a_protocol_types::ArtifactId::new("art-1"));
817
818        // Transition to COMPLETED
819        let event =
820            executor.transition_state("t1", "ctx-1", TaskState::Completed, None).await.unwrap();
821        assert_eq!(event.status.state, TaskState::Completed);
822        assert_valid_timestamp(&event.status.timestamp);
823
824        // Verify final state in store
825        let stored = executor.task_store().get_task("t1").await.unwrap();
826        assert_eq!(stored.status.state, TaskState::Completed);
827        assert_eq!(stored.artifacts.len(), 1);
828        assert_valid_timestamp(&stored.status.timestamp);
829    }
830
831    #[tokio::test]
832    async fn metadata_included_in_events() {
833        let store = Arc::new(InMemoryTaskStore::new());
834        let executor = V1Executor::new(store.clone());
835
836        // Create task with metadata
837        let now = Utc::now();
838        let mut metadata = HashMap::new();
839        metadata.insert("key".to_string(), serde_json::json!("value"));
840        let entry = TaskStoreEntry {
841            id: "t1".to_string(),
842            context_id: "ctx-1".to_string(),
843            status: TaskStatus::new(TaskState::Submitted),
844            artifacts: Vec::new(),
845            history: Vec::new(),
846            metadata,
847            push_configs: Vec::new(),
848            created_at: now,
849            updated_at: now,
850            version: 0,
851        };
852        store.create_task(entry).await.unwrap();
853
854        // Transition — metadata should be included in event
855        let event =
856            executor.transition_state("t1", "ctx-1", TaskState::Working, None).await.unwrap();
857
858        assert!(event.metadata.is_some());
859        let meta = event.metadata.unwrap();
860        assert_eq!(meta["key"], "value");
861    }
862
863    #[tokio::test]
864    async fn context_id_included_in_status_event() {
865        let executor = make_executor();
866        executor.create_task("t1", "ctx-abc").await.unwrap();
867
868        let event =
869            executor.transition_state("t1", "ctx-abc", TaskState::Working, None).await.unwrap();
870
871        assert_eq!(event.context_id, ContextId::new("ctx-abc"));
872    }
873
874    #[tokio::test]
875    async fn context_id_included_in_artifact_event() {
876        let executor = make_executor();
877        executor.create_task("t1", "ctx-abc").await.unwrap();
878
879        let artifact = Artifact::new(
880            a2a_protocol_types::ArtifactId::new("art-1"),
881            vec![a2a_protocol_types::Part::text("data")],
882        );
883
884        let event = executor.record_artifact("t1", "ctx-abc", artifact).await.unwrap();
885
886        assert_eq!(event.context_id, ContextId::new("ctx-abc"));
887    }
888
889    #[tokio::test]
890    async fn artifact_updates_append_to_or_replace_the_artifact_with_their_id() {
891        use super::super::processor::ArtifactUpdate;
892        use a2a_protocol_types::artifact::ArtifactId;
893        let executor = make_executor();
894        executor.create_task("t-merge", "ctx").await.unwrap();
895        let update = |id: &str, text: &str, append: bool| ArtifactUpdate {
896            artifact: Artifact::new(
897                ArtifactId::new(id),
898                vec![a2a_protocol_types::Part::text(text)],
899            ),
900            append,
901            last_chunk: false,
902            metadata: None,
903        };
904        let mut updates = executor.subscribe("t-merge");
905        for (id, text, append) in
906            [("a", "one", false), ("a", "two", true), ("b", "temp", false), ("b", "new", false)]
907        {
908            executor
909                .apply_artifact_update("t-merge", "ctx", update(id, text, append))
910                .await
911                .unwrap();
912        }
913
914        let entry = executor.task_store().get_task("t-merge").await.unwrap();
915        let texts: Vec<Vec<&str>> = entry
916            .artifacts
917            .iter()
918            .map(|artifact| artifact.parts.iter().filter_map(|part| part.text_content()).collect())
919            .collect();
920        assert_eq!(texts, vec![vec!["one", "two"], vec!["new"]]);
921        let mut sent = 0;
922        while let Ok(update) = updates.try_recv() {
923            assert!(matches!(update, StreamResponse::ArtifactUpdate(_)));
924            sent += 1;
925        }
926        assert_eq!(sent, 4, "a subscriber gets every update");
927    }
928
929    #[tokio::test]
930    async fn task_store_accessor() {
931        let store = Arc::new(InMemoryTaskStore::new());
932        let executor = V1Executor::new(store.clone());
933
934        // Verify task_store() returns the same store
935        executor.create_task("t1", "ctx-1").await.unwrap();
936        let task = executor.task_store().get_task("t1").await.unwrap();
937        assert_eq!(task.id, "t1");
938    }
939}