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(engine): stage sidecar writes in a unique temp file (#202)

xerj-org17dee35c1a87
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rs
index e0ccf13a9..d412d8db7 100644
--- a/engine/crates/xerj-engine/src/engine.rs
+++ b/engine/crates/xerj-engine/src/engine.rs
@@ -228,8 +228,12 @@ pub struct ApiKeyRecord {
/// default. Mirrors `index::write_file_atomic` but hardens the mode.
fn write_secret_file_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
- let tmp = path.with_extension("tmp");
- {
+ // Unique staging name, for the same reason as `index::write_file_atomic`:
+ // two concurrent key mints sharing one `api_keys.tmp` can interleave into a
+ // key store that no longer parses, and a corrupt key store silently drops
+ // every persisted key at the next boot.
+ let tmp = crate::index::staging_path(path);
+ let staged = (|| -> std::io::Result<()> {
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create(true).truncate(true);
#[cfg(unix)]
@@ -240,14 +244,19 @@ fn write_secret_file_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Re
let mut f = opts.open(&tmp)?;
f.write_all(bytes)?;
f.sync_all()?;
+ // Belt and braces: pin 0600 even if the platform ignored the open mode.
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt as _;
+ std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600))?;
+ }
+ std::fs::rename(&tmp, path)
+ })();
+ // Never leave a staging file behind on failure — it holds key material.
+ if let Err(e) = staged {
+ let _ = std::fs::remove_file(&tmp);
+ return Err(e);
}
- // Tighten an already-existing tmp inode too (create() reuses perms).
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt as _;
- std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600))?;
- }
- std::fs::rename(&tmp, path)?;
if let Some(parent) = path.parent() {
if let Ok(dir) = std::fs::File::open(parent) {
let _ = dir.sync_all();
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 3b6732f8c..bc6e64cc5 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -25464,21 +25464,58 @@ fn store_config_from(config: &Config, wal_shards_override: Option<usize>) -> Ind
}
}
+/// Per-process sequence that makes every in-flight temp file name unique.
+static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// A staging path next to `path` that no other writer can be using.
+///
+/// `path.with_extension("tmp")` — what this used to be — is the *same* name for
+/// every writer of that file, so two concurrent `write_file_atomic` calls on one
+/// sidecar both opened it `O_TRUNC` and interleaved their bytes before either
+/// renamed. Measured on this tree with the old shared name, 4 threads writing
+/// two different-length settings bodies for 200 rounds: 294 of the 800 writes
+/// failed outright with ENOENT (the loser renaming a file the winner had
+/// already moved), and with those errors swallowed — which is what the callers
+/// did — 16 of the 200 rounds left a `settings.json` that does not parse. That
+/// is exactly the file `Index::open` now refuses (#202), so the writer must not
+/// be able to manufacture it.
+///
+/// Prior art: tantivy stages atomic writes in a *unique* temp file created in
+/// the destination's own directory and then persists it over the target
+/// (`tempfile::Builder::tempfile_in` → `persist`,
+/// tantivy `src/directory/mmap_directory/mod.rs:362-378`, MIT). Same-directory
+/// keeps the rename on one filesystem; unique keeps concurrent writers apart.
+/// Adapted, not copied — we name the file ourselves rather than take a runtime
+/// dependency on `tempfile`, and we additionally fsync the parent directory.
+pub(crate) fn staging_path(path: &Path) -> std::path::PathBuf {
+ let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ let name = path
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_else(|| "sidecar".to_string());
+ path.with_file_name(format!("{name}.tmp.{}.{seq}", std::process::id()))
+}
+
/// Write `bytes` to `path` atomically: write a same-directory temp file,
/// fsync it, then rename over the target. A kill -9 mid-write leaves
/// either the old file or the new file on disk, never a truncated one.
-/// This matters for `schema.json`: `load_schema` treats a torn file as
-/// "no schema" and silently falls back to an empty dynamic mapping,
-/// which is a mapping-loss corruption after crash.
+/// This matters for `schema.json` and `settings.json`: since #202 a torn
+/// sidecar is refused at open rather than silently replaced by a default, so
+/// the write path has to be the one thing that cannot produce one.
pub fn write_file_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
- let tmp = path.with_extension("tmp");
- {
+ let tmp = staging_path(path);
+ let staged = (|| -> std::io::Result<()> {
use std::io::Write as _;
let mut f = std::fs::File::create(&tmp)?;
f.write_all(bytes)?;
- f.sync_all()?;
+ f.sync_all()
+ })();
+ // A unique staging name means a failed write leaves debris nobody will
+ // overwrite, so clean it up here rather than at the next write.
+ if let Err(e) = staged.and_then(|()| std::fs::rename(&tmp, path)) {
+ let _ = std::fs::remove_file(&tmp);
+ return Err(e);
}
- std::fs::rename(&tmp, path)?;
// Make the rename itself durable across power loss.
if let Some(parent) = path.parent() {
if let Ok(dir) = std::fs::File::open(parent) {
diff --git a/engine/crates/xerj-engine/tests/corrupt_index_metadata.rs b/engine/crates/xerj-engine/tests/corrupt_index_metadata.rs
index 55bbaa617..aa58dcb27 100644
--- a/engine/crates/xerj-engine/tests/corrupt_index_metadata.rs
+++ b/engine/crates/xerj-engine/tests/corrupt_index_metadata.rs
@@ -327,3 +327,84 @@ async fn a_failed_index_can_still_be_deleted() {
engine.create_index("removable", Schema::empty()).unwrap();
assert!(engine.get_index("removable").is_ok());
}
+
+// ── the writer must not manufacture what the reader now refuses ───────────────
+
+/// Refusing a torn sidecar is only safe if our own writer cannot produce one.
+///
+/// `write_file_atomic` staged every write in `<file>.tmp` — one shared name for
+/// all writers of that path. Two concurrent settings writes (`PUT /_settings`
+/// racing another `PUT /_settings`, or an `index.blocks` update) therefore both
+/// opened it `O_TRUNC` and interleaved their bytes before either renamed, so
+/// the *complete* file that landed was a mix of two bodies. Pre-fix, this test
+/// reports 294 of 800 writes failing with ENOENT (the loser renaming a file the
+/// winner had already moved) and — with those errors swallowed, which is what
+/// the callers do — 16 of 200 rounds leaving an unparseable file. After the
+/// fix: no failed writes, no torn file, no debris.
+///
+/// Before #202 that torn file was "only" silently swapped for an empty mapping.
+/// Now it refuses the open, so a lost race would brick the index — which is why
+/// this test lives here and not in a general-hygiene file.
+#[test]
+fn concurrent_atomic_writes_never_leave_a_torn_sidecar() {
+ let dir = TempDir::new().unwrap();
+ let path = dir.path().join("settings.json");
+
+ // Two bodies of very different length: a short write landing inside a long
+ // one is what leaves trailing garbage behind valid-looking JSON.
+ let small = serde_json::to_vec_pretty(&json!({"index": {"refresh_interval": "1s"}})).unwrap();
+ let big = serde_json::to_vec_pretty(&json!({
+ "index": {"analysis": (0..400).map(|i| format!("filter-{i}")).collect::<Vec<_>>()}
+ }))
+ .unwrap();
+
+ let mut torn = 0usize;
+ let mut write_errors: Vec<String> = Vec::new();
+ for _ in 0..200 {
+ std::thread::scope(|s| {
+ let handles: Vec<_> = [&small, &big, &small, &big]
+ .into_iter()
+ .map(|payload| {
+ let p = path.clone();
+ s.spawn(move || xerj_engine::index::write_file_atomic(&p, payload))
+ })
+ .collect();
+ for h in handles {
+ // A shared staging name also made writes fail spuriously: the
+ // loser of the race renamed a file the winner had already moved
+ // (ENOENT). Record it rather than panicking, so a failure names
+ // the defect instead of "a scoped thread panicked".
+ if let Err(e) = h.join().expect("writer thread") {
+ write_errors.push(e.to_string());
+ }
+ }
+ });
+ let bytes = std::fs::read(&path).unwrap();
+ if serde_json::from_slice::<serde_json::Value>(&bytes).is_err() {
+ torn += 1;
+ }
+ }
+ assert!(
+ write_errors.is_empty(),
+ "{} concurrent writes failed, first: {} — writers must not collide on a staging file",
+ write_errors.len(),
+ write_errors[0]
+ );
+ assert_eq!(
+ torn, 0,
+ "{torn}/200 rounds of concurrent writes left a settings.json that does not parse — \
+ the write path can manufacture the corruption the read path now refuses"
+ );
+
+ // And no staging debris is left behind for a successful write.
+ let leftovers: Vec<_> = std::fs::read_dir(dir.path())
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .map(|e| e.file_name().to_string_lossy().into_owned())
+ .filter(|n| n != "settings.json")
+ .collect();
+ assert!(
+ leftovers.is_empty(),
+ "staging files left behind: {leftovers:?}"
+ );
+}