Skip to content

armgit / xerj

Public Imported from GitHub
0

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

207 KB
Raw Blame
//! 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::TcpStream;
use std::sync::{Arc, Mutex};
use std::thread;

static FAILPOINT_TEST_LOCK: Mutex<()> = Mutex::new(());

/// #953: the replacement failpoint fires only in the run it was armed for.
///
/// It was a bare process-wide boundary number, so any concurrent test that
/// drove the legacy path took the injected crash: that test failed with an
/// error it had nothing to do with and the arming test ran clean. Keyed on the
/// state directory, another run at the same boundary passes straight through,
/// and so does the armed run at a different boundary. Holds
/// `FAILPOINT_TEST_LOCK` because arming REPLACES whatever is armed.
#[test]
fn replacement_failpoint_cannot_be_taken_by_another_run() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let mine = tempfile::tempdir().unwrap();
    let theirs = tempfile::tempdir().unwrap();
    arm_replacement_failpoint(4, mine.path());

    replacement_failpoint(4, theirs.path()).expect("another run at the armed boundary");
    replacement_failpoint(2, mine.path()).expect("the armed run at another boundary");

    let error = replacement_failpoint(4, mine.path()).unwrap_err();
    assert!(
        format!("{error:#}").contains("injected replacement crash boundary 4"),
        "{error:#}"
    );
    replacement_failpoint(4, mine.path()).expect("the failpoint is one-shot");
}

/// Owns the process-global PDF worker environment for the duration of one
/// test. `XERJ_PDF_WORKER_BIN` is read inside `spawn_worker`, so a test that
/// sets it silently rewrites what every concurrently running test in this
/// binary observes — including the unit tests in `extract::pdf`. Acquire this
/// **before** the first `set_var`; the shared lock is the only thing that
/// makes those two suites safe to run at the default thread count.
#[cfg(unix)]
struct PdfWorkerEnvGuard {
    /// Held, never read: dropping it after the environment is cleared is the
    /// whole point.
    _lock: std::sync::MutexGuard<'static, ()>,
}

#[cfg(unix)]
impl PdfWorkerEnvGuard {
    fn acquire() -> Self {
        Self {
            _lock: crate::extract::pdf::WORKER_BIN_ENV_LOCK
                .lock()
                .unwrap_or_else(|poison| poison.into_inner()),
        }
    }
}

#[cfg(unix)]
impl Drop for PdfWorkerEnvGuard {
    fn drop(&mut self) {
        std::env::remove_var("XERJ_PDF_WORKER_BIN");
        std::env::remove_var("XERJ_TEST_PDF_COUNT");
    }
}

fn inject_pdf_spool_capacity(state_dir: &Path) {
    for (name, value) in [
        ("available-bytes", 16_u64 << 30),
        ("fd-limit", 4096),
        ("fd-open", 16),
    ] {
        fs::write(
            state_dir.join(format!(".autoindex-test-pdf-spool-{name}")),
            value.to_string(),
        )
        .unwrap();
    }
}

#[derive(Default)]
struct MockState {
    docs: HashMap<String, Value>,
    /// Catalog documents, kept apart from `docs` on purpose: `docs.len()` is
    /// what `_count`/`_search` answer with, and the run verifies live data
    /// counts against the journal (#195). Catalog rows are not data rows.
    catalog_docs: HashMap<String, Value>,
    /// Every (method, path) the run issued. The refusal tests assert on the
    /// ABSENCE of remote mutations, which no document count can express.
    requests: Vec<(String, String)>,
    data_bulk_number: usize,
    fail_data_bulk: usize,
    failed_once: bool,
    delete_calls: usize,
    response_delay_ms: u64,
    catalog_preexists: bool,
    catalog_mapping_upgraded: bool,
    /// #755: whether a catalog `_mapping` PUT declared the keyword corpus-scope
    /// field. On this legacy path it arrives in its own PUT, because `prefix`
    /// cannot be re-declared on a catalog that already holds it as `text`.
    catalog_corpus_scope_mapped: bool,
    catalog_bulk_before_upgrade: bool,
    /// Set if the additive mapping upgrade ever asks for `started`. This is
    /// the executable half of `catalog::catalog_mapping`'s tripwire: against a
    /// legacy (v1.0.0-rc.4) catalog that request is refused 400 and aborts the
    /// run, so the product must never send it. Asserted false rather than left
    /// to the 400 branch below, which a correct product never reaches.
    started_mapping_requested: bool,
    /// Catalog bulk actions the fixture does not model. Recorded rather than
    /// panicked on: this runs inside the server thread while the state guard
    /// is held, so a panic here would poison the `Mutex` and turn
    /// `MockEndpoint::drop`'s `join().unwrap()` into a second, misleading
    /// panic. Tests assert on it from the test thread instead.
    unexpected_catalog_actions: Vec<String>,
    stop: bool,
    embedding_identity_sha256: String,
    /// Reject every data-bulk item with a 403 explicit write-block error
    /// (the status ES gives `index.blocks.write` / `read_only`; only the
    /// flood-stage block is 429) without applying anything — the #195 shape.
    block_writes: bool,
    /// Accept every data bulk (`errors: false`) but persist nothing — the
    /// shape of any rejection path the client-side classifier misses.
    swallow_data_bulks: bool,
    /// `_count` answers 200 with no `count`, and a size:0 `_search` answers
    /// `timed_out`. Models a node that accepted the writes and then could
    /// not finish a count (merge, deadline). Must not look like zero docs.
    fail_counts: bool,
    /// Opt-in (#2407): `_count` on these indices answers 0. The fixture keeps
    /// one document map for every index, so this is how a test models one
    /// dataset index holding nothing while its siblings are live.
    empty_count_indices: Vec<String>,
    /// Independent failed counts, including their size:0 search fallback.
    unknown_count_indices: Vec<String>,
    /// Answer the catalog's duplicate-alias sweep — and ONLY that request —
    /// with a 500 whose body names the condition. Scoped to the one call so
    /// the fixture proves the sweep is what wedged the run (#345), not that a
    /// server which 500s everything fails.
    ///
    /// #905: the sweep is a candidate `_search` followed by a by-`_id` delete
    /// now, not one `_delete_by_query`, so the fault is injected on the search.
    /// It is still the first and only server call the sweep makes, which is
    /// what the fixture needs.
    fail_alias_sweep: bool,
    /// One entry per alias-sweep request, holding the paths it named. The
    /// sweep used to be one round trip per duplicate path, so the batching is
    /// only observable here.
    alias_sweep_batches: Vec<Vec<String>>,
    /// Refuse the FIRST document of every data bulk with a per-item 400 and
    /// apply the rest. This is the one bulk shape that produces an
    /// `item_error` without a `server_error`: status is neither 429 nor 5xx
    /// and the type is not a block, so the run continues and must still
    /// report the rejection.
    reject_first_data_item: bool,
    /// As `reject_first_data_item`, with the server's per-document size
    /// refusal, which a retry cannot clear (#2807).
    reject_first_data_item_as_too_large: bool,
    /// Opt-in (#929): refuse the create-index PUT — which on this path carries
    /// the dataset's whole mapping — of every index whose name contains one of
    /// these, with the 400 a real engine returns for a field it cannot map.
    refused_dataset_indices: Vec<String>,
    /// Opt-in (#944): answer this many data bulks — the next ones — with a
    /// per-item 429 on EVERY item and apply nothing, the way the engine's
    /// memory circuit breaker does for the moment it is engaged. Then behave
    /// normally, so the client's re-send of exactly those items can land.
    throttle_data_bulks: usize,
    /// Opt-in (#955): the engine's `limits.max_actions_per_bulk`. A `_bulk` of
    /// more than twice this many lines — data or catalog — is refused whole
    /// with the engine's literal answer: HTTP 200, ONE item of status 413,
    /// nothing applied.
    max_actions_per_bulk: Option<usize>,
    /// Line count of every bulk `max_actions_per_bulk` refused, in order.
    oversize_bulks_refused: Vec<usize>,
    /// Opt-in (#1977): answer the catalog bulk `errors: false` and persist
    /// nothing. The data path's zero-live gate already refuses this shape;
    /// the catalog write used to exit 0 with an empty `autoindex-catalog`.
    swallow_catalog_bulks: bool,
    /// Opt-in (#1977): refuse every catalog action with a per-item 400 and
    /// persist nothing. Status 400 is not a `server_error`, so it used to be
    /// a warning on an exit-0 run.
    reject_catalog_items: bool,
}

struct MockEndpoint {
    url: String,
    state: Arc<Mutex<MockState>>,
    join: Option<thread::JoinHandle<()>>,
}

impl MockEndpoint {
    fn start(fail_data_bulk: usize) -> Self {
        Self::start_with_delay(fail_data_bulk, 0)
    }

    fn start_with_delay(fail_data_bulk: usize, response_delay_ms: u64) -> Self {
        let listener = crate::test_loopback::bind();
        listener.set_nonblocking(true).unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let state = Arc::new(Mutex::new(MockState {
            fail_data_bulk,
            response_delay_ms,
            embedding_identity_sha256: "a".repeat(64),
            ..MockState::default()
        }));
        let server_state = Arc::clone(&state);
        let join = thread::spawn(move || loop {
            match listener.accept() {
                Ok((stream, _)) => {
                    // BSD/macOS: accepted sockets inherit the listener's
                    // O_NONBLOCK; the handler does blocking reads.
                    stream.set_nonblocking(false).unwrap();
                    handle(stream, &server_state)
                }
                Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                    if server_state
                        .lock()
                        .unwrap_or_else(|poisoned| poisoned.into_inner())
                        .stop
                    {
                        break;
                    }
                    thread::yield_now();
                }
                Err(error) => panic!("mock endpoint accept failed: {error}"),
            }
        });
        Self {
            url,
            state,
            join: Some(join),
        }
    }

    fn start_with_existing_catalog() -> Self {
        let endpoint = Self::start(usize::MAX);
        endpoint.state.lock().unwrap().catalog_preexists = true;
        endpoint
    }
}

