Skip to content

armgit / xerj

Public Imported from GitHub
0

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

fix(autoindex): a byte-identical duplicate must not wedge a completed run (#345)

xerj-org5599f7f3ca1d
diff --git a/AGENTS.md b/AGENTS.md
index 2c26b10d9..f7003619f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -103,7 +103,10 @@ be driven by you on their behalf, so the loop is fixed:
Exit codes: `0` complete · `3` completed-with-junk — **this is success** · `2`
usage · `1` any error at all (read the `error:` line before acting) · `4`
-needs a decision (gate above; answer with `--approve`, never a retry). Percent,
+needs a decision (gate above; answer with `--approve`, never a retry). Exit `3`
+also carries `reason=catalog-alias-sweep-failed`: the corpus **is** indexed and
+the journal committed, and only the catalog's duplicate-alias cleanup could not
+run — read `reason`, not the bare code, to tell the two apart. Percent,
ETA and the drawn bar are honest or absent: `unknown` / `[????…]` when there is
no denominator, and a full bar only at a real 100%. The short version is under
"Running an index on someone's machine" in
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6b333a04a..5ff092b21 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2052,6 +2052,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
right: they deleted CJK, Cyrillic, Greek, Hebrew and Arabic documents
worldwide. Tracked as **#381**.
+- **`autoindex` aborted permanently on a corpus containing a byte-identical
+ duplicate** (#345). A duplicate path is the only thing that makes a run issue
+ the catalog's duplicate-alias `_delete_by_query` at all, and that call was
+ fatal. Because it runs *after* every document is durably indexed and after the
+ per-file journal has committed, a 5xx there turned a fully successful run into
+ `xerj-done ok=false exit=1 reason=aborted` — and it stayed that way: the
+ journal was complete, so every rerun indexed zero files and aborted on the
+ same line. The sweep is metadata-only bookkeeping and is now reported instead
+ of fatal: the run finishes `ok=true exit=3
+ reason=catalog-alias-sweep-failed`, names the paths whose alias document was
+ not swept, and records `catalog_alias_sweep_failed_paths` /
+ `catalog_alias_sweep_error` on the run document. Exit `3` already means
+ "completed, and something is recorded rather than fatal", so no new exit code
+ was introduced — read `reason` to tell it apart from `completed-with-junk`.
+ The catalog *bulk* that follows the sweep is still fatal, so a catalog index
+ that cannot be written still fails the run.
+
+- **Any 429/5xx from the server was reported as a bare status line.** The retry
+ wrapper kept `HTTP 500 Internal Server Error` and discarded the response body,
+ which is the same sentence for a poisoned index, a full disk and a panicking
+ handler — the reason #345 was filed as "not investigated". A bounded prefix of
+ the server's own `error.type: error.reason` (or the raw body, for a proxy's
+ error page) now travels with the status on every `with_retry` call site.
+
+- **The duplicate-alias sweep issued one HTTP request per duplicate path.** It
+ now names up to 1024 paths per request with a `terms` filter, so a corpus with
+ K duplicates costs `ceil(K/1024)` round trips instead of K — and has
+ proportionally less surface on which to fail.
+
## [1.0.0-rc.16] - 2026-08-13
Both rc.15 known issues (the progress-stream forgery and the outer-`.gitignore`
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rs
index 6c3e92a5f..9f09ddb43 100644
--- a/engine/crates/xerj-autoindex/src/cli.rs
+++ b/engine/crates/xerj-autoindex/src/cli.rs
@@ -368,7 +368,12 @@ pub fn help_text_with(feedback: bool) -> String {
autoindex-catalog and old target only after validation.\n\
\n\
EXIT CODES: 0 complete (also: gate answered with --approve cancel);\n\
- 3 completed-with-junk (junk recorded, never fatal);\n\
+ 3 completed-with-junk (junk recorded, never fatal), or\n\
+ catalog-alias-sweep-failed — the corpus IS indexed and the\n\
+ journal committed; only the catalog's duplicate-alias cleanup\n\
+ could not run. Read `reason` on the xerj-done line to tell the\n\
+ two apart, and rerun the same command once the reported server\n\
+ condition clears;\n\
4 NEEDS A DECISION — the estimate exceeded --max-minutes and\n\
nothing was indexed; a JSON decision request is on stdout;\n\
2 usage; 1 endpoint/journal failure, a refused corpus removal, or a\n\
diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rs
index e93360149..8b87b459c 100644
--- a/engine/crates/xerj-autoindex/src/esclient.rs
+++ b/engine/crates/xerj-autoindex/src/esclient.rs
@@ -273,6 +273,46 @@ fn is_index_block_error(error: &Value) -> bool {
type_is_block || reason_is_block
}
+/// How much of a 429/5xx body [`server_reason`] keeps. A 5xx body can be a
+/// whole stack trace; the sentence that names the condition is at the front.
+const SERVER_REASON_MAX: usize = 512;
+
+/// The server's own explanation for a 429/5xx, bounded to a prefix.
+///
+/// [`Es::with_retry`] used to report only `HTTP 500 Internal Server Error` and
+/// drop the body, which is the same sentence for a poisoned index, a full disk
+/// and a panicking handler. That is why #345 was filed as "not investigated":
+/// the reporter had a status line and nothing to act on, while the response
+/// they discarded carried the reason — every by-query refusal answers
+/// `{"error": {"type", "reason"}, "status"}` (`es_compat::by_query_response`),
+/// and `_bulk` already surfaces the per-item half of the same thing
+/// ([`BulkOutcome::first_server_error`]).
+///
+/// `error.type: error.reason` is preferred because that is the shape both XERJ
+/// and Elasticsearch answer with; the raw body is the fallback for anything
+/// else (an HTML proxy error page, a bare string), because a reverse proxy in
+/// front of the server is exactly the case where the status alone is useless.
+fn server_reason(resp: reqwest::blocking::Response) -> Option<String> {
+ let body = resp.text().ok()?;
+ let reason = serde_json::from_str::<Value>(&body)
+ .ok()
+ .and_then(|value| {
+ let error = value.get("error")?;
+ let kind = error.get("type").and_then(Value::as_str);
+ let why = error.get("reason").and_then(Value::as_str);
+ match (kind, why) {
+ (Some(kind), Some(why)) => Some(format!("{kind}: {why}")),
+ (Some(only), None) | (None, Some(only)) => Some(only.to_owned()),
+ (None, None) => None,
+ }
+ })
+ .unwrap_or(body);
+ // `chars`, not bytes: the body can be any encoding the server chose, and
+ // slicing one mid-codepoint would panic on the error path (#326).
+ let reason: String = reason.trim().chars().take(SERVER_REASON_MAX).collect();
+ (!reason.is_empty()).then_some(reason)
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EmbeddingExecutionIdentity {
pub version: u32,
@@ -527,7 +567,10 @@ impl Es {
if status.as_u16() == 429 {
self.admission.on_congestion();
}
- last_err = Some(anyhow!("{what}: HTTP {status}"));
+ last_err = Some(match server_reason(resp) {
+ Some(reason) => anyhow!("{what}: HTTP {status}: {reason}"),
+ None => anyhow!("{what}: HTTP {status}"),
+ });
} else {
return parse(resp);
}
@@ -1279,6 +1322,51 @@ mod tests {
}
}
+ /// #345: the reporter's whole issue was `delete_by_query: HTTP 500
+ /// Internal Server Error` and nothing else, so it was filed "not
+ /// investigated". The server had already said why — every by-query refusal
+ /// answers `{"error": {"type", "reason"}, "status"}` — and the client threw
+ /// the body away after the last retry. Cover both shapes the wire really
+ /// produces: the structured refusal, and a proxy's HTML page.
+ #[test]
+ fn an_exhausted_5xx_retry_reports_the_server_reason_not_only_the_status() {
+ for (body, expect) in [
+ (
+ br#"{"error":{"type":"internal_server_error_exception","reason":"collection publication was interrupted"},"status":500}"#.as_slice(),
+ "internal_server_error_exception: collection publication was interrupted",
+ ),
+ (
+ b"<html><body>502 upstream connect error</body></html>".as_slice(),
+ "<html><body>502 upstream connect error</body></html>",
+ ),
+ ] {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = std::thread::spawn(move || {
+ for _ in 0..6 {
+ let (mut stream, _) = listener.accept().unwrap();
+ read_request(&mut stream);
+ respond_status(&mut stream, "500 Internal Server Error", body);
+ }
+ });
+ let es = Es::with_bulk_policy(
+ &format!("http://{address}"),
+ None,
+ Duration::from_millis(100),
+ Duration::from_millis(1),
+ Duration::from_millis(2),
+ )
+ .unwrap();
+ let error = es
+ .delete_by_query("data", &serde_json::json!({"term": {"ax_file": "key"}}))
+ .unwrap_err();
+ let rendered = format!("{error:#}");
+ assert!(rendered.contains("HTTP 500 Internal Server Error"), "{rendered}");
+ assert!(rendered.contains(expect), "{rendered}");
+ server.join().unwrap();
+ }
+ }
+
#[test]
fn delete_by_query_that_never_reaches_zero_fails_at_the_pass_cap() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
index 57651de18..cddb5d447 100644
--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
@@ -101,6 +101,15 @@ struct MockState {
/// Accept every data bulk (`errors: false`) but persist nothing — the
/// shape of any rejection path the client-side classifier misses.
swallow_data_bulks: bool,
+ /// 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.
+ 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
@@ -294,6 +303,33 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {
.pointer("/query/term/file_key")
.and_then(Value::as_str)
.map(str::to_owned);
+ // 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.
+ 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()
+ });
let mut locked = state.lock().unwrap();
locked.delete_calls += 1;
if let Some(key) = ax_file {
@@ -306,7 +342,39 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {
.catalog_docs
.retain(|_, doc| doc.get("file_key").and_then(Value::as_str) != Some(key.as_str()));
}
- (200, json!({"deleted": 0, "failures": []}))
+ // 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.
+ if let Some(swept) = &alias_sweep {
+ locked.alias_sweep_batches.push(swept.clone());
+ }
+ match alias_sweep {
+ Some(_) 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
+ }),
+ ),
+ Some(swept) => {
+ locked.catalog_docs.retain(|_, 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))
+ });
+ (200, json!({"deleted": 0, "failures": []}))
+ }
+ None => (200, json!({"deleted": 0, "failures": []})),
+ }
} else if method == "GET" && path.ends_with("/_count") {
(200, json!({"count": state.lock().unwrap().docs.len()}))
} else if method == "POST" && path.ends_with("/_search") {
@@ -346,7 +414,11 @@ fn handle(mut stream: TcpStream, state: &Arc<Mutex<MockState>>) {
(200, json!({"acknowledged": true}))
};
let bytes = response.to_string();
- let reason = if status == 200 { "OK" } else { "Bad Request" };
+ 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{}",
@@ -1011,6 +1083,111 @@ fn fresh_cannot_erase_the_plan_and_bypass_the_removal_gate() {
assert_unsupported_delta_without_remote_mutation(&endpoint, config, &["new.csv"], &["old.csv"]);
}
+/// #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
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 2c80ee1c3..2ca9b471b 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -348,6 +348,104 @@ impl CodeCoverage {
}
}
+/// How many duplicate paths one catalog-alias sweep request may name.
+///
+/// The sweep used to issue one `_delete_by_query` per path. Lucene's
+/// `IndexWriter.deleteDocuments(Query...)`
+/// (`lucene/core/src/java/org/apache/lucene/index/IndexWriter.java:1883`) takes
+/// N queries and applies them in one packet — "All given deletes are applied
+/// and flushed atomically at the same time" — and its buffered query deletes
+/// are drained inside the writer (`FrozenBufferedUpdates.applyQueryDeletes`,
+/// `lucene/core/src/java/org/apache/lucene/index/FrozenBufferedUpdates.java:357`),
+/// never as a separate client-visible operation that can fail an otherwise
+/// complete write. Here each round trip was an independent way for an
+/// already-indexed corpus to fail (#345), so a corpus with K duplicates now
+/// costs `ceil(K / this)` requests instead of K.
+///
+/// Bounded rather than one request for everything because this list is one
+/// entry per duplicate path and the request has to stay a request.
+const ALIAS_SWEEP_CHUNK: usize = 1_024;
+
+/// The delete-by-query for one chunk of duplicate-alias paths.
+///
+/// `path` and `status` are both `keyword` in [`catalog::catalog_mapping`], and
+/// `terms` here takes a plain value array — never the `{index, id, path}`
+/// lookup form, which `_delete_by_query` does not resolve.
+fn alias_sweep_query(paths: &[&str]) -> Value {
+ json!({
+ "bool": {
+ "filter": [
+ {"term": {"status": "duplicate"}},
+ {"terms": {"path": paths}}
+ ]
+ }
+ })
+}
+
+/// The `reason` a run finishes with when every document is indexed but the
+/// legacy-scheme catalog alias sweep could not be completed.
+///
+/// Its own string, not `completed-with-junk`, so it is greppable: the two
+/// states need different operator responses and an agent branching on `reason`
+/// must be able to tell them apart.
+const ALIAS_SWEEP_FAILED_REASON: &str = "catalog-alias-sweep-failed";
+
+/// What a run says when the duplicate-alias sweep failed but the corpus is
+/// indexed.
+///
+/// This is the #345 half that made the issue expensive. A byte-identical
+/// duplicate is the ONLY thing that makes the sweep run at all, and the sweep
+/// is metadata-only bookkeeping that happens AFTER every data document is
+/// durably indexed and after the per-file journal has committed. Propagating
+/// its error turned a fully successful indexing run into
+/// `xerj-done ok=false exit=1 reason=aborted`, permanently: the journal is
+/// already complete, so every rerun indexes zero files and aborts on the same
+/// line. Lucene has the precedent for the other choice — `tryDeleteDocument`
+/// (`lucene/core/src/java/org/apache/lucene/index/IndexWriter.java:1688`)
+/// returns `-1` and lets the caller decide when a delete cannot be performed
+/// instead of throwing.
+///
+/// Two things keep the downgrade honest, and neither may be removed:
+///
+/// 1. It is loud and it NAMES the paths, because the cost is real — a stale
+/// legacy-scheme alias document can survive in the catalog beside the
+/// current one, which is a catalog-accuracy regression, not a free pass.
+/// 2. It cannot hide a broken catalog index. The catalog bulk immediately
+/// after this sweep is still fatal, so a catalog that cannot be written
+/// still aborts the run; only a catalog that accepts writes while refusing
+/// this delete reaches the warning.
+///
+/// One note per line, and the path list capped like every other human-facing
+/// listing in this file (see [`REFUSAL_LIST_CAP`]): [`progress::Progress::note`]
+/// sanitises a newline to `?`, so a multi-line message has to be multiple
+/// notes.
+fn alias_sweep_notes(paths: &[&str], error: &str) -> Vec<String> {
+ let mut notes = vec![
+ format!(
+ "warning: the corpus IS indexed — every document and the resume journal are \
+ committed — but the catalog's duplicate-alias sweep failed for {} path(s), so a \
+ stale alias document written by an older identity scheme may still sit beside \
+ the current one in {}. `xerj autoindex map` can therefore report a duplicate \
+ path twice. Rerun the same command once the server condition below clears; the \
+ sweep is idempotent.",
+ paths.len(),
+ catalog::CATALOG_INDEX,
+ ),
+ format!(" cause: {error}"),
+ ];
+ notes.extend(
+ paths
+ .iter()
+ .take(REFUSAL_LIST_CAP)
+ .map(|path| format!(" alias not swept: {path}")),
+ );
+ let remaining = paths.len().saturating_sub(REFUSAL_LIST_CAP);
+ if remaining > 0 {
+ notes.push(format!(" … and {remaining} more"));
+ }
+ notes
+}
+
/// Exit code for a run that committed (or confirmed) a corpus generation.
///
/// `3` is "completed with junk — recorded, never fatal", the same contract the
@@ -5415,26 +5513,40 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
// ── catalog write ────────────────────────────────────────────────────
// Alias IDs changed as identity evolved. Remove by logical path first so
// catalogs created by any previous identity scheme cannot survive beside
- // the one current alias document.
- pr.phase(
- "finalize-catalog",
- alias_paths_to_replace.len() as u64 + 1,
- 0,
- );
- for path in &alias_paths_to_replace {
- let _delete = pr.file(path, 0);
- es.delete_by_query(
- catalog::CATALOG_INDEX,
- &json!({
- "bool": {
- "filter": [
- {"term": {"status": "duplicate"}},
- {"term": {"path": path}}
- ]
- }
- }),
- )
- .with_context(|| format!("replace catalog alias for {path}"))?;
+ // the one current alias document. One request per CHUNK of paths — see
+ // [`alias_sweep_query`].
+ let mut alias_sweep_paths: Vec<&str> =
+ alias_paths_to_replace.iter().map(String::as_str).collect();
+ // Sorted so the chunk boundaries — and the failure report below — are the
+ // same on every run over the same corpus, not `HashSet` iteration order.
+ alias_sweep_paths.sort_unstable();
+ let alias_sweep_chunks: Vec<&[&str]> = alias_sweep_paths.chunks(ALIAS_SWEEP_CHUNK).collect();
+ pr.phase("finalize-catalog", alias_sweep_chunks.len() as u64 + 1, 0);
+ // Non-fatal, and only this sweep is. See [`alias_sweep_notes`] for why,
+ // and for the two things that keep the downgrade honest.
+ let mut alias_sweep_failed: Vec<&str> = Vec::new();
+ let mut alias_sweep_error: Option<String> = None;
+ for chunk in alias_sweep_chunks {
+ let _delete = pr.file(
+ &match chunk {
+ [only] => (*only).to_string(),
+ [first, ..] => format!("{first} (+{} more)", chunk.len() - 1),
+ [] => String::new(),
+ },
+ 0,
+ );
+ if let Err(error) = es.delete_by_query(catalog::CATALOG_INDEX, &alias_sweep_query(chunk)) {
+ alias_sweep_failed.extend_from_slice(chunk);
+ alias_sweep_error.get_or_insert_with(|| format!("{error:#}"));
+ }
+ }
+ // Said here, next to what happened, and again on the terminal line — a
+ // failure that is only visible in an exit code is the state this change
+ // exists to leave behind.
+ if let Some(error) = &alias_sweep_error {
+ for note in alias_sweep_notes(&alias_sweep_failed, error) {
+ pr.note(&note);
+ }
}
let mut cat_buf: Vec<u8> = Vec::new();
let push_doc = |id: &str, doc: &Value, buf: &mut Vec<u8>| {
@@ -5785,6 +5897,13 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
for (key, value) in code_coverage.fields() {
run_doc[key] = json!(value);
}
+ // Present only when it happened, so a healthy run document is unchanged and
+ // any reader that finds these keys knows the sweep really failed. The full
+ // list is kept here — the prose above is capped, the record is not.
+ if let Some(error) = &alias_sweep_error {
+ run_doc["catalog_alias_sweep_failed_paths"] = json!(alias_sweep_failed);
+ run_doc["catalog_alias_sweep_error"] = json!(error);
+ }
push_doc(&format!("run:{run_id}"), &run_doc, &mut cat_buf);
if !cat_buf.is_empty() {
@@ -5937,7 +6056,13 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
// an error long before this line, so `rejected_records` is provably 0
// here. Splitting them out of `junk_total_records` therefore changes no
// exit code.
- let code = if junk_total_records > 0 || junk_file_count > 0 {
+ //
+ // A failed alias sweep lands here too, and on 3 rather than on a code of
+ // its own: 3 already means "completed, and something about this run is
+ // recorded rather than fatal" (`cli.rs` EXIT CODES), and inventing a fourth
+ // success code would break every caller that already branches on 0/3. The
+ // `reason` is what tells the two apart.
+ let code = if junk_total_records > 0 || junk_file_count > 0 || alias_sweep_error.is_some() {
3
} else {
0
@@ -5956,10 +6081,20 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
("junk_files", junk_file_count as u64),
];
done_fields.extend(code_coverage.fields());
+ if alias_sweep_error.is_some() {
+ done_fields.push((
+ "catalog_alias_sweep_failures",
+ alias_sweep_failed.len() as u64,
+ ));
+ }
pr.finish(
true,
code,
- if code == 3 {
+ // The sweep failure wins the `reason` when both are true: junk is the
+ // everyday state and this one needs an operator.
+ if alias_sweep_error.is_some() {
+ ALIAS_SWEEP_FAILED_REASON
+ } else if code == 3 {
"completed-with-junk"
} else {
"completed"
@@ -7504,6 +7639,74 @@ mod code_coverage_tests {
]
);
}
+
+ /// The chunk boundary of the batched alias sweep (#345), asserted rather
+ /// than assumed: batching is only safe if the chunks partition the path
+ /// list exactly — one lost path leaves a stale alias document behind, and
+ /// one duplicated path is a wasted round trip on the run that has already
+ /// met a server problem.
+ #[test]
+ fn the_alias_sweep_partitions_its_paths_exactly_across_the_chunk_boundary() {
+ let corpus: Vec<String> = (0..ALIAS_SWEEP_CHUNK + 1)
+ .map(|nth| format!("dup-{nth:05}.csv"))
+ .collect();
+ for count in [0, 1, ALIAS_SWEEP_CHUNK - 1, ALIAS_SWEEP_CHUNK, corpus.len()] {
+ let paths: Vec<&str> = corpus[..count].iter().map(String::as_str).collect();
+ let chunks: Vec<&[&str]> = paths.chunks(ALIAS_SWEEP_CHUNK).collect();
+ assert_eq!(chunks.len(), count.div_ceil(ALIAS_SWEEP_CHUNK), "{count}");
+ let swept: Vec<&str> = chunks
+ .iter()
+ .flat_map(|chunk| {
+ let query = alias_sweep_query(chunk);
+ // The filter shape is the contract the server sees: a
+ // `status` term beside a `path` terms ARRAY, never the
+ // `{index, id, path}` lookup form.
+ assert_eq!(query["bool"]["filter"][0]["term"]["status"], "duplicate");
+ query["bool"]["filter"][1]["terms"]["path"]
+ .as_array()
+ .expect("terms values are a plain array")
+ .iter()
+ .map(|path| path.as_str().unwrap().to_owned())
+ .collect::<Vec<_>>()
+ })
+ .map(|path| {
+ corpus
+ .iter()
+ .find(|known| **known == path)
+ .expect("a swept path the corpus never contained")
+ .as_str()
+ })
+ .collect();
+ assert_eq!(swept, paths, "{count}");
+ }
+ }
+
+ /// The downgrade from fatal to reported is only defensible if it is loud
+ /// and names what survived (#345).
+ #[test]
+ fn a_failed_alias_sweep_names_its_paths_the_cause_and_caps_the_listing() {
+ let many: Vec<String> = (0..REFUSAL_LIST_CAP + 3)
+ .map(|nth| format!("dup-{nth}.csv"))
+ .collect();
+ let paths: Vec<&str> = many.iter().map(String::as_str).collect();
+ let notes = alias_sweep_notes(&paths, "delete_by_query: HTTP 500: publication interrupted");
+ let rendered = notes.join("\n");
+ assert!(rendered.contains("the corpus IS indexed"), "{rendered}");
+ assert!(rendered.contains(catalog::CATALOG_INDEX), "{rendered}");
+ assert!(rendered.contains("publication interrupted"), "{rendered}");
+ assert!(
+ rendered.contains("alias not swept: dup-0.csv"),
+ "{rendered}"
+ );
+ assert!(
+ !rendered.contains(&format!("alias not swept: dup-{}.csv", REFUSAL_LIST_CAP)),
+ "the listing is capped like every other one here: {rendered}"
+ );
+ assert!(rendered.contains("… and 3 more"), "{rendered}");
+ // A note carrying a newline would be sanitised to `?` on the progress
+ // surface, so each line has to be its own note.
+ assert!(notes.iter().all(|note| !note.contains('\n')), "{notes:?}");
+ }
}
#[cfg(test)]