Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(snapshot): restore honors the indices filter; 400 on unsupported options; ES-shaped info

xerj-org7b9ef132bb0e
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 076805c08..bff46fb78 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -18078,7 +18078,8 @@ pub async fn get_snapshot(
pub async fn restore_snapshot(
State(state): State<AppState>,
Path((repo, snapshot)): Path<(String, String)>,
- _body: Option<Json<Value>>,
+ axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
+ body: Option<Json<Value>>,
) -> impl IntoResponse {
let repo_config = match state.engine.snapshot_repos.get(&repo) {
Some(cfg) => cfg.clone(),
@@ -18093,8 +18094,80 @@ pub async fn restore_snapshot(
.and_then(Value::as_str)
.unwrap_or("/tmp/xerj-snapshots");
- match state.engine.restore_snapshot(repo_path, &snapshot).await {
- Ok(()) => Json(json!({ "accepted": true })).into_response(),
+ let body = body.map(|Json(b)| b).unwrap_or(Value::Null);
+
+ // Restore options that would CHANGE what gets written (index renames,
+ // per-index setting rewrites, feature states) are not implemented.
+ // Fail loud rather than restoring something other than what was asked
+ // for — ignoring a rename_pattern would clobber the source index.
+ for unsupported in [
+ "rename_pattern",
+ "rename_replacement",
+ "feature_states",
+ "index_settings",
+ "ignore_index_settings",
+ ] {
+ if body.get(unsupported).is_some() {
+ let reason =
+ format!("restore option [{unsupported}] is not supported by this XERJ version");
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(json!({
+ "error": {
+ "root_cause": [{ "type": "illegal_argument_exception", "reason": reason }],
+ "type": "illegal_argument_exception",
+ "reason": reason,
+ },
+ "status": 400,
+ })),
+ )
+ .into_response();
+ }
+ }
+
+ // ES accepts `indices` as an array of names/patterns or a single
+ // (possibly comma-separated) string; absent means "all indices in
+ // the snapshot".
+ let indices: Option<Vec<String>> = match body.get("indices") {
+ Some(Value::Array(arr)) => Some(
+ arr.iter()
+ .filter_map(|v| v.as_str().map(String::from))
+ .collect(),
+ ),
+ Some(Value::String(s)) => Some(vec![s.clone()]),
+ _ => None,
+ };
+
+ let wait_for_completion = params
+ .get("wait_for_completion")
+ .map(|v| v == "true")
+ .unwrap_or(false);
+
+ match state
+ .engine
+ .restore_snapshot(repo_path, &snapshot, indices)
+ .await
+ {
+ // Restores run synchronously either way; `wait_for_completion`
+ // only selects the ES response shape (accepted vs full info).
+ Ok(restored) => {
+ if wait_for_completion {
+ Json(json!({
+ "snapshot": {
+ "snapshot": snapshot,
+ "indices": restored,
+ "shards": {
+ "total": restored.len(),
+ "failed": 0,
+ "successful": restored.len(),
+ }
+ }
+ }))
+ .into_response()
+ } else {
+ Json(json!({ "accepted": true })).into_response()
+ }
+ }
Err(e) => ApiError::new(xerj_common::XerjError::from(e)).into_response(),
}
}
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rs
index ad2da0d88..f7200b8be 100644
--- a/engine/crates/xerj-engine/src/engine.rs
+++ b/engine/crates/xerj-engine/src/engine.rs
@@ -1034,7 +1034,25 @@ impl Engine {
}
/// Restore a snapshot: copies files back and reopens the indices.
- pub async fn restore_snapshot(&self, repo_path: &str, name: &str) -> Result<()> {
+ ///
+ /// `indices` is the ES restore-body `indices` filter: a list of index
+ /// names / wildcard patterns (each entry may itself be a comma-separated
+ /// multi-target expression, ES accepts both the string and array forms).
+ /// `None` / empty restores every index in the snapshot (ES default).
+ /// A non-wildcard entry that matches nothing in the snapshot is an
+ /// error — silently restoring nothing (or worse, everything) would
+ /// misreport what was rewritten. Returns the list of index names
+ /// actually restored.
+ ///
+ /// This filter used to be IGNORED entirely: a restore request naming
+ /// one index rewrote EVERY index in the snapshot with snapshot-time
+ /// state, destroying all writes made since (live-verified 2026-07-12).
+ pub async fn restore_snapshot(
+ &self,
+ repo_path: &str,
+ name: &str,
+ indices: Option<Vec<String>>,
+ ) -> Result<Vec<String>> {
let snap_dir = std::path::Path::new(repo_path).join(name);
let manifest_path = snap_dir.join("manifest.json");
@@ -1042,7 +1060,7 @@ impl Engine {
let manifest: Value =
serde_json::from_slice(&manifest_bytes).map_err(EngineError::Serde)?;
- let index_names: Vec<String> = manifest
+ let snapshot_indices: Vec<String> = manifest
.get("indices")
.and_then(Value::as_array)
.map(|arr| {
@@ -1052,6 +1070,43 @@ impl Engine {
})
.unwrap_or_default();
+ // Apply the `indices` filter. Split each entry on commas, then match
+ // each pattern against the snapshot's indices (glob `*` wildcards,
+ // same matcher the search path uses for index selectors).
+ let patterns: Vec<String> = indices
+ .unwrap_or_default()
+ .iter()
+ .flat_map(|entry| entry.split(','))
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ .collect();
+
+ let index_names: Vec<String> = if patterns.is_empty() {
+ snapshot_indices
+ } else {
+ let mut selected: Vec<String> = Vec::new();
+ for pat in &patterns {
+ let matched: Vec<&String> = snapshot_indices
+ .iter()
+ .filter(|n| glob_match(pat, n))
+ .collect();
+ if matched.is_empty() && !pat.contains('*') {
+ // ES: restore of an index absent from the snapshot fails
+ // loud (snapshot_restore_exception). Mirror that. The
+ // repo's filesystem path is deliberately NOT echoed.
+ return Err(EngineError::Common(xerj_common::XerjError::invalid_query(
+ format!("[{name}] no index matches [{pat}] in snapshot"),
+ )));
+ }
+ for m in matched {
+ if !selected.contains(m) {
+ selected.push(m.clone());
+ }
+ }
+ }
+ selected
+ };
+
for idx_name in &index_names {
let src_dir = snap_dir.join(idx_name.as_str());
if !src_dir.exists() {
@@ -1091,8 +1146,13 @@ impl Engine {
}
}
- info!(snapshot = name, repo = repo_path, "snapshot restored");
- Ok(())
+ info!(
+ snapshot = name,
+ repo = repo_path,
+ indices = ?index_names,
+ "snapshot restored"
+ );
+ Ok(index_names)
}
} // end impl Engine
diff --git a/engine/crates/xerj-engine/tests/integration.rs b/engine/crates/xerj-engine/tests/integration.rs
index 7f01e1de4..8d6b229c0 100644
--- a/engine/crates/xerj-engine/tests/integration.rs
+++ b/engine/crates/xerj-engine/tests/integration.rs
@@ -4768,3 +4768,78 @@ async fn test_semantic_text_match_survives_flush() {
);
}
+/// Blocker 5: snapshot RESTORE ignored the request `indices` filter and
+/// rewrote EVERY index in the snapshot with snapshot-time state, silently
+/// destroying all writes made since. The filter must select exactly the
+/// requested indices (with wildcard support) and error on unknown names.
+#[tokio::test]
+async fn test_restore_snapshot_honors_indices_filter() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ let repo = dir.path().join("snaprepo");
+ let repo_path = repo.to_str().unwrap();
+
+ for name in ["s1", "s2"] {
+ engine.create_index(name, Schema::empty()).unwrap();
+ let idx = engine.get_index(name).unwrap();
+ idx.index_document(Some("d1".into()), json!({"v": "original"}))
+ .await
+ .unwrap();
+ }
+ engine
+ .create_snapshot(
+ repo_path,
+ "snap1",
+ Some(vec!["s1".to_string(), "s2".to_string()]),
+ )
+ .await
+ .unwrap();
+
+ // Post-snapshot write to s2 — must SURVIVE a restore of s1 only.
+ engine
+ .get_index("s2")
+ .unwrap()
+ .index_document(Some("d2".into()), json!({"v": "after-snapshot"}))
+ .await
+ .unwrap();
+
+ let restored = engine
+ .restore_snapshot(repo_path, "snap1", Some(vec!["s1".to_string()]))
+ .await
+ .unwrap();
+ assert_eq!(restored, vec!["s1".to_string()]);
+
+ let s2 = engine.get_index("s2").unwrap();
+ let post = s2
+ .search(&make_search(json!({"match_all": {}})))
+ .await
+ .unwrap();
+ assert_eq!(
+ post.total.value, 2,
+ "restore of s1 must not roll back s2 (it used to clobber every index)"
+ );
+
+ // An index name absent from the snapshot errors loud (never a no-op).
+ assert!(engine
+ .restore_snapshot(repo_path, "snap1", Some(vec!["nope".to_string()]))
+ .await
+ .is_err());
+
+ // Wildcards select within the snapshot.
+ let both = engine
+ .restore_snapshot(repo_path, "snap1", Some(vec!["s*".to_string()]))
+ .await
+ .unwrap();
+ assert_eq!(both.len(), 2, "s* must match both snapshot indices");
+ let s2_rolled = engine
+ .get_index("s2")
+ .unwrap()
+ .search(&make_search(json!({"match_all": {}})))
+ .await
+ .unwrap();
+ assert_eq!(
+ s2_rolled.total.value, 1,
+ "explicitly-selected s2 rolls back to snapshot state"
+ );
+}
+