impl Drop for MockEndpoint {
    fn drop(&mut self) {
        self.state
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .stop = true;
        // Wake the nonblocking listener even on heavily loaded test hosts.
        let _ = TcpStream::connect(self.url.trim_start_matches("http://"));
        let _ = self.join.take().unwrap().join();
    }
}

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("");
    state
        .lock()
        .unwrap()
        .requests
        .push((method.to_owned(), path.to_owned()));
    let response_delay_ms = state.lock().unwrap().response_delay_ms;
    if response_delay_ms > 0 {
        thread::sleep(std::time::Duration::from_millis(response_delay_ms));
    }

    let (status, response) = if method == "GET" && path == "/v1/embedding/identity" {
        let identity = state.lock().unwrap().embedding_identity_sha256.clone();
        (
            200,
            json!({"data": {
                "version": 1,
                "backend": "lexical",
                "identity_sha256": identity,
                "dimensions": 384,
                "semantic_contract": "semantic_text-derived-vector.v1",
                "resumable": true
            }, "took_ms": 0, "request_id": "test"}),
        )
    } else if method == "PUT"
        && !path.starts_with("/autoindex-catalog")
        && state
            .lock()
            .unwrap()
            .refused_dataset_indices
            .iter()
            .any(|needle| path.contains(needle.as_str()))
    {
        // #929. Deliberately worded without "exists": `Es::ensure_index` reads
        // a 400 containing that word as "the index is already there".
        let reason = "nested semantic_text field [a.b] is not supported; map semantic_text as a \
                      top-level field";
        (
            400,
            json!({
                "error": {
                    "root_cause": [{"type": "mapper_parsing_exception", "reason": reason}],
                    "type": "mapper_parsing_exception",
                    "reason": reason
                },
                "status": 400
            }),
        )
    } else if method == "PUT" && path == "/autoindex-catalog" {
        if state.lock().unwrap().catalog_preexists {
            (
                400,
                json!({"error": {"type": "resource_already_exists_exception"}}),
            )
        } else {
            (200, json!({"acknowledged": true}))
        }
    } else if method == "PUT" && path == "/autoindex-catalog/_mapping" {
        let mapping: Value = serde_json::from_slice(&body).unwrap();
        let started_requested = mapping.pointer("/properties/started").is_some();
        let required = ["summary_generated_at", "invocation_telemetry_scope"];
        let upgraded = required.iter().all(|field| {
            mapping
                .pointer(&format!("/properties/{field}/type"))
                .and_then(Value::as_str)
                .is_some()
        });
        let corpus_scope_requested = mapping
            .pointer(&format!("/properties/{}/type", catalog::CORPUS_SCOPE_FIELD))
            .and_then(Value::as_str)
            == Some("keyword");
        let mut locked = state.lock().unwrap();
        locked.started_mapping_requested |= started_requested;
        if locked.catalog_preexists && started_requested {
            // The shape a real engine returns when the additive upgrade asks
            // for `started` on a legacy (v1.0.0-rc.4) catalog, where `started`
            // was dynamically inferred as `text`. Measured against a live
            // v1.0.0-rc.13 engine, not read off the handler: the request falls
            // past the `illegal_argument_exception` guard — that one only sees
            // *declared* mappings, and `started` was never declared — and is
            // refused by the `idx.schema()` guard, which returns
            // `XerjError::invalid_mapping` and therefore a 400
            // `mapper_parsing_exception`.
            //
            // A correct product never reaches this branch (see
            // `started_mapping_requested`, asserted false in
            // `existing_catalog_is_upgraded_before_new_run_metadata_is_written`).
            // It is kept, and kept accurate, so that adding `started` to the
            // additive upgrade fails here with the message the operator would
            // really see rather than passing silently.
            let reason = "field [started] already exists as [text], cannot add [date]";
            (
                400,
                json!({
                    "error": {
                        "root_cause": [{"type": "mapper_parsing_exception", "reason": reason}],
                        "type": "mapper_parsing_exception",
                        "reason": reason,
                    },
                    "status": 400,
                }),
            )
        } else {
            // #755: the additive upgrade and the corpus-scope field arrive in
            // SEPARATE PUTs now, so this accumulates rather than overwrites —
            // the flag means "the additive upgrade has landed", and the guard
            // that new run metadata must not precede it depends on that.
            locked.catalog_mapping_upgraded |= upgraded;
            locked.catalog_corpus_scope_mapped |= corpus_scope_requested;
            (200, json!({"acknowledged": true}))
        }
    } else if method == "POST" && path == "/_bulk" {
        (200, bulk_response(&body, state))
    } else if method == "POST" && path.contains("/_delete_by_query") {
        let query: Value = serde_json::from_slice(&body).unwrap();
        // A replacement purge is a `bool.should` of `ax_file` and `ax_path`
        // (#2139). A lone `term` is the older shape, still sent by sweeps.
        // Either term matching is enough: the path term is what drops a
        // generation published under a different content key.
        let mut file_terms: Vec<(String, String)> = Vec::new();
        for field in ["ax_file", "ax_path"] {
            if let Some(value) = query
                .pointer(&format!("/query/term/{field}"))
                .and_then(Value::as_str)
            {
                file_terms.push((field.to_string(), value.to_string()));
            }
        }
        if let Some(should) = query
            .pointer("/query/bool/should")
            .and_then(Value::as_array)
        {
            for clause in should {
                for field in ["ax_file", "ax_path"] {
                    if let Some(value) = clause
                        .pointer(&format!("/term/{field}"))
                        .and_then(Value::as_str)
                    {
                        file_terms.push((field.to_string(), value.to_string()));
                    }
                }
            }
        }
        let file_key = query
            .pointer("/query/term/file_key")
            .and_then(Value::as_str)
            .map(str::to_owned);
        // #905: the scoped catalog sweeps delete by exact `_id` now — the
        // corpus scope is decided client-side, per hit, so the delete carries
        // no predicate at all beyond the id list.
        let ids: Vec<String> = query
            .pointer("/query/ids/values")
            .and_then(Value::as_array)
            .map(|values| {
                values
                    .iter()
                    .filter_map(Value::as_str)
                    .map(str::to_owned)
                    .collect()
            })
            .unwrap_or_default();
        let mut locked = state.lock().unwrap();
        locked.delete_calls += 1;
        if !file_terms.is_empty() {
            locked.docs.retain(|_, doc| {
                !file_terms.iter().any(|(field, expected)| {
                    doc.get(field).and_then(Value::as_str) == Some(expected.as_str())
                })
            });
        }
        if let Some(key) = file_key {
            locked
                .catalog_docs
                .retain(|_, doc| doc.get("file_key").and_then(Value::as_str) != Some(key.as_str()));
        }
        // Catalog only: every by-`_id` delete this client issues names
        // `catalog::CATALOG_INDEX`. Report how many documents this pass
        // actually removed. `delete_by_query` repeats until a pass reports
        // zero, so answering `ids.len()` after the documents are gone loops
        // until the client gives up (#2314).
        let mut removed = 0u64;
        for id in &ids {
            if locked.catalog_docs.remove(id).is_some() {
                removed += 1;
            }
        }
        (200, json!({"deleted": removed, "failures": []}))
    } else if method == "GET" && path.ends_with("/_count") {
        let locked = state.lock().unwrap();
        if locked.fail_counts
            || locked
                .unknown_count_indices
                .iter()
                .any(|index| path == format!("/{index}/_count"))
        {
            (200, json!({"error": "count unavailable"}))
        } else if locked
            .empty_count_indices
            .iter()
            .any(|index| path == format!("/{index}/_count"))
        {
            (200, json!({"count": 0}))
        } else {
            (200, json!({"count": locked.docs.len()}))
        }
    } else if method == "POST"
        && path.ends_with("/_search")
        && serde_json::from_slice::<Value>(&body)
            .ok()
            .is_some_and(|query| query.get("size").and_then(Value::as_u64) == Some(0))
        && {
            let locked = state.lock().unwrap();
            locked.fail_counts
                || locked
                    .unknown_count_indices
                    .iter()
                    .any(|index| path == format!("/{index}/_search"))
        }
    {
        (
            200,
            json!({
                "took": 1,
                "timed_out": true,
                "hits": {"total": {"value": 0, "relation": "gte"}, "hits": []}
            }),
        )
    } else if method == "POST"
        && path.starts_with("/autoindex-catalog/")
        && path.ends_with("/_search")
        && serde_json::from_slice::<Value>(&body)
            .ok()
            .is_some_and(|query| {
                query
                    .pointer("/query/ids/values")
                    .and_then(Value::as_array)
                    .is_some()
            })
    {
        // #1977: the graph path reads catalog rows back by `_id` after the
        // write. Answer with the documents actually stored — an empty `hits`
        // array here would fail every successful run.
        let query: Value = serde_json::from_slice(&body).unwrap();
        let wanted = query
            .pointer("/query/ids/values")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default();
        let locked = state.lock().unwrap();
        let mut hits: Vec<Value> = wanted
            .iter()
            .filter_map(Value::as_str)
            .filter_map(|id| {
                locked
                    .catalog_docs
                    .get(id)
                    .map(|doc| json!({"_id": id, "_source": doc}))
            })
            .collect();
        hits.sort_by(|left, right| left["_id"].as_str().cmp(&right["_id"].as_str()));
        (
            200,
            json!({
                "hits": {
                    "total": {"value": hits.len(), "relation": "eq"},
                    "hits": hits
                }
            }),
        )
    } else if method == "POST" && path.ends_with("/_search") {
        // Report the REAL number of stored docs: `run_index` verifies live
        // counts against the journal (#195), so a mock that always answered 0
        // hits would (rightly) fail every successful run. The generated path
        // additionally reads back per-file and per-catalog projections, so the
        // count is filtered by whichever identity the query names.
        let query: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
        // The catalog's duplicate-alias sweep. Recognised by SHAPE — a
        // `status: duplicate` filter beside a `path` terms list — because
        // since #345 one request carries a whole chunk of paths rather than
        // one path per round trip. #905 moved it from `_delete_by_query` to a
        // candidate `_search`: the query is the same, and it is still one
        // request per chunk, which is what the batching assertion measures.
        let filter = query
            .pointer("/query/bool/filter")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default();
        let alias_sweep = filter
            .iter()
            .any(|clause| {
                clause.pointer("/term/status").and_then(Value::as_str) == Some("duplicate")
            })
            .then(|| {
                filter
                    .iter()
                    .find_map(|clause| clause.pointer("/terms/path").and_then(Value::as_array))
                    .map(|paths| {
                        paths
                            .iter()
                            .filter_map(Value::as_str)
                            .map(str::to_owned)
                            .collect::<Vec<String>>()
                    })
                    .unwrap_or_default()
            });
        if let Some(swept) = alias_sweep {
            let mut locked = state.lock().unwrap();
            // Recorded before the fault so a refused sweep is counted too —
            // the point of the batching assertion is how many round trips the
            // run made, not how many of them succeeded.
            locked.alias_sweep_batches.push(swept.clone());
            if locked.fail_alias_sweep {
                // What a poisoned catalog collection really answers: a 500
                // whose BODY names the condition. The client used to keep the
                // status and discard the body, which is the whole reason #345
                // was filed "not investigated".
                (
                    500,
                    json!({
                        "error": {
                            "type": "internal_server_error_exception",
                            "reason": "collection publication was interrupted; reopen the index \
                                       so WAL recovery can rebuild a consistent searchable state"
                        },
                        "status": 500
                    }),
                )
            } else {
                let mut hits: Vec<Value> = locked
                    .catalog_docs
                    .iter()
                    .filter(|(_, doc)| {
                        doc.get("status").and_then(Value::as_str) == Some("duplicate")
                            && swept.iter().any(|path| {
                                doc.get("path").and_then(Value::as_str) == Some(path.as_str())
                            })
                    })
                    .map(|(id, doc)| json!({"_id": id, "_source": doc}))
                    .collect();
                // Deterministic order, so a page boundary is never `HashMap`
                // iteration order.
                hits.sort_by(|left, right| left["_id"].as_str().cmp(&right["_id"].as_str()));
                (
                    200,
                    json!({
                        "hits": {
                            "total": {"value": hits.len(), "relation": "eq"},
                            "hits": hits
                        },
                        "aggregations": {}
                    }),
                )
            }
        } else if path.contains(catalog::CATALOG_INDEX)
            && query.pointer("/query/bool/filter").is_some()
        {
            // #2314: a deletion sweep reads catalog candidates with a
            // `bool.filter` of term clauses and deletes the hits by `_id`.
            // An empty `hits` array made that sweep a no-op.
            let filters = query
                .pointer("/query/bool/filter")
                .and_then(Value::as_array)
                .cloned()
                .unwrap_or_default();
            let locked = state.lock().unwrap();
            let mut hits: Vec<Value> = locked
                .catalog_docs
                .iter()
                .filter(|(_, doc)| {
                    filters.iter().all(|clause| {
                        clause
                            .get("term")
                            .and_then(Value::as_object)
                            .is_none_or(|term| {
                                term.iter()
                                    .all(|(field, value)| doc.get(field) == Some(value))
                            })
                            && clause
                                .get("terms")
                                .and_then(Value::as_object)
                                .and_then(|terms| terms.iter().next())
                                .is_none_or(|(field, values)| {
                                    values.as_array().is_some_and(|values| {
                                        values.iter().any(|value| doc.get(field) == Some(value))
                                    })
                                })
                    })
                })
                .map(|(id, doc)| json!({"_id": id, "_source": doc}))
                .collect();
            hits.sort_by(|left, right| left["_id"].as_str().cmp(&right["_id"].as_str()));
            let total = hits.len();
            let from = query.get("from").and_then(Value::as_u64).unwrap_or(0) as usize;
            let size = query
                .get("size")
                .and_then(Value::as_u64)
                .map(|size| size as usize)
                .unwrap_or(total);
            let page: Vec<Value> = hits.into_iter().skip(from).take(size).collect();
            (
                200,
                json!({
                    "hits": {
                        "total": {"value": total, "relation": "eq"},
                        "hits": page
                    }
                }),
            )
        } else {
            let ax_file = query
                .pointer("/query/term/ax_file")
                .or_else(|| query.pointer("/query/bool/must/0/term/ax_file"))
                .and_then(Value::as_str);
            let file_key = query
                .pointer("/query/term/file_key")
                .and_then(Value::as_str);
            let locked = state.lock().unwrap();
            let documents = if file_key.is_some() {
                &locked.catalog_docs
            } else {
                &locked.docs
            };
            let count = documents
                .values()
                .filter(|doc| {
                    ax_file
                        .is_none_or(|key| doc.get("ax_file").and_then(Value::as_str) == Some(key))
                        && file_key.is_none_or(|key| {
                            doc.get("file_key").and_then(Value::as_str) == Some(key)
                        })
                })
                .count();
            (
                200,
                json!({"hits":{"total":{"value":count},"hits":[]},"aggregations":{}}),
            )
        }
    } else {
        // ping, index creation/mapping, refresh, and catalog operations
        (200, json!({"acknowledged": true}))
    };
    let bytes = response.to_string();
    let reason = match status {
        200 => "OK",
        500 => "Internal Server Error",
        _ => "Bad Request",
    };
    write!(
        stream,
        "HTTP/1.1 {status} {reason}\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);
    // Graph edge bulks are accepted and discarded: this module counts *data*
    // bulks to place injected failures, so edge bulks must not shift the
    // numbering (the graph pipeline has its own e2e suite in detect::e2e).
    //
    // Read the target off whichever action verb the line carries. The brain
    // meta document is written with `create`, not `index`, so keying on
    // `/index/_index` alone let it fall through to the catalog branch and be
    // recorded as fixture drift once this module started indexing with the
    // graph enabled.
    let is_graph = lines
        .first()
        .and_then(|line| serde_json::from_slice::<Value>(line).ok())
        .and_then(|action| {
            ["index", "create", "delete", "update"]
                .iter()
                .find_map(|verb| {
                    action
                        .pointer(&format!("/{verb}/_index"))
                        .and_then(Value::as_str)
                        .map(str::to_owned)
                })
        })
        .is_some_and(|index| index.ends_with("-edges"));
    if is_graph {
        return json!({"errors": false, "items": []});
    }
    {
        // Checked before anything is applied and by LINES, as
        // `xerj-engine/src/bulk.rs` does.
        let mut locked = state.lock().unwrap();
        if let Some(max_actions) = locked.max_actions_per_bulk {
            if lines.len() > max_actions * 2 {
                locked.oversize_bulks_refused.push(lines.len());
                return json!({
                    "took": 0,
                    "errors": true,
                    "items": [{"index": {
                        "_index": "",
                        "_id": "",
                        "status": 413,
                        "error": {
                            "type": "engine_exception",
                            "reason": format!(
                                "bulk request contains {} lines (~{} actions); exceeds \
                                 max_actions_per_bulk of {max_actions}",
                                lines.len(),
                                lines.len() / 2
                            ),
                            "status": 413
                        }
                    }}]
                });
            }
        }
    }
    if !is_data {
        // Catalog bulks mix `index` and `delete` actions (stale aliases, and
        // the junk sweep of #238), so walk the NDJSON rather than assuming
        // action/document pairs — a delete carries no document line.
        let mut locked = state.lock().unwrap();
        if locked.catalog_preexists && !locked.catalog_mapping_upgraded {
            locked.catalog_bulk_before_upgrade = true;
        }
        if locked.swallow_catalog_bulks {
            return json!({"errors": false, "items": []});
        }
        if locked.reject_catalog_items {
            let mut items = Vec::new();
            let mut line = 0;
            while line < lines.len() {
                let Ok(action) = serde_json::from_slice::<Value>(lines[line]) else {
                    line += 1;
                    continue;
                };
                let is_delete = action.get("delete").is_some();
                items.push(json!({"index": {
                    "status": 400,
                    "error": {
                        "type": "document_parsing_exception",
                        "reason": "failed to parse field [time_min] of type [date]"
                    }
                }}));
                line += if is_delete { 1 } else { 2 };
            }
            return json!({"errors": true, "items": items});
        }
        let mut line = 0;
        while line < lines.len() {
            let Ok(action) = serde_json::from_slice::<Value>(lines[line]) else {
                line += 1;
                continue;
            };
            if action.pointer("/delete/_index").and_then(Value::as_str)
                == Some(catalog::CATALOG_INDEX)
            {
                if let Some(id) = action.pointer("/delete/_id").and_then(Value::as_str) {
                    locked.catalog_docs.remove(id);
                }
                line += 1;
            } else if action.pointer("/index/_index").and_then(Value::as_str)
                == Some(catalog::CATALOG_INDEX)
                && line + 1 < lines.len()
            {
                let id = action.pointer("/index/_id").unwrap().as_str().unwrap();
                let doc: Value = serde_json::from_slice(lines[line + 1]).unwrap();
                locked.catalog_docs.insert(id.to_owned(), doc);
                line += 2;
            } else {
                // Fixture drift, not a product signal. Recorded rather than
                // panicked on: this runs on the server thread with the state
                // guard held, so a panic here poisons the `Mutex` and turns
                // `MockEndpoint::drop`'s `join().unwrap()` into a second,
                // misleading panic. Tests assert on it from the test thread.
                locked
                    .unexpected_catalog_actions
                    .push(format!("unexpected catalog bulk action: {action}"));
                line += 1;
            }
        }
        return json!({"errors": false, "items": []});
    }

    let mut locked = state.lock().unwrap();
    locked.data_bulk_number += 1;
    if locked.throttle_data_bulks > 0 {
        locked.throttle_data_bulks -= 1;
        let items: Vec<Value> = lines
            .as_chunks::<2>()
            .0
            .iter()
            .map(|_| {
                json!({"index": {
                    "status": 429,
                    "error": {
                        "type": "engine_exception",
                        "reason": "[parent] real memory circuit breaker tripped: rss=15679MB >= watermark=15564MB (94% of limit=16384MB); writes rejected to prevent an out-of-memory kill",
                        "status": 429
                    }
                }})
            })
            .collect();
        return json!({"errors": true, "items": items});
    }
    if locked.block_writes {
        // Explicit write block: per-item 403 (never 429/5xx), nothing applied.
        let items: Vec<Value> = lines
            .as_chunks::<2>()
            .0
            .iter()
            .map(|_| {
                json!({"index": {
                    "status": 403,
                    "error": {
                        "type": "cluster_block_exception",
                        "reason": "index [failure-test-csv] is blocked for write operations",
                        "status": 403
                    }
                }})
            })
            .collect();
        return json!({"errors": true, "items": items});
    }
    if locked.swallow_data_bulks {
        return json!({"errors": false, "items": []});
    }
    if locked.reject_first_data_item || locked.reject_first_data_item_as_too_large {
        let too_large = locked.reject_first_data_item_as_too_large;
        let mut items = Vec::new();
        for (nth, pair) in lines.as_chunks::<2>().0.iter().enumerate() {
            if nth == 0 {
                let action: Value = serde_json::from_slice(pair[0]).unwrap();
                items.push(json!({"index": {
                    "_id": action.pointer("/index/_id").cloned().unwrap_or(Value::Null),
                    "status": 400,
                    "error": if too_large {
                        json!({
                            "type": "engine_exception",
                            "reason": "document is 16590136 bytes, over the 8388608 byte \
                                       limit for one indexed JSON document; it was not \
                                       indexed. Split it into smaller documents"
                        })
                    } else {
                        json!({
                            "type": "document_parsing_exception",
                            "reason": "refused: value could not be parsed"
                        })
                    }
                }}));
                continue;
            }
            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);
            items.push(json!({"index": {"status": 201}}));
        }
        return json!({"errors": true, "items": items});
    }
    let fail = !locked.failed_once && locked.data_bulk_number == locked.fail_data_bulk;
    let (pairs, _) = lines.as_chunks::<2>();
    let visible = if fail { pairs.len() / 2 } else { pairs.len() };
    for pair in pairs.iter().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(),
        endpoint_url: None,
        url: url.to_owned(),
        api_key: None,
        api_key_file: None,
        workers: 1,
        scan_workers: 1,
        pdf_workers: 1,
        resource_notes: Vec::new(),
        xerj_url_note: None,
        pdf_timeout_secs: 30,
        bulk_mb: 64,
        bulk_timeout_secs: 3_600,
        snapshot_max_bytes: 64 << 30,
        prefix: "failure-test".into(),
        replace_prefix: false,
        prefix_note: None,
        state_dir: Some(state_dir.to_owned()),
        fresh: false,
        follow_symlinks: false,
        follow_symlinks_outside_root: false,
        stub_globs: Vec::new(),
        ignore: crate::ignore_rules::IgnoreOptions::default(),
        max_file_bytes: 1 << 30,
        sample: 50,
        no_semantic: true,
        code_analyzer: Default::default(),
        // This module preserves legacy graph-enabled failure behavior;
        // incremental non-graph behavior has its own HTTP suite.
        brain: None,
        no_graph: false,
        // The gate is switched off in these fixtures on purpose: they assert
        // indexing, resume and edge behaviour, and a timing-derived stop would
        // make them depend on how loaded the runner was. The gate's own
        // behaviour is covered in `gate_tests` and `cli::tests`.
        max_minutes: 0,
        approve: None,
        max_index_bytes: None,
        budget_plan: None,
        drop_indexed: false,
        dry_run: false,
        walk_only: false,
        json: false,
        quiet: true,
        progress: crate::progress::ProgressMode::None,
        progress_interval: None,
        watch: false,
        label: None,
        debounce: std::time::Duration::from_millis(0),
        exclude_rels: Vec::new(),
        exclude: Vec::new(),
        skip_corpus_data: false,
    }
}

/// Row documents only — the file-level graph node document this module's
/// graph-enabled config also publishes (`ax_locator: "file"`) is not part of
/// any replacement transaction's subject.
fn data_rows(state: &MockState) -> Vec<&Value> {
    state
        .docs
        .values()
        .filter(|doc| doc["ax_locator"].as_str() != Some("file"))
        .collect()
}

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()
}

fn dataset_catalog_docs(endpoint: &MockEndpoint) -> Vec<Value> {
    let mut docs: Vec<Value> = endpoint
        .state
        .lock()
        .unwrap()
        .catalog_docs
        .values()
        .filter(|doc| doc.get("doc_kind").and_then(Value::as_str) == Some("dataset"))
        .cloned()
        .collect();
    docs.sort_by_key(|doc| {
        doc.get("slug")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string()
    });
    docs
}

/// The documented headline workflow: point autoindex at a folder, add a file,
/// rerun. The rerun must not fail, must say plainly that the added file was
/// not indexed, and `--fresh` must then absorb it in place.
/// Code/AST coverage on the LEGACY (graph-enabled) path.
///
/// #294 only ever affected the generated `--no-graph` executor, and that
/// asymmetry is exactly why it survived: the two paths reported identically,
/// so comparing their terminal lines told a caller nothing. The counters exist
/// on both, from one definition (`CodeCoverage`), so the next divergence
/// between them is visible in the output rather than only in the index.
#[test]
fn the_legacy_terminal_line_and_run_document_report_code_coverage() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _sink_guard = crate::progress::SINK_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(
        corpus.path().join("alpha.rs"),
        "pub struct AlphaConfig {\n    pub retries: u32,\n}\n\n\
         pub fn alpha_connect(cfg: &AlphaConfig) -> bool {\n    cfg.retries > 0\n}\n",
    )
    .unwrap();
    fs::write(corpus.path().join("rows.csv"), "id,value\n1,first\n").unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert!(!config.no_graph, "this module covers the legacy path");
    config.quiet = false;
    config.progress = crate::progress::ProgressMode::Plain;

    let buffer = Arc::new(Mutex::new(Vec::new()));
    let (code, report) = {
        let _sink = crate::progress::install_test_sink(&buffer);
        run_index_report(config).unwrap()
    };
    assert_eq!(code, 0);
    let report = report.unwrap();
    assert_eq!(report["code_files"], 1, "{report}");
    assert_eq!(report["code_files_indexed"], 1, "{report}");
    assert_eq!(report["code_files_junked"], 0, "{report}");
    let stream = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
    let done = stream
        .lines()
        .find(|line| line.starts_with("xerj-done "))
        .unwrap_or_else(|| panic!("{stream}"));
    assert!(
        done.contains("code_files=1 code_files_indexed=1 code_files_junked=0"),
        "{done}"
    );
    assert!(!stream.contains("warning:"), "{stream}");
    let locked = endpoint.state.lock().unwrap();
    let ast = locked
        .docs
        .values()
        // The file-level AST document carries `defs`; the #500 per-symbol
        // documents also carry `language` but no `defs`, so select on `defs`.
        .find(|doc| doc.get("language").is_some() && doc.get("defs").is_some())
        .unwrap_or_else(|| panic!("the legacy path indexes an AST document for alpha.rs"));
    assert_eq!(ast["language"], "rust", "{ast}");
    assert_eq!(ast["title"], "alpha.rs", "{ast}");
    assert!(
        ast["defs"]
            .as_str()
            .is_some_and(|defs| defs.contains("struct AlphaConfig")),
        "{ast}"
    );
}

/// #955 on the legacy (graph) path, where the defect was SILENT. The catalog
/// went out as one `_bulk` whatever `--bulk-mb` said; past the engine's
/// `max_actions_per_bulk` the answer is one item of status 413, which is
/// neither a 429 nor a 5xx, so `write catalog` counted one ignorable
/// `item_error` and the run reported success with no catalog at all — the map
/// every later `xerj autoindex map` and agent query reads. The catalog is now
/// windowed and a refused request is halved, so the whole catalog lands.
#[test]
fn a_catalog_bulk_the_server_refuses_as_too_large_still_lands_whole() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _sink_guard = crate::progress::SINK_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let write_corpus = |root: &Path| {
        for name in ["a", "b", "c", "d", "e", "f"] {
            fs::write(
                root.join(format!("{name}.csv")),
                format!("id,value\n1,{name}-first\n2,{name}-second\n"),
            )
            .unwrap();
        }
    };
    let catalog_ids = |endpoint: &MockEndpoint| {
        let locked = endpoint.state.lock().unwrap();
        let mut ids: Vec<String> = locked
            .catalog_docs
            .iter()
            .map(|(id, doc)| {
                // A run document's id carries the run's own timestamp.
                if doc["doc_kind"] == "run" {
                    "run".to_owned()
                } else {
                    id.clone()
                }
            })
            .collect();
        ids.sort();
        ids
    };

    let control_corpus = tempfile::tempdir().unwrap();
    let control_state = tempfile::tempdir().unwrap();
    write_corpus(control_corpus.path());
    let control = MockEndpoint::start(usize::MAX);
    let (code, _) = run_index_report(cfg(
        control_corpus.path(),
        control_state.path(),
        &control.url,
    ))
    .unwrap();
    assert_eq!(code, 0);
    let expected = catalog_ids(&control);
    assert!(expected.len() > 4, "{expected:?}");

    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    write_corpus(corpus.path());
    let endpoint = MockEndpoint::start(usize::MAX);
    // Three actions a request: every data bulk here fits (one file, two rows),
    // so the ONLY request over the limit is the catalog — the silent case.
    endpoint.state.lock().unwrap().max_actions_per_bulk = Some(3);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert!(!config.no_graph, "this module covers the legacy path");
    config.quiet = false;
    config.progress = crate::progress::ProgressMode::Plain;
    let buffer = Arc::new(Mutex::new(Vec::new()));
    let (code, _report) = {
        let _sink = crate::progress::install_test_sink(&buffer);
        run_index_report(config).unwrap()
    };
    assert_eq!(code, 0);
    assert_eq!(
        catalog_ids(&endpoint),
        expected,
        "the catalog is the one an unlimited server gets — before #955 it was empty"
    );
    {
        let locked = endpoint.state.lock().unwrap();
        assert!(
            !locked.oversize_bulks_refused.is_empty(),
            "the limit was actually met"
        );
        assert_eq!(
            data_rows(&locked).len(),
            12,
            "six files of two rows: no data bulk was over the limit"
        );
    }
    let stream = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
    let done = stream
        .lines()
        .find(|line| line.starts_with("xerj-done "))
        .unwrap_or_else(|| panic!("{stream}"));
    assert!(done.starts_with("xerj-done ok=true exit=0 "), "{done}");
    assert!(
        done.contains(" bulk_splits="),
        "the terminal line must say the server refused a request for its size: {done}"
    );
}

