use std::collections::BTreeMap;
use multicast::output::CommandResult;
use multicast_codemode::{
ExecutionEvent, ExecutionState, ExecutionStatus, LogEntryState, Snippet, normalize_code,
sanitize_namespace,
};
use serde_json::{Value, json};
use super::ledger::{self, Ledger, Run};
use super::{Resolved, State, check_schema, error, not_found, ok, referenced_methods, warn_ledger};
const FAILING_STREAK: usize = 3;
const DEFAULT_STALE_DAYS: u64 = 30;
const RECENT_RUNS: usize = 10;
const VALUE_PREVIEW: usize = 160;
const CONSOLE_TAIL: usize = 20;
const DAY_MS: u64 = 86_400_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Severity {
Error,
Warning,
Notice,
}
impl Severity {
fn name(self) -> &'static str {
match self {
Self::Error => "error",
Self::Warning => "warning",
Self::Notice => "notice",
}
}
}
struct Finding {
severity: Severity,
workflow: String,
check: &'static str,
message: String,
hint: String,
execution_id: Option<String>,
}
impl Finding {
fn to_json(&self) -> Value {
let mut value = json!({
"severity": self.severity.name(),
"workflow": self.workflow,
"check": self.check,
"message": self.message,
"hint": self.hint,
});
if let Some(id) = &self.execution_id {
value["executionId"] = Value::String(id.clone());
}
value
}
}
pub(crate) fn timestamp(ms: u64) -> String {
let seconds = ms / 1000;
let days = (seconds / 86_400) as i64;
let time = seconds % 86_400;
let z = days + 719_468;
let era = z.div_euclid(146_097);
let day_of_era = z - era * 146_097;
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_index = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
let month = if month_index < 10 {
month_index + 3
} else {
month_index - 9
};
let year = year_of_era + era * 400 + i64::from(month <= 2);
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
time / 3600,
time % 3600 / 60,
time % 60
)
}
fn optional_timestamp(ms: Option<u64>) -> Value {
ms.map_or(Value::Null, |ms| Value::String(timestamp(ms)))
}
fn now_ms() -> u64 {
web_time::SystemTime::now()
.duration_since(web_time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_millis() as u64)
}
fn is_missing(message: &str) -> bool {
message.ends_with("not found")
}
fn preview(value: &Value, full: bool) -> Value {
if full {
return value.clone();
}
let text = value.to_string();
if text.chars().count() <= VALUE_PREVIEW {
return value.clone();
}
let shown: String = text.chars().take(VALUE_PREVIEW).collect();
let remaining = text.len() - shown.len();
Value::String(format!("{shown}… ({remaining} more bytes)"))
}
fn failure_streak<'a>(runs: &'a [Run], version: &str) -> (usize, Option<&'a Run>) {
let mut streak = 0;
let mut latest = None;
for run in runs.iter().filter(|run| run.version == version) {
match run.status.as_str() {
"error" => {
streak += 1;
latest.get_or_insert(run);
}
"completed" => break,
_ => {}
}
}
(streak, latest)
}
fn ledger_or_error(state: &State) -> Result<&Ledger, Box<CommandResult>> {
state.ledger().ok_or_else(|| {
Box::new(error(
"WORKFLOW_LEDGER_UNAVAILABLE",
"The workflow run ledger could not be opened",
))
})
}
impl State {
async fn reconcile(
&self,
ledger: &Ledger,
) -> Result<(Vec<(Run, ExecutionState)>, Vec<Run>), String> {
let service = self.service().await?;
let mut open = Vec::new();
let mut lost = Vec::new();
for run in ledger.unfinished()? {
match service.execution(run.execution_id.clone()).await {
Ok(execution) => {
warn_ledger(ledger.record(&execution, execution.updated_at));
if matches!(
execution.status,
ExecutionStatus::Running | ExecutionStatus::Paused
) {
open.push((run, execution));
}
}
Err(message) if is_missing(&message) => {
warn_ledger(ledger.mark_lost(&run.execution_id, now_ms()));
lost.push(run);
}
Err(message) => return Err(message),
}
}
Ok((open, lost))
}
pub(crate) async fn doctor(&self, options: &Value) -> Result<CommandResult, String> {
let ledger = match ledger_or_error(self) {
Ok(ledger) => ledger,
Err(result) => return Ok(*result),
};
let all = options.get("all").and_then(Value::as_bool).unwrap_or(false);
let stale_days = options
.get("stale_days")
.and_then(Value::as_f64)
.map_or(DEFAULT_STALE_DAYS, |days| days.max(0.0) as u64);
let now = now_ms();
let mut findings = Vec::new();
let (open, lost) = self.reconcile(ledger).await?;
for (run, execution) in open {
let id = run.execution_id.clone();
if execution.status == ExecutionStatus::Running {
findings.push(Finding {
severity: Severity::Warning,
workflow: run.workflow,
check: "interrupted",
message: format!(
"Run {id} stopped while running, started {}",
timestamp(run.started_at)
),
hint: format!("workflows resume {id}, or workflows cancel {id} to drop it"),
execution_id: Some(id),
});
} else {
let actions: Vec<String> = execution
.log
.iter()
.filter(|entry| {
entry.state == LogEntryState::Pending && entry.requires_approval
})
.map(|entry| {
format!("{}.{} (seq {})", entry.connector, entry.method, entry.seq)
})
.collect();
if actions.is_empty() {
findings.push(Finding {
severity: Severity::Warning,
workflow: run.workflow,
check: "recovery-required",
message: format!("Run {id} has an uncertain call outcome; reconcile it with the host before resuming"),
hint: format!("workflows resume {id}, or workflows cancel {id} to drop it"),
execution_id: Some(id),
});
continue;
}
findings.push(Finding {
severity: Severity::Warning,
workflow: run.workflow,
check: "awaiting-decision",
message: format!(
"Run {id} is waiting for approval of {}, since {}",
actions.join(", "),
timestamp(execution.updated_at)
),
hint: format!("workflows approve {id} or workflows reject {id}"),
execution_id: Some(id),
});
}
}
for run in lost {
let id = run.execution_id.clone();
findings.push(Finding {
severity: Severity::Notice,
check: "lost",
message: format!(
"Run {id} never finished and its execution is no longer in the store"
),
hint: format!("workflows run {}", run.workflow),
workflow: run.workflow,
execution_id: Some(id),
});
}
let snippets = self.service().await?.snippets().await?;
findings.extend(self.saved_findings(&snippets));
findings.extend(self.archetype_findings().await?);
let mut checked = 0;
for workflow in self.catalog_workflows().await? {
checked += 1;
findings.extend(self.health_findings(ledger, &workflow, now, stale_days)?);
}
findings.sort_by(|left, right| {
(left.severity, &left.workflow, left.check).cmp(&(
right.severity,
&right.workflow,
right.check,
))
});
let errors = count(&findings, Severity::Error);
let warnings = count(&findings, Severity::Warning);
let notices = count(&findings, Severity::Notice);
let shown: Vec<Value> = findings
.iter()
.filter(|finding| all || finding.severity != Severity::Notice)
.map(Finding::to_json)
.collect();
let healthy = errors == 0 && warnings == 0;
Ok(CommandResult::Ok {
data: json!({
"healthy": healthy,
"workflows": checked,
"errors": errors,
"warnings": warnings,
"notices": notices,
"findings": shown,
}),
cta: None,
exit_code: (!healthy).then_some(1),
})
}
async fn archetype_findings(&self) -> Result<Vec<Finding>, String> {
let mut findings = Vec::new();
for archetype in self.archetype_store()?.list()? {
let name = archetype.name.clone();
if self.archetypes.contains_key(&name) {
findings.push(Finding {
severity: Severity::Warning,
workflow: name.clone(),
check: "archetype-shadowed",
message: format!(
"Saved archetype '{name}' never activates: a shipped archetype has the same name"
),
hint: format!("archetypes delete {name}"),
execution_id: None,
});
continue;
}
let missing = self.missing_scope(&archetype).await?;
if !missing.is_empty() {
findings.push(Finding {
severity: Severity::Error,
workflow: name.clone(),
check: "archetype-missing-scope",
message: format!(
"Saved archetype '{name}' scopes {}, which this CLI no longer has",
missing.join(", ")
),
hint: format!(
"archetypes show {name}, then save a corrected scope or archetypes delete {name}"
),
execution_id: None,
});
}
}
Ok(findings)
}
fn saved_findings(&self, snippets: &[Snippet]) -> Vec<Finding> {
let namespace = sanitize_namespace(self.catalog.name());
let mut findings = Vec::new();
let mut programs: BTreeMap<String, Vec<String>> = BTreeMap::new();
for snippet in snippets {
let name = snippet.name.clone();
if self.shipped.contains_key(&name) {
findings.push(Finding {
severity: Severity::Warning,
workflow: name.clone(),
check: "shadowed",
message: format!(
"Saved workflow '{name}' never runs: a shipped workflow has the same name"
),
hint: format!("workflows delete {name}"),
execution_id: None,
});
continue;
}
let mut missing: Vec<String> = referenced_methods(&snippet.code, &namespace)
.into_iter()
.filter(|method| self.catalog.get(method).is_none())
.map(|method| format!("{namespace}.{method}"))
.collect();
missing.dedup();
if !missing.is_empty() {
findings.push(Finding {
severity: Severity::Error,
workflow: name.clone(),
check: "missing-command",
message: format!(
"Saved workflow '{name}' calls {}, which this CLI no longer has",
missing.join(", ")
),
hint: format!(
"workflows show {name}, then save a corrected program or workflows delete {name}"
),
execution_id: None,
});
}
if let Some(schema) = &snippet.input_schema
&& let Err(errors) = check_schema(schema)
{
findings.push(Finding {
severity: Severity::Error,
workflow: name.clone(),
check: "unsupported-schema",
message: format!(
"Saved workflow '{name}' has an input schema this CLI cannot check: {}",
errors.join("; ")
),
hint: format!("save '{name}' again with a supported input schema"),
execution_id: None,
});
}
programs
.entry(normalize_code(&snippet.code).trim().to_string())
.or_default()
.push(name);
}
for names in programs.into_values().filter(|names| names.len() > 1) {
for name in &names {
let others: Vec<&str> = names
.iter()
.filter(|other| *other != name)
.map(String::as_str)
.collect();
findings.push(Finding {
severity: Severity::Notice,
workflow: name.clone(),
check: "duplicate",
message: format!(
"Saved workflow '{name}' has the same program as {}",
others.join(", ")
),
hint: "keep one and workflows delete the others".to_string(),
execution_id: None,
});
}
}
findings
}
fn health_findings(
&self,
ledger: &Ledger,
workflow: &Resolved,
now: u64,
stale_days: u64,
) -> Result<Vec<Finding>, String> {
let name = &workflow.name;
let version = workflow.version();
let totals = ledger.totals(name)?;
let mut findings = Vec::new();
let Some(last_run) = totals.iter().map(|totals| totals.last_run).max() else {
findings.push(Finding {
severity: Severity::Notice,
workflow: name.clone(),
check: "never-run",
message: format!("Workflow '{name}' has never run"),
hint: format!("workflows run {name}"),
execution_id: None,
});
return Ok(findings);
};
let runs = ledger.recent(name, ledger::RUNS_PER_WORKFLOW)?;
let (streak, latest) = failure_streak(&runs, &version);
if let Some(latest) = latest {
let cause = latest
.fingerprint
.as_deref()
.and_then(|fingerprint| {
ledger
.failures(Some(name))
.ok()?
.into_iter()
.find(|group| group.fingerprint == fingerprint)
})
.map(|group| format!("{}: {}", group.step, group.shape))
.unwrap_or_default();
let failing = streak >= FAILING_STREAK;
findings.push(Finding {
severity: if failing {
Severity::Error
} else {
Severity::Warning
},
workflow: name.clone(),
check: if failing { "failing" } else { "failed" },
message: format!(
"The last {streak} run{} of '{name}' version {version} failed; latest cause {cause}",
if streak == 1 { "" } else { "s" }
),
hint: format!(
"workflows failures {name} and workflows trace {}",
latest.execution_id
),
execution_id: Some(latest.execution_id.clone()),
});
}
if now.saturating_sub(last_run) > stale_days.saturating_mul(DAY_MS) {
findings.push(Finding {
severity: Severity::Notice,
workflow: name.clone(),
check: "stale",
message: format!("Workflow '{name}' last ran {}", timestamp(last_run)),
hint: format!(
"workflows run {name} or, if saved and unused, workflows delete {name}"
),
execution_id: None,
});
}
Ok(findings)
}
pub(crate) async fn stats(&self, name: Option<&str>) -> Result<CommandResult, String> {
let ledger = match ledger_or_error(self) {
Ok(ledger) => ledger,
Err(result) => return Ok(*result),
};
let workflows = match name {
Some(name) => match self.resolve(name).await? {
Some(workflow) => vec![workflow],
None => return Ok(not_found(name)),
},
None => self.catalog_workflows().await?,
};
let mut rows = Vec::new();
for workflow in &workflows {
let version = workflow.version();
let totals = ledger.totals(&workflow.name)?;
let current = totals
.iter()
.find(|totals| totals.version == version)
.cloned()
.unwrap_or_default();
let decided = current.completed + current.failed;
let mut row = json!({
"name": workflow.name,
"origin": workflow.origin,
"version": version,
"runs": current.started,
"completed": current.completed,
"failed": current.failed,
"rejected": current.rejected,
"cancelled": current.cancelled,
"rolledBack": current.rolled_back,
"lost": current.lost,
"successRate": (decided > 0).then(|| current.completed as f64 / decided as f64),
"earlierVersionRuns": totals
.iter()
.filter(|totals| totals.version != version)
.map(|totals| totals.started)
.sum::<u64>(),
"firstRun": optional_timestamp(totals.iter().map(|t| t.first_run).min()),
"lastRun": optional_timestamp(totals.iter().map(|t| t.last_run).max()),
"lastSuccess": optional_timestamp(totals.iter().filter_map(|t| t.last_success).max()),
"lastFailure": optional_timestamp(totals.iter().filter_map(|t| t.last_failure).max()),
});
if name.is_some() {
row["recent"] = ledger
.recent(&workflow.name, RECENT_RUNS)?
.iter()
.map(|run| {
json!({
"executionId": run.execution_id,
"version": run.version,
"status": run.status,
"startedAt": timestamp(run.started_at),
"durationMs": run.ended_at.map(|end| end.saturating_sub(run.started_at)),
"failure": run.fingerprint,
})
})
.collect();
}
rows.push(row);
}
Ok(ok(Value::Array(rows)))
}
pub(crate) async fn failures(
&self,
name: Option<&str>,
all: bool,
) -> Result<CommandResult, String> {
let ledger = match ledger_or_error(self) {
Ok(ledger) => ledger,
Err(result) => return Ok(*result),
};
let mut last_success = BTreeMap::new();
let mut groups = Vec::new();
let mut resolved = 0;
for group in ledger.failures(name)? {
let success = match last_success.get(&group.workflow) {
Some(success) => *success,
None => {
let success = ledger
.totals(&group.workflow)?
.iter()
.filter_map(|totals| totals.last_success)
.max();
last_success.insert(group.workflow.clone(), success);
success
}
};
let active = success.is_none_or(|success| group.last_seen > success);
if !active {
resolved += 1;
if !all {
continue;
}
}
groups.push(json!({
"workflow": group.workflow,
"cause": group.fingerprint,
"active": active,
"count": group.count,
"step": group.step,
"message": group.shape,
"sample": group.sample,
"firstSeen": timestamp(group.first_seen),
"lastSeen": timestamp(group.last_seen),
"version": group.last_version,
"lastExecution": group.last_execution,
"hint": format!("workflows trace {}", group.last_execution),
}));
}
Ok(ok(json!({
"causes": groups,
"resolvedHidden": if all { 0 } else { resolved },
})))
}
pub(crate) async fn trace(&self, id: &str, full: bool) -> Result<CommandResult, String> {
let run = self
.ledger()
.and_then(|ledger| ledger.run(id).ok().flatten());
let execution = match self.service().await?.execution(id.to_string()).await {
Ok(execution) => execution,
Err(message) if is_missing(&message) => {
return Ok(match run {
Some(run) => ok(json!({
"executionId": id,
"workflow": run.workflow,
"version": run.version,
"traceId": run.trace_id,
"spanId": run.span_id,
"status": run.status,
"startedAt": timestamp(run.started_at),
"failure": run.fingerprint,
"detail": "The store no longer holds this execution; only its ledger record remains",
})),
None => error(
"EXECUTION_NOT_FOUND",
format!("No workflow execution '{id}'"),
),
});
}
Err(message) => return Err(message),
};
self.record(&execution);
Ok(ok(trace_view(&execution, run.as_ref(), full)))
}
}
fn count(findings: &[Finding], severity: Severity) -> usize {
findings
.iter()
.filter(|finding| finding.severity == severity)
.count()
}
fn trace_view(execution: &ExecutionState, run: Option<&Run>, full: bool) -> Value {
let steps: Vec<Value> = execution
.log
.iter()
.map(|entry| {
json!({
"seq": entry.seq,
"call": format!("{}.{}", entry.connector, entry.method),
"state": log_state_name(entry.state),
"needsApproval": entry.requires_approval,
"arguments": preview(&entry.arguments, full),
"result": entry.result.as_ref().map(|result| preview(result, full)),
})
})
.collect();
let failed_at = (execution.status == ExecutionStatus::Error).then(|| {
match execution
.log
.iter()
.rev()
.find(|entry| entry.state == LogEntryState::Executing)
{
Some(entry) => json!({
"seq": entry.seq,
"call": format!("{}.{}", entry.connector, entry.method),
}),
None => json!({
"call": "program",
"afterSeq": execution
.log
.iter()
.filter(|entry| entry.state == LogEntryState::Applied)
.map(|entry| entry.seq)
.max(),
}),
}
});
let console_skipped = if full {
0
} else {
execution.logs.len().saturating_sub(CONSOLE_TAIL)
};
let timeline: Vec<Value> = execution
.events
.iter()
.filter_map(|event| match event {
ExecutionEvent::Status { status, at } => Some(json!({
"status": ledger::status_name(*status),
"afterMs": at.saturating_sub(execution.created_at),
})),
_ => None,
})
.collect();
json!({
"executionId": execution.id,
"trace": execution.trace,
"workflow": run.map(|run| run.workflow.clone()),
"version": run.map(|run| run.version.clone()),
"status": ledger::status_name(execution.status),
"createdAt": timestamp(execution.created_at),
"durationMs": execution.updated_at.saturating_sub(execution.created_at),
"steps": steps,
"failedAt": failed_at,
"error": execution.error.as_deref().map(|raw| {
if full { raw.to_string() } else { ledger::readable_error(raw) }
}),
"console": execution.logs[console_skipped..],
"consoleSkipped": console_skipped,
"timeline": timeline,
})
}
fn log_state_name(state: LogEntryState) -> &'static str {
match state {
LogEntryState::Pending => "pending",
LogEntryState::Executing => "executing",
LogEntryState::Applied => "applied",
LogEntryState::Reverted => "reverted",
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_utc_timestamps() {
assert_eq!(timestamp(0), "1970-01-01T00:00:00Z");
assert_eq!(timestamp(951_782_400_000), "2000-02-29T00:00:00Z");
assert_eq!(timestamp(1_709_251_199_999), "2024-02-29T23:59:59Z");
assert_eq!(timestamp(4_102_444_800_000), "2100-01-01T00:00:00Z");
}
#[test]
fn previews_truncate_only_large_values() {
let small = json!({"a": 1});
assert_eq!(preview(&small, false), small);
let large = json!("x".repeat(400));
let shown = preview(&large, false);
let text = shown.as_str().unwrap();
assert!(text.ends_with("(242 more bytes)"), "{text}");
assert_eq!(preview(&large, true), large);
}
fn run(version: &str, status: &str) -> Run {
Run {
execution_id: format!("{version}-{status}"),
workflow: "w".into(),
version: version.into(),
started_at: 0,
ended_at: None,
status: status.into(),
fingerprint: None,
trace_id: None,
span_id: None,
}
}
#[test]
fn failure_streaks_ignore_decisions_and_other_versions() {
let runs = [
run("v2", "error"),
run("v2", "rejected"),
run("v1", "completed"),
run("v2", "error"),
run("v2", "completed"),
run("v2", "error"),
];
let (streak, latest) = failure_streak(&runs, "v2");
assert_eq!(streak, 2);
assert_eq!(latest.unwrap().execution_id, "v2-error");
assert_eq!(failure_streak(&runs, "v1").0, 0);
}
}