Skip to main content

adk_harness/snapshot/
store.rs

1//! Snapshot manifests (spec 3.1 §7.27): one record per snapshot, in memory or in
2//! `harness.db`.
3
4use std::sync::Mutex;
5
6use adk_core::Result;
7use async_trait::async_trait;
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12use super::walk::NotCovered;
13
14/// Why a snapshot was taken (spec 3.1 §9.3 `harness.snapshot.taken`).
15///
16/// # Example
17///
18/// ```rust
19/// use adk_harness::snapshot::SnapshotKind;
20///
21/// assert_eq!(serde_json::to_value(SnapshotKind::Turn).unwrap(), "turn");
22/// assert_eq!(SnapshotKind::Rewind.as_str(), "rewind");
23/// ```
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
25#[serde(rename_all = "lowercase")]
26pub enum SnapshotKind {
27    /// Before a user turn: the first model call of a run that carries a user message.
28    Turn,
29    /// Before a plan-graph step.
30    Step,
31    /// Before a `Destructive` call, such as `git reset --hard` (§7.30).
32    Destructive,
33    /// Before a rewind, so the rewind itself can be redone.
34    Rewind,
35}
36
37impl SnapshotKind {
38    /// The kind as the audit record names it.
39    pub fn as_str(self) -> &'static str {
40        match self {
41            Self::Turn => "turn",
42            Self::Step => "step",
43            Self::Destructive => "destructive",
44            Self::Rewind => "rewind",
45        }
46    }
47}
48
49impl std::fmt::Display for SnapshotKind {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        f.write_str(self.as_str())
52    }
53}
54
55/// One file of a snapshot's manifest.
56#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(rename_all = "camelCase")]
58pub struct FileEntry {
59    /// Relative to the workspace root, with `/` separators.
60    pub path: String,
61    /// The object id of its content (for a symlink, of its target).
62    pub sha256: String,
63    /// Length in bytes.
64    pub len: u64,
65    /// The permission bits on Unix; `0` elsewhere.
66    #[serde(default)]
67    pub mode: u32,
68    /// Modification time in nanoseconds since the Unix epoch, for the stat cache.
69    #[serde(default)]
70    pub mtime_ns: u64,
71    /// The inode number on Unix, for the stat cache.
72    #[serde(default)]
73    pub inode: u64,
74    /// For a symlink, its target; the link is restored as a link, never followed.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub link: Option<String>,
77}
78
79impl FileEntry {
80    /// Whether two entries hold the same content, kind and permissions.
81    pub fn same_content(&self, other: &Self) -> bool {
82        self.sha256 == other.sha256 && self.mode == other.mode && self.link == other.link
83    }
84}
85
86/// Where the session's plan stood when a snapshot was taken (spec 3.1 §7.11, §7.27).
87#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(rename_all = "camelCase")]
89pub struct PlanMark {
90    /// The installed plan's hash.
91    pub plan_hash: String,
92    /// The graph thread turns ran on.
93    pub thread_id: String,
94    /// The steps completed on that thread, in plan order.
95    pub completed: Vec<String>,
96    /// Whether the plan was still running.
97    pub running: bool,
98}
99
100/// The events a rewind removed from the session, kept with the snapshot taken before it so
101/// `/redo` puts them back (spec 3.1 §7.27).
102#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
103#[serde(rename_all = "camelCase")]
104pub struct TranscriptTail {
105    /// The id of the last event the rewind kept; `None` when it removed every event.
106    pub after: Option<String>,
107    /// The removed events, serialized.
108    pub events: Vec<Value>,
109}
110
111/// One snapshot's record (spec 3.1 §7.27): who and what it is for, and the object holding
112/// its file list. Stored sealed under the store key when one is configured.
113#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
114#[serde(rename_all = "camelCase")]
115pub struct SnapshotRecord {
116    /// `snap-` and a random id.
117    pub id: String,
118    /// The application.
119    pub app_name: String,
120    /// The user.
121    pub user_id: String,
122    /// The session.
123    pub session_id: String,
124    /// The workspace: [`root_digest`](super::root_digest) of its canonical root.
125    pub root: String,
126    /// When the walk started.
127    pub created_at: DateTime<Utc>,
128    /// Why it was taken.
129    pub kind: SnapshotKind,
130    /// The run it was taken in.
131    pub invocation_id: String,
132    /// The plan step it precedes (kind `step`).
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub step: Option<String>,
135    /// The object holding the file list ([`FileEntry`] array, JSON).
136    pub files_object: String,
137    /// How many files it holds.
138    pub file_count: usize,
139    /// Their total length.
140    pub total_bytes: u64,
141    /// Bytes this snapshot added to the object store.
142    pub bytes_new: u64,
143    /// Whether the walk stopped at `max_files`.
144    pub partial: bool,
145    /// Files the walk saw and left out, at most [`NOT_COVERED_LISTED`](super::NOT_COVERED_LISTED).
146    #[serde(default)]
147    pub not_covered: Vec<NotCovered>,
148    /// How many more were left out than listed.
149    #[serde(default)]
150    pub not_covered_more: usize,
151    /// Where the plan stood.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub plan: Option<PlanMark>,
154    /// For kind `rewind`: the events the rewind removed.
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub transcript: Option<TranscriptTail>,
157    /// For kind `rewind`: what the rewind then wrote, path to hash (`None` removed), so its
158    /// own writes are never a conflict for the next rewind.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub rewound: Option<std::collections::BTreeMap<String, Option<String>>>,
161}
162
163/// Where snapshot records are kept (spec 3.1 §7.27): [`InMemorySnapshotStore`], or
164/// `SqliteSnapshotStore` in `harness.db` (feature `sqlite`).
165///
166/// Lists are oldest first.
167#[async_trait]
168pub trait SnapshotStore: Send + Sync {
169    /// Stores `record`, replacing one with the same id.
170    async fn put(&self, record: &SnapshotRecord) -> Result<()>;
171
172    /// The record `id`.
173    async fn get(&self, id: &str) -> Result<Option<SnapshotRecord>>;
174
175    /// The records of a session, oldest first.
176    async fn list_session(
177        &self,
178        app: &str,
179        user: &str,
180        session: &str,
181    ) -> Result<Vec<SnapshotRecord>>;
182
183    /// The records of a workspace (by root digest), oldest first.
184    async fn list_root(&self, root: &str) -> Result<Vec<SnapshotRecord>>;
185
186    /// Removes the records `ids`.
187    async fn delete(&self, ids: &[String]) -> Result<()>;
188}
189
190fn oldest_first(records: &mut [SnapshotRecord]) {
191    records.sort_by(|a, b| a.created_at.cmp(&b.created_at).then_with(|| a.id.cmp(&b.id)));
192}
193
194/// Snapshot records in memory.
195///
196/// # Example
197///
198/// ```rust
199/// use adk_harness::snapshot::{InMemorySnapshotStore, SnapshotStore};
200///
201/// # tokio_test_block(async {
202/// let store = InMemorySnapshotStore::new();
203/// assert!(store.list_session("app", "alice", "s1").await.unwrap().is_empty());
204/// # });
205/// # fn tokio_test_block(f: impl std::future::Future<Output = ()>) {
206/// #     tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(f)
207/// # }
208/// ```
209#[derive(Debug, Default)]
210pub struct InMemorySnapshotStore {
211    records: Mutex<Vec<SnapshotRecord>>,
212}
213
214impl InMemorySnapshotStore {
215    /// An empty store.
216    pub fn new() -> Self {
217        Self::default()
218    }
219}
220
221#[async_trait]
222impl SnapshotStore for InMemorySnapshotStore {
223    async fn put(&self, record: &SnapshotRecord) -> Result<()> {
224        let mut records = self.records.lock().unwrap_or_else(|e| e.into_inner());
225        records.retain(|known| known.id != record.id);
226        records.push(record.clone());
227        Ok(())
228    }
229
230    async fn get(&self, id: &str) -> Result<Option<SnapshotRecord>> {
231        Ok(self
232            .records
233            .lock()
234            .unwrap_or_else(|e| e.into_inner())
235            .iter()
236            .find(|record| record.id == id)
237            .cloned())
238    }
239
240    async fn list_session(
241        &self,
242        app: &str,
243        user: &str,
244        session: &str,
245    ) -> Result<Vec<SnapshotRecord>> {
246        let mut out: Vec<SnapshotRecord> = self
247            .records
248            .lock()
249            .unwrap_or_else(|e| e.into_inner())
250            .iter()
251            .filter(|r| r.app_name == app && r.user_id == user && r.session_id == session)
252            .cloned()
253            .collect();
254        oldest_first(&mut out);
255        Ok(out)
256    }
257
258    async fn list_root(&self, root: &str) -> Result<Vec<SnapshotRecord>> {
259        let mut out: Vec<SnapshotRecord> = self
260            .records
261            .lock()
262            .unwrap_or_else(|e| e.into_inner())
263            .iter()
264            .filter(|record| record.root == root)
265            .cloned()
266            .collect();
267        oldest_first(&mut out);
268        Ok(out)
269    }
270
271    async fn delete(&self, ids: &[String]) -> Result<()> {
272        self.records.lock().unwrap_or_else(|e| e.into_inner()).retain(|r| !ids.contains(&r.id));
273        Ok(())
274    }
275}
276
277/// Snapshot records in a SQLite database, `harness.db` in adk-cli: table
278/// `adk_harness_snapshots`, the record sealed under the store key when one is configured
279/// (spec 3.1 §7.12, I68).
280///
281/// # Example
282///
283/// ```rust,ignore
284/// let store = adk_harness::snapshot::SqliteSnapshotStore::new(pool);
285/// store.migrate().await?;
286/// ```
287#[cfg(feature = "sqlite")]
288#[derive(Debug, Clone)]
289pub struct SqliteSnapshotStore {
290    pool: sqlx::SqlitePool,
291    #[cfg(feature = "encrypted")]
292    envelope: Option<crate::encrypted::StoreEnvelope>,
293}
294
295#[cfg(feature = "sqlite")]
296impl SqliteSnapshotStore {
297    /// A store over `pool`.
298    pub fn new(pool: sqlx::SqlitePool) -> Self {
299        Self {
300            pool,
301            #[cfg(feature = "encrypted")]
302            envelope: None,
303        }
304    }
305
306    /// Seals every record under `keyring` (spec 3.1 §7.12).
307    #[cfg(feature = "encrypted")]
308    #[must_use]
309    pub fn with_keyring(mut self, keyring: crate::encrypted::StoreKeyring) -> Self {
310        self.envelope = Some(crate::encrypted::StoreEnvelope::new(keyring, "snapshots"));
311        self
312    }
313
314    /// Re-seals every record a previous key sealed, seals records written before a key was
315    /// configured, and returns how many rows changed. Without a keyring, nothing changes.
316    ///
317    /// # Errors
318    ///
319    /// Returns `harness.store.decrypt_failed` when a row opens under no key the keyring
320    /// holds, or the database error.
321    #[cfg(feature = "encrypted")]
322    pub async fn rewrap(&self) -> Result<u64> {
323        let Some(envelope) = &self.envelope else {
324            return Ok(0);
325        };
326        let rows: Vec<(String, String)> =
327            sqlx::query_as("SELECT id, record FROM adk_harness_snapshots")
328                .fetch_all(&self.pool)
329                .await
330                .map_err(crate::fsutil::db_error)?;
331        let mut changed = 0;
332        for (id, text) in rows {
333            if let Some(resealed) = envelope.reseal_or_seal(&[&id], &text)? {
334                sqlx::query("UPDATE adk_harness_snapshots SET record = ? WHERE id = ?")
335                    .bind(resealed)
336                    .bind(&id)
337                    .execute(&self.pool)
338                    .await
339                    .map_err(crate::fsutil::db_error)?;
340                changed += 1;
341            }
342        }
343        Ok(changed)
344    }
345
346    /// Creates the store's table if it does not exist.
347    ///
348    /// # Errors
349    ///
350    /// Returns the database error when a statement fails.
351    pub async fn migrate(&self) -> Result<()> {
352        for statement in [
353            "CREATE TABLE IF NOT EXISTS adk_harness_snapshots (\
354                id TEXT PRIMARY KEY, app_name TEXT NOT NULL, user_id TEXT NOT NULL, \
355                session_id TEXT NOT NULL, root TEXT NOT NULL, created_at TEXT NOT NULL, \
356                kind TEXT NOT NULL, record TEXT NOT NULL)",
357            "CREATE INDEX IF NOT EXISTS adk_harness_snapshots_session \
358                ON adk_harness_snapshots (app_name, user_id, session_id)",
359            "CREATE INDEX IF NOT EXISTS adk_harness_snapshots_root \
360                ON adk_harness_snapshots (root)",
361        ] {
362            sqlx::query(statement).execute(&self.pool).await.map_err(crate::fsutil::db_error)?;
363        }
364        Ok(())
365    }
366
367    #[cfg(feature = "encrypted")]
368    fn encode(&self, id: &str, text: String) -> Result<String> {
369        crate::encrypted::encode_row(self.envelope.as_ref(), &[id], text)
370    }
371
372    #[cfg(not(feature = "encrypted"))]
373    fn encode(&self, _id: &str, text: String) -> Result<String> {
374        Ok(text)
375    }
376
377    #[cfg(feature = "encrypted")]
378    fn decode(&self, id: &str, text: String) -> Result<String> {
379        crate::encrypted::decode_row(self.envelope.as_ref(), "snapshots", &[id], text)
380    }
381
382    #[cfg(not(feature = "encrypted"))]
383    fn decode(&self, _id: &str, text: String) -> Result<String> {
384        Ok(text)
385    }
386
387    fn parse(&self, id: String, text: String) -> Result<Option<SnapshotRecord>> {
388        let text = self.decode(&id, text)?;
389        // A record that does not parse restores nothing.
390        Ok(serde_json::from_str(&text).ok())
391    }
392
393    async fn select(&self, sql: &'static str, binds: &[&str]) -> Result<Vec<SnapshotRecord>> {
394        let mut query = sqlx::query_as::<_, (String, String)>(sql);
395        for bind in binds {
396            query = query.bind(*bind);
397        }
398        let rows = query.fetch_all(&self.pool).await.map_err(crate::fsutil::db_error)?;
399        let mut out = Vec::with_capacity(rows.len());
400        for (id, text) in rows {
401            if let Some(record) = self.parse(id, text)? {
402                out.push(record);
403            }
404        }
405        oldest_first(&mut out);
406        Ok(out)
407    }
408}
409
410#[cfg(feature = "sqlite")]
411#[async_trait]
412impl SnapshotStore for SqliteSnapshotStore {
413    async fn put(&self, record: &SnapshotRecord) -> Result<()> {
414        let text = serde_json::to_string(record)
415            .map_err(|error| crate::fsutil::serialize_error("snapshot record", &error))?;
416        let text = self.encode(&record.id, text)?;
417        sqlx::query(
418            "INSERT INTO adk_harness_snapshots \
419             (id, app_name, user_id, session_id, root, created_at, kind, record) \
420             VALUES (?, ?, ?, ?, ?, ?, ?, ?) \
421             ON CONFLICT (id) DO UPDATE SET record = excluded.record",
422        )
423        .bind(&record.id)
424        .bind(&record.app_name)
425        .bind(&record.user_id)
426        .bind(&record.session_id)
427        .bind(&record.root)
428        .bind(record.created_at.to_rfc3339_opts(chrono::SecondsFormat::Nanos, true))
429        .bind(record.kind.as_str())
430        .bind(text)
431        .execute(&self.pool)
432        .await
433        .map_err(crate::fsutil::db_error)?;
434        Ok(())
435    }
436
437    async fn get(&self, id: &str) -> Result<Option<SnapshotRecord>> {
438        Ok(self
439            .select("SELECT id, record FROM adk_harness_snapshots WHERE id = ?", &[id])
440            .await?
441            .into_iter()
442            .next())
443    }
444
445    async fn list_session(
446        &self,
447        app: &str,
448        user: &str,
449        session: &str,
450    ) -> Result<Vec<SnapshotRecord>> {
451        self.select(
452            "SELECT id, record FROM adk_harness_snapshots \
453             WHERE app_name = ? AND user_id = ? AND session_id = ?",
454            &[app, user, session],
455        )
456        .await
457    }
458
459    async fn list_root(&self, root: &str) -> Result<Vec<SnapshotRecord>> {
460        self.select("SELECT id, record FROM adk_harness_snapshots WHERE root = ?", &[root]).await
461    }
462
463    async fn delete(&self, ids: &[String]) -> Result<()> {
464        for id in ids {
465            sqlx::query("DELETE FROM adk_harness_snapshots WHERE id = ?")
466                .bind(id)
467                .execute(&self.pool)
468                .await
469                .map_err(crate::fsutil::db_error)?;
470        }
471        Ok(())
472    }
473}