Skip to main content

lean_ctx/core/session/
persistence.rs

1use chrono::Utc;
2use serde::{Deserialize, Serialize};
3
4use super::heuristics::{normalize_loaded_session, session_matches_project_root};
5use super::paths::sessions_dir;
6use super::state::{BATCH_SAVE_INTERVAL, extract_session_facts};
7#[allow(clippy::wildcard_imports)]
8use super::types::*;
9
10/// Keep the startup warm set deliberately small: cache warming is an optional
11/// optimisation and must never turn process startup into a session-store scan.
12const PROJECT_HISTORY_LIMIT: usize = 8;
13
14#[derive(Debug, Default, Deserialize, Serialize)]
15struct ProjectSessionIndex {
16    version: u8,
17    project_root: String,
18    /// Oldest to newest; duplicates are removed before appending on every save.
19    session_ids: Vec<String>,
20}
21
22fn normalized_safe_project_root(project_root: &str) -> Option<String> {
23    let path = std::path::Path::new(project_root);
24    if project_root.trim().is_empty() || crate::core::pathutil::is_broad_or_unsafe_root(path) {
25        return None;
26    }
27    Some(
28        crate::core::pathutil::safe_canonicalize_or_self(path)
29            .to_string_lossy()
30            .to_string(),
31    )
32}
33
34fn project_index_path(dir: &std::path::Path, project_root: &str) -> std::path::PathBuf {
35    let key = blake3::hash(project_root.as_bytes()).to_hex();
36    dir.join("project-index").join(format!("{key}.json"))
37}
38
39/// Update one project's bounded warm-history index under a short, local lock.
40/// The index is strictly an acceleration structure: a failure never invalidates
41/// the already-committed session save.
42fn update_project_index(dir: &std::path::Path, project_root: &str, id: &str) -> Result<(), String> {
43    use fs2::FileExt;
44    use std::time::{Duration, Instant};
45
46    const LOCK_TIMEOUT: Duration = Duration::from_millis(200);
47    const RETRY_INTERVAL: Duration = Duration::from_millis(10);
48
49    let index_path = project_index_path(dir, project_root);
50    let index_dir = index_path.parent().ok_or("project index has no parent")?;
51    std::fs::create_dir_all(index_dir).map_err(|e| format!("create project index: {e}"))?;
52
53    let lock_path = index_path.with_extension("lock");
54    let lock = std::fs::OpenOptions::new()
55        .create(true)
56        .truncate(false)
57        .write(true)
58        .open(lock_path)
59        .map_err(|e| format!("project index lock: {e}"))?;
60    let deadline = Instant::now() + LOCK_TIMEOUT;
61    loop {
62        match lock.try_lock_exclusive() {
63            Ok(()) => break,
64            Err(error)
65                if crate::core::file_lock::is_contended(&error) && Instant::now() < deadline =>
66            {
67                std::thread::sleep(RETRY_INTERVAL);
68            }
69            Err(error) if crate::core::file_lock::is_contended(&error) => {
70                return Err("project index lock timed out".to_string());
71            }
72            Err(error) => return Err(format!("project index lock: {error}")),
73        }
74    }
75
76    let result = (|| {
77        let mut index = std::fs::read_to_string(&index_path)
78            .ok()
79            .and_then(|json| serde_json::from_str::<ProjectSessionIndex>(&json).ok())
80            .filter(|index| index.version == 1 && index.project_root == project_root)
81            .unwrap_or_else(|| ProjectSessionIndex {
82                version: 1,
83                project_root: project_root.to_string(),
84                session_ids: Vec::new(),
85            });
86
87        index.session_ids.retain(|existing| existing != id);
88        index.session_ids.push(id.to_string());
89        let excess = index
90            .session_ids
91            .len()
92            .saturating_sub(PROJECT_HISTORY_LIMIT);
93        if excess > 0 {
94            index.session_ids.drain(..excess);
95        }
96
97        let json =
98            serde_json::to_string(&index).map_err(|e| format!("serialize project index: {e}"))?;
99        let tmp = index_path.with_extension(format!("{}.tmp", std::process::id()));
100        std::fs::write(&tmp, json).map_err(|e| format!("write project index: {e}"))?;
101        restrict_file_permissions(&tmp);
102        std::fs::rename(tmp, index_path).map_err(|e| format!("commit project index: {e}"))
103    })();
104    let _ = FileExt::unlock(&lock);
105    result
106}
107
108#[cfg(unix)]
109fn restrict_file_permissions(path: &std::path::Path) {
110    use std::os::unix::fs::PermissionsExt;
111    let perms = std::fs::Permissions::from_mode(0o600);
112    let _ = std::fs::set_permissions(path, perms);
113}
114
115#[cfg(not(unix))]
116fn restrict_file_permissions(_path: &std::path::Path) {}
117
118fn validate_session_id(id: &str) -> Result<(), String> {
119    if id.is_empty()
120        || id == "latest"
121        || id.starts_with('.')
122        || id.contains('/')
123        || id.contains('\\')
124        || id.contains(std::path::MAIN_SEPARATOR)
125    {
126        return Err("invalid session id".to_string());
127    }
128    Ok(())
129}
130
131fn persist_session_facts(session: &SessionState) -> Result<(), String> {
132    let Some(project_root) = session
133        .project_root
134        .as_deref()
135        .filter(|project_root| !project_root.trim().is_empty())
136    else {
137        return Ok(());
138    };
139
140    let facts = extract_session_facts(session);
141    if facts.is_empty() {
142        return Ok(());
143    }
144
145    let mut knowledge = crate::core::knowledge::ProjectKnowledge::load_or_create(project_root);
146    for fact in facts {
147        knowledge.add_fact(fact);
148    }
149    knowledge.save()
150}
151
152impl PreparedSave {
153    /// Writes the pre-serialized session data, latest pointer, and compaction
154    /// snapshot to disk atomically. A per-session file lock and version check
155    /// make deferred saves monotonic even when background tasks finish out of
156    /// order.
157    pub fn write_to_disk(self) -> Result<(), String> {
158        use fs2::FileExt;
159
160        if !self.dir.exists() {
161            std::fs::create_dir_all(&self.dir).map_err(|e| e.to_string())?;
162        }
163        let lock_path = self.dir.join(format!(".{}.save.lock", self.id));
164        let lock = std::fs::OpenOptions::new()
165            .create(true)
166            .truncate(false)
167            .write(true)
168            .open(lock_path)
169            .map_err(|e| format!("open session save lock: {e}"))?;
170        lock.lock_exclusive()
171            .map_err(|e| format!("lock session save: {e}"))?;
172
173        let result = (|| {
174            let path = self.dir.join(format!("{}.json", self.id));
175            if persisted_session_version(&path).is_some_and(|version| version > self.version) {
176                return Ok(());
177            }
178            let tmp = self.dir.join(format!(".{}.json.tmp", self.id));
179            std::fs::write(&tmp, &self.json).map_err(|e| e.to_string())?;
180            restrict_file_permissions(&tmp);
181            std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
182
183            let latest_path = self.dir.join("latest.json");
184            let latest_tmp = self.dir.join(".latest.json.tmp");
185            std::fs::write(&latest_tmp, &self.pointer_json).map_err(|e| e.to_string())?;
186            restrict_file_permissions(&latest_tmp);
187            std::fs::rename(&latest_tmp, &latest_path).map_err(|e| e.to_string())?;
188
189            if let Some(snapshot) = self.compaction_snapshot {
190                let snap_path = self.dir.join(format!("{}_snapshot.txt", self.id));
191                if let Err(error) = crate::core::atomic_fs::write_bytes_with_fallback(
192                    &snap_path,
193                    snapshot.as_bytes(),
194                    None,
195                ) {
196                    tracing::debug!("lean-ctx: compaction snapshot update skipped: {error}");
197                } else {
198                    restrict_file_permissions(&snap_path);
199                }
200            }
201            if let Some(project_root) = self.project_index_root.as_deref()
202                && let Err(error) = update_project_index(&self.dir, project_root, &self.id)
203            {
204                tracing::debug!("lean-ctx: session warm-history index update skipped: {error}");
205            }
206            Ok(())
207        })();
208        let _ = FileExt::unlock(&lock);
209        result
210    }
211}
212
213fn persisted_session_version(path: &std::path::Path) -> Option<u32> {
214    let value: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
215    value["version"].as_u64()?.try_into().ok()
216}
217
218impl SessionState {
219    /// Counts locally recorded decisions from the trailing seven days.
220    #[must_use]
221    pub fn decision_count_this_week() -> u64 {
222        let cutoff = Utc::now() - chrono::Duration::days(7);
223        Self::list_sessions()
224            .into_iter()
225            .filter_map(|summary| Self::load_by_id(&summary.id))
226            .flat_map(|session| session.decisions)
227            .filter(|decision| decision.timestamp >= cutoff)
228            .count()
229            .try_into()
230            .unwrap_or(u64::MAX)
231    }
232
233    /// Serializes and writes the session state to disk synchronously.
234    pub fn save(&mut self) -> Result<(), String> {
235        let prepared = self.prepare_save()?;
236        match prepared.write_to_disk() {
237            Ok(()) => Ok(()),
238            Err(e) => {
239                self.stats.unsaved_changes = BATCH_SAVE_INTERVAL;
240                Err(e)
241            }
242        }
243    }
244
245    /// Serialize session state while holding the lock (CPU-only), reset the
246    /// unsaved counter, and return a `PreparedSave` whose I/O can be deferred
247    /// to a background thread via `write_to_disk()`.
248    pub fn prepare_save(&mut self) -> Result<PreparedSave, String> {
249        if self
250            .project_root
251            .as_deref()
252            .is_some_and(|root| normalized_safe_project_root(root).is_none())
253        {
254            return Err(
255                "refusing to persist a session for a broad or unsafe project root".to_string(),
256            );
257        }
258        let dir = sessions_dir().ok_or("cannot determine home directory")?;
259        let compaction_snapshot = if self.stats.total_tool_calls > 0 {
260            Some(self.build_compaction_snapshot())
261        } else {
262            None
263        };
264        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
265        let pointer_json = serde_json::to_string(&LatestPointer {
266            id: self.id.clone(),
267        })
268        .map_err(|e| e.to_string())?;
269        self.stats.unsaved_changes = 0;
270        // #717: arm the time-based flush window.
271        self.last_flush = Some(std::time::Instant::now());
272        Ok(PreparedSave {
273            dir,
274            id: self.id.clone(),
275            version: self.version,
276            json,
277            pointer_json,
278            compaction_snapshot,
279            project_index_root: self
280                .project_root
281                .as_deref()
282                .and_then(normalized_safe_project_root),
283        })
284    }
285
286    /// Load the bounded warm-history set for one safe project root.
287    ///
288    /// There is intentionally no legacy full-store fallback: cache warming is
289    /// optional, while scanning every persisted session on each MCP launch is
290    /// not acceptable under concurrent agent load. New saves populate the
291    /// index; legacy sessions remain available through explicit session tools.
292    pub(crate) fn load_recent_for_project_root(project_root: &str, limit: usize) -> Vec<Self> {
293        let Some(project_root) = normalized_safe_project_root(project_root) else {
294            return Vec::new();
295        };
296        let Some(dir) = sessions_dir() else {
297            return Vec::new();
298        };
299        let Some(index) = std::fs::read_to_string(project_index_path(&dir, &project_root))
300            .ok()
301            .and_then(|json| serde_json::from_str::<ProjectSessionIndex>(&json).ok())
302            .filter(|index| index.version == 1 && index.project_root == project_root)
303        else {
304            return Vec::new();
305        };
306
307        index
308            .session_ids
309            .iter()
310            .rev()
311            .take(limit.min(PROJECT_HISTORY_LIMIT))
312            .filter_map(|id| Self::load_by_id(id))
313            .collect()
314    }
315
316    /// Loads the most recent session matching the current working directory's
317    /// project root.
318    ///
319    /// Returns `None` (a fresh session) rather than falling back to the global
320    /// `latest.json` pointer: that unconditional fallback bypassed project-root
321    /// matching and was the root cause of cross-project session leakage — one
322    /// project's findings/decisions/knowledge bleeding into another project's
323    /// first session. The correct project session is loaded later from the MCP
324    /// `roots` handshake (`load_latest_for_project_root`).
325    ///
326    /// Also refuses to scope to a broad/unsafe cwd (e.g. the MCP daemon's HOME),
327    /// which would otherwise resurrect the contaminated "HOME mega-session".
328    pub fn load_latest() -> Option<Self> {
329        let cwd = std::env::current_dir().ok()?;
330        if crate::core::pathutil::is_broad_or_unsafe_root(&cwd) {
331            return None;
332        }
333        Self::load_latest_for_project_root(&cwd.to_string_lossy())
334    }
335
336    /// Loads the session referenced by the global `latest.json` pointer,
337    /// regardless of project. Intended only for explicit, cross-project UX
338    /// (e.g. `lean-ctx session` status from an arbitrary directory) — never for
339    /// injecting knowledge into a new project's context. Prefer `load_latest`.
340    pub fn load_global_latest_pointer() -> Option<Self> {
341        let dir = sessions_dir()?;
342        let latest_path = dir.join("latest.json");
343        let pointer_json = std::fs::read_to_string(&latest_path).ok()?;
344        let pointer: LatestPointer = serde_json::from_str(&pointer_json).ok()?;
345        Self::load_by_id(&pointer.id)
346    }
347
348    /// Loads the most recent session matching a specific project root.
349    pub fn load_latest_for_project_root(project_root: &str) -> Option<Self> {
350        // Broad roots ("/", HOME, agent sandboxes) never own a session. Bail out
351        // BEFORE scanning: the daemon boots with cwd "/" and previously walked
352        // every stored session here, stat-ing each session's project_root /
353        // shell_cwd. For roots under ~/Documents that probe popped the macOS
354        // TCC prompt in lean-ctx's name on every launchd (re)start (#356) —
355        // and `shell_cwd.starts_with("/")` could even leak an arbitrary
356        // project's session into the broad-root context.
357        if crate::core::pathutil::is_broad_or_unsafe_root(std::path::Path::new(project_root)) {
358            return None;
359        }
360        let dir = sessions_dir()?;
361        let target_root =
362            crate::core::pathutil::safe_canonicalize_or_self(std::path::Path::new(project_root));
363        let mut latest_match: Option<Self> = None;
364
365        for entry in std::fs::read_dir(&dir).ok()?.flatten() {
366            let path = entry.path();
367            if path.extension().and_then(|e| e.to_str()) != Some("json") {
368                continue;
369            }
370            if path.file_name().and_then(|n| n.to_str()) == Some("latest.json") {
371                continue;
372            }
373
374            let Some(id) = path.file_stem().and_then(|n| n.to_str()) else {
375                continue;
376            };
377            let Some(session) = Self::load_by_id(id) else {
378                continue;
379            };
380
381            if !session_matches_project_root(&session, &target_root) {
382                continue;
383            }
384
385            if latest_match
386                .as_ref()
387                .is_none_or(|existing| session.updated_at > existing.updated_at)
388            {
389                latest_match = Some(session);
390            }
391        }
392
393        latest_match
394    }
395
396    /// Loads a specific session from disk by its unique ID.
397    pub fn load_by_id(id: &str) -> Option<Self> {
398        validate_session_id(id).ok()?;
399        let dir = sessions_dir()?;
400        let path = dir.join(format!("{id}.json"));
401        let json = std::fs::read_to_string(&path).ok()?;
402        let session: Self = serde_json::from_str(&json).ok()?;
403        Some(normalize_loaded_session(session))
404    }
405
406    /// Deletes a saved session and its compaction snapshot.
407    ///
408    /// If the deleted session is the global latest pointer, the pointer is
409    /// moved to the newest remaining session or removed when none remain.
410    pub fn delete_session(id: &str) -> Result<bool, String> {
411        validate_session_id(id)?;
412        let Some(dir) = sessions_dir() else {
413            return Ok(false);
414        };
415        let path = dir.join(format!("{id}.json"));
416        if !path.exists() {
417            return Ok(false);
418        }
419
420        if let Some(session) = Self::load_by_id(id) {
421            persist_session_facts(&session)?;
422        }
423        std::fs::remove_file(&path).map_err(|e| e.to_string())?;
424
425        let snapshot = dir.join(format!("{id}_snapshot.txt"));
426        match std::fs::remove_file(&snapshot) {
427            Ok(()) => {}
428            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
429            Err(e) => return Err(e.to_string()),
430        }
431
432        let latest_path = dir.join("latest.json");
433        let points_to_deleted = std::fs::read_to_string(&latest_path)
434            .ok()
435            .and_then(|json| serde_json::from_str::<LatestPointer>(&json).ok())
436            .is_some_and(|pointer| pointer.id == id);
437        if points_to_deleted {
438            if let Some(next) = Self::list_sessions().into_iter().next() {
439                let latest_tmp = dir.join(".latest.json.tmp");
440                let pointer_json = serde_json::to_string(&LatestPointer { id: next.id })
441                    .map_err(|e| e.to_string())?;
442                std::fs::write(&latest_tmp, pointer_json).map_err(|e| e.to_string())?;
443                restrict_file_permissions(&latest_tmp);
444                std::fs::rename(&latest_tmp, &latest_path).map_err(|e| e.to_string())?;
445            } else {
446                match std::fs::remove_file(&latest_path) {
447                    Ok(()) => {}
448                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
449                    Err(e) => return Err(e.to_string()),
450                }
451            }
452        }
453
454        Ok(true)
455    }
456
457    /// Lists all saved sessions as summaries, sorted by most recently updated.
458    pub fn list_sessions() -> Vec<SessionSummary> {
459        let Some(dir) = sessions_dir() else {
460            return Vec::new();
461        };
462
463        let mut summaries = Vec::new();
464        if let Ok(entries) = std::fs::read_dir(&dir) {
465            for entry in entries.flatten() {
466                let path = entry.path();
467                if path.extension().and_then(|e| e.to_str()) != Some("json") {
468                    continue;
469                }
470                if path.file_name().and_then(|n| n.to_str()) == Some("latest.json") {
471                    continue;
472                }
473                if let Ok(json) = std::fs::read_to_string(&path)
474                    && let Ok(session) = serde_json::from_str::<SessionState>(&json)
475                {
476                    summaries.push(SessionSummary {
477                        id: session.id,
478                        started_at: session.started_at,
479                        updated_at: session.updated_at,
480                        version: session.version,
481                        task: session.task.as_ref().map(|t| t.description.clone()),
482                        tool_calls: session.stats.total_tool_calls,
483                        tokens_saved: session.stats.total_tokens_saved,
484                        project_root: session.project_root,
485                    });
486                }
487            }
488        }
489
490        summaries.sort_by_key(|x| std::cmp::Reverse(x.updated_at));
491        summaries
492    }
493
494    /// Scans all saved sessions for contaminated ones — those rooted at a
495    /// broad/unsafe path (HOME, filesystem root, agent sandbox dir) without a
496    /// real project marker, i.e. the historic "HOME mega-session" artifact.
497    ///
498    /// Returns `(found, quarantined)` where `found` is `(id, root)` pairs. When
499    /// `apply` is true, each offending session file is moved to a
500    /// `sessions/quarantine/` subdirectory (non-destructive) instead of being
501    /// loaded into any project's context.
502    pub fn doctor_quarantine_unsafe_roots(apply: bool) -> (Vec<(String, String)>, usize) {
503        let mut found: Vec<(String, String)> = Vec::new();
504        let mut quarantined = 0usize;
505        let Some(dir) = sessions_dir() else {
506            return (found, quarantined);
507        };
508        let Ok(entries) = std::fs::read_dir(&dir) else {
509            return (found, quarantined);
510        };
511        for entry in entries.flatten() {
512            let path = entry.path();
513            if path.extension().and_then(|e| e.to_str()) != Some("json") {
514                continue;
515            }
516            let Some(id) = path.file_stem().and_then(|n| n.to_str()) else {
517                continue;
518            };
519            if id == "latest" || id.starts_with('.') {
520                continue;
521            }
522            let Some(session) = Self::load_by_id(id) else {
523                continue;
524            };
525            let Some(root) = session.project_root.as_deref() else {
526                continue;
527            };
528            let root_path = std::path::Path::new(root);
529            if crate::core::pathutil::is_broad_or_unsafe_root(root_path) {
530                found.push((id.to_string(), root.to_string()));
531                if apply {
532                    let q_dir = dir.join("quarantine");
533                    if std::fs::create_dir_all(&q_dir).is_ok()
534                        && std::fs::rename(&path, q_dir.join(format!("{id}.json"))).is_ok()
535                    {
536                        quarantined += 1;
537                    }
538                }
539            }
540        }
541        (found, quarantined)
542    }
543
544    /// Deletes sessions older than `max_age_days`, preserving the latest. Returns count removed.
545    pub fn cleanup_old_sessions(max_age_days: i64) -> u32 {
546        let Some(dir) = sessions_dir() else { return 0 };
547
548        let cutoff = Utc::now() - chrono::Duration::days(max_age_days);
549        let latest = Self::load_latest().map(|s| s.id);
550        let mut removed = 0u32;
551
552        if let Ok(entries) = std::fs::read_dir(&dir) {
553            for entry in entries.flatten() {
554                let path = entry.path();
555                if path.extension().and_then(|e| e.to_str()) != Some("json") {
556                    continue;
557                }
558                let filename = path.file_stem().and_then(|n| n.to_str()).unwrap_or("");
559                if filename == "latest" || filename.starts_with('.') {
560                    continue;
561                }
562                if latest.as_deref() == Some(filename) {
563                    continue;
564                }
565                if let Ok(json) = std::fs::read_to_string(&path)
566                    && let Ok(session) = serde_json::from_str::<SessionState>(&json)
567                    && session.updated_at < cutoff
568                    && std::fs::read_to_string(&path)
569                        .ok()
570                        .and_then(|content| serde_json::from_str::<Self>(&content).ok())
571                        .is_none_or(|session| persist_session_facts(&session).is_ok())
572                    && std::fs::remove_file(&path).is_ok()
573                {
574                    removed += 1;
575                }
576            }
577        }
578
579        removed
580    }
581}
582
583#[cfg(test)]
584mod tests {
585    use super::SessionState;
586
587    #[test]
588    fn recent_project_sessions_use_bounded_index_without_scanning_legacy_store() {
589        let _data = crate::core::data_dir::isolated_data_dir();
590        let project = tempfile::tempdir().expect("project tempdir");
591        let root = project.path().to_string_lossy().to_string();
592
593        for id in ["first", "second", "third"] {
594            let mut session = SessionState::new();
595            session.id = id.to_string();
596            session.project_root = Some(root.clone());
597            session.save().expect("save indexed session");
598        }
599
600        // A malformed legacy artifact proves the hot path consults only the
601        // per-project index, never `list_sessions()` as a hidden fallback.
602        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
603        std::fs::write(sessions.join("legacy-unreadable.json"), "not json")
604            .expect("write legacy artifact");
605
606        let ids: Vec<_> = SessionState::load_recent_for_project_root(&root, 8)
607            .into_iter()
608            .map(|session| session.id)
609            .collect();
610        assert_eq!(ids, ["third", "second", "first"]);
611    }
612
613    #[test]
614    fn recent_project_sessions_refuse_broad_roots() {
615        let _data = crate::core::data_dir::isolated_data_dir();
616        assert!(SessionState::load_recent_for_project_root("/", 8).is_empty());
617    }
618
619    #[test]
620    fn broad_root_sessions_are_never_persisted() {
621        let _data = crate::core::data_dir::isolated_data_dir();
622        let mut session = SessionState::new();
623        session.project_root = Some("/".to_string());
624
625        let error = session
626            .save()
627            .expect_err("broad root save must be rejected");
628
629        assert!(error.contains("broad or unsafe"));
630        assert!(
631            crate::core::session::paths::sessions_dir()
632                .expect("sessions dir")
633                .read_dir()
634                .map_or(true, |mut entries| entries.next().is_none())
635        );
636    }
637
638    #[test]
639    fn deferred_save_cannot_replace_a_newer_session_version() {
640        let _data = crate::core::data_dir::isolated_data_dir();
641        let mut session = SessionState::new();
642        let id = session.id.clone();
643        let older = session.prepare_save().expect("prepare older save");
644        session.increment();
645        let expected_version = session.version;
646        let newer = session.prepare_save().expect("prepare newer save");
647
648        newer.write_to_disk().expect("write newer save");
649        older.write_to_disk().expect("skip older save");
650
651        assert_eq!(
652            SessionState::load_by_id(&id)
653                .expect("load persisted session")
654                .version,
655            expected_version
656        );
657    }
658}