/// Locks the three fixtures this module's HTTP tests share.
fn http_test_guards() -> (
    std::sync::MutexGuard<'static, ()>,
    std::sync::MutexGuard<'static, ()>,
    std::sync::MutexGuard<'static, ()>,
) {
    (
        FAILPOINT_TEST_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
        state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
        crate::progress::SINK_TEST_LOCK
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
    )
}

/// #1977: one repository per directory, the shape of the ~210-index report.
/// Every dataset the run publishes has a catalog row before the run exits 0.
///
/// 201 is one past the read-back chunk of 200, so the gate's second ids
/// query is part of the passing run and not only the failure path.
#[test]
fn many_datasets_in_one_run_each_get_a_catalog_row() {
    let _guards = http_test_guards();
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    const REPOS: usize = 201;
    for n in 0..REPOS {
        let repo = corpus.path().join(format!("repo-{n:02}"));
        fs::create_dir_all(repo.join(".git")).unwrap();
        fs::write(repo.join(".git").join("HEAD"), "ref: refs/heads/main\n").unwrap();
        fs::write(
            repo.join("notes.md"),
            format!("# repo {n}\n\nnotes for repository {n}.\n"),
        )
        .unwrap();
    }
    let endpoint = MockEndpoint::start(usize::MAX);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert!(
        !config.no_graph,
        "the empty-catalog report is the graph path"
    );
    let (code, _) = run_index_report(config).unwrap();
    assert_eq!(code, 0);
    let datasets = dataset_catalog_docs(&endpoint);
    assert_eq!(
        datasets.len(),
        REPOS,
        "each repository is its own dataset and must have a catalog row: {datasets:?}"
    );
    let runs = endpoint
        .state
        .lock()
        .unwrap()
        .catalog_docs
        .values()
        .filter(|doc| doc.get("doc_kind").and_then(Value::as_str) == Some("run"))
        .count();
    assert_eq!(runs, 1, "the run document is part of the catalog gate");
}

/// #1977: the server answers the catalog bulk as a clean success and writes
/// nothing. That is the data path's swallowed-bulk shape (#195). On the graph
/// path it used to exit 0 with `autoindex-catalog` still empty, so `xerj_map`
/// reported no datasets. The run must fail, and the same command must recover
/// once the server accepts the write — the journal is not finished until the
/// rows are visible.
#[test]
fn a_catalog_bulk_answered_success_but_not_stored_does_not_exit_zero() {
    let _guards = http_test_guards();
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(
        corpus.path().join("rows.csv"),
        "id,value\n1,first\n2,second\n",
    )
    .unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    endpoint.state.lock().unwrap().swallow_catalog_bulks = true;
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    let error = run_index_report(config.clone()).unwrap_err();
    let message = format!("{error:#}");
    assert!(
        message.contains("not visible"),
        "the failure must say the catalog rows are missing: {message}"
    );
    assert!(
        message.contains("rerun the same command"),
        "the failure must name the recovery: {message}"
    );
    {
        let locked = endpoint.state.lock().unwrap();
        assert!(
            locked.catalog_docs.is_empty(),
            "the swallowed bulk must not have stored a catalog row"
        );
        assert_eq!(
            data_rows(&locked).len(),
            2,
            "the data indices are searchable; only the catalog write was lost"
        );
    }
    assert_eq!(
        event_count(state_dir.path(), "finish"),
        0,
        "a catalog the map cannot see must not finish the resume journal"
    );
    endpoint.state.lock().unwrap().swallow_catalog_bulks = false;
    let (code, _) = run_index_report(config).unwrap();
    assert_eq!(code, 0, "the same command rewrites the catalog");
    assert_eq!(
        dataset_catalog_docs(&endpoint).len(),
        1,
        "the recovered run publishes the dataset row"
    );
}

/// #1977: a per-item 400 on every catalog action is not a `server_error`, so
/// it used to be a warning on exit 0 while the catalog stayed empty.
#[test]
fn a_catalog_bulk_refused_item_by_item_does_not_exit_zero() {
    let _guards = http_test_guards();
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("rows.csv"), "id,value\n1,first\n").unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    endpoint.state.lock().unwrap().reject_catalog_items = true;
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    let error = run_index_report(config.clone()).unwrap_err();
    let message = format!("{error:#}");
    assert!(
        message.contains("refused") && message.contains("catalog"),
        "the failure must name the refused catalog documents: {message}"
    );
    assert!(
        endpoint.state.lock().unwrap().catalog_docs.is_empty(),
        "a refused catalog bulk stores nothing"
    );
    assert_eq!(
        event_count(state_dir.path(), "finish"),
        0,
        "a refused catalog must not finish the resume journal"
    );
    endpoint.state.lock().unwrap().reject_catalog_items = false;
    let (code, _) = run_index_report(config).unwrap();
    assert_eq!(
        code, 0,
        "clearing the refusal lets the same command recover"
    );
    assert_eq!(dataset_catalog_docs(&endpoint).len(), 1);
}

/// #944: the shape that aborted a 48,533-file run at 60% — one data bulk
/// answered HTTP 200 with every item `status: 429` by the engine's memory
/// circuit breaker, which engages and releases within a second. The legacy
/// path treated `server_errors > 0` as fatal on the spot. The items are now
/// re-sent once the moment passes, every record lands, the run exits 0, and
/// the terminal line says it happened.
#[test]
fn a_per_item_429_on_a_data_bulk_is_resent_and_the_run_completes() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _sink_guard = crate::progress::SINK_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(
        corpus.path().join("rows.csv"),
        "id,value\n1,first\n2,second\n3,third\n",
    )
    .unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    endpoint.state.lock().unwrap().throttle_data_bulks = 1;
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert!(!config.no_graph, "this module covers the legacy path");
    config.quiet = false;
    config.progress = crate::progress::ProgressMode::Plain;

    let buffer = Arc::new(Mutex::new(Vec::new()));
    let (code, _report) = {
        let _sink = crate::progress::install_test_sink(&buffer);
        run_index_report(config).unwrap()
    };
    assert_eq!(code, 0, "a transient per-item 429 must not end the run");
    let stream = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
    let done = stream
        .lines()
        .find(|line| line.starts_with("xerj-done "))
        .unwrap_or_else(|| panic!("{stream}"));
    assert!(done.starts_with("xerj-done ok=true exit=0 "), "{done}");
    assert!(
        done.contains(" bulk_retries=1"),
        "the terminal line must say the run re-sent a bulk: {done}"
    );
    let locked = endpoint.state.lock().unwrap();
    assert_eq!(
        data_rows(&locked).len(),
        3,
        "every rejected record landed on the re-send"
    );
    assert_eq!(
        locked.data_bulk_number, 2,
        "the throttled bulk and its one re-send; nothing else was retried"
    );
}

#[test]
fn a_rerun_after_an_added_file_succeeds_and_fresh_absorbs_it() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("first.csv"), "id,value\n1,first\n").unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert_eq!(run_index(config.clone()).unwrap(), 0);

    fs::write(corpus.path().join("second.csv"), "id,value\n2,second\n").unwrap();
    // #2314: a csv that fits the frozen dataset is indexed on the rerun.
    // It is not a stale plan and not junk.
    let (code, report) = run_index_report(config.clone()).unwrap();
    assert_eq!(code, 0, "{report:?}");
    let report = report.unwrap();
    assert_eq!(report["files_junk"], 0, "{report}");
    assert!(
        report.get("skipped_appeared").is_none(),
        "a same-schema addition is indexed, not skipped: {report}"
    );
    {
        let locked = endpoint.state.lock().unwrap();
        let live: std::collections::HashSet<&str> = locked
            .docs
            .values()
            .filter_map(|doc| doc["ax_path"].as_str())
            .collect();
        assert!(live.contains("first.csv"), "{live:?}");
        assert!(live.contains("second.csv"), "{live:?}");
    }

    // --fresh still rebuilds in place and keeps both files.
    config.fresh = true;
    assert_eq!(run_index(config).unwrap(), 0);
    let locked = endpoint.state.lock().unwrap();
    let indexed: std::collections::HashSet<&str> = locked
        .docs
        .values()
        .filter_map(|doc| doc["ax_path"].as_str())
        .collect();
    assert!(indexed.contains("first.csv"), "{indexed:?}");
    assert!(indexed.contains("second.csv"), "{indexed:?}");
}

/// #2372: the stale-resume-plan summary names the appeared paths and says
/// `--fresh` next to them. `skipped_appeared` stays the count. The existing
/// `skipped` list is unchanged. The plain `xerj-done` line stays numeric;
/// the names are the lines immediately before it.
fn assert_stale_resume_summary(report: &Value, stream: &str, paths: &[&str]) {
    assert_eq!(report["files_junk"], 0, "{report}");
    assert_eq!(report["skipped_appeared"], paths.len(), "{report}");
    assert_eq!(report["skipped_appeared_files"], json!(paths), "{report}");
    assert!(
        report.get("skipped_appeared_not_listed").is_none(),
        "these paths fit in the summary: {report}"
    );
    let action = report["skipped_appeared_action"]
        .as_str()
        .unwrap_or_else(|| panic!("missing skipped_appeared_action: {report}"));
    assert!(action.contains("--fresh"), "{action}");
    let listed: Vec<&str> = report["skipped"]["files"]
        .as_array()
        .unwrap_or_else(|| panic!("skipped list removed: {report}"))
        .iter()
        .filter_map(|file| file["path"].as_str())
        .collect();
    assert_eq!(
        listed, paths,
        "the existing skipped list still names them: {report}"
    );

    let done_at = stream
        .rfind("xerj-done ")
        .unwrap_or_else(|| panic!("{stream}"));
    let summary_at = stream[..done_at]
        .rfind("not indexed —")
        .unwrap_or_else(|| panic!("summary did not name the files before xerj-done:\n{stream}"));
    let summary = &stream[summary_at..done_at];
    for path in paths {
        assert!(summary.contains(path), "summary missing {path}: {summary}");
    }
    assert!(summary.contains("--fresh"), "{summary}");
    assert!(
        !summary.contains("… and"),
        "these paths are not a remainder: {summary}"
    );
    let done = stream[done_at..]
        .lines()
        .next()
        .unwrap_or_else(|| panic!("{stream}"));
    assert!(done.contains("reason=stale-resume-plan"), "{done}");
    assert!(
        done.contains(&format!("skipped_appeared={}", paths.len())),
        "{done}"
    );
    assert!(
        !done.contains(paths[0]),
        "the plain done line stays numeric; paths are the lines above it: {done}"
    );
}

/// #2076: a resume whose journaled plan predates files now on disk used to
/// record those files as junk and finish `reason=completed-with-junk`. That is
/// the everyday "some input was unusable" success, so an agent treats the
/// corpus as searchable and the new files never land. The frozen graph plan
/// still cannot absorb them (clustering and graph identity stay put;
/// `--no-graph` is the route that reconciles additions). The resume must say
/// the plan is stale, name `--fresh`, and keep the files out of `files_junk`.
#[test]
fn a_resume_whose_plan_predates_new_files_reports_a_stale_plan_not_junk() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _sink_guard = crate::progress::SINK_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("planned.csv"), "id,value\n1,planned\n").unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert_eq!(run_index(config.clone()).unwrap(), 0);

    // Seven is the field-report shape; two is enough to prove the count is
    // not folded into junk and survives a second resume.
    fs::write(corpus.path().join("added-a.md"), "# added a\n").unwrap();
    fs::write(corpus.path().join("added-b.md"), "# added b\n").unwrap();
    config.quiet = false;
    config.progress = crate::progress::ProgressMode::Plain;

    let resume = |config: &IndexCfg| {
        let buffer = Arc::new(Mutex::new(Vec::new()));
        let (code, report) = {
            let _sink = crate::progress::install_test_sink(&buffer);
            run_index_report(config.clone()).unwrap()
        };
        let stream = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
        (code, report, stream)
    };

    let (code, report, stream) = resume(&config);
    assert_eq!(code, 3, "a stale plan is recorded, never fatal");
    let report = report.unwrap();
    assert_eq!(
        report["files_junk"], 0,
        "post-plan files are not junk: {report}"
    );
    assert_eq!(report["skipped_appeared"], 2, "{report}");
    assert_stale_resume_summary(&report, &stream, &["added-a.md", "added-b.md"]);
    assert!(
        stream.contains("skipped because the resumed plan is stale"),
        "{stream}"
    );
    assert!(
        stream.contains("--fresh"),
        "the note must name the flag that includes them: {stream}"
    );
    let done = stream
        .lines()
        .find(|line| line.starts_with("xerj-done "))
        .unwrap_or_else(|| panic!("{stream}"));
    assert!(
        done.contains("reason=stale-resume-plan"),
        "not completed-with-junk: {done}"
    );
    assert!(
        done.contains("junk_files=0") && done.contains("skipped_appeared=2"),
        "{done}"
    );
    assert!(!done.contains("reason=completed-with-junk"), "{done}");
    assert!(done.contains("ok=false"), "{done}");
    {
        let locked = endpoint.state.lock().unwrap();
        let live: Vec<&str> = locked
            .docs
            .values()
            .filter_map(|doc| doc["ax_path"].as_str())
            .collect();
        assert!(
            live.iter().all(|path| *path == "planned.csv"),
            "the frozen plan still publishes nothing for the new files: {live:?}"
        );
    }

    // A second resume must not quietly reclassify the same files as junk.
    // `--progress json` is the machine terminal object: the paths and the
    // `--fresh` recovery have to be fields on it, not only prose notes.
    config.progress = crate::progress::ProgressMode::Json;
    let (again, report, stream) = resume(&config);
    assert_eq!(again, 3);
    let report = report.unwrap();
    assert_eq!(report["files_junk"], 0, "{report}");
    assert_eq!(report["skipped_appeared"], 2, "{report}");
    assert_eq!(
        report["skipped_appeared_files"],
        json!(["added-a.md", "added-b.md"]),
        "{report}"
    );
    assert!(
        report["skipped_appeared_action"]
            .as_str()
            .unwrap_or("")
            .contains("--fresh"),
        "{report}"
    );
    let done = stream
        .lines()
        .filter_map(|line| serde_json::from_str::<Value>(line).ok())
        .find(|event| event["event"] == "done")
        .unwrap_or_else(|| panic!("no JSON done event:\n{stream}"));
    assert_eq!(done["exit"], 3, "{done}");
    assert_eq!(done["reason"], "stale-resume-plan", "{done}");
    // #2411: a completed run over a stale plan does not include these files.
    // Other partial outcomes have their own fields; ok is not a coverage proof.
    assert_eq!(done["ok"], false, "{done}");
    assert_eq!(done["skipped_appeared"], 2, "{done}");
    assert_eq!(
        done["skipped_appeared_files"],
        json!(["added-a.md", "added-b.md"]),
        "{done}"
    );
    assert!(done.get("skipped_appeared_not_listed").is_none(), "{done}");
    assert!(
        done["skipped_appeared_action"]
            .as_str()
            .unwrap_or("")
            .contains("--fresh"),
        "{done}"
    );

    config.fresh = true;
    config.quiet = true;
    config.progress = crate::progress::ProgressMode::None;
    assert_eq!(run_index(config).unwrap(), 0);
    let locked = endpoint.state.lock().unwrap();
    let indexed: std::collections::HashSet<&str> = locked
        .docs
        .values()
        .filter_map(|doc| doc["ax_path"].as_str())
        .collect();
    assert!(indexed.contains("planned.csv"), "{indexed:?}");
    assert!(indexed.contains("added-a.md"), "{indexed:?}");
    assert!(indexed.contains("added-b.md"), "{indexed:?}");
}

/// #1911: one file that changed between phase A's digest and phase B's read
/// (a live lock file on Windows) aborted the whole run with "bulk/backend
/// failures", after other files' records were already live — 87 partial
/// indices and a journal to clean by hand, and a retry met the same file. It is
/// now one skipped file with the reason in the catalog: every other file is
/// indexed and journaled, the run completes with exit 3, and the next run
/// indexes the file's new content.
#[test]
fn a_file_that_changes_mid_run_is_skipped_and_the_run_finishes() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("first.csv"), "id,value\n1,first\n").unwrap();
    fs::write(corpus.path().join("second.csv"), "id,value\n2,second\n").unwrap();
    let live = corpus.path().join("app.lock");
    fs::write(&live, "pid 1\n").unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);

    let grow = live.clone();
    arm_phase_b_start_hook(state_dir.path(), move || {
        let mut f = fs::OpenOptions::new().append(true).open(grow).unwrap();
        f.write_all(b"pid 2 took the lock\n").unwrap();
    });
    let (code, report) =
        run_index_report(config.clone()).expect("one changing file must not abort the run");
    assert_eq!(
        code, 3,
        "a skipped file is completed-with-junk, not a failure"
    );
    let report = report.unwrap();
    assert_eq!(report["files_junk"], 1, "{report}");
    assert_eq!(
        file_done_count(state_dir.path()),
        2,
        "every other file is journaled done"
    );
    {
        let locked = endpoint.state.lock().unwrap();
        let mut paths: Vec<&str> = data_rows(&locked)
            .iter()
            .filter_map(|doc| doc["ax_path"].as_str())
            .collect();
        paths.sort_unstable();
        paths.dedup();
        assert_eq!(paths, vec!["first.csv", "second.csv"], "{paths:?}");
        let skipped: Vec<&Value> = locked
            .catalog_docs
            .values()
            .filter(|doc| doc["path"].as_str() == Some("app.lock"))
            .collect();
        assert_eq!(
            skipped.len(),
            1,
            "the changed file is recorded: {skipped:?}"
        );
        assert_eq!(skipped[0]["status"], "skipped", "{}", skipped[0]);
        let reason = skipped[0]["reason"].as_str().unwrap_or_default();
        assert!(
            reason.contains("changed while this run was reading it"),
            "{reason}"
        );
        assert!(reason.contains("changed size"), "{reason}");
        assert!(reason.contains("rerun"), "{reason}");
    }

    // The file has settled: the same command picks up its current content.
    let (code, _) = run_index_report(config).expect("the rerun completes");
    assert_eq!(code, 0, "nothing is left to skip once the file is still");
    let locked = endpoint.state.lock().unwrap();
    let indexed: std::collections::HashSet<&str> = locked
        .docs
        .values()
        .filter_map(|doc| doc["ax_path"].as_str())
        .collect();
    assert!(indexed.contains("app.lock"), "{indexed:?}");
}

