Skip to main content

agentmux_srv_core/backend/
session_snapshot.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The last-session snapshot kept in the client row's meta (`session:last_topology`): saved when a window closes
5//! or the OS shuts down, read back by the restore (`server/service/session_restore.rs`, which re-exports these
6//! under its old paths). Only the store is involved, so the upgrade's carry-forward test reaches it from the core.
7
8use serde_json::Value;
9
10use crate::backend::obj::Client;
11use crate::backend::storage::store::Store;
12
13pub const SNAPSHOT_META_KEY: &str = "session:last_topology";
14
15/// Persist a snapshot as the durable "last session" record, overwriting
16/// whatever was there before. Best-effort: a write failure is logged, never
17/// propagated — this must never block the close it rides alongside.
18///
19/// Reads-then-writes the singleton `Client` row inside a single
20/// `with_tx` (reagentx P1 on PR #2560): the two used to be separate
21/// `store.get_all`/`store.update` calls, unlike `persist_subscriber`'s
22/// window handlers which already wrap this exact shape in a transaction.
23/// A concurrent write to `Client` between the read and the write here
24/// (e.g. another in-flight `CloseWindow` pruning `windowids`, or a second
25/// concurrent snapshot save/clear) would silently lose whichever change
26/// didn't win the race — a classic lost-update. `with_tx` holds the
27/// store's connection lock for the whole read+write, so no other caller
28/// can observe or write an intermediate state.
29/// Returns whether the write actually landed. Callers on the clean-close path
30/// (`window_close.rs`) intentionally discard this — that path is documented
31/// best-effort, and must never let a snapshot failure block the close it is
32/// riding along with. The OS-shutdown path (`handle_save_session_snapshot`
33/// below) is different: it has nothing else to do after this call, so it
34/// uses the result to report whether the flush actually succeeded rather
35/// than reporting success unconditionally.
36pub fn save_last_session_snapshot(store: &Store, snapshot: Value) -> bool {
37    let result = store.with_tx(|tx| {
38        let clients = tx.get_all::<Client>()?;
39        let Some(mut client) = clients.into_iter().next() else {
40            // No client row to attach the snapshot to — nothing was written.
41            // Not a store error, but still not a successful save: surface it
42            // as one via the Ok(false) below rather than Ok(()) reading as
43            // unconditional success regardless of what actually happened.
44            return Ok(false);
45        };
46        client.meta.insert(SNAPSHOT_META_KEY.to_string(), snapshot);
47        tx.update(&mut client)?;
48        Ok(true)
49    });
50    match result {
51        Ok(saved) => saved,
52        Err(e) => {
53            tracing::warn!(
54                error = %e,
55                "session_restore: failed to persist last-session snapshot"
56            );
57            false
58        }
59    }
60}
61
62pub fn load_last_session_snapshot(store: &Store) -> Option<Value> {
63    let clients = store.get_all::<Client>().ok()?;
64    let client = clients.into_iter().next()?;
65    client.meta.get(SNAPSHOT_META_KEY).cloned()
66}