multicast-workflows 2.0.0

Durable Code Mode workflows attached to multicast CLIs as first-party commands
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
//! Durable per-workflow run ledger.
//!
//! The Code Mode store keeps executions but prunes terminal history and does
//! not record which workflow or which program version an execution ran. The
//! ledger keeps that link in a separate SQLite database beside the store:
//!
//! - `runs` holds recent runs per workflow, tagged with the program version.
//!   Terminal runs beyond [`RUNS_PER_WORKFLOW`] are pruned; unfinished runs are
//!   never pruned.
//! - `totals` holds counters per workflow and version. They are never pruned.
//! - `failures` groups failed runs by fingerprint, so a thousand runs failing
//!   for one reason are one row with a count.
//!
//! Terminal outcomes are counted once: recording an execution that the ledger
//! already holds as terminal changes nothing.

#[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};

/// Terminal runs retained per workflow in the run history.
pub(crate) const RUNS_PER_WORKFLOW: usize = 100;

/// Longest normalized failure message retained.
const MESSAGE_SHAPE_LIMIT: usize = 160;

/// Longest sample failure message retained.
const SAMPLE_LIMIT: usize = 500;

/// Ledger status of a run whose execution left the Code Mode store unfinished.
pub(crate) const LOST: &str = "lost";

/// Identifies a workflow run at the moment it starts.
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,
}

/// One recorded run.
#[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>,
}

/// Counters for one workflow version.
#[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>,
}

/// One group of failures that share a cause.
#[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,
}

/// Run ledger stored beside the workflow store.
pub(crate) struct Ledger {
    connection: Mutex<Connection>,
}

/// Returns the ledger location for a workflow store.
#[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")
}

/// Returns a short stable digest of a workflow's program and input schema.
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()
}

/// Ledger name of an execution status.
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",
    }
}

/// Whether a ledger status is final.
pub(crate) fn is_terminal(status: &str) -> bool {
    !matches!(status, "running" | "paused")
}

/// Where a failed execution stopped and the shape of its error.
///
/// The step is the call that was executing when the run failed, or
/// `program` when every call had finished and the program itself threw.
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)
}

/// The human-readable part of an execution error.
///
/// A failed command reports a structured error object; its code and message
/// are what a maintainer reads, and the remaining fields are noise. Any other
/// error text is returned unchanged.
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(),
    }
}

/// Fingerprint of a failure: its step and its message shape.
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())
}

/// Reduces an error message to the part that stays the same across runs.
///
/// Quoted text of any quote style becomes `'…'`, and any word containing a digit (numbers,
/// identifiers, timestamps) becomes `#`. Whitespace is collapsed.
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)
}

/// Truncates text to a character count, marking the cut.
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 {
    /// Opens or creates the 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)
    }

    /// Records a run that has just started.
    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(())
            })
        })
    }

    /// Records the current state of an execution the ledger tracks.
    ///
    /// Untracked executions (ad hoc programs) are ignored. A terminal outcome
    /// is counted only on the transition into it.
    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())
            }),
        )
    }

    /// Marks an unfinished run whose execution is no longer in the store.
    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(())
            })
        })
    }

    /// Returns one run by execution identifier.
    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()
        })
    }

    /// Returns unfinished runs, oldest first.
    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()
        })
    }

    /// Returns a workflow's most recent runs, newest first.
    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()
        })
    }

    /// Returns a workflow's counters for every version it has run.
    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()
        })
    }

    /// Returns failure groups, most recently seen first.
    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()
        })
    }

    /// Removes every record of a workflow.
    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,
        });
        // Recording the same running status must still save its correlation.
        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);
    }
}