/// #2352: a file that disappears between the walk and the hash (a browser
/// profile lock file another process removes) used to abort the whole run
/// with ENOENT. It is one skipped catalog row; every other file is indexed
/// and the run finishes with exit 3. The next run, with the file still gone,
/// sweeps that row and exits 0.
#[test]
fn a_file_deleted_after_enumeration_is_skipped_and_the_run_finishes() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("first.csv"), "id,value\n1,first\n").unwrap();
    fs::write(corpus.path().join("second.csv"), "id,value\n2,second\n").unwrap();
    let live = corpus.path().join("app.lock");
    fs::write(&live, "pid 1\n").unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);

    let gone = live.clone();
    arm_before_hash_hook(state_dir.path(), move || {
        fs::remove_file(gone).unwrap();
    });
    let (code, report) =
        run_index_report(config.clone()).expect("a vanished file must not abort the run");
    assert_eq!(
        code, 3,
        "a skipped file is completed-with-junk, not a failure"
    );
    let report = report.unwrap();
    assert_eq!(report["files_junk"], 1, "{report}");
    assert_eq!(
        file_done_count(state_dir.path()),
        2,
        "every other file is journaled done"
    );
    {
        let locked = endpoint.state.lock().unwrap();
        let mut paths: Vec<&str> = data_rows(&locked)
            .iter()
            .filter_map(|doc| doc["ax_path"].as_str())
            .collect();
        paths.sort_unstable();
        paths.dedup();
        assert_eq!(paths, vec!["first.csv", "second.csv"], "{paths:?}");
        let skipped: Vec<&Value> = locked
            .catalog_docs
            .values()
            .filter(|doc| doc["path"].as_str() == Some("app.lock"))
            .collect();
        assert_eq!(
            skipped.len(),
            1,
            "the vanished file is recorded: {skipped:?}"
        );
        assert_eq!(skipped[0]["status"], "skipped", "{}", skipped[0]);
        let reason = skipped[0]["reason"].as_str().unwrap_or_default();
        assert!(reason.contains("no longer exists"), "{reason}");
        assert!(reason.contains("disappeared"), "{reason}");
        assert!(
            !reason.contains("not in the frozen resume plan"),
            "{reason}"
        );
    }

    let (code, report) = run_index_report(config).expect("the rerun completes");
    assert_eq!(
        code, 0,
        "a file that is gone on the next walk is not still junk: {report:?}"
    );
}

#[test]
fn completed_plan_sweeps_a_vanished_content_group() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("first.csv"), "id,value\n1,first\n").unwrap();
    fs::write(corpus.path().join("second.csv"), "id,value\n2,second\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::remove_file(corpus.path().join("second.csv")).unwrap();
    assert_eq!(run_index(config).unwrap(), 3);
    let locked = endpoint.state.lock().unwrap();
    let live: std::collections::HashSet<&str> = locked
        .docs
        .values()
        .filter_map(|doc| doc["ax_path"].as_str())
        .collect();
    assert!(live.contains("first.csv"), "{live:?}");
    assert!(!live.contains("second.csv"), "{live:?}");
    assert!(locked
        .catalog_docs
        .values()
        .all(|doc| doc["path"].as_str() != Some("second.csv")));
}

#[test]
/// #2314: a rerun that both deletes indexed files and adds same-schema files
/// used to refuse before any mutation. The deletions are swept and the
/// additions are indexed.
fn completed_plan_sweeps_deletions_and_indexes_same_schema_additions() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("b-old.csv"), "id,value\n1,b\n").unwrap();
    fs::write(corpus.path().join("a-old.csv"), "id,value\n2,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::remove_file(corpus.path().join("b-old.csv")).unwrap();
    fs::remove_file(corpus.path().join("a-old.csv")).unwrap();
    fs::write(corpus.path().join("z-new.csv"), "id,value\n3,z\n").unwrap();
    fs::write(corpus.path().join("m-new.csv"), "id,value\n4,m\n").unwrap();
    assert_eq!(run_index(config).unwrap(), 3);
    let locked = endpoint.state.lock().unwrap();
    let live: std::collections::HashSet<&str> = locked
        .docs
        .values()
        .filter_map(|doc| doc["ax_path"].as_str())
        .collect();
    assert!(
        live.contains("m-new.csv") && live.contains("z-new.csv"),
        "{live:?}"
    );
    assert!(
        !live.contains("a-old.csv") && !live.contains("b-old.csv"),
        "{live:?}"
    );
}

/// An in-place EDIT is a replacement, not a removal. `--fresh` is the route
/// the refusal itself recommends for picking up added and changed files, so
/// the gate must not classify the edited file's superseded content key as a
/// vanished group — the path is still there, and the pipeline republishes it.
#[test]
fn fresh_absorbs_an_edited_file_instead_of_calling_it_a_removal() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("notes.csv"), "id,value\n1,before\n").unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert_eq!(run_index(config.clone()).unwrap(), 0);

    fs::write(corpus.path().join("notes.csv"), "id,value\n1,after\n").unwrap();
    config.fresh = true;
    assert_eq!(
        run_index(config).unwrap(),
        0,
        "an edited file is a same-path replacement, not a vanished content group"
    );
    let locked = endpoint.state.lock().unwrap();
    assert!(
        locked
            .docs
            .values()
            .any(|doc| doc["value"].as_str() == Some("after")),
        "the new content is live: {:?}",
        locked.docs
    );
    // What must never happen is this run being REFUSED by a message claiming a
    // file that is sitting in the folder has vanished. The previous content
    // key is not the one `--fresh` writes, so the purge is by path (#2139):
    // the pre-edit row must not stay live beside the new one.
    assert!(
        locked
            .docs
            .values()
            .all(|doc| doc["value"].as_str() != Some("before")),
        "--fresh must drop the pre-edit row: {:?}",
        locked.docs
    );
}

/// An ordinary rerun keeps the planned key and replaces its records, so
/// nothing is stranded. `--fresh` of the same edit now purges by path as well
/// ([`fresh_absorbs_an_edited_file_instead_of_calling_it_a_removal`]); this
/// test is the path that does not need a new key to get there.
#[test]
fn an_ordinary_rerun_replaces_an_edited_file_without_stranding_records() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("notes.csv"), "id,value\n1,before\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(corpus.path().join("notes.csv"), "id,value\n1,after\n").unwrap();
    assert_eq!(run_index(config).unwrap(), 0);
    let locked = endpoint.state.lock().unwrap();
    let values: Vec<&str> = locked
        .docs
        .values()
        .filter_map(|doc| doc["value"].as_str())
        .collect();
    assert_eq!(values, ["after"], "the superseded record is replaced");
}

/// #2139: graph resume must drop symbol documents whose declaration moved or
/// disappeared. CSV row locators (`r0`) stay put when a cell changes, so
/// [`an_ordinary_rerun_replaces_an_edited_file_without_stranding_records`]
/// still passes when the file-level `ax_file` delete is a no-op. Per-symbol
/// ids are `code:<line>:<name>` and do not.
#[test]
fn graph_resume_drops_shifted_and_removed_symbols() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("jobs.rs"), GRAPH_CODE_V1).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);
    {
        let locked = endpoint.state.lock().unwrap();
        let rows = graph_symbol_rows(&locked);
        assert!(
            rows.iter().any(|(name, _, code)| {
                name == "query_job" && code.contains("group_id") && !code.contains("&self")
            }),
            "genesis must index the original query_job symbol: {rows:?}"
        );
        assert!(
            rows.iter().any(|(name, _, _)| name == "gone_symbol"),
            "genesis must index gone_symbol: {rows:?}"
        );
    }

    // A previous generation under a different content key (what `--fresh`, or
    // an earlier key change, leaves behind). Ordinary resume keeps the planned
    // key and used to delete only that key, so this document survived.
    endpoint.state.lock().unwrap().docs.insert(
        "stale-generation".to_string(),
        json!({
            "ax_path": "jobs.rs",
            "ax_file": "stale-generation-key",
            "ax_locator": "code:1:query_job",
            "name": "query_job",
            "line": 1,
            "code": "pub fn query_job(group_id: &str, raw: &str) -> bool"
        }),
    );

    fs::write(corpus.path().join("jobs.rs"), GRAPH_CODE_V2).unwrap();
    assert_eq!(
        run_index(config).unwrap(),
        0,
        "graph resume of an edited code file must succeed"
    );
    let locked = endpoint.state.lock().unwrap();
    let live = graph_symbol_rows(&locked);
    let rendered = serde_json::to_string(&locked.docs).unwrap();
    assert!(
        !rendered.contains("gone_symbol"),
        "removed symbol gone_symbol is still indexed: {rendered}"
    );
    assert!(
        !rendered.contains("pub fn query_job(group_id"),
        "the pre-edit query_job signature is still indexed: {rendered}"
    );
    assert!(
        rendered.contains("pub fn query_job(&self"),
        "the current query_job signature is missing: {rendered}"
    );
    drop(locked);

    let fresh_corpus = tempfile::tempdir().unwrap();
    let fresh_state = tempfile::tempdir().unwrap();
    fs::write(fresh_corpus.path().join("jobs.rs"), GRAPH_CODE_V2).unwrap();
    let fresh = MockEndpoint::start(usize::MAX);
    let fresh_config = cfg(fresh_corpus.path(), fresh_state.path(), &fresh.url);
    assert_eq!(run_index(fresh_config).unwrap(), 0);
    let fresh_locked = fresh.state.lock().unwrap();
    let fresh_rows = graph_symbol_rows(&fresh_locked);
    assert_eq!(
        live, fresh_rows,
        "symbol documents (name, line, code) must match a fresh graph index of the edited file"
    );
    let live_docs = endpoint.state.lock().unwrap().docs.len();
    assert_eq!(
        live_docs,
        fresh_locked.docs.len(),
        "document count must match a fresh graph index of the edited file\n\
         live={}\nfresh={}",
        serde_json::to_string(&endpoint.state.lock().unwrap().docs).unwrap(),
        serde_json::to_string(&fresh_locked.docs).unwrap()
    );
}

/// #2139: `--fresh` gives the edited file a new content key and used to skip
/// the delete, so the previous symbol documents stayed searchable. A second
/// edit then resumes on that new key and must not bring the first generation
/// back either.
#[test]
fn fresh_then_resume_drops_every_previous_symbol_generation() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("jobs.rs"), GRAPH_CODE_V1).unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert_eq!(run_index(config.clone()).unwrap(), 0);

    fs::write(corpus.path().join("jobs.rs"), GRAPH_CODE_V2).unwrap();
    config.fresh = true;
    assert_eq!(run_index(config.clone()).unwrap(), 0, "--fresh of an edit");
    {
        let rendered = serde_json::to_string(&endpoint.state.lock().unwrap().docs).unwrap();
        assert!(
            !rendered.contains("gone_symbol"),
            "--fresh left the removed symbol: {rendered}"
        );
        assert!(
            !rendered.contains("pub fn query_job(group_id"),
            "--fresh left the pre-edit signature: {rendered}"
        );
        assert!(
            rendered.contains("pub fn query_job(&self"),
            "--fresh did not index the current signature: {rendered}"
        );
    }

    fs::write(corpus.path().join("jobs.rs"), GRAPH_CODE_V3).unwrap();
    config.fresh = false;
    assert_eq!(run_index(config).unwrap(), 0, "resume after --fresh");
    let rendered = serde_json::to_string(&endpoint.state.lock().unwrap().docs).unwrap();
    assert!(
        !rendered.contains("gone_symbol")
            && !rendered.contains("pub fn query_job(group_id")
            && !rendered.contains("pub fn query_job(&self, group_id"),
        "a later resume must not keep either previous generation: {rendered}"
    );
    assert!(
        rendered.contains("pub fn query_job(&self, id: u64)"),
        "the third signature is missing: {rendered}"
    );
}

fn graph_symbol_rows(state: &MockState) -> Vec<(String, u64, String)> {
    let mut rows: Vec<(String, u64, String)> = state
        .docs
        .values()
        .filter(|doc| doc.get("defs").is_none() && doc["ax_locator"].as_str() != Some("file"))
        .filter_map(|doc| {
            Some((
                doc.get("name")?.as_str()?.to_string(),
                doc.get("line")?.as_u64()?,
                doc.get("code")?.as_str()?.to_string(),
            ))
        })
        .collect();
    rows.sort();
    rows
}

const GRAPH_CODE_V1: &str = "\
struct Jobs;\n\
\n\
impl Jobs {\n\
    pub fn gone_symbol() -> i32 {\n\
        1\n\
    }\n\
\n\
    pub fn query_job(group_id: &str, raw: &str) -> bool {\n\
        !raw.is_empty()\n\
    }\n\
}\n\
";

const GRAPH_CODE_V2: &str = "\
struct Jobs;\n\
\n\
impl Jobs {\n\
    // the signature gained &self and the declaration moved down\n\
\n\
\n\
    pub fn query_job(&self, group_id: &str, raw: &str) -> bool {\n\
        !raw.is_empty()\n\
    }\n\
}\n\
";

/// Not a substring of [`GRAPH_CODE_V2`], so a search of the indexed text can
/// tell the third generation from the second.
const GRAPH_CODE_V3: &str = "\
struct Jobs;\n\
\n\
impl Jobs {\n\
    pub fn query_job(&self, id: u64) -> bool {\n\
        id > 0\n\
    }\n\
}\n\
";

/// Index, then add one file and edit another. The rerun replaces the edit and
/// indexes the addition (#2314). `--fresh` afterwards keeps both.
#[test]
fn fresh_absorbs_an_addition_and_an_edit_after_a_reported_rerun() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("first.csv"), "id,value\n1,before\n").unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert_eq!(run_index(config.clone()).unwrap(), 0);

    fs::write(corpus.path().join("first.csv"), "id,value\n1,after\n").unwrap();
    fs::write(corpus.path().join("second.csv"), "id,value\n2,second\n").unwrap();
    assert_eq!(
        run_index(config.clone()).unwrap(),
        0,
        "an edit is replaced and a same-schema addition is indexed"
    );
    {
        let locked = endpoint.state.lock().unwrap();
        let live: std::collections::HashSet<&str> = locked
            .docs
            .values()
            .filter_map(|doc| doc["ax_path"].as_str())
            .collect();
        assert!(
            live.contains("first.csv") && live.contains("second.csv"),
            "{live:?}"
        );
        assert!(locked
            .docs
            .values()
            .any(|doc| doc["value"].as_str() == Some("after")));
    }

    config.fresh = true;
    assert_eq!(
        run_index(config).unwrap(),
        0,
        "--fresh is the documented way out of exactly this state"
    );
    let locked = endpoint.state.lock().unwrap();
    let live: std::collections::HashSet<&str> = locked
        .docs
        .values()
        .filter_map(|doc| doc["ax_path"].as_str())
        .collect();
    assert!(live.contains("first.csv"), "{live:?}");
    assert!(live.contains("second.csv"), "{live:?}");
    assert!(
        locked
            .docs
            .values()
            .any(|doc| doc["value"].as_str() == Some("after")),
        "the edited file's new content is live: {:?}",
        locked.docs
    );
}

/// #2314: `--fresh` used to be refused when a file had disappeared, because
/// discarding the journal does not delete documents. The sweep runs first, so
/// the deleted file's documents are gone and the added file is indexed.
#[test]
fn fresh_sweeps_a_deleted_file_and_indexes_the_addition() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("old.csv"), "id,value\n1,old\n").unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert_eq!(run_index(config.clone()).unwrap(), 0);

    fs::remove_file(corpus.path().join("old.csv")).unwrap();
    fs::write(corpus.path().join("new.csv"), "id,value\n2,new\n").unwrap();
    config.fresh = true;
    assert_eq!(run_index(config).unwrap(), 3);
    let locked = endpoint.state.lock().unwrap();
    let live: std::collections::HashSet<&str> = locked
        .docs
        .values()
        .filter_map(|doc| doc["ax_path"].as_str())
        .collect();
    assert!(live.contains("new.csv"), "{live:?}");
    assert!(!live.contains("old.csv"), "{live:?}");
}

/// #345. A byte-identical duplicate is the ONLY thing that makes a run issue
/// the catalog's duplicate-alias `_delete_by_query` at all, and that call was
/// fatal. A 500 there turned a run whose every document AND whose per-file
/// journal had already committed into `xerj-done ok=false exit=1
/// reason=aborted` — permanently, because the journal is complete, so every
/// rerun indexes zero files and aborts on the same line.
///
/// Three things are asserted together because each one alone is insufficient:
/// the run reaches a terminal non-aborted state, the surfaced text carries the
/// SERVER's reason (a status line alone is what left the original report
/// uninvestigable), and the same corpus without a duplicate is untouched by
/// the identical fault — which is what proves the duplicate is the cause
/// rather than a coincidence.
#[test]
fn a_refused_duplicate_alias_sweep_is_reported_loudly_and_is_not_fatal() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _sink_guard = crate::progress::SINK_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    let shared = "id,value\n1,same\n";
    fs::write(corpus.path().join("a.csv"), shared).unwrap();
    fs::write(corpus.path().join("b.csv"), shared).unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    config.quiet = false;
    config.progress = crate::progress::ProgressMode::Plain;
    assert_eq!(run_index(config.clone()).unwrap(), 0);
    {
        let batches = &endpoint.state.lock().unwrap().alias_sweep_batches;
        assert_eq!(
            batches.len(),
            1,
            "one duplicate path is one sweep request, not one per path: {batches:?}"
        );
        assert_eq!(batches[0].len(), 1, "{batches:?}");
    }

    // Now refuse only that one call, and rerun the completed corpus.
    endpoint.state.lock().unwrap().fail_alias_sweep = true;
    let buffer = Arc::new(Mutex::new(Vec::new()));
    let (code, report) = {
        let _sink = crate::progress::install_test_sink(&buffer);
        run_index_report(config.clone())
            .expect("a fully indexed corpus must not be aborted by a metadata-only catalog sweep")
    };
    assert_eq!(code, 3, "recorded, never fatal — cli.rs EXIT CODES");
    let stream = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
    let done = stream
        .lines()
        .find(|line| line.starts_with("xerj-done "))
        .unwrap_or_else(|| panic!("{stream}"));
    assert!(done.contains("ok=true"), "{done}");
    assert!(
        done.contains("reason=catalog-alias-sweep-failed"),
        "the sweep failure needs its own greppable reason, not completed-with-junk: {done}"
    );
    assert!(done.contains("catalog_alias_sweep_failures=1"), "{done}");
    // The server said WHY, and the operator has to be able to read it.
    assert!(
        stream.contains("collection publication was interrupted"),
        "the server's own reason must reach the surface: {stream}"
    );
    assert!(stream.contains("the corpus IS indexed"), "{stream}");
    assert!(stream.contains("alias not swept: b.csv"), "{stream}");
    let report = report.expect("the run still publishes its run document");
    assert_eq!(report["catalog_alias_sweep_failed_paths"], json!(["b.csv"]));
    assert!(
        report["catalog_alias_sweep_error"]
            .as_str()
            .is_some_and(|error| error.contains("HTTP 500 Internal Server Error")
                && error.contains("collection publication was interrupted")),
        "{report}"
    );

    // The control: the identical fault over a corpus with no duplicate never
    // reaches the sweep at all, so nothing about that run changes.
    let control_corpus = tempfile::tempdir().unwrap();
    let control_state = tempfile::tempdir().unwrap();
    fs::write(control_corpus.path().join("a.csv"), shared).unwrap();
    let control_endpoint = MockEndpoint::start(usize::MAX);
    control_endpoint.state.lock().unwrap().fail_alias_sweep = true;
    let control = cfg(
        control_corpus.path(),
        control_state.path(),
        &control_endpoint.url,
    );
    assert_eq!(run_index(control).unwrap(), 0);
    assert!(
        control_endpoint
            .state
            .lock()
            .unwrap()
            .alias_sweep_batches
            .is_empty(),
        "a corpus with no duplicate must not issue the sweep at all"
    );
}

#[test]
fn deleting_one_path_of_a_duplicate_pair_is_not_a_removed_content_group() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    let bytes = "id,value\n1,same\n";
    fs::write(corpus.path().join("a.csv"), bytes).unwrap();
    fs::write(corpus.path().join("b.csv"), bytes).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);

    // b.csv becomes canonical under the same content key: the group survives
    // the deletion, so no document is stranded and the rerun is allowed.
    fs::remove_file(corpus.path().join("a.csv")).unwrap();
    let result = run_index(config);
    assert!(
        result.is_ok(),
        "a surviving content group must not trip the removal gate: {result:?}"
    );
    let locked = endpoint.state.lock().unwrap();
    // Row documents only: this module indexes graph-enabled, so the surviving
    // source also carries a file-level node document under the same ax_path.
    let live: Vec<&str> = data_rows(&locked)
        .into_iter()
        .filter_map(|doc| doc["ax_path"].as_str())
        .collect();
    assert_eq!(live, ["b.csv"], "canonical path follows the surviving file");
}

