Skip to main content

agent_service/manager/
run_manager.rs

1//! Coordinates run admission, bounded execution, cancellation, and durable history.
2
3use agent_metering::{ModelPricing, UsageRecord};
4
5use super::{
6    CancelRunError, CancelRunOutcome, ExecutionOutcome, ExecutionReport, ManagedRun, RunExecutor,
7    RunManagerConfigError, SubmitRunError,
8};
9use crate::{Run, RunEvent, RunEventKind, RunId, RunStatus};
10use agent_runtime::{
11    CancellationToken, EventSink, Message, RunEventKind as RuntimeRunEventKind, ToolContext,
12};
13use agent_storage::{ExecutionStore, StoredMessage, StoredRun, StoredRunEvent, StoredRunStatus};
14use chrono::{DateTime, Utc};
15use std::{
16    collections::HashMap,
17    str::FromStr,
18    sync::{Arc, RwLock},
19    time::SystemTime,
20};
21use tokio::sync::{Mutex, broadcast, mpsc};
22use tracing::{error, info};
23use uuid::Uuid;
24
25/// Coordinates run admission, in-memory state, and bounded execution.
26#[derive(Clone)]
27pub struct RunManager {
28    runs: Arc<Mutex<HashMap<RunId, ManagedRun>>>,
29    sender: mpsc::Sender<RunId>,
30    persistence: Arc<RwLock<Option<Arc<dyn ExecutionStore>>>>,
31    event_sender: broadcast::Sender<(RunId, RunEvent)>,
32}
33
34impl RunManager {
35    /// Creates an in-memory manager. Use `with_storage` to enable durability.
36    pub fn new(
37        executor: Arc<dyn RunExecutor>,
38        max_concurrent_runs: usize,
39        max_queued_runs: usize,
40    ) -> Result<Self, RunManagerConfigError> {
41        if max_concurrent_runs == 0 {
42            return Err(RunManagerConfigError::ZeroConcurrency);
43        }
44        if max_queued_runs == 0 {
45            return Err(RunManagerConfigError::ZeroQueueCapacity);
46        }
47
48        let runs = Arc::new(Mutex::new(HashMap::<RunId, ManagedRun>::new()));
49        let persistence: Arc<RwLock<Option<Arc<dyn ExecutionStore>>>> = Arc::new(RwLock::new(None));
50        let (event_sender, _) = broadcast::channel(512);
51        let (sender, receiver) = mpsc::channel(max_queued_runs);
52        let receiver = Arc::new(Mutex::new(receiver));
53
54        for _ in 0..max_concurrent_runs {
55            let runs = Arc::clone(&runs);
56            let receiver = Arc::clone(&receiver);
57            let executor = Arc::clone(&executor);
58            let persistence = Arc::clone(&persistence);
59
60            tokio::spawn(async move {
61                loop {
62                    let run_id = {
63                        let mut receiver = receiver.lock().await;
64                        receiver.recv().await
65                    };
66                    let Some(run_id) = run_id else { break };
67
68                    let (run, cancellation, history, context, history_len) = {
69                        let mut runs = runs.lock().await;
70                        let Some(entry) = runs.get_mut(&run_id) else {
71                            continue;
72                        };
73                        if entry.run.mark_running().is_err() {
74                            continue;
75                        }
76                        entry.record(RunEventKind::Started);
77                        (
78                            entry.run.clone(),
79                            entry.cancellation.clone(),
80                            entry.history.clone(),
81                            entry.context.clone(),
82                            entry.history.len(),
83                        )
84                    };
85
86                    if let Some(storage) = current_storage(&persistence)
87                        && let Err(storage_error) = persist_snapshot_and_event(
88                            storage.as_ref(),
89                            &run,
90                            &RunEvent {
91                                sequence: 1,
92                                kind: RunEventKind::Started,
93                                iteration: None,
94                                tool_name: None,
95                                model_id: None,
96                                next_model_id: None,
97                                model_candidates: None,
98                                attempted_candidates: None,
99                                error_category: None,
100                                occurred_at: SystemTime::now(),
101                            },
102                        )
103                        .await
104                    {
105                        error!(run_id = %run_id, %storage_error, "failed to persist run start");
106                    }
107
108                    info!(run_id = %run.id, agent = %run.agent, "agent run started");
109                    let (event_sender, mut event_receiver) = mpsc::unbounded_channel();
110                    let event_sink: Arc<dyn EventSink> =
111                        Arc::new(RuntimeEventChannel(event_sender));
112                    // Do not rely on every executor/tool implementation to
113                    // cooperate with the token. Dropping the execution future
114                    // here guarantees that cancellation stops the active work.
115                    let cancellation_signal = cancellation.clone();
116                    let cancellation_requested = async {
117                        while !cancellation_signal.is_cancelled() {
118                            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
119                        }
120                    };
121                    tokio::pin!(cancellation_requested);
122                    let execution = executor.execute_with_event_sink(
123                        run.id,
124                        run.agent.clone(),
125                        run.input.clone(),
126                        history,
127                        context,
128                        cancellation,
129                        event_sink,
130                    );
131                    tokio::pin!(execution);
132                    let mut events_open = true;
133                    let result = loop {
134                        tokio::select! {
135                            _ = &mut cancellation_requested => {
136                                break Ok(ExecutionReport {
137                                    outcome: ExecutionOutcome::Cancelled,
138                                    runtime_events: Vec::new(),
139                                    messages: None,
140                                });
141                            }
142                            runtime_event = event_receiver.recv(), if events_open => {
143                                match runtime_event {
144                                    Some(event) => persist_runtime_event(
145                                        &runs, &persistence, run_id, &event
146                                    ).await,
147                                    None => events_open = false,
148                                }
149                            }
150                            result = &mut execution => break result,
151                        }
152                    };
153                    // Drain events emitted immediately before the executor returned.
154                    while let Ok(event) = event_receiver.try_recv() {
155                        persist_runtime_event(&runs, &persistence, run_id, &event).await;
156                    }
157                    // Executors using the default adapter may only return a batch.
158                    if let Ok(report) = &result {
159                        for event in &report.runtime_events {
160                            persist_runtime_event(&runs, &persistence, run_id, event).await;
161                        }
162                    }
163
164                    let persisted = {
165                        let mut runs = runs.lock().await;
166                        if let Some(entry) = runs.get_mut(&run_id) {
167                            if entry.run.status != RunStatus::Running {
168                                None
169                            } else {
170                                if let Ok(report) = &result
171                                    && let Some(messages) = &report.messages
172                                {
173                                    entry.history = messages.clone();
174                                }
175                                let event = match result {
176                                    Ok(ExecutionReport {
177                                        outcome: ExecutionOutcome::Completed(response),
178                                        ..
179                                    }) => {
180                                        let _ = entry.run.complete(response);
181                                        RunEventKind::Completed
182                                    }
183                                    Ok(ExecutionReport {
184                                        outcome: ExecutionOutcome::Cancelled,
185                                        ..
186                                    }) => {
187                                        let _ = entry.run.cancel();
188                                        RunEventKind::Cancelled
189                                    }
190                                    Ok(ExecutionReport {
191                                        outcome: ExecutionOutcome::TimedOut,
192                                        ..
193                                    }) => {
194                                        let _ = entry.run.time_out();
195                                        RunEventKind::TimedOut
196                                    }
197                                    Ok(ExecutionReport {
198                                        outcome: ExecutionOutcome::MaxIterationsReached,
199                                        ..
200                                    }) => {
201                                        let _ = entry.run.reach_max_iterations();
202                                        RunEventKind::MaxIterationsReached
203                                    }
204                                    Ok(ExecutionReport {
205                                        outcome: ExecutionOutcome::Failed(error),
206                                        ..
207                                    }) => {
208                                        let _ = entry.run.fail(error);
209                                        RunEventKind::Failed
210                                    }
211                                    Err(error) => {
212                                        let _ = entry.run.fail(error);
213                                        RunEventKind::Failed
214                                    }
215                                };
216                                entry.record(event);
217                                info!(run_id = %run_id, agent = %entry.run.agent, status = ?entry.run.status, "agent run finished");
218                                Some((
219                                    entry.run.clone(),
220                                    entry
221                                        .events
222                                        .last()
223                                        .cloned()
224                                        .expect("terminal event was recorded"),
225                                    entry.history.clone(),
226                                    entry.persisted_message_count,
227                                ))
228                            }
229                        } else {
230                            None
231                        }
232                    };
233
234                    if let (
235                        Some(storage),
236                        Some((snapshot, terminal_event, messages, message_count)),
237                    ) = (current_storage(&persistence), persisted)
238                    {
239                        if let Err(storage_error) =
240                            storage.update_run(to_stored_run(&snapshot)).await
241                        {
242                            error!(run_id = %run_id, %storage_error, "failed to persist terminal run state");
243                        }
244                        if let Err(storage_error) = storage
245                            .append_event(to_stored_event(run_id, &terminal_event))
246                            .await
247                        {
248                            error!(run_id = %run_id, sequence = terminal_event.sequence, %storage_error, "failed to persist terminal run event");
249                        }
250                        // Runtime results carry the complete transcript. The initial
251                        // history and submitted user message are already durable.
252                        if let (Some(mut next_sequence), Some(conversation_id)) =
253                            (message_count, snapshot.conversation_id)
254                        {
255                            let suffix = messages.into_iter().skip(history_len + 1);
256                            for message in suffix {
257                                let stored = StoredMessage {
258                                    conversation_id,
259                                    run_id: Some(run_id.as_uuid()),
260                                    sequence: next_sequence,
261                                    message,
262                                    created_at: Utc::now(),
263                                };
264                                match storage.append_message(stored).await {
265                                    Ok(()) => next_sequence += 1,
266                                    Err(storage_error) => {
267                                        error!(run_id = %run_id, %storage_error, "failed to persist conversation message");
268                                        break;
269                                    }
270                                }
271                            }
272                        }
273                    }
274                }
275            });
276        }
277
278        Ok(Self {
279            runs,
280            sender,
281            persistence,
282            event_sender,
283        })
284    }
285
286    /// Enables durable run, event, and conversation-message persistence.
287    pub fn with_storage(self, storage: Arc<dyn ExecutionStore>) -> Self {
288        // Workers share this slot, so attaching storage immediately after
289        // construction is safe before the manager is handed to request handlers.
290        // No work should be submitted before this builder is called.
291        let mut guard = self
292            .persistence
293            .write()
294            .unwrap_or_else(|poisoned| poisoned.into_inner());
295        *guard = Some(storage);
296        drop(guard);
297        self
298    }
299
300    pub async fn submit(
301        &self,
302        agent: impl Into<String>,
303        input: impl Into<String>,
304        history: Vec<Message>,
305        context: ToolContext,
306    ) -> Result<RunId, SubmitRunError> {
307        self.submit_inner(agent, input, history, context, None)
308            .await
309    }
310
311    async fn submit_inner(
312        &self,
313        agent: impl Into<String>,
314        input: impl Into<String>,
315        history: Vec<Message>,
316        mut context: ToolContext,
317        task_id: Option<Uuid>,
318    ) -> Result<RunId, SubmitRunError> {
319        // Reserve queue capacity before touching durable state. This avoids
320        // leaving a persisted queued run behind when admission is rejected.
321        let permit = self
322            .sender
323            .try_reserve()
324            .map_err(|_| SubmitRunError::QueueFull)?;
325        let mut run = Run::new(agent, input);
326        let run_id = run.id;
327        let storage = current_storage(&self.persistence);
328        let conversation_id = if storage.is_some() {
329            context
330                .conversation_id
331                .as_deref()
332                .map(Uuid::from_str)
333                .transpose()
334                .map_err(|error| {
335                    SubmitRunError::Storage(format!("invalid conversation identifier: {error}"))
336                })?
337        } else {
338            None
339        };
340        run.conversation_id = conversation_id;
341        context.run_id = Some(run_id.as_uuid());
342        let mut persisted_message_count = None;
343        if let Some(storage) = storage {
344            if let Some(conversation_id) = conversation_id {
345                let existing = storage
346                    .list_messages(conversation_id)
347                    .await
348                    .map_err(|error| SubmitRunError::Storage(error.to_string()))?;
349                if existing.len() != history.len() {
350                    return Err(SubmitRunError::Storage(format!(
351                        "conversation history mismatch: storage has {} messages but caller supplied {}",
352                        existing.len(),
353                        history.len()
354                    )));
355                }
356                // Compare the exact structured transcript, not only its length.
357                for (stored, supplied) in existing.iter().zip(&history) {
358                    let left = serde_json::to_value(&stored.message)
359                        .map_err(|error| SubmitRunError::Storage(error.to_string()))?;
360                    let right = serde_json::to_value(supplied)
361                        .map_err(|error| SubmitRunError::Storage(error.to_string()))?;
362                    if left != right {
363                        return Err(SubmitRunError::Storage(
364                            "conversation history differs from durable history; reload before continuing".into()
365                        ));
366                    }
367                }
368                persisted_message_count = Some(existing.len() as u64 + 1);
369            }
370
371            storage
372                .insert_run(to_stored_run(&run))
373                .await
374                .map_err(|error| SubmitRunError::Storage(error.to_string()))?;
375            if let Some(task_id) = task_id {
376                storage
377                    .associate_task_run(task_id, run_id.as_uuid())
378                    .await
379                    .map_err(|error| SubmitRunError::Storage(error.to_string()))?;
380            }
381            storage
382                .append_event(to_stored_event(run_id, &queued_event()))
383                .await
384                .map_err(|error| SubmitRunError::Storage(error.to_string()))?;
385            if let Some(conversation_id) = conversation_id {
386                storage
387                    .append_message(StoredMessage {
388                        conversation_id,
389                        run_id: Some(run_id.as_uuid()),
390                        sequence: persisted_message_count.unwrap() - 1,
391                        message: Message::User {
392                            content: run.input.clone(),
393                        },
394                        created_at: Utc::now(),
395                    })
396                    .await
397                    .map_err(|error| SubmitRunError::Storage(error.to_string()))?;
398            }
399        }
400
401        let initial_event = queued_event();
402        self.runs.lock().await.insert(
403            run_id,
404            ManagedRun {
405                run,
406                cancellation: CancellationToken::new(),
407                events: vec![initial_event.clone()],
408                history,
409                context,
410                persisted_message_count,
411                event_sender: self.event_sender.clone(),
412            },
413        );
414        let _ = self.event_sender.send((run_id, initial_event));
415        permit.send(run_id);
416        info!(run_id = %run_id, "agent conversation run queued");
417        Ok(run_id)
418    }
419
420    /// Submits an execution on behalf of a scheduled task and records the
421    /// task/run association before returning the run identifier.
422    pub async fn submit_for_task(
423        &self,
424        task_id: Uuid,
425        agent: impl Into<String>,
426        input: impl Into<String>,
427        history: Vec<Message>,
428        context: ToolContext,
429    ) -> Result<RunId, SubmitRunError> {
430        if current_storage(&self.persistence).is_none() {
431            return Err(SubmitRunError::Storage(
432                "execution storage is not configured".into(),
433            ));
434        }
435        self.submit_inner(agent, input, history, context, Some(task_id))
436            .await
437    }
438
439    pub async fn cancel(&self, run_id: RunId) -> Result<CancelRunOutcome, CancelRunError> {
440        let active = {
441            let mut runs = self.runs.lock().await;
442            if let Some(entry) = runs.get_mut(&run_id) {
443                let outcome = match entry.run.status {
444                    RunStatus::Queued => {
445                        entry.cancellation.cancel();
446                        entry.run.cancel().expect("queued run can be cancelled");
447                        entry.record(RunEventKind::Cancelled);
448                        let snapshot = entry.run.clone();
449                        let event = entry.events.last().cloned().unwrap();
450                        Some((CancelRunOutcome::CancelledBeforeStart, snapshot, event))
451                    }
452                    RunStatus::Running => {
453                        if entry.cancellation.is_cancelled() {
454                            return Ok(CancelRunOutcome::AlreadyRequested);
455                        }
456                        entry.cancellation.cancel();
457                        return Ok(CancelRunOutcome::Requested);
458                    }
459                    _ => return Ok(CancelRunOutcome::AlreadyFinished),
460                };
461                outcome
462            } else {
463                None
464            }
465        };
466
467        if let Some((outcome, snapshot, event)) = active {
468            if let Some(storage) = current_storage(&self.persistence) {
469                persist_snapshot_and_event(storage.as_ref(), &snapshot, &event)
470                    .await
471                    .map_err(|error| CancelRunError::Storage(error.to_string()))?;
472            }
473            return Ok(outcome);
474        }
475
476        // A process restart discards all in-memory cancellation tokens and
477        // workers, but leaves the durable run snapshot behind. Such a run is
478        // not executing anymore and can be safely moved to a terminal state.
479        let storage = current_storage(&self.persistence).ok_or(CancelRunError::NotFound)?;
480        let Some(stored) = storage
481            .get_run(run_id.as_uuid())
482            .await
483            .map_err(|error| CancelRunError::Storage(error.to_string()))?
484        else {
485            return Err(CancelRunError::NotFound);
486        };
487        let outcome = match stored.status {
488            StoredRunStatus::Queued => CancelRunOutcome::CancelledBeforeStart,
489            StoredRunStatus::Running => CancelRunOutcome::Requested,
490            _ => return Ok(CancelRunOutcome::AlreadyFinished),
491        };
492        recover_interrupted_run(storage.as_ref(), stored)
493            .await
494            .map_err(|error| CancelRunError::Storage(error.to_string()))?;
495        Ok(outcome)
496    }
497
498    /// Cancels every active execution belonging to a conversation and waits
499    /// until its worker has observed cancellation before returning.
500    pub async fn cancel_conversation(&self, conversation_id: Uuid) -> Result<(), String> {
501        let runs = self.list().await;
502        let active = runs
503            .into_iter()
504            .filter(|run| {
505                run.conversation_id == Some(conversation_id)
506                    && matches!(run.status, RunStatus::Queued | RunStatus::Running)
507            })
508            .map(|run| run.id)
509            .collect::<Vec<_>>();
510
511        for run_id in &active {
512            self.cancel(*run_id)
513                .await
514                .map_err(|error| error.to_string())?;
515        }
516
517        tokio::time::timeout(std::time::Duration::from_secs(10), async {
518            loop {
519                let mut unfinished = false;
520                for run_id in &active {
521                    if self.get(*run_id).await.is_some_and(|run| {
522                        matches!(run.status, RunStatus::Queued | RunStatus::Running)
523                    }) {
524                        unfinished = true;
525                        break;
526                    }
527                }
528                if !unfinished {
529                    return;
530                }
531                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
532            }
533        })
534        .await
535        .map_err(|_| "timed out waiting for conversation runs to stop".to_owned())
536    }
537
538    pub async fn list(&self) -> Vec<Run> {
539        let mut by_id = HashMap::new();
540        if let Some(storage) = current_storage(&self.persistence) {
541            let in_memory_ids = self
542                .runs
543                .lock()
544                .await
545                .keys()
546                .map(|id| id.as_uuid())
547                .collect::<std::collections::HashSet<_>>();
548            match storage.list_runs(None).await {
549                Ok(stored) => {
550                    for run in stored {
551                        let run = if !in_memory_ids.contains(&run.id) {
552                            match recover_interrupted_run(storage.as_ref(), run.clone()).await {
553                                Ok(recovered) => recovered,
554                                Err(error) => {
555                                    error!(run_id = %run.id, %error, "failed to recover interrupted run");
556                                    run
557                                }
558                            }
559                        } else {
560                            run
561                        };
562                        by_id.insert(run.id, from_stored_run(run));
563                    }
564                }
565                Err(error) => error!(%error, "failed to load persisted runs"),
566            }
567        }
568        for entry in self.runs.lock().await.values() {
569            by_id.insert(entry.run.id.as_uuid(), entry.run.clone());
570        }
571        let mut result: Vec<_> = by_id.into_values().collect();
572        result.sort_by_key(|run| std::cmp::Reverse(run.created_at));
573        result
574    }
575
576    /// Subscribe to the manager-wide live event bus. Consumers filter by run ID
577    /// and load the event snapshot after subscribing to avoid missing events.
578    pub fn subscribe_events(&self) -> broadcast::Receiver<(RunId, RunEvent)> {
579        self.event_sender.subscribe()
580    }
581
582    pub async fn events(&self, run_id: RunId) -> Option<Vec<RunEvent>> {
583        if let Some(events) = self
584            .runs
585            .lock()
586            .await
587            .get(&run_id)
588            .map(|entry| entry.events.clone())
589        {
590            return Some(events);
591        }
592        let storage = current_storage(&self.persistence)?;
593        match storage.list_events(run_id.as_uuid(), None).await {
594            Ok(events) => Some(events.into_iter().map(from_stored_event).collect()),
595            Err(error) => {
596                error!(run_id = %run_id, %error, "failed to load persisted run events");
597                None
598            }
599        }
600    }
601
602    pub async fn get(&self, run_id: RunId) -> Option<Run> {
603        if let Some(run) = self
604            .runs
605            .lock()
606            .await
607            .get(&run_id)
608            .map(|entry| entry.run.clone())
609        {
610            return Some(run);
611        }
612        let storage = current_storage(&self.persistence)?;
613        match storage.get_run(run_id.as_uuid()).await {
614            Ok(Some(run)) => Some(from_stored_run(run)),
615            Ok(None) => None,
616            Err(error) => {
617                error!(run_id = %run_id, %error, "failed to load persisted run");
618                None
619            }
620        }
621    }
622
623    /// Lists the durable executions associated with one scheduled task.
624    pub async fn task_runs(&self, task_id: Uuid) -> Result<Vec<Run>, String> {
625        let Some(storage) = current_storage(&self.persistence) else {
626            return Ok(Vec::new());
627        };
628        let stored = storage
629            .list_task_runs(task_id)
630            .await
631            .map_err(|error| error.to_string())?;
632        let mut by_id = stored
633            .into_iter()
634            .map(from_stored_run)
635            .map(|run| (run.id.as_uuid(), run))
636            .collect::<HashMap<_, _>>();
637        for entry in self.runs.lock().await.values() {
638            if by_id.contains_key(&entry.run.id.as_uuid()) {
639                by_id.insert(entry.run.id.as_uuid(), entry.run.clone());
640            }
641        }
642        let mut result = by_id.into_values().collect::<Vec<_>>();
643        result.sort_by_key(|run| std::cmp::Reverse(run.created_at));
644        Ok(result)
645    }
646
647    /// Lists durable invocation usage, optionally restricted to one run.
648    pub async fn usage_records(&self, run_id: Option<RunId>) -> Result<Vec<UsageRecord>, String> {
649        let Some(storage) = current_storage(&self.persistence) else {
650            return Ok(Vec::new());
651        };
652        storage
653            .list_usage(run_id.map(|id| id.as_uuid()))
654            .await
655            .map_err(|error| error.to_string())
656    }
657
658    /// Lists all registered pricing versions for the dashboard catalogue.
659    pub async fn pricing_catalog(&self) -> Result<Vec<ModelPricing>, String> {
660        let Some(storage) = current_storage(&self.persistence) else {
661            return Ok(Vec::new());
662        };
663        storage
664            .list_all_pricing()
665            .await
666            .map_err(|error| error.to_string())
667    }
668
669    /// Registers an immutable pricing version for future cost calculations.
670    pub async fn register_pricing(&self, pricing: ModelPricing) -> Result<(), String> {
671        let Some(storage) = current_storage(&self.persistence) else {
672            return Err("usage storage is not configured".into());
673        };
674        storage
675            .insert_pricing(pricing)
676            .await
677            .map_err(|error| error.to_string())
678    }
679
680    /// Returns immutable pricing versions registered for one provider/model pair.
681    pub async fn pricing_for(
682        &self,
683        provider: &str,
684        model: &str,
685    ) -> Result<Vec<ModelPricing>, String> {
686        let Some(storage) = current_storage(&self.persistence) else {
687            return Ok(Vec::new());
688        };
689        storage
690            .list_pricing(provider, model)
691            .await
692            .map_err(|error| error.to_string())
693    }
694
695    pub async fn history(&self, run_id: RunId) -> Option<Vec<Message>> {
696        if let Some(history) = self
697            .runs
698            .lock()
699            .await
700            .get(&run_id)
701            .map(|entry| entry.history.clone())
702        {
703            return Some(history);
704        }
705        let storage = current_storage(&self.persistence)?;
706        let run = storage.get_run(run_id.as_uuid()).await.ok()??;
707        let conversation_id = run.conversation_id?;
708        storage
709            .list_messages(conversation_id)
710            .await
711            .ok()
712            .map(|messages| {
713                messages
714                    .into_iter()
715                    .map(|message| message.message)
716                    .collect()
717            })
718    }
719}
720
721struct RuntimeEventChannel(mpsc::UnboundedSender<agent_runtime::RunEvent>);
722
723impl EventSink for RuntimeEventChannel {
724    fn emit(&self, event: &agent_runtime::RunEvent) {
725        let _ = self.0.send(event.clone());
726    }
727}
728
729async fn persist_runtime_event(
730    runs: &Arc<Mutex<HashMap<RunId, ManagedRun>>>,
731    persistence: &RwLock<Option<Arc<dyn ExecutionStore>>>,
732    run_id: RunId,
733    runtime_event: &agent_runtime::RunEvent,
734) {
735    if let RuntimeRunEventKind::ModelUsageRecorded { record } = &runtime_event.kind {
736        if let Some(storage) = current_storage(persistence)
737            && let Err(error) = storage.append_usage(record.clone()).await
738        {
739            error!(run_id = %run_id, invocation_id = %record.invocation_id, %error, "failed to persist model usage record");
740        }
741        return;
742    }
743    let event = {
744        let mut runs = runs.lock().await;
745        let Some(entry) = runs.get_mut(&run_id) else {
746            return;
747        };
748        entry.record_runtime(runtime_event);
749        entry.events.last().cloned()
750    };
751    if let (Some(storage), Some(event)) = (current_storage(persistence), event)
752        && let Err(error) = storage.append_event(to_stored_event(run_id, &event)).await
753    {
754        error!(run_id = %run_id, sequence = event.sequence, %error, "failed to persist live runtime event");
755    }
756}
757
758fn current_storage(
759    slot: &RwLock<Option<Arc<dyn ExecutionStore>>>,
760) -> Option<Arc<dyn ExecutionStore>> {
761    slot.read()
762        .unwrap_or_else(|poisoned| poisoned.into_inner())
763        .clone()
764}
765
766fn queued_event() -> RunEvent {
767    RunEvent {
768        sequence: 0,
769        kind: RunEventKind::Queued,
770        iteration: None,
771        tool_name: None,
772        model_id: None,
773        next_model_id: None,
774        model_candidates: None,
775        attempted_candidates: None,
776        error_category: None,
777        occurred_at: SystemTime::now(),
778    }
779}
780
781async fn persist_snapshot_and_event(
782    storage: &dyn ExecutionStore,
783    run: &Run,
784    event: &RunEvent,
785) -> Result<(), agent_storage::StorageError> {
786    storage.update_run(to_stored_run(run)).await?;
787    storage.append_event(to_stored_event(run.id, event)).await
788}
789
790async fn recover_interrupted_run(
791    storage: &dyn ExecutionStore,
792    mut run: StoredRun,
793) -> Result<StoredRun, agent_storage::StorageError> {
794    if !matches!(
795        run.status,
796        StoredRunStatus::Queued | StoredRunStatus::Running
797    ) {
798        return Ok(run);
799    }
800
801    run.status = StoredRunStatus::Cancelled;
802    run.finished_at = Some(Utc::now());
803    run.error = Some("execution was interrupted by an application restart".into());
804    storage.update_run(run.clone()).await?;
805
806    let events = storage.list_events(run.id, None).await?;
807    storage
808        .append_event(StoredRunEvent {
809            run_id: run.id,
810            sequence: events.len() as u64,
811            kind: "cancelled".into(),
812            iteration: None,
813            tool_name: None,
814            model_id: None,
815            next_model_id: None,
816            model_candidates: None,
817            attempted_candidates: None,
818            error_category: None,
819            occurred_at: Utc::now(),
820        })
821        .await?;
822    Ok(run)
823}
824
825fn to_stored_run(run: &Run) -> StoredRun {
826    StoredRun {
827        id: run.id.as_uuid(),
828        conversation_id: run.conversation_id,
829        agent: run.agent.clone(),
830        input: run.input.clone(),
831        status: match run.status {
832            RunStatus::Queued => StoredRunStatus::Queued,
833            RunStatus::Running => StoredRunStatus::Running,
834            RunStatus::Completed => StoredRunStatus::Completed,
835            RunStatus::Failed => StoredRunStatus::Failed,
836            RunStatus::Cancelled => StoredRunStatus::Cancelled,
837            RunStatus::TimedOut => StoredRunStatus::TimedOut,
838            RunStatus::MaxIterationsReached => StoredRunStatus::MaxIterationsReached,
839        },
840        created_at: DateTime::<Utc>::from(run.created_at),
841        started_at: run.started_at.map(DateTime::<Utc>::from),
842        finished_at: run.finished_at.map(DateTime::<Utc>::from),
843        response: run.response.clone(),
844        error: run.error.clone(),
845    }
846}
847
848fn from_stored_run(run: StoredRun) -> Run {
849    Run {
850        id: RunId::from_uuid(run.id),
851        agent: run.agent,
852        input: run.input,
853        conversation_id: run.conversation_id,
854        status: match run.status {
855            StoredRunStatus::Queued => RunStatus::Queued,
856            StoredRunStatus::Running => RunStatus::Running,
857            StoredRunStatus::Completed => RunStatus::Completed,
858            StoredRunStatus::Failed => RunStatus::Failed,
859            StoredRunStatus::Cancelled => RunStatus::Cancelled,
860            StoredRunStatus::TimedOut => RunStatus::TimedOut,
861            StoredRunStatus::MaxIterationsReached => RunStatus::MaxIterationsReached,
862        },
863        created_at: run.created_at.into(),
864        started_at: run.started_at.map(Into::into),
865        finished_at: run.finished_at.map(Into::into),
866        response: run.response,
867        error: run.error,
868    }
869}
870
871fn to_stored_event(run_id: RunId, event: &RunEvent) -> StoredRunEvent {
872    StoredRunEvent {
873        run_id: run_id.as_uuid(),
874        sequence: event.sequence,
875        kind: event_kind_name(event.kind).to_owned(),
876        iteration: event.iteration,
877        tool_name: event.tool_name.clone(),
878        model_id: event.model_id.clone(),
879        next_model_id: event.next_model_id.clone(),
880        model_candidates: event.model_candidates.clone(),
881        attempted_candidates: event.attempted_candidates,
882        error_category: event.error_category.map(str::to_owned),
883        occurred_at: DateTime::<Utc>::from(event.occurred_at),
884    }
885}
886
887fn from_stored_event(event: StoredRunEvent) -> RunEvent {
888    RunEvent {
889        sequence: event.sequence,
890        kind: parse_event_kind(&event.kind).unwrap_or(RunEventKind::Failed),
891        iteration: event.iteration,
892        tool_name: event.tool_name,
893        model_id: event.model_id,
894        next_model_id: event.next_model_id,
895        model_candidates: event.model_candidates,
896        attempted_candidates: event.attempted_candidates,
897        error_category: event.error_category.as_deref().and_then(static_category),
898        occurred_at: event.occurred_at.into(),
899    }
900}
901
902fn static_category(value: &str) -> Option<&'static str> {
903    Some(match value {
904        "configuration" => "configuration",
905        "authorization" => "authorization",
906        "model" => "model",
907        "tool" => "tool",
908        "timeout" => "timeout",
909        "cancellation" => "cancellation",
910        "rate_limited" => "rate_limited",
911        "quota_exceeded" => "quota_exceeded",
912        "transient" => "transient",
913        "candidate_unavailable" => "candidate_unavailable",
914        "permanent" => "permanent",
915        _ => return None,
916    })
917}
918
919fn event_kind_name(kind: RunEventKind) -> &'static str {
920    match kind {
921        RunEventKind::Queued => "queued",
922        RunEventKind::Started => "started",
923        RunEventKind::Completed => "completed",
924        RunEventKind::Failed => "failed",
925        RunEventKind::Cancelled => "cancelled",
926        RunEventKind::TimedOut => "timed_out",
927        RunEventKind::MaxIterationsReached => "max_iterations_reached",
928        RunEventKind::ModelRequested => "model_requested",
929        RunEventKind::ModelCandidatesDiscovered => "model_candidates_discovered",
930        RunEventKind::ModelCandidateAttemptStarted => "model_candidate_attempt_started",
931        RunEventKind::ModelCandidateAttemptFailed => "model_candidate_attempt_failed",
932        RunEventKind::ModelFallback => "model_fallback",
933        RunEventKind::ModelSelected => "model_selected",
934        RunEventKind::ModelRoutingFailed => "model_routing_failed",
935        RunEventKind::ModelResponded => "model_responded",
936        RunEventKind::ToolExecutionStarted => "tool_execution_started",
937        RunEventKind::ToolExecutionFinished => "tool_execution_finished",
938        RunEventKind::ModelFailed => "model_failed",
939        RunEventKind::RuntimeCancelled => "runtime_cancelled",
940        RunEventKind::RuntimeTimedOut => "runtime_timed_out",
941    }
942}
943
944fn parse_event_kind(value: &str) -> Option<RunEventKind> {
945    Some(match value {
946        "queued" => RunEventKind::Queued,
947        "started" => RunEventKind::Started,
948        "completed" => RunEventKind::Completed,
949        "failed" => RunEventKind::Failed,
950        "cancelled" => RunEventKind::Cancelled,
951        "timed_out" => RunEventKind::TimedOut,
952        "max_iterations_reached" => RunEventKind::MaxIterationsReached,
953        "model_requested" => RunEventKind::ModelRequested,
954        "model_candidates_discovered" => RunEventKind::ModelCandidatesDiscovered,
955        "model_candidate_attempt_started" => RunEventKind::ModelCandidateAttemptStarted,
956        "model_candidate_attempt_failed" => RunEventKind::ModelCandidateAttemptFailed,
957        "model_fallback" => RunEventKind::ModelFallback,
958        "model_selected" => RunEventKind::ModelSelected,
959        "model_routing_failed" => RunEventKind::ModelRoutingFailed,
960        "model_responded" => RunEventKind::ModelResponded,
961        "tool_execution_started" => RunEventKind::ToolExecutionStarted,
962        "tool_execution_finished" => RunEventKind::ToolExecutionFinished,
963        "model_failed" => RunEventKind::ModelFailed,
964        "runtime_cancelled" => RunEventKind::RuntimeCancelled,
965        "runtime_timed_out" => RunEventKind::RuntimeTimedOut,
966        _ => return None,
967    })
968}