Skip to main content

agentmux_srv/sagas/
recovery.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Saga durability — resume-on-startup (PR 2).
5//
6// See `docs/specs/SPEC_SAGA_DURABILITY_2026-05-01.md` §4 (resume-on-
7// startup). Called from `main.rs` after the saga log is opened and
8// `saga_id_alloc` is seeded, but BEFORE the API server begins
9// accepting requests so resumed compensation can't interleave with
10// new sagas.
11//
12// **Algorithm.** For each saga the durable log says is unresolved
13// (state `running` / `compensating` / `failed`):
14//   1. Mark its lifecycle row `compensating` so a second crash mid-
15//      recovery isn't confused with a fresh partial-apply.
16//   2. Walk the saga's `succeeded` step rows in REVERSE `step_index`
17//      order. (Failed steps have nothing to compensate — their
18//      effects didn't apply.)
19//   3. For each succeeded step, derive the inverse `Command` via
20//      `derive_inverse_command`. If derivable, dispatch it through
21//      the reducer + apply emitted events to mstore. If NOT derivable,
22//      log a warning + skip — operator review needed.
23//   4. After the walk: `terminate(Compensated)` if every dispatched
24//      inverse succeeded; `mark_failed_compensation` otherwise. The
25//      saga's lifecycle reflects the recovery outcome for the next
26//      `--diag sagas` query.
27//
28// **Limitation: not every forward command has a derivable inverse.**
29// Recovery encodes only the inverses we can construct purely from the
30// recorded `cmd_json` + a small piece of state (e.g. the new id
31// emitted by `Create*`). For commands whose compensation requires
32// information the saga didn't persist (e.g. `MoveTab` lacks the
33// original src index, so a strict round-trip needs the saga's
34// pre-state), we log "skipped — no inverse derivable" and proceed.
35// In practice this is fine because:
36//   * `tear_off_tab`, `tear_off_block`, `restore_torn_off_tab`,
37//     `delete_block`, `delete_tab`, `promote_block_to_tab` either
38//     drive their own compensation in their inner future before
39//     returning Err (the normal path), or end up in `failed` with
40//     specific recoverable shapes encoded below.
41//   * Any saga the recovery layer can't fully unwind ends in
42//     `failed_compensation`, which `--diag sagas` flags for operator
43//     attention.
44
45use agentmux_common::ipc::{Command, Event};
46
47use crate::sagas::log::{command_discriminant_name, SagaOutcome, UnresolvedSaga, UnresolvedStep};
48use crate::server::AppState;
49
50/// Resume any unresolved sagas left over from a prior srv-process run.
51/// Returns the number of sagas the recovery layer touched (compensated
52/// or marked `failed_compensation`).
53///
54/// Logged at INFO; non-fatal if the saga log read fails (caller logs
55/// and continues — the alternative is refusing to start the server,
56/// which leaves users locked out for a transient SQLite hiccup).
57pub async fn compensate_unresolved(state: &AppState) -> Result<usize, String> {
58    let unresolved = state
59        .saga_log
60        .unresolved_sagas()
61        .map_err(|e| format!("read unresolved sagas: {}", e))?;
62
63    if unresolved.is_empty() {
64        return Ok(0);
65    }
66
67    tracing::info!(
68        "[saga] resume-on-startup: found {} unresolved saga(s) from prior run",
69        unresolved.len()
70    );
71
72    let mut resumed = 0usize;
73    for saga in &unresolved {
74        match recover_saga(state, saga).await {
75            Ok(()) => {
76                resumed += 1;
77                tracing::info!(
78                    saga_id = saga.saga_id,
79                    name = %saga.name,
80                    "[saga] resume-on-startup compensated saga"
81                );
82            }
83            Err(e) => {
84                tracing::error!(
85                    saga_id = saga.saga_id,
86                    name = %saga.name,
87                    "[saga] resume-on-startup failed to compensate: {} — saga marked failed_compensation",
88                    e
89                );
90                if let Err(log_err) = state
91                    .saga_log
92                    .mark_failed_compensation(saga.saga_id, &e)
93                {
94                    tracing::warn!(
95                        saga_id = saga.saga_id,
96                        "[saga] mark_failed_compensation log write failed: {}",
97                        log_err
98                    );
99                }
100                // Counted as resumed (touched) because we did write a
101                // terminal lifecycle row — distinguishes "saw unresolved
102                // and acted" from "saw unresolved and ignored".
103                resumed += 1;
104            }
105        }
106    }
107
108    Ok(resumed)
109}
110
111/// Compensate a single unresolved saga. Walks succeeded steps in
112/// reverse, dispatches the inverse of each through the reducer, and
113/// marks the saga `compensated` on success.
114async fn recover_saga(state: &AppState, saga: &UnresolvedSaga) -> Result<(), String> {
115    // Mark the lifecycle row `compensating` first so a second crash
116    // during recovery doesn't trip the next restart's recovery into
117    // double-compensating.
118    state
119        .saga_log
120        .mark_compensating(saga.saga_id)
121        .map_err(|e| format!("mark compensating: {}", e))?;
122
123    // Allocate fresh step indices ABOVE the saga's existing max so
124    // recovery rows don't overwrite original-step provenance.
125    let mut next_idx = state
126        .saga_log
127        .next_step_index(saga.saga_id)
128        .map_err(|e| format!("next_step_index: {}", e))?;
129
130    reject_pending_steps(saga)?;
131
132    let succeeded_steps: Vec<&UnresolvedStep> = saga
133        .steps
134        .iter()
135        .rev()
136        .filter(|s| s.state == "succeeded")
137        .collect();
138    if succeeded_steps.is_empty() {
139        return terminate_with_nothing_to_undo(state, saga);
140    }
141
142    let mut errors: Vec<String> = Vec::new();
143    for step in succeeded_steps {
144        if let Err(msg) = compensate_step(state, saga, step, &mut next_idx).await {
145            errors.push(msg);
146        }
147    }
148    finish_recovery(state, saga, errors)
149}
150
151/// A pending step started but never reached succeeded, failed or
152/// compensated: usually a crash between dispatch and `finish_step`,
153/// after the reducer and the mstore apply already committed. Such a
154/// saga cannot safely be marked `compensated`, because side effects
155/// may still be applied; it goes to `failed_compensation` for operator
156/// review, with the pending step and forward state left in the log.
157fn reject_pending_steps(saga: &UnresolvedSaga) -> Result<(), String> {
158    let pending = saga.steps.iter().filter(|s| s.state == "pending").count();
159    if pending == 0 {
160        return Ok(());
161    }
162    Err(format!(
163        "saga has {} pending step(s) (crashed mid-dispatch); cannot auto-recover — operator review needed",
164        pending
165    ))
166}
167
168/// No forward state to undo and no pending steps: the saga reached
169/// `start_saga` but either crashed before any step succeeded, or every
170/// step failed cleanly. Mark it `compensated` to clear it from the
171/// unresolved set.
172fn terminate_with_nothing_to_undo(state: &AppState, saga: &UnresolvedSaga) -> Result<(), String> {
173    let reason = format!(
174        "no succeeded steps to compensate (saga state at restart: {})",
175        saga.state
176    );
177    state
178        .saga_log
179        .terminate(saga.saga_id, SagaOutcome::Compensated { reason })
180        .map_err(|e| format!("terminate(Compensated, no-op): {}", e))
181}
182
183/// The saga's last row: `compensated` when every inverse worked, an
184/// error (which the caller records as `failed_compensation`) otherwise.
185fn finish_recovery(state: &AppState, saga: &UnresolvedSaga, errors: Vec<String>) -> Result<(), String> {
186    if !errors.is_empty() {
187        return Err(errors.join("; "));
188    }
189    state
190        .saga_log
191        .terminate(
192            saga.saga_id,
193            SagaOutcome::Compensated {
194                reason: format!("resumed on srv restart (was {} at startup)", saga.state),
195            },
196        )
197        .map_err(|e| format!("terminate(Compensated): {}", e))
198}
199
200/// Undo one succeeded forward step. `next_idx` is the index for the
201/// recovery row this step writes; it moves on whenever a row was
202/// attempted, and stays put for a step whose command cannot be read.
203async fn compensate_step(
204    state: &AppState,
205    saga: &UnresolvedSaga,
206    step: &UnresolvedStep,
207    next_idx: &mut u32,
208) -> Result<(), String> {
209    let forward_cmd: Command = match serde_json::from_str(&step.cmd_json) {
210        Ok(c) => c,
211        Err(e) => {
212            let msg = format!(
213                "step {} cmd_json deserialization failed: {} — skipping",
214                step.step_index, e
215            );
216            tracing::warn!(saga_id = saga.saga_id, "[saga] {}", msg);
217            return Err(msg);
218        }
219    };
220    let Some(inverse) = derive_inverse_command(&forward_cmd, step) else {
221        let result = record_no_inverse(state, saga, step, &forward_cmd, *next_idx);
222        *next_idx += 1;
223        return result;
224    };
225    let inv_name = command_discriminant_name(&inverse);
226    let result = match dispatch_inverse(state, inverse.clone()).await {
227        Ok(events) => {
228            record_inverse_applied(state, saga, step, *next_idx, &inv_name, &inverse, &events);
229            Ok(())
230        }
231        Err(e) => {
232            tracing::warn!(
233                saga_id = saga.saga_id,
234                step_index = *next_idx,
235                "[saga] recovery dispatch of inverse '{}' failed: {}",
236                inv_name,
237                e
238            );
239            append_recovery_row(state, saga.saga_id, *next_idx, "failure", &inv_name, &inverse, &[], Some(&e));
240            Err(format!("step {}: {}", step.step_index, e))
241        }
242    };
243    *next_idx += 1;
244    result
245}
246
247/// A succeeded forward step with no derivable inverse is a failure to
248/// compensate, not a no-op: the side effect remains on disk while the
249/// saga lifecycle would otherwise be marked `compensated`, hiding
250/// unresolved state from operators (and from `--diag sagas`, which
251/// keys on terminal state). Log a recovery row with state `failed`
252/// for visibility and return the error so the saga ends in
253/// `failed_compensation`.
254fn record_no_inverse(
255    state: &AppState,
256    saga: &UnresolvedSaga,
257    step: &UnresolvedStep,
258    forward_cmd: &Command,
259    next_idx: u32,
260) -> Result<(), String> {
261    let msg = format!(
262        "step {} ({}): no inverse derivable from saga log — operator review needed",
263        step.step_index, step.name,
264    );
265    tracing::error!(
266        saga_id = saga.saga_id,
267        step_index = step.step_index,
268        forward = %step.name,
269        "[saga] {}",
270        msg,
271    );
272    append_recovery_row(
273        state,
274        saga.saga_id,
275        next_idx,
276        "no-inverse",
277        &format!("no_inverse_for_{}", step.name),
278        forward_cmd,
279        &[],
280        Some("no inverse derivable from saga log"),
281    );
282    Err(msg)
283}
284
285/// The inverse ran: record it, then mark the ORIGINAL forward step
286/// compensated so a second crash-recovery startup doesn't re-replay
287/// its inverse. Idempotent: the UPDATE only fires on rows currently
288/// in `succeeded` state.
289fn record_inverse_applied(
290    state: &AppState,
291    saga: &UnresolvedSaga,
292    step: &UnresolvedStep,
293    next_idx: u32,
294    inv_name: &str,
295    inverse: &Command,
296    events: &[Event],
297) {
298    append_recovery_row(state, saga.saga_id, next_idx, "success", inv_name, inverse, events, None);
299    if let Err(e) = state.saga_log.mark_step_compensated(saga.saga_id, step.step_index) {
300        tracing::warn!(
301            saga_id = saga.saga_id,
302            step_index = step.step_index,
303            "[saga] mark_step_compensated log write failed: {} — second restart may re-replay this inverse",
304            e
305        );
306    }
307}
308
309/// Write one recovery row; a failed write is logged and recovery goes on.
310fn append_recovery_row(
311    state: &AppState,
312    saga_id: u64,
313    step_index: u32,
314    label: &str,
315    name: &str,
316    cmd: &Command,
317    events: &[Event],
318    error: Option<&str>,
319) {
320    if let Err(e) = state
321        .saga_log
322        .append_recovery_step(saga_id, step_index, name, cmd, events, error)
323    {
324        tracing::warn!(
325            saga_id,
326            step_index,
327            "[saga] append_recovery_step ({}) log write failed: {}",
328            label,
329            e
330        );
331    }
332}
333
334/// Dispatch a recovery-time compensating command + apply its events
335/// to mstore. Mirrors `SagaCtx::compensate` but standalone (no live
336/// saga to attach to). Returns the emitted events on success, the
337/// reducer's error message on rejection.
338async fn dispatch_inverse(state: &AppState, cmd: Command) -> Result<Vec<Event>, String> {
339    let events = crate::server::service::dispatch_to_reducer(state, cmd).await;
340    if let Some(message) = events.iter().find_map(|e| match e {
341        Event::Error { message, .. } => Some(message.clone()),
342        _ => None,
343    }) {
344        return Err(message);
345    }
346    for ev in &events {
347        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore) {
348            return Err(format!("mstore apply failed: {}", e));
349        }
350    }
351    crate::server::service::publish_events(state, &events);
352    Ok(events)
353}
354
355/// Map a forward `Command` to its compensating inverse, given the
356/// recorded step row (which carries the forward command's emitted
357/// events in `output_json`, useful for `Create*` → extract-new-id →
358/// `Delete*`).
359///
360/// Returns `None` for commands whose inverse cannot be derived from
361/// the saga log alone (caller logs + skips). Documented limitations:
362///
363/// * `MoveTab` and `MoveBlock`: we don't know the source's `dst_index`
364///   the tab/block was originally at, so we can't perfectly restore
365///   the prior order. We construct a swap that at least returns the
366///   tab/block to its source — index 0. This is incorrect for
367///   re-ordering inverses but acceptable for the common tear-off
368///   case (where the source workspace's order is not the saga's
369///   concern; the saga only cares the tab is back in `src`).
370/// * Any `Delete*`: not invertible — un-deleting requires
371///   reconstructing the deleted entity's full state, which is
372///   gone from the saga log by definition.
373/// * `Update*Meta`, `Rename*`, `SetActiveTab`, etc: pure-state
374///   patches whose inverse needs the prior value. The saga log
375///   doesn't capture pre-state today (deferred to a future spec
376///   bump).
377pub fn derive_inverse_command(forward: &Command, step: &UnresolvedStep) -> Option<Command> {
378    match forward {
379        // Create* → Delete* using the new id from the forward step's
380        // emitted events.
381        Command::CreateWorkspace { .. } => {
382            let new_id = extract_workspace_id_from_output(step)?;
383            Some(Command::DeleteWorkspace {
384                workspace_id: new_id,
385                // `force: false` — recovery-time inverse of a
386                // CreateWorkspace, not driven by the `delete_workspace`
387                // saga itself (Step 5 PR 2).
388                force: false,
389            })
390        }
391        Command::CreateTab { workspace_id, .. } => {
392            let new_id = extract_tab_id_from_output(step)?;
393            Some(Command::DeleteTab {
394                workspace_id: workspace_id.clone(),
395                tab_id: new_id,
396                // Compensating delete must bypass the reducer's
397                // last-tab guard (workspace might be down to one
398                // tab now after partial saga apply).
399                force: true,
400            })
401        }
402        Command::CreateBlock { tab_id, .. } => {
403            let new_id = extract_block_id_from_output(step)?;
404            Some(Command::DeleteBlock {
405                tab_id: tab_id.clone(),
406                block_id: new_id,
407            })
408        }
409        // Move* → swap src/dst. Index goes to 0 (see fn docstring).
410        Command::MoveTab {
411            tab_id,
412            src_workspace_id,
413            dst_workspace_id,
414            ..
415        } => Some(Command::MoveTab {
416            tab_id: tab_id.clone(),
417            src_workspace_id: dst_workspace_id.clone(),
418            dst_workspace_id: src_workspace_id.clone(),
419            dst_index: 0,
420            // Undoing a tear-off drains the workspace the saga created.
421            allow_empty_source: true,
422        }),
423        Command::MoveBlock {
424            block_id,
425            src_tab_id,
426            dst_tab_id,
427            ..
428        } => Some(Command::MoveBlock {
429            block_id: block_id.clone(),
430            src_tab_id: dst_tab_id.clone(),
431            dst_tab_id: src_tab_id.clone(),
432            dst_index: 0,
433        }),
434        // CreateWindow's inverse is CloseWindowInternal — the
435        // saga's recorded `cmd_json` carries the window_id directly,
436        // so the inverse is derivable.
437        Command::CreateWindow { window_id, .. } => Some(Command::CloseWindowInternal {
438            window_id: window_id.clone(),
439        }),
440        // CloseWindowInternal / SwitchWorkspace / DeleteX / RenameX /
441        // UpdateXMeta / SetActiveTab: not invertible from the saga
442        // log alone. CloseWindowInternal's inverse would require
443        // reconstructing the window's prior workspace + state;
444        // SwitchWorkspace's inverse needs the prior workspace_id
445        // which we don't capture; DeleteX is destructive; the meta
446        // / rename / set-active commands need a snapshot of the
447        // prior value. These end up logged with "skipped — no
448        // inverse derivable" during recovery.
449        _ => None,
450    }
451}
452
453/// Pull the first `WorkspaceCreated.workspace_id` from a step's
454/// emitted events. Used to derive `CreateWorkspace`'s inverse.
455fn extract_workspace_id_from_output(step: &UnresolvedStep) -> Option<String> {
456    let output = step.output_json.as_ref()?;
457    let events: Vec<Event> = serde_json::from_str(output).ok()?;
458    events.iter().find_map(|e| match e {
459        Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
460        _ => None,
461    })
462}
463
464fn extract_tab_id_from_output(step: &UnresolvedStep) -> Option<String> {
465    let output = step.output_json.as_ref()?;
466    let events: Vec<Event> = serde_json::from_str(output).ok()?;
467    events.iter().find_map(|e| match e {
468        Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
469        _ => None,
470    })
471}
472
473fn extract_block_id_from_output(step: &UnresolvedStep) -> Option<String> {
474    let output = step.output_json.as_ref()?;
475    let events: Vec<Event> = serde_json::from_str(output).ok()?;
476    events.iter().find_map(|e| match e {
477        Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
478        _ => None,
479    })
480}
481
482#[cfg(test)]
483mod tests {
484    use super::*;
485    use crate::sagas::log::SagaLog;
486
487    fn dummy_step(state: &str, cmd_json: &str, output_json: Option<&str>) -> UnresolvedStep {
488        UnresolvedStep {
489            step_index: 0,
490            name: "test".into(),
491            state: state.to_string(),
492            cmd_json: cmd_json.to_string(),
493            output_json: output_json.map(str::to_string),
494            started_at: 0,
495            ended_at: None,
496        }
497    }
498
499    // --- Inverse-command mapping tests ---
500
501    #[test]
502    fn create_workspace_inverse_is_delete_workspace_with_new_id() {
503        let cmd = Command::CreateWorkspace { name: "test".into() };
504        let output = serde_json::to_string(&vec![Event::WorkspaceCreated {
505            workspace_id: "ws-1".into(),
506            name: "test".into(),
507            version: 1,
508        }])
509        .unwrap();
510        let step = dummy_step("succeeded", "{}", Some(&output));
511        let inv = derive_inverse_command(&cmd, &step).expect("should derive");
512        match inv {
513            Command::DeleteWorkspace { workspace_id, force } => {
514                assert_eq!(workspace_id, "ws-1");
515                assert!(!force, "recovery-time inverse should not be saga-flagged");
516            }
517            other => panic!("expected DeleteWorkspace, got {:?}", other),
518        }
519    }
520
521    #[test]
522    fn create_workspace_without_output_returns_none() {
523        let cmd = Command::CreateWorkspace { name: "test".into() };
524        let step = dummy_step("succeeded", "{}", None);
525        assert!(derive_inverse_command(&cmd, &step).is_none());
526    }
527
528    #[test]
529    fn create_tab_inverse_is_delete_tab_force_true() {
530        let cmd = Command::CreateTab {
531            workspace_id: "ws-1".into(),
532            name: "tab".into(),
533        };
534        let output = serde_json::to_string(&vec![Event::TabCreated {
535            workspace_id: "ws-1".into(),
536            tab_id: "tab-1".into(),
537            name: "tab".into(),
538            version: 1,
539        }])
540        .unwrap();
541        let step = dummy_step("succeeded", "{}", Some(&output));
542        let inv = derive_inverse_command(&cmd, &step).expect("should derive");
543        match inv {
544            Command::DeleteTab {
545                workspace_id,
546                tab_id,
547                force,
548            } => {
549                assert_eq!(workspace_id, "ws-1");
550                assert_eq!(tab_id, "tab-1");
551                assert!(force, "compensating DeleteTab must bypass last-tab guard");
552            }
553            other => panic!("expected DeleteTab, got {:?}", other),
554        }
555    }
556
557    #[test]
558    fn create_block_inverse_is_delete_block() {
559        let cmd = Command::CreateBlock {
560            tab_id: "tab-1".into(),
561            meta: serde_json::Value::Null,
562        };
563        let output = serde_json::to_string(&vec![Event::BlockCreated {
564            tab_id: "tab-1".into(),
565            block_id: "blk-1".into(),
566            meta: serde_json::Value::Null,
567            version: 1,
568        }])
569        .unwrap();
570        let step = dummy_step("succeeded", "{}", Some(&output));
571        let inv = derive_inverse_command(&cmd, &step).expect("should derive");
572        match inv {
573            Command::DeleteBlock { tab_id, block_id } => {
574                assert_eq!(tab_id, "tab-1");
575                assert_eq!(block_id, "blk-1");
576            }
577            other => panic!("expected DeleteBlock, got {:?}", other),
578        }
579    }
580
581    #[test]
582    fn move_tab_inverse_swaps_src_and_dst() {
583        let cmd = Command::MoveTab {
584            tab_id: "tab-1".into(),
585            src_workspace_id: "ws-src".into(),
586            dst_workspace_id: "ws-dst".into(),
587            dst_index: 5,
588            allow_empty_source: false,
589        };
590        let step = dummy_step("succeeded", "{}", None);
591        let inv = derive_inverse_command(&cmd, &step).expect("should derive");
592        match inv {
593            Command::MoveTab {
594                tab_id,
595                src_workspace_id,
596                dst_workspace_id,
597                dst_index,
598                allow_empty_source,
599            } => {
600                assert_eq!(tab_id, "tab-1");
601                // src/dst swapped.
602                assert_eq!(src_workspace_id, "ws-dst");
603                assert_eq!(dst_workspace_id, "ws-src");
604                // Limitation: original src index lost; goes to 0.
605                assert_eq!(dst_index, 0);
606                assert!(allow_empty_source, "undoing a tear-off drains its new workspace");
607            }
608            other => panic!("expected MoveTab, got {:?}", other),
609        }
610    }
611
612    #[test]
613    fn move_block_inverse_swaps_src_and_dst() {
614        let cmd = Command::MoveBlock {
615            block_id: "blk-1".into(),
616            src_tab_id: "tab-src".into(),
617            dst_tab_id: "tab-dst".into(),
618            dst_index: 3,
619        };
620        let step = dummy_step("succeeded", "{}", None);
621        let inv = derive_inverse_command(&cmd, &step).expect("should derive");
622        match inv {
623            Command::MoveBlock {
624                block_id,
625                src_tab_id,
626                dst_tab_id,
627                dst_index,
628            } => {
629                assert_eq!(block_id, "blk-1");
630                assert_eq!(src_tab_id, "tab-dst");
631                assert_eq!(dst_tab_id, "tab-src");
632                assert_eq!(dst_index, 0);
633            }
634            other => panic!("expected MoveBlock, got {:?}", other),
635        }
636    }
637
638    #[test]
639    fn create_window_inverse_is_close_window_internal() {
640        let cmd = Command::CreateWindow {
641            window_id: "win-1".into(),
642            workspace_id: "ws-1".into(),
643        };
644        let step = dummy_step("succeeded", "{}", None);
645        let inv = derive_inverse_command(&cmd, &step).expect("should derive");
646        match inv {
647            Command::CloseWindowInternal { window_id } => {
648                assert_eq!(window_id, "win-1");
649            }
650            other => panic!("expected CloseWindowInternal, got {:?}", other),
651        }
652    }
653
654    #[test]
655    fn delete_commands_have_no_derivable_inverse() {
656        // Delete is destructive — no auto-compensation (un-delete
657        // requires reconstruction we don't have). Operator review path.
658        let cmd = Command::DeleteWorkspace {
659            workspace_id: "ws-1".into(),
660            force: false,
661        };
662        let step = dummy_step("succeeded", "{}", None);
663        assert!(derive_inverse_command(&cmd, &step).is_none());
664
665        let cmd = Command::DeleteTab {
666            workspace_id: "ws-1".into(),
667            tab_id: "tab-1".into(),
668            force: false,
669        };
670        assert!(derive_inverse_command(&cmd, &step).is_none());
671
672        let cmd = Command::DeleteBlock {
673            tab_id: "tab-1".into(),
674            block_id: "blk-1".into(),
675        };
676        assert!(derive_inverse_command(&cmd, &step).is_none());
677    }
678
679    #[test]
680    fn pure_meta_commands_have_no_derivable_inverse() {
681        // Update / rename commands need pre-state to invert; saga
682        // log doesn't capture it. Documented limitation.
683        let cmd = Command::RenameWorkspace {
684            workspace_id: "ws-1".into(),
685            name: "new".into(),
686        };
687        let step = dummy_step("succeeded", "{}", None);
688        assert!(derive_inverse_command(&cmd, &step).is_none());
689
690        let cmd = Command::SetActiveTab {
691            workspace_id: "ws-1".into(),
692            tab_id: "tab-1".into(),
693        };
694        assert!(derive_inverse_command(&cmd, &step).is_none());
695    }
696
697    // --- compensate_unresolved tests ---
698
699    #[tokio::test]
700    async fn compensate_unresolved_no_unresolved_returns_zero() {
701        let state = crate::server::tests::test_state();
702        let n = compensate_unresolved(&state).await.unwrap();
703        assert_eq!(n, 0);
704    }
705
706    #[tokio::test]
707    async fn compensate_unresolved_with_no_succeeded_steps_marks_compensated() {
708        // A saga that wrote `start_saga` but no steps, then crashed.
709        // Recovery should mark it `compensated` (no work to undo) and
710        // remove it from `unresolved_sagas`.
711        let state = crate::server::tests::test_state();
712        state
713            .saga_log
714            .start_saga(99, "ghost_saga", &serde_json::json!({"x": 1}))
715            .unwrap();
716        // Mid-recovery crash simulation: lifecycle is `running` with
717        // zero steps.
718
719        let n = compensate_unresolved(&state).await.unwrap();
720        assert_eq!(n, 1);
721
722        // Saga is now `compensated`, no longer unresolved.
723        let unresolved = state.saga_log.unresolved_sagas().unwrap();
724        assert!(unresolved.is_empty());
725        let snap = state.saga_log.snapshot_recent(10).unwrap();
726        let ghost = snap.iter().find(|s| s.saga_id == 99).unwrap();
727        assert_eq!(ghost.state, "compensated");
728    }
729
730    /// End-to-end: simulate a real partial-apply tear_off_tab. Run the
731    /// forward saga to completion (writing `succeeded` step rows), then
732    /// manually flip the lifecycle row back to `running` to mimic a
733    /// crash before terminate(). Open a fresh `AppState` over the same
734    /// `sagas.db`, call `compensate_unresolved`, assert the saga ends
735    /// `compensated` with recovery rows recorded.
736    ///
737    /// Why fresh AppState: PR 2 brief calls for "construct a fresh
738    /// AppState pointing to the same sagas.db, call compensate_unresolved
739    /// and assert it returns 1 + the saga is marked `compensated`."
740    /// The reducer state difference between the original and fresh
741    /// AppState mirrors what happens at process restart — except in
742    /// this test mstore is also fresh, so the recovery's reducer
743    /// dispatches operate against a clean reducer state. We assert
744    /// only the saga log behaviour (the mstore-dispatched compensating
745    /// commands are no-ops here because there's no entity to delete in
746    /// the fresh mstore — but the saga log still records the
747    /// compensation attempts, which is what `--diag sagas` surfaces).
748    #[tokio::test]
749    async fn compensate_unresolved_picks_up_running_saga_with_succeeded_steps() {
750        // Use a shared on-disk SagaLog so two AppStates can see the
751        // same saga log rows (in-memory dbs aren't shareable).
752        let tmp = tempfile::NamedTempFile::new().unwrap();
753        let saga_log = std::sync::Arc::new(SagaLog::open(tmp.path()).unwrap());
754
755        // Pre-seed: a saga that succeeded forward through two steps,
756        // then "crashed" before terminate. (We synthesize the rows
757        // directly rather than running a real saga to keep the test
758        // hermetic to the recovery API contract.)
759        saga_log
760            .start_saga(1, "tear_off_tab", &serde_json::json!({"tab_id": "tab-x"}))
761            .unwrap();
762        let create_cmd = Command::CreateWorkspace {
763            name: "".to_string(),
764        };
765        saga_log.start_step(1, 0, "CreateWorkspace", &create_cmd).unwrap();
766        saga_log
767            .finish_step(
768                1,
769                0,
770                &[Event::WorkspaceCreated {
771                    workspace_id: "new-ws".into(),
772                    name: "".into(),
773                    version: 1,
774                }],
775            )
776            .unwrap();
777        let move_cmd = Command::MoveTab {
778            tab_id: "tab-x".into(),
779            src_workspace_id: "src-ws".into(),
780            dst_workspace_id: "new-ws".into(),
781            dst_index: 0,
782            allow_empty_source: false,
783        };
784        saga_log.start_step(1, 1, "MoveTab", &move_cmd).unwrap();
785        saga_log
786            .finish_step(
787                1,
788                1,
789                &[Event::TabMoved {
790                    tab_id: "tab-x".into(),
791                    src_workspace_id: "src-ws".into(),
792                    dst_workspace_id: "new-ws".into(),
793                    dst_index: 0,
794                    new_src_active_tab_id: None,
795                    new_dst_active_tab_id: None,
796                    version: 2,
797                }],
798            )
799            .unwrap();
800        // No terminate() — saga is still `running` in the log.
801
802        // Build a fresh AppState backed by the same saga log.
803        let mut state = crate::server::tests::test_state();
804        state.saga_log = std::sync::Arc::clone(&saga_log);
805
806        // Run recovery.
807        let n = compensate_unresolved(&state).await.unwrap();
808        assert_eq!(n, 1, "expected to recover exactly 1 saga");
809
810        // Saga log shows it `compensated` (or `failed_compensation`
811        // if the dispatched inverses errored against the empty
812        // mstore — but the saga is no longer unresolved either way).
813        let unresolved = state.saga_log.unresolved_sagas().unwrap();
814        assert!(
815            unresolved.is_empty(),
816            "saga should no longer be unresolved, got: {:?}",
817            unresolved
818        );
819        let snap = state.saga_log.snapshot_recent(10).unwrap();
820        let resumed = snap.iter().find(|s| s.saga_id == 1).expect("saga 1 missing");
821        assert!(
822            resumed.state == "compensated" || resumed.state == "failed_compensation",
823            "expected compensated or failed_compensation, got {}",
824            resumed.state
825        );
826    }
827
828    /// Mid-step-failure recovery: succeeded prefix + one failed step.
829    /// Recovery should compensate the succeeded prefix and skip the
830    /// failed one (its effects didn't apply by definition).
831    #[tokio::test]
832    async fn compensate_unresolved_skips_failed_steps() {
833        let tmp = tempfile::NamedTempFile::new().unwrap();
834        let saga_log = std::sync::Arc::new(SagaLog::open(tmp.path()).unwrap());
835
836        saga_log
837            .start_saga(2, "test_saga", &serde_json::json!({}))
838            .unwrap();
839        let cmd_a = Command::CreateBlock {
840            tab_id: "tab-1".into(),
841            meta: serde_json::Value::Null,
842        };
843        saga_log.start_step(2, 0, "CreateBlock", &cmd_a).unwrap();
844        saga_log
845            .finish_step(
846                2,
847                0,
848                &[Event::BlockCreated {
849                    tab_id: "tab-1".into(),
850                    block_id: "blk-A".into(),
851                    meta: serde_json::Value::Null,
852                    version: 1,
853                }],
854            )
855            .unwrap();
856        let cmd_b = Command::MoveTab {
857            tab_id: "tab-1".into(),
858            src_workspace_id: "ws-src".into(),
859            dst_workspace_id: "ws-dst".into(),
860            dst_index: 0,
861            allow_empty_source: false,
862        };
863        saga_log.start_step(2, 1, "MoveTab", &cmd_b).unwrap();
864        saga_log.fail_step(2, 1, "reducer rejected").unwrap();
865        // No terminate — recovery picks this up.
866
867        let mut state = crate::server::tests::test_state();
868        state.saga_log = std::sync::Arc::clone(&saga_log);
869
870        compensate_unresolved(&state).await.unwrap();
871
872        // Verify recovery wrote at least one new step row beyond
873        // index 1 (the failed step). That row is the inverse of the
874        // succeeded CreateBlock at index 0.
875        let unresolved = state.saga_log.unresolved_sagas().unwrap();
876        assert!(unresolved.is_empty());
877        let snap = state.saga_log.snapshot_recent(10).unwrap();
878        let saga = snap.iter().find(|s| s.saga_id == 2).unwrap();
879        // Step count = succeeded forward + compensated recovery rows
880        // (excluding `failed`). At minimum, the original CreateBlock
881        // success counts. If recovery succeeded at dispatching,
882        // there'll be a `compensated` row too.
883        assert!(saga.step_count >= 1);
884    }
885}
886
887#[cfg(test)]
888#[path = "recovery_saga_tests.rs"]
889mod saga_tests;