#[test]
fn unchanged_planned_junk_is_not_reported_as_added_content() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("rows.csv"), "id,value\n1,kept\n").unwrap();
    fs::write(
        corpus.path().join("opaque.bin"),
        [0_u8, 159, 146, 150, 0, 255],
    )
    .unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert_eq!(run_index(config.clone()).unwrap(), 3);
    let result = run_index(config);
    assert!(
        result.is_ok(),
        "unchanged durable junk must not trip the membership gate: {result:?}"
    );
}

#[test]
fn deleted_planned_junk_is_swept_rather_than_refused() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("rows.csv"), "id,value\n1,kept\n").unwrap();
    fs::write(
        corpus.path().join("opaque.bin"),
        [0_u8, 159, 146, 150, 0, 255],
    )
    .unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert_eq!(run_index(config.clone()).unwrap(), 3);

    // A junk file publishes exactly one catalog row and nothing else, and the
    // #238 sweep deletes that row. Nothing is stranded, so the removal gate
    // must not fire — refusing here would block a case the pipeline handles
    // completely. Only a file that published DOCUMENTS refuses a rerun.
    fs::remove_file(corpus.path().join("opaque.bin")).unwrap();
    assert_eq!(run_index(config.clone()).unwrap(), 0);
    {
        let locked = endpoint.state.lock().unwrap();
        assert!(
            locked
                .catalog_docs
                .values()
                .all(|doc| doc["path"].as_str() != Some("opaque.bin")),
            "the deleted junk file's catalog row must be swept, not left immortal"
        );
        assert!(
            locked
                .catalog_docs
                .values()
                .any(|doc| doc["path"].as_str() == Some("rows.csv")),
            "the surviving indexed file keeps its entry"
        );
    }

    // Deleting the indexed file sweeps its documents too (#2314).
    fs::remove_file(corpus.path().join("rows.csv")).unwrap();
    assert_eq!(run_index(config).unwrap(), 3);
    let locked = endpoint.state.lock().unwrap();
    assert!(locked
        .docs
        .values()
        .all(|doc| doc["ax_path"].as_str() != Some("rows.csv")));
    assert!(locked
        .catalog_docs
        .values()
        .all(|doc| doc["path"].as_str() != Some("rows.csv")));
}

#[test]
/// #2314: emptying the folder sweeps the indexed file, including under
/// `--fresh`. Discarding the journal used to leave the documents live and
/// the command refused rather than recover.
fn emptying_the_folder_sweeps_the_indexed_file_including_fresh() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("only.csv"), "id,value\n1,only\n").unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert_eq!(run_index(config.clone()).unwrap(), 0);

    fs::remove_file(corpus.path().join("only.csv")).unwrap();
    assert_eq!(run_index(config.clone()).unwrap(), 3);
    assert!(endpoint
        .state
        .lock()
        .unwrap()
        .docs
        .values()
        .all(|doc| doc["ax_path"].as_str() != Some("only.csv")));
    config.fresh = true;
    assert_eq!(run_index(config).unwrap(), 0);
    assert!(endpoint
        .state
        .lock()
        .unwrap()
        .docs
        .values()
        .all(|doc| doc["ax_path"].as_str() != Some("only.csv")));
}

#[test]
fn semantic_resume_rejects_embedding_identity_drift_before_another_bulk() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(
        corpus.path().join("report.txt"),
        "Quarterly operating income improved materially after stronger subscription renewals. \
         Management expects durable demand across the next reporting period.",
    )
    .unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    config.no_semantic = false;
    assert_eq!(run_index(config.clone()).unwrap(), 0);
    assert_eq!(event_count(state_dir.path(), "embedding_identity"), 1);
    let bulks_before = endpoint.state.lock().unwrap().data_bulk_number;
    endpoint.state.lock().unwrap().embedding_identity_sha256 = "b".repeat(64);
    let error = run_index(config).unwrap_err().to_string();
    assert!(error.contains("refusing to mix vector spaces"), "{error}");
    assert!(error.contains("--fresh"), "{error}");
    assert_eq!(
        endpoint.state.lock().unwrap().data_bulk_number,
        bulks_before,
        "identity drift must fail before another data bulk"
    );
}

/// `--fresh` must keep working on a graph-enabled (legacy) journal.
///
/// `xerj brain` documents `--fresh` as "ignore the resume journal, re-walk
/// everything" (brain.rs), and its self-heal path depends on it: when the
/// resume journal says a folder is indexed but the server has none of it (a
/// wiped data dir), `brain` sets `fresh = true` and re-runs `run_index_report`
/// to converge. The durable-generation refusal added alongside incremental
/// `--no-graph` reconciliation is deliberately scoped so it cannot reach this
/// path — `brain` always runs graph-enabled, which never commits a generation.
#[test]
fn fresh_restarts_a_completed_graph_enabled_journal_the_way_brain_self_heal_needs() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(
        corpus.path().join("records.csv"),
        "id,value\n0,indexed\n1,indexed\n",
    )
    .unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert_eq!(run_index(config.clone()).unwrap(), 0);
    let plans_before = event_count(state_dir.path(), "plan");

    // The server lost everything; brain's recovery is exactly this.
    endpoint.state.lock().unwrap().docs.clear();
    config.fresh = true;
    assert_eq!(
        run_index(config).unwrap(),
        0,
        "--fresh must not be refused on a legacy graph-enabled journal"
    );
    assert_eq!(
        event_count(state_dir.path(), "plan"),
        plans_before,
        "--fresh restarts from a discarded journal, so it writes exactly one fresh plan"
    );
    assert_eq!(data_rows(&endpoint.state.lock().unwrap()).len(), 2);
}

#[test]
fn fresh_publication_skips_delete_and_noop_resume_does_not_append_plan() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    // run_index reaches Journal::file_done; the file_done IO failpoint is
    // a global one-shot, so every file_done-reaching test must hold its
    // lock (armer or not) or it can steal an armed injection. Acquired
    // after FAILPOINT_TEST_LOCK everywhere — one consistent order.
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    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();
    // A fixed endpoint delay makes the start/summary chronology
    // deterministic instead of relying on scheduler timing.
    let endpoint = MockEndpoint::start_with_delay(usize::MAX, 5);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);

    let (initial_code, initial_summary) = run_index_report(config.clone()).unwrap();
    assert_eq!(initial_code, 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);
    let source_bytes = fs::metadata(corpus.path().join("records.csv"))
        .unwrap()
        .len();
    let initial_dataset = endpoint
        .state
        .lock()
        .unwrap()
        .catalog_docs
        .values()
        .find(|doc| doc.get("doc_kind").and_then(Value::as_str) == Some("dataset"))
        .cloned()
        .expect("dataset catalog document");
    let initial_dataset_bytes = initial_dataset
        .get("bytes")
        .and_then(Value::as_u64)
        .unwrap();
    assert_eq!(initial_dataset_bytes, source_bytes);
    let initial_summary = initial_summary.unwrap();
    assert_eq!(
        initial_summary["invocation_telemetry_scope"],
        json!("latest_invocation_of_durable_run")
    );
    let initial_started =
        chrono::DateTime::parse_from_rfc3339(initial_summary["started"].as_str().unwrap()).unwrap();
    let initial_summary_generated_at = chrono::DateTime::parse_from_rfc3339(
        initial_summary["summary_generated_at"].as_str().unwrap(),
    )
    .unwrap();
    assert!(
        initial_summary_generated_at - initial_started >= chrono::Duration::milliseconds(5),
        "started must be captured before work, not synthesized with the summary"
    );

    let (resume_code, resume_summary) = run_index_report(config).unwrap();
    assert_eq!(resume_code, 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"
    );
    let resumed_dataset = endpoint
        .state
        .lock()
        .unwrap()
        .catalog_docs
        .values()
        .find(|doc| doc.get("doc_kind").and_then(Value::as_str) == Some("dataset"))
        .cloned()
        .expect("dataset catalog document after resume");
    assert_eq!(
        resumed_dataset["bytes"],
        json!(source_bytes),
        "an unchanged resume must not replace durable dataset bytes with zero"
    );
    assert_eq!(
        resume_summary.unwrap()["invocation_telemetry_scope"],
        json!("latest_invocation_of_durable_run")
    );
}

#[test]
fn changed_source_replaces_durable_dataset_bytes_across_reopen() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    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\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);
    let initial_bytes = fs::metadata(&path).unwrap().len();
    assert_eq!(dataset_catalog_docs(&endpoint)[0]["bytes"], initial_bytes);

    fs::write(
        &path,
        "id,value,description\n0,new,a longer replacement source\n1,new,second row\n",
    )
    .unwrap();
    let replacement_bytes = fs::metadata(&path).unwrap().len();
    assert_ne!(replacement_bytes, initial_bytes);
    assert_eq!(run_index(config.clone()).unwrap(), 0);

    // Reopen the durable journal independently of the product invocation.
    let root = config.root.canonicalize().unwrap();
    let reopened = state::Journal::open(
        state_dir.path(),
        &root.to_string_lossy(),
        &config.url,
        &config.prefix,
        config.bulk_timeout_secs,
        false,
    )
    .unwrap();
    assert_eq!(reopened.done.len(), 1);
    assert_eq!(
        reopened.done.values().next().unwrap().bytes,
        replacement_bytes
    );
    drop(reopened);

    // A following unchanged product rescan must publish the replacement
    // generation's durable bytes, not zero and not the historical size.
    assert_eq!(run_index(config).unwrap(), 0);
    assert_eq!(
        dataset_catalog_docs(&endpoint)[0]["bytes"],
        replacement_bytes
    );
}

#[test]
/// #2314: deleting one of two indexed files removes its documents. Dataset
/// bytes then describe what is still live, and a second rerun sees the same
/// settled corpus.
fn deleted_path_documents_are_swept_and_bytes_follow_the_survivor() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    let removed = corpus.path().join("removed.csv");
    let retained = corpus.path().join("retained.csv");
    fs::write(&removed, "id,value\n0,removed\n1,removed\n").unwrap();
    fs::write(&retained, "id,value\n2,retained\n3,retained\n").unwrap();
    let durable_live_bytes =
        fs::metadata(&removed).unwrap().len() + fs::metadata(&retained).unwrap().len();
    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!(
        dataset_catalog_docs(&endpoint)[0]["bytes"],
        durable_live_bytes
    );
    // Row documents only: this module indexes graph-enabled now that
    // `--no-graph` takes the generated executor, so each source also publishes
    // one file-level node document.
    assert_eq!(data_rows(&endpoint.state.lock().unwrap()).len(), 4);

    fs::remove_file(&removed).unwrap();
    let retained_bytes = fs::metadata(&retained).unwrap().len();
    // The sweep is exit 3 (files-removed). The next rerun of the settled
    // folder is exit 0: nothing left to remove.
    for expected in [3, 0] {
        assert_eq!(run_index(config.clone()).unwrap(), expected);
        let locked = endpoint.state.lock().unwrap();
        let rows = data_rows(&locked);
        assert_eq!(rows.len(), 2, "the removed file's rows are gone");
        assert!(rows
            .iter()
            .all(|doc| doc["ax_path"].as_str() == Some("retained.csv")));
        drop(locked);
        assert_eq!(dataset_catalog_docs(&endpoint)[0]["bytes"], retained_bytes);
    }
}

#[test]
fn product_path_counts_shared_source_once_per_distinct_dataset() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    let path = corpus.path().join("finance.sqlite");
    {
        let db = rusqlite::Connection::open(&path).unwrap();
        db.execute_batch(
            "CREATE TABLE quarterly (quarter TEXT, revenue INTEGER);
             INSERT INTO quarterly VALUES ('2026-Q1', 100);
             CREATE TABLE annual (year INTEGER, filing TEXT);
             INSERT INTO annual VALUES (2026, '10-K');",
        )
        .unwrap();
    }
    let source_bytes = fs::metadata(&path).unwrap().len();
    let endpoint = MockEndpoint::start(usize::MAX);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);

    assert_eq!(run_index(config.clone()).unwrap(), 0);
    let root = config.root.canonicalize().unwrap();
    let mut journal = state::Journal::open(
        state_dir.path(),
        &root.to_string_lossy(),
        &config.url,
        &config.prefix,
        config.bulk_timeout_secs,
        false,
    )
    .unwrap();
    let mut plan = journal.plan.clone().unwrap();
    assert_eq!(plan.datasets.len(), 2);
    let assignment = plan.files.values_mut().next().unwrap();
    assert_eq!(assignment.assignments.len(), 2);
    // Model a compatible historical plan that repeated one group assignment.
    // Catalog accounting must deduplicate it by dataset slug.
    assignment
        .assignments
        .push(assignment.assignments[0].clone());
    journal.write_plan(&plan).unwrap();
    drop(journal);

    assert_eq!(run_index(config).unwrap(), 0);
    let datasets = dataset_catalog_docs(&endpoint);
    assert_eq!(datasets.len(), 2);
    assert!(datasets
        .iter()
        .all(|dataset| dataset["bytes"] == json!(source_bytes)));
}

#[test]
fn existing_catalog_is_upgraded_before_new_run_metadata_is_written() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("records.csv"), "id,value\n0,one\n").unwrap();
    let endpoint = MockEndpoint::start_with_existing_catalog();
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);

    let (code, summary) = run_index_report(config).unwrap();
    assert_eq!(code, 0);
    let summary = summary.unwrap();
    assert!(summary["started"].is_string());
    assert!(summary["summary_generated_at"].is_string());
    assert_eq!(
        summary["invocation_telemetry_scope"],
        json!("latest_invocation_of_durable_run")
    );
    let state = endpoint.state.lock().unwrap();
    assert!(state.catalog_mapping_upgraded);
    assert!(
        state.catalog_corpus_scope_mapped,
        "#755: the legacy path must also install the keyword `{}` field — `prefix` is not \
         re-declarable on a catalog that already holds it as text (rc.15..rc.67 inferred it \
         from the run document), so the #737/#693 scoped sweeps have nothing exact to match \
         on without it",
        catalog::CORPUS_SCOPE_FIELD
    );
    assert!(
        !state.started_mapping_requested,
        "the additive upgrade asked a legacy catalog for `started`; a real v1.0.0-rc.4 catalog \
         answers that with 400 mapper_parsing_exception (\"field [started] already exists as \
         [text], cannot add [date]\") and the run aborts before any document work — see the \
         tripwire on catalog::catalog_mapping"
    );
    assert!(
        !state.catalog_bulk_before_upgrade,
        "new run metadata must not reach a legacy catalog before its additive mapping upgrade"
    );
    assert!(
        state.unexpected_catalog_actions.is_empty(),
        "fixture does not model these catalog bulk actions: {:?}",
        state.unexpected_catalog_actions
    );
}

#[test]
fn unchanged_resume_keeps_durable_dataset_junk_and_coercion_notes() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("records.csv"), "id,value\n0,one\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);
    let root = config.root.canonicalize().unwrap();
    let mut journal = state::Journal::open(
        state_dir.path(),
        &root.to_string_lossy(),
        &config.url,
        &config.prefix,
        config.bulk_timeout_secs,
        false,
    )
    .unwrap();
    let plan = journal.plan.clone().unwrap();
    let slug = plan.datasets[0].slug.clone();
    let mut completion = journal.done.values().next().unwrap().clone();
    completion.junk = 7;
    completion.dropped_by_dataset.insert(slug.clone(), 3);
    journal.file_done(&completion).unwrap();
    drop(journal);

    assert_eq!(run_index(config).unwrap(), 0);
    let dataset = dataset_catalog_docs(&endpoint)
        .into_iter()
        .find(|doc| doc["slug"] == slug)
        .unwrap();
    assert_eq!(dataset["junk_records"], 7);
    assert!(dataset["notes"].as_array().unwrap().iter().any(|note| note
        .as_str()
        .is_some_and(|text| { text.contains("3 field values could not be coerced") })));
}

#[test]
fn legacy_plan_without_completion_cleans_possible_partial_visibility() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    // run_index reaches Journal::file_done; the file_done IO failpoint is
    // a global one-shot, so every file_done-reaching test must hold its
    // lock (armer or not) or it can steal an armed injection. Acquired
    // after FAILPOINT_TEST_LOCK everywhere — one consistent order.
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    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_with_scoped_guidance() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    // run_index reaches Journal::file_done; the file_done IO failpoint is
    // a global one-shot, so every file_done-reaching test must hold its
    // lock (armer or not) or it can steal an armed injection. Acquired
    // after FAILPOINT_TEST_LOCK everywhere — one consistent order.
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    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("remove or move one of these two files"));
    assert!(message.contains(
        &state_dir
            .path()
            .join("journal.ndjson")
            .display()
            .to_string()
    ));
    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_or_else(|p| p.into_inner());
    // run_index reaches Journal::file_done; the file_done IO failpoint is
    // a global one-shot, so every file_done-reaching test must hold its
    // lock (armer or not) or it can steal an armed injection. Acquired
    // after FAILPOINT_TEST_LOCK everywhere — one consistent order.
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    // 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
                    .values()
                    .filter(|doc| doc.get("value").is_some())
                    .count()
                    < 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
                .values()
                .filter(|doc| doc.get("value").is_some())
                .count(),
            rows
        );
        assert_eq!(
            locked.delete_calls, 2,
            "fresh publication skips delete; replacement and repair each clean once"
        );
        assert!(locked
            .docs
            .values()
            .filter(|doc| doc.get("value").is_some())
            .all(|doc| {
                doc["value"]
                    .as_str()
                    .is_some_and(|value| value.starts_with("replacement-"))
            }));
        let mut locators: Vec<usize> = locked
            .docs
            .values()
            .filter(|doc| doc.get("value").is_some())
            .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 stage_finish_failure_preserves_previous_records_and_resume_replaces_them() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    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);
    let (old_docs, old_deletes, old_bulks) = {
        let state = endpoint.state.lock().unwrap();
        (
            state.docs.clone(),
            state.delete_calls,
            state.data_bulk_number,
        )
    };
    assert!(!old_docs.is_empty());
    fs::write(&path, "id,value\n0,new\n1,new\n").unwrap();

    // Compression can buffer a successful write until into_reader finishes
    // the frame. This local failure must precede the remote replacement.
    arm_replacement_failpoint(5, state_dir.path());
    let error = run_index(config.clone()).unwrap_err();
    assert!(
        format!("{error:#}").contains("injected replacement crash boundary 5"),
        "{error:#}"
    );
    {
        let state = endpoint.state.lock().unwrap();
        assert_eq!(
            state.delete_calls, old_deletes,
            "deleted before stage finished"
        );
        assert_eq!(state.data_bulk_number, old_bulks);
        assert_eq!(
            state.docs, old_docs,
            "previous records must remain readable"
        );
    }
    assert_eq!(file_done_count(state_dir.path()), 1);
    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(),
        "failed replacement cannot be committed"
    );
    assert_eq!(replay.pending_replacements.len(), 1);
    drop(replay);

    assert_eq!(run_index(config.clone()).unwrap(), 0);
    assert_eq!(file_done_count(state_dir.path()), 2);
    let (new_docs, new_bulks) = {
        let state = endpoint.state.lock().unwrap();
        assert_eq!(state.delete_calls, old_deletes + 1);
        let rows: Vec<_> = state
            .docs
            .values()
            .filter(|doc| doc.get("value").is_some())
            .collect();
        assert_eq!(rows.len(), 2);
        assert!(rows.iter().all(|doc| doc["value"].as_str() == Some("new")));
        (state.docs.clone(), state.data_bulk_number)
    };
    // A zero-work rerun must retain the completed replacement unchanged.
    assert_eq!(run_index(config).unwrap(), 0);
    let state = endpoint.state.lock().unwrap();
    assert_eq!(state.docs, new_docs);
    assert_eq!(state.data_bulk_number, new_bulks);
    assert_eq!(state.delete_calls, old_deletes + 1);
}

