agentmux_srv/sagas/delete_workspace.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Phase E.5.7 (Step 5 PR 2) — DeleteWorkspace saga.
5//
6// Replaces the inline cascade-on-dispatch pattern in
7// `service.rs::("workspace", "DeleteWorkspace")` with a saga that
8// records lifecycle brackets in the durable saga log. Closes the
9// remaining gap in the Step 5 series:
10//
11// * PR 1 already migrated `DeleteBlock` and `DeleteTab` to sagas.
12// * The `("workspace", "DeleteWorkspace")` RPC handler still issued
13// a single `Command::DeleteWorkspace` whose reducer arm cascaded
14// through tabs+blocks atomically, but a crash mid-cascade left
15// inconsistent state with no durable record of WHAT was deleted.
16//
17// **Saga-as-narrator pattern.** The reducer's `handle_delete_workspace`
18// remains the canonical mutator (it cascades through tabs+blocks and
19// drops window mappings in a single in-memory step). The saga's
20// contribution is durability: it walks the workspace's tabs first via
21// per-tab `Command::DeleteTab { force: true }` dispatches, recording
22// each in the saga log, then issues the final
23// `Command::DeleteWorkspace { force: true }` to drop the (now-empty)
24// workspace + window mappings.
25//
26// This decomposition means crash recovery (`recovery::compensate_unresolved`,
27// merged in #636) sees per-tab progress markers and can mark the saga
28// `failed_compensation` for operator review if the cascade was
29// interrupted — versus the legacy single-shot `DeleteWorkspace` which
30// either fully applied or left the reducer state untouched, with no
31// durable trace either way.
32//
33// **Steps:**
34// 1. Snapshot the workspace's tabs+blocks (read-only) for the saga
35// log's `input` field. Provenance for `--diag sagas`: which entities
36// existed at saga start, so an operator can reason about a partial
37// cascade later.
38// 2. For each tab (in `tab_ids` order): dispatch
39// `Command::DeleteTab { force: true }`. The reducer cascades the
40// tab's blocks atomically; the persist subscriber writes SQLite
41// via `wcore::delete_tab` (which kills PTY controllers via
42// `delete_tab_inner` → `delete_controller(block_id)`).
43// `force: true` bypasses the reducer's last-tab guard — we're
44// intentionally draining the workspace.
45// 3. Final dispatch: `Command::DeleteWorkspace { force: true }`. The
46// workspace is empty by this point (step 2 deleted every tab), so
47// the reducer's cascade only removes the workspace record + drops
48// window mappings (emitting `SrvWindowClosed` per affected window).
49// The `force: true` flag is provenance-only — the reducer's
50// behaviour is identical regardless.
51//
52// **Compensation.** Delete sagas are awkward to compensate by design:
53// once a tab + its blocks are gone (SQLite rows deleted, controllers
54// killed), reconstruction would require persisting the pre-state, which
55// no current saga does. Per the brief: compensation is **record-only**.
56// If a step fails mid-cascade we rely on `classify_run_saga_result` to
57// classify the error path:
58//
59// * `Err` (non-timeout) → `Compensated` — the saga's per-step log
60// rows already record what was deleted; subsequent crash-recovery
61// does NOT replay (Delete commands have no derivable inverse in
62// `recovery::derive_inverse_command`, by design).
63// * `Err` containing `"timed out"` → `Failed` — the saga timed out
64// before completing; recovery will see `running` lifecycle + the
65// succeeded step prefix and mark it `failed_compensation` (since
66// Delete has no derivable inverse, the operator must reconcile).
67// * `Ok` → `Completed` — clean cascade.
68//
69// **Pre-condition:** the workspace must exist in the reducer state OR
70// in SQLite. Bootstrap loads SQLite into reducer at startup, so they
71// normally match; we accept either to handle migration-window flows
72// where SQLite-direct writes haven't yet flowed through the reducer.
73
74use agentmux_common::ipc::Command;
75use serde_json::{json, Value};
76
77use super::{
78 alloc_saga_id, classify_run_saga_result, emit_saga_started, emit_terminal, run_saga, SagaCtx,
79};
80use crate::server::AppState;
81
82/// Run the DeleteWorkspace saga. On success returns
83/// `{"workspace_id": "...", "deleted_tab_count": N, "deleted_block_count": M}`.
84pub async fn run(state: &AppState, workspace_id: String) -> Result<Value, String> {
85 // Pre-condition + snapshot: read the workspace's tabs+blocks
86 // before any dispatch. We need the tab list to drive step 2's
87 // per-tab DeleteTab dispatches, and we record block ids in the
88 // saga log so `--diag sagas` can show what was destroyed.
89 let (tab_ids, block_count, block_ids) = {
90 let s = state.srv_state.lock().await;
91 let Some(workspace) = s.workspaces.get(&workspace_id) else {
92 return Err(format!(
93 "DeleteWorkspace: workspace not found: {}",
94 workspace_id
95 ));
96 };
97 let tab_ids: Vec<String> = workspace.tab_ids.clone();
98 let block_count: usize = workspace
99 .tab_ids
100 .iter()
101 .map(|tid| s.tabs.get(tid).map(|t| t.block_ids.len()).unwrap_or(0))
102 .sum();
103 let block_ids: Vec<String> = workspace
104 .tab_ids
105 .iter()
106 .filter_map(|tid| s.tabs.get(tid))
107 .flat_map(|t| t.block_ids.iter().cloned())
108 .collect();
109 (tab_ids, block_count, block_ids)
110 };
111
112 let saga_id = alloc_saga_id(state);
113 if let Err(e) = emit_saga_started(
114 state,
115 saga_id,
116 "delete_workspace",
117 json!({
118 "workspace_id": &workspace_id,
119 "tab_ids": &tab_ids,
120 "block_count": block_count,
121 }),
122 )
123 .await
124 {
125 return Err(e);
126 }
127 // Stop every agent in every tab of the workspace up front — gracefully,
128 // concurrently, under one deadline — before any record goes (pane-close
129 // spec §9.5). The per-tab cascade below then finds nothing left to stop.
130 // An agent's block stays when `agents:always_available` is on: parked first, so neither this
131 // stop nor a tab's delete reaches it.
132 let ctx = SagaCtx::new(state, saga_id);
133 let parked = super::park_agents::park_agent_blocks(&ctx, &block_ids, false).await;
134 super::agent_teardown::run_many(
135 state,
136 &super::park_agents::not_parked(&block_ids, &parked),
137 super::agent_teardown::Policy::close(),
138 )
139 .await;
140 let result = run_saga(
141 "delete_workspace",
142 run_inner(ctx, workspace_id.clone(), tab_ids.clone(), block_count),
143 )
144 .await;
145 for block_id in &block_ids {
146 super::close_pane::finish_close(state, block_id).await;
147 }
148 emit_terminal(state, saga_id, classify_run_saga_result(&result)).await;
149 result
150}
151
152async fn run_inner(
153 ctx: SagaCtx<'_>,
154 workspace_id: String,
155 tab_ids: Vec<String>,
156 block_count: usize,
157) -> Result<Value, String> {
158 // Step 2: per-tab DeleteTab dispatch. `force: true` bypasses the
159 // reducer's last-tab guard — the saga is intentionally draining
160 // the workspace, the guard exists to protect user-facing CloseTab
161 // flows from emptying a workspace by accident. Every agent was
162 // already closed gracefully above (`agent_teardown::run_many`); the
163 // persist subscriber's `wcore::delete_tab` → `delete_tab_inner` →
164 // `agent_teardown::discard` is only the backstop and finds nothing.
165 //
166 // **No compensation.** If a tab's DeleteTab dispatch fails mid-
167 // cascade, the already-deleted prefix is gone — we can't
168 // reconstruct the SQLite rows or respawn the PTY controllers.
169 // Returning `Err` records the failure in the saga log (per-step
170 // succeeded rows for the prefix + a failed row for the rejecting
171 // tab). `classify_run_saga_result` maps non-timeout `Err` to
172 // `Compensated`, which is technically inaccurate (nothing was
173 // un-done) but matches the saga framework's convention for
174 // non-timeout errors and avoids surfacing the saga to recovery's
175 // `failed`-state replay path (Delete has no derivable inverse
176 // anyway, so recovery would just mark `failed_compensation` —
177 // which is fine; either outcome surfaces in `--diag sagas`).
178 for (i, tab_id) in tab_ids.iter().enumerate() {
179 if let Err(reason) = ctx
180 .dispatch(Command::DeleteTab {
181 workspace_id: workspace_id.clone(),
182 tab_id: tab_id.clone(),
183 // Saga is draining the workspace; bypass the
184 // user-facing last-tab guard. (Saga's own pre-checks
185 // already validated the workspace exists.)
186 force: true,
187 })
188 .await
189 {
190 tracing::warn!(
191 workspace_id = %workspace_id,
192 tab_id = %tab_id,
193 step = i,
194 "[saga] DeleteWorkspace step 2 (DeleteTab): dispatch failed: {} — succeeded prefix already gone, no compensation possible",
195 reason,
196 );
197 return Err(format!(
198 "DeleteWorkspace step 2 (DeleteTab {}): {}",
199 tab_id, reason
200 ));
201 }
202 }
203
204 // Step 3: drop the (now-empty) workspace + cascade window mappings.
205 // The reducer's `handle_delete_workspace` removes the workspace
206 // record + emits `SrvWindowClosed` per affected window; the
207 // persist subscriber's `apply_workspace_deleted` runs
208 // `wcore::delete_workspace` for SQLite (idempotent if the
209 // workspace was already removed by the per-tab cascade in step 2).
210 if let Err(reason) = ctx
211 .dispatch(Command::DeleteWorkspace {
212 workspace_id: workspace_id.clone(),
213 // Saga-driven dispatch — provenance flag for the durable
214 // log. Reducer behaviour is identical for both values.
215 force: true,
216 })
217 .await
218 {
219 tracing::warn!(
220 workspace_id = %workspace_id,
221 "[saga] DeleteWorkspace step 3 (DeleteWorkspace): dispatch failed: {} — tabs already gone, workspace partially deleted",
222 reason,
223 );
224 return Err(format!("DeleteWorkspace step 3 (DeleteWorkspace): {}", reason));
225 }
226
227 Ok(json!({
228 "workspace_id": workspace_id,
229 "deleted_tab_count": tab_ids.len(),
230 "deleted_block_count": block_count,
231 }))
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237 use crate::backend::obj::{Block, Tab, Workspace};
238 use crate::server::tests::{dispatch_apply, test_state};
239 use agentmux_common::ipc::Event;
240
241 /// Seed a workspace with N tabs, each containing one block.
242 /// Returns `(state, workspace_id, tab_ids, block_ids)`.
243 async fn seed_workspace_with_tabs_and_blocks(
244 n: usize,
245 ) -> (
246 crate::server::AppState,
247 String,
248 Vec<String>,
249 Vec<String>,
250 ) {
251 let state = test_state();
252 let ws_evs = dispatch_apply(
253 &state,
254 Command::CreateWorkspace { name: "w".into() },
255 )
256 .await;
257 let ws_id = ws_evs
258 .iter()
259 .find_map(|e| match e {
260 Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
261 _ => None,
262 })
263 .unwrap();
264 let mut tab_ids = Vec::new();
265 let mut block_ids = Vec::new();
266 for i in 0..n {
267 let tab_evs = dispatch_apply(
268 &state,
269 Command::CreateTab {
270 workspace_id: ws_id.clone(),
271 name: format!("tab-{}", i),
272 },
273 )
274 .await;
275 let tab_id = tab_evs
276 .iter()
277 .find_map(|e| match e {
278 Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
279 _ => None,
280 })
281 .unwrap();
282 let blk_evs = dispatch_apply(
283 &state,
284 Command::CreateBlock {
285 tab_id: tab_id.clone(),
286 meta: serde_json::Value::Null,
287 },
288 )
289 .await;
290 let block_id = blk_evs
291 .iter()
292 .find_map(|e| match e {
293 Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
294 _ => None,
295 })
296 .unwrap();
297 tab_ids.push(tab_id);
298 block_ids.push(block_id);
299 }
300 (state, ws_id, tab_ids, block_ids)
301 }
302
303 #[tokio::test]
304 async fn happy_path_cascades_tabs_and_blocks() {
305 let (state, ws_id, tab_ids, block_ids) =
306 seed_workspace_with_tabs_and_blocks(2).await;
307
308 // Sanity: pre-state has workspace + tabs + blocks in both
309 // reducer state and SQLite.
310 {
311 let s = state.srv_state.lock().await;
312 assert!(s.workspaces.contains_key(&ws_id));
313 assert_eq!(s.workspaces[&ws_id].tab_ids.len(), 2);
314 assert_eq!(s.tabs.len(), 2);
315 assert_eq!(s.blocks.len(), 2);
316 }
317 for tab_id in &tab_ids {
318 assert!(state.mstore.get::<Tab>(tab_id).unwrap().is_some());
319 }
320 for block_id in &block_ids {
321 assert!(state.mstore.get::<Block>(block_id).unwrap().is_some());
322 }
323
324 let result = run(&state, ws_id.clone()).await.unwrap();
325 assert_eq!(result["workspace_id"], ws_id);
326 assert_eq!(result["deleted_tab_count"], 2);
327 assert_eq!(result["deleted_block_count"], 2);
328
329 // Reducer: workspace + all tabs + all blocks gone.
330 let s = state.srv_state.lock().await;
331 assert!(!s.workspaces.contains_key(&ws_id));
332 assert!(s.tabs.is_empty());
333 assert!(s.blocks.is_empty());
334 drop(s);
335
336 // SQLite: matches.
337 assert!(state.mstore.get::<Workspace>(&ws_id).unwrap().is_none());
338 for tab_id in &tab_ids {
339 assert!(state.mstore.get::<Tab>(tab_id).unwrap().is_none());
340 }
341 for block_id in &block_ids {
342 assert!(state.mstore.get::<Block>(block_id).unwrap().is_none());
343 }
344 }
345
346 #[tokio::test]
347 async fn rejects_when_workspace_not_found() {
348 let state = test_state();
349 let err = run(&state, "ghost-ws".into()).await.unwrap_err();
350 assert!(err.contains("workspace not found"), "got: {}", err);
351 }
352
353 #[tokio::test]
354 async fn empty_workspace_succeeds() {
355 // Workspace exists but has zero tabs — saga should skip the
356 // per-tab loop and proceed directly to step 3 (DeleteWorkspace).
357 let state = test_state();
358 let ws_evs = dispatch_apply(
359 &state,
360 Command::CreateWorkspace { name: "empty".into() },
361 )
362 .await;
363 let ws_id = ws_evs
364 .iter()
365 .find_map(|e| match e {
366 Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
367 _ => None,
368 })
369 .unwrap();
370
371 let result = run(&state, ws_id.clone()).await.unwrap();
372 assert_eq!(result["deleted_tab_count"], 0);
373 assert_eq!(result["deleted_block_count"], 0);
374
375 let s = state.srv_state.lock().await;
376 assert!(!s.workspaces.contains_key(&ws_id));
377 }
378
379 #[tokio::test]
380 async fn writes_lifecycle_brackets_to_saga_log() {
381 // Verify the saga records `start_saga` + per-step `succeeded`
382 // rows + a terminal `completed` lifecycle row. This is what
383 // PR 2's `--diag sagas` and `compensate_unresolved` rely on.
384 let (state, ws_id, _tab_ids, _block_ids) =
385 seed_workspace_with_tabs_and_blocks(1).await;
386 run(&state, ws_id.clone()).await.unwrap();
387
388 let snap = state.saga_log.snapshot_recent(10).unwrap();
389 let saga = snap
390 .iter()
391 .find(|s| s.name == "delete_workspace")
392 .expect("delete_workspace saga should appear in snapshot");
393 assert_eq!(saga.state, "completed", "saga should terminate completed");
394 // 1 DeleteTab step + 1 DeleteWorkspace step = 2 forward steps.
395 assert!(
396 saga.step_count >= 2,
397 "expected >= 2 steps, got {}",
398 saga.step_count
399 );
400 // No unresolved sagas — recovery shouldn't pick this up.
401 let unresolved = state.saga_log.unresolved_sagas().unwrap();
402 assert!(
403 unresolved.iter().all(|s| s.saga_id != saga.saga_id),
404 "saga should not be unresolved post-completion"
405 );
406 }
407
408 #[tokio::test]
409 async fn cascade_drops_window_mappings() {
410 // Seed a workspace mapped to a window; saga should cascade
411 // window-removal via the reducer's existing
412 // handle_delete_workspace logic (which emits SrvWindowClosed
413 // per affected window).
414 let (state, ws_id, _tab_ids, _block_ids) =
415 seed_workspace_with_tabs_and_blocks(1).await;
416 let win_id = "win-test".to_string();
417 let _ = dispatch_apply(
418 &state,
419 Command::CreateWindow {
420 window_id: win_id.clone(),
421 workspace_id: ws_id.clone(),
422 },
423 )
424 .await;
425 {
426 let s = state.srv_state.lock().await;
427 assert!(s.windows.contains_key(&win_id));
428 }
429
430 run(&state, ws_id.clone()).await.unwrap();
431
432 let s = state.srv_state.lock().await;
433 assert!(!s.windows.contains_key(&win_id));
434 }
435}