Skip to main content

sqlite_graphrag/commands/
restore.rs

1//! Handler for the `restore` CLI subcommand.
2
3use crate::errors::AppError;
4use crate::i18n::errors_msg;
5use crate::output;
6use crate::output::JsonOutputFormat;
7use crate::paths::AppPaths;
8use crate::storage::connection::open_rw;
9use crate::storage::memories;
10use crate::storage::versions;
11use rusqlite::params;
12use rusqlite::OptionalExtension;
13use serde::Serialize;
14
15#[derive(clap::Args)]
16#[command(after_long_help = "EXAMPLES:\n  \
17    # Restore the latest non-`restore` version of a memory\n  \
18    sqlite-graphrag restore --name onboarding\n\n  \
19    # Restore a specific version\n  \
20    sqlite-graphrag restore --name onboarding --version 3\n\n  \
21    # Restore within a specific namespace\n  \
22    sqlite-graphrag restore --name onboarding --namespace my-project")]
23/// Restore args.
24pub struct RestoreArgs {
25    /// Memory name as a positional argument. Alternative to `--name`.
26    #[arg(
27        value_name = "NAME",
28        conflicts_with = "name",
29        help = "Memory name to restore; alternative to --name"
30    )]
31    pub name_positional: Option<String>,
32    /// Memory name to restore (must exist, including soft-deleted/forgotten).
33    #[arg(long)]
34    pub name: Option<String>,
35    /// Version to restore. When omitted, defaults to the latest non-`restore` version
36    /// from `memory_versions`. This makes the forget+restore workflow work without
37    /// requiring the user to discover the version first.
38    #[arg(long)]
39    pub version: Option<i64>,
40    #[arg(long, help = "Namespace (flag / XDG namespace.default / global)")]
41    /// Namespace scope.
42    pub namespace: Option<String>,
43    /// Optimistic locking: reject if the current updated_at does not match (exit 3).
44    #[arg(
45        long,
46        value_name = "EPOCH_OR_RFC3339",
47        value_parser = crate::parsers::parse_expected_updated_at,
48        long_help = "Optimistic lock: reject if updated_at does not match. \
49Accepts Unix epoch (e.g. 1700000000) or RFC 3339 (e.g. 2026-04-19T12:00:00Z)."
50    )]
51    pub expected_updated_at: Option<i64>,
52    /// Output format.
53    #[arg(long, value_enum, default_value_t = JsonOutputFormat::Json)]
54    pub format: JsonOutputFormat,
55    /// Emit machine-readable JSON on stdout.
56    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
57    pub json: bool,
58    /// Path to the SQLite database file.
59    #[arg(long)]
60    pub db: Option<String>,
61}
62
63#[derive(Serialize)]
64struct RestoreResponse {
65    /// Always `"restored"` — signals the completed action to shell callers and LLM agents.
66    action: String,
67    memory_id: i64,
68    name: String,
69    version: i64,
70    restored_from: i64,
71    /// Total execution time in milliseconds from handler start to serialisation.
72    elapsed_ms: u64,
73}
74
75/// Run.
76pub fn run(
77    args: RestoreArgs,
78    llm_backend: crate::cli::LlmBackendChoice,
79    embedding_backend: crate::cli::EmbeddingBackendChoice,
80) -> Result<(), AppError> {
81    let start = std::time::Instant::now();
82    let _ = args.format;
83    tracing::debug!(target: "restore", name = ?args.name_positional.as_deref().or(args.name.as_deref()), version = ?args.version, "restoring version");
84    let name = args
85        .name_positional
86        .as_deref()
87        .or(args.name.as_deref())
88        .ok_or_else(|| {
89            AppError::Validation(
90                "name required: pass as positional argument or via --name".to_string(),
91            )
92        })?
93        .to_string();
94    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
95    let paths = AppPaths::resolve(args.db.as_deref())?;
96    let mut conn = open_rw(&paths.db)?;
97
98    // PRD line 1118: query WITHOUT a deleted_at filter — restore must work on soft-deleted memories
99    let result: Option<(i64, i64)> = conn
100        .query_row(
101            "SELECT id, updated_at FROM memories WHERE namespace = ?1 AND name = ?2",
102            params![namespace, name],
103            |r| Ok((r.get(0)?, r.get(1)?)),
104        )
105        .optional()?;
106    let (memory_id, current_updated_at) = result
107        .ok_or_else(|| AppError::NotFound(errors_msg::memory_not_found(&name, &namespace)))?;
108
109    if let Some(expected) = args.expected_updated_at {
110        if expected != current_updated_at {
111            return Err(AppError::Conflict(errors_msg::optimistic_lock_conflict(
112                expected,
113                current_updated_at,
114            )));
115        }
116    }
117
118    // v1.0.22 P0: resolve optional `--version`. When absent, uses the highest version
119    // whose `change_reason` is not 'restore' (recovers the real state, not meta-restore).
120    // Lets the forget+restore workflow function without manually reading memory_versions.
121    let target_version: i64 = match args.version {
122        Some(v) => v,
123        None => {
124            let last: Option<i64> = conn
125                .query_row(
126                    "SELECT MAX(version) FROM memory_versions
127                     WHERE memory_id = ?1 AND change_reason != 'restore'",
128                    params![memory_id],
129                    |r| r.get(0),
130                )
131                .optional()?
132                .flatten();
133            let v = last.ok_or_else(|| {
134                AppError::NotFound(errors_msg::memory_not_found(&name, &namespace))
135            })?;
136            tracing::info!(target: "restore",
137                "restore --version omitted; using latest non-restore version: {}",
138                v
139            );
140            v
141        }
142    };
143
144    let version_row: (String, String, String, String, String) = {
145        let mut stmt = conn.prepare_cached(
146            "SELECT name, type, description, body, metadata
147             FROM memory_versions
148             WHERE memory_id = ?1 AND version = ?2",
149        )?;
150
151        stmt.query_row(params![memory_id, target_version], |r| {
152            Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?))
153        })
154        .map_err(|_| AppError::NotFound(errors_msg::version_not_found(target_version, &name)))?
155    };
156
157    let (_old_name, old_type, old_description, old_body, old_metadata) = version_row;
158
159    // Read current FTS-indexed values before the UPDATE so sync_fts_after_update
160    // can issue the correct DELETE command for the external-content FTS5 table.
161    let (cur_name, cur_desc, cur_body): (String, String, String) = conn.query_row(
162        "SELECT name, description, body FROM memories WHERE id = ?1",
163        params![memory_id],
164        |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
165    )?;
166
167    // v1.0.21 P1-D: re-embed restored body to keep `vec_memories` synchronized
168    // with `memories`. Without this, semantic queries used the post-forget version
169    // vector, causing inconsistent recall (vec_memories=2 vs memories=3 after forget+restore).
170    output::emit_progress_i18n(
171        "Re-computing embedding for restored memory...",
172        crate::i18n::validation::runtime_pt::restore_recomputing_embedding(),
173    );
174    let skip_embed = crate::embedder::should_skip_embedding_on_failure();
175    let embedding: Option<Vec<f32>> = match crate::embedder::embed_passage_with_embedding_choice(
176        &paths.models,
177        &old_body,
178        embedding_backend,
179        llm_backend,
180    ) {
181        Ok((emb, _backend)) => Some(emb),
182        // v1.1.2 (Gap 2): typed payload rejections are permanent and must not
183        // be swallowed by --skip-embedding-on-failure.
184        Err(
185            e @ (AppError::Validation(_)
186            | AppError::BodyTooLarge { .. }
187            | AppError::TooManyTokens { .. }),
188        ) => return Err(e),
189        Err(e) if skip_embed => {
190            tracing::warn!(error = %e, "restore: embedding failed; --skip-embedding-on-failure active, persisting without embedding");
191            None
192        }
193        Err(e) => return Err(e),
194    };
195    let snippet: String = old_body.chars().take(300).collect();
196
197    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
198
199    // deleted_at = NULL reactivates soft-deleted memories; no deleted_at filter in the WHERE
200    let affected = if let Some(ts) = args.expected_updated_at {
201        tx.execute(
202            "UPDATE memories SET type=?2, description=?3, body=?4, body_hash=?5, deleted_at=NULL
203             WHERE id=?1 AND updated_at=?6",
204            rusqlite::params![
205                memory_id,
206                old_type,
207                old_description,
208                old_body,
209                blake3::hash(old_body.as_bytes()).to_hex().to_string(),
210                ts
211            ],
212        )?
213    } else {
214        tx.execute(
215            "UPDATE memories SET type=?2, description=?3, body=?4, body_hash=?5, deleted_at=NULL
216             WHERE id=?1",
217            rusqlite::params![
218                memory_id,
219                old_type,
220                old_description,
221                old_body,
222                blake3::hash(old_body.as_bytes()).to_hex().to_string()
223            ],
224        )?
225    };
226
227    if affected == 0 {
228        return Err(AppError::Conflict(errors_msg::concurrent_process_conflict()));
229    }
230
231    let next_v = versions::next_version(&tx, memory_id)?;
232
233    versions::insert_version(
234        &tx,
235        memory_id,
236        next_v,
237        &cur_name,
238        &old_type,
239        &old_description,
240        &old_body,
241        &old_metadata,
242        None,
243        "restore",
244    )?;
245
246    if let Some(ref emb) = embedding {
247        memories::upsert_vec(
248            &tx, memory_id, &namespace, &old_type, emb, &cur_name, &snippet,
249        )?;
250    }
251
252    memories::sync_fts_after_update(
253        &tx,
254        memory_id,
255        &cur_name,
256        &cur_desc,
257        &cur_body,
258        &cur_name,
259        &old_description,
260        &old_body,
261    )?;
262
263    tx.commit()?;
264
265    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
266
267    output::emit_json(&RestoreResponse {
268        action: "restored".to_string(),
269        memory_id,
270        name: cur_name.clone(),
271        version: next_v,
272        restored_from: target_version,
273        elapsed_ms: start.elapsed().as_millis() as u64,
274    })?;
275
276    Ok(())
277}
278
279#[cfg(test)]
280mod tests {
281    use crate::errors::AppError;
282
283    #[test]
284    fn optimistic_lock_conflict_returns_exit_3() {
285        let err = AppError::Conflict(
286            "optimistic lock conflict: expected updated_at=50, but current is 99".to_string(),
287        );
288        assert_eq!(err.exit_code(), 3);
289        assert!(err.to_string().contains("conflict"));
290    }
291
292    #[test]
293    fn restore_response_includes_action_field() {
294        let resp = super::RestoreResponse {
295            action: "restored".to_string(),
296            memory_id: 1,
297            name: "test-mem".to_string(),
298            version: 3,
299            restored_from: 2,
300            elapsed_ms: 42,
301        };
302        let json = serde_json::to_value(&resp).expect("serialization failed");
303        assert_eq!(json["action"], "restored");
304        assert_eq!(json["memory_id"], 1);
305        assert_eq!(json["version"], 3);
306        assert_eq!(json["restored_from"], 2);
307    }
308}