#[test]
fn resume_repairs_kills_after_plan_delete_and_final_bulk_before_file_done() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    // run_index reaches Journal::file_done; the file_done IO failpoint is
    // a global one-shot, so every file_done-reaching test must hold its
    // lock (armer or not) or it can steal an armed injection. Acquired
    // after FAILPOINT_TEST_LOCK everywhere — one consistent order.
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    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();

        arm_replacement_failpoint(boundary, state_dir.path());
        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
                .values()
                .filter(|doc| doc.get("value").is_some())
                .count(),
            rows,
            "boundary {boundary}"
        );
        assert!(locked
            .docs
            .values()
            .filter(|doc| doc.get("value").is_some())
            .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_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    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, &state_dir.path().join("journal.ndjson"));
        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
                .values()
                .filter(|doc| doc.get("value").is_some())
                .count(),
            2
        );
        assert!(locked
            .docs
            .values()
            .filter(|doc| doc.get("value").is_some())
            .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_or_else(|p| p.into_inner());
    // run_index reaches Journal::file_done; the file_done IO failpoint is
    // a global one-shot, so every file_done-reaching test must hold its
    // lock (armer or not) or it can steal an armed injection. Acquired
    // after FAILPOINT_TEST_LOCK everywhere — one consistent order.
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    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();
    arm_replacement_failpoint(2, state_dir.path());
    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
            .values()
            .filter(|doc| doc.get("value").is_some())
            .count(),
        2
    );
    assert!(locked
        .docs
        .values()
        .filter(|doc| doc.get("value").is_some())
        .all(|doc| doc["value"].as_str() == Some("generation-c")));
}

#[test]
fn a_planned_key_never_gains_two_owners_when_old_content_moves_paths() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    // run_index reaches Journal::file_done; the file_done IO failpoint is
    // a global one-shot, so every file_done-reaching test must hold its
    // lock (armer or not) or it can steal an armed injection. Acquired
    // after FAILPOINT_TEST_LOCK everywhere — one consistent order.
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    let original = "id,value\n0,original\n1,original\n";
    fs::write(corpus.path().join("a.csv"), original).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);

    // a.csv keeps its planned key by path while its OLD bytes reappear as
    // b.csv — whose content key is exactly the planned key a.csv claims. Both
    // files owning one ax_file key would let each replacement delete the
    // other's freshly published documents.
    fs::write(
        corpus.path().join("a.csv"),
        "id,value\n0,rewritten\n1,rewritten\n",
    )
    .unwrap();
    fs::write(corpus.path().join("b.csv"), original).unwrap();
    assert_eq!(run_index(config.clone()).unwrap(), 3);
    {
        let locked = endpoint.state.lock().unwrap();
        // Graph detection is enabled in this module, so a.csv also carries a
        // file-level node document (`ax_locator: "file"`, no row fields). The
        // replacement transaction's subject is the row documents.
        let rows: Vec<&Value> = data_rows(&locked);
        assert_eq!(rows.len(), 2);
        assert!(rows.iter().all(|doc| {
            doc["ax_path"].as_str() == Some("a.csv") && doc["value"].as_str() == Some("rewritten")
        }));
        assert!(locked
            .docs
            .values()
            .all(|doc| doc["ax_path"].as_str() == Some("a.csv")));
    }
    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.pending_replacements.is_empty());
    assert_eq!(replay.done.len(), 1);
    let plan = replay.plan.clone().unwrap();
    assert_eq!(plan.junk_files.len(), 1);
    assert_eq!(plan.junk_files[0].rel, "b.csv");
    assert!(plan.junk_files[0]
        .reason
        .contains("key ownership exclusive"));
    drop(replay);

    // The divergence is durable and deterministic: an identical rerun keeps
    // the same owner, appends no new plan, and changes no documents.
    let plans_before = event_count(state_dir.path(), "plan");
    assert_eq!(run_index(config).unwrap(), 3);
    assert_eq!(event_count(state_dir.path(), "plan"), plans_before);
    let locked = endpoint.state.lock().unwrap();
    let rows = data_rows(&locked);
    assert_eq!(rows.len(), 2);
    assert!(rows
        .iter()
        .all(|doc| doc["value"].as_str() == Some("rewritten")));
}

/// #2314: a same-schema file added after the plan was frozen is indexed.
/// Deleting it afterwards must take its catalog row with it. The catalog is
/// the data map every `map`/`status`/agent query reads; it must not keep
/// advertising a file that is gone.

#[test]
fn an_added_then_deleted_file_leaves_no_immortal_catalog_entry() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(
        corpus.path().join("planned.csv"),
        "id,value\n0,planned\n1,planned\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);

    // Appears after the plan froze and fits the frozen dataset: indexed.
    fs::write(
        corpus.path().join("added.csv"),
        "id,value\n2,added\n3,added\n",
    )
    .unwrap();
    assert_eq!(run_index(config.clone()).unwrap(), 0);
    let indexed_id = {
        let locked = endpoint.state.lock().unwrap();
        let (id, doc) = locked
            .catalog_docs
            .iter()
            .find(|(_, doc)| doc["path"].as_str() == Some("added.csv"))
            .expect("a same-schema addition is reported in the catalog");
        assert_eq!(doc["doc_kind"].as_str(), Some("file"));
        assert_ne!(doc["status"].as_str(), Some("stale-plan"));
        id.clone()
    };

    // Delete it: the catalog entry goes with it. Exit 3 names the removal;
    // the following rerun of the settled folder is exit 0.
    fs::remove_file(corpus.path().join("added.csv")).unwrap();
    assert_eq!(run_index(config.clone()).unwrap(), 3);
    {
        let locked = endpoint.state.lock().unwrap();
        assert!(
            !locked.catalog_docs.contains_key(&indexed_id),
            "the catalog entry for a deleted added file must not survive"
        );
        assert!(
            locked
                .catalog_docs
                .values()
                .all(|doc| doc["path"].as_str() != Some("added.csv")),
            "no catalog document may still name the deleted file"
        );
        assert!(locked
            .docs
            .values()
            .all(|doc| doc["ax_path"].as_str() != Some("added.csv")));
        // The file that is still there keeps its entry.
        assert!(locked
            .catalog_docs
            .values()
            .any(|doc| doc["path"].as_str() == Some("planned.csv")));
    }

    // Converged: nothing left to add or sweep, so no further plan is appended.
    let plans_before = event_count(state_dir.path(), "plan");
    assert_eq!(run_index(config).unwrap(), 0);
    assert_eq!(event_count(state_dir.path(), "plan"), plans_before);
}

#[test]
fn deleting_an_entire_duplicate_group_strands_no_pending_replacement() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    // run_index reaches Journal::file_done; the file_done IO failpoint is
    // a global one-shot, so every file_done-reaching test must hold its
    // lock (armer or not) or it can steal an armed injection. Acquired
    // after FAILPOINT_TEST_LOCK everywhere — one consistent order.
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("dup-a.csv"), "id,value\n0,dup\n1,dup\n").unwrap();
    fs::write(corpus.path().join("dup-b.csv"), "id,value\n0,dup\n1,dup\n").unwrap();
    fs::write(corpus.path().join("keep.csv"), "id,value\n2,keep\n3,keep\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);
    let starts = event_count(state_dir.path(), "file_replace_start");

    // The whole duplicate group disappears. Its documents are swept (#2314).
    // A key with no current file must still never get a replacement intent
    // journaled, which would be re-appended forever without ever committing.
    fs::remove_file(corpus.path().join("dup-a.csv")).unwrap();
    fs::remove_file(corpus.path().join("dup-b.csv")).unwrap();
    for expected in [3, 0] {
        assert_eq!(run_index(config.clone()).unwrap(), expected);
        assert_eq!(
            event_count(state_dir.path(), "file_replace_start"),
            starts,
            "an orphaned duplicate-group key must not schedule a replacement"
        );
        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.pending_replacements.is_empty());
        let locked = endpoint.state.lock().unwrap();
        let live: std::collections::HashSet<&str> = locked
            .docs
            .values()
            .filter_map(|doc| doc["ax_path"].as_str())
            .collect();
        assert!(live.contains("keep.csv"), "{live:?}");
        assert!(
            !live.contains("dup-a.csv") && !live.contains("dup-b.csv"),
            "{live:?}"
        );
        assert!(locked.catalog_docs.values().all(|doc| {
            let path = doc["path"].as_str();
            path != Some("dup-a.csv") && path != Some("dup-b.csv")
        }));
        assert!(replay
            .done
            .values()
            .all(|done| done.path != "dup-a.csv" && done.path != "dup-b.csv"));
    }
}

#[test]
fn partial_file_done_is_rolled_back_before_another_worker_commits() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    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, &state_dir.path().join("journal.ndjson"));
    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
            .values()
            .filter(|doc| doc.get("value").is_some())
            .count(),
        4
    );
    assert!(locked
        .docs
        .values()
        .filter(|doc| doc.get("value").is_some())
        .all(|doc| {
            doc["value"]
                .as_str()
                .is_some_and(|value| value.ends_with("-new"))
        }));
}

/// #195: an index write block rejects every bulk item with status 403 (the
/// status ES assigns explicit/API blocks — only the flood-stage
/// `read_only_allow_delete` block is 429). A status-based classifier filed
/// those items under "junk source records", journaled the file COMPLETE, and
/// the instructed rerun then resumed past the journal and reported success
/// over an empty index. Blocks must be classified by error type: fatal,
/// file left pending, and the rerun after the block lifts must really index.
#[test]
fn write_block_rejections_are_backend_fatal_and_the_file_stays_pending() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(
        corpus.path().join("records.csv"),
        "id,value\n0,blocked\n1,blocked\n",
    )
    .unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);

    endpoint.state.lock().unwrap().block_writes = true;
    let error = format!("{:#}", run_index(config.clone()).unwrap_err());
    assert!(error.contains("blocked"), "{error}");
    assert_eq!(
        file_done_count(state_dir.path()),
        0,
        "a write-blocked source file must stay pending in the journal"
    );
    assert!(endpoint.state.lock().unwrap().docs.is_empty());

    // Block lifted: the SAME command must resume and actually index.
    endpoint.state.lock().unwrap().block_writes = false;
    assert_eq!(run_index(config).unwrap(), 0);
    assert_eq!(file_done_count(state_dir.path()), 1);
    assert_eq!(data_rows(&endpoint.state.lock().unwrap()).len(), 2);
}

/// Pins WHY the run document carries no backend-rejection count, so nobody
/// "restores" one that could only ever read 0.
///
/// Making `junk_records_total` durable narrowed it: it no longer folds in the
/// per-item rejections that `record_bulk_outcome` counts. That looks like a
/// lost signal, and it would be one — except that a single per-item rejection
/// also lands in `bulk_errors`, which aborts the run before the run document,
/// the map, the summary line and the exit code exist at all. So the narrowed
/// number was unreachable in any published map either way.
///
/// The rejection count is therefore reported in the one place a rejected run
/// ever reaches: the abort message, where it supplies the scale that
/// `bulk_errors`' first-five sample cannot.
///
/// The file that carried the refused record is named and stays un-journaled,
/// so the rerun the message asks for really retries it (#2807).
#[test]
fn backend_rejected_records_abort_the_run_before_any_map_is_written() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(
        corpus.path().join("records.csv"),
        "id,value\n0,kept\n1,kept\n2,kept\n",
    )
    .unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    endpoint.state.lock().unwrap().reject_first_data_item = true;
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);

    // A per-item 400 is NOT a server error (not 429, not 5xx, not a block), so
    // it is the weakest rejection the classifier recognises — and even it is
    // fatal.
    let error = format!("{:#}", run_index_report(config).unwrap_err());
    assert!(
        error.contains("document_parsing_exception"),
        "the refusal itself must be quoted: {error}"
    );
    assert!(
        error.contains("The backend refused 1 record(s)."),
        "the abort must state how many records were refused, not just sample the errors: {error}"
    );

    // #2807: the refused record's source file is named and is NOT journaled
    // complete, as the message says. It used to be journaled, so a rerun
    // resumed past it, reported success and never sent the refused record.
    assert!(
        error.contains("records.csv"),
        "the abort must name the file whose record was refused: {error}"
    );
    assert_eq!(
        file_done_count(state_dir.path()),
        0,
        "a source with a refused record must not be journaled complete"
    );

    // With the refusal gone, the same command resumes and sends every record.
    endpoint.state.lock().unwrap().reject_first_data_item = false;
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    run_index_report(config).unwrap();
    assert_eq!(file_done_count(state_dir.path()), 1);
}

/// #195 last-resort gate: a backend that ACCEPTS every bulk but persists
/// nothing (the shape of any rejection path the per-item classifier does
/// not recognise) must not yield a success exit. The journal says records
/// landed; the live count says zero; the run must fail and say how to
/// recover.
#[test]
fn zero_live_documents_after_journaled_records_fails_the_run() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(
        corpus.path().join("records.csv"),
        "id,value\n0,ghost\n1,ghost\n",
    )
    .unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    endpoint.state.lock().unwrap().swallow_data_bulks = true;
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);

    let error = format!("{:#}", run_index(config).unwrap_err());
    assert!(error.contains("verification failed"), "{error}");
    assert!(error.contains("0 documents are live"), "{error}");
    assert!(error.contains("--fresh"), "{error}");
    let state = state_dir.path().display().to_string();
    assert!(
        error.contains(&format!("Journal state dir: {state}")),
        "the refusal must name the journal directory: {error}"
    );
    assert!(
        error.contains("may belong to another data dir"),
        "a reused journal must say it may belong to another data dir: {error}"
    );
}

/// #2407: the zero-live gate summed live documents over every dataset, so a
/// populated sibling hid an index that held nothing. The reporter's re-run
/// printed `ok: indexed and searchable` over a 0-document `-docs` index
/// beside a live `-json` one. The empty dataset must fail the run by name,
/// and it must not be the all-empty error `xerj brain` reads as a wiped
/// destination.
#[test]
fn an_empty_dataset_beside_a_live_one_fails_the_run() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let write_corpus = |root: &Path| {
        fs::write(root.join("rows.csv"), "id,value\n1,first\n2,second\n").unwrap();
        fs::write(
            root.join("notes.md"),
            "# Notes\n\nTiered merge policy picks segments of similar size.\n",
        )
        .unwrap();
    };
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    write_corpus(corpus.path());
    let endpoint = MockEndpoint::start(usize::MAX);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    let prefix = config.prefix.clone();
    assert_eq!(run_index(config.clone()).unwrap(), 0);
    // Learn the prose dataset's index rather than hard-coding the slug scheme.
    let prose = {
        let locked = endpoint.state.lock().unwrap();
        let slug = data_rows(&locked)
            .into_iter()
            .find(|doc| doc["ax_path"] == "notes.md")
            .and_then(|doc| doc["ax_dataset"].as_str())
            .expect("notes.md is indexed")
            .to_owned();
        format!("{prefix}-{slug}")
    };

    let completed = || -> Vec<Value> {
        fs::read_to_string(state_dir.path().join("journal.ndjson"))
            .unwrap()
            .lines()
            .map(|line| serde_json::from_str::<Value>(line).unwrap())
            .filter(|row| row["kind"] == "file_done")
            .collect()
    };
    let before_journal = completed();
    let before_docs = endpoint.state.lock().unwrap().docs.clone();
    let sibling = {
        let locked = endpoint.state.lock().unwrap();
        let slug = data_rows(&locked)
            .into_iter()
            .find(|doc| doc["ax_path"] == "rows.csv")
            .and_then(|doc| doc["ax_dataset"].as_str())
            .unwrap()
            .to_owned();
        format!("{prefix}-{slug}")
    };
    endpoint.state.lock().unwrap().empty_count_indices = vec![prose.clone()];
    // A known live sibling and an unknown sibling must both leave the
    // independently confirmed missing dataset visible as a verification error.
    for unknown in [false, true] {
        endpoint.state.lock().unwrap().unknown_count_indices = if unknown {
            vec![sibling.clone()]
        } else {
            vec![]
        };
        let error = run_index(config.clone()).unwrap_err();
        assert!(
            !error.is::<crate::ZeroLiveVerificationError>(),
            "partial evidence must not claim a wiped destination: {error:#}"
        );
        let error = format!("{error:#}");
        assert!(error.contains("verification failed"), "{error}");
        assert!(
            error.contains(&format!("{prose} (")) && error.contains("record(s) from 1 file(s))"),
            "the empty index is named with attributable journal counts: {error}"
        );
        assert!(error.contains("1 of the 2 dataset index(es)"), "{error}");
        assert!(error.contains("--fresh"), "{error}");
        assert_eq!(
            completed(),
            before_journal,
            "completed file authority survives verification failure"
        );
        assert_eq!(
            endpoint.state.lock().unwrap().docs,
            before_docs,
            "verification failure must retain existing records"
        );
    }
    // Exercise the recovery the diagnostic recommends, then an ordinary resume.
    {
        let mut locked = endpoint.state.lock().unwrap();
        locked.empty_count_indices.clear();
        locked.unknown_count_indices.clear();
    }
    let mut rebuild = config.clone();
    rebuild.fresh = true;
    assert_eq!(run_index(rebuild).unwrap(), 0);
    assert_eq!(run_index(config).unwrap(), 0);
    let locked = endpoint.state.lock().unwrap();
    assert!(data_rows(&locked)
        .iter()
        .any(|doc| doc["ax_path"] == "notes.md"));
    assert!(data_rows(&locked)
        .iter()
        .any(|doc| doc["ax_path"] == "rows.csv"));
}

/// A node that accepted the bulks and then could not count (the size:0
/// fallback comes back `timed_out` with total 0) must not abort finalize.
/// Treating that 0 as "nothing is live" is the count-mismatch abort: the
/// journal is right, the count is not a measurement.
#[test]
fn a_count_that_does_not_answer_does_not_fail_a_run_that_wrote_records() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(
        corpus.path().join("records.csv"),
        "id,value\n0,kept\n1,kept\n",
    )
    .unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    endpoint.state.lock().unwrap().fail_counts = true;
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);

    let code = run_index(config).expect("an unanswered count is not an empty index");
    assert_eq!(code, 0, "the records were accepted");
    assert!(
        endpoint.state.lock().unwrap().docs.len() >= 2,
        "the mock kept the documents the count could not see"
    );
}

