1use std::collections::BTreeMap;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicU64, Ordering};
4
5use async_trait::async_trait;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use sha2::{Digest, Sha256};
9use thiserror::Error;
10use tokio::sync::Mutex;
11
12use crate::{ConnectorDescription, ExecutionCheckpoint};
13
14pub const DEFAULT_MAX_EXECUTIONS: usize = 50;
16pub const DEFAULT_AUTO_PRUNE_GRACE_MS: u64 = 60_000;
18pub const MAX_DURABLE_VALUE_BYTES: usize = 1_000_000;
20pub const DEFAULT_PAUSED_TTL_MS: u64 = 24 * 60 * 60 * 1_000;
22pub const DEFAULT_MAX_EVENTS: usize = 1_000;
24
25static EXECUTION_SEQUENCE: AtomicU64 = AtomicU64::new(0);
26
27#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct CapabilitySnapshot {
30 pub connectors: Vec<ConnectorDescription>,
32 pub fingerprint: String,
34}
35
36impl CapabilitySnapshot {
37 pub fn new(connectors: Vec<ConnectorDescription>) -> Result<Self, String> {
39 let bytes = serde_json::to_vec(&connectors).map_err(|error| error.to_string())?;
40 Ok(Self {
41 connectors,
42 fingerprint: format!("{:x}", Sha256::digest(bytes)),
43 })
44 }
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize)]
49pub struct ArtifactRef {
50 pub id: String,
52 pub execution_id: String,
54 pub bytes: usize,
56 pub preview: String,
58}
59
60#[async_trait]
62#[allow(
63 clippy::double_must_use,
64 reason = "async_trait annotates generated futures"
65)]
66pub trait ArtifactStore: Send + Sync {
67 async fn put(&self, execution_id: &str, value: &Value) -> Result<ArtifactRef, String>;
69 async fn get(&self, execution_id: &str, artifact_id: &str) -> Result<Option<Value>, String>;
71 async fn delete_execution(&self, execution_id: &str) -> Result<(), String>;
73}
74
75#[derive(Clone)]
76struct MemoryArtifact {
77 execution_id: String,
78 value: Value,
79}
80
81#[derive(Default)]
83pub struct MemoryArtifactStore {
84 values: Mutex<BTreeMap<String, MemoryArtifact>>,
85}
86
87#[async_trait]
88impl ArtifactStore for MemoryArtifactStore {
89 async fn put(&self, execution_id: &str, value: &Value) -> Result<ArtifactRef, String> {
90 let bytes = serde_json::to_vec(value).map_err(|error| error.to_string())?;
91 let id = format!(
92 "{:x}",
93 Sha256::digest([execution_id.as_bytes(), &bytes].concat())
94 );
95 self.values.lock().await.insert(
96 id.clone(),
97 MemoryArtifact {
98 execution_id: execution_id.to_string(),
99 value: value.clone(),
100 },
101 );
102 Ok(ArtifactRef {
103 id,
104 execution_id: execution_id.to_string(),
105 bytes: bytes.len(),
106 preview: truncate_bytes(String::from_utf8_lossy(&bytes).into_owned(), 512),
107 })
108 }
109
110 async fn get(&self, execution_id: &str, artifact_id: &str) -> Result<Option<Value>, String> {
111 Ok(self
112 .values
113 .lock()
114 .await
115 .get(artifact_id)
116 .filter(|artifact| artifact.execution_id == execution_id)
117 .map(|artifact| artifact.value.clone()))
118 }
119
120 async fn delete_execution(&self, execution_id: &str) -> Result<(), String> {
121 self.values
122 .lock()
123 .await
124 .retain(|_, artifact| artifact.execution_id != execution_id);
125 Ok(())
126 }
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
131#[serde(rename_all = "snake_case")]
132pub enum ExecutionStatus {
133 Running,
135 Paused,
137 Completed,
139 Error,
141 Rejected,
143 RolledBack,
145 Cancelled,
147}
148
149impl ExecutionStatus {
150 fn terminal(self) -> bool {
151 matches!(
152 self,
153 Self::Completed | Self::Error | Self::Rejected | Self::RolledBack | Self::Cancelled
154 )
155 }
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize)]
160#[serde(tag = "type", rename_all = "snake_case")]
161pub enum ExecutionEvent {
162 Status {
164 status: ExecutionStatus,
166 at: u64,
168 },
169 Chunk {
171 data: Value,
173 at: u64,
175 },
176 Log {
178 level: String,
180 message: String,
182 at: u64,
184 },
185 Progress {
187 message: String,
189 fraction: Option<f64>,
191 at: u64,
193 },
194}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
198#[serde(rename_all = "snake_case")]
199pub enum LogEntryState {
200 Pending,
202 Executing,
204 Applied,
206 Reverted,
208}
209
210fn one_attempt() -> u32 {
211 1
212}
213
214#[derive(Debug, Clone, Serialize, Deserialize)]
216pub struct LogEntry {
217 #[serde(default)]
219 pub attempts: u32,
220 #[serde(default = "one_attempt")]
222 pub attempt_limit: u32,
223 pub seq: u64,
225 pub connector: String,
227 pub method: String,
229 pub arguments: Value,
231 pub result: Option<Value>,
233 pub requires_approval: bool,
235 pub ephemeral: bool,
237 pub state: LogEntryState,
239}
240
241#[derive(Debug, Clone, Serialize, Deserialize)]
243pub struct ExecutionState {
244 #[serde(default, skip_serializing_if = "Option::is_none")]
246 pub trace: Option<crate::ExecutionTrace>,
247 pub id: String,
249 pub code: String,
251 pub status: ExecutionStatus,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub workflow_wait: Option<crate::WorkflowWait>,
256 #[serde(default, skip_serializing_if = "Vec::is_empty")]
258 pub workflow_children: Vec<crate::WorkflowChild>,
259 pub log: Vec<LogEntry>,
261 pub result: Option<Value>,
263 pub error: Option<String>,
265 pub logs: Vec<String>,
267 pub connectors: Vec<String>,
269 #[serde(default)]
271 pub capabilities: Option<CapabilitySnapshot>,
272 #[serde(default)]
274 pub events: Vec<ExecutionEvent>,
275 pub created_at: u64,
277 pub updated_at: u64,
279 #[serde(default, skip_serializing_if = "Option::is_none")]
281 pub retained_until: Option<u64>,
282}
283
284#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
286pub struct PendingAction {
287 pub execution_id: String,
289 pub seq: u64,
291 pub connector: String,
293 pub method: String,
295 pub arguments: Value,
297}
298
299#[derive(Debug, Clone, PartialEq)]
301pub enum ToolDecision {
302 Recover(u64),
304 Replay(Value),
306 Execute(u64),
308 Pause(u64),
310}
311
312#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
314pub struct Snippet {
315 pub name: String,
317 pub description: String,
319 pub code: String,
321 pub saved_at: u64,
323 pub input_schema: Option<Value>,
325 pub connectors: Vec<String>,
327}
328
329#[async_trait]
331#[allow(
332 clippy::double_must_use,
333 reason = "async_trait annotates generated futures"
334)]
335pub trait RuntimeStore: Send + Sync {
336 async fn workflow_identity(&self) -> Result<String, String> {
338 Err("WORKFLOW_UNSUPPORTED".into())
339 }
340 async fn get_workflows(&self) -> Result<Option<Value>, String> {
342 Err("WORKFLOW_UNSUPPORTED".into())
343 }
344 async fn put_workflows(&self, _catalog: &Value) -> Result<(), String> {
346 Err("WORKFLOW_UNSUPPORTED".into())
347 }
348 async fn get_checkpoint(&self, _id: &str) -> Result<Option<ExecutionCheckpoint>, String> {
350 Err("Runtime store does not support engine checkpoints".into())
351 }
352 async fn put_checkpoint(
354 &self,
355 _id: &str,
356 _checkpoint: &ExecutionCheckpoint,
357 ) -> Result<(), String> {
358 Err("Runtime store does not support engine checkpoints".into())
359 }
360 async fn get_execution(&self, id: &str) -> Result<Option<ExecutionState>, String>;
362 async fn put_execution(&self, execution: &ExecutionState) -> Result<(), String>;
364 async fn list_executions(&self) -> Result<Vec<ExecutionState>, String>;
366 async fn delete_execution(&self, id: &str) -> Result<(), String>;
368 async fn get_snippet(&self, name: &str) -> Result<Option<Snippet>, String>;
370 async fn put_snippet(&self, snippet: &Snippet) -> Result<(), String>;
372 async fn list_snippets(&self) -> Result<Vec<Snippet>, String>;
374 async fn delete_snippet(&self, name: &str) -> Result<bool, String>;
376}
377
378#[derive(Default)]
379struct MemoryState {
380 workflow_identity: Option<String>,
381 workflows: Option<Value>,
382 checkpoints: BTreeMap<String, ExecutionCheckpoint>,
383 executions: BTreeMap<String, ExecutionState>,
384 snippets: BTreeMap<String, Snippet>,
385}
386
387#[derive(Default)]
389pub struct MemoryStore {
390 state: Mutex<MemoryState>,
391}
392
393impl MemoryStore {
394 pub fn with_workflow_identity(identity: impl Into<String>) -> Self {
396 Self {
397 state: Mutex::new(MemoryState {
398 workflow_identity: Some(identity.into()),
399 ..Default::default()
400 }),
401 }
402 }
403}
404#[async_trait]
405impl RuntimeStore for MemoryStore {
406 async fn workflow_identity(&self) -> Result<String, String> {
407 #[allow(
408 unused_mut,
409 reason = "native store creates and persists an identity; wasm requires the host identity"
410 )]
411 let mut state = self.state.lock().await;
412 if let Some(id) = &state.workflow_identity {
413 return Ok(id.clone());
414 }
415 #[cfg(not(target_arch = "wasm32"))]
416 {
417 let mut bytes = [0u8; 24];
418 getrandom::fill(&mut bytes).map_err(|e| e.to_string())?;
419 let id = bytes.iter().map(|b| format!("{b:02x}")).collect::<String>();
420 state.workflow_identity = Some(id.clone());
421 Ok(id)
422 }
423 #[cfg(target_arch = "wasm32")]
424 {
425 Err(
426 "WORKFLOW_IDENTITY_REQUIRED: wasm host must supply a unique memory-store identity"
427 .into(),
428 )
429 }
430 }
431
432 async fn get_workflows(&self) -> Result<Option<Value>, String> {
433 Ok(self.state.lock().await.workflows.clone())
434 }
435 async fn put_workflows(&self, catalog: &Value) -> Result<(), String> {
436 self.state.lock().await.workflows = Some(catalog.clone());
437 Ok(())
438 }
439 async fn get_checkpoint(&self, id: &str) -> Result<Option<ExecutionCheckpoint>, String> {
440 Ok(self.state.lock().await.checkpoints.get(id).cloned())
441 }
442 async fn put_checkpoint(
443 &self,
444 id: &str,
445 checkpoint: &ExecutionCheckpoint,
446 ) -> Result<(), String> {
447 self.state
448 .lock()
449 .await
450 .checkpoints
451 .insert(id.into(), checkpoint.clone());
452 Ok(())
453 }
454 async fn get_execution(&self, id: &str) -> Result<Option<ExecutionState>, String> {
455 Ok(self.state.lock().await.executions.get(id).cloned())
456 }
457
458 async fn put_execution(&self, execution: &ExecutionState) -> Result<(), String> {
459 self.state
460 .lock()
461 .await
462 .executions
463 .insert(execution.id.clone(), execution.clone());
464 Ok(())
465 }
466
467 async fn list_executions(&self) -> Result<Vec<ExecutionState>, String> {
468 Ok(self
469 .state
470 .lock()
471 .await
472 .executions
473 .values()
474 .cloned()
475 .collect())
476 }
477
478 async fn delete_execution(&self, id: &str) -> Result<(), String> {
479 let mut state = self.state.lock().await;
480 state.executions.remove(id);
481 state.checkpoints.remove(id);
482 Ok(())
483 }
484
485 async fn get_snippet(&self, name: &str) -> Result<Option<Snippet>, String> {
486 Ok(self.state.lock().await.snippets.get(name).cloned())
487 }
488
489 async fn put_snippet(&self, snippet: &Snippet) -> Result<(), String> {
490 self.state
491 .lock()
492 .await
493 .snippets
494 .insert(snippet.name.clone(), snippet.clone());
495 Ok(())
496 }
497
498 async fn list_snippets(&self) -> Result<Vec<Snippet>, String> {
499 Ok(self.state.lock().await.snippets.values().cloned().collect())
500 }
501
502 async fn delete_snippet(&self, name: &str) -> Result<bool, String> {
503 Ok(self.state.lock().await.snippets.remove(name).is_some())
504 }
505}
506
507#[derive(Debug, Error)]
509pub enum RuntimeError {
510 #[error("Execution \"{0}\" not found")]
512 MissingExecution(String),
513 #[error("{0}")]
515 InvalidState(String),
516 #[error("{0}")]
518 DurableValue(String),
519 #[error("Runtime store failed: {0}")]
521 Store(String),
522}
523
524pub struct CodeModeRuntime {
526 pub(crate) store: Arc<dyn RuntimeStore>,
527 artifacts: Arc<dyn ArtifactStore>,
528 auto_prune_grace_ms: u64,
529 pub(crate) gate: Mutex<()>,
530 pub(crate) workflow_gate: Mutex<()>,
531 pub(crate) workflow_limits: crate::WorkflowLimits,
532}
533
534impl CodeModeRuntime {
535 pub async fn checkpoint(&self, id: &str) -> Result<Option<ExecutionCheckpoint>, RuntimeError> {
537 let state = self.require(id).await?;
538 let checkpoint = self
539 .store
540 .get_checkpoint(id)
541 .await
542 .map_err(RuntimeError::Store)?;
543 if checkpoint.is_none() && !state.log.is_empty() {
544 return Err(RuntimeError::Store(
545 "CHECKPOINT_MISSING: execution has journaled calls but no engine continuation"
546 .into(),
547 ));
548 }
549 Ok(checkpoint)
550 }
551
552 pub async fn save_checkpoint(
554 &self,
555 id: &str,
556 checkpoint: &ExecutionCheckpoint,
557 ) -> Result<(), RuntimeError> {
558 self.workflow_checkpoint_bytes(id, checkpoint)
559 .await
560 .map_err(RuntimeError::Store)?;
561 let _guard = self.gate.lock().await;
562 let state = self.require(id).await?;
563 if state.status != ExecutionStatus::Running {
564 return Err(RuntimeError::InvalidState(
565 "Only a running execution can save a checkpoint".into(),
566 ));
567 }
568 self.store
569 .put_checkpoint(id, checkpoint)
570 .await
571 .map_err(RuntimeError::Store)
572 }
573 pub fn new(store: Arc<dyn RuntimeStore>) -> Self {
575 Self::with_artifacts(store, Arc::new(MemoryArtifactStore::default()))
576 }
577
578 pub fn with_artifacts(store: Arc<dyn RuntimeStore>, artifacts: Arc<dyn ArtifactStore>) -> Self {
580 Self {
581 store,
582 artifacts,
583 auto_prune_grace_ms: DEFAULT_AUTO_PRUNE_GRACE_MS,
584 gate: Mutex::new(()),
585 workflow_gate: Mutex::new(()),
586 workflow_limits: crate::WorkflowLimits::default(),
587 }
588 }
589
590 pub fn with_auto_prune_grace_ms(mut self, grace_ms: u64) -> Self {
597 self.auto_prune_grace_ms = grace_ms;
598 self
599 }
600
601 pub async fn begin(
603 &self,
604 code: impl Into<String>,
605 connectors: Vec<String>,
606 now: u64,
607 ) -> Result<String, RuntimeError> {
608 self.begin_inner(code.into(), connectors, None, now, None, None)
609 .await
610 }
611
612 pub async fn begin_with_capabilities(
614 &self,
615 code: &str,
616 capabilities: CapabilitySnapshot,
617 now: u64,
618 ) -> Result<String, RuntimeError> {
619 self.begin_retained(code, capabilities, now, None, None)
620 .await
621 }
622
623 pub async fn begin_retained(
625 &self,
626 code: &str,
627 capabilities: CapabilitySnapshot,
628 now: u64,
629 retained_until: Option<u64>,
630 execution_id: Option<String>,
631 ) -> Result<String, RuntimeError> {
632 let connectors = capabilities
633 .connectors
634 .iter()
635 .map(|connector| connector.name.clone())
636 .collect();
637 self.begin_inner(
638 code.to_string(),
639 connectors,
640 Some(capabilities),
641 now,
642 retained_until,
643 execution_id,
644 )
645 .await
646 }
647
648 async fn begin_inner(
649 &self,
650 code: String,
651 connectors: Vec<String>,
652 capabilities: Option<CapabilitySnapshot>,
653 now: u64,
654 retained_until: Option<u64>,
655 execution_id: Option<String>,
656 ) -> Result<String, RuntimeError> {
657 let _guard = self.gate.lock().await;
658 ensure_size("The execution code", &Value::String(code.clone()))?;
659 let sequence = EXECUTION_SEQUENCE.fetch_add(1, Ordering::Relaxed);
660 let id = execution_id.unwrap_or_else(|| format!("exec_{now:016}_{sequence:016x}"));
661 if self
662 .store
663 .get_execution(&id)
664 .await
665 .map_err(RuntimeError::Store)?
666 .is_some()
667 {
668 return Err(RuntimeError::InvalidState(
669 "Execution ID already exists".into(),
670 ));
671 }
672 self.store
673 .put_execution(&ExecutionState {
674 trace: None,
675 id: id.clone(),
676 code,
677 status: ExecutionStatus::Running,
678 workflow_wait: None,
679 workflow_children: Vec::new(),
680 log: Vec::new(),
681 result: None,
682 error: None,
683 logs: Vec::new(),
684 connectors,
685 capabilities,
686 events: vec![ExecutionEvent::Status {
687 status: ExecutionStatus::Running,
688 at: now,
689 }],
690 created_at: now,
691 updated_at: now,
692 retained_until,
693 })
694 .await
695 .map_err(RuntimeError::Store)?;
696 self.prune_locked(
697 DEFAULT_MAX_EXECUTIONS,
698 Some(&id),
699 Some(now),
700 self.auto_prune_grace_ms,
701 )
702 .await?;
703 Ok(id)
704 }
705
706 pub(crate) async fn record_trace(
708 &self,
709 id: &str,
710 trace: crate::ExecutionTrace,
711 ) -> Result<(), RuntimeError> {
712 let _guard = self.gate.lock().await;
713 let mut execution = self.require(id).await?;
714 if execution.status == ExecutionStatus::Running {
715 execution.trace = Some(trace);
716 self.save(&execution).await?;
717 }
718 Ok(())
719 }
720
721 pub async fn resume(&self, id: &str, now: u64) -> Result<ExecutionState, RuntimeError> {
723 let _guard = self.gate.lock().await;
724 let mut execution = self.require(id).await?;
725 if execution.status != ExecutionStatus::Paused {
726 return Err(RuntimeError::InvalidState(format!(
727 "Execution \"{id}\" is {:?}, not paused",
728 execution.status
729 )));
730 }
731 if execution
732 .log
733 .iter()
734 .any(|entry| entry.state == LogEntryState::Pending)
735 {
736 return Err(RuntimeError::InvalidState(format!(
737 "Execution \"{id}\" is awaiting approval; use approve or reject"
738 )));
739 }
740 if execution.workflow_wait.is_some() {
741 return Err(RuntimeError::InvalidState(
742 "Workflow child waits recover through the tree scheduler".into(),
743 ));
744 }
745 execution.status = ExecutionStatus::Running;
746 execution.error = None;
747 push_event(
748 &mut execution,
749 ExecutionEvent::Status {
750 status: ExecutionStatus::Running,
751 at: now,
752 },
753 );
754 execution.updated_at = now;
755 self.save(&execution).await?;
756 Ok(execution)
757 }
758
759 pub async fn cancel(&self, id: &str, now: u64) -> Result<bool, RuntimeError> {
761 let _guard = self.gate.lock().await;
762 let mut execution = self.require(id).await?;
763 if execution.status.terminal() {
764 return Ok(false);
765 }
766 execution.status = ExecutionStatus::Cancelled;
767 execution.error = Some("Execution cancelled".to_string());
768 execution.updated_at = now;
769 push_event(
770 &mut execution,
771 ExecutionEvent::Status {
772 status: ExecutionStatus::Cancelled,
773 at: now,
774 },
775 );
776 self.save(&execution).await?;
777 Ok(true)
778 }
779
780 pub async fn event(&self, id: &str, event: ExecutionEvent) -> Result<(), RuntimeError> {
782 let _guard = self.gate.lock().await;
783 let mut execution = self.require(id).await?;
784 push_event(&mut execution, event);
785 self.save(&execution).await
786 }
787
788 pub async fn artifact(
790 &self,
791 execution_id: &str,
792 artifact_id: &str,
793 ) -> Result<Option<Value>, RuntimeError> {
794 self.artifacts
795 .get(execution_id, artifact_id)
796 .await
797 .map_err(RuntimeError::Store)
798 }
799
800 async fn spill(&self, execution_id: &str, value: Value) -> Result<Value, RuntimeError> {
801 if serialized_size(&value) <= MAX_DURABLE_VALUE_BYTES {
802 return Ok(value);
803 }
804 let artifact = self
805 .artifacts
806 .put(execution_id, &value)
807 .await
808 .map_err(RuntimeError::Store)?;
809 Ok(serde_json::json!({ "$artifact": artifact }))
810 }
811
812 async fn rehydrate(&self, execution_id: &str, value: Value) -> Result<Value, RuntimeError> {
813 let Some(artifact) = artifact_ref(&value)? else {
814 return Ok(value);
815 };
816 self.artifacts
817 .get(execution_id, &artifact.id)
818 .await
819 .map_err(RuntimeError::Store)?
820 .ok_or_else(|| {
821 RuntimeError::Store(format!("Artifact \"{}\" is unavailable", artifact.id))
822 })
823 }
824
825 async fn rehydrate_execution(
826 &self,
827 mut execution: ExecutionState,
828 ) -> Result<ExecutionState, RuntimeError> {
829 for entry in &mut execution.log {
830 entry.arguments = self
831 .rehydrate(&execution.id, entry.arguments.clone())
832 .await?;
833 if let Some(result) = entry.result.take() {
834 entry.result = Some(self.rehydrate(&execution.id, result).await?);
835 }
836 }
837 if let Some(result) = execution.result.take() {
838 execution.result = Some(self.rehydrate(&execution.id, result).await?);
839 }
840 Ok(execution)
841 }
842
843 async fn rehydrate_entry(
844 &self,
845 execution_id: &str,
846 mut entry: LogEntry,
847 ) -> Result<LogEntry, RuntimeError> {
848 entry.arguments = self.rehydrate(execution_id, entry.arguments).await?;
849 if let Some(result) = entry.result.take() {
850 entry.result = Some(self.rehydrate(execution_id, result).await?);
851 }
852 Ok(entry)
853 }
854
855 async fn rehydrate_pending(
856 &self,
857 execution_id: &str,
858 mut action: PendingAction,
859 ) -> Result<PendingAction, RuntimeError> {
860 action.arguments = self.rehydrate(execution_id, action.arguments).await?;
861 Ok(action)
862 }
863
864 #[allow(clippy::too_many_arguments)]
866 pub async fn decide(
867 &self,
868 id: &str,
869 seq: u64,
870 connector: &str,
871 method: &str,
872 arguments: Value,
873 requires_approval: bool,
874 ephemeral: bool,
875 now: u64,
876 ) -> Result<ToolDecision, RuntimeError> {
877 let _guard = self.gate.lock().await;
878 let mut execution = self.require(id).await?;
879 if execution.status != ExecutionStatus::Running {
880 return Ok(ToolDecision::Pause(seq));
881 }
882 if requires_approval && ephemeral {
883 return Err(RuntimeError::InvalidState(format!(
884 "{connector}.{method} cannot require approval and re-execute on replay"
885 )));
886 }
887 let arguments = self.spill(id, arguments).await?;
888 if let Some(entry) = execution.log.iter_mut().find(|entry| entry.seq == seq) {
889 if entry.connector != connector
890 || entry.method != method
891 || stable_json(&entry.arguments) != stable_json(&arguments)
892 {
893 execution.status = ExecutionStatus::Error;
894 execution.error = Some(format!(
895 "Replay diverged at step {seq}: expected {}.{}, got {connector}.{method}. \
896 Code must be deterministic up to tool calls and steps.",
897 entry.connector, entry.method
898 ));
899 execution.updated_at = now;
900 self.save(&execution).await?;
901 return Ok(ToolDecision::Pause(seq));
902 }
903 return match entry.state {
904 LogEntryState::Applied if !entry.ephemeral => Ok(ToolDecision::Replay(
905 self.rehydrate(id, entry.result.clone().unwrap_or(Value::Null))
906 .await?,
907 )),
908 LogEntryState::Executing if connector != "codemode" => {
909 entry.attempts = entry.attempts.max(1);
911 execution.updated_at = now;
912 self.save(&execution).await?;
913 Ok(ToolDecision::Recover(seq))
914 }
915 LogEntryState::Pending | LogEntryState::Executing | LogEntryState::Applied => {
916 if entry.state == LogEntryState::Applied {
917 entry.attempts = 0;
918 entry.attempt_limit = 0;
919 }
920 entry.state = LogEntryState::Executing;
921 execution.updated_at = now;
922 self.save(&execution).await?;
923 Ok(ToolDecision::Execute(seq))
924 }
925 LogEntryState::Reverted => {
926 entry.state = if requires_approval {
927 LogEntryState::Pending
928 } else {
929 LogEntryState::Executing
930 };
931 entry.arguments = arguments;
932 entry.result = None;
933 entry.attempts = 0;
934 entry.attempt_limit = 0;
935 entry.requires_approval = requires_approval;
936 entry.ephemeral = ephemeral;
937 if requires_approval {
938 execution.status = ExecutionStatus::Paused;
939 push_event(
940 &mut execution,
941 ExecutionEvent::Status {
942 status: ExecutionStatus::Paused,
943 at: now,
944 },
945 );
946 }
947 execution.updated_at = now;
948 self.save(&execution).await?;
949 Ok(if requires_approval {
950 ToolDecision::Pause(seq)
951 } else {
952 ToolDecision::Execute(seq)
953 })
954 }
955 };
956 }
957 execution.log.push(LogEntry {
958 attempts: 0,
959 attempt_limit: 0,
960 seq,
961 connector: connector.to_string(),
962 method: method.to_string(),
963 arguments,
964 result: None,
965 requires_approval,
966 ephemeral,
967 state: if requires_approval {
968 LogEntryState::Pending
969 } else {
970 LogEntryState::Executing
971 },
972 });
973 if requires_approval {
974 execution.status = ExecutionStatus::Paused;
975 push_event(
976 &mut execution,
977 ExecutionEvent::Status {
978 status: ExecutionStatus::Paused,
979 at: now,
980 },
981 );
982 }
983 execution.updated_at = now;
984 self.save(&execution).await?;
985 Ok(if requires_approval {
986 ToolDecision::Pause(seq)
987 } else {
988 ToolDecision::Execute(seq)
989 })
990 }
991
992 pub(crate) async fn charge_attempt(
994 &self,
995 id: &str,
996 seq: u64,
997 configured_limit: u32,
998 now: u64,
999 ) -> Result<u32, RuntimeError> {
1000 let _guard = self.gate.lock().await;
1001 let mut execution = self.require(id).await?;
1002 if execution.status != ExecutionStatus::Running {
1003 return Err(RuntimeError::InvalidState(
1004 "Execution is not running".into(),
1005 ));
1006 }
1007 let entry = execution
1008 .log
1009 .iter_mut()
1010 .find(|entry| entry.seq == seq)
1011 .ok_or_else(|| RuntimeError::InvalidState(format!("No log entry at step {seq}")))?;
1012 if entry.state != LogEntryState::Executing {
1013 return Err(RuntimeError::InvalidState("Call is not executing".into()));
1014 }
1015 let configured = configured_limit.clamp(1, crate::MAX_CALL_ATTEMPTS);
1016 if entry.attempt_limit == 0 {
1017 entry.attempt_limit = configured;
1018 }
1019 if entry.attempts >= entry.attempt_limit.min(configured) {
1020 return Err(RuntimeError::InvalidState(serde_json::json!({
1021 "code": "CALL_ATTEMPTS_EXHAUSTED", "retryable": false,
1022 "message": "Connector call exhausted its durable attempt budget", "sequence": seq,
1023 }).to_string()));
1024 }
1025 entry.attempts += 1;
1026 let attempt = entry.attempts;
1027 execution.updated_at = now;
1028 self.save(&execution).await?;
1029 Ok(attempt)
1030 }
1031
1032 pub(crate) async fn suspend_call(
1034 &self,
1035 id: &str,
1036 reason: String,
1037 now: u64,
1038 ) -> Result<(), RuntimeError> {
1039 let _guard = self.gate.lock().await;
1040 let mut execution = self.require(id).await?;
1041 if execution.status != ExecutionStatus::Running {
1042 return Err(RuntimeError::InvalidState(
1043 "Execution is not running".into(),
1044 ));
1045 }
1046 execution.status = ExecutionStatus::Paused;
1047 execution.error = Some(reason);
1048 execution.updated_at = now;
1049 push_event(
1050 &mut execution,
1051 ExecutionEvent::Status {
1052 status: ExecutionStatus::Paused,
1053 at: now,
1054 },
1055 );
1056 self.save(&execution).await
1057 }
1058
1059 pub(crate) async fn defer_call(
1061 &self,
1062 id: &str,
1063 seq: u64,
1064 reason: String,
1065 now: u64,
1066 ) -> Result<(), RuntimeError> {
1067 let _guard = self.gate.lock().await;
1068 let mut execution = self.require(id).await?;
1069 if execution.status != ExecutionStatus::Running {
1070 return Err(RuntimeError::InvalidState(
1071 "Execution is not running".into(),
1072 ));
1073 }
1074 let entry = execution
1075 .log
1076 .iter_mut()
1077 .find(|entry| entry.seq == seq)
1078 .ok_or_else(|| RuntimeError::InvalidState(format!("No log entry at step {seq}")))?;
1079 if entry.state != LogEntryState::Executing {
1080 return Err(RuntimeError::InvalidState("Call is not executing".into()));
1081 }
1082 entry.state = LogEntryState::Reverted;
1083 entry.result = None;
1084 execution.status = ExecutionStatus::Paused;
1085 execution.error = Some(reason);
1086 execution.updated_at = now;
1087 push_event(
1088 &mut execution,
1089 ExecutionEvent::Status {
1090 status: ExecutionStatus::Paused,
1091 at: now,
1092 },
1093 );
1094 self.save(&execution).await
1095 }
1096
1097 pub async fn record_result(
1099 &self,
1100 id: &str,
1101 seq: u64,
1102 result: Value,
1103 now: u64,
1104 ) -> Result<(), RuntimeError> {
1105 let _guard = self.gate.lock().await;
1106 let mut execution = self.require(id).await?;
1107 if execution.status != ExecutionStatus::Running {
1108 return Err(RuntimeError::InvalidState(format!(
1109 "Execution \"{id}\" is {:?}, not running",
1110 execution.status
1111 )));
1112 }
1113 let result = self.spill(id, result).await?;
1114 if execution.status != ExecutionStatus::Running {
1115 return Err(RuntimeError::InvalidState(format!(
1116 "Execution \"{id}\" is {:?}, not running",
1117 execution.status
1118 )));
1119 }
1120 let Some(entry) = execution.log.iter_mut().find(|entry| entry.seq == seq) else {
1121 return Err(RuntimeError::InvalidState(format!(
1122 "No log entry at step {seq}"
1123 )));
1124 };
1125 if entry.state != LogEntryState::Executing {
1126 return Err(RuntimeError::InvalidState(format!(
1127 "Log entry at step {seq} is {:?}, not executing",
1128 entry.state
1129 )));
1130 }
1131 entry.result = Some(result);
1132 entry.state = LogEntryState::Applied;
1133 execution.updated_at = now;
1134 self.save(&execution).await
1135 }
1136
1137 pub async fn complete(
1139 &self,
1140 id: &str,
1141 result: Value,
1142 logs: Vec<String>,
1143 now: u64,
1144 ) -> Result<(), RuntimeError> {
1145 let _guard = self.gate.lock().await;
1146 let mut execution = self.require(id).await?;
1147 if execution.status != ExecutionStatus::Running {
1148 return Err(RuntimeError::InvalidState(format!(
1149 "Execution \"{id}\" is {:?}, not running",
1150 execution.status
1151 )));
1152 }
1153 let result = self.spill(id, result).await?;
1154 execution.status = ExecutionStatus::Completed;
1155 push_event(
1156 &mut execution,
1157 ExecutionEvent::Status {
1158 status: ExecutionStatus::Completed,
1159 at: now,
1160 },
1161 );
1162 execution.result = Some(result);
1163 execution.logs = bounded_logs(logs);
1164 execution.updated_at = now;
1165 self.save(&execution).await
1166 }
1167
1168 pub async fn fail(
1170 &self,
1171 id: &str,
1172 error: impl Into<String>,
1173 logs: Vec<String>,
1174 now: u64,
1175 ) -> Result<(), RuntimeError> {
1176 let _guard = self.gate.lock().await;
1177 let mut execution = self.require(id).await?;
1178 if execution.status != ExecutionStatus::Running {
1179 return Err(RuntimeError::InvalidState(format!(
1180 "Execution \"{id}\" is {:?}, not running",
1181 execution.status
1182 )));
1183 }
1184 execution.status = ExecutionStatus::Error;
1185 push_event(
1186 &mut execution,
1187 ExecutionEvent::Status {
1188 status: ExecutionStatus::Error,
1189 at: now,
1190 },
1191 );
1192 execution.error = Some(truncate_bytes(error.into(), MAX_DURABLE_VALUE_BYTES));
1193 execution.logs = bounded_logs(logs);
1194 execution.updated_at = now;
1195 self.save(&execution).await
1196 }
1197
1198 pub(crate) async fn fail_tree(
1199 &self,
1200 id: &str,
1201 error: String,
1202 now: u64,
1203 ) -> Result<(), RuntimeError> {
1204 let _guard = self.gate.lock().await;
1205 let mut state = self.require(id).await?;
1206 if matches!(
1207 state.status,
1208 ExecutionStatus::Running | ExecutionStatus::Paused
1209 ) {
1210 state.status = ExecutionStatus::Error;
1211 state.workflow_wait = None;
1212 state.error = Some(error);
1213 state.updated_at = now;
1214 push_event(
1215 &mut state,
1216 ExecutionEvent::Status {
1217 status: ExecutionStatus::Error,
1218 at: now,
1219 },
1220 );
1221 self.save(&state).await?;
1222 }
1223 Ok(())
1224 }
1225 pub async fn approve(&self, id: &str, seq: u64, now: u64) -> Result<bool, RuntimeError> {
1227 let _guard = self.gate.lock().await;
1228 let mut execution = self.require(id).await?;
1229 if execution.status != ExecutionStatus::Paused {
1230 return Ok(false);
1231 }
1232 let Some(entry) = execution
1233 .log
1234 .iter()
1235 .find(|entry| entry.seq == seq && entry.state == LogEntryState::Pending)
1236 else {
1237 return Ok(false);
1238 };
1239 let _ = entry;
1240 execution.status = ExecutionStatus::Running;
1241 execution.updated_at = now;
1242 self.save(&execution).await?;
1243 Ok(true)
1244 }
1245
1246 pub async fn reject(&self, id: &str, seq: u64, now: u64) -> Result<bool, RuntimeError> {
1248 let _guard = self.gate.lock().await;
1249 let mut execution = self.require(id).await?;
1250 if execution.status != ExecutionStatus::Paused {
1251 return Err(RuntimeError::InvalidState(format!(
1252 "Execution \"{id}\" is {:?}, not paused",
1253 execution.status
1254 )));
1255 }
1256 let Some(entry) = execution
1257 .log
1258 .iter_mut()
1259 .find(|entry| entry.seq == seq && entry.state == LogEntryState::Pending)
1260 else {
1261 return Ok(false);
1262 };
1263 entry.state = LogEntryState::Reverted;
1264 let error = format!(
1265 "Action {}.{} rejected by user",
1266 entry.connector, entry.method
1267 );
1268 execution.status = ExecutionStatus::Rejected;
1269 push_event(
1270 &mut execution,
1271 ExecutionEvent::Status {
1272 status: ExecutionStatus::Rejected,
1273 at: now,
1274 },
1275 );
1276 execution.error = Some(error);
1277 execution.updated_at = now;
1278 self.save(&execution).await?;
1279 Ok(true)
1280 }
1281
1282 pub async fn pending(&self, id: Option<&str>) -> Result<Vec<PendingAction>, RuntimeError> {
1284 let executions = if let Some(id) = id {
1285 let mut states = vec![self.require(id).await?];
1286 for child in self
1287 .workflow_children(id)
1288 .await
1289 .map_err(RuntimeError::Store)?
1290 {
1291 states.push(self.require(&child.id).await?);
1292 }
1293 states
1294 } else {
1295 self.store
1296 .list_executions()
1297 .await
1298 .map_err(RuntimeError::Store)?
1299 };
1300 let mut result = Vec::new();
1301 for execution in executions
1302 .into_iter()
1303 .filter(|execution| execution.status == ExecutionStatus::Paused)
1304 {
1305 for entry in execution
1306 .log
1307 .into_iter()
1308 .filter(|entry| entry.state == LogEntryState::Pending)
1309 {
1310 let action = PendingAction {
1311 execution_id: execution.id.clone(),
1312 seq: entry.seq,
1313 connector: entry.connector,
1314 method: entry.method,
1315 arguments: entry.arguments,
1316 };
1317 result.push(self.rehydrate_pending(&execution.id, action).await?);
1318 }
1319 }
1320 result.sort_by(|left, right| {
1321 right
1322 .execution_id
1323 .cmp(&left.execution_id)
1324 .then_with(|| left.seq.cmp(&right.seq))
1325 });
1326 Ok(result)
1327 }
1328
1329 pub async fn actions_to_revert(&self, id: &str) -> Result<Vec<LogEntry>, RuntimeError> {
1331 let execution = self.require(id).await?;
1332 validate_rollback_state(&execution)?;
1333 let mut actions = Vec::new();
1334 for entry in execution.log.into_iter().filter(|entry| {
1335 entry.state == LogEntryState::Applied && !entry.ephemeral && entry.connector != "__step"
1336 }) {
1337 actions.push(self.rehydrate_entry(&execution.id, entry).await?);
1338 }
1339 actions.sort_by_key(|entry| std::cmp::Reverse(entry.seq));
1340 Ok(actions)
1341 }
1342
1343 pub async fn mark_reverted(&self, id: &str, seq: u64, now: u64) -> Result<(), RuntimeError> {
1345 let _guard = self.gate.lock().await;
1346 let mut execution = self.require(id).await?;
1347 if let Some(entry) = execution.log.iter_mut().find(|entry| entry.seq == seq) {
1348 entry.state = LogEntryState::Reverted;
1349 execution.updated_at = now;
1350 self.save(&execution).await?;
1351 }
1352 Ok(())
1353 }
1354
1355 pub async fn finish_rollback(&self, id: &str, now: u64) -> Result<(), RuntimeError> {
1357 let _guard = self.gate.lock().await;
1358 let mut execution = self.require(id).await?;
1359 validate_rollback_state(&execution)?;
1360 execution.status = ExecutionStatus::RolledBack;
1361 push_event(
1362 &mut execution,
1363 ExecutionEvent::Status {
1364 status: ExecutionStatus::RolledBack,
1365 at: now,
1366 },
1367 );
1368 execution.updated_at = now;
1369 self.save(&execution).await
1370 }
1371
1372 pub async fn expire(&self, now: u64, max_age_ms: u64) -> Result<Vec<String>, RuntimeError> {
1374 let _guard = self.gate.lock().await;
1375 let mut expired = Vec::new();
1376 for mut execution in self
1377 .store
1378 .list_executions()
1379 .await
1380 .map_err(RuntimeError::Store)?
1381 {
1382 if !matches!(
1383 execution.status,
1384 ExecutionStatus::Paused | ExecutionStatus::Running
1385 ) || now.saturating_sub(execution.updated_at) <= max_age_ms
1386 {
1387 continue;
1388 }
1389 execution.status = if execution.status == ExecutionStatus::Paused {
1390 ExecutionStatus::Rejected
1391 } else {
1392 ExecutionStatus::Error
1393 };
1394 execution.error = Some(if execution.status == ExecutionStatus::Rejected {
1395 "Expired awaiting approval".to_string()
1396 } else {
1397 "Expired while running - the host never completed the pass".to_string()
1398 });
1399 for entry in &mut execution.log {
1400 if entry.state == LogEntryState::Pending {
1401 entry.state = LogEntryState::Reverted;
1402 }
1403 }
1404 execution.updated_at = now;
1405 self.save(&execution).await?;
1406 expired.push(execution.id);
1407 }
1408 Ok(expired)
1409 }
1410
1411 pub async fn execution(&self, id: &str) -> Result<Option<ExecutionState>, RuntimeError> {
1413 let Some(execution) = self
1414 .store
1415 .get_execution(id)
1416 .await
1417 .map_err(RuntimeError::Store)?
1418 else {
1419 return Ok(None);
1420 };
1421 self.rehydrate_execution(execution).await.map(Some)
1422 }
1423
1424 pub async fn execution_snapshot(
1426 &self,
1427 id: &str,
1428 ) -> Result<Option<ExecutionState>, RuntimeError> {
1429 let mut state = self
1430 .store
1431 .get_execution(id)
1432 .await
1433 .map_err(RuntimeError::Store)?;
1434 if let Some(state) = &mut state {
1435 state.workflow_children = self
1436 .workflow_children(id)
1437 .await
1438 .map_err(RuntimeError::Store)?;
1439 }
1440 Ok(state)
1441 }
1442
1443 pub async fn executions(&self) -> Result<Vec<ExecutionState>, RuntimeError> {
1445 let mut executions = self
1446 .store
1447 .list_executions()
1448 .await
1449 .map_err(RuntimeError::Store)?;
1450 executions.sort_by_key(|execution| {
1451 (
1452 std::cmp::Reverse(execution.created_at),
1453 std::cmp::Reverse(execution.id.clone()),
1454 )
1455 });
1456 Ok(executions)
1457 }
1458
1459 pub async fn prune(&self, keep: usize) -> Result<usize, RuntimeError> {
1461 let _guard = self.gate.lock().await;
1462 self.prune_locked(keep, None, None, 0).await
1463 }
1464
1465 pub async fn prune_at(&self, keep: usize, now: u64) -> Result<usize, RuntimeError> {
1467 let _guard = self.gate.lock().await;
1468 self.prune_locked(keep, None, Some(now), 0).await
1469 }
1470
1471 pub async fn save_snippet(
1473 &self,
1474 name: impl Into<String>,
1475 description: impl Into<String>,
1476 execution_id: &str,
1477 input_schema: Option<Value>,
1478 now: u64,
1479 ) -> Result<Snippet, RuntimeError> {
1480 let execution = self.require(execution_id).await?;
1481 if execution.status != ExecutionStatus::Completed {
1482 return Err(RuntimeError::InvalidState(
1483 "Only completed executions can be saved as snippets".to_string(),
1484 ));
1485 }
1486 let snippet = Snippet {
1487 name: name.into(),
1488 description: description.into(),
1489 code: execution.code,
1490 saved_at: now,
1491 input_schema,
1492 connectors: execution.connectors,
1493 };
1494 if !self
1495 .workflow_publish_snippet(&snippet)
1496 .await
1497 .map_err(RuntimeError::Store)?
1498 {
1499 self.store
1500 .put_snippet(&snippet)
1501 .await
1502 .map_err(RuntimeError::Store)?;
1503 }
1504 Ok(snippet)
1505 }
1506
1507 pub async fn publish_snippet(&self, snippet: Snippet) -> Result<Snippet, RuntimeError> {
1509 if !self
1510 .workflow_publish_snippet(&snippet)
1511 .await
1512 .map_err(RuntimeError::Store)?
1513 {
1514 self.store
1515 .put_snippet(&snippet)
1516 .await
1517 .map_err(RuntimeError::Store)?;
1518 }
1519 Ok(snippet)
1520 }
1521
1522 pub async fn snippets(&self) -> Result<Vec<Snippet>, RuntimeError> {
1524 let mut snippets = self
1525 .store
1526 .list_snippets()
1527 .await
1528 .map_err(RuntimeError::Store)?;
1529 let published = self
1530 .workflow_snippets()
1531 .await
1532 .map_err(RuntimeError::Store)?;
1533 if self.store.get_workflows().await.is_ok() {
1534 snippets = published;
1535 } else {
1536 snippets.extend(published);
1537 }
1538 snippets.sort_by(|left, right| left.name.cmp(&right.name));
1539 Ok(snippets)
1540 }
1541
1542 pub async fn delete_snippet(&self, name: &str) -> Result<bool, RuntimeError> {
1544 let published = self
1545 .workflow_delete_snippet(name)
1546 .await
1547 .map_err(RuntimeError::Store)?;
1548 let legacy = self
1549 .store
1550 .delete_snippet(name)
1551 .await
1552 .map_err(RuntimeError::Store)?;
1553 Ok(published || legacy)
1554 }
1555
1556 async fn require(&self, id: &str) -> Result<ExecutionState, RuntimeError> {
1557 self.store
1558 .get_execution(id)
1559 .await
1560 .map_err(RuntimeError::Store)?
1561 .ok_or_else(|| RuntimeError::MissingExecution(id.to_string()))
1562 }
1563
1564 async fn save(&self, execution: &ExecutionState) -> Result<(), RuntimeError> {
1565 self.store
1566 .put_execution(execution)
1567 .await
1568 .map_err(RuntimeError::Store)
1569 }
1570
1571 async fn prune_locked(
1572 &self,
1573 keep: usize,
1574 excluding: Option<&str>,
1575 now: Option<u64>,
1576 minimum_age_ms: u64,
1577 ) -> Result<usize, RuntimeError> {
1578 let mut terminal = self
1579 .store
1580 .list_executions()
1581 .await
1582 .map_err(RuntimeError::Store)?
1583 .into_iter()
1584 .filter(|execution| {
1585 execution.status.terminal()
1586 && now.is_none_or(|now| {
1587 now.saturating_sub(execution.updated_at) >= minimum_age_ms
1588 })
1589 && execution
1590 .retained_until
1591 .is_none_or(|until| now.is_some_and(|now| now >= until))
1592 && excluding.is_none_or(|id| execution.id.as_str() != id)
1593 })
1594 .collect::<Vec<_>>();
1595 terminal.sort_by_key(|execution| std::cmp::Reverse(execution.created_at));
1596 let remove = terminal.len().saturating_sub(keep);
1597 for execution in terminal.into_iter().rev().take(remove) {
1598 self.store
1599 .delete_execution(&execution.id)
1600 .await
1601 .map_err(RuntimeError::Store)?;
1602 self.artifacts
1603 .delete_execution(&execution.id)
1604 .await
1605 .map_err(RuntimeError::Store)?;
1606 }
1607 Ok(remove)
1608 }
1609}
1610
1611fn ensure_size(what: &str, value: &Value) -> Result<(), RuntimeError> {
1612 let size = serialized_size(value);
1613 if size > MAX_DURABLE_VALUE_BYTES {
1614 Err(RuntimeError::DurableValue(format!(
1615 "{what} is too large to record durably ({size} bytes > \
1616 {MAX_DURABLE_VALUE_BYTES} byte limit). Write large data to a file or workspace \
1617 instead and pass or return a small reference."
1618 )))
1619 } else {
1620 Ok(())
1621 }
1622}
1623
1624fn serialized_size(value: &Value) -> usize {
1625 serde_json::to_vec(value).map_or(usize::MAX, |value| value.len())
1626}
1627
1628fn stable_json(value: &Value) -> String {
1629 match value {
1630 Value::Object(values) => {
1631 let mut values = values.iter().collect::<Vec<_>>();
1632 values.sort_by_key(|(key, _)| *key);
1633 format!(
1634 "{{{}}}",
1635 values
1636 .into_iter()
1637 .map(|(key, value)| format!(
1638 "{}:{}",
1639 serde_json::to_string(key).unwrap(),
1640 stable_json(value)
1641 ))
1642 .collect::<Vec<_>>()
1643 .join(",")
1644 )
1645 }
1646 Value::Array(values) => format!(
1647 "[{}]",
1648 values.iter().map(stable_json).collect::<Vec<_>>().join(",")
1649 ),
1650 value => serde_json::to_string(value).unwrap_or_default(),
1651 }
1652}
1653
1654fn bounded_logs(logs: Vec<String>) -> Vec<String> {
1655 let mut size = 2;
1656 logs.into_iter()
1657 .take_while(|log| {
1658 size += log.len() + 3;
1659 size <= MAX_DURABLE_VALUE_BYTES
1660 })
1661 .collect()
1662}
1663
1664fn push_event(execution: &mut ExecutionState, event: ExecutionEvent) {
1665 execution.events.push(event);
1666 if execution.events.len() > DEFAULT_MAX_EVENTS {
1667 execution
1668 .events
1669 .drain(..execution.events.len() - DEFAULT_MAX_EVENTS);
1670 }
1671}
1672
1673fn artifact_ref(value: &Value) -> Result<Option<ArtifactRef>, RuntimeError> {
1674 let Value::Object(values) = value else {
1675 return Ok(None);
1676 };
1677 if values.len() != 1 {
1678 return Ok(None);
1679 }
1680 let Some(artifact) = values.get("$artifact") else {
1681 return Ok(None);
1682 };
1683 serde_json::from_value::<ArtifactRef>(artifact.clone())
1684 .map(Some)
1685 .map_err(|error| RuntimeError::Store(error.to_string()))
1686}
1687
1688fn truncate_bytes(mut value: String, limit: usize) -> String {
1689 if value.len() <= limit {
1690 return value;
1691 }
1692 let mut end = limit;
1693 while !value.is_char_boundary(end) {
1694 end -= 1;
1695 }
1696 value.truncate(end);
1697 value
1698}
1699
1700fn validate_rollback_state(execution: &ExecutionState) -> Result<(), RuntimeError> {
1701 if !execution.status.terminal() || execution.status == ExecutionStatus::RolledBack {
1702 return Err(RuntimeError::InvalidState(format!(
1703 "Execution \"{}\" is {:?}, not rollback eligible",
1704 execution.id, execution.status
1705 )));
1706 }
1707 if execution.log.iter().any(|entry| {
1708 matches!(
1709 entry.state,
1710 LogEntryState::Pending | LogEntryState::Executing
1711 )
1712 }) {
1713 return Err(RuntimeError::InvalidState(format!(
1714 "Execution \"{}\" has an unfinished action",
1715 execution.id
1716 )));
1717 }
1718 Ok(())
1719}
1720
1721#[cfg(test)]
1722mod history_retention_tests {
1723 use super::*;
1724 use serde_json::json;
1725
1726 #[tokio::test]
1727 async fn automatic_pruning_preserves_a_burst_until_after_completion_grace() {
1728 let runtime = CodeModeRuntime::new(Arc::new(MemoryStore::default()));
1729 let mut ids = Vec::new();
1730 for caller in 0..100 {
1731 let id = runtime.begin("return input", vec![], 1).await.unwrap();
1732 runtime
1733 .complete(&id, json!(caller), vec![], 1_000_000)
1734 .await
1735 .unwrap();
1736 ids.push(id);
1737 }
1738 runtime.begin("return 0", vec![], 1_059_999).await.unwrap();
1740 for (caller, id) in ids.iter().enumerate() {
1741 let state = runtime
1742 .execution(id)
1743 .await
1744 .unwrap()
1745 .expect("recent result was pruned before its caller could fetch it");
1746 assert_eq!(state.result, Some(json!(caller)));
1747 }
1748 runtime.begin("return 0", vec![], 1_060_000).await.unwrap();
1749 let mut retained = 0;
1750 for id in &ids {
1751 retained += usize::from(runtime.execution(id).await.unwrap().is_some());
1752 }
1753 assert_eq!(retained, 50, "old history must return to its count limit");
1754 }
1755
1756 #[tokio::test]
1757 async fn configured_grace_expires_and_explicit_pruning_bypasses_it() {
1758 for grace in [0, 5] {
1759 let runtime = CodeModeRuntime::new(Arc::new(MemoryStore::default()))
1760 .with_auto_prune_grace_ms(grace);
1761 for caller in 0..100 {
1762 let id = runtime.begin("return input", vec![], 1).await.unwrap();
1763 runtime
1764 .complete(&id, json!(caller), vec![], 100)
1765 .await
1766 .unwrap();
1767 }
1768 if grace == 5 {
1769 runtime.begin("return 0", vec![], 104).await.unwrap();
1770 let terminal = runtime
1771 .executions()
1772 .await
1773 .unwrap()
1774 .into_iter()
1775 .filter(|s| s.status.terminal())
1776 .count();
1777 assert_eq!(terminal, 100);
1778 }
1779 runtime.begin("return 0", vec![], 105).await.unwrap();
1780 let terminal = runtime
1781 .executions()
1782 .await
1783 .unwrap()
1784 .into_iter()
1785 .filter(|s| s.status.terminal())
1786 .count();
1787 assert_eq!(terminal, 50);
1788 assert_eq!(runtime.prune(0).await.unwrap(), 50);
1789 assert!(
1790 runtime
1791 .executions()
1792 .await
1793 .unwrap()
1794 .iter()
1795 .all(|s| !s.status.terminal())
1796 );
1797 }
1798 let runtime = CodeModeRuntime::new(Arc::new(MemoryStore::default()));
1799 let id = runtime.begin("return 0", vec![], 1).await.unwrap();
1800 runtime.complete(&id, json!(0), vec![], 2).await.unwrap();
1801 assert_eq!(runtime.prune_at(0, 3).await.unwrap(), 1);
1802 assert!(runtime.execution(&id).await.unwrap().is_none());
1803 }
1804
1805 #[tokio::test]
1806 async fn automatic_grace_preserves_errors_cancellation_and_clock_rollback() {
1807 let runtime = CodeModeRuntime::new(Arc::new(MemoryStore::default()));
1808 let mut ids = Vec::new();
1809 for caller in 0..100 {
1810 let id = runtime.begin("return input", vec![], 1).await.unwrap();
1811 if caller % 2 == 0 {
1812 runtime
1813 .fail(&id, "literal failure", vec![], 1_000_000)
1814 .await
1815 .unwrap();
1816 } else {
1817 assert!(runtime.cancel(&id, 1_000_000).await.unwrap());
1818 }
1819 ids.push(id);
1820 }
1821 runtime.begin("return 0", vec![], 0).await.unwrap();
1822 runtime.begin("return 0", vec![], 1_059_999).await.unwrap();
1823 for (caller, id) in ids.iter().enumerate() {
1824 let state = runtime
1825 .execution(id)
1826 .await
1827 .unwrap()
1828 .expect("recent terminal state was lost");
1829 if caller % 2 == 0 {
1830 assert_eq!(state.status, ExecutionStatus::Error);
1831 assert_eq!(state.error.as_deref(), Some("literal failure"));
1832 } else {
1833 assert_eq!(state.status, ExecutionStatus::Cancelled);
1834 }
1835 }
1836 assert_eq!(runtime.prune(0).await.unwrap(), 100);
1837 assert_eq!(runtime.executions().await.unwrap().len(), 2);
1838 }
1839}
1840
1841#[cfg(test)]
1842mod tests {
1843 use serde_json::json;
1844
1845 use super::*;
1846
1847 #[tokio::test]
1848 async fn checkpoints_are_private_persisted_and_state_guarded() {
1849 let store = Arc::new(MemoryStore::default());
1850 let runtime = CodeModeRuntime::new(store.clone());
1851 let id = runtime.begin("async () => 1", vec![], 1).await.unwrap();
1852 let checkpoint = ExecutionCheckpoint {
1853 identity: "fixture-build/program-1".into(),
1854 bytes: vec![0, 1, 255],
1855 };
1856 assert!(runtime.checkpoint(&id).await.unwrap().is_none());
1857 runtime.save_checkpoint(&id, &checkpoint).await.unwrap();
1858 let reopened = CodeModeRuntime::new(store.clone());
1859 assert_eq!(
1860 reopened.checkpoint(&id).await.unwrap(),
1861 Some(checkpoint.clone())
1862 );
1863 let projection = serde_json::to_value(reopened.execution(&id).await.unwrap()).unwrap();
1864 assert!(projection.get("checkpoint").is_none());
1865 runtime.cancel(&id, 2).await.unwrap();
1866 assert!(runtime.save_checkpoint(&id, &checkpoint).await.is_err());
1867 store.delete_execution(&id).await.unwrap();
1868 assert!(store.get_checkpoint(&id).await.unwrap().is_none());
1869 assert!(runtime.checkpoint(&id).await.is_err());
1870 }
1871
1872 #[tokio::test]
1873 async fn missing_checkpoint_cannot_replay_an_execution_with_journaled_calls() {
1874 let runtime = runtime();
1875 let id = runtime.begin("async () => 1", vec![], 1).await.unwrap();
1876 runtime
1877 .decide(&id, 0, "fixture", "read", json!({}), false, false, 2)
1878 .await
1879 .unwrap();
1880 assert!(
1881 runtime
1882 .checkpoint(&id)
1883 .await
1884 .unwrap_err()
1885 .to_string()
1886 .contains("CHECKPOINT_MISSING")
1887 );
1888 }
1889
1890 fn runtime() -> CodeModeRuntime {
1891 CodeModeRuntime::new(Arc::new(MemoryStore::default()))
1892 }
1893
1894 fn runtime_parts() -> (CodeModeRuntime, Arc<MemoryStore>, Arc<MemoryArtifactStore>) {
1895 let store = Arc::new(MemoryStore::default());
1896 let artifacts = Arc::new(MemoryArtifactStore::default());
1897 (
1898 CodeModeRuntime::with_artifacts(store.clone(), artifacts.clone()),
1899 store,
1900 artifacts,
1901 )
1902 }
1903
1904 fn artifact_id(value: &Value) -> String {
1905 serde_json::from_value::<ArtifactRef>(value["$artifact"].clone())
1906 .unwrap()
1907 .id
1908 }
1909
1910 #[tokio::test]
1911 async fn pauses_approves_and_replays_without_reapplying() {
1912 let runtime = runtime();
1913 let id = runtime
1914 .begin("async () => {}", vec!["db".into()], 1)
1915 .await
1916 .unwrap();
1917 assert_eq!(
1918 runtime
1919 .decide(&id, 0, "db", "write", json!({"id": 1}), true, false, 2)
1920 .await
1921 .unwrap(),
1922 ToolDecision::Pause(0)
1923 );
1924 assert!(runtime.approve(&id, 0, 3).await.unwrap());
1925 assert_eq!(
1926 runtime
1927 .decide(&id, 0, "db", "write", json!({"id": 1}), true, false, 4)
1928 .await
1929 .unwrap(),
1930 ToolDecision::Execute(0)
1931 );
1932 runtime
1933 .record_result(&id, 0, json!({"ok": true}), 5)
1934 .await
1935 .unwrap();
1936 assert_eq!(
1937 runtime
1938 .decide(&id, 0, "db", "write", json!({"id": 1}), true, false, 6)
1939 .await
1940 .unwrap(),
1941 ToolDecision::Replay(json!({"ok": true}))
1942 );
1943 }
1944
1945 #[tokio::test]
1946 async fn rejects_results_for_pending_approval_entries() {
1947 let runtime = runtime();
1948 let id = runtime
1949 .begin("async () => {}", vec!["db".into()], 1)
1950 .await
1951 .unwrap();
1952 runtime
1953 .decide(&id, 0, "db", "write", json!({"id": 1}), true, false, 2)
1954 .await
1955 .unwrap();
1956
1957 let error = runtime
1958 .record_result(&id, 0, json!({"forged": true}), 3)
1959 .await
1960 .unwrap_err();
1961
1962 assert!(matches!(error, RuntimeError::InvalidState(_)));
1963 let execution = runtime.execution(&id).await.unwrap().unwrap();
1964 assert_eq!(execution.status, ExecutionStatus::Paused);
1965 assert_eq!(execution.log[0].state, LogEntryState::Pending);
1966 }
1967
1968 #[tokio::test]
1969 async fn terminal_state_cannot_be_overwritten_by_late_completion() {
1970 let runtime = runtime();
1971 let id = runtime.begin("async () => 42", vec![], 1).await.unwrap();
1972 runtime.cancel(&id, 2).await.unwrap();
1973
1974 let error = runtime
1975 .complete(&id, json!(42), Vec::new(), 3)
1976 .await
1977 .unwrap_err();
1978
1979 assert!(matches!(error, RuntimeError::InvalidState(_)));
1980 assert_eq!(
1981 runtime.execution(&id).await.unwrap().unwrap().status,
1982 ExecutionStatus::Cancelled
1983 );
1984 }
1985
1986 #[tokio::test]
1987 async fn stale_rejection_cannot_replace_cancellation() {
1988 let runtime = runtime();
1989 let id = runtime
1990 .begin("async () => {}", vec!["db".into()], 1)
1991 .await
1992 .unwrap();
1993 runtime
1994 .decide(&id, 0, "db", "write", json!({}), true, false, 2)
1995 .await
1996 .unwrap();
1997 runtime.cancel(&id, 3).await.unwrap();
1998
1999 let error = runtime.reject(&id, 0, 4).await.unwrap_err();
2000
2001 assert!(matches!(error, RuntimeError::InvalidState(_)));
2002 assert_eq!(
2003 runtime.execution(&id).await.unwrap().unwrap().status,
2004 ExecutionStatus::Cancelled
2005 );
2006 }
2007
2008 #[tokio::test]
2009 async fn rollback_rejects_running_executions() {
2010 let runtime = runtime();
2011 let id = runtime.begin("async () => 42", vec![], 1).await.unwrap();
2012
2013 let error = runtime.actions_to_revert(&id).await.unwrap_err();
2014
2015 assert!(matches!(error, RuntimeError::InvalidState(_)));
2016 assert_eq!(
2017 runtime.execution(&id).await.unwrap().unwrap().status,
2018 ExecutionStatus::Running
2019 );
2020 }
2021
2022 #[tokio::test]
2023 async fn resume_cannot_bypass_pending_approval() {
2024 let runtime = runtime();
2025 let id = runtime
2026 .begin("async () => {}", vec!["db".into()], 1)
2027 .await
2028 .unwrap();
2029 runtime
2030 .decide(&id, 0, "db", "write", json!({"id": 1}), true, false, 2)
2031 .await
2032 .unwrap();
2033
2034 let error = runtime.resume(&id, 3).await.unwrap_err();
2035
2036 assert!(matches!(error, RuntimeError::InvalidState(_)));
2037 let execution = runtime.execution(&id).await.unwrap().unwrap();
2038 assert_eq!(execution.status, ExecutionStatus::Paused);
2039 assert_eq!(execution.log[0].state, LogEntryState::Pending);
2040 }
2041
2042 #[tokio::test]
2043 async fn ephemeral_observations_are_retained_but_never_replayed() {
2044 let runtime = runtime();
2045 let id = runtime
2046 .begin("async () => {}", vec!["db".into()], 1)
2047 .await
2048 .unwrap();
2049 runtime
2050 .decide(&id, 0, "db", "read", json!({}), false, true, 2)
2051 .await
2052 .unwrap();
2053 runtime.record_result(&id, 0, json!(73), 3).await.unwrap();
2054 assert_eq!(
2055 runtime.execution(&id).await.unwrap().unwrap().log[0].result,
2056 Some(json!(73))
2057 );
2058 assert_eq!(
2059 runtime
2060 .decide(&id, 0, "db", "read", json!({}), false, true, 4)
2061 .await
2062 .unwrap(),
2063 ToolDecision::Execute(0)
2064 );
2065 runtime.record_result(&id, 0, json!(91), 5).await.unwrap();
2066 assert_eq!(
2067 runtime.execution(&id).await.unwrap().unwrap().log[0].result,
2068 Some(json!(91))
2069 );
2070 }
2071
2072 #[tokio::test]
2073 async fn rollback_targets_only_logged_connector_actions() {
2074 let runtime = runtime();
2075 let id = runtime
2076 .begin("async () => {}", vec!["db".into()], 1)
2077 .await
2078 .unwrap();
2079 runtime
2080 .decide(&id, 0, "db", "read", json!({}), false, true, 2)
2081 .await
2082 .unwrap();
2083 runtime.record_result(&id, 0, json!(1), 3).await.unwrap();
2084 runtime
2085 .decide(&id, 1, "db", "write", json!({}), false, false, 4)
2086 .await
2087 .unwrap();
2088 runtime.record_result(&id, 1, json!(2), 5).await.unwrap();
2089 runtime
2090 .complete(&id, json!({"ok": true}), Vec::new(), 6)
2091 .await
2092 .unwrap();
2093
2094 let actions = runtime.actions_to_revert(&id).await.unwrap();
2095
2096 assert_eq!(actions.len(), 1);
2097 assert_eq!(actions[0].seq, 1);
2098 }
2099
2100 #[tokio::test]
2101 async fn divergence_is_terminal() {
2102 let runtime = runtime();
2103 let id = runtime.begin("async () => {}", vec![], 1).await.unwrap();
2104 runtime
2105 .decide(&id, 0, "db", "read", json!({"id": 1}), false, false, 2)
2106 .await
2107 .unwrap();
2108 runtime.record_result(&id, 0, json!(1), 3).await.unwrap();
2109 assert_eq!(
2110 runtime
2111 .decide(&id, 0, "db", "read", json!({"id": 2}), false, false, 4)
2112 .await
2113 .unwrap(),
2114 ToolDecision::Pause(0)
2115 );
2116 assert_eq!(
2117 runtime.execution(&id).await.unwrap().unwrap().status,
2118 ExecutionStatus::Error
2119 );
2120 }
2121
2122 #[tokio::test]
2123 async fn spills_and_rehydrates_oversized_replay_values() {
2124 let (runtime, store, _) = runtime_parts();
2125 let id = runtime
2126 .begin("async () => {}", vec!["db".into()], 1)
2127 .await
2128 .unwrap();
2129 runtime
2130 .decide(&id, 0, "db", "read", json!({}), false, false, 2)
2131 .await
2132 .unwrap();
2133 let value = json!("x".repeat(MAX_DURABLE_VALUE_BYTES + 1));
2134 runtime
2135 .record_result(&id, 0, value.clone(), 3)
2136 .await
2137 .unwrap();
2138 let raw = store.get_execution(&id).await.unwrap().unwrap();
2139 assert!(raw.log[0].result.as_ref().unwrap()["$artifact"].is_object());
2140 let execution = runtime.execution(&id).await.unwrap().unwrap();
2141 assert_eq!(execution.log[0].result, Some(value.clone()));
2142 assert_eq!(
2143 runtime
2144 .decide(&id, 0, "db", "read", json!({}), false, false, 4)
2145 .await
2146 .unwrap(),
2147 ToolDecision::Replay(value)
2148 );
2149 }
2150
2151 #[tokio::test]
2152 async fn spills_and_rehydrates_oversized_arguments() {
2153 let (runtime, store, _) = runtime_parts();
2154 let id = runtime
2155 .begin("async () => {}", vec!["db".into()], 1)
2156 .await
2157 .unwrap();
2158 let arguments = json!({"payload": "x".repeat(MAX_DURABLE_VALUE_BYTES + 1)});
2159
2160 assert_eq!(
2161 runtime
2162 .decide(&id, 0, "db", "write", arguments.clone(), false, false, 2)
2163 .await
2164 .unwrap(),
2165 ToolDecision::Execute(0)
2166 );
2167
2168 let raw = store.get_execution(&id).await.unwrap().unwrap();
2169 assert!(raw.log[0].arguments["$artifact"].is_object());
2170 let execution = runtime.execution(&id).await.unwrap().unwrap();
2171 assert_eq!(execution.log[0].arguments, arguments);
2172 }
2173
2174 #[tokio::test]
2175 async fn pending_actions_rehydrate_oversized_arguments() {
2176 let runtime = runtime();
2177 let id = runtime
2178 .begin("async () => {}", vec!["db".into()], 1)
2179 .await
2180 .unwrap();
2181 let arguments = json!({"payload": "x".repeat(MAX_DURABLE_VALUE_BYTES + 1)});
2182
2183 assert_eq!(
2184 runtime
2185 .decide(&id, 0, "db", "write", arguments.clone(), true, false, 2)
2186 .await
2187 .unwrap(),
2188 ToolDecision::Pause(0)
2189 );
2190
2191 let pending = runtime.pending(Some(&id)).await.unwrap();
2192 assert_eq!(pending[0].arguments, arguments);
2193 }
2194
2195 #[tokio::test]
2196 async fn retrieves_oversized_final_result_by_execution_and_artifact_ids() {
2197 let (runtime, store, _) = runtime_parts();
2198 let id = runtime.begin("async () => {}", vec![], 1).await.unwrap();
2199 let value = json!("x".repeat(MAX_DURABLE_VALUE_BYTES + 1));
2200
2201 runtime
2202 .complete(&id, value.clone(), Vec::new(), 2)
2203 .await
2204 .unwrap();
2205
2206 let raw = store.get_execution(&id).await.unwrap().unwrap();
2207 let artifact_id = artifact_id(raw.result.as_ref().unwrap());
2208 assert_eq!(
2209 runtime.artifact(&id, &artifact_id).await.unwrap(),
2210 Some(value.clone())
2211 );
2212 assert_eq!(
2213 runtime.execution(&id).await.unwrap().unwrap().result,
2214 Some(value)
2215 );
2216 }
2217
2218 #[tokio::test]
2219 async fn denies_artifact_lookup_for_wrong_execution_owner() {
2220 let (runtime, store, _) = runtime_parts();
2221 let owner = runtime.begin("async () => {}", vec![], 1).await.unwrap();
2222 let other = runtime.begin("async () => {}", vec![], 2).await.unwrap();
2223 let value = json!("x".repeat(MAX_DURABLE_VALUE_BYTES + 1));
2224 runtime
2225 .complete(&owner, value, Vec::new(), 3)
2226 .await
2227 .unwrap();
2228 let raw = store.get_execution(&owner).await.unwrap().unwrap();
2229 let artifact_id = artifact_id(raw.result.as_ref().unwrap());
2230
2231 assert_eq!(runtime.artifact(&other, &artifact_id).await.unwrap(), None);
2232 }
2233
2234 #[tokio::test]
2235 async fn missing_artifact_fails_rehydrated_execution_lookup() {
2236 let (runtime, _, artifacts) = runtime_parts();
2237 let id = runtime.begin("async () => {}", vec![], 1).await.unwrap();
2238 let value = json!("x".repeat(MAX_DURABLE_VALUE_BYTES + 1));
2239 runtime.complete(&id, value, Vec::new(), 2).await.unwrap();
2240
2241 artifacts.delete_execution(&id).await.unwrap();
2242 let error = runtime.execution(&id).await.unwrap_err();
2243
2244 assert!(matches!(error, RuntimeError::Store(message) if message.contains("unavailable")));
2245 }
2246
2247 #[tokio::test]
2248 async fn prune_deletes_artifacts_for_removed_executions() {
2249 let (runtime, store, _) = runtime_parts();
2250 let id = runtime.begin("async () => {}", vec![], 1).await.unwrap();
2251 let value = json!("x".repeat(MAX_DURABLE_VALUE_BYTES + 1));
2252 runtime
2253 .complete(&id, value.clone(), Vec::new(), 2)
2254 .await
2255 .unwrap();
2256 let raw = store.get_execution(&id).await.unwrap().unwrap();
2257 let artifact_id = artifact_id(raw.result.as_ref().unwrap());
2258 assert_eq!(
2259 runtime.artifact(&id, &artifact_id).await.unwrap(),
2260 Some(value)
2261 );
2262
2263 assert_eq!(runtime.prune(0).await.unwrap(), 1);
2264
2265 assert_eq!(runtime.artifact(&id, &artifact_id).await.unwrap(), None);
2266 assert!(runtime.execution(&id).await.unwrap().is_none());
2267 }
2268}