use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
use multicast_codemode::{CodeMode, MemoryStore};
use multicast_codemode::{
CodeModeRunOptions, CodeModeService, Connector, ConnectorDescription, ConnectorTool,
ExecutionState, ExecutionStatus, LogEntryState, MulticastConnector, ToolAnnotations,
ToolContext, ToolPolicy,
};
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
use multicast_codemode_local::{LocalCodeModeService, LocalExecutor, LocalExecutorOptions};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::{Resolved, State, program};
pub const MAX_FIXTURE_BYTES: usize = 16 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FixtureContract {
pub input_schema: Value,
pub output_schema: Option<Value>,
pub annotations: ToolAnnotations,
pub policy: ToolPolicy,
}
impl From<&ConnectorTool> for FixtureContract {
fn from(tool: &ConnectorTool) -> Self {
Self {
input_schema: tool.input_schema.clone(),
output_schema: tool.output_schema.clone(),
annotations: tool.annotations.clone(),
policy: tool.policy,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FixtureCall {
pub method: String,
pub arguments: Value,
pub result: Value,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WorkflowFixture {
pub format_version: u32,
pub workflow: String,
pub captured_version: String,
pub connector: String,
pub input_schema: Option<Value>,
pub input: Value,
pub max_attempts: u32,
pub contracts: BTreeMap<String, FixtureContract>,
pub calls: Vec<FixtureCall>,
pub expected: Value,
}
impl State {
pub(super) async fn capture_fixture(
&self,
workflow: &Resolved,
input: Value,
execution_id: &str,
) -> Result<Value, String> {
let (input, code) = program(workflow, input)?;
let service = self.service().await?;
let execution = service.execution(execution_id.into()).await?;
if execution.status != ExecutionStatus::Completed || execution.code != code {
return Err("Capture requires a completed execution of this workflow and input".into());
}
let description = MulticastConnector::new(self.catalog.clone())
.describe()
.await?;
let mut contracts = BTreeMap::new();
let mut calls = Vec::new();
for entry in &execution.log {
if entry.connector == "codemode" {
continue;
}
if entry.connector != description.name || entry.state != LogEntryState::Applied {
return Err(format!(
"Step {} has no completed command observation",
entry.seq
));
}
let tool = description
.tools
.iter()
.find(|tool| tool.name == entry.method)
.ok_or_else(|| format!("Command '{}' no longer exists", entry.method))?;
if tool.policy.requires_approval != entry.requires_approval
|| (tool.policy.replay == multicast_codemode::ReplayPolicy::Reexecute)
!= entry.ephemeral
{
return Err(format!(
"Policy changed since step {} ran; capture a new run",
entry.seq
));
}
let result = entry.result.clone().ok_or_else(|| {
format!(
"Step {} has no recorded result; capture a new run",
entry.seq
)
})?;
contracts.insert(entry.method.clone(), FixtureContract::from(tool));
calls.push(FixtureCall {
method: entry.method.clone(),
arguments: observed_value(service, execution_id, entry.arguments.clone()).await?,
result: observed_value(service, execution_id, result).await?,
});
}
let fixture = WorkflowFixture {
format_version: 1,
workflow: workflow.name.clone(),
captured_version: workflow.version(),
connector: description.name,
input_schema: workflow.input_schema.clone(),
input,
max_attempts: self
.retry
.max_attempts
.clamp(1, multicast_codemode::MAX_CALL_ATTEMPTS),
contracts,
calls,
expected: observed_value(
service,
execution_id,
execution
.result
.ok_or("Completed execution has no result")?,
)
.await?,
};
let bytes = serde_json::to_vec(&fixture).map_err(|error| error.to_string())?;
if bytes.len() > MAX_FIXTURE_BYTES {
return Err("Fixture exceeds the 16 MiB limit".into());
}
serde_json::to_value(fixture).map_err(|error| error.to_string())
}
pub(super) async fn check_fixture(
&self,
workflow: &Resolved,
path: &str,
) -> Result<Value, String> {
let bytes = if let Some(host) = &self.host {
host.read_fixture(path)?
} else {
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
{
use std::io::Read;
let file = std::fs::File::open(path)
.map_err(|error| format!("Cannot read fixture: {error}"))?;
let mut bytes = Vec::new();
file.take(MAX_FIXTURE_BYTES as u64 + 1)
.read_to_end(&mut bytes)
.map_err(|error| format!("Cannot read fixture: {error}"))?;
bytes
}
#[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
{
return Err("A workflow host is required".into());
}
};
if bytes.len() > MAX_FIXTURE_BYTES {
return Err("Fixture exceeds the 16 MiB limit".into());
}
let fixture: WorkflowFixture =
serde_json::from_slice(&bytes).map_err(|error| format!("Invalid fixture: {error}"))?;
if fixture.format_version != 1 || fixture.workflow != workflow.name {
return Err("Fixture format or workflow name does not match".into());
}
if fixture.input_schema != workflow.input_schema {
return Err("Workflow input schema changed; review and recapture the fixture".into());
}
if fixture.max_attempts
!= self
.retry
.max_attempts
.clamp(1, multicast_codemode::MAX_CALL_ATTEMPTS)
{
return Err("Workflow retry budget changed; review and recapture the fixture".into());
}
let (_, code) = program(workflow, fixture.input.clone())?;
let mut description = MulticastConnector::new(self.catalog.clone())
.describe()
.await?;
if description.name != fixture.connector {
return Err("Fixture connector namespace changed".into());
}
for (method, contract) in &fixture.contracts {
let current = description
.tools
.iter()
.find(|tool| &tool.name == method)
.ok_or_else(|| format!("Command '{method}' no longer exists"))?;
if FixtureContract::from(current) != *contract {
return Err(format!(
"Command '{method}' contract or policy changed; review and recapture the fixture"
));
}
}
if fixture
.calls
.iter()
.any(|call| !fixture.contracts.contains_key(&call.method))
{
return Err("Fixture call has no pinned contract".into());
}
for tool in &mut description.tools {
tool.policy = ToolPolicy::default();
}
let cursor = Arc::new(Mutex::new(Cursor::default()));
let connector = Arc::new(FixtureConnector {
description,
calls: fixture.calls.clone(),
cursor: cursor.clone(),
});
let service = if let Some(host) = &self.host {
host.fixture_service(vec![connector])?
} else {
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
{
let local = LocalCodeModeService::spawn(move || {
CodeMode::new(
Arc::new(MemoryStore::default()),
LocalExecutor::new(LocalExecutorOptions::default()),
vec![connector],
)
})?;
Arc::new(local) as Arc<dyn CodeModeService>
}
#[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
{
return Err("A workflow host is required".into());
}
};
let execution = service.execute(code, CodeModeRunOptions::default()).await?;
let mut execution = self.settle(service.as_ref(), execution).await?;
if let Some(result) = execution.result.take() {
execution.result = Some(observed_value(service.as_ref(), &execution.id, result).await?);
}
let cursor = cursor.lock().map_err(|error| error.to_string())?;
check_observations(&fixture, &cursor, &execution)?;
Ok(
json!({"workflow": workflow.name, "passed": true, "calls": cursor.next, "version": workflow.version()}),
)
}
}
async fn observed_value(
service: &dyn CodeModeService,
execution_id: &str,
value: Value,
) -> Result<Value, String> {
if let Some(values) = value.as_object()
&& values.len() == 1
&& let Some(reference) = values.get("$artifact")
{
let reference: multicast_codemode::ArtifactRef =
serde_json::from_value(reference.clone()).map_err(|error| error.to_string())?;
if reference.bytes > MAX_FIXTURE_BYTES {
return Err("Fixture exceeds the 16 MiB limit".into());
}
return service.artifact(execution_id.into(), reference.id).await;
}
Ok(value)
}
#[derive(Default)]
struct Cursor {
next: usize,
failure: Option<String>,
}
struct FixtureConnector {
description: ConnectorDescription,
calls: Vec<FixtureCall>,
cursor: Arc<Mutex<Cursor>>,
}
#[async_trait]
impl Connector for FixtureConnector {
fn name(&self) -> &str {
&self.description.name
}
async fn describe(&self) -> Result<ConnectorDescription, String> {
Ok(self.description.clone())
}
async fn execute(
&self,
method: &str,
arguments: Value,
_: &ToolContext,
) -> Result<Value, String> {
let mut cursor = self.cursor.lock().map_err(|error| error.to_string())?;
if let Some(failure) = &cursor.failure {
return Err(failure.clone());
}
let expected = self.calls.get(cursor.next);
if expected.is_none_or(|call| call.method != method || call.arguments != arguments) {
let message = format!(
"Call {} differs from the fixture: observed {method}({arguments})",
cursor.next
);
cursor.failure = Some(message.clone());
return Err(message);
}
cursor.next += 1;
Ok(expected.expect("checked above").result.clone())
}
}
fn check_observations(
fixture: &WorkflowFixture,
cursor: &Cursor,
execution: &ExecutionState,
) -> Result<(), String> {
if let Some(failure) = &cursor.failure {
return Err(failure.clone());
}
if execution.status != ExecutionStatus::Completed {
return Err(format!(
"Offline workflow did not complete: {}",
execution.error.as_deref().unwrap_or("no result")
));
}
if cursor.next != fixture.calls.len() {
return Err(format!(
"Workflow made {} calls; fixture requires {}",
cursor.next,
fixture.calls.len()
));
}
if execution.result.as_ref() != Some(&fixture.expected) {
return Err("Workflow result differs from the reviewed fixture expectation".into());
}
Ok(())
}