/// #241 regression: a run must never be silent.
///
/// Before this fix `autoindex` printed a handful of phase banners, one line
/// per 200 completed files, and then nothing at all through the entire
/// `finalize` block — measured at 47-64% of wall in the issue and at 45% (100
/// of 222 s) on the corpus used to reproduce it here. An agent watching the
/// stream could not tell a running index from a hung one.
///
/// This asserts the three properties that make the stream readable, through
/// the REAL progress surface a production run uses:
///   1. phase B reports as it goes, with a percent and an ETA field;
///   2. the previously-silent finalize block reports at all;
///   3. every run on a surface that prints at all ends with a terminal line
///      stating the outcome in words, because exit 3 is a success an agent
///      otherwise reads as failure. (`--progress none` prints nothing —
///      asserted by `quiet_runs_emit_no_progress_stream_at_all` below.)
#[test]
fn a_run_reports_progress_through_every_phase_and_closes_the_stream() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _sink_guard = crate::progress::SINK_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    // Distinct bytes per file: byte-identical files collapse into one
    // canonical file plus aliases, which would make `files=8` a lie.
    for n in 0..8 {
        fs::write(
            corpus.path().join(format!("rows-{n}.csv")),
            format!("id,value\n{n}0,alpha\n{n}1,beta\n{n}2,gamma\n"),
        )
        .unwrap();
    }

    let endpoint = MockEndpoint::start(usize::MAX);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    config.quiet = false;
    config.progress = crate::progress::ProgressMode::Plain;
    config.progress_interval = Some(std::time::Duration::from_secs(1));

    let buffer = Arc::new(Mutex::new(Vec::new()));
    let (code, _report) = {
        let _sink = crate::progress::install_test_sink(&buffer);
        run_index_report(config).unwrap()
    };
    let stream = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();

    let progress_lines: Vec<&str> = stream
        .lines()
        .filter(|line| line.starts_with("xerj-progress "))
        .collect();
    assert!(
        progress_lines.len() >= 5,
        "a run must narrate its phases, got {} line(s):\n{stream}",
        progress_lines.len()
    );
    assert!(
        progress_lines
            .iter()
            .any(|line| line.contains("phase=index")),
        "phase B must report:\n{stream}"
    );
    assert!(
        progress_lines
            .iter()
            .any(|line| line.contains("phase=finalize")),
        "the finalize block was the longest silence in the tool; it must report now:\n{stream}"
    );
    assert!(
        progress_lines
            .iter()
            .all(|line| line.contains(" pct=") && line.contains(" eta_s=")),
        "every progress line carries a percent and an ETA field (possibly `unknown`):\n{stream}"
    );

    // ...and the same run hands the agent something it can show a person.
    // Asserted on the REAL pipeline rather than on a hand-built snapshot.
    //
    // This corpus indexes in ~0.3 s, so it is also the end-to-end proof of the
    // burst floor: every one of its phase changes falls inside `BAR_MIN_GAP`,
    // and a run that short must therefore relay ONE display line, not one per
    // phase. The machine lines above already proved every phase is on the
    // stream — the relay is deliberately quieter than the record.
    let bars: Vec<&str> = stream
        .lines()
        .filter(|line| line.starts_with("xerj-bar "))
        .collect();
    assert_eq!(
        bars.len(),
        1,
        "a sub-2s run relays exactly one bar, whatever its phase count:\n{stream}"
    );
    assert!(
        bars[0].starts_with("xerj-bar [") && bars[0].contains(']'),
        "the display line carries a drawn bar:\n{stream}"
    );
    // The display line is derived, never a second source of truth: it may not
    // claim completion while the machine line still reports work outstanding.
    assert!(
        !bars.iter().any(|line| line.contains("[####")
            && line.contains("----]")
            && line.contains("100.0%")),
        "a partly-drawn bar cannot be labelled 100%:\n{stream}"
    );

    let done = stream
        .lines()
        .find(|line| line.starts_with("xerj-done "))
        .unwrap_or_else(|| panic!("a run must close its own stream:\n{stream}"));
    assert!(
        done.contains("ok=true") && done.contains(&format!("exit={code}")),
        "{done}"
    );
    assert!(done.contains("reason=completed"), "{done}");
    assert!(done.contains("files=8"), "{done}");
}

/// The other half of the contract: `--quiet` still means silence, so nothing
/// here can spam a caller that asked for none.
#[test]
fn quiet_runs_emit_no_progress_stream_at_all() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _sink_guard = crate::progress::SINK_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(corpus.path().join("rows.csv"), "id,value\n0,alpha\n").unwrap();

    let endpoint = MockEndpoint::start(usize::MAX);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert_eq!(config.progress, crate::progress::ProgressMode::None);

    let buffer = Arc::new(Mutex::new(Vec::new()));
    {
        let _sink = crate::progress::install_test_sink(&buffer);
        run_index_report(config).unwrap();
    }
    assert!(
        buffer.lock().unwrap().is_empty(),
        "--quiet asked for nothing: {}",
        String::from_utf8_lossy(&buffer.lock().unwrap())
    );
}

/// Where #240 (the resource policy) and #241 (the progress stream) meet.
///
/// Two rules have to hold at once, and each is easy to break while honouring
/// the other:
///
///  * The resource decision is **announced on the progress surface**, not on a
///    bare `eprintln!` gated on `!quiet`. A raw write would survive
///    `--progress none` — which promises silence — and would inject a
///    non-JSON line into the middle of `--progress json`, which promises one
///    parseable stream. (`quiet_runs_emit_no_progress_stream_at_all` above is
///    the other side of this assertion: it fails if any of these lines escape
///    the surface.)
///  * The numbers announced are the ones the run **got**, not the ones it
///    asked for. `pool::configure` is first-call-wins, because rayon pools
///    cannot be resized, so a process that already indexed once — `xerj
///    brain` does exactly that — keeps its original phase-A width. Reporting
///    the request there would make the stream and the run summary a record of
///    an intention rather than of a run.
///
/// The second rule is made observable by asking for a width this process
/// provably cannot grant: the pool is built before the run, then one more
/// thread than it has is requested.
#[test]
fn the_resource_plan_is_announced_on_the_progress_surface_with_the_width_it_got() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _sink_guard = crate::progress::SINK_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(
        corpus.path().join("rows.csv"),
        "id,value\n0,alpha\n1,beta\n",
    )
    .unwrap();

    // Build the process-global scan pool first, so the width below is one this
    // run cannot possibly be granted.
    let installed = crate::pool::width();
    let endpoint = MockEndpoint::start(usize::MAX);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    config.quiet = false;
    config.progress = crate::progress::ProgressMode::Plain;
    config.progress_interval = Some(std::time::Duration::from_secs(1));
    config.scan_workers = installed + 1;
    config.workers = 3;
    config.resource_notes = vec!["memory safe zone 256 MiB allows 3 index workers".to_string()];

    let buffer = Arc::new(Mutex::new(Vec::new()));
    let (_code, report) = {
        let _sink = crate::progress::install_test_sink(&buffer);
        run_index_report(config).unwrap()
    };
    let stream = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();

    assert!(
        stream.contains(&format!("{installed} scan threads")),
        "the run must announce the phase-A width it actually got, not {}: {stream}",
        installed + 1
    );
    assert!(
        !stream.contains(&format!("{} scan threads", installed + 1)),
        "a width the pool refused must never be reported as fact: {stream}"
    );
    assert!(
        stream.contains("3 index workers"),
        "phase B must name the count the policy chose: {stream}"
    );
    assert!(
        stream.contains("memory safe zone 256 MiB allows 3 index workers"),
        "what the machine forced on the run belongs in the same stream: {stream}"
    );
    assert!(
        stream.contains(&format!("with {installed} threads")),
        "the phase-A banner must carry the real width too: {stream}"
    );

    // The summary is read after the fact by agents and by `xerj brain`; it has
    // to agree with the stream rather than repeat the request.
    let report = report.expect("a completed run produces a summary");
    assert_eq!(report["scan_workers"], serde_json::json!(installed));
    assert_eq!(report["workers"], serde_json::json!(3));
}

#[cfg(unix)]
#[test]
fn fresh_pdf_is_parsed_once_and_failed_publication_retry_reparses_once() {
    use std::os::unix::fs::PermissionsExt;

    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    inject_pdf_spool_capacity(state_dir.path());
    let tools = tempfile::tempdir().unwrap();
    let pdf = corpus.path().join("quarterly-report.pdf");
    fs::write(
        &pdf,
        b"%PDF-1.4\nfake bytes consumed by the isolated test worker\n",
    )
    .unwrap();
    fs::copy(&pdf, corpus.path().join("quarterly-report-copy.pdf")).unwrap();

    let count = tools.path().join("worker-count");
    let worker = tools.path().join("pdf-worker");
    let worker_script = String::from_utf8(
        br#"#!/bin/sh
printf 'parse\n' >> "$XERJ_TEST_PDF_COUNT"
printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"title":"quarterly-report","page":1,"body":"Quarterly revenue increased while operating margin improved.","pdf_pages_total":1,"pdf_pages_with_text":1,"pdf_pages_omitted":0},"locator":"p1-s0","group":null,"origin":"extractor"}]}'
"#
        .to_vec(),
    )
    .unwrap()
    .replace("__XERJ_VERSION__", env!("CARGO_PKG_VERSION"));
    fs::write(&worker, worker_script).unwrap();
    fs::set_permissions(&worker, fs::Permissions::from_mode(0o700)).unwrap();

    let endpoint = MockEndpoint::start(1);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    let _env = PdfWorkerEnvGuard::acquire();
    std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);
    std::env::set_var("XERJ_TEST_PDF_COUNT", &count);

    let first = run_index(config.clone()).unwrap_err();
    assert!(format!("{first:#}").contains("bulk backend failed"));
    assert_eq!(
        fs::read_to_string(&count).unwrap().lines().count(),
        1,
        "Phase A's extraction must be replayed in Phase B, not parsed again"
    );
    assert_eq!(file_done_count(state_dir.path()), 0);

    // The process-local spool is intentionally not journal state. A retry has
    // a frozen plan, performs exactly one fresh extraction in Phase B, and
    // commits only after the backend accepts it.
    assert_eq!(run_index(config).unwrap(), 0);
    assert_eq!(fs::read_to_string(&count).unwrap().lines().count(), 2);
    assert_eq!(file_done_count(state_dir.path()), 1);
    assert_eq!(data_rows(&endpoint.state.lock().unwrap()).len(), 1);
}

#[cfg(unix)]
#[test]
fn refused_pdf_spool_reparses_and_reports_fallback_without_weakening_publication() {
    use std::os::unix::fs::PermissionsExt;

    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    let tools = tempfile::tempdir().unwrap();
    fs::write(
        corpus.path().join("quarterly-report.pdf"),
        b"%PDF-1.4\nfake bytes consumed by the isolated test worker\n",
    )
    .unwrap();
    fs::write(
        state_dir
            .path()
            .join(".autoindex-test-pdf-spool-available-bytes"),
        ((4_u64 << 30) + (32 << 20) - 1).to_string(),
    )
    .unwrap();
    fs::write(
        state_dir.path().join(".autoindex-test-pdf-spool-fd-limit"),
        "4096",
    )
    .unwrap();
    fs::write(
        state_dir.path().join(".autoindex-test-pdf-spool-fd-open"),
        "16",
    )
    .unwrap();

    let count = tools.path().join("worker-count");
    let worker = tools.path().join("pdf-worker");
    let worker_script = String::from_utf8(
        br#"#!/bin/sh
printf 'parse\n' >> "$XERJ_TEST_PDF_COUNT"
printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"title":"quarterly-report","page":1,"body":"Quarterly revenue increased while operating margin improved.","pdf_pages_total":1,"pdf_pages_with_text":1,"pdf_pages_omitted":0},"locator":"p1-s0","group":null,"origin":"extractor"}]}'
"#
        .to_vec(),
    )
    .unwrap()
    .replace("__XERJ_VERSION__", env!("CARGO_PKG_VERSION"));
    fs::write(&worker, worker_script).unwrap();
    fs::set_permissions(&worker, fs::Permissions::from_mode(0o700)).unwrap();

    let endpoint = MockEndpoint::start(0);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    let _env = PdfWorkerEnvGuard::acquire();
    std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);
    std::env::set_var("XERJ_TEST_PDF_COUNT", &count);

    let (code, report) = run_index_report(config).unwrap();
    assert_eq!(code, 0);
    assert_eq!(fs::read_to_string(&count).unwrap().lines().count(), 2);
    assert_eq!(file_done_count(state_dir.path()), 1);
    assert_eq!(data_rows(&endpoint.state.lock().unwrap()).len(), 1);
    let reuse = report.unwrap()["pdf_extraction_reuse"].clone();
    assert_eq!(reuse["reservations_started"], 0);
    assert_eq!(reuse["capacity_fallbacks"], 1);
    assert_eq!(reuse["phase_b_pdf_parses"], 1);
    assert_eq!(reuse["replay_verified"], 0);
    assert_eq!(reuse["artifacts_not_created"], 1);
    assert_eq!(reuse["phase_a_pdf_parser_responses"], 1);
    assert_eq!(reuse["capacity_status"], "disabled");
    assert_eq!(
        reuse["fallback_examples"][0]["path"],
        "quarterly-report.pdf"
    );
}

#[cfg(unix)]
#[test]
fn refused_spool_does_not_pay_a_second_phase_a_source_hash() {
    use std::os::unix::fs::PermissionsExt;

    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    let tools = tempfile::tempdir().unwrap();
    let pdf = corpus.path().join("quarterly-report.pdf");
    fs::write(&pdf, b"%PDF-1.4\nsame-size-source-generation\n").unwrap();
    let size = fs::metadata(&pdf).unwrap().len();
    let digest = content::resolve_reporting(
        vec![crate::walk::FileEntry {
            path: pdf.clone(),
            rel: "quarterly-report.pdf".into(),
            rel_id: "quarterly-report.pdf".into(),
            is_symlink: false,
            size,
        }],
        &|_| {},
    )
    .unwrap()
    .digests
    .remove(0);

    let worker = tools.path().join("pdf-worker");
    let worker_script = String::from_utf8(
        br#"#!/bin/sh
printf 'Z' | dd of="$2" bs=1 seek=10 conv=notrunc 2>/dev/null
printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"body":"Quarterly revenue increased while operating margin improved."},"locator":"p1-s0","group":null,"origin":"extractor"}]}'
"#
        .to_vec(),
    )
    .unwrap()
    .replace("__XERJ_VERSION__", env!("CARGO_PKG_VERSION"));
    fs::write(&worker, worker_script).unwrap();
    fs::set_permissions(&worker, fs::Permissions::from_mode(0o700)).unwrap();
    let _env = PdfWorkerEnvGuard::acquire();
    std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);

    let budget = crate::extract::pdf::ExtractionSpoolBudget::new(0, 0);
    let progress = Progress::silent();
    let scan = scan_file(
        &pdf,
        size,
        &digest,
        &PhaseAContext {
            state_dir: state_dir.path(),
            budget: &budget,
            capacity_warning: None,
            progress: &progress,
            meter: &crate::estimate::Meter::new(),
            tally: &crate::ScanTally::default(),
        },
        100,
        1 << 30,
        false,
    );
    assert!(scan.pdf_spool.is_none());
    assert_eq!(scan.pdf_spool_fallbacks.len(), 1);
    for fallback in &scan.pdf_spool_fallbacks {
        budget.record_fallback_example(
            "quarterly-report.pdf",
            fallback.category,
            &fallback.message,
        );
    }
    let report = budget.report();
    assert_eq!(report["artifacts_created"], 0);
    assert_eq!(report["phase_b_eligible_artifacts"], 0);
    assert_eq!(report["artifacts_discarded_before_replay"], 0);
    assert_eq!(report["fallback_categories"]["artifact_count_ceiling"], 1);
    assert!(report["fallback_categories"]
        .get("source_generation_changed")
        .is_none());
}

/// The other half of the branch above: with capacity available the artifact
/// *is* created, and phase A must then throw it away because the source moved
/// underneath the parser. Without this the source-generation arm of
/// `scan_file` has no test at all — its sibling above deliberately runs with a
/// zero budget, so it never reaches the `content::verify` comparison.
#[cfg(unix)]
#[test]
fn source_changed_during_phase_a_discards_the_artifact_and_names_the_reason() {
    use std::os::unix::fs::PermissionsExt;

    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    inject_pdf_spool_capacity(state_dir.path());
    let tools = tempfile::tempdir().unwrap();
    let pdf = corpus.path().join("quarterly-report.pdf");
    fs::write(&pdf, b"%PDF-1.4\nsame-size-source-generation\n").unwrap();
    let size = fs::metadata(&pdf).unwrap().len();
    let digest = content::resolve_reporting(
        vec![crate::walk::FileEntry {
            path: pdf.clone(),
            rel: "quarterly-report.pdf".into(),
            rel_id: "quarterly-report.pdf".into(),
            is_symlink: false,
            size,
        }],
        &|_| {},
    )
    .unwrap()
    .digests
    .remove(0);

    // Same trick as the sibling test: the worker rewrites one byte of its own
    // input, so the file keeps its length and changes its digest.
    let worker = tools.path().join("pdf-worker");
    let worker_script = String::from_utf8(
        br#"#!/bin/sh
printf 'Z' | dd of="$2" bs=1 seek=10 conv=notrunc 2>/dev/null
printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"body":"Quarterly revenue increased while operating margin improved."},"locator":"p1-s0","group":null,"origin":"extractor"}]}'
"#
        .to_vec(),
    )
    .unwrap()
    .replace("__XERJ_VERSION__", env!("CARGO_PKG_VERSION"));
    fs::write(&worker, worker_script).unwrap();
    fs::set_permissions(&worker, fs::Permissions::from_mode(0o700)).unwrap();
    let _env = PdfWorkerEnvGuard::acquire();
    std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);

    let (budget, _) =
        crate::extract::pdf::ExtractionSpoolBudget::for_state_dir(state_dir.path(), 1, 1, 8);
    let progress = Progress::silent();
    let scan = scan_file(
        &pdf,
        size,
        &digest,
        &PhaseAContext {
            state_dir: state_dir.path(),
            budget: &budget,
            capacity_warning: None,
            progress: &progress,
            meter: &crate::estimate::Meter::new(),
            tally: &crate::ScanTally::default(),
        },
        100,
        1 << 30,
        false,
    );

    assert!(
        scan.pdf_spool.is_none(),
        "an artifact bound to a superseded source generation must not reach phase B"
    );
    let categories: Vec<&str> = scan
        .pdf_spool_fallbacks
        .iter()
        .map(|fallback| fallback.category)
        .collect();
    assert_eq!(categories, vec!["source_generation_changed"]);
    let report = budget.report();
    assert_eq!(report["artifacts_created"], 1);
    assert_eq!(report["artifacts_discarded_before_replay"], 1);
    assert_eq!(report["phase_b_eligible_artifacts"], 0);
    assert_eq!(report["current_live_artifacts"], 0);
    assert_eq!(report["current_retained_or_reserved_bytes"], 0);
    assert_eq!(
        report["fallback_categories"]["source_generation_changed"],
        1
    );
}

#[cfg(unix)]
#[test]
fn verified_but_junk_pdf_spool_is_created_then_discarded_not_eligible() {
    use std::os::unix::fs::PermissionsExt;

    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    inject_pdf_spool_capacity(state_dir.path());
    let tools = tempfile::tempdir().unwrap();
    let pdf = corpus.path().join("empty-report.pdf");
    fs::write(&pdf, b"%PDF-1.4\nempty test input\n").unwrap();
    let size = fs::metadata(&pdf).unwrap().len();
    let digest = content::resolve_reporting(
        vec![crate::walk::FileEntry {
            path: pdf.clone(),
            rel: "empty-report.pdf".into(),
            rel_id: "empty-report.pdf".into(),
            is_symlink: false,
            size,
        }],
        &|_| {},
    )
    .unwrap()
    .digests
    .remove(0);
    let worker = tools.path().join("pdf-worker");
    let script = format!(
        "#!/bin/sh\nprintf '%s' '{{\"schema\":1,\"extractor\":\"xerj-autoindex/{}\",\"parser\":\"pdf_oxide/0.3.75\",\"containment\":\"test worker\",\"records\":[]}}'\n",
        env!("CARGO_PKG_VERSION")
    );
    fs::write(&worker, script).unwrap();
    fs::set_permissions(&worker, fs::Permissions::from_mode(0o700)).unwrap();
    let _env = PdfWorkerEnvGuard::acquire();
    std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);

    let (budget, _) =
        crate::extract::pdf::ExtractionSpoolBudget::for_state_dir(state_dir.path(), 1, 1, 8);
    let progress = Progress::silent();
    let mut scan = scan_file(
        &pdf,
        size,
        &digest,
        &PhaseAContext {
            state_dir: state_dir.path(),
            budget: &budget,
            capacity_warning: None,
            progress: &progress,
            meter: &crate::estimate::Meter::new(),
            tally: &crate::ScanTally::default(),
        },
        100,
        1 << 30,
        false,
    );
    assert!(scan.junk.is_some());
    assert!(scan.pdf_spool.is_some());
    assert!(take_pdf_spool_if_indexable(&mut scan.pdf_spool, true, &budget).is_none());
    let report = budget.report();
    assert_eq!(report["artifacts_created"], 1);
    assert_eq!(report["artifacts_discarded_before_replay"], 1);
    assert_eq!(report["phase_b_eligible_artifacts"], 0);
}

