Skip to main content

adk_harness/snapshot/
runtime.rs

1//! `Snapshots`: walking, hashing, storing and collecting a workspace's snapshots
2//! (spec 3.1 §7.27).
3
4use std::collections::{BTreeMap, HashMap, HashSet};
5use std::path::{Path, PathBuf};
6use std::sync::{Arc, Mutex};
7use std::time::{Duration, SystemTime};
8
9use adk_core::{ErrorCategory, ReadonlyContext, Result};
10use chrono::Utc;
11use serde_json::{Value, json};
12
13use super::objects::{SnapshotObjects, object_id, root_digest, snapshot_error};
14use super::store::{
15    FileEntry, PlanMark, SnapshotKind, SnapshotRecord, SnapshotStore, TranscriptTail,
16};
17use super::walk::{EntryKind, ExcludeFilter, NotCovered, WalkOptions, WalkedFile, walk};
18use super::{NOT_COVERED_LISTED, SnapshotConfig};
19
20/// A file whose modification time is this close to the walk is hashed again next time:
21/// a write in the same clock tick would leave its size and time unchanged.
22const RACY_WINDOW: Duration = Duration::from_secs(2);
23
24/// Objects younger than this are never collected: another process may be writing the
25/// snapshot that references them.
26const GC_GRACE: Duration = Duration::from_secs(600);
27
28/// Most (session, run) pairs remembered so a run is snapshotted as a turn once.
29const TURNS_REMEMBERED: usize = 4096;
30
31/// What to snapshot and what to record with it.
32///
33/// # Example
34///
35/// ```rust
36/// use adk_harness::snapshot::{SnapshotKind, SnapshotRequest};
37///
38/// let request = SnapshotRequest::new("adk-rust", "alice", "s1", "inv-1", SnapshotKind::Destructive);
39/// assert_eq!(request.kind, SnapshotKind::Destructive);
40/// ```
41#[derive(Clone, Debug)]
42#[non_exhaustive]
43pub struct SnapshotRequest {
44    /// The application.
45    pub app_name: String,
46    /// The user.
47    pub user_id: String,
48    /// The session.
49    pub session_id: String,
50    /// The run it is taken in.
51    pub invocation_id: String,
52    /// Why it is taken.
53    pub kind: SnapshotKind,
54    /// The plan step it precedes.
55    pub step: Option<String>,
56    /// Where the plan stands.
57    pub plan: Option<PlanMark>,
58    /// For a rewind: the events it removes.
59    pub transcript: Option<TranscriptTail>,
60}
61
62impl SnapshotRequest {
63    /// A snapshot of `kind` for the session, in the run `invocation_id`.
64    pub fn new(
65        app_name: impl Into<String>,
66        user_id: impl Into<String>,
67        session_id: impl Into<String>,
68        invocation_id: impl Into<String>,
69        kind: SnapshotKind,
70    ) -> Self {
71        Self {
72            app_name: app_name.into(),
73            user_id: user_id.into(),
74            session_id: session_id.into(),
75            invocation_id: invocation_id.into(),
76            kind,
77            step: None,
78            plan: None,
79            transcript: None,
80        }
81    }
82
83    /// A snapshot of `kind` for the run `ctx` describes.
84    pub fn for_context(ctx: &dyn ReadonlyContext, kind: SnapshotKind) -> Self {
85        Self::new(ctx.app_name(), ctx.user_id(), ctx.session_id(), ctx.invocation_id(), kind)
86    }
87
88    /// Records the plan step it precedes.
89    #[must_use]
90    pub fn step(mut self, step: impl Into<String>) -> Self {
91        self.step = Some(step.into());
92        self
93    }
94
95    /// Records where the plan stands.
96    #[must_use]
97    pub fn plan(mut self, plan: Option<PlanMark>) -> Self {
98        self.plan = plan;
99        self
100    }
101
102    /// Records the events a rewind removes.
103    #[must_use]
104    pub fn transcript(mut self, tail: TranscriptTail) -> Self {
105        self.transcript = Some(tail);
106        self
107    }
108}
109
110/// What a snapshot holds, as `harness.snapshot.taken` records it (spec 3.1 §9.3).
111#[derive(Clone, Debug, PartialEq, Eq)]
112pub struct SnapshotInfo {
113    /// The snapshot's id.
114    pub id: String,
115    /// Why it was taken.
116    pub kind: SnapshotKind,
117    /// How many files it holds.
118    pub files: usize,
119    /// Bytes it added to the object store.
120    pub bytes_new: u64,
121    /// Whether the walk stopped at `max_files`.
122    pub partial: bool,
123    /// How many files it left out.
124    pub not_covered: usize,
125}
126
127impl SnapshotInfo {
128    /// The extension fields of `harness.snapshot.taken`.
129    pub fn audit_fields(&self) -> Value {
130        json!({
131            "snapshotId": self.id,
132            "kind": self.kind.as_str(),
133            "files": self.files,
134            "bytesNew": self.bytes_new,
135            "partial": self.partial,
136            "notCovered": self.not_covered,
137        })
138    }
139}
140
141/// The current tree, hashed but not stored.
142#[derive(Clone, Debug, Default)]
143pub struct TreeScan {
144    /// The files, sorted by path.
145    pub files: Vec<FileEntry>,
146    /// Whether the walk stopped at `max_files`.
147    pub partial: bool,
148    /// Files the walk saw and left out.
149    pub not_covered: Vec<NotCovered>,
150}
151
152/// One file's stat and hash, so an unchanged file is not read again.
153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
154struct Stat {
155    len: u64,
156    mtime_ns: u64,
157    inode: u64,
158}
159
160#[derive(Default)]
161struct StatCache {
162    seeded: bool,
163    entries: HashMap<String, (Stat, String)>,
164}
165
166/// A workspace's snapshots (spec 3.1 §7.27): the walker over the root, the stat cache, the
167/// object store and the record store, with retention and garbage collection.
168///
169/// Built by [`HarnessAgentBuilder::snapshots`](crate::HarnessAgentBuilder::snapshots) and
170/// reached through [`HarnessRuntime::snapshots`](crate::HarnessRuntime::snapshots) or
171/// [`Harness::snapshots`](crate::Harness::snapshots). [`take`](Self::take) is the "snapshot
172/// now" a governed path calls before a `Destructive` call (§7.30).
173///
174/// # Example
175///
176/// ```rust
177/// use std::sync::Arc;
178/// use adk_harness::snapshot::{
179///     InMemorySnapshotObjects, InMemorySnapshotStore, SnapshotConfig, SnapshotKind,
180///     SnapshotRequest, Snapshots,
181/// };
182///
183/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
184/// let dir = tempfile::tempdir().unwrap();
185/// std::fs::write(dir.path().join("a.txt"), "one").unwrap();
186/// let snapshots = Snapshots::new(
187///     SnapshotConfig::default(),
188///     &adk_devtools::Workspace::new(dir.path()),
189///     Arc::new(InMemorySnapshotStore::new()),
190///     Arc::new(InMemorySnapshotObjects::new()),
191/// )
192/// .unwrap();
193/// let info = snapshots
194///     .take(SnapshotRequest::new("app", "alice", "s1", "inv-1", SnapshotKind::Turn))
195///     .await
196///     .unwrap();
197/// assert_eq!(info.files, 1);
198/// # });
199/// ```
200pub struct Snapshots {
201    config: SnapshotConfig,
202    root: PathBuf,
203    root_digest: String,
204    exclude: Option<ExcludeFilter>,
205    store: Arc<dyn SnapshotStore>,
206    objects: Arc<dyn SnapshotObjects>,
207    cache: Arc<Mutex<StatCache>>,
208    turns: Mutex<HashSet<String>>,
209    gate: tokio::sync::Mutex<()>,
210}
211
212impl std::fmt::Debug for Snapshots {
213    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214        f.debug_struct("Snapshots")
215            .field("root", &self.root)
216            .field("config", &self.config)
217            .field("objects", &self.objects)
218            .finish_non_exhaustive()
219    }
220}
221
222fn walk_error(error: impl std::fmt::Display) -> adk_core::AdkError {
223    snapshot_error(
224        "harness.snapshot.walk",
225        ErrorCategory::Internal,
226        format!("the snapshot walk stopped: {error}"),
227    )
228}
229
230impl Snapshots {
231    /// Snapshots of `workspace`'s root under `config`, recorded in `store` with contents in
232    /// `objects`.
233    ///
234    /// # Errors
235    ///
236    /// Returns `harness.snapshot.inside_workspace` when the objects would be kept inside
237    /// the workspace (I68), or `harness.snapshot.io` when the root cannot be resolved.
238    pub fn new(
239        config: SnapshotConfig,
240        workspace: &adk_devtools::Workspace,
241        store: Arc<dyn SnapshotStore>,
242        objects: Arc<dyn SnapshotObjects>,
243    ) -> Result<Self> {
244        let root = workspace.root().canonicalize().map_err(|error| {
245            snapshot_error(
246                "harness.snapshot.io",
247                ErrorCategory::InvalidInput,
248                format!(
249                    "the workspace {} cannot be snapshotted: {error}",
250                    workspace.root().display()
251                ),
252            )
253        })?;
254        if let Some(location) = objects.location() {
255            let location = canonical_prefix(location);
256            if location.starts_with(&root) {
257                return Err(snapshot_error(
258                    "harness.snapshot.inside_workspace",
259                    ErrorCategory::InvalidInput,
260                    format!(
261                        "snapshot objects at {} would be inside the workspace {} they snapshot; \
262                         keep them beside harness.db instead (spec 3.1 I68)",
263                        location.display(),
264                        root.display()
265                    ),
266                ));
267            }
268        }
269        let excluder = workspace.clone();
270        let exclude: ExcludeFilter = Arc::new(move |path: &Path| excluder.is_excluded(path));
271        Ok(Self {
272            root_digest: root_digest(&root),
273            root,
274            config,
275            exclude: Some(exclude),
276            store,
277            objects,
278            cache: Arc::default(),
279            turns: Mutex::default(),
280            gate: tokio::sync::Mutex::new(()),
281        })
282    }
283
284    /// The configuration.
285    pub fn config(&self) -> &SnapshotConfig {
286        &self.config
287    }
288
289    /// The canonical workspace root.
290    pub fn root(&self) -> &Path {
291        &self.root
292    }
293
294    /// The root's digest, which names its object directory and keys its records.
295    pub fn root_digest(&self) -> &str {
296        &self.root_digest
297    }
298
299    /// The record store.
300    pub fn store(&self) -> &Arc<dyn SnapshotStore> {
301        &self.store
302    }
303
304    /// The object store.
305    pub fn objects(&self) -> &Arc<dyn SnapshotObjects> {
306        &self.objects
307    }
308
309    pub(crate) fn walk_options(&self) -> WalkOptions {
310        WalkOptions {
311            max_files: self.config.max_files,
312            max_file_bytes: Some(self.config.max_file_bytes),
313            skip_dirs: self.config.skip_dirs.clone(),
314            enter: Vec::new(),
315            git_entries: None,
316            gitignore: true,
317            exclude: self.exclude.clone(),
318        }
319    }
320
321    /// Whether the run `invocation_id` of the session already has its turn snapshot;
322    /// marks it when not.
323    pub(crate) fn first_turn_snapshot(&self, session: &str, invocation_id: &str) -> bool {
324        let mut turns = self.turns.lock().unwrap_or_else(|e| e.into_inner());
325        if turns.len() >= TURNS_REMEMBERED {
326            turns.clear();
327        }
328        turns.insert(format!("{session}\u{1f}{invocation_id}"))
329    }
330
331    /// Takes a snapshot now: walks the root, stores what changed, records it and applies
332    /// retention (spec 3.1 §7.27). The "snapshot now" a `Destructive` call takes (§7.30).
333    ///
334    /// # Errors
335    ///
336    /// Returns the object or record store's error; nothing is recorded then.
337    pub async fn take(&self, request: SnapshotRequest) -> Result<SnapshotInfo> {
338        let _gate = self.gate.lock().await;
339        self.seed_cache().await;
340        let created_at = Utc::now();
341        let (files, partial, not_covered, bytes_new) = self.hash_tree(true).await?;
342        let manifest = serde_json::to_vec(&files)
343            .map_err(|error| crate::fsutil::serialize_error("snapshot manifest", &error))?;
344        let files_object = object_id(&manifest);
345        let objects = self.objects.clone();
346        let (id_for_put, manifest_bytes) = (files_object.clone(), manifest);
347        let manifest_new =
348            tokio::task::spawn_blocking(move || objects.put(&id_for_put, &manifest_bytes))
349                .await
350                .map_err(walk_error)??;
351        let listed: Vec<NotCovered> =
352            not_covered.iter().take(NOT_COVERED_LISTED).cloned().collect();
353        let record = SnapshotRecord {
354            id: format!("snap-{}", uuid::Uuid::new_v4().simple()),
355            app_name: request.app_name,
356            user_id: request.user_id,
357            session_id: request.session_id,
358            root: self.root_digest.clone(),
359            created_at,
360            kind: request.kind,
361            invocation_id: request.invocation_id,
362            step: request.step,
363            files_object,
364            file_count: files.len(),
365            total_bytes: files.iter().map(|file| file.len).sum(),
366            bytes_new: bytes_new + manifest_new,
367            partial,
368            not_covered_more: not_covered.len() - listed.len(),
369            not_covered: listed,
370            plan: request.plan,
371            transcript: request.transcript,
372            rewound: None,
373        };
374        self.store.put(&record).await?;
375        let info = SnapshotInfo {
376            id: record.id.clone(),
377            kind: record.kind,
378            files: record.file_count,
379            bytes_new: record.bytes_new,
380            partial,
381            not_covered: not_covered.len(),
382        };
383        tracing::debug!(
384            snapshot.id = %info.id,
385            snapshot.kind = %info.kind,
386            snapshot.files = info.files,
387            snapshot.bytes_new = info.bytes_new,
388            snapshot.partial = info.partial,
389            "snapshot taken"
390        );
391        if let Err(error) = self.retain(&record).await {
392            tracing::warn!(error = %error, "snapshot retention did not complete");
393        }
394        Ok(info)
395    }
396
397    /// The current tree, hashed through the stat cache, nothing stored.
398    ///
399    /// # Errors
400    ///
401    /// Returns `harness.snapshot.walk` when the walk cannot run.
402    pub async fn scan(&self) -> Result<TreeScan> {
403        self.seed_cache().await;
404        let (files, partial, not_covered, _) = self.hash_tree(false).await?;
405        Ok(TreeScan { files, partial, not_covered })
406    }
407
408    /// The file list of `record`.
409    ///
410    /// # Errors
411    ///
412    /// Returns `harness.snapshot.missing_object` when its list was collected.
413    pub async fn files(&self, record: &SnapshotRecord) -> Result<Vec<FileEntry>> {
414        let objects = self.objects.clone();
415        let id = record.files_object.clone();
416        let bytes =
417            tokio::task::spawn_blocking(move || objects.get(&id)).await.map_err(walk_error)??;
418        serde_json::from_slice(&bytes).map_err(|error| {
419            snapshot_error(
420                "harness.snapshot.corrupt_object",
421                ErrorCategory::Internal,
422                format!("snapshot {}'s file list does not parse: {error}", record.id),
423            )
424        })
425    }
426
427    /// The content of the object `id`.
428    ///
429    /// # Errors
430    ///
431    /// As [`SnapshotObjects::get`].
432    pub async fn object(&self, id: &str) -> Result<Vec<u8>> {
433        let objects = self.objects.clone();
434        let id = id.to_string();
435        tokio::task::spawn_blocking(move || objects.get(&id)).await.map_err(walk_error)?
436    }
437
438    /// The session's snapshots, oldest first.
439    ///
440    /// # Errors
441    ///
442    /// Returns the record store's error.
443    pub async fn list(&self, app: &str, user: &str, session: &str) -> Result<Vec<SnapshotRecord>> {
444        Ok(self
445            .store
446            .list_session(app, user, session)
447            .await?
448            .into_iter()
449            .filter(|record| record.root == self.root_digest)
450            .collect())
451    }
452
453    /// Removes the session's snapshots and the objects only they referenced: a session's
454    /// snapshots go with the session (spec 3.1 §7.27). Returns how many were removed.
455    ///
456    /// # Errors
457    ///
458    /// Returns the record or object store's error.
459    pub async fn forget_session(&self, app: &str, user: &str, session: &str) -> Result<usize> {
460        let _gate = self.gate.lock().await;
461        let ids: Vec<String> =
462            self.list(app, user, session).await?.into_iter().map(|record| record.id).collect();
463        if ids.is_empty() {
464            return Ok(0);
465        }
466        self.store.delete(&ids).await?;
467        self.collect_garbage().await?;
468        Ok(ids.len())
469    }
470
471    /// Seeds the stat cache from the workspace's latest snapshot, once per process.
472    async fn seed_cache(&self) {
473        if self.cache.lock().unwrap_or_else(|e| e.into_inner()).seeded {
474            return;
475        }
476        let latest = match self.store.list_root(&self.root_digest).await {
477            Ok(records) => records.into_iter().last(),
478            Err(_) => None,
479        };
480        let mut seeded = HashMap::new();
481        if let Some(latest) = latest
482            && let Ok(files) = self.files(&latest).await
483        {
484            let walked_at = u64::try_from(latest.created_at.timestamp_nanos_opt().unwrap_or(0))
485                .unwrap_or(0)
486                .saturating_sub(RACY_WINDOW.as_nanos() as u64);
487            for file in files {
488                if file.link.is_none() && file.mtime_ns < walked_at {
489                    seeded.insert(
490                        file.path.clone(),
491                        (
492                            Stat { len: file.len, mtime_ns: file.mtime_ns, inode: file.inode },
493                            file.sha256,
494                        ),
495                    );
496                }
497            }
498        }
499        let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
500        if !cache.seeded {
501            cache.entries.extend(seeded);
502            cache.seeded = true;
503        }
504    }
505
506    /// Walks and hashes the tree off the async runtime; with `store`, puts every object
507    /// that is not stored yet. Returns the sorted entries, whether the walk was partial,
508    /// what it left out and the bytes it wrote.
509    async fn hash_tree(&self, store: bool) -> Result<(Vec<FileEntry>, bool, Vec<NotCovered>, u64)> {
510        let root = self.root.clone();
511        let options = self.walk_options();
512        let cache = self.cache.clone();
513        let objects = self.objects.clone();
514        tokio::task::spawn_blocking(move || {
515            let started = SystemTime::now()
516                .duration_since(std::time::UNIX_EPOCH)
517                .map_or(0, |since| u64::try_from(since.as_nanos()).unwrap_or(u64::MAX));
518            let racy_after = started.saturating_sub(RACY_WINDOW.as_nanos() as u64);
519            let tree = walk(&root, &options);
520            let mut entries = Vec::with_capacity(tree.files.len());
521            let mut not_covered = tree.not_covered;
522            let mut bytes_new = 0;
523            for file in tree.files {
524                match hash_file(&root, &file, &cache, objects.as_ref(), store, racy_after) {
525                    Ok((entry, written)) => {
526                        bytes_new += written;
527                        entries.push(entry);
528                    }
529                    // A file that vanished mid-walk is simply not in the snapshot.
530                    Err(HashFailure::Gone) => {}
531                    Err(HashFailure::Store(error)) => return Err(error),
532                }
533            }
534            entries.sort_by(|a, b| a.path.cmp(&b.path));
535            not_covered.sort_by(|a, b| a.path.cmp(&b.path));
536            Ok((entries, tree.partial, not_covered, bytes_new))
537        })
538        .await
539        .map_err(walk_error)?
540    }
541
542    /// Retention (spec 3.1 §7.27): the session keeps its last `keep_turns` turn snapshots
543    /// and what came after the oldest of them; the workspace keeps at most `max_bytes` of
544    /// objects, oldest snapshots dropped first; then unreferenced objects are collected.
545    async fn retain(&self, latest: &SnapshotRecord) -> Result<()> {
546        let session = self.list(&latest.app_name, &latest.user_id, &latest.session_id).await?;
547        let turns: Vec<&SnapshotRecord> =
548            session.iter().filter(|record| record.kind == SnapshotKind::Turn).collect();
549        let keep = self.config.keep_turns.max(1) as usize;
550        let mut drop: Vec<String> = Vec::new();
551        if turns.len() > keep {
552            let cutoff = turns[turns.len() - keep].created_at;
553            drop.extend(
554                session
555                    .iter()
556                    .filter(|record| record.created_at < cutoff && record.id != latest.id)
557                    .map(|record| record.id.clone()),
558            );
559        }
560        let objects = self.objects.clone();
561        let listed =
562            tokio::task::spawn_blocking(move || objects.list()).await.map_err(walk_error)??;
563        let total: u64 = listed.iter().map(|info| info.bytes).sum();
564        if total > self.config.max_bytes {
565            let sizes: HashMap<&str, u64> =
566                listed.iter().map(|info| (info.id.as_str(), info.bytes)).collect();
567            let mut records = self.store.list_root(&self.root_digest).await?;
568            records.retain(|record| !drop.contains(&record.id));
569            let mut counted: HashSet<String> = HashSet::new();
570            let mut used = 0_u64;
571            let mut over = false;
572            let mut lists: BTreeMap<String, Vec<FileEntry>> = BTreeMap::new();
573            for record in records.iter().rev() {
574                if over && record.id != latest.id {
575                    drop.push(record.id.clone());
576                    continue;
577                }
578                if !lists.contains_key(&record.files_object) {
579                    let files = self.files(record).await.unwrap_or_default();
580                    lists.insert(record.files_object.clone(), files);
581                }
582                let ids = std::iter::once(record.files_object.as_str()).chain(
583                    lists[&record.files_object]
584                        .iter()
585                        .filter(|f| f.link.is_none())
586                        .map(|f| f.sha256.as_str()),
587                );
588                for id in ids {
589                    if counted.insert(id.to_string()) {
590                        used += sizes.get(id).copied().unwrap_or(0);
591                    }
592                }
593                if used > self.config.max_bytes && record.id != latest.id {
594                    over = true;
595                    drop.push(record.id.clone());
596                }
597            }
598        }
599        if drop.is_empty() {
600            return Ok(());
601        }
602        tracing::info!(snapshots.dropped = drop.len(), "snapshot retention dropped old snapshots");
603        self.store.delete(&drop).await?;
604        self.collect_garbage().await
605    }
606
607    /// Removes every object no record of this workspace references, sparing recent ones.
608    async fn collect_garbage(&self) -> Result<()> {
609        let records = self.store.list_root(&self.root_digest).await?;
610        let mut referenced: HashSet<String> = HashSet::new();
611        for record in &records {
612            if !referenced.insert(record.files_object.clone()) {
613                continue;
614            }
615            // A list that cannot be read keeps everything: never collect blind.
616            let files = self.files(record).await?;
617            referenced.extend(files.into_iter().filter(|f| f.link.is_none()).map(|f| f.sha256));
618        }
619        let objects = self.objects.clone();
620        let removed = tokio::task::spawn_blocking(move || -> Result<usize> {
621            let now = SystemTime::now();
622            let mut removed = 0;
623            for info in objects.list()? {
624                let recent = info
625                    .modified
626                    .and_then(|modified| now.duration_since(modified).ok())
627                    .is_some_and(|age| age < GC_GRACE);
628                if !referenced.contains(&info.id) && !recent {
629                    objects.remove(&info.id)?;
630                    removed += 1;
631                }
632            }
633            Ok(removed)
634        })
635        .await
636        .map_err(walk_error)??;
637        if removed > 0 {
638            tracing::debug!(objects.removed = removed, "snapshot objects collected");
639        }
640        Ok(())
641    }
642}
643
644/// `path` with its longest existing prefix resolved, so a directory not created yet is
645/// compared as it will be.
646fn canonical_prefix(path: &Path) -> PathBuf {
647    let mut missing = Vec::new();
648    let mut current = path.to_path_buf();
649    loop {
650        if let Ok(resolved) = current.canonicalize() {
651            return missing.iter().rev().fold(resolved, |acc: PathBuf, part| acc.join(part));
652        }
653        match (current.file_name().map(std::ffi::OsStr::to_os_string), current.parent()) {
654            (Some(name), Some(parent)) => {
655                missing.push(name);
656                current = parent.to_path_buf();
657            }
658            _ => return path.to_path_buf(),
659        }
660    }
661}
662
663enum HashFailure {
664    Gone,
665    Store(adk_core::AdkError),
666}
667
668/// Hashes one walked file through the cache; with `store`, puts its object when missing.
669fn hash_file(
670    root: &Path,
671    file: &WalkedFile,
672    cache: &Mutex<StatCache>,
673    objects: &dyn SnapshotObjects,
674    store: bool,
675    racy_after: u64,
676) -> std::result::Result<(FileEntry, u64), HashFailure> {
677    let path = root.join(&file.path);
678    if file.kind == EntryKind::Symlink {
679        let target = std::fs::read_link(&path).map_err(|_| HashFailure::Gone)?;
680        let target = target.to_string_lossy().into_owned();
681        return Ok((
682            FileEntry {
683                path: file.path.clone(),
684                sha256: object_id(target.as_bytes()),
685                len: target.len() as u64,
686                mode: file.mode,
687                mtime_ns: file.mtime_ns,
688                inode: file.inode,
689                link: Some(target),
690            },
691            0,
692        ));
693    }
694    let stat = Stat { len: file.len, mtime_ns: file.mtime_ns, inode: file.inode };
695    let cached = {
696        let cache = cache.lock().unwrap_or_else(|e| e.into_inner());
697        cache
698            .entries
699            .get(&file.path)
700            .filter(|(known, _)| *known == stat)
701            .map(|(_, sha)| sha.clone())
702    };
703    let mut written = 0;
704    let sha256 = match cached {
705        Some(sha) if !store || objects.contains(&sha).map_err(HashFailure::Store)? => sha,
706        _ => {
707            let bytes = std::fs::read(&path).map_err(|_| HashFailure::Gone)?;
708            let sha = object_id(&bytes);
709            if store {
710                written = objects.put(&sha, &bytes).map_err(HashFailure::Store)?;
711            }
712            if file.mtime_ns < racy_after && bytes.len() as u64 == file.len {
713                cache
714                    .lock()
715                    .unwrap_or_else(|e| e.into_inner())
716                    .entries
717                    .insert(file.path.clone(), (stat, sha.clone()));
718            }
719            sha
720        }
721    };
722    Ok((
723        FileEntry {
724            path: file.path.clone(),
725            sha256,
726            len: file.len,
727            mode: file.mode,
728            mtime_ns: file.mtime_ns,
729            inode: file.inode,
730            link: None,
731        },
732        written,
733    ))
734}
735
736#[cfg(test)]
737mod tests {
738    use super::*;
739    use crate::snapshot::{InMemorySnapshotObjects, InMemorySnapshotStore};
740
741    fn snapshots(dir: &Path, config: SnapshotConfig) -> (Snapshots, Arc<InMemorySnapshotObjects>) {
742        let objects = Arc::new(InMemorySnapshotObjects::new());
743        let snapshots = Snapshots::new(
744            config,
745            &adk_devtools::Workspace::new(dir),
746            Arc::new(InMemorySnapshotStore::new()),
747            objects.clone(),
748        )
749        .unwrap();
750        (snapshots, objects)
751    }
752
753    fn request(session: &str, invocation: &str) -> SnapshotRequest {
754        SnapshotRequest::new("app", "alice", session, invocation, SnapshotKind::Turn)
755    }
756
757    #[tokio::test]
758    async fn an_unchanged_tree_adds_nothing_and_a_change_adds_only_itself() {
759        let dir = tempfile::tempdir().unwrap();
760        std::fs::write(dir.path().join("a.txt"), "one").unwrap();
761        std::fs::write(dir.path().join("b.txt"), "two").unwrap();
762        let (snapshots, _) = snapshots(dir.path(), SnapshotConfig::default());
763        let first = snapshots.take(request("s1", "i1")).await.unwrap();
764        assert_eq!(first.files, 2);
765        assert!(first.bytes_new > 0);
766        let second = snapshots.take(request("s1", "i2")).await.unwrap();
767        assert_eq!(second.bytes_new, 0, "identical tree, identical manifest: nothing new");
768        std::fs::write(dir.path().join("b.txt"), "two, changed").unwrap();
769        let third = snapshots.take(request("s1", "i3")).await.unwrap();
770        assert!(third.bytes_new >= "two, changed".len() as u64);
771    }
772
773    #[tokio::test]
774    async fn the_stat_cache_reads_an_unchanged_file_once() {
775        let dir = tempfile::tempdir().unwrap();
776        let path = dir.path().join("a.txt");
777        std::fs::write(&path, "one").unwrap();
778        // Old enough to be trusted by the cache.
779        let old = std::fs::File::options().write(true).open(&path).unwrap();
780        old.set_modified(SystemTime::now() - Duration::from_secs(60)).unwrap();
781        drop(old);
782        let (snapshots, _) = snapshots(dir.path(), SnapshotConfig::default());
783        let first = snapshots.scan().await.unwrap();
784        // Unreadable now, yet the cached hash answers because size, time and inode match.
785        #[cfg(unix)]
786        {
787            use std::os::unix::fs::PermissionsExt as _;
788            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();
789            let second = snapshots.scan().await.unwrap();
790            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
791            assert_eq!(second.files[0].sha256, first.files[0].sha256);
792            assert_eq!(second.files[0].mode & 0o777, 0o000, "the mode is read, the content is not");
793        }
794        // A change of size is seen.
795        std::fs::write(&path, "one more").unwrap();
796        let third = snapshots.scan().await.unwrap();
797        assert_ne!(third.files[0].sha256, first.files[0].sha256);
798    }
799
800    #[tokio::test]
801    async fn retention_keeps_the_last_turns_and_collects_their_objects() {
802        let dir = tempfile::tempdir().unwrap();
803        let config = SnapshotConfig { keep_turns: 2, ..SnapshotConfig::default() };
804        let (snapshots, objects) = snapshots(dir.path(), config);
805        for turn in 0..4 {
806            std::fs::write(dir.path().join("a.txt"), format!("version {turn}")).unwrap();
807            snapshots.take(request("s1", &format!("i{turn}"))).await.unwrap();
808        }
809        let kept = snapshots.list("app", "alice", "s1").await.unwrap();
810        assert_eq!(kept.len(), 2);
811        assert_eq!(kept[0].invocation_id, "i2");
812        // In memory, objects have no age, so collection is immediate: two manifests and two
813        // versions of a.txt remain.
814        assert_eq!(objects.list().unwrap().len(), 4);
815        assert_eq!(snapshots.forget_session("app", "alice", "s1").await.unwrap(), 2);
816        assert!(objects.list().unwrap().is_empty());
817    }
818
819    #[tokio::test]
820    async fn the_byte_budget_drops_the_oldest_snapshots_first() {
821        let dir = tempfile::tempdir().unwrap();
822        let config = SnapshotConfig { max_bytes: 3_000, ..SnapshotConfig::default() };
823        let (snapshots, objects) = snapshots(dir.path(), config);
824        for turn in 0..4 {
825            std::fs::write(dir.path().join("a.bin"), vec![turn as u8; 1_000]).unwrap();
826            snapshots.take(request("s1", &format!("i{turn}"))).await.unwrap();
827        }
828        let kept = snapshots.list("app", "alice", "s1").await.unwrap();
829        assert!(kept.len() < 4 && !kept.is_empty(), "{}", kept.len());
830        assert_eq!(kept.last().unwrap().invocation_id, "i3", "the newest is never dropped");
831        let total: u64 = objects.list().unwrap().iter().map(|info| info.bytes).sum();
832        assert!(total <= 3_000, "{total}");
833    }
834
835    #[tokio::test]
836    async fn objects_inside_the_workspace_are_refused() {
837        let dir = tempfile::tempdir().unwrap();
838        let result = Snapshots::new(
839            SnapshotConfig::default(),
840            &adk_devtools::Workspace::new(dir.path()),
841            Arc::new(InMemorySnapshotStore::new()),
842            Arc::new(crate::snapshot::FileSnapshotObjects::new(dir.path().join(".snapshots"))),
843        );
844        assert_eq!(result.unwrap_err().code, "harness.snapshot.inside_workspace");
845    }
846}