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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(autoindex): deduplicate content with crash-safe replacement
bugerc529e6047e98
diff --git a/engine/Cargo.lock b/engine/Cargo.lockindex 54a160078..ef94050c5 100644--- a/engine/Cargo.lock+++ b/engine/Cargo.lock@@ -1515,6 +1515,16 @@ dependencies = ["tokio",]+[[package]]+name = "fs2"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"+dependencies = [+ "libc",+ "winapi",+]+[[package]]name = "fst"version = "0.4.7"@@ -5863,6 +5873,7 @@ dependencies = ["csv","encoding_rs","flate2",+ "fs2","libc","memchr","pdf_oxide",diff --git a/engine/crates/xerj-autoindex/Cargo.toml b/engine/crates/xerj-autoindex/Cargo.tomlindex 731df6fa7..d9d45ad49 100644--- a/engine/crates/xerj-autoindex/Cargo.toml+++ b/engine/crates/xerj-autoindex/Cargo.toml@@ -18,6 +18,8 @@ xxhash-rust.workspace = truememchr.workspace = truerayon.workspace = truelibc = "0.2"+tempfile.workspace = true+fs2 = "0.4"# ES-compat HTTP client. Blocking mode: all of autoindex is synchronous# (std threads), invoked from the server binary via spawn_blocking.reqwest = { workspace = true, features = ["blocking"] }@@ -33,4 +35,3 @@ serde_yaml = "0.9" # YAML multi-docrusqlite = { version = "0.32", features = ["bundled"] }[dev-dependencies]-tempfile.workspace = truediff --git a/engine/crates/xerj-autoindex/src/catalog.rs b/engine/crates/xerj-autoindex/src/catalog.rsindex e64c046d2..b49e9d823 100644--- a/engine/crates/xerj-autoindex/src/catalog.rs+++ b/engine/crates/xerj-autoindex/src/catalog.rs@@ -31,6 +31,7 @@ pub fn catalog_mapping() -> Value {"format": {"type": "keyword"},"status": {"type": "keyword"},"reason": {"type": "text"},+ "duplicate_of": {"type": "keyword"},"records": {"type": "long"},"junk": {"type": "long"},"run_id": {"type": "keyword"},@@ -59,6 +60,7 @@ pub const GOTCHAS: &[&str] = &["all dates are normalized to RFC3339 UTC millis; mappings use strict_date_optional_time||epoch_millis","query all data with the wildcard index pattern (e.g. ax-*) or comma lists — never multi-index aliases (they resolve to the first index only)","documents were indexed with refresh at the end of the run; new writes need _refresh before they are searchable",+ "byte-identical paths are indexed once; canonical records retain every current filename in _source.ax_paths, and exact alias resolution is available through the catalog's duplicate_files entries",];pub struct DatasetDocInput<'a> {@@ -130,6 +132,41 @@ pub fn file_doc()}+pub fn duplicate_file_doc(+ file_key: &str,+ path: &str,+ path_id: &str,+ duplicate_of: &str,+ bytes: u64,+ run_id: &str,+) -> (String, Value) {+ let alias_id = duplicate_file_id(file_key, path, path_id);+ (+ alias_id,+ json!({+ "doc_kind": "file",+ "file_key": file_key,+ "path": path,+ "format": "duplicate",+ "status": "duplicate",+ "reason": format!("byte-identical content already indexed from {duplicate_of}"),+ "duplicate_of": duplicate_of,+ "records": 0,+ "junk": 0,+ "bytes": bytes,+ "run_id": run_id,+ }),+ )+}++pub fn duplicate_file_id(file_key: &str, path: &str, path_id: &str) -> String {+ let identity = if path_id.is_empty() { path } else { path_id };+ format!(+ "file-alias:{}",+ crate::ids::doc_id("duplicate-file", file_key, identity)+ )+}+/// Build the five ready-to-send query classes for a dataset./// Only verified-working forms are ever emitted.pub fn build_sample_queries(pd: &PlanDataset, correlations: &[KeyCorr]) -> Vec<Value> {@@ -248,6 +285,7 @@ pub fn render_map(datasets: &[Value],correlations: &[Value],junk_files: &[Value],+ duplicate_files: &[Value],junk_total: u64,) -> String {let mut s = String::new();@@ -255,10 +293,12 @@ pub fn render_map(if let Some(r) = run {let g = |k: &str| r.get(k).map(pretty_val).unwrap_or_default();s.push_str(&format!(- "run `{}` — root `{}` — {} files, {} records indexed, {} junk records, wall {}s\n\n",+ "run `{}` — root `{}` — {} paths ({} unique content, {} duplicate aliases), {} records indexed, {} junk records, wall {}s\n\n",g("run_id"),g("root"),g("files_total"),+ g("unique_content_files"),+ g("duplicate_files"),g("records_total"),g("junk_records_total"),g("wall_seconds"),@@ -400,6 +440,21 @@ pub fn render_map(}}+ if !duplicate_files.is_empty() {+ s.push_str(&format!(+ "## Duplicate aliases ({} paths; content indexed once)\n\n",+ duplicate_files.len()+ ));+ for file in duplicate_files.iter().take(30) {+ let g = |key: &str| file.get(key).map(pretty_val).unwrap_or_default();+ s.push_str(&format!("- `{}` → `{}`\n", g("path"), g("duplicate_of")));+ }+ if duplicate_files.len() > 30 {+ s.push_str(&format!("- … and {} more\n", duplicate_files.len() - 30));+ }+ s.push('\n');+ }+if !correlations.is_empty() {s.push_str("## Cross-dataset correlations\n\n");for c in correlations {@@ -490,3 +545,22 @@ fn trunc_f(s: &str) -> String {Err(_) => s.to_string(),}}++#[cfg(test)]+mod duplicate_tests {+ use super::*;++ #[test]+ fn duplicate_aliases_render_separately_from_junk() {+ let duplicate = json!({+ "path": "copy.pdf",+ "duplicate_of": "report.pdf",+ "status": "duplicate"+ });+ let rendered = render_map(None, &[], &[], &[], &[duplicate], 0);+ assert!(rendered.contains("## Duplicate aliases"));+ assert_eq!(rendered.matches("## Duplicate aliases").count(), 1);+ assert!(rendered.contains("`copy.pdf` → `report.pdf`"));+ assert!(!rendered.contains("## Junk / skipped"));+ }+}diff --git a/engine/crates/xerj-autoindex/src/content.rs b/engine/crates/xerj-autoindex/src/content.rsnew file mode 100644index 000000000..4f865b47a--- /dev/null+++ b/engine/crates/xerj-autoindex/src/content.rs@@ -0,0 +1,285 @@+//! Full-content identity, duplicate grouping, and mutation detection.++use crate::state::DuplicateFile;+use crate::walk::FileEntry;+use anyhow::{Context, Result};+use rayon::prelude::*;+use std::collections::HashMap;+use std::fs::File;+use std::io::{BufReader, Read};+use std::path::Path;+use xxhash_rust::xxh3::Xxh3;++pub struct Inventory {+ pub files: Vec<FileEntry>,+ /// Durable document identity. New plans use the full-content key.+ pub keys: Vec<String>,+ /// Full digest used to detect mutations even when a legacy key is retained.+ pub digests: Vec<String>,+ pub duplicates: Vec<DuplicateFile>,+}++/// Hash each file once, group equal digests, then byte-verify only digest peers.+///+/// This is linear in corpus bytes for adversarial common-prefix inputs rather+/// than pairwise O(n² × file_size).+pub fn resolve(files: Vec<FileEntry>) -> Result<Inventory> {+ let digests: Vec<Result<String>> = files+ .par_iter()+ .map(|file| full_digest(&file.path, file.size))+ .collect();+ let digests: Vec<String> = digests.into_iter().collect::<Result<_>>()?;+ resolve_with_digests(files, digests)+}++fn resolve_with_digests(files: Vec<FileEntry>, digests: Vec<String>) -> Result<Inventory> {+ let mut groups: HashMap<&str, Vec<usize>> = HashMap::new();+ for (index, digest) in digests.iter().enumerate() {+ groups.entry(digest).or_default().push(index);+ }++ let mut keep = vec![true; files.len()];+ let mut resolved_keys = digests.clone();+ let mut duplicates = Vec::new();+ for indices in groups.values() {+ if indices.len() < 2 {+ continue;+ }+ let mut indices = indices.clone();+ // Prefer a real in-tree path over a followed symlink as canonical.+ indices.sort_by_key(|&index| (files[index].is_symlink, files[index].rel.clone()));+ // A digest match is still only a candidate: verify exact bytes.+ let mut representatives: Vec<usize> = Vec::new();+ for index in indices {+ let canonical = representatives.iter().copied().find(|&candidate| {+ same_file_identity(&files[candidate].path, &files[index].path)+ || files_equal(&files[candidate].path, &files[index].path).unwrap_or(false)+ });+ if let Some(canonical) = canonical {+ keep[index] = false;+ duplicates.push(DuplicateFile {+ file_key: resolved_keys[canonical].clone(),+ rel: files[index].rel.clone(),+ path_id: files[index].rel_id.clone(),+ duplicate_of: files[canonical].rel.clone(),+ bytes: files[index].size,+ });+ } else {+ if !representatives.is_empty() {+ // A full-digest collision was byte-proven, not assumed.+ // Give the unequal representative a deterministic,+ // path-specific discriminator so documents cannot collide.+ resolved_keys[index] = format!(+ "{}-collision-{:032x}",+ digests[index],+ xxhash_rust::xxh3::xxh3_128(files[index].rel_id.as_bytes())+ );+ }+ representatives.push(index);+ }+ }+ }++ let mut unique_files = Vec::new();+ let mut unique_keys = Vec::new();+ let mut unique_digests = Vec::new();+ for (index, file) in files.into_iter().enumerate() {+ if keep[index] {+ unique_files.push(file);+ unique_keys.push(resolved_keys[index].clone());+ unique_digests.push(digests[index].clone());+ }+ }+ duplicates.sort_by(|a, b| a.rel.cmp(&b.rel));+ Ok(Inventory {+ files: unique_files,+ keys: unique_keys,+ digests: unique_digests,+ duplicates,+ })+}++pub fn verify(path: &Path, expected_size: u64, expected_digest: &str) -> Result<()> {+ let actual_size = std::fs::metadata(path)+ .with_context(|| format!("stat {}", path.display()))?+ .len();+ anyhow::ensure!(+ actual_size == expected_size,+ "{} changed size during autoindex (expected {}, now {}); retry the run",+ path.display(),+ expected_size,+ actual_size+ );+ let actual = full_digest(path, actual_size)?;+ anyhow::ensure!(+ actual == expected_digest,+ "{} changed content during autoindex; retry the run",+ path.display()+ );+ Ok(())+}++fn full_digest(path: &Path, size: u64) -> Result<String> {+ let mut file =+ BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);+ let mut hash = Xxh3::new();+ let mut buf = [0u8; 64 * 1024];+ loop {+ let n = file.read(&mut buf)?;+ if n == 0 {+ break;+ }+ hash.update(&buf[..n]);+ }+ Ok(format!("axf2-{:032x}-{size:x}", hash.digest128()))+}++fn files_equal(a: &Path, b: &Path) -> Result<bool> {+ let mut a = BufReader::new(File::open(a).with_context(|| format!("open {}", a.display()))?);+ let mut b = BufReader::new(File::open(b).with_context(|| format!("open {}", b.display()))?);+ let mut ab = [0u8; 64 * 1024];+ let mut bb = [0u8; 64 * 1024];+ loop {+ let an = read_chunk(&mut a, &mut ab)?;+ let bn = read_chunk(&mut b, &mut bb)?;+ if an != bn || ab[..an] != bb[..bn] {+ return Ok(false);+ }+ if an == 0 {+ return Ok(true);+ }+ }+}++#[cfg(unix)]+fn same_file_identity(a: &Path, b: &Path) -> bool {+ use std::os::unix::fs::MetadataExt;+ match (std::fs::metadata(a), std::fs::metadata(b)) {+ (Ok(a), Ok(b)) => a.dev() == b.dev() && a.ino() == b.ino(),+ _ => false,+ }+}++#[cfg(not(unix))]+fn same_file_identity(_a: &Path, _b: &Path) -> bool {+ false+}++fn read_chunk(reader: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {+ let mut read = 0;+ while read < buf.len() {+ let n = reader.read(&mut buf[read..])?;+ if n == 0 {+ break;+ }+ read += n;+ }+ Ok(read)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::fs;++ #[test]+ fn identical_paths_become_one_content_file_and_an_alias() {+ let dir = tempfile::tempdir().unwrap();+ fs::write(dir.path().join("a.txt"), b"same records\n").unwrap();+ fs::write(dir.path().join("b.txt"), b"same records\n").unwrap();+ let inv = resolve(crate::walk::walk(dir.path(), false).unwrap()).unwrap();+ assert_eq!(inv.files.len(), 1);+ assert_eq!(inv.files[0].rel, "a.txt");+ assert_eq!(inv.duplicates.len(), 1);+ assert_eq!(inv.duplicates[0].duplicate_of, "a.txt");+ assert_eq!(inv.keys[0], inv.duplicates[0].file_key);+ }++ #[test]+ fn same_prefix_and_size_but_different_tail_get_distinct_durable_keys() {+ let dir = tempfile::tempdir().unwrap();+ let mut first = vec![b'x'; 65_537];+ let mut second = first.clone();+ first[65_536] = b'a';+ second[65_536] = b'b';+ fs::write(dir.path().join("a.txt"), first).unwrap();+ fs::write(dir.path().join("b.txt"), second).unwrap();+ let inv = resolve(crate::walk::walk(dir.path(), false).unwrap()).unwrap();+ assert_eq!(inv.files.len(), 2);+ assert!(inv.duplicates.is_empty());+ assert_ne!(inv.keys[0], inv.keys[1]);+ }++ #[test]+ fn verification_detects_same_size_tail_mutation() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("a.txt");+ fs::write(&path, b"content-a").unwrap();+ let inv = resolve(crate::walk::walk(dir.path(), false).unwrap()).unwrap();+ fs::write(&path, b"content-b").unwrap();+ assert!(verify(&path, 9, &inv.digests[0]).is_err());+ }++ #[test]+ fn byte_proven_full_digest_collision_gets_distinct_document_identity() {+ let dir = tempfile::tempdir().unwrap();+ fs::write(dir.path().join("a.txt"), b"unequal-a").unwrap();+ fs::write(dir.path().join("b.txt"), b"unequal-b").unwrap();+ let files = crate::walk::walk(dir.path(), false).unwrap();+ let forced = vec!["axf2-forced-9".to_string(); 2];+ let inv = resolve_with_digests(files, forced).unwrap();+ assert_eq!(inv.files.len(), 2);+ assert!(inv.duplicates.is_empty());+ assert_ne!(inv.keys[0], inv.keys[1]);+ assert!(inv.keys.iter().any(|key| key.contains("-collision-")));+ }++ #[cfg(unix)]+ #[test]+ fn hardlinks_are_aliases_without_pairwise_reading() {+ let dir = tempfile::tempdir().unwrap();+ let a = dir.path().join("a.txt");+ let b = dir.path().join("b.txt");+ fs::write(&a, b"hardlinked").unwrap();+ fs::hard_link(&a, &b).unwrap();+ let inv = resolve(crate::walk::walk(dir.path(), false).unwrap()).unwrap();+ assert_eq!(inv.files.len(), 1);+ assert_eq!(inv.duplicates.len(), 1);+ }++ #[cfg(unix)]+ #[test]+ fn lossy_display_collisions_keep_distinct_alias_identities() {+ use std::ffi::OsString;+ use std::os::unix::ffi::OsStringExt;+ let dir = tempfile::tempdir().unwrap();+ fs::write(dir.path().join("canonical"), b"same").unwrap();+ fs::write(+ dir.path().join(OsString::from_vec(vec![b'a', 0x80])),+ b"same",+ )+ .unwrap();+ fs::write(+ dir.path().join(OsString::from_vec(vec![b'a', 0x81])),+ b"same",+ )+ .unwrap();+ let inv = resolve(crate::walk::walk(dir.path(), false).unwrap()).unwrap();+ assert_eq!(inv.files.len(), 1);+ assert_eq!(inv.duplicates.len(), 2);+ assert_ne!(inv.duplicates[0].path_id, inv.duplicates[1].path_id);+ }++ #[cfg(unix)]+ #[test]+ fn followed_symlink_does_not_become_canonical_over_real_path() {+ use std::os::unix::fs::symlink;+ let dir = tempfile::tempdir().unwrap();+ let real = dir.path().join("z-real");+ fs::write(&real, b"same").unwrap();+ symlink(&real, dir.path().join("a-link")).unwrap();+ let inv = resolve(crate::walk::walk(dir.path(), true).unwrap()).unwrap();+ assert_eq!(inv.files[0].rel, "z-real");+ assert_eq!(inv.duplicates[0].rel, "a-link");+ }+}diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rsindex e5bc2348b..6e45d0ab0 100644--- a/engine/crates/xerj-autoindex/src/esclient.rs+++ b/engine/crates/xerj-autoindex/src/esclient.rs@@ -131,6 +131,21 @@ impl Es {Err(anyhow!("PUT /{index} failed: {status} {text}"))}+ /// Additive mapping update for fields introduced after an index was created.+ pub fn update_mapping(&self, index: &str, body: &Value) -> Result<()> {+ let resp = self+ .req(reqwest::Method::PUT, &format!("/{index}/_mapping"))+ .json(body)+ .send()+ .context("PUT mapping")?;+ let status = resp.status();+ if status.is_success() {+ return Ok(());+ }+ let text = resp.text().unwrap_or_default();+ Err(anyhow!("PUT /{index}/_mapping failed: {status} {text}"))+ }+pub fn bulk(&self, body: Vec<u8>) -> Result<BulkOutcome> {self.with_retry("_bulk",@@ -195,6 +210,40 @@ impl Es {.with_context(|| format!("bulk send (request timeout {:?})", self.bulk_timeout))}+ /// Remove every document matching `query` before a file-level replacement.+ /// Refresh is requested so a retry cannot observe or retain an older+ /// locator set alongside the replacement.+ pub fn delete_by_query(&self, index: &str, query: &Value) -> Result<()> {+ self.with_retry(+ "delete_by_query",+ || {+ self.req(+ reqwest::Method::POST,+ &format!("/{index}/_delete_by_query?refresh=true"),+ )+ .json(&serde_json::json!({"query": query}))+ .send()+ .map_err(|e| anyhow!("delete_by_query: {e}"))+ },+ |resp| {+ let status = resp.status();+ let body: Value = resp.json().unwrap_or(Value::Null);+ if status.is_success()+ && body+ .get("failures")+ .and_then(Value::as_array)+ .is_none_or(Vec::is_empty)+ {+ Ok(())+ } else {+ Err(anyhow!(+ "POST /{index}/_delete_by_query failed: HTTP {status}: {body}"+ ))+ }+ },+ )+ }+pub fn refresh(&self, pattern: &str) -> Result<()> {self.with_retry("refresh",diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rsnew file mode 100644index 000000000..9e3d0c612--- /dev/null+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs@@ -0,0 +1,688 @@+//! HTTP-level regression tests for the file replacement transaction.+//!+//! These deliberately exercise `run_index`, `Es`, extraction, staging, bulk+//! splitting, and the durable journal together. The fake endpoint injects a+//! per-item backend failure after applying part of a bulk, which models the+//! most dangerous response shape: visibility changed, but `file_done` must+//! not be durable.++use super::*;+use std::collections::HashMap;+use std::fs;+use std::io::{BufRead, BufReader, Read, Write};+use std::net::{TcpListener, TcpStream};+use std::sync::{Arc, Mutex};+use std::thread;++static FAILPOINT_TEST_LOCK: Mutex<()> = Mutex::new(());++#[derive(Default)]+struct MockState {+ docs: HashMap<String, Value>,+ data_bulk_number: usize,+ fail_data_bulk: usize,+ failed_once: bool,+ delete_calls: usize,+ stop: bool,+}++struct MockEndpoint {+ url: String,+ state: Arc<Mutex<MockState>>,+ join: Option<thread::JoinHandle<()>>,+}++impl MockEndpoint {+ fn start(fail_data_bulk: usize) -> Self {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ listener.set_nonblocking(true).unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ let state = Arc::new(Mutex::new(MockState {+ fail_data_bulk,+ ..MockState::default()+ }));+ let server_state = Arc::clone(&state);+ let join = thread::spawn(move || loop {+ match listener.accept() {+ Ok((stream, _)) => handle(stream, &server_state),+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {+ if server_state.lock().unwrap().stop {+ break;+ }+ thread::yield_now();+ }+ Err(error) => panic!("mock endpoint accept failed: {error}"),+ }+ });+ Self {+ url,+ state,+ join: Some(join),+ }+ }+}++impl Drop for MockEndpoint {+ fn drop(&mut self) {+ self.state.lock().unwrap().stop = true;+ // Wake the nonblocking listener even on heavily loaded test hosts.+ let _ = TcpStream::connect(self.url.trim_start_matches("http://"));+ self.join.take().unwrap().join().unwrap();+ }+}++fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {+ let clone = stream.try_clone().unwrap();+ let mut reader = BufReader::new(clone);+ let mut request_line = String::new();+ if reader.read_line(&mut request_line).unwrap() == 0 {+ return;+ }+ let mut content_length = 0usize;+ loop {+ let mut line = String::new();+ reader.read_line(&mut line).unwrap();+ if line == "\r\n" || line.is_empty() {+ break;+ }+ if let Some(value) = line+ .to_ascii_lowercase()+ .strip_prefix("content-length:")+ .map(str::trim)+ {+ content_length = value.parse().unwrap();+ }+ }+ let mut body = vec![0; content_length];+ reader.read_exact(&mut body).unwrap();+ let mut parts = request_line.split_whitespace();+ let method = parts.next().unwrap_or("");+ let path = parts.next().unwrap_or("");++ let response = if method == "POST" && path == "/_bulk" {+ bulk_response(&body, state)+ } else if method == "POST" && path.contains("/_delete_by_query") {+ let query: Value = serde_json::from_slice(&body).unwrap();+ let ax_file = query+ .pointer("/query/term/ax_file")+ .and_then(Value::as_str)+ .map(str::to_owned);+ let mut locked = state.lock().unwrap();+ locked.delete_calls += 1;+ if let Some(key) = ax_file {+ locked+ .docs+ .retain(|_, doc| doc.get("ax_file").and_then(Value::as_str) != Some(key.as_str()));+ }+ json!({"deleted": 0, "failures": []})+ } else if method == "GET" && path.ends_with("/_count") {+ json!({"count": state.lock().unwrap().docs.len()})+ } else if method == "POST" && path.ends_with("/_search") {+ json!({"hits":{"total":{"value":0},"hits":[]},"aggregations":{}})+ } else {+ // ping, index creation/mapping, refresh, and catalog operations+ json!({"acknowledged": true})+ };+ let bytes = response.to_string();+ write!(+ stream,+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",+ bytes.len(),+ bytes+ )+ .unwrap();+}++fn bulk_response(body: &[u8], state: &Arc<Mutex<MockState>>) -> Value {+ let lines: Vec<&[u8]> = body+ .split(|byte| *byte == b'\n')+ .filter(|line| !line.is_empty())+ .collect();+ let is_data = lines+ .first()+ .and_then(|line| serde_json::from_slice::<Value>(line).ok())+ .and_then(|action| action.pointer("/index/_index").cloned())+ .and_then(|index| index.as_str().map(str::to_owned))+ .is_some_and(|index| index != catalog::CATALOG_INDEX);+ if !is_data {+ return json!({"errors": false, "items": []});+ }++ let mut locked = state.lock().unwrap();+ locked.data_bulk_number += 1;+ let fail = !locked.failed_once && locked.data_bulk_number == locked.fail_data_bulk;+ let pairs = lines.chunks_exact(2);+ let visible = if fail { pairs.len() / 2 } else { pairs.len() };+ for pair in lines.chunks_exact(2).take(visible) {+ let action: Value = serde_json::from_slice(pair[0]).unwrap();+ let doc: Value = serde_json::from_slice(pair[1]).unwrap();+ let id = action.pointer("/index/_id").unwrap().as_str().unwrap();+ locked.docs.insert(id.to_owned(), doc);+ }+ if fail {+ locked.failed_once = true;+ json!({+ "errors": true,+ "items": [{"index": {+ "status": 500,+ "error": {"type": "injected_failure", "reason": "partial bulk"}+ }}]+ })+ } else {+ json!({"errors": false, "items": []})+ }+}++fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {+ IndexCfg {+ root: root.to_owned(),+ url: url.to_owned(),+ api_key: None,+ workers: 1,+ pdf_workers: 1,+ pdf_timeout_secs: 30,+ bulk_mb: 64,+ bulk_timeout_secs: 3_600,+ prefix: "failure-test".into(),+ state_dir: Some(state_dir.to_owned()),+ fresh: false,+ follow_symlinks: false,+ max_file_gb: 1,+ sample: 50,+ no_semantic: true,+ dry_run: false,+ json: false,+ quiet: true,+ }+}++fn file_done_count(state_dir: &Path) -> usize {+ let journal = fs::read_to_string(state_dir.join("journal.ndjson")).unwrap();+ journal+ .lines()+ .filter(|line| {+ serde_json::from_str::<Value>(line)+ .ok()+ .and_then(|value| value.get("kind").cloned())+ .as_ref()+ .and_then(Value::as_str)+ == Some("file_done")+ })+ .count()+}++fn event_count(state_dir: &Path, kind: &str) -> usize {+ fs::read_to_string(state_dir.join("journal.ndjson"))+ .unwrap()+ .lines()+ .filter_map(|line| serde_json::from_str::<Value>(line).ok())+ .filter(|value| value.get("kind").and_then(Value::as_str) == Some(kind))+ .count()+}++#[test]+fn fresh_publication_skips_delete_and_noop_resume_does_not_append_plan() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(+ corpus.path().join("records.csv"),+ "id,value\n0,fresh\n1,fresh\n",+ )+ .unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);++ assert_eq!(run_index(config.clone()).unwrap(), 0);+ assert_eq!(endpoint.state.lock().unwrap().delete_calls, 0);+ assert_eq!(event_count(state_dir.path(), "plan"), 1);+ assert_eq!(event_count(state_dir.path(), "file_replace_start"), 1);++ assert_eq!(run_index(config).unwrap(), 0);+ assert_eq!(endpoint.state.lock().unwrap().delete_calls, 0);+ assert_eq!(+ event_count(state_dir.path(), "plan"),+ 1,+ "an identical resume must reuse the durable plan"+ );+}++#[test]+fn legacy_plan_without_completion_cleans_possible_partial_visibility() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let first_state = tempfile::tempdir().unwrap();+ let legacy_state = tempfile::tempdir().unwrap();+ fs::write(+ corpus.path().join("records.csv"),+ "id,value\n0,current\n1,current\n",+ )+ .unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let first_config = cfg(corpus.path(), first_state.path(), &endpoint.url);+ assert_eq!(run_index(first_config.clone()).unwrap(), 0);++ let root = first_config+ .root+ .canonicalize()+ .unwrap()+ .to_string_lossy()+ .to_string();+ let first = state::Journal::open(+ first_state.path(),+ &root,+ &first_config.url,+ &first_config.prefix,+ first_config.bulk_timeout_secs,+ false,+ )+ .unwrap();+ let plan = first.plan.clone().unwrap();+ let key = plan.files.keys().next().unwrap().clone();+ drop(first);++ // A pre-intent journal may contain only its plan even though older or+ // partial bulk records are already visible.+ let mut legacy = state::Journal::open(+ legacy_state.path(),+ &root,+ &first_config.url,+ &first_config.prefix,+ first_config.bulk_timeout_secs,+ false,+ )+ .unwrap();+ legacy.write_plan(&plan).unwrap();+ drop(legacy);+ let deletes_before = {+ let mut state = endpoint.state.lock().unwrap();+ state.docs.insert(+ "obsolete-locator".to_string(),+ json!({+ "ax_file": key,+ "ax_locator": "obsolete",+ "value": "must-be-removed"+ }),+ );+ state.delete_calls+ };++ let mut resume_config = first_config;+ resume_config.state_dir = Some(legacy_state.path().to_owned());+ assert_eq!(run_index(resume_config).unwrap(), 0);+ let state = endpoint.state.lock().unwrap();+ assert_eq!(state.delete_calls, deletes_before + 1);+ assert!(!state.docs.contains_key("obsolete-locator"));+ assert!(state+ .docs+ .values()+ .all(|doc| doc.get("ax_locator").and_then(Value::as_str) != Some("obsolete")));+}++#[test]+fn legacy_key_collision_fails_before_visibility_and_points_to_fresh() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ let mut owner = vec![b'x'; 65_537];+ owner[65_536] = b'b';+ let owner_path = corpus.path().join("b.txt");+ fs::write(&owner_path, &owner).unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 0);++ // Convert the current full-content plan into the exact legacy shape which+ // keyed content from first-64-KiB + size.+ let legacy_key = ids::file_key(&owner_path, owner.len() as u64).unwrap();+ let root = config+ .root+ .canonicalize()+ .unwrap()+ .to_string_lossy()+ .to_string();+ let mut journal = state::Journal::open(+ state_dir.path(),+ &root,+ &config.url,+ &config.prefix,+ config.bulk_timeout_secs,+ false,+ )+ .unwrap();+ let mut plan = journal.plan.clone().unwrap();+ let old_key = plan.files.keys().next().unwrap().clone();+ let assignment = plan.files.remove(&old_key).unwrap();+ plan.files.insert(legacy_key, assignment);+ journal.write_plan(&plan).unwrap();+ drop(journal);++ let mut sibling = owner;+ sibling[65_536] = b'a';+ fs::write(corpus.path().join("a.txt"), sibling).unwrap();+ let (bulks_before, deletes_before, docs_before) = {+ let state = endpoint.state.lock().unwrap();+ (+ state.data_bulk_number,+ state.delete_calls,+ state.docs.clone(),+ )+ };+ let error = run_index(config).unwrap_err();+ let message = format!("{error:#}");+ assert!(message.contains("collides with legacy resume key"));+ assert!(message.contains("rerun with --fresh"));+ let state = endpoint.state.lock().unwrap();+ assert_eq!(state.data_bulk_number, bulks_before);+ assert_eq!(state.delete_calls, deletes_before);+ assert_eq!(state.docs, docs_before);+}++#[test]+fn existing_completion_is_invalidated_and_partial_visibility_is_deleted_on_resume() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ // 1: failure immediately after delete; 2: one complete 5,000-doc bulk+ // then a partial final bulk; 3: two complete bulks then a partial final+ // bulk immediately before the file_done journal append.+ for (fail_bulk, rows) in [(1, 6_001usize), (2, 6_001), (3, 10_001)] {+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ let mut csv = String::from("id,value\n");+ for row in 0..rows {+ csv.push_str(&format!("{row},value-{row}\n"));+ }+ fs::write(corpus.path().join("records.csv"), &csv).unwrap();+ let endpoint = MockEndpoint::start(fail_bulk);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);++ // Establish the dangerous case: an older generation is both live and+ // durably complete before the replacement begins.+ {+ let mut locked = endpoint.state.lock().unwrap();+ locked.fail_data_bulk = usize::MAX;+ }+ assert_eq!(run_index(config.clone()).unwrap(), 0);+ assert_eq!(file_done_count(state_dir.path()), 1);+ fs::write(+ corpus.path().join("records.csv"),+ csv.replace("value-", "replacement-"),+ )+ .unwrap();+ {+ let mut locked = endpoint.state.lock().unwrap();+ locked.data_bulk_number = 0;+ locked.fail_data_bulk = fail_bulk;+ locked.failed_once = false;+ }+ let error = run_index(config.clone()).unwrap_err();+ assert!(+ error.to_string().contains("bulk/backend failures"),+ "{error:#}"+ );+ assert_eq!(+ file_done_count(state_dir.path()),+ 1,+ "failure after data bulk {fail_bulk} must retain only historical completion"+ );+ let replay = state::Journal::open(+ state_dir.path(),+ &config.root.to_string_lossy(),+ &config.url,+ &config.prefix,+ config.bulk_timeout_secs,+ false,+ )+ .unwrap();+ assert!(+ replay.done.is_empty(),+ "replacement intent must invalidate historical file_done on replay"+ );+ assert_eq!(replay.pending_replacements.len(), 1);+ drop(replay);+ {+ let locked = endpoint.state.lock().unwrap();+ assert!(locked.failed_once);+ assert!(locked.docs.len() < rows);+ }++ assert_eq!(run_index(config).unwrap(), 0);+ assert_eq!(file_done_count(state_dir.path()), 2);+ let locked = endpoint.state.lock().unwrap();+ assert_eq!(locked.docs.len(), rows);+ assert_eq!(+ locked.delete_calls, 2,+ "fresh publication skips delete; replacement and repair each clean once"+ );+ assert!(locked.docs.values().all(|doc| {+ doc["value"]+ .as_str()+ .is_some_and(|value| value.starts_with("replacement-"))+ }));+ let mut locators: Vec<usize> = locked+ .docs+ .values()+ .map(|doc| {+ doc["ax_locator"]+ .as_str()+ .unwrap()+ .trim_start_matches('r')+ .parse()+ .unwrap()+ })+ .collect();+ locators.sort_unstable();+ assert_eq!(locators, (0..rows).collect::<Vec<_>>());+ }+}++#[test]+fn resume_repairs_kills_after_plan_delete_and_final_bulk_before_file_done() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ for boundary in [1u8, 2, 4] {+ let rows = 6_001usize;+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ let path = corpus.path().join("records.csv");+ let mut csv = String::from("id,value\n");+ for row in 0..rows {+ csv.push_str(&format!("{row},old-{row}\n"));+ }+ fs::write(&path, &csv).unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 0);+ fs::write(&path, csv.replace("old-", "new-")).unwrap();++ REPLACEMENT_FAILPOINT.store(boundary, Ordering::SeqCst);+ let error = run_index(config.clone()).unwrap_err();+ assert!(+ format!("{error:#}").contains("injected replacement crash"),+ "boundary {boundary}: {error:#}"+ );+ let replay = state::Journal::open(+ state_dir.path(),+ &config.root.to_string_lossy(),+ &config.url,+ &config.prefix,+ config.bulk_timeout_secs,+ false,+ )+ .unwrap();+ assert!(replay.done.is_empty(), "boundary {boundary}");+ assert_eq!(replay.pending_replacements.len(), 1, "boundary {boundary}");+ drop(replay);++ assert_eq!(run_index(config).unwrap(), 0);+ let locked = endpoint.state.lock().unwrap();+ assert_eq!(locked.docs.len(), rows, "boundary {boundary}");+ assert!(locked.docs.values().all(|doc| {+ doc["value"]+ .as_str()+ .is_some_and(|value| value.starts_with("new-"))+ }));+ }+}++#[test]+fn file_done_append_and_fsync_failures_are_fatal_and_resume_repairs() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();+ for io_boundary in [1u8, 2, 3] {+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ let path = corpus.path().join("records.csv");+ fs::write(&path, "id,value\n0,old\n1,old\n").unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 0);+ fs::write(&path, "id,value\n0,new\n1,new\n").unwrap();++ state::fail_next_file_done_io(io_boundary);+ let error = run_index(config.clone()).unwrap_err();+ let message = format!("{error:#}");+ assert!(+ message.contains("durably commit completed source"),+ "{message}"+ );+ assert!(+ message.contains(if io_boundary == 1 {+ "append failure"+ } else if io_boundary == 3 {+ "partial file_done write"+ } else {+ "fsync failure"+ }),+ "{message}"+ );+ let replay = state::Journal::open(+ state_dir.path(),+ &config.root.to_string_lossy(),+ &config.url,+ &config.prefix,+ config.bulk_timeout_secs,+ false,+ )+ .unwrap();+ assert!(replay.done.is_empty());+ assert_eq!(replay.pending_replacements.len(), 1);+ drop(replay);++ assert_eq!(run_index(config).unwrap(), 0);+ let locked = endpoint.state.lock().unwrap();+ assert_eq!(locked.docs.len(), 2);+ assert!(locked+ .docs+ .values()+ .all(|doc| doc["value"].as_str() == Some("new")));+ }+}++#[test]+fn pending_generation_b_is_superseded_when_source_changes_to_c() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ let path = corpus.path().join("records.csv");+ fs::write(&path, "id,value\n0,generation-a\n1,generation-a\n").unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ assert_eq!(run_index(config.clone()).unwrap(), 0);++ fs::write(&path, "id,value\n0,generation-b\n1,generation-b\n").unwrap();+ REPLACEMENT_FAILPOINT.store(2, Ordering::SeqCst);+ run_index(config.clone()).unwrap_err();+ let replay_b = state::Journal::open(+ state_dir.path(),+ &config.root.to_string_lossy(),+ &config.url,+ &config.prefix,+ config.bulk_timeout_secs,+ false,+ )+ .unwrap();+ let key = replay_b.pending_replacements.keys().next().unwrap().clone();+ let generation_b = replay_b.pending_replacements[&key].clone();+ drop(replay_b);++ fs::write(&path, "id,value\n0,generation-c\n1,generation-c\n").unwrap();+ assert_eq!(run_index(config.clone()).unwrap(), 0);+ let replay_c = state::Journal::open(+ state_dir.path(),+ &config.root.to_string_lossy(),+ &config.url,+ &config.prefix,+ config.bulk_timeout_secs,+ false,+ )+ .unwrap();+ assert!(replay_c.pending_replacements.is_empty());+ let committed_generation = replay_c.done[&key].generation.as_deref().unwrap();+ assert_ne!(committed_generation, generation_b);+ let events: Vec<Value> = fs::read_to_string(state_dir.path().join("journal.ndjson"))+ .unwrap()+ .lines()+ .map(|line| serde_json::from_str(line).unwrap())+ .collect();+ let starts: Vec<&str> = events+ .iter()+ .filter(|event| {+ event["kind"] == "file_replace_start"+ && event["file_key"].as_str() == Some(key.as_str())+ })+ .filter_map(|event| event["generation"].as_str())+ .collect();+ assert_eq!(starts[starts.len() - 2], generation_b);+ assert_eq!(starts.last().copied(), Some(committed_generation));+ drop(replay_c);+ let locked = endpoint.state.lock().unwrap();+ assert_eq!(locked.docs.len(), 2);+ assert!(locked+ .docs+ .values()+ .all(|doc| doc["value"].as_str() == Some("generation-c")));+}++#[test]+fn partial_file_done_is_rolled_back_before_another_worker_commits() {+ let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();+ let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ fs::write(corpus.path().join("a.csv"), "id,value\n0,a-old\n1,a-old\n").unwrap();+ fs::write(corpus.path().join("b.csv"), "id,value\n2,b-old\n3,b-old\n").unwrap();+ let endpoint = MockEndpoint::start(usize::MAX);+ let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);+ config.workers = 2;+ assert_eq!(run_index(config.clone()).unwrap(), 0);++ fs::write(corpus.path().join("a.csv"), "id,value\n0,a-new\n1,a-new\n").unwrap();+ fs::write(corpus.path().join("b.csv"), "id,value\n2,b-new\n3,b-new\n").unwrap();+ state::fail_next_file_done_io(3);+ let error = run_index(config.clone()).unwrap_err();+ assert!(format!("{error:#}").contains("partial file_done write"));++ // One worker hit the partial append and rolled back while the other was+ // allowed to commit. Replay must remain parseable and expose exactly one+ // pending generation rather than malformed middle corruption.+ let replay = state::Journal::open(+ state_dir.path(),+ &config.root.to_string_lossy(),+ &config.url,+ &config.prefix,+ config.bulk_timeout_secs,+ false,+ )+ .unwrap();+ assert_eq!(replay.pending_replacements.len(), 1);+ assert_eq!(replay.done.len(), 1);+ drop(replay);++ assert_eq!(run_index(config).unwrap(), 0);+ let locked = endpoint.state.lock().unwrap();+ assert_eq!(locked.docs.len(), 4);+ assert!(locked.docs.values().all(|doc| {+ doc["value"]+ .as_str()+ .is_some_and(|value| value.ends_with("-new"))+ }));+}diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex d2cc3a1a0..a346d6124 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -6,6 +6,7 @@pub mod catalog;pub mod cli;pub mod coerce;+mod content;pub mod correlate;pub mod dataset;pub mod esclient;@@ -19,6 +20,7 @@ pub mod walk;use anyhow::{Context, Result};use serde_json::{json, Map, Value};use std::collections::HashMap;+use std::io::{BufRead, BufReader, Seek, Write};use std::path::Path;use std::sync::atomic::{AtomicU64, Ordering};use std::sync::Mutex;@@ -63,6 +65,65 @@ const GB: u64 = 1 << 30;const SAMPLE_LIMIT_BYTES: u64 = 4 << 20;const SQLDUMP_SAMPLE_LIMIT: u64 = 64 << 20;+#[cfg(test)]+static REPLACEMENT_FAILPOINT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);++#[cfg(test)]+fn replacement_failpoint(boundary: u8) -> Result<()> {+ if REPLACEMENT_FAILPOINT+ .compare_exchange(boundary, 0, Ordering::SeqCst, Ordering::SeqCst)+ .is_ok()+ {+ anyhow::bail!("injected replacement crash boundary {boundary}");+ }+ Ok(())+}++#[cfg(not(test))]+#[inline]+fn replacement_failpoint(_boundary: u8) -> Result<()> {+ Ok(())+}++fn record_bulk_outcome(+ es: &Es,+ body: Vec<u8>,+ junk_records: &AtomicU64,+ bulk_errors: &Mutex<Vec<String>>,+ send_err: &mut Option<String>,+) -> bool {+ match es.bulk(body) {+ Ok(outcome) => {+ if outcome.server_errors > 0 {+ *send_err = Some(format!(+ "bulk backend failed for {} item(s): {}. Source file was not journaled \+ complete; fix the server/embedding configuration and rerun autoindex",+ outcome.server_errors,+ outcome+ .first_server_error+ .as_deref()+ .unwrap_or("unknown server error")+ ));+ return true;+ }+ if outcome.item_errors > 0 {+ junk_records.fetch_add(outcome.item_errors, Ordering::Relaxed);+ if let Some(error) = outcome.first_error {+ let mut errors = bulk_errors.lock().unwrap();+ if errors.len() < 5 {+ errors.push(error);+ }+ }+ }+ false+ }+ Err(error) => {+ *send_err = Some(format!("{error:#}"));+ true+ }+ }+}+// ─── Phase A: per-file scan (sniff + bounded sampling) ───────────────────struct FileScan {@@ -164,6 +225,7 @@ fn scan_file(path: &Path, size: u64, sample: usize, max_file_gb: u64) -> FileScapub const PROVENANCE_FIELDS: &[&str] = &["ax_path",+ "ax_paths","ax_file","ax_locator","ax_dataset",@@ -188,9 +250,116 @@ fn build_mapping(specs: &[infer::FieldSpec]) -> Value {// ─── the main run ────────────────────────────────────────────────────────+fn select_resume_plan_keys(+ files: &[walk::FileEntry],+ content_keys: &[String],+ plan: &Plan,+) -> Result<Vec<Option<String>>> {+ let mut planned_by_rel: HashMap<&str, &str> = HashMap::new();+ let mut planned_by_path_id: HashMap<&str, &str> = HashMap::new();+ for (key, assignment) in &plan.files {+ if let Some(previous) = planned_by_rel.insert(&assignment.rel, key) {+ anyhow::bail!(+ "resume plan assigns path {} to both {} and {}; use --fresh after verifying the \+ existing index",+ assignment.rel,+ previous,+ key+ );+ }+ if !assignment.path_id.is_empty() {+ if let Some(previous) = planned_by_path_id.insert(&assignment.path_id, key) {+ anyhow::bail!(+ "resume plan assigns one native path identity to both {} and {}; use --fresh \+ after verifying the existing index",+ previous,+ key+ );+ }+ }+ }+ let current_rels: std::collections::HashSet<&str> =+ files.iter().map(|file| file.rel.as_str()).collect();+ let current_path_ids: std::collections::HashSet<&str> =+ files.iter().map(|file| file.rel_id.as_str()).collect();+ let mut claimed = std::collections::HashSet::new();+ let mut selected = Vec::with_capacity(files.len());+ for (file, content_key) in files.iter().zip(content_keys) {+ let exact_path = planned_by_path_id+ .get(file.rel_id.as_str())+ .or_else(|| planned_by_rel.get(file.rel.as_str()))+ .filter(|key| !claimed.contains(**key))+ .map(|key| (*key).to_string());+ let exact_content = plan+ .files+ .contains_key(content_key)+ .then(|| content_key.clone())+ .filter(|key| !claimed.contains(key.as_str()));+ let key = if let Some(key) = exact_path.or(exact_content) {+ Some(key)+ } else {+ // Computing the legacy prefix key is intentionally the final+ // fallback. Normal resumes are O(files), with no 64 KiB read.+ let legacy_key = ids::file_key(&file.path, file.size)?;+ if let Some(assignment) = plan.files.get(&legacy_key) {+ let has_exact_current_owner = current_rels.contains(assignment.rel.as_str())+ || (!assignment.path_id.is_empty()+ && current_path_ids.contains(assignment.path_id.as_str()));+ if claimed.contains(legacy_key.as_str()) || has_exact_current_owner {+ anyhow::bail!(+ "{} collides with legacy resume key {} already owned by {}. No documents \+ were changed; rerun with --fresh to build distinct full-content keys",+ file.rel,+ legacy_key,+ assignment.rel+ );+ }+ Some(legacy_key)+ } else {+ None+ }+ };+ if let Some(key) = &key {+ claimed.insert(key.clone());+ }+ selected.push(key);+ }+ Ok(selected)+}++fn alias_keys_to_reindex(+ previous: &[state::DuplicateFile],+ current: &[state::DuplicateFile],+ migration_keys: Option<&[String]>,+) -> std::collections::HashSet<String> {+ let paths_by_key = |aliases: &[state::DuplicateFile]| {+ let mut by_key: HashMap<String, std::collections::BTreeSet<String>> = HashMap::new();+ for alias in aliases {+ by_key+ .entry(alias.file_key.clone())+ .or_default()+ .insert(alias.rel.clone());+ }+ by_key+ };+ let previous = paths_by_key(previous);+ let current = paths_by_key(current);+ let mut changed = std::collections::HashSet::new();+ if let Some(keys) = migration_keys {+ changed.extend(keys.iter().cloned());+ }+ for key in previous.keys().chain(current.keys()) {+ if previous.get(key) != current.get(key) {+ changed.insert(key.clone());+ }+ }+ changed+}+fn run_index(cfg: IndexCfg) -> Result<i32> {extract::pdf::configure_workers(cfg.pdf_workers);extract::pdf::configure_timeout(cfg.pdf_timeout_secs);+ use rayon::prelude::*;let t0 = Instant::now();if !cfg.quiet {eprintln!(@@ -201,8 +370,8 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {let es = Es::with_bulk_timeout(&cfg.url, cfg.api_key.clone(), cfg.bulk_timeout_secs)?;es.ping()?;- let files = walk::walk(&cfg.root, cfg.follow_symlinks)?;- if files.is_empty() {+ let discovered_files = walk::walk(&cfg.root, cfg.follow_symlinks)?;+ if discovered_files.is_empty() {println!("no files found under {}", cfg.root.display());return Ok(0);}@@ -215,19 +384,12 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {if !cfg.quiet {eprintln!("autoindex: {} files ({} MB) under {}",- files.len(),- files.iter().map(|f| f.size).sum::<u64>() / (1 << 20),+ discovered_files.len(),+ discovered_files.iter().map(|f| f.size).sum::<u64>() / (1 << 20),root_str);}- // content-based file keys (parallel)- use rayon::prelude::*;- let keys: Vec<String> = files- .par_iter()- .map(|f| ids::file_key(&f.path, f.size).unwrap_or_default())- .collect();-let state_dir = cfg.state_dir.clone()@@ -240,6 +402,7 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {cfg.bulk_timeout_secs,cfg.fresh,)?;+ let resumed_with_plan = journal.plan.is_some();let run_id = journal.run_id.clone();if journal.resumed && !cfg.quiet {eprintln!(@@ -248,6 +411,110 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {journal.done.len());}+ // Full hashing on every run is deliberate: size/mtime/inode fingerprints+ // cannot prove byte identity across all supported local and network+ // filesystems. A metadata-only shortcut could leave stale live documents+ // forever after a same-size rewrite with restored or stale timestamps.+ let mut inventory = content::resolve(discovered_files)?;+ let mut content_changed = std::collections::HashSet::new();+ let mut stale_alias_ids = Vec::new();+ let mut alias_paths_to_replace = std::collections::HashSet::new();+ let mut plan_changed = journal.plan.is_none();+ // Preserve legacy document IDs while upgrading old plans with full digests.+ // A later same-size/tail mutation is then detected and reindexed.+ if let Some(plan) = &mut journal.plan {+ let needs_alias_path_migration = !plan.alias_paths_indexed;+ let previous_aliases = plan.duplicate_files.clone();+ alias_paths_to_replace.extend(previous_aliases.iter().map(|alias| alias.rel.clone()));+ stale_alias_ids.extend(+ plan.duplicate_files+ .iter()+ .map(|old| catalog::duplicate_file_id(&old.file_key, &old.rel, &old.path_id)),+ );+ let selected_plan_keys = select_resume_plan_keys(&inventory.files, &inventory.keys, plan)?;+ for (index, planned_key) in selected_plan_keys.into_iter().enumerate() {+ let file = &inventory.files[index];+ if let Some(planned_key) = planned_key {+ let assignment = plan.files.get_mut(&planned_key).expect("planned key");+ if assignment.rel != file.rel {+ content_changed.insert(planned_key.clone());+ plan_changed = true;+ }+ if assignment+ .content_digest+ .as_deref()+ .is_some_and(|digest| digest != inventory.digests[index])+ {+ content_changed.insert(planned_key.clone());+ plan_changed = true;+ }+ if assignment.path_id != file.rel_id+ || assignment.content_digest.as_deref()+ != Some(inventory.digests[index].as_str())+ {+ plan_changed = true;+ }+ assignment.rel = file.rel.clone();+ assignment.path_id = file.rel_id.clone();+ assignment.content_digest = Some(inventory.digests[index].clone());+ inventory.keys[index] = planned_key;+ }+ }+ let key_by_path: HashMap<&str, &str> = inventory+ .files+ .iter()+ .zip(inventory.keys.iter())+ .map(|(file, key)| (file.rel.as_str(), key.as_str()))+ .collect();+ for duplicate in &mut inventory.duplicates {+ if let Some(key) = key_by_path.get(duplicate.duplicate_of.as_str()) {+ duplicate.file_key = (*key).to_string();+ }+ }+ let current_alias_ids: std::collections::HashSet<String> = inventory+ .duplicates+ .iter()+ .map(|alias| catalog::duplicate_file_id(&alias.file_key, &alias.rel, &alias.path_id))+ .collect();+ stale_alias_ids.retain(|id| !current_alias_ids.contains(id));+ // The historical global flag cannot identify which live documents+ // already carry ax_paths. Its one-time migration must rewrite every+ // canonical key; ordinary alias changes remain scoped per key.+ content_changed.extend(alias_keys_to_reindex(+ &previous_aliases,+ &inventory.duplicates,+ needs_alias_path_migration.then_some(inventory.keys.as_slice()),+ ));+ if needs_alias_path_migration {+ plan.alias_paths_indexed = true;+ plan_changed = true;+ }+ if previous_aliases != inventory.duplicates {+ plan_changed = true;+ }+ plan.duplicate_files = inventory.duplicates.clone();+ }+ alias_paths_to_replace.extend(inventory.duplicates.iter().map(|alias| alias.rel.clone()));+ let files = inventory.files;+ let keys = inventory.keys;+ let digests = inventory.digests;+ let duplicate_files = inventory.duplicates;+ let paths_discovered = files.len() + duplicate_files.len();+ if !duplicate_files.is_empty() && !cfg.quiet {+ eprintln!(+ "autoindex: {} byte-identical duplicate path(s) will reuse canonical content",+ duplicate_files.len()+ );+ for duplicate in duplicate_files.iter().take(10) {+ eprintln!(+ " duplicate: {} → {}",+ duplicate.rel, duplicate.duplicate_of+ );+ }+ if duplicate_files.len() > 10 {+ eprintln!(" … and {} more", duplicate_files.len() - 10);+ }+ }// ── Phase A: inference (skipped when a frozen plan exists) ──────────let mut clusters_rt: Option<Vec<dataset::Cluster>> = None;@@ -311,8 +578,10 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {.entry(key.clone()).or_insert_with(|| FileAssignment {rel: files[m].rel.clone(),+ path_id: files[m].rel_id.clone(),family: c.family.as_str().to_string(),gzip: sn.map(|s| s.gzip).unwrap_or(false),+ content_digest: Some(digests[m].clone()),assignments: Vec::new(),});fa.assignments@@ -344,6 +613,8 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {datasets,files: file_assignments,junk_files,+ duplicate_files,+ alias_paths_indexed: true,};clusters_rt = Some(clusters);plan@@ -359,11 +630,63 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {for d in &plan.datasets {es.ensure_index(&d.index, &build_mapping(&d.specs)).with_context(|| format!("create index {}", d.index))?;+ es.update_mapping(+ &d.index,+ &json!({"properties": {"ax_paths": {"type": "keyword"}}}),+ )+ .with_context(|| format!("upgrade alias-path mapping for {}", d.index))?;}es.ensure_index(catalog::CATALOG_INDEX, &catalog::catalog_mapping())?;- if journal.plan.is_none() {+ es.update_mapping(+ catalog::CATALOG_INDEX,+ &json!({"properties": {"duplicate_of": {"type": "keyword"}}}),+ )+ .context("upgrade autoindex catalog mapping for duplicate aliases")?;+ // A replacement transaction starts before the effective new plan is+ // persisted and before live visibility changes. If the process dies at+ // any later boundary, journal replay removes the older file_done and+ // deterministically schedules a delete-before-replace repair.+ let generation_by_key: HashMap<&str, &str> = keys+ .iter()+ .zip(digests.iter())+ .map(|(key, digest)| (key.as_str(), digest.as_str()))+ .collect();+ // Snapshot whether live records may already exist before this run starts+ // any new publication intents. Fresh first publications can skip the+ // delete/refresh round trip; replacements and crash repairs cannot.+ let mut cleanup_required: std::collections::HashSet<String> = journal+ .done+ .keys()+ .chain(journal.pending_replacements.keys())+ .cloned()+ .collect();+ let mut replacements: Vec<&String> = content_changed+ .iter()+ .filter(|key| {+ let desired = generation_by_key.get(key.as_str()).copied();+ journal.done.contains_key(key.as_str())+ || journal+ .pending_replacements+ .get(key.as_str())+ .is_some_and(|pending| Some(pending.as_str()) != desired)+ })+ .collect();+ replacements.sort();+ for key in replacements {+ journal.file_replace_start(+ key,+ generation_by_key+ .get(key.as_str())+ .copied()+ .unwrap_or("unknown"),+ )?;+ }+ // Persist only an effective plan change. Repeating the full plan on every+ // no-op resume caused journal growth proportional to plan_size × runs.+ if plan_changed {journal.write_plan(&plan)?;}+ replacement_failpoint(1).context("after durable replacement plan")?;// ── Phase B: full-stream extraction + bulk indexing ─────────────────struct DsRt {@@ -398,7 +721,7 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {let mut new_unplanned: Vec<JunkFile> = Vec::new();let mut todo: Vec<usize> = Vec::new();for i in 0..files.len() {- if keys[i].is_empty() || done0.contains(&keys[i]) {+ if keys[i].is_empty() || done0.contains(&keys[i]) && !content_changed.contains(&keys[i]) {continue;}if plan.files.contains_key(&keys[i]) {@@ -416,6 +739,31 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {});}}+ if resumed_with_plan {+ // Legacy journals predate intent-before-publication and may have live+ // partial records without either file_done or file_replace_start.+ // Conservatively clean every resumed planned todo once. Only a plan+ // created in this process can prove that its first publication is+ // genuinely fresh and skip the delete round trip.+ cleanup_required.extend(todo.iter().map(|&i| keys[i].clone()));+ }+ // Every publication, including a fresh one, receives durable intent+ // before its first bulk. A failed fresh publication therefore skips the+ // unnecessary delete now but is recognized as pending and cleaned on the+ // next run.+ let mut intent_keys: Vec<&str> = todo.iter().map(|&i| keys[i].as_str()).collect();+ intent_keys.sort_unstable();+ intent_keys.dedup();+ for key in intent_keys {+ let generation = generation_by_key.get(key).copied().unwrap_or("unknown");+ if journal+ .pending_replacements+ .get(key)+ .is_none_or(|pending| pending != generation)+ {+ journal.file_replace_start(key, generation)?;+ }+ }// ascending by size — workers pop() from the tail, so the BIGGEST files// start first and can't serialize the end of the run.todo.sort_by_key(|&i| files[i].size);@@ -428,6 +776,21 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {}let queue = Mutex::new(todo);+ let mut paths_by_key: HashMap<String, Vec<String>> = files+ .iter()+ .zip(keys.iter())+ .map(|(file, key)| (key.clone(), vec![file.rel.clone()]))+ .collect();+ for duplicate in &plan.duplicate_files {+ paths_by_key+ .entry(duplicate.file_key.clone())+ .or_default()+ .push(duplicate.rel.clone());+ }+ for paths in paths_by_key.values_mut() {+ paths.sort();+ paths.dedup();+ }let journal_mx = Mutex::new(&mut journal);let files_done = AtomicU64::new(0);let records_total = AtomicU64::new(0);@@ -439,8 +802,6 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {std::thread::scope(|scope| {for _ in 0..cfg.workers.min(n_todo.max(1)) {scope.spawn(|| {- let mut buf: Vec<u8> = Vec::with_capacity(bulk_cut + (1 << 20));- let mut buf_docs = 0usize;loop {let i = match queue.lock().unwrap().pop() {Some(i) => i,@@ -448,6 +809,7 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {};let f = &files[i];let key = &keys[i];+ let expected_digest = &digests[i];let fa = plan.files.get(key).unwrap();let asg: HashMap<Option<String>, String> =fa.assignments.iter().cloned().collect();@@ -468,6 +830,29 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {let mut file_records = 0u64;let mut file_junk = 0u64;let mut send_err: Option<String> = None;+ let mut staged = match tempfile::Builder::new()+ .prefix(".autoindex-stage-")+ .tempfile_in(&state_dir)+ {+ Ok(file) => file,+ Err(error) => {+ let mut errors = bulk_errors.lock().unwrap();+ if errors.len() < 5 {+ errors.push(format!(+ "create per-file staging area for {}: {error}",+ f.rel+ ));+ }+ continue;+ }+ };+ if let Err(error) = content::verify(&f.path, f.size, expected_digest) {+ let mut errors = bulk_errors.lock().unwrap();+ if errors.len() < 5 {+ errors.push(format!("{error:#}"));+ }+ continue;+ }{let mut sink = |rec: extract::RawRecord| -> bool {let Some(slug) = asg.get(&rec.group).or_else(|| asg.get(&None)) else {@@ -484,6 +869,18 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {rt.dropped.fetch_add(dropped as u64, Ordering::Relaxed);}fields.insert("ax_path".into(), Value::String(f.rel.clone()));+ fields.insert(+ "ax_paths".into(),+ Value::Array(+ paths_by_key+ .get(key)+ .into_iter()+ .flatten()+ .cloned()+ .map(Value::String)+ .collect(),+ ),+ );fields.insert("ax_file".into(), Value::String(key.clone()));fields.insert("ax_locator".into(), Value::String(rec.locator.clone()));fields.insert("ax_dataset".into(), Value::String(slug.clone()));@@ -491,52 +888,19 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {fields.insert("ax_format".into(), Value::String(format_str(Some(&sn))));let id = ids::doc_id(slug, key, &rec.locator);let action = json!({"index": {"_index": rt.index, "_id": id}});- buf.extend_from_slice(action.to_string().as_bytes());- buf.push(b'\n');- buf.extend_from_slice(+ if let Err(error) = writeln!(+ staged.as_file_mut(),+ "{}\n{}",+ action,serde_json::to_string(&Value::Object(fields)).unwrap_or_else(|_| "{}".into())- .as_bytes(),- );- buf.push(b'\n');- buf_docs += 1;+ ) {+ send_err =+ Some(format!("stage extracted records for {}: {error}", f.rel));+ return false;+ }rt.records.fetch_add(1, Ordering::Relaxed);file_records += 1;- if buf.len() >= bulk_cut || buf_docs >= 5000 {- match es.bulk(std::mem::take(&mut buf)) {- Ok(o) => {- if o.server_errors > 0 {- send_err = Some(format!(- "bulk backend failed for {} item(s): {}. \- Source file was not journaled complete; fix \- the server/embedding configuration and rerun \- autoindex to resume",- o.server_errors,- o.first_server_error- .as_deref()- .unwrap_or("unknown server error")- ));- return false;- }- if o.item_errors > 0 {- junk_records- .fetch_add(o.item_errors, Ordering::Relaxed);- if let Some(e) = o.first_error {- let mut be = bulk_errors.lock().unwrap();- if be.len() < 5 {- be.push(e);- }- }- }- }- Err(e) => {- send_err = Some(format!("{e:#}"));- return false;- }- }- buf_docs = 0;- buf.reserve(bulk_cut);- }true};let res = extract::extract(&f.path, &sn, None, &mut sink);@@ -545,6 +909,7 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {file_junk += stats.junk;}Err(e) => {+ send_err = Some(format!("extract {}: {e}", f.rel));extra_junk.lock().unwrap().push(JunkFile {file_key: key.clone(),rel: f.rel.clone(),@@ -556,31 +921,108 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {}}}- // flush the remainder for THIS file before journaling- if !buf.is_empty() && send_err.is_none() {- match es.bulk(std::mem::take(&mut buf)) {- Ok(o) => {- if o.server_errors > 0 {+ if send_err.is_none() {+ if let Err(error) = content::verify(&f.path, f.size, expected_digest) {+ send_err = Some(format!(+ "{error:#}; no records from this changing file were made visible"+ ));+ }+ }+ // Visibility begins only after extraction and the second+ // full-content verification. Delete-before-replace makes+ // a retry clean up any partial prior attempt.+ if send_err.is_none() && cleanup_required.contains(key) {+ let mut indices: Vec<&str> = fa+ .assignments+ .iter()+ .filter_map(|(_, slug)| ds_rt.get(slug).map(|rt| rt.index.as_str()))+ .collect();+ indices.sort_unstable();+ indices.dedup();+ for index in indices {+ if let Err(error) =+ es.delete_by_query(index, &json!({"term": {"ax_file": key}}))+ {+ send_err = Some(format!(+ "remove prior records for {} before replacement: {error:#}",+ f.rel+ ));+ break;+ }+ }+ if send_err.is_none() {+ if let Err(error) = replacement_failpoint(2) {+ send_err = Some(format!("{error:#}"));+ }+ }+ }+ if send_err.is_none() {+ if let Err(error) = staged.as_file_mut().rewind() {+ send_err =+ Some(format!("rewind staged records for {}: {error}", f.rel));+ }+ }+ if send_err.is_none() {+ let mut reader = BufReader::new(staged.as_file_mut());+ let mut buf = Vec::with_capacity(bulk_cut + (1 << 20));+ let mut docs = 0usize;+ loop {+ let mut action = Vec::new();+ match reader.read_until(b'\n', &mut action) {+ Ok(0) => break,+ Ok(_) => {}+ Err(error) => {+ send_err =+ Some(format!("read staged action for {}: {error}", f.rel));+ break;+ }+ }+ let mut document = Vec::new();+ match reader.read_until(b'\n', &mut document) {+ Ok(0) => {send_err = Some(format!(- "bulk backend failed for {} item(s): {}. Source file \- was not journaled complete; fix the server/embedding \- configuration and rerun autoindex to resume",- o.server_errors,- o.first_server_error- .as_deref()- .unwrap_or("unknown server error")+ "staged record for {} ended without a document",+ f.rel));+ break;}- if o.item_errors > 0 {- junk_records.fetch_add(- o.item_errors.saturating_sub(o.server_errors),- Ordering::Relaxed,- );+ Ok(_) => {}+ Err(error) => {+ send_err = Some(format!(+ "read staged document for {}: {error}",+ f.rel+ ));+ break;}}- Err(e) => send_err = Some(format!("{e:#}")),+ buf.extend_from_slice(&action);+ buf.extend_from_slice(&document);+ docs += 1;+ if (buf.len() >= bulk_cut || docs >= 5000)+ && record_bulk_outcome(+ &es,+ std::mem::take(&mut buf),+ &junk_records,+ &bulk_errors,+ &mut send_err,+ )+ {+ break;+ }+ if buf.is_empty() {+ docs = 0;+ buf.reserve(bulk_cut);+ }+ }+ if !buf.is_empty() && send_err.is_none() {+ record_bulk_outcome(+ &es,+ buf,+ &junk_records,+ &bulk_errors,+ &mut send_err,+ );}- buf_docs = 0;}if let Some(e) = send_err {// endpoint trouble: record, do NOT journal file_done@@ -590,6 +1032,13 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {}continue;}+ if let Err(error) = replacement_failpoint(4) {+ let mut errors = bulk_errors.lock().unwrap();+ if errors.len() < 5 {+ errors.push(format!("{error:#}"));+ }+ continue;+ }records_total.fetch_add(file_records, Ordering::Relaxed);junk_records.fetch_add(file_junk, Ordering::Relaxed);if let Some(rt) = fa.assignments.first().and_then(|(_, slug)| ds_rt.get(slug)) {@@ -601,17 +1050,34 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {rt.junk.fetch_add(file_junk, Ordering::Relaxed);}}- journal_mx- .lock()- .unwrap()- .file_done(&FileDone {+ let (commit_result, journal_path) = {+ let mut journal = journal_mx.lock().unwrap();+ let path = journal.path().display().to_string();+ let result = journal.file_done(&FileDone {file_key: key.clone(),path: f.rel.clone(),records: file_records,junk: file_junk,bytes: f.size,- })- .ok();+ generation: Some(expected_digest.clone()),+ });+ (result, path)+ };+ match commit_result {+ Ok(()) => {}+ Err(error) => {+ let mut errors = bulk_errors.lock().unwrap();+ if errors.len() < 5 {+ errors.push(format!(+ "durably commit completed source {} to {}: {error:#}. \+ Live records may be present, but the file remains pending; \+ repair journal storage and rerun autoindex",+ f.rel, journal_path+ ));+ }+ continue;+ }+ }let dn = files_done.fetch_add(1, Ordering::Relaxed) + 1;if !cfg.quiet && (dn.is_multiple_of(200) || f.size > 5 * (1 << 20)) {eprintln!(" [{dn}/{n_todo}] {} ({} records)", f.rel, file_records);@@ -710,6 +1176,23 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {let time_corrs = correlate::time_alignment(&series);// ── catalog write ────────────────────────────────────────────────────+ // Alias IDs changed as identity evolved. Remove by logical path first so+ // catalogs created by any previous identity scheme cannot survive beside+ // the one current alias document.+ for path in &alias_paths_to_replace {+ es.delete_by_query(+ catalog::CATALOG_INDEX,+ &json!({+ "bool": {+ "filter": [+ {"term": {"status": "duplicate"}},+ {"term": {"path": path}}+ ]+ }+ }),+ )+ .with_context(|| format!("replace catalog alias for {path}"))?;+ }let mut cat_buf: Vec<u8> = Vec::new();let push_doc = |id: &str, doc: &Value, buf: &mut Vec<u8>| {let action = json!({"index": {"_index": catalog::CATALOG_INDEX, "_id": id}});@@ -718,6 +1201,11 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {buf.extend_from_slice(doc.to_string().as_bytes());buf.push(b'\n');};+ for id in &stale_alias_ids {+ let action = json!({"delete": {"_index": catalog::CATALOG_INDEX, "_id": id}});+ cat_buf.extend_from_slice(action.to_string().as_bytes());+ cat_buf.push(b'\n');+ }// dataset docslet mut junk_records_by_run: u64 = junk_records.load(Ordering::Relaxed);@@ -775,6 +1263,11 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {{let j = journal_mx.lock().unwrap();for fd in j.done.values() {+ let current_path = plan+ .files+ .get(&fd.file_key)+ .map(|assignment| assignment.rel.as_str())+ .unwrap_or(&fd.path);let fmt = plan.files.get(&fd.file_key)@@ -788,7 +1281,7 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {.unwrap_or_else(|| "unknown".into());let (id, doc) = catalog::file_doc(&fd.file_key,- &fd.path,+ current_path,&fmt,"indexed",None,@@ -819,6 +1312,17 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {push_doc(&id, &doc, &mut cat_buf);junk_records_by_run += 0; // junk FILES tracked separately from junk records}+ for duplicate in &plan.duplicate_files {+ let (id, doc) = catalog::duplicate_file_doc(+ &duplicate.file_key,+ &duplicate.rel,+ &duplicate.path_id,+ &duplicate.duplicate_of,+ duplicate.bytes,+ &run_id,+ );+ push_doc(&id, &doc, &mut cat_buf);+ }for c in &key_corrs {let mut v = c.to_value();@@ -847,8 +1351,10 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {"url": cfg.url,"prefix": cfg.prefix,"started": chrono::Utc::now().to_rfc3339(),- "files_total": files.len(),+ "files_total": paths_discovered,+ "unique_content_files": files.len(),"files_indexed": journal_mx.lock().unwrap().done.len(),+ "duplicate_files": plan.duplicate_files.len(),"files_junk": all_junk.len(),"records_total": total_records,"junk_records_total": junk_records_by_run,@@ -869,8 +1375,8 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {if cfg.json {println!("{run_doc}");} else if !cfg.quiet {- println!("\ndone in {wall:.1}s — {} datasets, {} records live, {} junk records, {} junk/skipped files",- plan.datasets.len(), total_records, junk_total_records, all_junk.len());+ println!("\ndone in {wall:.1}s — {} datasets, {} records live, {} duplicate aliases, {} junk records, {} junk/skipped files",+ plan.datasets.len(), total_records, plan.duplicate_files.len(), junk_total_records, all_junk.len());let mut rows: Vec<(&String, u64)> = plan.datasets.iter()@@ -967,12 +1473,32 @@ fn run_map(cfg: MapCfg) -> Result<i32> {}all};+ let latest_run_filter = runs+ .first()+ .and_then(|run| run.get("run_id"))+ .and_then(|value| value.as_str())+ .map(|run_id| json!({"term": {"run_id": run_id}}));+ let mut junk_must = vec![json!({"term": {"doc_kind": "file"}})];+ if let Some(filter) = latest_run_filter.clone() {+ junk_must.push(filter);+ }let junk_files = fetch(- json!({"bool": {"must": [{"term": {"doc_kind": "file"}}],- "must_not": [{"term": {"status": "indexed"}}]}}),+ json!({"bool": {"must": junk_must,+ "must_not": [+ {"term": {"status": "indexed"}},+ {"term": {"status": "duplicate"}}+ ]}}),500,None,)?;+ let mut duplicate_must = vec![+ json!({"term": {"doc_kind": "file"}}),+ json!({"term": {"status": "duplicate"}}),+ ];+ if let Some(filter) = latest_run_filter {+ duplicate_must.push(filter);+ }+ let duplicate_files = fetch(json!({"bool": {"must": duplicate_must}}), 500, None)?;if cfg.json {println!("{}",@@ -981,6 +1507,7 @@ fn run_map(cfg: MapCfg) -> Result<i32> {"datasets": datasets,"correlations": correlations,"junk_files": junk_files,+ "duplicate_files": duplicate_files,"gotchas": catalog::GOTCHAS,}))?);@@ -992,6 +1519,7 @@ fn run_map(cfg: MapCfg) -> Result<i32> {&datasets,&correlations,&junk_files,+ &duplicate_files,junk_files.len() as u64));@@ -1063,3 +1591,210 @@ fn run_status(cfg: StatusCfg) -> Result<i32> {}Ok(0)}++#[cfg(test)]+mod duplicate_integration_tests {+ use super::*;+ use std::collections::HashSet;+ use std::fs;+ use std::io::Write;++ fn legacy_assignment(rel: &str) -> FileAssignment {+ FileAssignment {+ rel: rel.to_string(),+ path_id: String::new(),+ family: "txt".to_string(),+ gzip: false,+ content_digest: None,+ assignments: vec![(None, "text".to_string())],+ }+ }++ #[test]+ fn legacy_prefix_collision_has_one_deterministic_owner() {+ let corpus = tempfile::tempdir().unwrap();+ let mut a = vec![b'x'; 65_537];+ let mut b = a.clone();+ a[65_536] = b'a';+ b[65_536] = b'b';+ fs::write(corpus.path().join("a.txt"), a).unwrap();+ fs::write(corpus.path().join("b.txt"), b).unwrap();+ let files = walk::walk(corpus.path(), false).unwrap();+ let inventory = content::resolve(files.clone()).unwrap();+ let legacy = ids::file_key(&files[0].path, files[0].size).unwrap();+ assert_eq!(+ legacy,+ ids::file_key(&files[1].path, files[1].size).unwrap()+ );++ // The exact historical owner sorts second. It must retain the legacy+ // key; the earlier collision sibling must never steal or share it.+ let mut plan = Plan::default();+ plan.files+ .insert(legacy.clone(), legacy_assignment("b.txt"));+ let error = select_resume_plan_keys(&inventory.files, &inventory.keys, &plan).unwrap_err();+ let message = format!("{error:#}");+ assert!(message.contains("collides with legacy resume key"));+ assert!(message.contains("rerun with --fresh"));+ }++ #[test]+ fn one_alias_change_invalidates_only_its_content_key() {+ let alias = |file_key: &str, rel: &str| state::DuplicateFile {+ file_key: file_key.to_string(),+ rel: rel.to_string(),+ path_id: format!("id:{rel}"),+ duplicate_of: format!("{file_key}.txt"),+ bytes: 10,+ };+ let previous = vec![alias("a", "a-copy.txt"), alias("c", "c-copy.txt")];+ let current = vec![+ alias("a", "a-copy.txt"),+ alias("b", "b-copy.txt"),+ alias("c", "c-copy.txt"),+ ];+ assert_eq!(+ alias_keys_to_reindex(&previous, ¤t, None),+ HashSet::from(["b".to_string()])+ );+ assert_eq!(+ alias_keys_to_reindex(¤t, &previous, None),+ HashSet::from(["b".to_string()])+ );+ assert_eq!(+ alias_keys_to_reindex(+ &previous,+ ¤t,+ Some(&["a".to_string(), "b".to_string(), "c".to_string()])+ ),+ HashSet::from(["a".to_string(), "b".to_string(), "c".to_string()])+ );+ }++ #[test]+ fn duplicate_content_keeps_journal_and_live_id_cardinality_equal_on_resume() {+ let corpus = tempfile::tempdir().unwrap();+ let state_dir = tempfile::tempdir().unwrap();+ let body = "quarterly revenue was 42\noperating income was 7\n";+ fs::write(corpus.path().join("report-original.txt"), body).unwrap();+ fs::write(corpus.path().join("report-copy.txt"), body).unwrap();++ let discovered = walk::walk(corpus.path(), false).unwrap();+ let inventory = content::resolve(discovered).unwrap();+ assert_eq!(inventory.files.len(), 1);+ assert_eq!(inventory.duplicates.len(), 1);++ let mut live_ids = HashSet::new();+ let mut records = 0u64;+ let sniffed = sniff::sniff(&inventory.files[0].path).unwrap();+ extract::extract(&inventory.files[0].path, &sniffed, None, &mut |record| {+ live_ids.insert(ids::doc_id("text", &inventory.keys[0], &record.locator));+ records += 1;+ true+ })+ .unwrap();++ let mut journal = state::Journal::open(+ state_dir.path(),+ "corpus",+ "http://engine",+ "test",+ 300,+ false,+ )+ .unwrap();+ journal+ .write_plan(&Plan {+ duplicate_files: inventory.duplicates.clone(),+ ..Plan::default()+ })+ .unwrap();+ journal+ .file_done(&FileDone {+ file_key: inventory.keys[0].clone(),+ path: inventory.files[0].rel.clone(),+ records,+ junk: 0,+ bytes: inventory.files[0].size,+ generation: Some(inventory.digests[0].clone()),+ })+ .unwrap();+ drop(journal);++ let resumed = state::Journal::open(+ state_dir.path(),+ "corpus",+ "http://engine",+ "test",+ 300,+ false,+ )+ .unwrap();+ assert!(resumed.resumed);+ assert_eq!(+ resumed.done.values().map(|f| f.records).sum::<u64>(),+ records+ );+ assert_eq!(records as usize, live_ids.len());+ let done = resumed.done_keys();+ assert!(inventory.keys.iter().all(|key| done.contains(key)));+ let aliases = &resumed.plan.unwrap().duplicate_files;+ assert_eq!(aliases, &inventory.duplicates);+ }++ #[test]+ fn mutation_after_more_than_one_bulk_is_staged_and_retry_replaces_stale_locators() {+ let corpus = tempfile::tempdir().unwrap();+ let path = corpus.path().join("large.csv");+ let mut csv = String::from("id,value\n");+ for id in 0..6_001 {+ csv.push_str(&format!("{id},old-{id}\n"));+ }+ fs::write(&path, csv).unwrap();++ let inventory = content::resolve(walk::walk(corpus.path(), false).unwrap()).unwrap();+ let expected_size = inventory.files[0].size;+ let expected_digest = inventory.digests[0].clone();+ let sniffed = sniff::sniff(&path).unwrap();+ let mut staged = tempfile::NamedTempFile::new().unwrap();+ let mut staged_docs = 0usize;+ extract::extract(&path, &sniffed, None, &mut |record| {+ writeln!(+ staged,+ "{}\n{}",+ record.locator,+ Value::Object(record.fields)+ )+ .unwrap();+ staged_docs += 1;+ if staged_docs == 5_001 {+ // A shorter source replaces the file while extraction is in+ // progress, after the production 5,000-document bulk cut.+ fs::write(&path, "id,value\n0,new-0\n1,new-1\n").unwrap();+ }+ true+ })+ .unwrap();+ assert!(staged_docs > 5_000);++ let mut live: HashSet<String> = (0..6_001).map(|id| format!("row:{id}")).collect();+ assert!(content::verify(&path, expected_size, &expected_digest).is_err());+ // Verification precedes delete/visibility, so a rejected attempt has+ // not mixed any staged records into the old live set.+ assert_eq!(live.len(), 6_001);++ // The retry's delete-before-replace removes every old locator before+ // the now-short source becomes visible.+ live.clear();+ let retry_sniffed = sniff::sniff(&path).unwrap();+ extract::extract(&path, &retry_sniffed, None, &mut |record| {+ live.insert(record.locator);+ true+ })+ .unwrap();+ assert_eq!(live, HashSet::from(["r0".into(), "r1".into()]));+ }+}++#[cfg(test)]+mod failure_resume_http_tests;diff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rsindex a69118fd4..bee9c444f 100644--- a/engine/crates/xerj-autoindex/src/state.rs+++ b/engine/crates/xerj-autoindex/src/state.rs@@ -4,12 +4,24 @@//! dedupe it.use anyhow::{Context, Result};+use fs2::FileExt;use serde::{Deserialize, Serialize};use serde_json::Value;use std::collections::{HashMap, HashSet};use std::io::{BufRead, Write};use std::path::{Path, PathBuf};+#[cfg(test)]+static FILE_DONE_IO_FAILPOINT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);+#[cfg(test)]+pub(crate) static FILE_DONE_IO_FAILPOINT_TEST_LOCK: std::sync::Mutex<()> =+ std::sync::Mutex::new(());++#[cfg(test)]+pub(crate) fn fail_next_file_done_io(boundary: u8) {+ FILE_DONE_IO_FAILPOINT.store(boundary, std::sync::atomic::Ordering::SeqCst);+}+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct PlanDataset {pub slug: String,@@ -72,8 +84,14 @@ mod tests {#[derive(Debug, Clone, Serialize, Deserialize)]pub struct FileAssignment {pub rel: String,+ /// Reversible path identity used for deterministic resume matching.+ #[serde(default, skip_serializing_if = "String::is_empty")]+ pub path_id: String,pub family: String,pub gzip: bool,+ /// Full-content digest used to validate durable identity across resumes.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub content_digest: Option<String>,/// group (None = whole file) → dataset slugpub assignments: Vec<(Option<String>, String)>,}@@ -88,6 +106,19 @@ pub struct JunkFile {pub bytes: u64,}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+pub struct DuplicateFile {+ /// Content identity of the canonical file.+ pub file_key: String,+ /// Root-relative alias path which was not indexed separately.+ pub rel: String,+ #[serde(default)]+ pub path_id: String,+ /// Root-relative canonical path whose records represent this content.+ pub duplicate_of: String,+ pub bytes: u64,+}+#[derive(Debug, Clone, Default, Serialize, Deserialize)]pub struct Plan {pub datasets: Vec<PlanDataset>,@@ -96,6 +127,12 @@ pub struct Plan {/// junk/skipped files recorded at scan time (never fatal)#[serde(default)]pub junk_files: Vec<JunkFile>,+ /// Byte-identical paths represented by a canonical content file.+ #[serde(default)]+ pub duplicate_files: Vec<DuplicateFile>,+ /// Canonical records have been rewritten with the `ax_paths` alias list.+ #[serde(default)]+ pub alias_paths_indexed: bool,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -105,14 +142,23 @@ pub struct FileDone {pub records: u64,pub junk: u64,pub bytes: u64,+ /// Content generation committed by this record. Legacy completions have+ /// no generation and cannot commit a newer pending replacement.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub generation: Option<String>,}pub struct Journal {path: PathBuf,file: std::fs::File,+ _state_lock: std::fs::File,pub run_id: String,pub resumed: bool,pub done: HashMap<String, FileDone>,+ /// Durable replacement transactions which have not reached file_done.+ /// Replay removes these keys from `done`, so a crash after destructive+ /// publication can never make resume skip a zero/partial generation.+ pub pending_replacements: HashMap<String, String>,pub plan: Option<Plan>,}@@ -135,57 +181,141 @@ impl Journal {) -> Result<Journal> {std::fs::create_dir_all(state_dir).with_context(|| format!("create state dir {}", state_dir.display()))?;+ let lock_path = state_dir.join(".autoindex.lock");+ let state_lock = std::fs::OpenOptions::new()+ .create(true)+ .truncate(false)+ .read(true)+ .write(true)+ .open(&lock_path)?;+ state_lock.try_lock_exclusive().with_context(|| {+ format!(+ "autoindex state {} is already in use by another process; wait for it to \+ finish or choose a different --state-dir",+ state_dir.display()+ )+ })?;+ // Hard kills cannot run NamedTempFile::drop. Stages are owned by this+ // journal directory and use a reserved prefix, so removing only+ // regular files with that prefix is deterministic and scope-safe.+ for entry in std::fs::read_dir(state_dir)? {+ let entry = entry?;+ if entry+ .file_name()+ .to_string_lossy()+ .starts_with(".autoindex-stage-")+ && entry.file_type()?.is_file()+ {+ std::fs::remove_file(entry.path()).with_context(|| {+ format!("remove orphan autoindex stage {}", entry.path().display())+ })?;+ }+ }let jpath = state_dir.join("journal.ndjson");if fresh && jpath.exists() {std::fs::remove_file(&jpath).ok();}let mut done = HashMap::new();+ let mut pending_replacements: HashMap<String, String> = HashMap::new();let mut plan = None;let mut run_id = None;let mut resumed = false;if jpath.exists() {let f = std::fs::File::open(&jpath)?;- for line in std::io::BufReader::new(f).lines() {- let Ok(line) = line else { break };- let Ok(v) = serde_json::from_str::<Value>(&line) else {- break; // torn tail line — stop replay here- };- match v.get("kind").and_then(|k| k.as_str()) {- Some("run") => {- let (jr, ju, jp) = (- v.get("root").and_then(|x| x.as_str()).unwrap_or(""),- v.get("url").and_then(|x| x.as_str()).unwrap_or(""),- v.get("prefix").and_then(|x| x.as_str()).unwrap_or(""),- );- if jr != root || ju != url || jp != prefix {- anyhow::bail!(+ let file_len = f.metadata()?.len();+ let mut reader = std::io::BufReader::new(f);+ let mut valid_end = 0u64;+ loop {+ let record_start = valid_end;+ let mut bytes = Vec::new();+ let read = reader.read_until(b'\n', &mut bytes)?;+ if read == 0 {+ break;+ }+ let newline_terminated = bytes.last() == Some(&b'\n');+ match serde_json::from_slice::<Value>(+ bytes.strip_suffix(b"\n").unwrap_or(bytes.as_slice()),+ ) {+ Ok(v) if newline_terminated => {+ valid_end += read as u64;+ match v.get("kind").and_then(|k| k.as_str()) {+ Some("run") => {+ let (jr, ju, jp) = (+ v.get("root").and_then(|x| x.as_str()).unwrap_or(""),+ v.get("url").and_then(|x| x.as_str()).unwrap_or(""),+ v.get("prefix").and_then(|x| x.as_str()).unwrap_or(""),+ );+ if jr != root || ju != url || jp != prefix {+ anyhow::bail!("journal at {} was created for root={jr} url={ju} prefix={jp}; \current run has root={root} url={url} prefix={prefix}. \Use --fresh to discard it or --state-dir for a separate state.",jpath.display());- }- if run_id.is_none() {- run_id = v- .get("run_id")- .and_then(|x| x.as_str())- .map(|s| s.to_string());- }- resumed = true;- }- Some("plan") => {- if let Some(p) = v.get("plan") {- if let Ok(p) = serde_json::from_value::<Plan>(p.clone()) {- plan = Some(p);+ }+ if run_id.is_none() {+ run_id = v+ .get("run_id")+ .and_then(|x| x.as_str())+ .map(|s| s.to_string());+ }+ resumed = true;+ }+ Some("plan") => {+ if let Some(p) = v.get("plan") {+ if let Ok(p) = serde_json::from_value::<Plan>(p.clone()) {+ plan = Some(p);+ }+ }+ }+ Some("file_done") => {+ if let Ok(fd) = serde_json::from_value::<FileDone>(v.clone()) {+ let commits_pending = pending_replacements+ .get(&fd.file_key)+ .is_none_or(|pending| {+ fd.generation.as_deref() == Some(pending.as_str())+ });+ if commits_pending {+ pending_replacements.remove(&fd.file_key);+ done.insert(fd.file_key.clone(), fd);+ }+ }}+ Some("file_replace_start") => {+ if let (Some(file_key), Some(generation)) = (+ v.get("file_key").and_then(Value::as_str),+ v.get("generation").and_then(Value::as_str),+ ) {+ done.remove(file_key);+ pending_replacements+ .insert(file_key.to_string(), generation.to_string());+ }+ }+ _ => {}}}- Some("file_done") => {- if let Ok(fd) = serde_json::from_value::<FileDone>(v.clone()) {- done.insert(fd.file_key.clone(), fd);- }+ Ok(_) | Err(_)+ if !newline_terminated && record_start + read as u64 == file_len =>+ {+ let repair = std::fs::OpenOptions::new().write(true).open(&jpath)?;+ repair.set_len(record_start)?;+ repair.sync_data().with_context(|| {+ format!(+ "sync repaired torn journal tail at byte {record_start} in {}",+ jpath.display()+ )+ })?;+ break;+ }+ Ok(_) => unreachable!("complete JSON without newline handled as torn tail"),+ Err(error) => {+ anyhow::bail!(+ "journal corruption at byte {record_start} in {}: malformed \+ newline-terminated record ({error}). Refusing to discard records \+ after corruption; restore the journal or use --fresh",+ jpath.display()+ );}- _ => {}}}}@@ -204,56 +334,169 @@ impl Journal {let mut j = Journal {path: jpath,file,+ _state_lock: state_lock,run_id: run_id.clone(),resumed: resumed && !is_new,done,+ pending_replacements,plan,};if is_new {- j.append(&serde_json::json!({- "v": 1, "kind": "run", "root": root, "url": url, "prefix": prefix,- "bulk_timeout_secs": bulk_timeout_secs,- "run_id": run_id, "started": chrono::Utc::now().to_rfc3339(),- }))?;+ j.append_transaction(+ &serde_json::json!({+ "v": 1, "kind": "run", "root": root, "url": url, "prefix": prefix,+ "bulk_timeout_secs": bulk_timeout_secs,+ "run_id": run_id, "started": chrono::Utc::now().to_rfc3339(),+ }),+ "run",+ )?;} else {- j.append(&serde_json::json!({- "kind": "resume", "bulk_timeout_secs": bulk_timeout_secs,- "at": chrono::Utc::now().to_rfc3339(),- }))?;+ j.append_transaction(+ &serde_json::json!({+ "kind": "resume", "bulk_timeout_secs": bulk_timeout_secs,+ "at": chrono::Utc::now().to_rfc3339(),+ }),+ "resume",+ )?;}Ok(j)}- fn append(&mut self, v: &Value) -> Result<()> {+ fn append_transaction(&mut self, v: &Value, what: &str) -> Result<()> {let mut line = serde_json::to_string(v)?;line.push('\n');- self.file.write_all(line.as_bytes())?;+ let start = self.file.metadata()?.len();+ #[cfg(test)]+ if what == "file_done"+ && FILE_DONE_IO_FAILPOINT+ .compare_exchange(+ 1,+ 0,+ std::sync::atomic::Ordering::SeqCst,+ std::sync::atomic::Ordering::SeqCst,+ )+ .is_ok()+ {+ anyhow::bail!("injected file_done append failure before any bytes");+ }+ #[cfg(test)]+ let partial_write = what == "file_done"+ && FILE_DONE_IO_FAILPOINT+ .compare_exchange(+ 3,+ 0,+ std::sync::atomic::Ordering::SeqCst,+ std::sync::atomic::Ordering::SeqCst,+ )+ .is_ok();+ #[cfg(not(test))]+ let partial_write = false;+ let write_result = if partial_write {+ let written = line.len().min(23);+ self.file+ .write_all(&line.as_bytes()[..written])+ .and_then(|_| {+ Err(std::io::Error::other(format!(+ "injected partial file_done write after {written} bytes"+ )))+ })+ } else {+ self.file.write_all(line.as_bytes())+ };+ if let Err(error) = write_result {+ return self.rollback_transaction(start, what, "append", error);+ }+ #[cfg(test)]+ let injected_sync_failure = what == "file_done"+ && FILE_DONE_IO_FAILPOINT+ .compare_exchange(+ 2,+ 0,+ std::sync::atomic::Ordering::SeqCst,+ std::sync::atomic::Ordering::SeqCst,+ )+ .is_ok();+ #[cfg(not(test))]+ let injected_sync_failure = false;+ let sync_result = if injected_sync_failure {+ Err(std::io::Error::other("injected file_done fsync failure"))+ } else {+ self.file.sync_data()+ };+ if let Err(error) = sync_result {+ return self.rollback_transaction(start, what, "fsync", error);+ }Ok(())}+ fn rollback_transaction(+ &mut self,+ start: u64,+ what: &str,+ operation: &str,+ error: std::io::Error,+ ) -> Result<()> {+ let rollback = self.file.set_len(start).and_then(|_| self.file.sync_data());+ match rollback {+ Ok(()) => Err(error).context(format!(+ "{operation} durable {what}; partial transaction was rolled back to byte {start}"+ )),+ Err(rollback_error) => anyhow::bail!(+ "{operation} durable {what} failed: {error}; rollback to byte {start} also \+ failed: {rollback_error}. Treat journal state as ambiguous and rerun after \+ repairing storage"+ ),+ }+ }+pub fn write_plan(&mut self, plan: &Plan) -> Result<()> {- self.append(&serde_json::json!({"kind": "plan", "plan": plan}))?;- self.file.sync_data().ok();+ self.append_transaction(&serde_json::json!({"kind": "plan", "plan": plan}), "plan")?;self.plan = Some(plan.clone());Ok(())}pub fn file_done(&mut self, fd: &FileDone) -> Result<()> {+ if let Some(pending) = self.pending_replacements.get(&fd.file_key) {+ anyhow::ensure!(+ fd.generation.as_deref() == Some(pending.as_str()),+ "refusing stale completion for {} generation {:?}; pending generation is {}",+ fd.file_key,+ fd.generation,+ pending+ );+ }let mut v = serde_json::to_value(fd)?;v["kind"] = Value::String("file_done".into());- self.append(&v)?;+ self.append_transaction(&v, "file_done")?;+ self.pending_replacements.remove(&fd.file_key);self.done.insert(fd.file_key.clone(), fd.clone());- // fsync batched: every 32 completions- if self.done.len().is_multiple_of(32) {- self.file.sync_data().ok();- }+ Ok(())+ }++ /// Durably invalidate an older completion before persisting a new plan or+ /// changing live visibility. Replaying this record schedules repair until+ /// a later durable file_done commits the generation.+ pub fn file_replace_start(&mut self, file_key: &str, generation: &str) -> Result<()> {+ self.append_transaction(+ &serde_json::json!({+ "kind": "file_replace_start",+ "file_key": file_key,+ "generation": generation,+ }),+ "file_replace_start",+ )?;+ self.done.remove(file_key);+ self.pending_replacements+ .insert(file_key.to_string(), generation.to_string());Ok(())}pub fn finish(&mut self, summary: &Value) -> Result<()> {- self.append(&serde_json::json!({"kind": "finish", "summary": summary,- "at": chrono::Utc::now().to_rfc3339()}))?;- self.file.sync_data().ok();+ self.append_transaction(+ &serde_json::json!({"kind": "finish", "summary": summary,+ "at": chrono::Utc::now().to_rfc3339()}),+ "finish",+ )?;Ok(())}@@ -265,3 +508,316 @@ impl Journal {&self.path}}++#[cfg(test)]+mod compatibility_tests {+ use super::*;+ use std::fs;+ use std::io::Write;++ #[test]+ fn pre_dedupe_plan_deserializes_with_empty_aliases_and_no_digest() {+ let plan: Plan = serde_json::from_value(serde_json::json!({+ "datasets": [],+ "files": {+ "legacy-key": {+ "rel": "report.pdf",+ "family": "pdf",+ "gzip": false,+ "assignments": []+ }+ },+ "junk_files": []+ }))+ .unwrap();+ assert!(plan.duplicate_files.is_empty());+ assert!(plan.files["legacy-key"].content_digest.is_none());+ }++ #[test]+ fn replacement_start_durably_invalidates_done_until_a_durable_commit() {+ let dir = tempfile::tempdir().unwrap();+ let mut journal =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ let old = FileDone {+ file_key: "file-key".into(),+ path: "large.csv".into(),+ records: 6_001,+ junk: 0,+ bytes: 100,+ generation: Some("old-generation".into()),+ };+ journal.file_done(&old).unwrap();+ journal+ .file_replace_start("file-key", "new-generation")+ .unwrap();+ journal.write_plan(&Plan::default()).unwrap();+ drop(journal);++ let resumed = Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ assert!(!resumed.done.contains_key("file-key"));+ assert_eq!(+ resumed.pending_replacements.get("file-key"),+ Some(&"new-generation".to_string())+ );+ drop(resumed);++ let mut committing =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ committing+ .file_done(&FileDone {+ records: 2,+ bytes: 20,+ generation: Some("new-generation".into()),+ ..old+ })+ .unwrap();+ drop(committing);+ let committed =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ assert_eq!(committed.done["file-key"].records, 2);+ assert!(!committed.pending_replacements.contains_key("file-key"));++ // The commit really reached the append-only file, rather than only+ // changing the in-memory replay state.+ let text = fs::read_to_string(dir.path().join("journal.ndjson")).unwrap();+ assert!(text.contains("\"kind\":\"file_replace_start\""));+ assert_eq!(text.matches("\"kind\":\"file_done\"").count(), 2);+ }++ #[test]+ fn torn_file_done_tail_is_truncated_before_repair_commit_is_appended() {+ let dir = tempfile::tempdir().unwrap();+ let mut journal =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ journal+ .file_replace_start("file-key", "generation-2")+ .unwrap();+ drop(journal);+ let path = dir.path().join("journal.ndjson");+ let valid_len = fs::metadata(&path).unwrap().len();+ fs::OpenOptions::new()+ .append(true)+ .open(&path)+ .unwrap()+ .write_all(br#"{"kind":"file_done","file_key":"file-key","generation":"gener"#)+ .unwrap();++ let mut repaired =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ assert!(repaired.done.is_empty());+ assert_eq!(repaired.pending_replacements["file-key"], "generation-2");+ assert!(fs::metadata(&path).unwrap().len() > valid_len);+ repaired+ .file_done(&FileDone {+ file_key: "file-key".into(),+ path: "records.csv".into(),+ records: 2,+ junk: 0,+ bytes: 20,+ generation: Some("generation-2".into()),+ })+ .unwrap();+ drop(repaired);++ let reopened =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ assert_eq!(reopened.done["file-key"].records, 2);+ assert!(reopened.pending_replacements.is_empty());+ }++ #[test]+ fn torn_replacement_start_and_plan_tails_are_repaired_before_append() {+ for torn in [+ br#"{"kind":"file_replace_start","file_key":"file-key","generation":"new""#.as_slice(),+ br#"{"kind":"plan","plan":{"datasets":[],"files":{"#.as_slice(),+ ] {+ let dir = tempfile::tempdir().unwrap();+ let journal =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ drop(journal);+ let path = dir.path().join("journal.ndjson");+ fs::OpenOptions::new()+ .append(true)+ .open(&path)+ .unwrap()+ .write_all(torn)+ .unwrap();++ let repaired =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ assert!(repaired.pending_replacements.is_empty());+ drop(repaired);+ // The resume appended after truncation must itself remain visible+ // on every later replay.+ let reopened =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ assert!(reopened.resumed);+ }+ }++ #[test]+ fn malformed_newline_terminated_middle_record_fails_closed() {+ let dir = tempfile::tempdir().unwrap();+ let mut journal =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ journal.write_plan(&Plan::default()).unwrap();+ drop(journal);+ let path = dir.path().join("journal.ndjson");+ let mut file = fs::OpenOptions::new().append(true).open(&path).unwrap();+ file.write_all(b"{malformed middle}\n").unwrap();+ file.write_all(b"{\"kind\":\"resume\"}\n").unwrap();+ drop(file);++ let error = Journal::open(dir.path(), "root", "http://engine", "ax", 300, false)+ .err()+ .expect("corruption must fail closed");+ let message = format!("{error:#}");+ assert!(message.contains("journal corruption"));+ assert!(message.contains("use --fresh"));+ }++ #[test]+ fn stale_generation_completion_cannot_clear_newer_pending_replacement() {+ let dir = tempfile::tempdir().unwrap();+ let mut journal =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ journal.file_replace_start("file-key", "new").unwrap();+ let error = journal+ .file_done(&FileDone {+ file_key: "file-key".into(),+ path: "records.csv".into(),+ records: 10,+ junk: 0,+ bytes: 10,+ generation: Some("old".into()),+ })+ .unwrap_err();+ assert!(error.to_string().contains("refusing stale completion"));+ assert_eq!(journal.pending_replacements["file-key"], "new");+ assert!(!journal.done.contains_key("file-key"));+ }++ #[test]+ fn append_and_fsync_commit_failures_leave_pending_and_replayable() {+ let _guard = FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();+ for boundary in [1, 2, 3] {+ let dir = tempfile::tempdir().unwrap();+ let mut journal =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ journal.file_replace_start("file-key", "new").unwrap();+ fail_next_file_done_io(boundary);+ let error = journal+ .file_done(&FileDone {+ file_key: "file-key".into(),+ path: "records.csv".into(),+ records: 2,+ junk: 0,+ bytes: 20,+ generation: Some("new".into()),+ })+ .unwrap_err();+ assert!(format!("{error:#}").contains(if boundary == 1 {+ "append failure"+ } else if boundary == 3 {+ "partial file_done write"+ } else {+ "fsync failure"+ }));+ assert!(journal.done.is_empty());+ assert_eq!(journal.pending_replacements["file-key"], "new");+ drop(journal);+ let replay =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ assert!(replay.done.is_empty());+ assert_eq!(replay.pending_replacements["file-key"], "new");+ }+ }++ #[test]+ fn partial_commit_is_rolled_back_before_another_worker_appends() {+ let _guard = FILE_DONE_IO_FAILPOINT_TEST_LOCK.lock().unwrap();+ let dir = tempfile::tempdir().unwrap();+ let mut journal =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ journal+ .file_replace_start("file-c", "generation-c")+ .unwrap();+ fail_next_file_done_io(3);+ let error = journal+ .file_done(&FileDone {+ file_key: "file-c".into(),+ path: "c.csv".into(),+ records: 2,+ junk: 0,+ bytes: 20,+ generation: Some("generation-c".into()),+ })+ .unwrap_err();+ assert!(format!("{error:#}").contains("after 23 bytes"));++ // The mutex would now pass to another worker. Its complete record must+ // begin exactly at the rolled-back boundary, not after a torn prefix.+ journal+ .file_done(&FileDone {+ file_key: "file-d".into(),+ path: "d.csv".into(),+ records: 3,+ junk: 0,+ bytes: 30,+ generation: Some("generation-d".into()),+ })+ .unwrap();+ drop(journal);++ let mut replay =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ assert_eq!(replay.pending_replacements["file-c"], "generation-c");+ assert!(!replay.done.contains_key("file-c"));+ assert_eq!(replay.done["file-d"].records, 3);+ replay+ .file_done(&FileDone {+ file_key: "file-c".into(),+ path: "c.csv".into(),+ records: 2,+ junk: 0,+ bytes: 20,+ generation: Some("generation-c".into()),+ })+ .unwrap();+ drop(replay);+ let committed =+ Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ assert_eq!(committed.done.len(), 2);+ assert!(committed.pending_replacements.is_empty());+ }++ #[test]+ fn state_lock_precedes_safe_direct_child_orphan_cleanup() {+ let dir = tempfile::tempdir().unwrap();+ fs::write(dir.path().join(".autoindex-stage-orphan"), b"staged").unwrap();+ fs::create_dir(dir.path().join(".autoindex-stage-directory")).unwrap();+ #[cfg(unix)]+ std::os::unix::fs::symlink(+ dir.path().join(".autoindex-stage-orphan-target"),+ dir.path().join(".autoindex-stage-symlink"),+ )+ .unwrap();++ let journal = Journal::open(dir.path(), "root", "http://engine", "ax", 300, false).unwrap();+ assert!(!dir.path().join(".autoindex-stage-orphan").exists());+ assert!(dir.path().join(".autoindex-stage-directory").is_dir());+ #[cfg(unix)]+ assert!(dir.path().join(".autoindex-stage-symlink").is_symlink());++ // A second opener is rejected before it can inspect or clean stages+ // belonging to the live first process.+ fs::write(dir.path().join(".autoindex-stage-live"), b"live stage").unwrap();+ let error = Journal::open(dir.path(), "root", "http://engine", "ax", 300, false)+ .err()+ .expect("second process must not share a state directory");+ assert!(error.to_string().contains("already in use"));+ assert!(dir.path().join(".autoindex-stage-live").exists());+ drop(journal);+ }+}diff --git a/engine/crates/xerj-autoindex/src/walk.rs b/engine/crates/xerj-autoindex/src/walk.rsindex f414204db..02c2a7bad 100644--- a/engine/crates/xerj-autoindex/src/walk.rs+++ b/engine/crates/xerj-autoindex/src/walk.rs@@ -10,6 +10,10 @@ pub struct FileEntry {pub path: PathBuf,/// Root-relative path with forward slashes — the stable `ax_path` value.pub rel: String,+ /// Reversible platform-native identity; unlike `rel`, never lossy.+ pub rel_id: String,+ /// True when the discovered path itself is a symlink (target metadata follows).+ pub is_symlink: bool,pub size: u64,}@@ -42,9 +46,15 @@ pub fn walk(root: &Path, follow_symlinks: bool) -> Result<Vec<FileEntry>> {.unwrap_or(&p).to_string_lossy().replace('\\', "/");+ let rel_id = stable_path_id(p.strip_prefix(&root_canon).unwrap_or(&p));out.push(FileEntry {path: p,rel,+ rel_id,+ is_symlink: entry+ .path()+ .symlink_metadata()+ .is_ok_and(|m| m.file_type().is_symlink()),size: md.len(),});}@@ -52,3 +62,30 @@ pub fn walk(root: &Path, follow_symlinks: bool) -> Result<Vec<FileEntry>> {out.sort_by(|a, b| a.rel.cmp(&b.rel));Ok(out)}++#[cfg(unix)]+fn stable_path_id(path: &Path) -> String {+ use std::os::unix::ffi::OsStrExt;+ let mut out = String::from("unix:");+ for byte in path.as_os_str().as_bytes() {+ use std::fmt::Write;+ write!(out, "{byte:02x}").expect("write string");+ }+ out+}++#[cfg(windows)]+fn stable_path_id(path: &Path) -> String {+ use std::os::windows::ffi::OsStrExt;+ let mut out = String::from("windows:");+ for unit in path.as_os_str().encode_wide() {+ use std::fmt::Write;+ write!(out, "{unit:04x}").expect("write string");+ }+ out+}++#[cfg(not(any(unix, windows)))]+fn stable_path_id(path: &Path) -> String {+ format!("other:{}", path.to_string_lossy())+}