Skip to main content

agentmux_srv/sagas/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Phase E.5.5 — srv-side saga coordinator.
5//
6// NOT the same framework as `agentmux_launcher::saga`, despite the shared
7// name — see the "Why srv, not launcher" note directly below for the
8// original reasoning, and
9// docs/architecture/DECISION_SAGA_REDUCER_TWO_FRAMEWORKS_2026_09_07.md
10// for the decision to keep both rather than merge or rename them.
11//
12// **Why srv, not launcher:** the existing E.1a coordinator
13// framework lives in `agentmux-launcher::saga`. At the time this module was
14// written it had no consumers; Phase F.5 later gave it exactly one
15// (`pool_respawn`) — still cross-process-shaped, still not what this crate
16// needs. The original Phase E spec assumed
17// sagas would fan out across host/launcher/srv via cross-process
18// IPC; the actual implementation kept that fan-out in the frontend
19// (`requestTearOff` calls srv-rpc and host-rpc directly), so every
20// saga in the E.5 plan mutates only srv state. In-process oneshot
21// dispatch beats an IPC round-trip on every saga step. See
22// `docs/retro/saga-coordinator-location-analysis-2026-04-30.md` for
23// the full reasoning, including the robustness trade-offs (which
24// are the same for both placements).
25//
26// **Shape:** sagas are async functions that:
27//   1. allocate a fresh saga_id via `alloc_saga_id`,
28//   2. emit `Event::SagaStarted` via `emit_saga_started`,
29//   3. drive their state machine via `SagaCtx::dispatch` /
30//      `SagaCtx::compensate`,
31//   4. emit `Event::SagaCompleted` or `Event::SagaFailed` via
32//      `emit_terminal` once the inner work returns.
33//
34// `run_saga(state, name, future)` is a thin wrapper that does
35// 1+2+4 + applies a 5 s timeout. Sagas pass the future directly
36// (not a closure), avoiding the lifetime-of-SagaCtx complication
37// that closure-style coordinators run into.
38//
39// **Compensation:** the saga's inner future is responsible for
40// driving compensation before returning `Err`. `SagaCtx::compensate`
41// is a best-effort dispatch that swallows errors (the saga is
42// already failing; secondary failures get logged). Idempotency of
43// compensating commands (`MoveTab` back to source, `DeleteWorkspace`,
44// etc.) keeps the cleanup safe even if a step partially applied.
45//
46// What this module does NOT close (per the location analysis §4.2):
47// * Per-step SQLite transactions in the subscriber (gap; F1.A).
48// * Host pool-promote and renderer registration outside the saga
49//   (gap; Phase F).
50// * Saga state across srv restart (gap; Phase F+).
51
52pub mod agent_teardown;
53pub(crate) mod teardown_hooks;
54pub mod close_pane;
55pub mod delete_block;
56pub mod delete_tab;
57pub mod delete_workspace;
58pub mod log;
59pub mod orphan_reaper;
60pub mod park_agents;
61#[cfg(test)]
62pub(crate) mod park_agents_tests;
63pub mod promote_block_to_tab;
64pub mod recovery;
65pub mod pending_shutdown;
66pub mod redock_floating_pane;
67pub mod self_quit;
68pub mod sensitive_fallback;
69pub mod sensitive_runners;
70pub mod agent_notice;
71pub mod credential_notice;
72pub mod pane_confirm;
73pub mod capture_mask;
74pub mod deeplink_open;
75pub mod sensitive_window;
76pub mod restore_torn_off_tab;
77pub mod tear_off_block;
78pub mod tear_off_tab;
79
80// Step 7 — E.7 integration tests. Cross-saga end-to-end coverage
81// that exercises reducer + saga coordinator + persist subscriber +
82// saga log together against a real `AppState` (in-memory mstore +
83// sagalog). Per-saga unit tests under each saga module already cover
84// happy + reject paths in isolation; this module focuses on
85// multi-surface consistency (reducer/mstore/saga-log) that PR 2's
86// `compensate_unresolved` will rely on.
87#[cfg(test)]
88mod integration_tests;
89#[cfg(test)]
90mod shutdown_events_tests;
91#[cfg(test)]
92mod prompt_events_tests;
93
94use std::sync::atomic::{AtomicU32, Ordering};
95
96use agentmux_common::ipc::{Command, Event};
97use serde_json::Value;
98
99use crate::sagas::log::{command_discriminant_name, SagaOutcome};
100use crate::server::AppState;
101
102/// Maximum wall-clock time a saga is allowed to run before the
103/// coordinator force-fails it. Tear-off sagas should complete in
104/// tens of milliseconds; the budget is generous to absorb SQLite
105/// write spikes without flapping in CI.
106const SAGA_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
107
108/// Read-only context passed to a saga's inner async function.
109/// Wraps the AppState handle and the saga's allocated id.
110///
111/// Construct via [`SagaCtx::new`] — the durability log requires the
112/// per-step counter to start at zero and be owned by the ctx (so
113/// concurrent sagas don't interleave step indices).
114pub struct SagaCtx<'a> {
115    pub(crate) state: &'a AppState,
116    pub(crate) saga_id: u64,
117    /// Monotonic step index (0, 1, 2, ...) for this saga. Each
118    /// `dispatch` / `compensate` call `fetch_add(1)`s and writes the
119    /// resulting index into the saga log. Atomic because saga inner
120    /// futures may parallelise dispatches in the future (today they
121    /// don't, but the cost is one cache line).
122    pub(crate) step_index: AtomicU32,
123    /// (codex P1 PR #636 round 4.) Stack of forward-step indices that
124    /// have completed successfully and are eligible to be undone by
125    /// the next `compensate` call. `dispatch` pushes on success;
126    /// `compensate` pops to determine which original forward step
127    /// it's reversing, and marks that step `compensated` in the log.
128    /// Without this, in-process compensation only writes new
129    /// `compensated` rows at fresh indices; the original `succeeded`
130    /// rows stay `succeeded`, so resume-on-restart re-replays them
131    /// and either no-ops or worse double-applies the inverse.
132    ///
133    /// `Mutex<Vec>` (rather than a lock-free counter) because saga
134    /// inner futures could in theory parallelize compensations; in
135    /// practice they're serial today, so contention is zero.
136    pub(crate) forward_step_stack: tokio::sync::Mutex<Vec<u32>>,
137}
138
139impl<'a> SagaCtx<'a> {
140    /// Construct a fresh context for a saga that has just allocated
141    /// its `saga_id` (via [`alloc_saga_id`]).
142    pub fn new(state: &'a AppState, saga_id: u64) -> Self {
143        Self {
144            state,
145            saga_id,
146            step_index: AtomicU32::new(0),
147            forward_step_stack: tokio::sync::Mutex::new(Vec::new()),
148        }
149    }
150
151    /// Saga-id this context belongs to. Used by sagas that need to
152    /// log progress with the saga prefix.
153    #[allow(dead_code)]
154    pub fn saga_id(&self) -> u64 {
155        self.saga_id
156    }
157
158    /// Acquire the reducer's state lock for read-only inspection.
159    /// Used by sagas that need to inspect post-step state to decide
160    /// the next step (e.g. RestoreTornOffTab checking whether the
161    /// source workspace is now empty before issuing the cascade
162    /// delete). Hold briefly — the reducer is single-mutex.
163    pub async fn state_lock(&self) -> tokio::sync::MutexGuard<'_, crate::state::State> {
164        self.state.srv_state.lock().await
165    }
166
167    /// Dispatch `cmd` through the srv reducer and apply the emitted
168    /// events to SQLite + the broadcast bus, exactly like the
169    /// in-handler reducer-dispatch helpers.
170    ///
171    /// Returns the emitted event vec on success. If the reducer
172    /// emits any `Event::Error`, the error message is returned and
173    /// SQLite/bus side-effects are skipped — the caller must then
174    /// dispatch compensation for the saga's already-applied steps.
175    pub async fn dispatch(&self, cmd: Command) -> Result<Vec<Event>, String> {
176        // Saga durability — write a `pending` step row before
177        // dispatch so a crash mid-dispatch leaves a recoverable
178        // breadcrumb (PR 2's compensate-on-restart will see it).
179        let idx = self.step_index.fetch_add(1, Ordering::Relaxed);
180        let step_name = command_discriminant_name(&cmd);
181        if let Err(e) = self
182            .state
183            .saga_log
184            .start_step(self.saga_id, idx, &step_name, &cmd)
185        {
186            // Log-write failure is non-fatal: the in-memory saga
187            // path is still authoritative for THIS srv run; we lose
188            // crash-recovery for this step, but the user's command
189            // shouldn't fail because durability hiccupped.
190            tracing::warn!(
191                saga_id = self.saga_id,
192                step_index = idx,
193                "[saga] start_step log write failed: {} — continuing without durable log for this step",
194                e
195            );
196        }
197
198        let events = crate::server::service::dispatch_to_reducer(self.state, cmd).await;
199        if let Some(message) = events.iter().find_map(|e| match e {
200            Event::Error { message, .. } => Some(message.clone()),
201            _ => None,
202        }) {
203            if let Err(e) = self.state.saga_log.fail_step(self.saga_id, idx, &message) {
204                tracing::warn!(
205                    saga_id = self.saga_id,
206                    step_index = idx,
207                    "[saga] fail_step log write failed: {}",
208                    e
209                );
210            }
211            return Err(message);
212        }
213        for ev in &events {
214            if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, &self.state.mstore)
215            {
216                // (reagent P1 PR #631 round 2) Mark the step as
217                // failed in the durable log BEFORE returning. Without
218                // this, the step row stays in `pending` state even
219                // though the reducer already applied the command
220                // (line 139); PR 2's compensate-on-restart sees a
221                // `pending` step and can't determine whether the
222                // command was applied.
223                let err_msg = e.to_string();
224                if let Err(log_err) =
225                    self.state.saga_log.fail_step(self.saga_id, idx, &err_msg)
226                {
227                    tracing::warn!(
228                        saga_id = self.saga_id,
229                        step_index = idx,
230                        "[saga] fail_step log write failed during mstore-apply error path: {}",
231                        log_err,
232                    );
233                }
234                return Err(err_msg);
235            }
236        }
237        if let Err(e) = self.state.saga_log.finish_step(self.saga_id, idx, &events) {
238            tracing::warn!(
239                saga_id = self.saga_id,
240                step_index = idx,
241                "[saga] finish_step log write failed: {}",
242                e
243            );
244        }
245        // (codex P1 PR #636 round 4.) Track this idx as a successful
246        // forward step eligible for compensation. The next
247        // `compensate` call will pop this and mark the original step
248        // `compensated`, preventing resume-on-restart from re-replaying
249        // an inverse that already ran in-process.
250        self.forward_step_stack.lock().await.push(idx);
251        crate::server::service::publish_events(self.state, &events);
252        Ok(events)
253    }
254
255    /// Best-effort compensating dispatch. Same as `dispatch` but
256    /// SQLite-write failures are logged and swallowed. Intended for
257    /// the unwind path: the saga is already returning an error to
258    /// the caller; throwing on cleanup hides the original cause and
259    /// prevents subsequent compensating commands from running.
260    pub async fn compensate(&self, cmd: Command) {
261        // Compensation gets its own step row so the durable log
262        // distinguishes "step that succeeded forward" from "step
263        // that ran in unwind". Index continues monotonically from
264        // forward steps so `--diag sagas` shows the full sequence.
265        let idx = self.step_index.fetch_add(1, Ordering::Relaxed);
266        let step_name = command_discriminant_name(&cmd);
267        if let Err(e) = self
268            .state
269            .saga_log
270            .start_step(self.saga_id, idx, &step_name, &cmd)
271        {
272            tracing::warn!(
273                saga_id = self.saga_id,
274                step_index = idx,
275                "[saga] compensate start_step log write failed: {}",
276                e
277            );
278        }
279        let events =
280            crate::server::service::dispatch_to_reducer(self.state, cmd.clone()).await;
281        if let Some(message) = events.iter().find_map(|e| match e {
282            Event::Error { message, .. } => Some(message.clone()),
283            _ => None,
284        }) {
285            tracing::warn!(
286                saga_id = self.saga_id,
287                "[saga] compensation rejected by reducer: {} (cmd discriminant: {:?})",
288                message,
289                std::mem::discriminant(&cmd),
290            );
291            if let Err(e) = self.state.saga_log.fail_step(self.saga_id, idx, &message) {
292                tracing::warn!(
293                    saga_id = self.saga_id,
294                    step_index = idx,
295                    "[saga] compensate fail_step log write failed: {}",
296                    e
297                );
298            }
299            return;
300        }
301        for ev in &events {
302            if let Err(e) =
303                crate::persist_subscriber::apply_event_to_mstore(ev, &self.state.mstore)
304            {
305                tracing::warn!(
306                    saga_id = self.saga_id,
307                    "[saga] compensation: SQLite write failed: {}",
308                    e
309                );
310            }
311        }
312        if let Err(e) = self
313            .state
314            .saga_log
315            .compensate_step(self.saga_id, idx, &events)
316        {
317            tracing::warn!(
318                saga_id = self.saga_id,
319                step_index = idx,
320                "[saga] compensate_step log write failed: {}",
321                e
322            );
323        }
324        // (codex P1 PR #636 round 4.) Pop the most-recent successful
325        // forward step from the stack and mark its original log row
326        // as compensated. This prevents resume-on-restart from
327        // double-replaying the inverse of a step that already had
328        // in-process compensation. Idempotent — UPDATE only matches
329        // rows still in `succeeded` state.
330        if let Some(forward_idx) = self.forward_step_stack.lock().await.pop() {
331            if let Err(e) = self
332                .state
333                .saga_log
334                .mark_step_compensated(self.saga_id, forward_idx)
335            {
336                tracing::warn!(
337                    saga_id = self.saga_id,
338                    forward_step_index = forward_idx,
339                    "[saga] mark_step_compensated (live) log write failed: {} — restart may re-replay this inverse",
340                    e
341                );
342            }
343        }
344        crate::server::service::publish_events(self.state, &events);
345    }
346}
347
348/// Allocate the next saga_id. Monotonic per srv-process run.
349pub fn alloc_saga_id(state: &AppState) -> u64 {
350    state.saga_id_alloc.fetch_add(1, Ordering::Relaxed) + 1
351}
352
353/// Emit `Event::SagaStarted` for a freshly-allocated saga_id.
354/// Sagas call this immediately after `alloc_saga_id` so subscribers
355/// see the start record before any per-step events.
356///
357/// Also writes a `running` row to the durable saga log (PR 1 of
358/// SPEC_SAGA_DURABILITY_2026-05-01.md), recording `input` as the
359/// saga's arguments serialized to JSON. PR 2's `compensate_unresolved`
360/// + `--diag sagas` rely on this for crash-recovery provenance, so
361/// callers should pass a structured representation of their inputs
362/// (typically `serde_json::json!({...})`). (reagent P1 PR #631 —
363/// `Value::Null` placeholder erased provenance.)
364///
365/// **Fail-fast on log error.** (codex P1 PR #631 round 2.) If
366/// `start_saga` fails — most likely a UNIQUE constraint violation
367/// from a saga_id collision — the saga MUST NOT proceed. Otherwise
368/// later `terminate()` calls would `UPDATE saga SET ... WHERE saga_id=?`
369/// against a *different run's* row, mixing lifecycle data across
370/// sagas and silently corrupting the durability log. Returning
371/// `Err` here propagates up to the caller, which records the
372/// failure via `emit_terminal` (with a fresh saga_id allocated by
373/// the caller's `alloc_saga_id` retry path, if any).
374pub async fn emit_saga_started(
375    state: &AppState,
376    saga_id: u64,
377    name: &'static str,
378    input: serde_json::Value,
379) -> Result<(), String> {
380    if let Err(e) = state.saga_log.start_saga(saga_id, name, &input) {
381        let msg = format!(
382            "saga durable start row insert failed for saga_id={}: {} (likely ID collision; refusing to run)",
383            saga_id, e
384        );
385        tracing::error!(
386            saga_id,
387            name,
388            "[saga] {} — aborting saga to avoid corrupting prior run's lifecycle row",
389            msg,
390        );
391        return Err(msg);
392    }
393    let v = state.srv_state.lock().await.bump_version();
394    let _ = state.srv_events_tx.send(Event::SagaStarted {
395        saga_id,
396        name: name.to_string(),
397        version: v,
398    });
399    Ok(())
400}
401
402/// Outcome a saga's inner future hands back to `emit_terminal`.
403///
404/// (codex P1 PR #631) The original PR 1 implementation mapped every
405/// `Err` to `SagaOutcome::Compensated`, which is wrong for timeout/
406/// abort paths: `run_saga` wraps the inner future in
407/// `tokio::time::timeout`, and a timeout cancels the future *before*
408/// it can run its compensation block. Recording "compensated" when
409/// nothing was compensated would hide partially-applied state from
410/// PR 2's `compensate_unresolved` resume scan — exactly the failure
411/// mode this log exists to catch.
412///
413/// `Compensated` should only be recorded when compensation actually
414/// completed; everything else (timeout, panic-converted-to-error,
415/// pre-compensation early-return) records `Failed`, which leaves the
416/// saga visible to PR 2's resume scan.
417#[derive(Debug)]
418pub enum SagaTerminal<'a> {
419    /// All steps applied successfully.
420    Completed,
421    /// Compensation block ran to completion. Caller asserts this only
422    /// after every compensating dispatch returned without error.
423    Compensated { reason: &'a str },
424    /// Saga aborted before/during compensation: timeout, panic,
425    /// pre-compensation early-return, or any other path where
426    /// compensation can't be assumed to have run. Default for the
427    /// "I don't know if compensation completed" case.
428    Failed { reason: &'a str },
429}
430
431/// Emit the saga's terminal lifecycle event + durable log row.
432///
433/// Maps `SagaTerminal` to:
434/// - `Completed` → `Event::SagaCompleted` + log state `completed`.
435/// - `Compensated { reason }` → `Event::SagaFailed { reason }` + log state `compensated`.
436/// - `Failed { reason }` → `Event::SagaFailed { reason }` + log state `failed`.
437///
438/// The renderer-facing event is the same `SagaFailed` for both
439/// non-success paths (the renderer doesn't currently distinguish).
440/// The durable log distinguishes — PR 2's resume scan picks up
441/// `failed` rows where compensation may not have run.
442pub async fn emit_terminal(state: &AppState, saga_id: u64, terminal: SagaTerminal<'_>) {
443    let log_outcome = match &terminal {
444        SagaTerminal::Completed => SagaOutcome::Completed,
445        SagaTerminal::Compensated { reason } => SagaOutcome::Compensated {
446            reason: reason.to_string(),
447        },
448        SagaTerminal::Failed { reason } => SagaOutcome::Failed {
449            reason: reason.to_string(),
450        },
451    };
452    // (codex P1 PR #636 round 7 — reverted from round 6.)
453    // Bulk-mark only on Compensated. Round 6 extended to Failed too,
454    // but BOTH bots flagged that as data-loss: timeout/abort paths
455    // classify as Failed and never run compensation, but the bulk-
456    // mark would relabel forward steps as `compensated`, hiding
457    // them from recovery and leaving side effects permanently
458    // applied.
459    //
460    // Sagas that DO unwind via inner-future ctx.compensate calls
461    // should classify as Compensated (the per-step pop already
462    // marks 1:1; this bulk call catches residual 1:N cases like
463    // tear_off_block's single DeleteWorkspace undoing both
464    // CreateWorkspace + CreateTab). `classify_run_saga_result`
465    // maps non-timeout Err → Compensated to support this; timeouts
466    // → Failed so recovery picks up un-undone rows.
467    if matches!(terminal, SagaTerminal::Compensated { .. }) {
468        if let Err(e) = state.saga_log.mark_all_succeeded_steps_compensated(saga_id) {
469            tracing::warn!(
470                saga_id,
471                "[saga] mark_all_succeeded_steps_compensated failed: {} — restart may re-replay an inverse",
472                e
473            );
474        }
475    }
476    if let Err(e) = state.saga_log.terminate(saga_id, log_outcome) {
477        tracing::warn!(
478            saga_id,
479            "[saga] terminate log write failed: {} — saga lifecycle row will look 'running' to PR 2's resume scan, which will then compensate it",
480            e
481        );
482    }
483    let v = state.srv_state.lock().await.bump_version();
484    let event = match terminal {
485        SagaTerminal::Completed => Event::SagaCompleted {
486            saga_id,
487            version: v,
488        },
489        SagaTerminal::Compensated { reason } | SagaTerminal::Failed { reason } => {
490            Event::SagaFailed {
491                saga_id,
492                reason: reason.to_string(),
493                version: v,
494            }
495        }
496    };
497    let _ = state.srv_events_tx.send(event);
498}
499
500/// Convenience: classify the standard `run_saga` `Result<Value, String>`
501/// outcome into a `SagaTerminal`.
502///
503/// - `Ok(_)` → `Completed`.
504/// - `Err(_)` → `Failed`.
505///
506/// (codex P1 PR #631 round 2.) The earlier round mapped non-timeout
507/// `Err` to `Compensated` on the assumption that "our sagas drive
508/// compensation in their inner future before returning `Err`."
509/// That's true for the *forward* dispatch failures, but
510/// `SagaCtx::compensate` is **best-effort** — if a compensating
511/// dispatch is itself rejected by the reducer, `compensate` logs a
512/// warning and returns without signaling failure. Marking those as
513/// `Compensated` would hide partially-applied state from PR 2's
514/// restart recovery (which scans for `running`/`failed` to know what
515/// to compensate).
516///
517/// Conservative default: classify all errors as `Failed`. Sagas that
518/// can *prove* compensation succeeded (e.g. a future per-step
519/// compensation-success log) construct `SagaTerminal::Compensated`
520/// directly without going through this helper.
521pub fn classify_run_saga_result(result: &Result<serde_json::Value, String>) -> SagaTerminal<'_> {
522    match result {
523        Ok(_) => SagaTerminal::Completed,
524        // Timeouts/aborts: compensation never ran (run_saga's
525        // tokio::time::timeout cancels the inner future before it
526        // can compensate). Classify as Failed so recovery picks up
527        // the un-undone forward steps.
528        Err(reason) if reason.contains("timed out") => SagaTerminal::Failed { reason },
529        // Other Err: by convention, our sagas drive compensation
530        // in their inner future before returning Err (each
531        // ctx.compensate call already marked its target). Classify
532        // as Compensated so emit_terminal's bulk-mark cleans up any
533        // residual succeeded rows from 1:N compensation patterns
534        // (e.g. tear_off_block's single DeleteWorkspace undoing
535        // multiple CreateX steps). Sagas that abort without
536        // compensating should explicitly construct
537        // SagaTerminal::Failed instead of using this helper.
538        // (codex round 7 reversal of round 1's blanket-Failed.)
539        Err(reason) => SagaTerminal::Compensated { reason },
540    }
541}
542
543/// Run a saga's inner future under a 5 s timeout. The inner future
544/// is responsible for emitting `SagaStarted` (the saga itself, since
545/// it owns the saga_id allocation) and any compensation it needs;
546/// `run_saga` only enforces the timeout and emits the terminal
547/// `SagaCompleted` / `SagaFailed`.
548///
549/// Concrete usage (per saga):
550/// ```ignore
551/// pub async fn run(state: &AppState, ...) -> Result<Value, String> {
552///     let saga_id = alloc_saga_id(state);
553///     emit_saga_started(state, saga_id, "tear_off_tab", serde_json::json!({})).await;
554///     let ctx = SagaCtx::new(state, saga_id);
555///     let result = run_saga(run_inner(ctx, ...)).await;
556///     emit_terminal(state, saga_id, classify_run_saga_result(&result)).await;
557///     result
558/// }
559/// ```
560pub async fn run_saga<Fut>(name: &'static str, fut: Fut) -> Result<Value, String>
561where
562    Fut: std::future::Future<Output = Result<Value, String>>,
563{
564    match tokio::time::timeout(SAGA_TIMEOUT, fut).await {
565        Ok(r) => r,
566        Err(_) => Err(format!("saga '{}' timed out after {:?}", name, SAGA_TIMEOUT)),
567    }
568}