#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
use std::path::Path;
use std::sync::Mutex;
use crate::database::{Connection, OptionalExtension, params};
use multicast_codemode::{ExecutionState, ExecutionStatus, LogEntryState};
use sha2::{Digest, Sha256};
pub(crate) const RUNS_PER_WORKFLOW: usize = 100;
const MESSAGE_SHAPE_LIMIT: usize = 160;
const SAMPLE_LIMIT: usize = 500;
pub(crate) const LOST: &str = "lost";
pub(crate) struct RunStart<'a> {
pub execution_id: &'a str,
pub workflow: &'a str,
pub origin: &'a str,
pub version: &'a str,
pub at: u64,
}
#[derive(Debug, Clone)]
pub(crate) struct Run {
pub execution_id: String,
pub workflow: String,
pub version: String,
pub started_at: u64,
pub ended_at: Option<u64>,
pub status: String,
pub fingerprint: Option<String>,
pub trace_id: Option<String>,
pub span_id: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Totals {
pub version: String,
pub started: u64,
pub completed: u64,
pub failed: u64,
pub rejected: u64,
pub cancelled: u64,
pub rolled_back: u64,
pub lost: u64,
pub first_run: u64,
pub last_run: u64,
pub last_success: Option<u64>,
pub last_failure: Option<u64>,
}
#[derive(Debug, Clone)]
pub(crate) struct FailureGroup {
pub workflow: String,
pub fingerprint: String,
pub step: String,
pub shape: String,
pub sample: String,
pub count: u64,
pub first_seen: u64,
pub last_seen: u64,
pub last_execution: String,
pub last_version: String,
}
pub(crate) struct Ledger {
connection: Mutex<Connection>,
}
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
pub(crate) fn ledger_path(store_path: &Path) -> std::path::PathBuf {
store_path.with_extension("ledger.sqlite")
}
pub(crate) fn version(code: &str, input_schema: Option<&serde_json::Value>) -> String {
let mut hasher = Sha256::new();
hasher.update(code.trim().as_bytes());
hasher.update([0]);
if let Some(schema) = input_schema {
hasher.update(schema.to_string().as_bytes());
}
short_hex(&hasher.finalize())
}
fn short_hex(bytes: &[u8]) -> String {
bytes[..6]
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
pub(crate) fn status_name(status: ExecutionStatus) -> &'static str {
match status {
ExecutionStatus::Running => "running",
ExecutionStatus::Paused => "paused",
ExecutionStatus::Completed => "completed",
ExecutionStatus::Error => "error",
ExecutionStatus::Rejected => "rejected",
ExecutionStatus::RolledBack => "rolled_back",
ExecutionStatus::Cancelled => "cancelled",
}
}
pub(crate) fn is_terminal(status: &str) -> bool {
!matches!(status, "running" | "paused")
}
pub(crate) fn failure_signature(state: &ExecutionState) -> (String, String) {
let step = state
.log
.iter()
.rev()
.find(|entry| entry.state == LogEntryState::Executing)
.map(|entry| format!("{}.{}", entry.connector, entry.method))
.unwrap_or_else(|| "program".to_string());
let shape = message_shape(&readable_error(state.error.as_deref().unwrap_or("")));
(step, shape)
}
pub(crate) fn readable_error(raw: &str) -> String {
let Ok(serde_json::Value::Object(error)) = serde_json::from_str::<serde_json::Value>(raw)
else {
return raw.to_string();
};
let message = error.get("message").and_then(serde_json::Value::as_str);
match (
error.get("code").and_then(serde_json::Value::as_str),
message,
) {
(Some(code), Some(message)) => format!("{code}: {message}"),
(None, Some(message)) => message.to_string(),
_ => raw.to_string(),
}
}
pub(crate) fn fingerprint(step: &str, shape: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(step.as_bytes());
hasher.update([0]);
hasher.update(shape.as_bytes());
short_hex(&hasher.finalize())
}
pub(crate) fn message_shape(message: &str) -> String {
let mut unquoted = String::with_capacity(message.len());
let mut chars = message.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '"' || ch == '\'' || ch == '`' {
let rest: String = chars.clone().collect();
if let Some(end) = rest.find(ch) {
unquoted.push_str("'…'");
for _ in 0..rest[..end].chars().count() + 1 {
chars.next();
}
continue;
}
}
unquoted.push(ch);
}
let mut shape = String::with_capacity(unquoted.len());
let mut word = String::new();
let flush = |word: &mut String, shape: &mut String| {
if word.chars().any(|ch| ch.is_ascii_digit()) {
shape.push('#');
} else {
shape.push_str(word);
}
word.clear();
};
for ch in unquoted.chars() {
if ch.is_alphanumeric() || ch == '_' || ch == '-' {
word.push(ch);
} else {
flush(&mut word, &mut shape);
if ch.is_whitespace() {
if !shape.ends_with(' ') && !shape.is_empty() {
shape.push(' ');
}
} else {
shape.push(ch);
}
}
}
flush(&mut word, &mut shape);
truncate(shape.trim_end(), MESSAGE_SHAPE_LIMIT)
}
pub(crate) fn truncate(text: &str, limit: usize) -> String {
if text.chars().count() <= limit {
return text.to_string();
}
let mut cut: String = text.chars().take(limit).collect();
cut.push('…');
cut
}
fn sql(error: crate::database::Error) -> String {
format!("Workflow ledger error: {error}")
}
impl Ledger {
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
pub(crate) fn open(path: &Path) -> Result<Self, String> {
Self::from_connection(Connection::open(path).map_err(sql)?)
}
pub(crate) fn from_database(
database: std::sync::Arc<dyn crate::WorkflowDatabase>,
) -> Result<Self, String> {
Self::from_connection(Connection::new(database))
}
fn from_connection(connection: Connection) -> Result<Self, String> {
connection
.execute_batch(
"CREATE TABLE IF NOT EXISTS runs (
execution_id TEXT PRIMARY KEY,
workflow TEXT NOT NULL,
origin TEXT NOT NULL,
version TEXT NOT NULL,
started_at INTEGER NOT NULL,
ended_at INTEGER,
status TEXT NOT NULL,
fingerprint TEXT
);
CREATE INDEX IF NOT EXISTS runs_by_workflow ON runs (workflow, started_at);
CREATE TABLE IF NOT EXISTS totals (
workflow TEXT NOT NULL,
version TEXT NOT NULL,
started INTEGER NOT NULL DEFAULT 0,
completed INTEGER NOT NULL DEFAULT 0,
failed INTEGER NOT NULL DEFAULT 0,
rejected INTEGER NOT NULL DEFAULT 0,
cancelled INTEGER NOT NULL DEFAULT 0,
rolled_back INTEGER NOT NULL DEFAULT 0,
lost INTEGER NOT NULL DEFAULT 0,
first_run INTEGER NOT NULL,
last_run INTEGER NOT NULL,
last_success INTEGER,
last_failure INTEGER,
PRIMARY KEY (workflow, version)
);
CREATE TABLE IF NOT EXISTS failures (
workflow TEXT NOT NULL,
fingerprint TEXT NOT NULL,
step TEXT NOT NULL,
shape TEXT NOT NULL,
sample TEXT NOT NULL,
count INTEGER NOT NULL,
first_seen INTEGER NOT NULL,
last_seen INTEGER NOT NULL,
last_execution TEXT NOT NULL,
last_version TEXT NOT NULL,
PRIMARY KEY (workflow, fingerprint)
);",
)
.map_err(sql)?;
connection
.transaction(|tx| {
let columns: Vec<String> = tx
.prepare("PRAGMA table_info(runs)")
.map_err(sql)?
.query_map(params![], |row| row.get(1))
.map_err(sql)?
.collect::<crate::database::Result<_>>()
.map_err(sql)?;
for column in ["trace_id", "span_id"] {
if !columns.iter().any(|name| name == column) {
tx.execute(
&format!("ALTER TABLE runs ADD COLUMN {column} TEXT"),
params![],
)
.map_err(sql)?;
}
}
Ok(())
})
.map_err(sql)?;
Ok(Self {
connection: Mutex::new(connection),
})
}
fn with<T>(
&self,
work: impl FnOnce(&mut Connection) -> crate::database::Result<T>,
) -> Result<T, String> {
let mut connection = self
.connection
.lock()
.map_err(|_| "Workflow ledger lock poisoned".to_string())?;
work(&mut connection).map_err(sql)
}
pub(crate) fn start(&self, run: &RunStart<'_>) -> Result<(), String> {
self.with(|connection| {
connection.transaction(|tx| {
let inserted = tx.execute(
"INSERT OR IGNORE INTO runs (execution_id, workflow, origin, version, started_at, status)
VALUES (?1, ?2, ?3, ?4, ?5, 'running')",
params![run.execution_id, run.workflow, run.origin, run.version, run.at],
)?;
if inserted == 1 {
tx.execute(
"INSERT INTO totals (workflow, version, started, first_run, last_run)
VALUES (?1, ?2, 1, ?3, ?3)
ON CONFLICT (workflow, version)
DO UPDATE SET started = started + 1, last_run = excluded.last_run",
params![run.workflow, run.version, run.at],
)?;
}
Ok(())
})
})
}
pub(crate) fn record(&self, state: &ExecutionState, at: u64) -> Result<(), String> {
if let Some(trace) = &state.trace {
self.with(|connection| {
connection
.execute(
"UPDATE runs SET trace_id = ?2, span_id = ?3 WHERE execution_id = ?1",
params![state.id, trace.trace_id, trace.span_id],
)
.map(|_| ())
})?;
}
let status = status_name(state.status);
let failure = (state.status == ExecutionStatus::Error).then(|| {
let (step, shape) = failure_signature(state);
let sample = truncate(
&readable_error(state.error.as_deref().unwrap_or("")),
SAMPLE_LIMIT,
);
(fingerprint(&step, &shape), step, shape, sample)
});
self.transition(
&state.id,
status,
at,
failure.as_ref().map(|(fp, step, shape, sample)| {
(fp.as_str(), step.as_str(), shape.as_str(), sample.as_str())
}),
)
}
pub(crate) fn mark_lost(&self, execution_id: &str, at: u64) -> Result<(), String> {
self.transition(execution_id, LOST, at, None)
}
fn transition(
&self,
execution_id: &str,
status: &str,
at: u64,
failure: Option<(&str, &str, &str, &str)>,
) -> Result<(), String> {
self.with(|connection| {
connection.transaction(|tx| {
let current: Option<(String, String, String)> = tx
.query_row(
"SELECT status, workflow, version FROM runs WHERE execution_id = ?1",
params![execution_id],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
)
.optional()?;
let Some((previous, workflow, version)) = current else {
return Ok(());
};
if is_terminal(&previous) || previous == status {
return Ok(());
}
let terminal = is_terminal(status);
tx.execute(
"UPDATE runs SET status = ?2, ended_at = ?3, fingerprint = ?4 WHERE execution_id = ?1",
params![
execution_id,
status,
terminal.then_some(at),
failure.map(|(fp, ..)| fp)
],
)?;
if terminal {
let column = match status {
"completed" => "completed",
"error" => "failed",
"rejected" => "rejected",
"cancelled" => "cancelled",
"rolled_back" => "rolled_back",
_ => "lost",
};
let marker = match status {
"completed" => ", last_success = ?3",
"error" => ", last_failure = ?3",
_ => "",
};
let update = format!(
"UPDATE totals SET {column} = {column} + 1{marker}
WHERE workflow = ?1 AND version = ?2"
);
if marker.is_empty() {
tx.execute(&update, params![workflow, version])?;
} else {
tx.execute(&update, params![workflow, version, at])?;
}
if let Some((fp, step, shape, sample)) = failure {
tx.execute(
"INSERT INTO failures (workflow, fingerprint, step, shape, sample, count,
first_seen, last_seen, last_execution, last_version)
VALUES (?1, ?2, ?3, ?4, ?5, 1, ?6, ?6, ?7, ?8)
ON CONFLICT (workflow, fingerprint) DO UPDATE SET
count = count + 1, sample = excluded.sample,
last_seen = excluded.last_seen,
last_execution = excluded.last_execution,
last_version = excluded.last_version",
params![workflow, fp, step, shape, sample, at, execution_id, version],
)?;
}
tx.execute(
"DELETE FROM runs WHERE workflow = ?1 AND status NOT IN ('running', 'paused')
AND execution_id NOT IN (
SELECT execution_id FROM runs
WHERE workflow = ?1 AND status NOT IN ('running', 'paused')
ORDER BY started_at DESC, rowid DESC LIMIT ?2)",
params![workflow, RUNS_PER_WORKFLOW as i64],
)?;
}
Ok(())
})
})
}
pub(crate) fn run(&self, execution_id: &str) -> Result<Option<Run>, String> {
self.with(|connection| {
connection
.query_row(
&format!("{RUN_COLUMNS} WHERE execution_id = ?1"),
params![execution_id],
run_row,
)
.optional()
})
}
pub(crate) fn unfinished(&self) -> Result<Vec<Run>, String> {
self.with(|connection| {
let statement = connection.prepare(&format!(
"{RUN_COLUMNS} WHERE status IN ('running', 'paused') ORDER BY started_at, rowid"
))?;
statement.query_map(params![], run_row)?.collect()
})
}
pub(crate) fn recent(&self, workflow: &str, limit: usize) -> Result<Vec<Run>, String> {
self.with(|connection| {
let statement = connection.prepare(&format!(
"{RUN_COLUMNS} WHERE workflow = ?1 ORDER BY started_at DESC, rowid DESC LIMIT ?2"
))?;
statement
.query_map(params![workflow, limit as i64], run_row)?
.collect()
})
}
pub(crate) fn totals(&self, workflow: &str) -> Result<Vec<Totals>, String> {
self.with(|connection| {
let statement = connection.prepare(
"SELECT version, started, completed, failed, rejected, cancelled, rolled_back,
lost, first_run, last_run, last_success, last_failure
FROM totals WHERE workflow = ?1 ORDER BY last_run DESC",
)?;
statement
.query_map(params![workflow], |row| {
Ok(Totals {
version: row.get(0)?,
started: row.get(1)?,
completed: row.get(2)?,
failed: row.get(3)?,
rejected: row.get(4)?,
cancelled: row.get(5)?,
rolled_back: row.get(6)?,
lost: row.get(7)?,
first_run: row.get(8)?,
last_run: row.get(9)?,
last_success: row.get(10)?,
last_failure: row.get(11)?,
})
})?
.collect()
})
}
pub(crate) fn failures(&self, workflow: Option<&str>) -> Result<Vec<FailureGroup>, String> {
self.with(|connection| {
let statement = connection.prepare(
"SELECT workflow, fingerprint, step, shape, sample, count, first_seen, last_seen,
last_execution, last_version
FROM failures WHERE ?1 IS NULL OR workflow = ?1
ORDER BY last_seen DESC, workflow, fingerprint",
)?;
statement
.query_map(params![workflow], |row| {
Ok(FailureGroup {
workflow: row.get(0)?,
fingerprint: row.get(1)?,
step: row.get(2)?,
shape: row.get(3)?,
sample: row.get(4)?,
count: row.get(5)?,
first_seen: row.get(6)?,
last_seen: row.get(7)?,
last_execution: row.get(8)?,
last_version: row.get(9)?,
})
})?
.collect()
})
}
pub(crate) fn forget(&self, workflow: &str) -> Result<(), String> {
self.with(|connection| {
connection.transaction(|tx| {
for table in ["runs", "totals", "failures"] {
tx.execute(
&format!("DELETE FROM {table} WHERE workflow = ?1"),
params![workflow],
)?;
}
Ok(())
})
})
}
}
const RUN_COLUMNS: &str = "SELECT execution_id, workflow, version, started_at, ended_at, status, fingerprint, trace_id, span_id FROM runs";
fn run_row(row: &crate::database::Row) -> crate::database::Result<Run> {
Ok(Run {
execution_id: row.get(0)?,
workflow: row.get(1)?,
version: row.get(2)?,
started_at: row.get(3)?,
ended_at: row.get(4)?,
status: row.get(5)?,
fingerprint: row.get(6)?,
trace_id: row.get(7)?,
span_id: row.get(8)?,
})
}
#[cfg(all(test, feature = "native", not(target_arch = "wasm32")))]
mod tests {
use super::*;
#[tokio::test]
async fn trace_links_survive_old_ledger_migration_and_reopening() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("ledger.sqlite");
let old = Connection::open(&path).unwrap();
old.execute_batch(
"CREATE TABLE runs (
execution_id TEXT PRIMARY KEY, workflow TEXT NOT NULL, origin TEXT NOT NULL,
version TEXT NOT NULL, started_at INTEGER NOT NULL, ended_at INTEGER,
status TEXT NOT NULL, fingerprint TEXT);
INSERT INTO runs VALUES ('legacy', 'w', 'shipped', 'v1', 1, NULL, 'running', NULL);",
)
.unwrap();
drop(old);
let ledger = Ledger::open(&path).unwrap();
assert!(ledger.run("legacy").unwrap().unwrap().trace_id.is_none());
let runtime = multicast_codemode::CodeModeRuntime::new(std::sync::Arc::new(
multicast_codemode::MemoryStore::default(),
));
let id = runtime.begin("return 1", vec![], 1).await.unwrap();
let mut state = runtime.execution(&id).await.unwrap().unwrap();
state.id = "legacy".into();
state.trace = Some(multicast_codemode::ExecutionTrace {
trace_id: "4bf92f3577b34da6a3ce929d0e0e4736".into(),
span_id: "00f067aa0ba902b7".into(),
trace_flags: 1,
workflow: None,
});
ledger.record(&state, 2).unwrap();
drop(ledger);
let ledger = Ledger::open(&path).unwrap();
let run = ledger.run("legacy").unwrap().unwrap();
assert_eq!(
run.trace_id.as_deref(),
Some("4bf92f3577b34da6a3ce929d0e0e4736")
);
assert_eq!(run.span_id.as_deref(), Some("00f067aa0ba902b7"));
assert_eq!(run.status, "running");
}
#[test]
fn message_shapes_ignore_values_but_keep_wording() {
assert_eq!(
message_shape("Cannot divide 17 by zero in 'job-42' (exec_9f3a)"),
"Cannot divide # by zero in '…' (#)"
);
assert_eq!(
message_shape("Cannot divide 3 by zero in \"x\" (exec_00)"),
message_shape("Cannot divide 17 by zero in 'job-42' (exec_9f3a)")
);
assert_ne!(
message_shape("Cannot divide 3 by zero"),
message_shape("Cannot multiply 3 by zero")
);
}
#[test]
fn structured_command_errors_shape_by_code_and_message() {
let raw = |n: u32| {
format!(
"{{\"code\":\"DIVISION_BY_ZERO\",\"message\":\"Cannot divide {n} by zero\",\"retryable\":null}}"
)
};
assert_eq!(
readable_error(&raw(5)),
"DIVISION_BY_ZERO: Cannot divide 5 by zero"
);
assert_eq!(
message_shape(&readable_error(&raw(5))),
"DIVISION_BY_ZERO: Cannot divide # by zero"
);
assert_ne!(
message_shape(&readable_error(&raw(5))),
message_shape(&readable_error(
"{\"code\":\"OVERFLOW\",\"message\":\"Cannot divide 5 by zero\"}"
))
);
assert_eq!(readable_error("plain text"), "plain text");
}
#[test]
fn terminal_outcomes_count_once() {
let dir = tempfile::tempdir().unwrap();
let ledger = Ledger::open(&dir.path().join("ledger.sqlite")).unwrap();
ledger
.start(&RunStart {
execution_id: "e1",
workflow: "w",
origin: "shipped",
version: "v1",
at: 10,
})
.unwrap();
ledger.transition("e1", "paused", 11, None).unwrap();
ledger.transition("e1", "completed", 12, None).unwrap();
ledger.transition("e1", "completed", 13, None).unwrap();
ledger.transition("e1", "error", 14, None).unwrap();
let totals = ledger.totals("w").unwrap();
assert_eq!(totals.len(), 1);
assert_eq!(
(totals[0].started, totals[0].completed, totals[0].failed),
(1, 1, 0)
);
assert_eq!(totals[0].last_success, Some(12));
assert_eq!(ledger.run("e1").unwrap().unwrap().ended_at, Some(12));
}
#[test]
fn every_terminal_outcome_updates_its_total() {
let dir = tempfile::tempdir().unwrap();
let ledger = Ledger::open(&dir.path().join("ledger.sqlite")).unwrap();
let outcomes = [
("e1", "completed"),
("e2", "error"),
("e3", "rejected"),
("e4", "cancelled"),
("e5", "rolled_back"),
("e6", LOST),
];
for (index, (id, status)) in outcomes.iter().enumerate() {
let at = 10 + index as u64;
ledger
.start(&RunStart {
execution_id: id,
workflow: "w",
origin: "saved",
version: "v",
at,
})
.unwrap();
ledger.transition(id, status, at, None).unwrap();
}
let totals = ledger.totals("w").unwrap();
let t = &totals[0];
assert_eq!(
(
t.started,
t.completed,
t.failed,
t.rejected,
t.cancelled,
t.rolled_back,
t.lost
),
(6, 1, 1, 1, 1, 1, 1)
);
assert_eq!((t.last_success, t.last_failure), (Some(10), Some(11)));
}
#[test]
fn history_keeps_unfinished_runs_and_bounds_finished_ones() {
let dir = tempfile::tempdir().unwrap();
let ledger = Ledger::open(&dir.path().join("ledger.sqlite")).unwrap();
let start = |id: &str, at: u64| {
ledger
.start(&RunStart {
execution_id: id,
workflow: "w",
origin: "saved",
version: "v",
at,
})
.unwrap()
};
start("paused", 0);
ledger.transition("paused", "paused", 0, None).unwrap();
let finished = RUNS_PER_WORKFLOW as u64 + 5;
for index in 1..=finished {
let id = format!("e{index}");
start(&id, index);
ledger
.transition(&id, "error", index, Some(("fp", "program", "boom", "boom")))
.unwrap();
}
let recent = ledger.recent("w", 1000).unwrap();
assert_eq!(recent.len(), RUNS_PER_WORKFLOW + 1);
assert!(recent.iter().any(|run| run.execution_id == "paused"));
assert!(recent.iter().all(|run| run.execution_id != "e1"));
let totals = ledger.totals("w").unwrap();
assert_eq!(totals[0].failed, finished);
let failures = ledger.failures(Some("w")).unwrap();
assert_eq!(failures.len(), 1);
assert_eq!(failures[0].count, finished);
assert_eq!(failures[0].first_seen, 1);
assert_eq!(failures[0].last_seen, finished);
}
}