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 if let Some(pointer) = &self.workflow_limits.publish_requires
1487 && execution.result.as_ref().and_then(|v| v.pointer(pointer))
1488 != Some(&Value::Bool(true))
1489 {
1490 return Err(RuntimeError::InvalidState(format!(
1491 "WORKFLOW_UNVERIFIED: the saved run must return true at {pointer}"
1492 )));
1493 }
1494 let snippet = Snippet {
1495 name: name.into(),
1496 description: description.into(),
1497 code: execution.code,
1498 saved_at: now,
1499 input_schema,
1500 connectors: execution.connectors,
1501 };
1502 if !self
1503 .workflow_publish_snippet(&snippet)
1504 .await
1505 .map_err(RuntimeError::Store)?
1506 {
1507 self.store
1508 .put_snippet(&snippet)
1509 .await
1510 .map_err(RuntimeError::Store)?;
1511 }
1512 Ok(snippet)
1513 }
1514
1515 pub async fn publish_snippet(&self, snippet: Snippet) -> Result<Snippet, RuntimeError> {
1517 if let Some(pointer) = &self.workflow_limits.publish_requires {
1518 return Err(RuntimeError::InvalidState(format!(
1519 "WORKFLOW_UNVERIFIED: this host publishes only runs that return true at {pointer}; run it in a program and publish there"
1520 )));
1521 }
1522 if !self
1523 .workflow_publish_snippet(&snippet)
1524 .await
1525 .map_err(RuntimeError::Store)?
1526 {
1527 self.store
1528 .put_snippet(&snippet)
1529 .await
1530 .map_err(RuntimeError::Store)?;
1531 }
1532 Ok(snippet)
1533 }
1534
1535 pub async fn snippets(&self) -> Result<Vec<Snippet>, RuntimeError> {
1537 let mut snippets = self
1538 .store
1539 .list_snippets()
1540 .await
1541 .map_err(RuntimeError::Store)?;
1542 let published = self
1543 .workflow_snippets()
1544 .await
1545 .map_err(RuntimeError::Store)?;
1546 if self.store.get_workflows().await.is_ok() {
1547 snippets = published;
1548 } else {
1549 snippets.extend(published);
1550 }
1551 snippets.sort_by(|left, right| left.name.cmp(&right.name));
1552 Ok(snippets)
1553 }
1554
1555 pub async fn delete_snippet(&self, name: &str) -> Result<bool, RuntimeError> {
1557 let published = self
1558 .workflow_delete_snippet(name)
1559 .await
1560 .map_err(RuntimeError::Store)?;
1561 let legacy = self
1562 .store
1563 .delete_snippet(name)
1564 .await
1565 .map_err(RuntimeError::Store)?;
1566 Ok(published || legacy)
1567 }
1568
1569 async fn require(&self, id: &str) -> Result<ExecutionState, RuntimeError> {
1570 self.store
1571 .get_execution(id)
1572 .await
1573 .map_err(RuntimeError::Store)?
1574 .ok_or_else(|| RuntimeError::MissingExecution(id.to_string()))
1575 }
1576
1577 async fn save(&self, execution: &ExecutionState) -> Result<(), RuntimeError> {
1578 self.store
1579 .put_execution(execution)
1580 .await
1581 .map_err(RuntimeError::Store)
1582 }
1583
1584 async fn prune_locked(
1585 &self,
1586 keep: usize,
1587 excluding: Option<&str>,
1588 now: Option<u64>,
1589 minimum_age_ms: u64,
1590 ) -> Result<usize, RuntimeError> {
1591 let mut terminal = self
1592 .store
1593 .list_executions()
1594 .await
1595 .map_err(RuntimeError::Store)?
1596 .into_iter()
1597 .filter(|execution| {
1598 execution.status.terminal()
1599 && now.is_none_or(|now| {
1600 now.saturating_sub(execution.updated_at) >= minimum_age_ms
1601 })
1602 && execution
1603 .retained_until
1604 .is_none_or(|until| now.is_some_and(|now| now >= until))
1605 && excluding.is_none_or(|id| execution.id.as_str() != id)
1606 })
1607 .collect::<Vec<_>>();
1608 terminal.sort_by_key(|execution| std::cmp::Reverse(execution.created_at));
1609 let remove = terminal.len().saturating_sub(keep);
1610 for execution in terminal.into_iter().rev().take(remove) {
1611 self.store
1612 .delete_execution(&execution.id)
1613 .await
1614 .map_err(RuntimeError::Store)?;
1615 self.artifacts
1616 .delete_execution(&execution.id)
1617 .await
1618 .map_err(RuntimeError::Store)?;
1619 }
1620 Ok(remove)
1621 }
1622}
1623
1624fn ensure_size(what: &str, value: &Value) -> Result<(), RuntimeError> {
1625 let size = serialized_size(value);
1626 if size > MAX_DURABLE_VALUE_BYTES {
1627 Err(RuntimeError::DurableValue(format!(
1628 "{what} is too large to record durably ({size} bytes > \
1629 {MAX_DURABLE_VALUE_BYTES} byte limit). Write large data to a file or workspace \
1630 instead and pass or return a small reference."
1631 )))
1632 } else {
1633 Ok(())
1634 }
1635}
1636
1637fn serialized_size(value: &Value) -> usize {
1638 serde_json::to_vec(value).map_or(usize::MAX, |value| value.len())
1639}
1640
1641fn stable_json(value: &Value) -> String {
1642 match value {
1643 Value::Object(values) => {
1644 let mut values = values.iter().collect::<Vec<_>>();
1645 values.sort_by_key(|(key, _)| *key);
1646 format!(
1647 "{{{}}}",
1648 values
1649 .into_iter()
1650 .map(|(key, value)| format!(
1651 "{}:{}",
1652 serde_json::to_string(key).unwrap(),
1653 stable_json(value)
1654 ))
1655 .collect::<Vec<_>>()
1656 .join(",")
1657 )
1658 }
1659 Value::Array(values) => format!(
1660 "[{}]",
1661 values.iter().map(stable_json).collect::<Vec<_>>().join(",")
1662 ),
1663 value => serde_json::to_string(value).unwrap_or_default(),
1664 }
1665}
1666
1667fn bounded_logs(logs: Vec<String>) -> Vec<String> {
1668 let mut size = 2;
1669 logs.into_iter()
1670 .take_while(|log| {
1671 size += log.len() + 3;
1672 size <= MAX_DURABLE_VALUE_BYTES
1673 })
1674 .collect()
1675}
1676
1677fn push_event(execution: &mut ExecutionState, event: ExecutionEvent) {
1678 execution.events.push(event);
1679 if execution.events.len() > DEFAULT_MAX_EVENTS {
1680 execution
1681 .events
1682 .drain(..execution.events.len() - DEFAULT_MAX_EVENTS);
1683 }
1684}
1685
1686fn artifact_ref(value: &Value) -> Result<Option<ArtifactRef>, RuntimeError> {
1687 let Value::Object(values) = value else {
1688 return Ok(None);
1689 };
1690 if values.len() != 1 {
1691 return Ok(None);
1692 }
1693 let Some(artifact) = values.get("$artifact") else {
1694 return Ok(None);
1695 };
1696 serde_json::from_value::<ArtifactRef>(artifact.clone())
1697 .map(Some)
1698 .map_err(|error| RuntimeError::Store(error.to_string()))
1699}
1700
1701fn truncate_bytes(mut value: String, limit: usize) -> String {
1702 if value.len() <= limit {
1703 return value;
1704 }
1705 let mut end = limit;
1706 while !value.is_char_boundary(end) {
1707 end -= 1;
1708 }
1709 value.truncate(end);
1710 value
1711}
1712
1713fn validate_rollback_state(execution: &ExecutionState) -> Result<(), RuntimeError> {
1714 if !execution.status.terminal() || execution.status == ExecutionStatus::RolledBack {
1715 return Err(RuntimeError::InvalidState(format!(
1716 "Execution \"{}\" is {:?}, not rollback eligible",
1717 execution.id, execution.status
1718 )));
1719 }
1720 if execution.log.iter().any(|entry| {
1721 matches!(
1722 entry.state,
1723 LogEntryState::Pending | LogEntryState::Executing
1724 )
1725 }) {
1726 return Err(RuntimeError::InvalidState(format!(
1727 "Execution \"{}\" has an unfinished action",
1728 execution.id
1729 )));
1730 }
1731 Ok(())
1732}
1733
1734#[cfg(test)]
1735mod history_retention_tests {
1736 use super::*;
1737 use serde_json::json;
1738
1739 #[tokio::test]
1740 async fn automatic_pruning_preserves_a_burst_until_after_completion_grace() {
1741 let runtime = CodeModeRuntime::new(Arc::new(MemoryStore::default()));
1742 let mut ids = Vec::new();
1743 for caller in 0..100 {
1744 let id = runtime.begin("return input", vec![], 1).await.unwrap();
1745 runtime
1746 .complete(&id, json!(caller), vec![], 1_000_000)
1747 .await
1748 .unwrap();
1749 ids.push(id);
1750 }
1751 runtime.begin("return 0", vec![], 1_059_999).await.unwrap();
1753 for (caller, id) in ids.iter().enumerate() {
1754 let state = runtime
1755 .execution(id)
1756 .await
1757 .unwrap()
1758 .expect("recent result was pruned before its caller could fetch it");
1759 assert_eq!(state.result, Some(json!(caller)));
1760 }
1761 runtime.begin("return 0", vec![], 1_060_000).await.unwrap();
1762 let mut retained = 0;
1763 for id in &ids {
1764 retained += usize::from(runtime.execution(id).await.unwrap().is_some());
1765 }
1766 assert_eq!(retained, 50, "old history must return to its count limit");
1767 }
1768
1769 #[tokio::test]
1770 async fn configured_grace_expires_and_explicit_pruning_bypasses_it() {
1771 for grace in [0, 5] {
1772 let runtime = CodeModeRuntime::new(Arc::new(MemoryStore::default()))
1773 .with_auto_prune_grace_ms(grace);
1774 for caller in 0..100 {
1775 let id = runtime.begin("return input", vec![], 1).await.unwrap();
1776 runtime
1777 .complete(&id, json!(caller), vec![], 100)
1778 .await
1779 .unwrap();
1780 }
1781 if grace == 5 {
1782 runtime.begin("return 0", vec![], 104).await.unwrap();
1783 let terminal = runtime
1784 .executions()
1785 .await
1786 .unwrap()
1787 .into_iter()
1788 .filter(|s| s.status.terminal())
1789 .count();
1790 assert_eq!(terminal, 100);
1791 }
1792 runtime.begin("return 0", vec![], 105).await.unwrap();
1793 let terminal = runtime
1794 .executions()
1795 .await
1796 .unwrap()
1797 .into_iter()
1798 .filter(|s| s.status.terminal())
1799 .count();
1800 assert_eq!(terminal, 50);
1801 assert_eq!(runtime.prune(0).await.unwrap(), 50);
1802 assert!(
1803 runtime
1804 .executions()
1805 .await
1806 .unwrap()
1807 .iter()
1808 .all(|s| !s.status.terminal())
1809 );
1810 }
1811 let runtime = CodeModeRuntime::new(Arc::new(MemoryStore::default()));
1812 let id = runtime.begin("return 0", vec![], 1).await.unwrap();
1813 runtime.complete(&id, json!(0), vec![], 2).await.unwrap();
1814 assert_eq!(runtime.prune_at(0, 3).await.unwrap(), 1);
1815 assert!(runtime.execution(&id).await.unwrap().is_none());
1816 }
1817
1818 #[tokio::test]
1819 async fn automatic_grace_preserves_errors_cancellation_and_clock_rollback() {
1820 let runtime = CodeModeRuntime::new(Arc::new(MemoryStore::default()));
1821 let mut ids = Vec::new();
1822 for caller in 0..100 {
1823 let id = runtime.begin("return input", vec![], 1).await.unwrap();
1824 if caller % 2 == 0 {
1825 runtime
1826 .fail(&id, "literal failure", vec![], 1_000_000)
1827 .await
1828 .unwrap();
1829 } else {
1830 assert!(runtime.cancel(&id, 1_000_000).await.unwrap());
1831 }
1832 ids.push(id);
1833 }
1834 runtime.begin("return 0", vec![], 0).await.unwrap();
1835 runtime.begin("return 0", vec![], 1_059_999).await.unwrap();
1836 for (caller, id) in ids.iter().enumerate() {
1837 let state = runtime
1838 .execution(id)
1839 .await
1840 .unwrap()
1841 .expect("recent terminal state was lost");
1842 if caller % 2 == 0 {
1843 assert_eq!(state.status, ExecutionStatus::Error);
1844 assert_eq!(state.error.as_deref(), Some("literal failure"));
1845 } else {
1846 assert_eq!(state.status, ExecutionStatus::Cancelled);
1847 }
1848 }
1849 assert_eq!(runtime.prune(0).await.unwrap(), 100);
1850 assert_eq!(runtime.executions().await.unwrap().len(), 2);
1851 }
1852}
1853
1854#[cfg(test)]
1855mod tests {
1856 use serde_json::json;
1857
1858 use super::*;
1859
1860 #[tokio::test]
1861 async fn checkpoints_are_private_persisted_and_state_guarded() {
1862 let store = Arc::new(MemoryStore::default());
1863 let runtime = CodeModeRuntime::new(store.clone());
1864 let id = runtime.begin("async () => 1", vec![], 1).await.unwrap();
1865 let checkpoint = ExecutionCheckpoint {
1866 identity: "fixture-build/program-1".into(),
1867 bytes: vec![0, 1, 255],
1868 };
1869 assert!(runtime.checkpoint(&id).await.unwrap().is_none());
1870 runtime.save_checkpoint(&id, &checkpoint).await.unwrap();
1871 let reopened = CodeModeRuntime::new(store.clone());
1872 assert_eq!(
1873 reopened.checkpoint(&id).await.unwrap(),
1874 Some(checkpoint.clone())
1875 );
1876 let projection = serde_json::to_value(reopened.execution(&id).await.unwrap()).unwrap();
1877 assert!(projection.get("checkpoint").is_none());
1878 runtime.cancel(&id, 2).await.unwrap();
1879 assert!(runtime.save_checkpoint(&id, &checkpoint).await.is_err());
1880 store.delete_execution(&id).await.unwrap();
1881 assert!(store.get_checkpoint(&id).await.unwrap().is_none());
1882 assert!(runtime.checkpoint(&id).await.is_err());
1883 }
1884
1885 #[tokio::test]
1886 async fn missing_checkpoint_cannot_replay_an_execution_with_journaled_calls() {
1887 let runtime = runtime();
1888 let id = runtime.begin("async () => 1", vec![], 1).await.unwrap();
1889 runtime
1890 .decide(&id, 0, "fixture", "read", json!({}), false, false, 2)
1891 .await
1892 .unwrap();
1893 assert!(
1894 runtime
1895 .checkpoint(&id)
1896 .await
1897 .unwrap_err()
1898 .to_string()
1899 .contains("CHECKPOINT_MISSING")
1900 );
1901 }
1902
1903 fn runtime() -> CodeModeRuntime {
1904 CodeModeRuntime::new(Arc::new(MemoryStore::default()))
1905 }
1906
1907 fn runtime_parts() -> (CodeModeRuntime, Arc<MemoryStore>, Arc<MemoryArtifactStore>) {
1908 let store = Arc::new(MemoryStore::default());
1909 let artifacts = Arc::new(MemoryArtifactStore::default());
1910 (
1911 CodeModeRuntime::with_artifacts(store.clone(), artifacts.clone()),
1912 store,
1913 artifacts,
1914 )
1915 }
1916
1917 fn artifact_id(value: &Value) -> String {
1918 serde_json::from_value::<ArtifactRef>(value["$artifact"].clone())
1919 .unwrap()
1920 .id
1921 }
1922
1923 #[tokio::test]
1924 async fn pauses_approves_and_replays_without_reapplying() {
1925 let runtime = runtime();
1926 let id = runtime
1927 .begin("async () => {}", vec!["db".into()], 1)
1928 .await
1929 .unwrap();
1930 assert_eq!(
1931 runtime
1932 .decide(&id, 0, "db", "write", json!({"id": 1}), true, false, 2)
1933 .await
1934 .unwrap(),
1935 ToolDecision::Pause(0)
1936 );
1937 assert!(runtime.approve(&id, 0, 3).await.unwrap());
1938 assert_eq!(
1939 runtime
1940 .decide(&id, 0, "db", "write", json!({"id": 1}), true, false, 4)
1941 .await
1942 .unwrap(),
1943 ToolDecision::Execute(0)
1944 );
1945 runtime
1946 .record_result(&id, 0, json!({"ok": true}), 5)
1947 .await
1948 .unwrap();
1949 assert_eq!(
1950 runtime
1951 .decide(&id, 0, "db", "write", json!({"id": 1}), true, false, 6)
1952 .await
1953 .unwrap(),
1954 ToolDecision::Replay(json!({"ok": true}))
1955 );
1956 }
1957
1958 #[tokio::test]
1959 async fn rejects_results_for_pending_approval_entries() {
1960 let runtime = runtime();
1961 let id = runtime
1962 .begin("async () => {}", vec!["db".into()], 1)
1963 .await
1964 .unwrap();
1965 runtime
1966 .decide(&id, 0, "db", "write", json!({"id": 1}), true, false, 2)
1967 .await
1968 .unwrap();
1969
1970 let error = runtime
1971 .record_result(&id, 0, json!({"forged": true}), 3)
1972 .await
1973 .unwrap_err();
1974
1975 assert!(matches!(error, RuntimeError::InvalidState(_)));
1976 let execution = runtime.execution(&id).await.unwrap().unwrap();
1977 assert_eq!(execution.status, ExecutionStatus::Paused);
1978 assert_eq!(execution.log[0].state, LogEntryState::Pending);
1979 }
1980
1981 #[tokio::test]
1982 async fn terminal_state_cannot_be_overwritten_by_late_completion() {
1983 let runtime = runtime();
1984 let id = runtime.begin("async () => 42", vec![], 1).await.unwrap();
1985 runtime.cancel(&id, 2).await.unwrap();
1986
1987 let error = runtime
1988 .complete(&id, json!(42), Vec::new(), 3)
1989 .await
1990 .unwrap_err();
1991
1992 assert!(matches!(error, RuntimeError::InvalidState(_)));
1993 assert_eq!(
1994 runtime.execution(&id).await.unwrap().unwrap().status,
1995 ExecutionStatus::Cancelled
1996 );
1997 }
1998
1999 #[tokio::test]
2000 async fn stale_rejection_cannot_replace_cancellation() {
2001 let runtime = runtime();
2002 let id = runtime
2003 .begin("async () => {}", vec!["db".into()], 1)
2004 .await
2005 .unwrap();
2006 runtime
2007 .decide(&id, 0, "db", "write", json!({}), true, false, 2)
2008 .await
2009 .unwrap();
2010 runtime.cancel(&id, 3).await.unwrap();
2011
2012 let error = runtime.reject(&id, 0, 4).await.unwrap_err();
2013
2014 assert!(matches!(error, RuntimeError::InvalidState(_)));
2015 assert_eq!(
2016 runtime.execution(&id).await.unwrap().unwrap().status,
2017 ExecutionStatus::Cancelled
2018 );
2019 }
2020
2021 #[tokio::test]
2022 async fn rollback_rejects_running_executions() {
2023 let runtime = runtime();
2024 let id = runtime.begin("async () => 42", vec![], 1).await.unwrap();
2025
2026 let error = runtime.actions_to_revert(&id).await.unwrap_err();
2027
2028 assert!(matches!(error, RuntimeError::InvalidState(_)));
2029 assert_eq!(
2030 runtime.execution(&id).await.unwrap().unwrap().status,
2031 ExecutionStatus::Running
2032 );
2033 }
2034
2035 #[tokio::test]
2036 async fn resume_cannot_bypass_pending_approval() {
2037 let runtime = runtime();
2038 let id = runtime
2039 .begin("async () => {}", vec!["db".into()], 1)
2040 .await
2041 .unwrap();
2042 runtime
2043 .decide(&id, 0, "db", "write", json!({"id": 1}), true, false, 2)
2044 .await
2045 .unwrap();
2046
2047 let error = runtime.resume(&id, 3).await.unwrap_err();
2048
2049 assert!(matches!(error, RuntimeError::InvalidState(_)));
2050 let execution = runtime.execution(&id).await.unwrap().unwrap();
2051 assert_eq!(execution.status, ExecutionStatus::Paused);
2052 assert_eq!(execution.log[0].state, LogEntryState::Pending);
2053 }
2054
2055 #[tokio::test]
2056 async fn ephemeral_observations_are_retained_but_never_replayed() {
2057 let runtime = runtime();
2058 let id = runtime
2059 .begin("async () => {}", vec!["db".into()], 1)
2060 .await
2061 .unwrap();
2062 runtime
2063 .decide(&id, 0, "db", "read", json!({}), false, true, 2)
2064 .await
2065 .unwrap();
2066 runtime.record_result(&id, 0, json!(73), 3).await.unwrap();
2067 assert_eq!(
2068 runtime.execution(&id).await.unwrap().unwrap().log[0].result,
2069 Some(json!(73))
2070 );
2071 assert_eq!(
2072 runtime
2073 .decide(&id, 0, "db", "read", json!({}), false, true, 4)
2074 .await
2075 .unwrap(),
2076 ToolDecision::Execute(0)
2077 );
2078 runtime.record_result(&id, 0, json!(91), 5).await.unwrap();
2079 assert_eq!(
2080 runtime.execution(&id).await.unwrap().unwrap().log[0].result,
2081 Some(json!(91))
2082 );
2083 }
2084
2085 #[tokio::test]
2086 async fn rollback_targets_only_logged_connector_actions() {
2087 let runtime = runtime();
2088 let id = runtime
2089 .begin("async () => {}", vec!["db".into()], 1)
2090 .await
2091 .unwrap();
2092 runtime
2093 .decide(&id, 0, "db", "read", json!({}), false, true, 2)
2094 .await
2095 .unwrap();
2096 runtime.record_result(&id, 0, json!(1), 3).await.unwrap();
2097 runtime
2098 .decide(&id, 1, "db", "write", json!({}), false, false, 4)
2099 .await
2100 .unwrap();
2101 runtime.record_result(&id, 1, json!(2), 5).await.unwrap();
2102 runtime
2103 .complete(&id, json!({"ok": true}), Vec::new(), 6)
2104 .await
2105 .unwrap();
2106
2107 let actions = runtime.actions_to_revert(&id).await.unwrap();
2108
2109 assert_eq!(actions.len(), 1);
2110 assert_eq!(actions[0].seq, 1);
2111 }
2112
2113 #[tokio::test]
2114 async fn divergence_is_terminal() {
2115 let runtime = runtime();
2116 let id = runtime.begin("async () => {}", vec![], 1).await.unwrap();
2117 runtime
2118 .decide(&id, 0, "db", "read", json!({"id": 1}), false, false, 2)
2119 .await
2120 .unwrap();
2121 runtime.record_result(&id, 0, json!(1), 3).await.unwrap();
2122 assert_eq!(
2123 runtime
2124 .decide(&id, 0, "db", "read", json!({"id": 2}), false, false, 4)
2125 .await
2126 .unwrap(),
2127 ToolDecision::Pause(0)
2128 );
2129 assert_eq!(
2130 runtime.execution(&id).await.unwrap().unwrap().status,
2131 ExecutionStatus::Error
2132 );
2133 }
2134
2135 #[tokio::test]
2136 async fn spills_and_rehydrates_oversized_replay_values() {
2137 let (runtime, store, _) = runtime_parts();
2138 let id = runtime
2139 .begin("async () => {}", vec!["db".into()], 1)
2140 .await
2141 .unwrap();
2142 runtime
2143 .decide(&id, 0, "db", "read", json!({}), false, false, 2)
2144 .await
2145 .unwrap();
2146 let value = json!("x".repeat(MAX_DURABLE_VALUE_BYTES + 1));
2147 runtime
2148 .record_result(&id, 0, value.clone(), 3)
2149 .await
2150 .unwrap();
2151 let raw = store.get_execution(&id).await.unwrap().unwrap();
2152 assert!(raw.log[0].result.as_ref().unwrap()["$artifact"].is_object());
2153 let execution = runtime.execution(&id).await.unwrap().unwrap();
2154 assert_eq!(execution.log[0].result, Some(value.clone()));
2155 assert_eq!(
2156 runtime
2157 .decide(&id, 0, "db", "read", json!({}), false, false, 4)
2158 .await
2159 .unwrap(),
2160 ToolDecision::Replay(value)
2161 );
2162 }
2163
2164 #[tokio::test]
2165 async fn spills_and_rehydrates_oversized_arguments() {
2166 let (runtime, store, _) = runtime_parts();
2167 let id = runtime
2168 .begin("async () => {}", vec!["db".into()], 1)
2169 .await
2170 .unwrap();
2171 let arguments = json!({"payload": "x".repeat(MAX_DURABLE_VALUE_BYTES + 1)});
2172
2173 assert_eq!(
2174 runtime
2175 .decide(&id, 0, "db", "write", arguments.clone(), false, false, 2)
2176 .await
2177 .unwrap(),
2178 ToolDecision::Execute(0)
2179 );
2180
2181 let raw = store.get_execution(&id).await.unwrap().unwrap();
2182 assert!(raw.log[0].arguments["$artifact"].is_object());
2183 let execution = runtime.execution(&id).await.unwrap().unwrap();
2184 assert_eq!(execution.log[0].arguments, arguments);
2185 }
2186
2187 #[tokio::test]
2188 async fn pending_actions_rehydrate_oversized_arguments() {
2189 let runtime = runtime();
2190 let id = runtime
2191 .begin("async () => {}", vec!["db".into()], 1)
2192 .await
2193 .unwrap();
2194 let arguments = json!({"payload": "x".repeat(MAX_DURABLE_VALUE_BYTES + 1)});
2195
2196 assert_eq!(
2197 runtime
2198 .decide(&id, 0, "db", "write", arguments.clone(), true, false, 2)
2199 .await
2200 .unwrap(),
2201 ToolDecision::Pause(0)
2202 );
2203
2204 let pending = runtime.pending(Some(&id)).await.unwrap();
2205 assert_eq!(pending[0].arguments, arguments);
2206 }
2207
2208 #[tokio::test]
2209 async fn retrieves_oversized_final_result_by_execution_and_artifact_ids() {
2210 let (runtime, store, _) = runtime_parts();
2211 let id = runtime.begin("async () => {}", vec![], 1).await.unwrap();
2212 let value = json!("x".repeat(MAX_DURABLE_VALUE_BYTES + 1));
2213
2214 runtime
2215 .complete(&id, value.clone(), Vec::new(), 2)
2216 .await
2217 .unwrap();
2218
2219 let raw = store.get_execution(&id).await.unwrap().unwrap();
2220 let artifact_id = artifact_id(raw.result.as_ref().unwrap());
2221 assert_eq!(
2222 runtime.artifact(&id, &artifact_id).await.unwrap(),
2223 Some(value.clone())
2224 );
2225 assert_eq!(
2226 runtime.execution(&id).await.unwrap().unwrap().result,
2227 Some(value)
2228 );
2229 }
2230
2231 #[tokio::test]
2232 async fn denies_artifact_lookup_for_wrong_execution_owner() {
2233 let (runtime, store, _) = runtime_parts();
2234 let owner = runtime.begin("async () => {}", vec![], 1).await.unwrap();
2235 let other = runtime.begin("async () => {}", vec![], 2).await.unwrap();
2236 let value = json!("x".repeat(MAX_DURABLE_VALUE_BYTES + 1));
2237 runtime
2238 .complete(&owner, value, Vec::new(), 3)
2239 .await
2240 .unwrap();
2241 let raw = store.get_execution(&owner).await.unwrap().unwrap();
2242 let artifact_id = artifact_id(raw.result.as_ref().unwrap());
2243
2244 assert_eq!(runtime.artifact(&other, &artifact_id).await.unwrap(), None);
2245 }
2246
2247 #[tokio::test]
2248 async fn missing_artifact_fails_rehydrated_execution_lookup() {
2249 let (runtime, _, artifacts) = 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.complete(&id, value, Vec::new(), 2).await.unwrap();
2253
2254 artifacts.delete_execution(&id).await.unwrap();
2255 let error = runtime.execution(&id).await.unwrap_err();
2256
2257 assert!(matches!(error, RuntimeError::Store(message) if message.contains("unavailable")));
2258 }
2259
2260 #[tokio::test]
2261 async fn prune_deletes_artifacts_for_removed_executions() {
2262 let (runtime, store, _) = runtime_parts();
2263 let id = runtime.begin("async () => {}", vec![], 1).await.unwrap();
2264 let value = json!("x".repeat(MAX_DURABLE_VALUE_BYTES + 1));
2265 runtime
2266 .complete(&id, value.clone(), Vec::new(), 2)
2267 .await
2268 .unwrap();
2269 let raw = store.get_execution(&id).await.unwrap().unwrap();
2270 let artifact_id = artifact_id(raw.result.as_ref().unwrap());
2271 assert_eq!(
2272 runtime.artifact(&id, &artifact_id).await.unwrap(),
2273 Some(value)
2274 );
2275
2276 assert_eq!(runtime.prune(0).await.unwrap(), 1);
2277
2278 assert_eq!(runtime.artifact(&id, &artifact_id).await.unwrap(), None);
2279 assert!(runtime.execution(&id).await.unwrap().is_none());
2280 }
2281}