#[cfg(unix)]
#[test]
fn multi_pdf_run_reuses_every_artifact_and_reports_exact_success_counters() {
    use std::os::unix::fs::PermissionsExt;

    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    inject_pdf_spool_capacity(state_dir.path());
    let tools = tempfile::tempdir().unwrap();
    const PDFS: usize = 6;
    for index in 0..PDFS {
        fs::write(
            corpus.path().join(format!("quarterly-report-{index}.pdf")),
            format!("%PDF-1.4\nunique isolated worker input {index}\n"),
        )
        .unwrap();
    }

    let count = tools.path().join("worker-count");
    let worker = tools.path().join("pdf-worker");
    let worker_script = String::from_utf8(
        br#"#!/bin/sh
printf 'parse\n' >> "$XERJ_TEST_PDF_COUNT"
printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"title":"quarterly-report","page":1,"body":"Quarterly revenue increased while operating margin improved.","pdf_pages_total":1,"pdf_pages_with_text":1,"pdf_pages_omitted":0},"locator":"p1-s0","group":null,"origin":"extractor"}]}'
"#
        .to_vec(),
    )
    .unwrap()
    .replace("__XERJ_VERSION__", env!("CARGO_PKG_VERSION"));
    fs::write(&worker, worker_script).unwrap();
    fs::set_permissions(&worker, fs::Permissions::from_mode(0o700)).unwrap();

    let endpoint = MockEndpoint::start(0);
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    config.workers = 8;
    config.pdf_workers = 2;
    let _env = PdfWorkerEnvGuard::acquire();
    std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);
    std::env::set_var("XERJ_TEST_PDF_COUNT", &count);
    let (code, report) = run_index_report(config).unwrap();
    assert_eq!(code, 0);
    assert_eq!(
        fs::read_to_string(&count).unwrap().lines().count(),
        PDFS,
        "each unique PDF must be parsed once in Phase A and replayed in Phase B"
    );
    assert_eq!(data_rows(&endpoint.state.lock().unwrap()).len(), PDFS);
    let reuse = report.unwrap()["pdf_extraction_reuse"].clone();
    assert_eq!(reuse["reservations_started"], PDFS);
    assert_eq!(
        reuse["cumulative_reserved_bytes"],
        PDFS as u64 * (32_u64 << 20)
    );
    assert_eq!(reuse["artifacts_created"], PDFS);
    assert_eq!(reuse["artifacts_not_created"], 0);
    assert_eq!(reuse["phase_b_eligible_artifacts"], PDFS);
    assert_eq!(reuse["artifacts_discarded_before_replay"], 0);
    assert!(reuse["exact_artifact_bytes"].as_u64().unwrap() > 0);
    assert_eq!(reuse["current_retained_or_reserved_bytes"], 0);
    assert!(reuse["peak_retained_or_reserved_bytes"].as_u64().unwrap() > 0);
    assert_eq!(reuse["current_live_artifacts"], 0);
    assert!(reuse["peak_live_artifacts"].as_u64().unwrap() > 0);
    assert_eq!(reuse["phase_a_pdf_parser_responses"], PDFS);
    assert_eq!(reuse["capacity_fallbacks"], 0);
    assert_eq!(reuse["io_fallbacks"], 0);
    assert_eq!(reuse["replay_verified"], PDFS);
    assert_eq!(reuse["replay_integrity_failures"], 0);
    assert_eq!(reuse["phase_b_pdf_parses"], 0);
    assert_eq!(reuse["fallback_examples"].as_array().unwrap().len(), 0);
    assert_eq!(reuse["fallback_examples_truncated"], false);
    assert_eq!(reuse["fallback_categories"].as_object().unwrap().len(), 0);
}

#[cfg(unix)]
#[test]
fn corrupted_pdf_replay_reparses_without_blaming_the_source_or_backend() {
    use std::os::unix::fs::PermissionsExt;

    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    inject_pdf_spool_capacity(state_dir.path());
    let tools = tempfile::tempdir().unwrap();
    let pdf = corpus.path().join("report.pdf");
    fs::write(&pdf, b"%PDF-1.4\ntest worker input\n").unwrap();
    let worker = tools.path().join("pdf-worker");
    let count = tools.path().join("worker-count");
    let worker_script = String::from_utf8(
        br#"#!/bin/sh
printf 'parse\n' >> "$XERJ_TEST_PDF_COUNT"
printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":"pdf_oxide/0.3.75","containment":"test worker","records":[{"fields":{"body":"Quarterly revenue increased while operating margin improved."},"locator":"p1-s0","group":null,"origin":"extractor"}]}'
"#
        .to_vec(),
    )
    .unwrap()
    .replace("__XERJ_VERSION__", env!("CARGO_PKG_VERSION"));
    fs::write(&worker, worker_script).unwrap();
    fs::set_permissions(&worker, fs::Permissions::from_mode(0o700)).unwrap();

    let endpoint = MockEndpoint::start(0);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    let _env = PdfWorkerEnvGuard::acquire();
    std::env::set_var("XERJ_PDF_WORKER_BIN", &worker);
    std::env::set_var("XERJ_TEST_PDF_COUNT", &count);
    crate::extract::pdf::corrupt_replay_for_source_size(fs::metadata(&pdf).unwrap().len());

    let (code, report) = run_index_report(config).unwrap();
    assert_eq!(code, 0);
    assert_eq!(fs::read_to_string(&count).unwrap().lines().count(), 2);
    assert_eq!(data_rows(&endpoint.state.lock().unwrap()).len(), 1);
    assert_eq!(file_done_count(state_dir.path()), 1);
    assert!(crate::extract::pdf::corrupted_replay_reservation_was_dropped());
    let reuse = report.unwrap()["pdf_extraction_reuse"].clone();
    assert_eq!(reuse["replay_verified"], 0);
    assert_eq!(reuse["replay_integrity_failures"], 1);
    assert_eq!(
        reuse["io_fallbacks"], 0,
        "a corrupted artifact is an integrity failure, not an I/O failure"
    );
    assert_eq!(reuse["phase_b_pdf_parses"], 1);
    assert_eq!(reuse["current_live_artifacts"], 0);
    assert_eq!(reuse["current_retained_or_reserved_bytes"], 0);
    assert_eq!(reuse["fallback_categories"]["replay_verification"], 1);
    assert_eq!(
        reuse["fallback_examples"][0]["category"],
        "replay_verification"
    );
}

#[test]
fn junk_scan_drops_its_spool_before_indexable_spools_are_retained() {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    struct DropProbe(Arc<AtomicUsize>);
    impl Drop for DropProbe {
        fn drop(&mut self) {
            self.0.fetch_add(1, Ordering::SeqCst);
        }
    }

    let drops = Arc::new(AtomicUsize::new(0));
    let budget = crate::extract::pdf::ExtractionSpoolBudget::new(1, 1);
    let mut junk = Some(DropProbe(Arc::clone(&drops)));
    assert!(take_pdf_spool_if_indexable(&mut junk, true, &budget).is_none());
    assert!(junk.is_none());
    assert_eq!(drops.load(Ordering::SeqCst), 1);

    let mut indexable = Some(DropProbe(Arc::clone(&drops)));
    let retained = take_pdf_spool_if_indexable(&mut indexable, false, &budget);
    assert!(retained.is_some());
    assert_eq!(drops.load(Ordering::SeqCst), 1);
    let report = budget.report();
    assert_eq!(report["artifacts_discarded_before_replay"], 1);
    assert_eq!(
        report["phase_b_eligible_artifacts"], 0,
        "eligibility is recorded only after the final todo set is known"
    );
    drop(retained);
    assert_eq!(drops.load(Ordering::SeqCst), 2);
}

/// A Unity scene whose SECOND `unity_class` starts past `after_bytes`, so a
/// phase A capped at that many bytes never samples it and phase B has nowhere
/// to route its records.
fn scene_with_a_late_class(after_bytes: usize) -> String {
    let mut s = String::from("%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n");
    let mut id = 1;
    while s.len() < after_bytes {
        s.push_str(&format!(
            "--- !u!1 &{id}\nGameObject:\n  m_Name: Pad{id:05}\n  \
             m_TagString: Untagged\n  m_IsActive: 1\n"
        ));
        id += 1;
    }
    s.push_str(
        "--- !u!114 &900001\nMonoBehaviour:\n  m_Name: LateBehaviour\n  \
         m_Enabled: 1\n  speed: 4\n",
    );
    s
}

/// Blocker: phase B meeting a group phase A never sampled pushed a `JunkFile`
/// for the whole file while leaving `send_err` unset — so the file ALSO
/// reached `journal.file_done`, and both passes wrote `catalog::file_doc`
/// under the same `file:{file_key}` id into the same bulk. The junk document
/// landed second and won: a file that indexed real records was reported in the
/// catalog as status "junk" with records 0, and `files_junk` counted it.
///
/// Reachable with no Unity involved (a >64 MiB SQL dump whose first row for
/// some table starts past `SQLDUMP_SAMPLE_LIMIT`); Unity is used here only
/// because the override lets the fixture be 3 KB instead of 64 MB.
#[test]
fn an_unsampled_group_does_not_overwrite_the_files_indexed_catalog_row() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    // Scoped to this corpus, so running the suite multi-threaded cannot let
    // the cap reach an unrelated test's fixtures.
    let _limit = crate::SampleLimitOverride::set(corpus.path(), 2048);
    fs::create_dir_all(corpus.path().join("Assets/Scenes")).unwrap();
    fs::write(
        corpus.path().join("Assets/Scenes/Main.unity"),
        scene_with_a_late_class(2048),
    )
    .unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    // 3 = completed with junk: records WERE dropped, and that must still be
    // reported. What must not happen is the whole file being called junk.
    let (code, report) = run_index_report(config).unwrap();
    let report = report.unwrap();
    assert_eq!(code, 3, "{report}");

    let locked = endpoint.state.lock().unwrap();
    let files: Vec<&Value> = locked
        .catalog_docs
        .values()
        .filter(|doc| doc.get("doc_kind").and_then(Value::as_str) == Some("file"))
        .collect();
    assert_eq!(
        files.len(),
        1,
        "one source file, one catalog row: {files:?}"
    );
    let file = files[0];
    assert_eq!(file["path"], "Assets/Scenes/Main.unity", "{file}");
    // The preconditions. Without these the test would pass on a fixture where
    // nothing was ever dropped, which is the failure mode it exists to catch.
    assert!(
        file["junk"].as_u64().unwrap_or(0) > 0,
        "precondition: the unsampled group's records must actually have been \
         dropped, or this fixture proves nothing: {file}"
    );
    assert!(
        file["records"].as_u64().unwrap_or(0) > 0,
        "precondition: the sampled group's records must actually have been \
         indexed: {file}"
    );
    assert_eq!(
        file["status"], "indexed",
        "a file that indexed records is not junk: {file}"
    );
    assert_eq!(
        report["files_junk"], 0,
        "the file completed; only some of its records were dropped: {report}"
    );
    assert!(
        locked.unexpected_catalog_actions.is_empty(),
        "{:?}",
        locked.unexpected_catalog_actions
    );
}

#[test]
fn a_junk_entry_for_a_completed_file_is_never_turned_into_a_catalog_row() {
    let entries = [
        state::JunkFile {
            file_key: "k-completed".into(),
            rel: "a.unity".into(),
            format: "unity".into(),
            status: "junk".into(),
            reason: "some group was never sampled".into(),
            bytes: 10,
        },
        state::JunkFile {
            file_key: "k-junked".into(),
            rel: "b.bin".into(),
            format: "binary".into(),
            status: "junk".into(),
            reason: "binary content".into(),
            bytes: 20,
        },
    ];
    let borrowed: Vec<&state::JunkFile> = entries.iter().collect();
    let completed: std::collections::HashSet<String> =
        ["k-completed".to_string()].into_iter().collect();
    let shadowed = crate::shadowed_junk_entries(&borrowed, &completed);
    assert_eq!(
        shadowed
            .iter()
            .map(|jf| jf.rel.as_str())
            .collect::<Vec<_>>(),
        vec!["a.unity"],
        "an entry naming a completed file collides with that file's own \
         catalog id and must be reported"
    );
    assert!(
        crate::shadowed_junk_entries(&borrowed, &std::collections::HashSet::new()).is_empty(),
        "with no completions nothing is shadowed"
    );
}

/// #929 on the legacy (graph-enabled) path. Here the dataset's whole mapping
/// rides on the create-index PUT, and the loop that sends it used to `?` out on
/// the first refusal exactly like the generated path did. Same contract: the
/// refused dataset costs its own files, the rest of the folder is indexed, the
/// run ends 3 and the terminal line and run document say what is missing — and
/// a re-run does not quietly "fix" it by pretending the files never existed.
#[test]
fn a_refused_dataset_on_the_graph_path_costs_that_dataset_not_the_run() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _sink_guard = crate::progress::SINK_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let write_corpus = |root: &Path| {
        fs::write(root.join("rows.csv"), "id,value\n1,first\n2,second\n").unwrap();
        fs::write(
            root.join("notes.md"),
            "# Notes\n\nTiered merge policy picks segments of similar size.\n",
        )
        .unwrap();
    };

    // Learn the tabular dataset's index from a clean run rather than
    // hard-coding the slug scheme.
    let tabular = {
        let corpus = tempfile::tempdir().unwrap();
        let state_dir = tempfile::tempdir().unwrap();
        write_corpus(corpus.path());
        let endpoint = MockEndpoint::start(usize::MAX);
        let config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
        let prefix = config.prefix.clone();
        assert_eq!(run_index(config).unwrap(), 0);
        let locked = endpoint.state.lock().unwrap();
        let slug = data_rows(&locked)
            .into_iter()
            .find(|doc| doc["ax_path"] == "rows.csv")
            .and_then(|doc| doc["ax_dataset"].as_str())
            .expect("rows.csv is indexed by the clean run")
            .to_owned();
        format!("{prefix}-{slug}")
    };

    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    write_corpus(corpus.path());
    let endpoint = MockEndpoint::start(usize::MAX);
    endpoint.state.lock().unwrap().refused_dataset_indices = vec![tabular.clone()];
    let mut config = cfg(corpus.path(), state_dir.path(), &endpoint.url);
    assert!(!config.no_graph, "this module covers the legacy path");
    config.quiet = false;
    config.progress = crate::progress::ProgressMode::Plain;

    let buffer = Arc::new(Mutex::new(Vec::new()));
    let (code, report) = {
        let _sink = crate::progress::install_test_sink(&buffer);
        run_index_report(config.clone())
            .unwrap_or_else(|error| panic!("the refusal aborted the run: {error:#}"))
    };
    assert_eq!(code, 3, "a refused dataset is exit 3, never 0 and never 1");
    let stream = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
    assert!(
        stream.contains("REFUSED by the server") && stream.contains(&tabular),
        "the refusal names the dataset on the progress surface:\n{stream}"
    );
    let done = stream
        .lines()
        .find(|line| line.starts_with("xerj-done "))
        .unwrap_or_else(|| panic!("{stream}"));
    assert!(
        done.contains("ok=true")
            && done.contains("exit=3")
            && done.contains("datasets_refused=1")
            && done.contains("files_refused=1"),
        "{done}"
    );
    {
        let locked = endpoint.state.lock().unwrap();
        let mut indexed: Vec<&str> = data_rows(&locked)
            .into_iter()
            .filter_map(|doc| doc["ax_path"].as_str())
            .collect();
        indexed.sort_unstable();
        indexed.dedup();
        assert_eq!(indexed, ["notes.md"], "the other dataset is indexed whole");
        let run = locked
            .catalog_docs
            .values()
            .find(|doc| doc["doc_kind"] == "run")
            .expect("the run document is published");
        assert_eq!(run["datasets_refused"], 1, "{run}");
        assert_eq!(run["files_refused"], 1, "{run}");
        let detail: Vec<Value> =
            serde_json::from_str(run["refused_datasets_json"].as_str().unwrap()).unwrap();
        assert_eq!(detail[0]["index"], tabular.as_str());
        assert!(detail[0]["reason"].as_str().unwrap().contains("400"));
        let junked = locked
            .catalog_docs
            .values()
            .find(|doc| doc["doc_kind"] == "file" && doc["path"] == "rows.csv")
            .expect("the refused file has a catalog document");
        assert_eq!(junked["status"], "junk", "{junked}");
        assert!(
            junked["reason"]
                .as_str()
                .is_some_and(|reason| reason.contains("was refused by the server")),
            "{junked}"
        );
    }
    let report = report.unwrap();
    assert_eq!(report["datasets_refused"], 1, "{report}");

    // A re-run resumes the durable plan: still exit 3, still names the refusal,
    // and does not misreport the refused file as one that "appeared after the
    // plan was frozen".
    let buffer = Arc::new(Mutex::new(Vec::new()));
    let (again, _) = {
        let _sink = crate::progress::install_test_sink(&buffer);
        run_index_report(config).unwrap()
    };
    assert_eq!(again, 3);
    let stream = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
    assert!(
        !stream.contains("appeared after the resume plan"),
        "{stream}"
    );
    let done = stream
        .lines()
        .find(|line| line.starts_with("xerj-done "))
        .unwrap();
    assert!(done.contains("datasets_refused=1"), "{done}");
}

/// #2807: a record the server refuses as over its per-document size limit is
/// refused again on every rerun, so its file is set aside as junk and the run
/// completes (exit 3) instead of aborting. The file's accepted records are
/// removed, it is not journaled, and it indexes once the refusal goes away.
#[test]
fn a_record_refused_as_too_large_sets_its_file_aside() {
    let _guard = FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let _io_guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
        .lock()
        .unwrap_or_else(|p| p.into_inner());
    let corpus = tempfile::tempdir().unwrap();
    let state_dir = tempfile::tempdir().unwrap();
    fs::write(
        corpus.path().join("records.csv"),
        "id,value\n0,kept\n1,kept\n2,kept\n",
    )
    .unwrap();
    let endpoint = MockEndpoint::start(usize::MAX);
    endpoint
        .state
        .lock()
        .unwrap()
        .reject_first_data_item_as_too_large = true;

    for round in 0..2 {
        let (code, _) = run_index_report(cfg(corpus.path(), state_dir.path(), &endpoint.url))
            .unwrap_or_else(|error| panic!("round {round} must not abort: {error:#}"));
        assert_eq!(code, 3, "round {round}: completed with junk");
        let state = endpoint.state.lock().unwrap();
        let catalog = serde_json::to_string(&state.catalog_docs).unwrap();
        assert!(
            catalog.contains("set aside at index time") && catalog.contains("records.csv"),
            "round {round}: the file is listed as junk with the reason: {catalog}"
        );
        assert!(
            !serde_json::to_string(&state.docs)
                .unwrap()
                .contains("\"kept\""),
            "round {round}: the file's accepted records are removed"
        );
        drop(state);
        assert_eq!(file_done_count(state_dir.path()), 0, "round {round}");
    }

    endpoint
        .state
        .lock()
        .unwrap()
        .reject_first_data_item_as_too_large = false;
    let (code, _) = run_index_report(cfg(corpus.path(), state_dir.path(), &endpoint.url)).unwrap();
    assert_eq!(code, 0);
    assert_eq!(file_done_count(state_dir.path()), 1);
}