AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
//! `xerj autoindex` — point it at ANY folder and it makes the contents
//! AI-searchable with ZERO configuration. Pure ES-compat HTTP client feature:
//! it does NOT link xerj-engine, works against any endpoint, and cannot
//! destabilize the server.
pub mod budget;
pub mod catalog;
pub mod cli;
pub mod coerce;
mod content;
pub mod correlate;
mod dataless;
pub mod dataset;
pub mod def;
pub mod detect;
pub mod esclient;
pub mod estimate;
pub mod extract;
mod family_junk;
pub mod feedback;
pub mod flood;
pub mod gain;
pub mod gate;
mod generation_catalog;
#[cfg(test)]
mod generation_catalog_http_tests;
/// `xerj corpus build` — harvested-record corpus packs (recipe → store →
/// identity → merge → deterministic pack).
pub mod harvest;
pub mod ids;
pub mod ignore_rules;
pub mod infer;
pub mod init;
/// `--label`: ingest-time labelling through the node's `/_decide` (#1062).
pub mod label;
pub mod map_report;
pub mod memory_cli;
pub mod neural_cost;
pub mod objsource;
#[cfg(test)]
mod objsource_minio_tests;
#[cfg(test)]
mod objsource_s3_tests;
/// `--watch` for object storage: poll a bucket, feed a change feed, count the cost.
pub mod objwatch;
pub mod order;
pub mod pool;
pub mod progress;
mod reconcile_plan;
pub mod remove;
pub mod resources;
pub mod search;
pub mod search_hints;
mod session_memory;
pub mod sessions;
pub mod skills;
pub mod sniff;
pub mod source;
mod stage;
pub mod staleness;
pub mod state;
mod sync;
mod sync_executor;
#[cfg(test)]
mod test_loopback;
pub mod walk;
pub mod watch;
pub mod xc;
use anyhow::{Context, Result};
use serde::Serialize;
use serde_json::{json, Map, Value};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::io::{BufRead, Write};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Condvar, Mutex};
use std::time::Instant;
use cli::{Cmd, IndexCfg, MapCfg, StatusCfg};
// Trait must be in scope for `href_raw.counters()` (a concrete `Href`, not a
// `Box<dyn EdgeDetector>` like the registry entries).
use detect::EdgeDetector as _;
use esclient::Es;
use progress::Progress;
use sniff::{Family, Sniffed};
use state::{DuplicateFile, FileAssignment, FileDone, JunkFile, Plan, PlanDataset};
const PREPARED_RECORDS_IDENTITY: &str = "prepared-records-v1";
const DOCUMENT_IDS_IDENTITY: &str = "document-ids-v1";
const DETECTOR_DISABLED_IDENTITY: &str = "disabled";
/// Ingest throughput for the summary line and the run document.
///
/// The numerator is documents this run submitted, not the live catalog
/// count. A no-op resume of tokio left 11246 documents live and submitted
/// 0, and `live / wall` printed 66096.3 docs/sec for a run that sent
/// nothing. `wall == 0` (a sub-millisecond no-op) stays 0 rather than `inf`.
pub(crate) fn ingest_docs_per_sec(submitted_this_run: u64, wall_secs: f64) -> f64 {
if wall_secs > 0.0 && submitted_this_run > 0 {
submitted_this_run as f64 / wall_secs
} else {
0.0
}
}
/// The indexed-vs-submitted line (#195).
///
/// A no-op resume prints `submitted 0 source records from 0 files` next to
/// a large live count, which reads as "nothing is indexed". When the corpus
/// is already live and this run sent nothing, say so. A first run
/// (`submitted > 0`) and an empty corpus (`live == 0`) keep the bare line.
pub(crate) fn indexed_vs_submitted_line(live: u64, submitted: u64, files: u64) -> String {
let mut line = format!(
"indexed: {live} documents live; this run submitted {submitted} source records from {files} files"
);
if live > 0 && submitted == 0 && files == 0 {
line.push_str(" (already indexed; nothing new to send)");
}
line
}
/// Render the `next:` guidance printed after a successful index run.
///
/// The run's own credential and URL are carried into the printed commands.
/// They used to be printed bare, so against an auth-enabled server — which is
/// the default, and what `xerj brain` boots — a *successful* run signed off by
/// handing the user two commands that both answer 401
/// (`ONBOARDING-401-REPRO.md` §3). Guidance that cannot be pasted is worse
/// than no guidance: it reads as a broken server.
///
/// `api_key` is the credential this run used (`None` means the server needs
/// none — `--insecure` or auth off — and the bare commands really do work).
/// `env_key` is the ambient `XERJ_API_KEY`; when it already holds the run's
/// key the hints reference `$XERJ_API_KEY` rather than the literal secret, so
/// the command still pastes into the same shell while the admin key stays out
/// of a banner users routinely paste into bug reports.
///
/// When the key came from neither the environment nor the user's own command
/// line — i.e. it was discovered on disk — the hint must still not echo it.
/// A blind onboarding run caught exactly that: `autoindex` found
/// `./data/admin.key` by itself and then printed the admin key verbatim in a
/// banner. The reader never typed that secret, so seeing it in copyable output
/// is a disclosure, not a convenience.
pub fn next_hint(
url: &str,
prefix: &str,
api_key: Option<&str>,
env_key: Option<&str>,
key_file: Option<&std::path::Path>,
) -> String {
let Some(key) = api_key else {
return with_field_report(format!(
"\nnext: `xerj autoindex map --url {url}` for the data map; \
search via `xerj search --url {url} --prefix {prefix} \"<what you need>\"`"
));
};
// A shell *expression* in every arm, so all renderings quote identically.
let key_expr = if env_key == Some(key) {
"$XERJ_API_KEY".to_string()
} else if let Some(path) = key_file {
// Reads the same secret at paste time without printing it here.
format!("$(cat {})", path.display())
} else {
key.to_string()
};
with_field_report(format!(
"\nnext: `xerj autoindex map --url {url} --api-key \"{key_expr}\"` for the data map;\n\
\x20 search via `xerj search --url {url} --prefix {prefix} --api-key \"{key_expr}\" \
\"<what you need>\"`"
))
}
fn with_field_report(hint: String) -> String {
with_field_report_if(hint, xerj_common::feedback::enabled())
}
/// The footer honours the same opt-out as every other surface
/// (`--disable-feedback` anywhere on the command line, or
/// `XERJ_DISABLE_FEEDBACK=true`). It used not to, so `xerj corpus index`, which
/// prints this footer from the autoindex run it drives, kept inviting a field
/// report after the operator had switched the invitation off (issue #1903).
fn with_field_report_if(hint: String, enabled: bool) -> String {
if enabled {
format!("{hint}\n{}", xerj_common::feedback::AUTO_SEND_LINE)
} else {
hint
}
}
/// The code-aware search hint that follows `next_hint` whenever source code
/// was indexed. One copy, shared by BOTH success printers — the interactive
/// run summary and the generated-run (`--no-graph`/brain) summary — because
/// #1103 was exactly this text existing in one printer and not the other.
/// It names `xerj search` and `xerj def`: those commands already request
/// `_passage`. A raw `_search` curl is what a blind run copied, and that
/// path returns a whole file unless the caller knows the projection.
pub(crate) fn code_search_hint(prefix: &str) -> String {
format!(
" code was indexed — `xerj search` and `xerj def` ask for the matching\n\
\x20 passage, so the header is a path and a line when the index has one:\n\
\x20 xerj search --prefix {prefix} \"<what you need>\"\n\
\x20 xerj def --prefix {prefix} <symbol>\n\
\x20 (add the same --url and --api-key the map line above used)"
)
}
/// What to print when a run indexed both code and prose.
///
/// The previous text pasted a `match` on `body` only. Line files (a
/// changelog is `txt-lines`) are stored in `text`, so that fragment misses
/// them and teaches a query that cannot see half the corpus. Name the
/// `ax_format` values this run actually wrote, and say which field holds
/// which side.
pub(crate) fn mixed_corpus_hint(formats: &[&str]) -> String {
let listed = if formats.is_empty() {
"none recorded".to_string()
} else {
formats.join(", ")
};
format!(
" this corpus mixes code and prose — code volume can swamp prose on\n\
\x20 shared words. Scope one side with a filter on `ax_format`\n\
\x20 (values in this run: {listed}).\n\
\x20 Prose sections are stored in `body`; line files such as changelogs\n\
\x20 are stored in `text`, so a match on `body` alone misses them."
)
}
fn prepared_records_identity(cfg: &IndexCfg) -> Result<String> {
let mut value = json!({
"contract": PREPARED_RECORDS_IDENTITY,
"sample": cfg.sample,
"no_semantic": cfg.no_semantic,
// Worker counts are operational only. The timeout can change whether
// a PDF yields records, so it is part of the semantic contract.
"pdf_timeout_secs": cfg.pdf_timeout_secs,
// The question set decides the label fields stamped on every record
// (#1062): two runs against the same folder with different question
// sets produce different documents and must not share a prepared
// corpus. Digest the file bytes — the set's own identity IS the bytes.
"label": cfg.label.as_ref().map(|p| {
std::fs::read(p).map(|bytes| format!("{:032x}", xxhash_rust::xxh3::xxh3_128(&bytes)))
.unwrap_or_else(|_| "unreadable".to_string())
}),
});
// Back-compat: every pre-#1233 cap was a whole number of GB, serialised as
// the top-level key `"max_file_gb": N`. Keep emitting exactly that whenever
// the byte cap is a whole number of GB, so an index built before the flag
// gained sub-GB granularity still re-derives its original digest and
// resumes cleanly. A genuinely sub-GB cap (the new capability) gets a
// distinct `max_file_bytes` key, which correctly reads as a different
// prepared-records contract and triggers a fresh generation.
let map = value.as_object_mut().expect("json! object");
if cfg.max_file_bytes.is_multiple_of(GB) {
map.insert("max_file_gb".into(), json!(cfg.max_file_bytes / GB));
} else {
map.insert("max_file_bytes".into(), json!(cfg.max_file_bytes));
}
Ok(format!(
"{}-{:032x}",
PREPARED_RECORDS_IDENTITY,
xxhash_rust::xxh3::xxh3_128(&serde_json::to_vec(&value)?)
))
}
fn preparation_contract_digest(cfg: &IndexCfg, plan: &Plan) -> Result<String> {
let (schema_identity, index_identity) = generation_contract_identities(plan)?;
let encoded = serde_json::to_vec(&json!({
"prepared_records": prepared_records_identity(cfg)?,
"document_ids": DOCUMENT_IDS_IDENTITY,
"schema_identity": schema_identity,
"index_identity": index_identity,
"plan": plan,
}))?;
Ok(format!(
"axpc1-{:032x}",
xxhash_rust::xxh3::xxh3_128(&encoded)
))
}
pub(crate) fn generation_contract_identities(plan: &Plan) -> Result<(String, String)> {
let mut datasets = plan.datasets.iter().collect::<Vec<_>>();
datasets.sort_by(|left, right| {
left.slug
.cmp(&right.slug)
.then_with(|| left.index.cmp(&right.index))
});
let schema = datasets
.iter()
.map(|dataset| {
json!({
"slug": dataset.slug,
"family": dataset.family,
"group": dataset.group,
"specs": dataset.specs,
"time_field": dataset.time_field,
"semantic_field": dataset.semantic_field,
})
})
.collect::<Vec<_>>();
let indices = datasets
.iter()
.map(|dataset| {
json!({
"index": dataset.index,
"mapping": build_mapping(&dataset.specs),
})
})
.collect::<Vec<_>>();
let digest = |label: &str, value: Value| -> Result<String> {
let bytes = serde_json::to_vec(&json!({"contract": label, "value": value}))?;
Ok(format!("{:032x}", xxhash_rust::xxh3::xxh3_128(&bytes)))
};
Ok((
digest(PREPARED_RECORDS_IDENTITY, Value::Array(schema))?,
digest(
DOCUMENT_IDS_IDENTITY,
json!({
"datasets": indices,
"catalog_index": catalog::CATALOG_INDEX,
"catalog_mapping": catalog::catalog_mapping(),
"document_ids": DOCUMENT_IDS_IDENTITY,
}),
)?,
))
}
/// The generation contract exactly as the shipped releases froze it on disk
/// (#755).
///
/// `index_identity` is written into every committed generation's execution
/// record in the journal and then compared for **equality** on the next run —
/// on the incremental-reconcile no-change arm, and in `provision_generation`
/// when a pending generation is replayed. So the identity this build computes
/// for a plan has to equal the identity the *previously shipped* build computed
/// for the same plan, or upgrading aborts every existing state dir. That is the
/// abort class this change exists to remove, so it must not be reintroduced by
/// the change itself.
///
/// This fixture is the shipped side of that equality: `CATALOG_MAPPING_JSON` is
/// `catalog::catalog_mapping()` serialized, captured verbatim from the
/// v1.0.0-rc.68..rc.71 tree (the releases that wrote the journals now in the
/// field), and [`index_identity`] mirrors `generation_contract_identities`'
/// index digest over it. `catalog_mapping_is_the_frozen_on_disk_contract`
/// compares the two; `a_generation_frozen_by_the_previous_release_still_reconciles`
/// runs the indexer over a journal carrying it.
#[cfg(test)]
pub(crate) mod frozen_contract {
use super::*;
/// `serde_json::to_string(&catalog::catalog_mapping())` on v1.0.0-rc.71.
pub(crate) const CATALOG_MAPPING_JSON: &str = r#"{"mappings":{"properties":{"doc_kind":{"type":"keyword"},"slug":{"type":"keyword"},"index_name":{"type":"keyword"},"record_count":{"type":"long"},"junk_records":{"type":"long"},"bytes":{"type":"long"},"file_count":{"type":"long"},"formats":{"type":"keyword"},"time_field":{"type":"keyword"},"time_min":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"time_max":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"semantic_field":{"type":"keyword"},"fields_json":{"type":"text"},"sample_queries_json":{"type":"text"},"notes":{"type":"text"},"path":{"type":"keyword"},"file_key":{"type":"keyword"},"format":{"type":"keyword"},"status":{"type":"keyword"},"reason":{"type":"text"},"duplicate_of":{"type":"keyword"},"records":{"type":"long"},"junk":{"type":"long"},"run_id":{"type":"keyword"},"corr_kind":{"type":"keyword"},"a_dataset":{"type":"keyword"},"b_dataset":{"type":"keyword"},"a_index":{"type":"keyword"},"b_index":{"type":"keyword"},"a_field":{"type":"keyword"},"b_field":{"type":"keyword"},"grade":{"type":"keyword"},"overlap":{"type":"long"},"containment":{"type":"double"},"range_overlap":{"type":"double"},"pearson_r":{"type":"double"},"activity_correlated":{"type":"boolean"},"started":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"summary_generated_at":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"invocation_telemetry_scope":{"type":"keyword"},"junk_records_this_run":{"type":"long"},"prefix":{"type":"keyword"}}}}"#;
/// The `index_identity` a v1.0.0-rc.68..rc.71 binary froze for `plan`:
/// `generation_contract_identities`' index digest, hashing the mapping
/// above instead of this build's `catalog::catalog_mapping()`.
pub(crate) fn index_identity(plan: &Plan) -> String {
let mut datasets = plan.datasets.iter().collect::<Vec<_>>();
datasets.sort_by(|left, right| {
left.slug
.cmp(&right.slug)
.then_with(|| left.index.cmp(&right.index))
});
let indices = datasets
.iter()
.map(|dataset| {
json!({
"index": dataset.index,
"mapping": build_mapping(&dataset.specs),
})
})
.collect::<Vec<_>>();
let value = json!({
"datasets": indices,
"catalog_index": catalog::CATALOG_INDEX,
"catalog_mapping": serde_json::from_str::<Value>(CATALOG_MAPPING_JSON)
.expect("the frozen catalog mapping parses"),
"document_ids": DOCUMENT_IDS_IDENTITY,
});
let bytes = serde_json::to_vec(&json!({
"contract": DOCUMENT_IDS_IDENTITY,
"value": value,
}))
.expect("the frozen contract serializes");
format!("{:032x}", xxhash_rust::xxh3::xxh3_128(&bytes))
}
}
/// One dataset the server refused to map: `(slug, the server's refusal)`.
pub(crate) type MappingRefusal = (String, String);
/// Longest refusal reason that is recorded, in characters.
///
/// Generous next to a real engine's answer — the refusal in #929 is under 500 —
/// and small next to what it multiplies into: see [`refusal_reason`].
const REFUSAL_REASON_MAX: usize = 1024;
/// The reason a refusal is recorded under: the error chain, bounded and with
/// control characters replaced.
///
/// The text is the SERVER's response body, verbatim, so it is outside input,
/// and it does not stay in one place. It is frozen into the plan and the
/// committed manifest, republished in the catalog's run document by every
/// later generation, copied into the catalog entry of EVERY file the refusal
/// cost, printed on stdout, and rendered by `xerj autoindex map`. Unbounded, a
/// verbose proxy error page under a 10,000-file dataset is tens of megabytes
/// of catalog; unsanitized, a body containing a newline can start a line of
/// its own on stdout — for instance a second, forged `REFUSED dataset` line.
/// [`progress::sanitize`] already solves both for the progress surface (it
/// counts characters, so it cannot split a code point), so the reason goes
/// through it once, here, before anything stores it.
fn refusal_reason(error: &anyhow::Error) -> String {
progress::sanitize(&format!("{error:#}"), REFUSAL_REASON_MAX)
}
/// Create every dataset index in `plan` and install its mapping.
///
/// A server *refusal* of one dataset's mapping (HTTP 400, see
/// [`esclient::MappingRefused`]) is returned, not propagated: it is a statement
/// about that one dataset and says nothing about the others, so the caller
/// decides what it costs. Every other failure — transport, auth, 5xx — is an
/// endpoint failure, is not specific to any dataset, and still aborts.
///
/// This used to be a bare `?` inside the loop, which let ONE unmappable field
/// name abort a 48,533-file, 1,526-dataset run with zero documents indexed
/// (#929). The precedent for the split is Meilisearch's batch processing,
/// read for approach only: a per-operation user error marks that one task
/// `Failed` while the batch carries on, and only an internal error aborts it
/// (`meilisearch/crates/index-scheduler/src/scheduler/process_index_operation.rs:173`).
fn install_dataset_mappings(
es: &Es,
plan: &Plan,
mut installed_one: impl FnMut(),
) -> Result<Vec<MappingRefusal>> {
let mut refused = Vec::new();
for dataset in &plan.datasets {
let create_body = dataset_mapping_body(dataset, extra_fields(plan, &dataset.slug));
let update_body = json!({
"properties": create_body["mappings"]["properties"].clone()
});
let installed = es
.ensure_index(&dataset.index, &create_body)
.with_context(|| format!("create generation index {}", dataset.index))
.and_then(|()| {
es.update_mapping(&dataset.index, &update_body)
.with_context(|| format!("install generation mapping for {}", dataset.index))
});
match installed {
Ok(()) => {}
Err(error) if error.downcast_ref::<esclient::MappingRefused>().is_some() => {
refused.push((dataset.slug.clone(), refusal_reason(&error)));
}
Err(error) => return Err(error),
}
installed_one();
}
Ok(refused)
}
/// The index-create body for one dataset: the frozen mapping
/// ([`build_mapping`]) plus, when the profiler marked the dataset's prose
/// semantic, the #1059 stemming analyzer declaration.
///
/// The analyzer goes into `settings.analysis.analyzer.default` — the surface
/// #937 (fixed by #991) made real: a declared default analyzer is honoured at
/// flush, at segment query and at merge, and the memtable has always resolved
/// it, so a whole index analyses one way for its whole life. A per-field
/// `analyzer` in the mapping is NOT used: that is the accepted-and-ignored
/// surface the #937 audit left open (`docs/ZERO_TOKEN_DIRECTION.md`).
///
/// Two properties this placement is load-bearing for:
///
/// - **The frozen identities.** `build_mapping`'s value is hashed into every
/// committed generation's `index_identity` (`generation_contract_identities`),
/// so the analyzer must NOT be declared inside it — here, in the create
/// body only, the digests are byte-identical to an older build's for the
/// same specs and no existing state dir aborts on upgrade. The transport
/// layer then adds `settings.index.xerj_ingest_shards` beside it
/// (`with_single_wal_shard`), the established precedent for a create-only
/// setting that lives outside the frozen contract.
/// - **New indexes only.** Analysis settings are immutable server-side after
/// creation (a settings PUT naming `analysis` is refused), and
/// [`Es::ensure_index`] tolerates `resource_already_exists` without
/// re-sending the body — so an index an earlier run or an older build
/// created is untouched, keeping its `standard` term space and its
/// postings, and only an index THIS run creates gets the stemmer. The
/// marker therefore rides the plan frozen in the journal: a pending
/// generation replayed after a restart still declares the analyzer.
fn dataset_create_body(dataset: &PlanDataset) -> Value {
dataset_mapping_body(dataset, &[])
}
/// Mapping upgrade for an index the graph path already created.
///
/// `ensure_index` does not resend the body once the index exists, and a full
/// properties PUT can 400 when an older dynamic type disagrees. The upgrade
/// sends `ax_paths` plus scalar fields an incremental absorb added after the
/// schema was frozen (#2176, #2314) — names the frozen mapping does not have.
fn graph_mapping_upgrade(plan: &Plan, dataset: &PlanDataset) -> Value {
let mut properties = serde_json::Map::new();
properties.insert("ax_paths".into(), json!({"type": "keyword"}));
for spec in extra_fields(plan, &dataset.slug) {
if properties.contains_key(&spec.name) {
continue;
}
let property = match spec.es_type.as_str() {
"date" => {
json!({"type": "date", "format": "strict_date_optional_time||epoch_millis"})
}
es_type => json!({"type": es_type}),
};
properties.insert(spec.name.clone(), property);
}
// #2351: `start_line` / `end_line` are mapped beside the frozen specs.
// A name the specs already declare (prose `start_line`) is not sent
// again. `end_line` is included when an older plan never inferred it,
// so a prose section that now stores the span is an explicit `long`.
if dataset.family == "docs" || dataset.family == "code" {
for name in ["start_line", "end_line"] {
if dataset.specs.iter().any(|spec| spec.name == name) || properties.contains_key(name) {
continue;
}
properties.insert(name.into(), json!({"type": "long"}));
}
}
json!({"properties": properties})
}
fn extra_fields<'a>(plan: &'a Plan, slug: &str) -> &'a [infer::FieldSpec] {
plan.incremental_fields
.get(slug)
.map(Vec::as_slice)
.unwrap_or(&[])
}
/// The index-create body, plus fields an incremental run added after the
/// schema was frozen (#2176). An extra name that the frozen mapping already
/// declares is left alone, so this cannot change `impl` from `text` to a
/// re-inferred `keyword`.
fn dataset_mapping_body(dataset: &PlanDataset, extra: &[infer::FieldSpec]) -> Value {
let mut create_body = build_mapping(&dataset.specs);
if let Some(props) = create_body
.pointer_mut("/mappings/properties")
.and_then(Value::as_object_mut)
{
for spec in extra {
if props.contains_key(&spec.name) {
continue;
}
let property = match spec.es_type.as_str() {
"date" => {
json!({"type": "date", "format": "strict_date_optional_time||epoch_millis"})
}
es_type => json!({"type": es_type}),
};
props.insert(spec.name.clone(), property);
}
}
create_body["mappings"]["properties"]["ax_paths"] = json!({"type": "keyword"});
if dataset.family == "docs" || dataset.family == "code" {
if let Some(props) = create_body
.pointer_mut("/mappings/properties")
.and_then(Value::as_object_mut)
{
props
.entry("impl".to_string())
.or_insert_with(|| json!({"type": "text"}));
props
.entry("end_line".to_string())
.or_insert_with(|| json!({"type": "long"}));
// #2351: same place as `end_line`, outside `build_mapping`, so the
// generation identity does not move. A spec that already typed
// `start_line` (prose) is left alone.
props
.entry("start_line".to_string())
.or_insert_with(|| json!({"type": "long"}));
}
}
if let Some(analyzer) = &dataset.text_analyzer {
create_body["settings"] = json!({"analysis": {"analyzer": {
"default": {"type": analyzer}
}}});
}
// #1093: autoindex PUTs an explicit full schema, so a lookup naming a
// field outside it is a mistake, not a dynamic-mapping probe — the exact
// case the refusal exists for (5 of 30 agent intents silently searched a
// wrong field name). Strict rides HERE, in the create body, not in
// `build_mapping`: this value is not hashed into the generation contract
// identities, so existing state dirs keep their digests; and
// `ensure_index` tolerates `resource_already_exists` without re-sending,
// so indices an older build created stay lenient (opt in via the setting).
if let Some(settings) = create_body
.get_mut("settings")
.and_then(Value::as_object_mut)
{
settings.insert("index.query.strict_unknown_fields".to_string(), json!(true));
} else {
create_body["settings"] = json!({"index.query.strict_unknown_fields": true});
}
// #1504: log messages are searched as phrases. The english analyzer
// already drops `is`; an omitted `match` is still OR for the content
// words, so `SIP 403 Forbidden` hits every line that contains `SIP`.
// The engine reads this key in `Index::search` and fills an omitted
// operator with AND. An explicit `"operator": "or"` is left alone, and
// a non-log index never gets the key, so the ES default stays OR.
// The key lives here, beside `strict_unknown_fields`, and not in
// `build_mapping`: that value is hashed into the generation contract.
if dataset.family == "logs" {
create_body["settings"]["index.query.default_match_operator"] = json!("and");
}
create_body
}
fn ensure_generation_catalog_mapping(es: &Es, pr: &Progress) -> Result<()> {
let mut catalog_create_body = catalog::catalog_mapping();
catalog_create_body["mappings"]["properties"]["duplicate_of"] = json!({"type": "keyword"});
// #755: the corpus-scope field rides here, beside `duplicate_of`, and NOT
// inside `catalog::catalog_mapping` — that function's value is hashed into
// the `index_identity` frozen in every committed generation, so declaring a
// new property there would abort the next run of every existing state dir
// (the very upgrade abort this change exists to remove). This body is not
// hashed, so the field is installed on every run without moving the digest.
catalog_create_body["mappings"]["properties"][catalog::CORPUS_SCOPE_FIELD] =
json!({"type": "keyword"});
let catalog_update_body = json!({
"properties": catalog_create_body["mappings"]["properties"].clone()
});
es.ensure_index(catalog::CATALOG_INDEX, &catalog_create_body)?;
install_catalog_mapping(es, &catalog_update_body, pr)
.context("install generation catalog mapping")
}
/// Provision a SEALED generation: every dataset mapping must install.
///
/// By the time a generation is provisioned its plan is frozen in the journal
/// and its records are sealed in a snapshot, so a dataset cannot be dropped
/// here without the manifest, the snapshot and the catalog disagreeing about
/// what the generation contains. A refusal at this point is therefore fatal —
/// but it names EVERY refused dataset (not just the first the loop met) and the
/// one recovery that works. [`preflight_generation_mappings`] is what keeps a
/// fresh run from ever getting here with an unmappable dataset.
pub(crate) fn ensure_generation_mappings(es: &Es, plan: &Plan, pr: &Progress) -> Result<()> {
let refused = install_dataset_mappings(es, plan, || {})?;
if !refused.is_empty() {
let named = refused
.iter()
.map(|(slug, reason)| format!("{slug} ({reason})"))
.collect::<Vec<_>>()
.join("; ");
anyhow::bail!(
"the server refused the mapping of {} dataset(s) in a generation that is already \
sealed: {named}. A sealed generation cannot drop a dataset, so re-running will \
repeat this refusal. No document was published. Rebuild with a new --state-dir and \
a new --prefix: a fresh run records a refused dataset (exit 3) and indexes the rest",
refused.len()
);
}
ensure_generation_catalog_mapping(es, pr)
}
/// Install a NOT-YET-SEALED plan's mappings and drop what the server refuses.
///
/// Runs before [`begin_non_graph_generation`] seals anything, which is the only
/// point at which a dataset can still leave the plan coherently: the manifest,
/// the snapshot, the contract digests and the catalog are all derived from the
/// plan this returns, so they agree about the refused dataset by construction.
///
/// A refusal is loud on purpose. It costs the corpus real files, so it goes out
/// through `pr.warn` (which `--quiet` does not silence), is recorded in the
/// plan's `refused_datasets`, turns each of its files into a catalogued junk
/// file carrying the server's own words, and keeps the exit code at 3.
///
/// Returns the plan to seal and the `index_identity` whose dataset mappings are
/// now installed, so provisioning the generation in this same process does not
/// pay the same two round trips per dataset a second time.
pub(crate) fn preflight_generation_mappings(
es: &Es,
mut plan: Plan,
sizes: &HashMap<&str, u64>,
pr: &Progress,
) -> Result<(Plan, String)> {
// Two round trips per dataset; a 1,526-dataset plan is a real wait, so it
// is a phase with a denominator rather than part of a stalled `scan`.
pr.phase("prepare", plan.datasets.len() as u64, 0);
let refused = install_dataset_mappings(es, &plan, || pr.item_done(0))?;
if !refused.is_empty() {
let before = plan.files.len();
refuse_datasets(&mut plan, &refused, sizes);
for refusal in &plan.refused_datasets {
pr.warn(&format!(
"autoindex: dataset {} REFUSED by the server — {} file(s) recorded as junk and NOT \
indexed; every other dataset continues. {}",
refusal.dataset.slug,
refusal.file_keys.len(),
refusal.reason
));
}
pr.warn(&format!(
"autoindex: {} of {} dataset(s) refused, {} of {before} file(s) not indexed — this run \
will exit 3 and name them in its summary (`datasets_refused`)",
plan.refused_datasets.len(),
plan.refused_datasets.len() + plan.datasets.len(),
before - plan.files.len(),
));
}
let (_, index_identity) = generation_contract_identities(&plan)?;
Ok((plan, index_identity))
}
/// Remove refused datasets from a plan that has not been sealed yet.
///
/// A file is dropped WHOLE when any dataset it feeds was refused. Splitting it
/// — keeping the accepted tables of a multi-table dump and dropping one — is
/// not expressible downstream: `prepare_artifact` routes a record with no
/// assignment of its own to the file's group-less dataset, or aborts the run
/// when there is none, so a partially assigned file would either mis-file the
/// refused records or fail the generation this exists to save.
///
/// Everything the manifest invariants tie to `plan.files` moves with it: the
/// duplicate aliases of a dropped file go (`validate_plan_projection` requires
/// aliases to belong to a live group, #283), and each surviving dataset's
/// `file_count` is recounted. Ordering is canonical throughout, because the
/// incremental projection must reproduce this plan byte for byte.
pub(crate) fn refuse_datasets(
plan: &mut Plan,
refusals: &[MappingRefusal],
sizes: &HashMap<&str, u64>,
) {
if refusals.is_empty() {
return;
}
let reasons: HashMap<&str, &str> = refusals
.iter()
.map(|(slug, reason)| (slug.as_str(), reason.as_str()))
.collect();
let (kept, dropped): (Vec<state::PlanDataset>, Vec<state::PlanDataset>) =
std::mem::take(&mut plan.datasets)
.into_iter()
.partition(|dataset| !reasons.contains_key(dataset.slug.as_str()));
plan.datasets = kept;
let mut refused: Vec<state::RefusedDataset> = dropped
.into_iter()
.map(|dataset| state::RefusedDataset {
reason: reasons[dataset.slug.as_str()].to_owned(),
dataset,
file_keys: Vec::new(),
})
.collect();
refused.sort_by(|left, right| left.dataset.slug.cmp(&right.dataset.slug));
// A file that feeds several refused datasets is attributed to the first by
// slug, so the attribution does not depend on `HashMap` iteration order.
let mut lost: Vec<(String, usize)> = plan
.files
.iter()
.filter_map(|(key, assignment)| {
refused
.iter()
.position(|refusal| {
assignment
.assignments
.iter()
.any(|(_, slug)| *slug == refusal.dataset.slug)
})
.map(|owner| (key.clone(), owner))
})
.collect();
lost.sort();
for (key, owner) in lost {
let assignment = plan.files.remove(&key).expect("key came from plan.files");
plan.junk_files.push(state::JunkFile {
file_key: key.clone(),
rel: assignment.rel,
format: if assignment.gzip {
format!("{}(gzip)", assignment.family)
} else {
assignment.family
},
status: "junk".into(),
reason: refused[owner].junk_reason(),
bytes: sizes.get(key.as_str()).copied().unwrap_or(0),
});
refused[owner].file_keys.push(key);
}
plan.duplicate_files
.retain(|alias| plan.files.contains_key(&alias.file_key));
for dataset in &mut plan.datasets {
dataset.file_count = plan
.files
.values()
.filter(|assignment| {
assignment
.assignments
.iter()
.any(|(_, slug)| *slug == dataset.slug)
})
.count();
}
plan.refused_datasets.extend(refused);
plan.refused_datasets
.sort_by(|left, right| left.dataset.slug.cmp(&right.dataset.slug));
}
/// Install the catalog mapping without letting a legacy field type abort the
/// run (#755).
///
/// The global `autoindex-catalog` is shared by every corpus on the node and it
/// outlives releases, so it can already hold a field whose dynamically inferred
/// type disagrees with what this build declares — and Elasticsearch cannot
/// change a field's type in place. The concrete instance this exists for:
/// v1.0.0-rc.15 (`61b31ef3`) began writing `prefix` on the catalog's run
/// document while `catalog::catalog_mapping` still did not declare it, so every
/// catalog written by rc.15..rc.67 inferred `prefix` as **text**; #737 (rc.68)
/// then declared it `keyword` and installed it with a hard `update_mapping`.
/// The result was a 400 `mapper_parsing_exception` on *every* subsequent
/// autoindex run against that node — an upgrade that bricks the tool.
///
/// A run must never abort because of a mapping an *earlier* release left
/// behind. Elasticsearch reports one conflicting field per request, so this
/// drops the named field and retries, which converges in at most one attempt
/// per declared property: every field this build *can* install gets installed,
/// including `catalog::CORPUS_SCOPE_FIELD` — a field no release ever wrote, so
/// it is always accepted as `keyword` and carries the corpus scope the #737
/// sweeps need even on a catalog whose `prefix` is text.
///
/// What is tolerated is a *narrower declared mapping*. The operator is warned,
/// with the reindex that retires the legacy field. Two limits on that tolerance
/// are real, and neither is papered over:
///
/// * A leftover analyzed field does not merely match *fewer* documents. A
/// `term` against `text` matches the analyzed TOKENS, so a single-token scope
/// value (`ax`) also matches a sibling corpus whose scope is `ax-2` (tokens
/// `[ax, 2]`) — wider, not narrower, and across the corpus boundary #737 drew.
/// That is precisely why the scope moved to `CORPUS_SCOPE_FIELD` instead of
/// being left on a possibly-text `prefix`. The widening is no longer load-
/// bearing on the delete path either: since #890 the sweeps go through
/// [`delete_catalog_docs_scoped`], which re-checks each hit's raw scope value
/// before deleting it by `_id`, so a legacy analyzed field can cost this
/// catalog *coverage* but can no longer cost a sibling corpus its documents.
/// * The loop gives up whatever field the engine names, and the safety of doing
/// so is not uniform across fields. It holds for the conjunctive scope filters
/// above; it does not hold for the `ensure!`-guarded exact reads built on
/// them — a catalog holding `run_id` as text would install without it and
/// then fail at the very end of the run in `finish_generated_run`, whose
/// `run_id` + `doc_kind` lookup requires exactly one hit. No catalog created
/// by `ensure_index` can be in that state (`catalog_mapping` declares
/// `run_id`); one auto-created by a stray document write could be.
///
/// An automatic reindex is deliberately still NOT done here: the catalog is
/// global across every corpus and its scoping drives deletions, so rewriting it
/// wholesale is a maintainer decision, not a silent side effect of a run.
fn install_catalog_mapping(es: &Es, body: &Value, pr: &Progress) -> Result<()> {
let mut properties = body
.get("properties")
.and_then(Value::as_object)
.cloned()
.context("catalog mapping update body has no `properties` object")?;
// One removal per iteration, so the loop is bounded by the declared field
// count; the extra turn is the (empty-properties) fixed point.
let attempts = properties.len() + 1;
let mut legacy: Vec<String> = Vec::new();
for _ in 0..attempts {
let err = match es.update_mapping(
catalog::CATALOG_INDEX,
&json!({"properties": Value::Object(properties.clone())}),
) {
Ok(()) => {
if !legacy.is_empty() {
pr.warn(&legacy_catalog_mapping_warning(
catalog::CATALOG_INDEX,
&legacy,
));
}
return Ok(());
}
Err(err) => err,
};
// Anything that is not a legacy type conflict — a 503, a refused
// connection, an unrelated 400 — is a real failure and still aborts.
let Some(field) = legacy_text_field_in_conflict(&format!("{err:#}")) else {
return Err(err);
};
// The conflict names a field this request did not declare: dropping it
// cannot make progress, so surface the error rather than spin. The
// warning's "the run continues" wording would be a lie here, so this
// says only what is true.
if properties.remove(&field).is_none() {
return Err(err.context(format!(
"`{}` reports a type conflict on `{field}`, which this mapping update does not \
declare — there is nothing to give up, so the conflict cannot be worked around \
here. Reindex `{}` into an index created with the current mapping",
catalog::CATALOG_INDEX,
catalog::CATALOG_INDEX,
)));
}
legacy.push(field);
}
anyhow::bail!(
"`{}` mapping install did not converge after {attempts} attempts (legacy fields: {})",
catalog::CATALOG_INDEX,
legacy.join(", ")
)
}
/// The operator-facing account of a legacy-mapped global catalog: which fields
/// an older build left as `text`, what the run did about it, and the
/// data-preserving reindex that retires them.
fn legacy_catalog_mapping_warning(index: &str, legacy: &[String]) -> String {
let named = legacy
.iter()
.map(|field| format!("`{field}`"))
.collect::<Vec<_>>()
.join(", ");
let (is, it) = if legacy.len() == 1 {
("is", "that field")
} else {
("are", "those fields")
};
// Where the scope field itself is the casualty, saying "scoping travels on
// it" would be exactly backwards. That needs something else on the node to
// have written `corpus_scope` as text first, but the run must describe the
// state it is actually in.
let scoping = if legacy
.iter()
.any(|field| field == catalog::CORPUS_SCOPE_FIELD)
{
format!(
"This catalog holds the corpus-scope field `{scope}` as text too, so NO exactly \
matchable scope remains: a scoped sweep of an excluded file's catalog documents can \
match nothing, or — on a single-token prefix — a sibling corpus's. Reindex before \
relying on exclusions",
scope = catalog::CORPUS_SCOPE_FIELD,
)
} else {
format!(
"corpus scoping travels on the keyword `{scope}` field that every catalog document \
this build writes carries",
scope = catalog::CORPUS_SCOPE_FIELD,
)
};
format!(
"autoindex: the global `{index}` was created by an older build — {named} {is} mapped as \
text, and Elasticsearch cannot change a field's type in place. The run CONTINUES: every \
other catalog field was installed as declared, and {scoping}. Documents an older build \
left behind keep the legacy type, so a scoped sweep can still miss them — to retire \
{it}, reindex `{index}` into an index created with the current mapping (fresh index with \
the keyword mapping, `_reindex` into it, then swap)"
)
}
/// Pull the field name out of an ES `field [X] already exists as [text], …`
/// mapper conflict. `None` for any other error, so unrelated failures pass
/// through untouched.
fn legacy_text_field_in_conflict(msg: &str) -> Option<String> {
let head = &msg[..msg.find("already exists as [text]")?];
let open = head.rfind("field [")? + "field [".len();
let close = open + head[open..].find(']')?;
Some(head[open..close].to_string())
}
#[cfg(test)]
mod catalog_mapping_conflict_tests {
use super::{legacy_catalog_mapping_warning, legacy_text_field_in_conflict};
#[test]
fn the_conflicting_field_is_pulled_out_of_the_mapper_exception() {
let raw = "PUT /autoindex-catalog/_mapping failed: 400 Bad Request \
field [prefix] already exists as [text], cannot add [keyword]";
assert_eq!(
legacy_text_field_in_conflict(raw).as_deref(),
Some("prefix")
);
}
#[test]
fn a_different_legacy_text_field_is_named() {
// Not just prefix: a fully-dynamic legacy catalog conflicts on whatever
// field the server checks first (e.g. doc_kind).
let raw = "field [doc_kind] already exists as [text], cannot add [keyword]";
assert_eq!(
legacy_text_field_in_conflict(raw).as_deref(),
Some("doc_kind")
);
}
/// If the scope field itself is what the catalog holds as text, the warning
/// must not go on claiming scoping "travels on" it. Nothing autoindex has
/// ever written can put a catalog in that state, but a stray document write
/// into the shared index can — which is exactly how #755's own repro
/// manufactures a legacy `prefix`.
#[test]
fn a_legacy_scope_field_is_not_described_as_carrying_the_scope() {
let warning = legacy_catalog_mapping_warning(
"autoindex-catalog",
&[crate::catalog::CORPUS_SCOPE_FIELD.to_string()],
);
assert!(
warning.contains("NO exactly matchable scope remains"),
"must say the scope is gone, not that it travels on the lost field: {warning}"
);
assert!(
!warning.contains("corpus scoping travels on"),
"must not claim the dropped field carries the scope: {warning}"
);
assert!(
warning.contains("_reindex"),
"must still name the way out: {warning}"
);
}
#[test]
fn unrelated_mapping_errors_are_not_read_as_a_legacy_conflict() {
// A 503 must abort the run, so it must not look like a droppable field.
let raw = "PUT /autoindex-catalog/_mapping failed: 503 unavailable";
assert_eq!(legacy_text_field_in_conflict(raw), None);
}
#[test]
fn the_warning_names_every_legacy_field_the_scope_field_and_the_reindex() {
let warning = legacy_catalog_mapping_warning(
"autoindex-catalog",
&["prefix".to_string(), "doc_kind".to_string()],
);
assert!(
warning.contains("`prefix`") && warning.contains("`doc_kind`"),
"must name every tolerated field: {warning}"
);
assert!(
warning.contains("older build")
&& warning.contains("run CONTINUES")
&& warning.contains("_reindex"),
"must say what happened and how to retire the legacy fields: {warning}"
);
assert!(
warning.contains(crate::catalog::CORPUS_SCOPE_FIELD),
"must name the field corpus scoping moved to: {warning}"
);
}
}
/// Project the current inventory onto a committed plan.
///
/// Pure by design and deliberately shared: `--dry-run` prints exactly the plan
/// the real reconcile would act on, because it is produced by this same call
/// rather than by a parallel implementation that could drift away from it.
///
/// The scan itself obeys the same two policies the legacy phase A does. It runs
/// inside the run's own pool, because `--workers` has to bound the CPU-bound
/// phase for the knob to mean anything (#240 §2), and it opens a per-file
/// progress guard, because a file this route touches must not drop out of the
/// progress denominator (#241). Run-local PDF artifact reuse is deliberately
/// disabled here: the generated route publishes from its own sealed snapshot
/// and never reaches the legacy phase B, so a retained artifact could never be
/// replayed (#248).
fn project_reconcile_plan(
inventory: &content::Inventory,
base_plan: &Plan,
cfg: &IndexCfg,
state_dir: &Path,
pr: &Progress,
meter: &estimate::Meter,
tally: &ScanTally,
) -> Result<Plan> {
let budget = extract::pdf::ExtractionSpoolBudget::new(0, 0);
let ctx = PhaseAContext {
state_dir,
budget: &budget,
capacity_warning: None,
progress: pr,
meter,
tally,
};
pr.phase(
"scan",
inventory.files.len() as u64,
inventory.files.iter().map(|file| file.size).sum(),
);
let stub_matcher =
GlobMatcher::compile(&cfg.stub_globs, "--stub").expect("validated at startup");
let scans: Vec<FileScan> = crate::pool::install(|| {
use rayon::prelude::*;
inventory
.files
.par_iter()
.zip(inventory.keys.par_iter())
.zip(inventory.digests.par_iter())
.map(|((file, content_id), digest)| {
let _in_flight = pr.file(&file.rel, file.size);
// Incremental re-index fast path: a file whose content is
// byte-identical to the committed generation (its content_id is
// present AND its freshly-hashed digest matches the committed
// one) needs no fresh scan — `reconcile_plan` carries the
// committed assignment forward untouched. The tree-sitter parse
// is the dominant per-file cost, so skipping it turns an
// unchanged re-index from O(corpus) into O(changed). Correctness
// authority is the identical digest check in `reconcile_plan`:
// if this ever skipped a *changed* file, that fast path declines
// and the run fails closed on empty sketches rather than
// carrying stale docs forward.
let unchanged = base_plan
.files
.get(content_id.as_str())
.and_then(|o| o.content_digest.as_deref())
== Some(digest.as_str());
// #929: a file a refused dataset already cost is projected by
// content identity alone (`reconcile_plan` carries its junk
// entry forward), so it needs no fresh parse either.
let refused = base_plan
.refused_datasets
.iter()
.any(|refusal| refusal.file_keys.binary_search(content_id).is_ok());
if unchanged || refused {
return FileScan {
sniffed: None,
sketches: Vec::new(),
junk: None,
pdf_spool: None,
pdf_spool_fallbacks: Vec::new(),
};
}
scan_file(
&file.path,
file.size,
digest,
&ctx,
cfg.sample,
cfg.max_file_bytes,
stub_matcher.matches(&file.rel),
)
})
.collect()
});
note_worker_address_space_cap(pr);
let rebuild = incremental_schema_rebuild_command(cfg, state_dir);
reconcile_plan::reconcile_plan(inventory, base_plan, scans, cfg.sample, &rebuild)
}
/// The command a per-file schema refusal tells the operator to run.
///
/// A new `--state-dir` and a new `--prefix` are both required: the watcher's
/// journal owns the current pair, and `preflight` refuses a different prefix
/// in that directory. The destination sits beside the live state dir so the
/// watcher can keep running until the operator stops it. Every flag that
/// changes what gets indexed is carried by [`legacy_rebuild_argv`].
fn incremental_schema_rebuild_command(cfg: &IndexCfg, state_dir: &Path) -> String {
let rebuild_dir = format!("{}-reindex", state_dir.display());
let rebuild_prefix = format!("{}-reindex", cfg.prefix);
legacy_rebuild_argv(cfg, Path::new(&rebuild_dir), &rebuild_prefix)
.iter()
.map(|arg| quote_shell(arg))
.collect::<Vec<_>>()
.join(" ")
}
/// Shell-quote one argv element. Safe characters are the same set
/// `catalog::shell_quote` uses; that helper is private to its module.
fn quote_shell(s: &str) -> String {
if s.is_empty() {
return "''".to_string();
}
let safe = s
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '-' | ':' | '\\'));
if safe {
s.to_string()
} else {
format!("'{}'", s.replace('\'', "'\\''"))
}
}
/// Code/AST coverage for one corpus: how much of what a person would call
/// "the source code" actually reached the index.
///
/// This exists because success looked identical to total loss. #294 junked
/// EVERY source file on the durable `--no-graph` path, and the run still
/// printed
///
/// ```text
/// xerj-done ok=true exit=3 reason=completed-with-junk wall=0.6s files=4 records=1 generation=1
/// ```
///
/// over a corpus of three source files and one `.md` — the same line a healthy
/// one-prose-file corpus prints. `records` counts records, not families, so
/// nothing on that line could distinguish "small corpus" from "the entire code
/// half is gone". These three counters make that state unrepresentable: a run
/// whose `code_files` is non-zero while `code_files_indexed` is zero can never
/// again print the same terminal line as a healthy one, on either path.
///
/// Counted per FILE, not per record, and derived from the same durable
/// artifacts the catalog is projected from (the plan's family strings plus the
/// per-file record counts), so a resumed run reports the corpus it holds rather
/// than the slice this invocation happened to touch.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CodeCoverage {
/// Source files classified into `Family::Code`, junked ones included.
pub files: u64,
/// …of those, the ones that produced at least one indexed record.
pub indexed: u64,
/// …of those, the ones that produced none.
pub junked: u64,
}
impl CodeCoverage {
/// Both call sites hold a catalog FORMAT string, which is the plan's
/// family (`Family::as_str`) plus the `(gzip)` suffix `format_str` and
/// `assignment_format` append — match the family, not the compression.
fn is_code_format(format: &str) -> bool {
format.strip_suffix("(gzip)").unwrap_or(format) == Family::Code.as_str()
}
/// Count one file the run classified as `format` and which produced
/// `records` indexed records. Non-code files are ignored, so both paths can
/// feed this their whole file list without pre-filtering.
pub fn observe(&mut self, format: &str, records: u64) {
if !Self::is_code_format(format) {
return;
}
self.files += 1;
if records > 0 {
self.indexed += 1;
} else {
self.junked += 1;
}
}
/// The terminal-line and run-document fields, in a fixed order. One
/// definition, so the legacy and generated paths cannot drift into
/// spelling the same measurement differently.
pub fn fields(&self) -> [(&'static str, u64); 3] {
[
("code_files", self.files),
("code_files_indexed", self.indexed),
("code_files_junked", self.junked),
]
}
/// The one state that is always a defect: source code was found, and none
/// of it reached the index. Cheap to compute and worth a sentence, because
/// the counters alone still need a reader who knows to look at them.
pub fn warning(&self) -> Option<String> {
(self.files > 0 && self.indexed == 0).then(|| {
format!(
"warning: {} source-code file(s) were detected and NONE produced an indexed \
record — code search over this corpus will return nothing. Check the catalog's \
file documents (doc_kind=file, status=indexed, records=0) before trusting \
this index.",
self.files
)
})
}
}
/// 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.
///
/// It carries **no corpus scope**, and it must not grow one (#905). `path` is a
/// logical path inside a corpus rather than a node-unique key and
/// `autoindex-catalog` is global across every corpus on the node, so this query
/// on its own reaches a SIBLING corpus's `status: duplicate` documents at the
/// same path. It stays a candidate FILTER: [`sweep_duplicate_aliases`] decides
/// per hit which corpus each candidate belongs to and deletes only this
/// corpus's, by `_id`.
///
/// A scope filter here instead would have been wrong in the other direction:
/// this sweep exists to reach documents whose ids follow HISTORICAL identity
/// schemes, and the oldest of those (pre-#416) carry no corpus field and no
/// prefix in their `_id` — a server-side `corpus_scope`/`prefix` term would
/// simply stop matching them and strand them. See
/// [`catalog_doc_corpus`] for how attribution is decided instead.
fn alias_sweep_query(paths: &[&str]) -> Value {
json!({
"bool": {
"filter": [
{"term": {"status": "duplicate"}},
{"terms": {"path": paths}}
]
}
})
}
/// Read a string field out of a search hit's `_source`.
///
/// Raw `_source`, never a server-side `term`: the whole point of the per-hit
/// re-check both catalog sweeps do is that the catalog's MAPPING cannot be
/// trusted to make a `term` byte-exact (#890).
fn source_str<'a>(hit: &'a Value, field: &str) -> Option<&'a str> {
hit.pointer("/_source")
.and_then(|source| source.get(field))
.and_then(Value::as_str)
}
/// Which corpus a catalog hit belongs to, decided from the document itself
/// (#905).
///
/// `autoindex-catalog` is global across every corpus on the node, so before
/// deleting anything out of it a sweep has to answer this. Three layers of
/// evidence, newest first, because the catalog outlives releases and a
/// document written years of release-numbers ago carries less of it:
///
/// 1. `catalog::CORPUS_SCOPE_FIELD` — #755 (v1.0.0-rc.72), `keyword` on every
/// catalog by construction, since no earlier release ever wrote the field.
/// 2. `prefix` — #737 (rc.68). Read from raw `_source`, never term-queried: on
/// a catalog an rc.15..rc.67 build touched it is dynamically-inferred
/// `text`, and that is exactly the #890 over-match.
/// 3. the `_id` — #416 (rc.57) put the corpus prefix into it
/// (`file-alias:{prefix}:{body}`). The prefix is a `sanitize_slug` output,
/// so it holds no `:`, and the body is `ids::doc_id`'s 32 hex characters,
/// which hold none either: the split is unambiguous.
///
/// Below that — an alias document written by rc.10..rc.56 — there is no corpus
/// evidence anywhere in the document, and [`CatalogDocCorpus::Anonymous`] says
/// so rather than guessing. What the caller does with that is the caller's
/// decision to make out loud; see [`sweep_duplicate_aliases`].
enum CatalogDocCorpus<'a> {
/// The document names its corpus, in a field or in its `_id`.
Named(&'a str),
/// The document names no corpus at all.
Anonymous,
}
fn catalog_doc_corpus<'a>(id: &'a str, hit: &'a Value) -> CatalogDocCorpus<'a> {
if let Some(scope) = source_str(hit, catalog::CORPUS_SCOPE_FIELD) {
return CatalogDocCorpus::Named(scope);
}
if let Some(prefix) = source_str(hit, "prefix") {
return CatalogDocCorpus::Named(prefix);
}
if let Some((prefix, _)) = id
.strip_prefix(catalog::ALIAS_ID_PREFIX)
.and_then(|body| body.split_once(':'))
{
return CatalogDocCorpus::Named(prefix);
}
CatalogDocCorpus::Anonymous
}
/// Delete THIS corpus's `status: duplicate` catalog documents at `paths`
/// (#905).
///
/// [`alias_sweep_query`] selects the candidates and cannot be scoped (see its
/// comment); the scope is applied here, per hit, by [`catalog_doc_corpus`].
/// A candidate the query returns that belongs to a sibling corpus is left
/// alone — an unscoped `_delete_by_query` took it, which is the data loss this
/// exists to stop.
///
/// THE ANONYMOUS CASE, DECIDED ON PURPOSE. A pre-#416 alias document names no
/// corpus, so "is this ours?" cannot be read off it. Neither blanket answer is
/// acceptable: deleting every anonymous hit keeps the whole cross-corpus reach
/// for exactly the catalogs most likely to hold such documents, and keeping
/// every anonymous hit strands the stale alias this sweep exists to remove —
/// the trade the issue warned a naive scope filter would silently make.
///
/// So neither is taken. The caller passes the ids this corpus ITSELF would
/// have written under the pre-#416 scheme, reconstructed from its own frozen
/// plan and current inventory by
/// [`catalog::unprefixed_duplicate_file_ids`] — the same reconstruct-the-id
/// move #739 already makes for legacy `file:`/`file-alias:` documents. An
/// anonymous hit whose `_id` is one of those is ours and is deleted; any other
/// anonymous hit is left in place and NAMED, so an operator can see the one
/// residual rather than discover it in `xerj autoindex map`.
///
/// The residual is bounded and it is honest to state it: a pre-#416 id is
/// `doc_id("duplicate-file", file_key, path|path_id)` with no corpus in it, so
/// two corpora holding a byte-identical file at the same logical path wrote
/// the SAME `_id` — one document, whichever ran last. Deleting it on a
/// reconstructed-id match therefore removes a document that was never uniquely
/// the sibling's, and both corpora rewrite their own prefix-scoped alias on
/// their next run. What is NOT claimed: that this recovers every pre-#416
/// alias. One whose `file_key` changed since (its content was edited) cannot be
/// reconstructed, and it is reported stranded rather than deleted.
fn sweep_duplicate_aliases(
es: &Es,
prefix: &str,
paths: &[&str],
own_unprefixed_ids: &HashSet<String>,
stranded: &mut Vec<String>,
) -> Result<()> {
let query = alias_sweep_query(paths);
let label = format!(
"corpus={prefix}, status=duplicate, {} path(s) from `{}`",
paths.len(),
paths.first().copied().unwrap_or("")
);
delete_catalog_hits_where(es, &query, &label, |id, hit| {
match catalog_doc_corpus(id, hit) {
CatalogDocCorpus::Named(owner) => owner == prefix,
CatalogDocCorpus::Anonymous if own_unprefixed_ids.contains(id) => true,
CatalogDocCorpus::Anonymous => {
stranded.push(match source_str(hit, "path") {
Some(path) => format!("{path} ({id})"),
None => id.to_string(),
});
false
}
}
})
}
/// What a run says about the alias documents the sweep deliberately did not
/// delete.
///
/// Loud for the same reason [`alias_sweep_notes`] is: the cost is real. A
/// stale pre-#416 alias left in the catalog makes `xerj autoindex map` report
/// a duplicate path twice, and the operator can only act on it if they are
/// told. It is NOT an error — the alternative was deleting a document this run
/// cannot prove is its own, and this file's whole subject is that a delete is
/// not recoverable.
///
/// Same listing cap and one-note-per-line rule as every other human-facing
/// listing here ([`REFUSAL_LIST_CAP`], [`progress::Progress::note`]).
fn stranded_alias_notes(stranded: &[String]) -> Vec<String> {
if stranded.is_empty() {
return Vec::new();
}
let mut notes = vec![format!(
"note: {} catalog alias document(s) at this corpus's duplicate path(s) carry no corpus \
in the document and none in their `_id` either — the id scheme v1.0.0-rc.10..rc.56 \
wrote — and none matched an id this corpus would have written, so they were LEFT IN \
PLACE rather than deleted: another corpus on this node may own them. `xerj autoindex \
map` can therefore report a duplicate path twice. Reindex `{}` to retire them.",
stranded.len(),
catalog::CATALOG_INDEX,
)];
notes.extend(
stranded
.iter()
.take(REFUSAL_LIST_CAP)
.map(|doc| format!(" alias left in place: {doc}")),
);
let remaining = stranded.len().saturating_sub(REFUSAL_LIST_CAP);
if remaining > 0 {
notes.push(format!(" … and {remaining} more"));
}
notes
}
/// 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";
/// `xerj-done` reason when a graph-path resume kept a frozen plan and files
/// now on disk are not in it (#2076).
///
/// Distinct from `completed-with-junk`. Those files are content the plan
/// predates, not unusable input, and counting them as junk made a resume look
/// like an ordinary successful-with-junk run. A file that fits a frozen
/// dataset is absorbed in place (#2314). A file that needs a new dataset is
/// not: dataset identity and graph anchors stay put, and `--fresh` rebuilds
/// the plan in place to include it. `--no-graph` reconciles both.
const STALE_RESUME_PLAN_REASON: &str = "stale-resume-plan";
/// `xerj-done` reason when a graph-path rerun removed documents for files
/// that left the folder (#2314).
///
/// Exit 3, not 0: a removal used to look like a no-op resume while the
/// documents stayed live, and exit 0 is what that bug printed. The index
/// matches the folder afterwards — this is success, the same way junk is —
/// and the next unchanged rerun is exit 0. Distinct from
/// `completed-with-junk`: the files were usable, they are gone.
const FILES_REMOVED_REASON: &str = "files-removed";
/// Catalog / plan status for a file the frozen resume plan does not cover.
const STALE_RESUME_PLAN_STATUS: &str = "stale-plan";
/// Durable reason stored on the plan and therefore in the catalog.
///
/// The phrase `not in the frozen resume plan` is the legacy marker: journals
/// written before #2076 used status `skipped` and this sentence, and a later
/// resume still has to recognise them.
const STALE_RESUME_PLAN_FILE_REASON: &str =
"skipped because the resumed plan is stale: not in the frozen resume plan, so nothing was \
published for it. Re-run with --fresh to rebuild the plan in place and include it (ids stay \
idempotent), or index it under a new --state-dir and --prefix";
pub(crate) fn is_stale_resume_skip(junk: &JunkFile) -> bool {
junk.status == STALE_RESUME_PLAN_STATUS || junk.reason.contains("not in the frozen resume plan")
}
/// How many appeared-file paths the stale-resume-plan summary names.
///
/// The rest are a count. Five is enough to see what the resume left out
/// without turning the summary into a directory listing (#2372). The mid-run
/// note still lists up to [`REFUSAL_LIST_CAP`].
const STALE_RESUME_SUMMARY_CAP: usize = 5;
/// Recovery sentence shared by the headline, the path list, and the JSON field.
///
/// One sentence, so the summary that names the paths also says `--fresh`
/// right there (#2372).
const STALE_RESUME_SUMMARY_ACTION: &str =
"Re-run with --fresh to rebuild the plan in place and include them (ids stay idempotent)";
/// Relative paths the frozen resume plan did not cover, in summary order.
///
/// Same predicate as the `skipped_appeared` count ([`is_stale_resume_skip`]),
/// so a legacy journal that stored these as status `skipped` is listed too.
/// Sorted so two runs over the same folder name the same paths. The count
/// stays the full length; this vec is not capped.
fn stale_resume_appeared_paths(junk: &[&JunkFile]) -> Vec<String> {
let mut paths: Vec<&str> = junk
.iter()
.filter(|jf| is_stale_resume_skip(jf))
.map(|jf| jf.rel.as_str())
.collect();
paths.sort_unstable();
paths.into_iter().map(str::to_string).collect()
}
/// Human lines for the stale-resume-plan summary.
///
/// The headline stays one line. These sit under it and name the files,
/// because a count alone sent an agent back to `--help` to find out what was
/// skipped (#2372). Empty when nothing appeared, so a clean run's summary is
/// unchanged.
fn stale_resume_summary_lines(paths: &[String]) -> Vec<String> {
if paths.is_empty() {
return Vec::new();
}
let shown = paths.len().min(STALE_RESUME_SUMMARY_CAP);
let rest = paths.len() - shown;
let mut lines = vec![format!(
"not indexed — {} appeared after the resume plan was frozen. {STALE_RESUME_SUMMARY_ACTION}:",
estimate::count_phrase(paths.len() as u64, "file", "files")
)];
for path in &paths[..shown] {
lines.push(format!(" {path}"));
}
if rest > 0 {
lines.push(format!(" … and {rest} more"));
}
lines
}
/// Additive summary fields for the same list.
///
/// `skipped_appeared` stays the count and is not in this map. Present only
/// when files appeared. `skipped_appeared_not_listed` is present only when
/// the list was capped, so a reader that finds it knows the summary did not
/// name every path.
fn stale_resume_summary_json(paths: &[String]) -> Map<String, Value> {
if paths.is_empty() {
return Map::new();
}
let shown = paths.len().min(STALE_RESUME_SUMMARY_CAP);
let mut fields = Map::new();
fields.insert("skipped_appeared_files".into(), json!(&paths[..shown]));
let rest = paths.len() - shown;
if rest > 0 {
fields.insert("skipped_appeared_not_listed".into(), json!(rest));
}
fields.insert(
"skipped_appeared_action".into(),
json!(STALE_RESUME_SUMMARY_ACTION),
);
fields
}
#[cfg(test)]
mod stale_resume_summary_tests {
use super::{
is_stale_resume_skip, stale_resume_appeared_paths, stale_resume_summary_json,
stale_resume_summary_lines, JunkFile, STALE_RESUME_PLAN_FILE_REASON,
STALE_RESUME_PLAN_STATUS, STALE_RESUME_SUMMARY_ACTION, STALE_RESUME_SUMMARY_CAP,
};
fn junk(rel: &str, status: &str, reason: &str) -> JunkFile {
JunkFile {
file_key: rel.into(),
rel: rel.into(),
format: "unknown".into(),
status: status.into(),
reason: reason.into(),
bytes: 1,
}
}
fn appeared(rel: &str) -> JunkFile {
junk(rel, STALE_RESUME_PLAN_STATUS, STALE_RESUME_PLAN_FILE_REASON)
}
#[test]
fn nothing_appeared_adds_no_summary() {
let ordinary = junk("notes.bin", "junk", "binary content");
let refs = [&ordinary];
assert!(stale_resume_appeared_paths(&refs).is_empty());
assert!(stale_resume_summary_lines(&[]).is_empty());
assert!(stale_resume_summary_json(&[]).is_empty());
}
#[test]
fn one_file_is_named_and_fresh_is_on_the_same_summary() {
let file = appeared("notes/new file.md");
let paths = stale_resume_appeared_paths(&[&file]);
assert_eq!(paths, vec!["notes/new file.md".to_string()]);
let lines = stale_resume_summary_lines(&paths);
assert_eq!(lines.len(), 2, "{lines:?}");
assert!(lines[0].contains("1 file"), "{lines:?}");
assert!(lines[0].contains("--fresh"), "{lines:?}");
assert!(lines[0].contains(STALE_RESUME_SUMMARY_ACTION), "{lines:?}");
assert_eq!(lines[1], " notes/new file.md");
assert!(
!lines.iter().any(|line| line.contains("… and")),
"{lines:?}"
);
let doc = stale_resume_summary_json(&paths);
assert_eq!(doc["skipped_appeared_files"], serde_json::json!(paths));
assert!(doc.get("skipped_appeared_not_listed").is_none(), "{doc:?}");
assert!(
doc["skipped_appeared_action"]
.as_str()
.unwrap()
.contains("--fresh"),
"{doc:?}"
);
assert!(doc.get("skipped_appeared").is_none(), "{doc:?}");
}
/// The summary names the first five paths, sorted, and counts the rest.
/// A legacy journal row (status `skipped`, the frozen-plan sentence) is
/// included; ordinary junk is not.
#[test]
fn the_summary_names_five_paths_and_counts_the_rest() {
let mut files: Vec<JunkFile> = ["m.md", "a.md", "q.md", "b.md", "z.md", "c.md", "d.md"]
.into_iter()
.map(appeared)
.collect();
files.push(junk(
"legacy.md",
"skipped",
"not in the frozen resume plan, so nothing was published",
));
files.push(junk("logo.png", "junk", "binary content (png)"));
let refs: Vec<&JunkFile> = files.iter().collect();
assert!(is_stale_resume_skip(&files[7]));
assert!(!is_stale_resume_skip(files.last().unwrap()));
let paths = stale_resume_appeared_paths(&refs);
assert_eq!(
paths,
vec![
"a.md",
"b.md",
"c.md",
"d.md",
"legacy.md",
"m.md",
"q.md",
"z.md",
]
);
let lines = stale_resume_summary_lines(&paths);
assert_eq!(lines.len(), STALE_RESUME_SUMMARY_CAP + 2, "{lines:?}");
assert!(lines[0].contains("8 files"), "{lines:?}");
assert!(lines[0].contains("--fresh"), "{lines:?}");
for (index, path) in paths.iter().take(STALE_RESUME_SUMMARY_CAP).enumerate() {
assert_eq!(lines[index + 1], format!(" {path}"));
}
assert_eq!(lines.last().unwrap(), " … and 3 more");
assert!(!lines.iter().any(|line| line.contains("q.md")), "{lines:?}");
let doc = stale_resume_summary_json(&paths);
assert_eq!(
doc["skipped_appeared_files"],
serde_json::json!(paths[..STALE_RESUME_SUMMARY_CAP])
);
assert_eq!(doc["skipped_appeared_not_listed"], 3);
assert_eq!(doc["skipped_appeared_action"], STALE_RESUME_SUMMARY_ACTION);
}
}
/// 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
/// legacy path publishes (`cli.rs` EXIT CODES, and CLAUDE.md's own indexing
/// workflow treats 3 as success). The generated path returned a flat `0`, which
/// silently downgraded that signal for `--no-graph`. Both inputs come from the
/// committed generation's own run document, so a no-op re-run over a corpus
/// that still contains junk reports 3 again instead of flapping to 0.
fn generated_exit_code(summary: &Value) -> i32 {
let count = |field: &str| summary.get(field).and_then(Value::as_u64).unwrap_or(0);
// #2336: every PDF failed because the worker process could not start.
// Exit 3 would call that success. The field is absent on every other run.
if count("pdf_worker_unavailable") > 0 {
return 1;
}
if count("junk_records_total") > 0 || count("files_junk") > 0 {
3
} else {
0
}
}
/// The FIRST line of a finished run's human summary on stdout (#1843).
///
/// Exit 3 is success, but an agent that sees a non-zero exit reads failure
/// unless something it reads first says otherwise. The `xerj-done` line on
/// stderr already carries `ok=true`, yet it is the LAST line of a long progress
/// stream and the summary on stdout opened with a timing line that never
/// mentioned the exit code at all. A finished run leads with one line that
/// starts `ok:` and names the exit code in words; exit 3 also says what was
/// recorded and where to look, so junk stays visible. A family-wide PDF
/// worker startup failure (#2336) leads with `not ok:` and exit 1. So does an
/// index that does not cover the folder because a stale resume plan skipped
/// files (#2411): exit 3, `ok=false`, and the line says the skipped files are
/// not searchable.
pub(crate) fn outcome_headline(
code: i32,
junk_files: u64,
junk_records: u64,
alias_sweep_failed: bool,
stale_plan_files: u64,
pdf_worker_unavailable: Option<u64>,
files_removed: u64,
) -> String {
if let Some(n) = pdf_worker_unavailable.filter(|n| *n > 0) {
return format!(
"not ok: the isolated PDF parser could not start for {}, so no PDF text was indexed. \
Other files in this run were still indexed. Exit 1 ({PDF_WORKER_UNAVAILABLE_REASON})",
estimate::count_phrase(n, "PDF file", "PDF files")
);
}
if code != 3 {
return format!("ok: indexed and searchable (exit {code}, completed)");
}
if stale_plan_files > 0 {
let files = estimate::count_phrase(stale_plan_files, "file", "files");
// #2411: `not ok:`, not `ok:`. The run finished and exit 3 is not an
// error, but the index does not cover the folder, and the `ok:` prefix
// was read as "this folder is searchable" by a caller that then saw
// four of its five files missing from results.
let mut line = format!(
"not ok: the index does not cover this folder — exit 3 \
({STALE_RESUME_PLAN_REASON}): {files} skipped because the resumed plan is stale and \
were not indexed, so they are not searchable. {STALE_RESUME_SUMMARY_ACTION}"
);
if junk_files > 0 || junk_records > 0 {
let mut recorded = Vec::new();
if junk_files > 0 {
recorded.push(estimate::count_phrase(junk_files, "file", "files"));
}
if junk_records > 0 {
recorded.push(estimate::count_phrase(junk_records, "record", "records"));
}
line.push_str(&format!(
". Also recorded as junk: {}",
recorded.join(" and ")
));
}
if alias_sweep_failed {
line.push_str(
". The catalog's duplicate-alias cleanup could not run; rerun the same command \
once the server condition clears",
);
}
return line;
}
if alias_sweep_failed {
return format!(
"ok: indexed and searchable — exit 3 ({ALIAS_SWEEP_FAILED_REASON}) is SUCCESS, not \
an error: the corpus is indexed and the journal committed; only the catalog's \
duplicate-alias cleanup could not run, so rerun the same command once the server \
condition clears"
);
}
if files_removed > 0 {
let files = estimate::count_phrase(files_removed, "file", "files");
let mut line = format!(
"ok: indexed and searchable — exit 3 ({FILES_REMOVED_REASON}) is SUCCESS, not an \
error: removed documents for {files} that no longer exist in the folder"
);
if junk_files > 0 || junk_records > 0 {
let mut recorded = Vec::new();
if junk_files > 0 {
recorded.push(estimate::count_phrase(junk_files, "file", "files"));
}
if junk_records > 0 {
recorded.push(estimate::count_phrase(junk_records, "record", "records"));
}
line.push_str(&format!(
". Also recorded as junk: {}",
recorded.join(" and ")
));
}
return line;
}
let mut recorded = Vec::new();
if junk_files > 0 {
recorded.push(estimate::count_phrase(junk_files, "file", "files"));
}
if junk_records > 0 {
recorded.push(estimate::count_phrase(junk_records, "record", "records"));
}
let recorded = if recorded.is_empty() {
"some input".to_string()
} else {
recorded.join(" and ")
};
format!(
"ok: indexed and searchable — exit 3 (completed-with-junk) is SUCCESS, not an error: \
{recorded} recorded as junk (skipped, never fatal; `xerj autoindex map` lists them)"
)
}
/// Terminal progress line for a run that ends on the generated `--no-graph`
/// path.
///
/// Every exit closes the stream itself (#241). `Ticker::drop` reports
/// `ok=false` for a run that never called `finish`, so a generated run that
/// merely returned would print an aborted line straight after a successful
/// commit — the one place the two landed changes could contradict each other.
/// Exit 3 is success ("completed, some input was unusable"), so it is spelled
/// out in words rather than left as a bare number.
fn finish_generated_progress(pr: &Progress, code: i32, summary: &Value, skipped_dataless: u64) {
let count = |field: &str| summary.get(field).and_then(Value::as_u64).unwrap_or(0);
// Read back from the committed generation's own run document, exactly like
// every other number on this line — a resumed or no-op run therefore
// reports the corpus's coverage, not an empty one.
let coverage = CodeCoverage {
files: count("code_files"),
indexed: count("code_files_indexed"),
junked: count("code_files_junked"),
};
// Before `finish`: the terminal line is the last thing this stream emits.
if let Some(warning) = coverage.warning() {
pr.note(&warning);
}
// #2370: a family that was entirely or mostly junked is a warning, not a
// count the reader has to notice. `warn` still prints under `--quiet`.
let family_lines = family_junk::lines_from_summary(summary);
for line in &family_lines {
pr.warn(line);
}
let mut extra = vec![
("files", count("files_indexed")),
("records", count("records_total")),
("generation", count("generation")),
];
// #929: present only when a dataset was refused, so the terminal line of a
// run that lost nothing is unchanged — and one that did cannot print the
// same line as a whole corpus.
if count("datasets_refused") > 0 {
extra.push(("datasets_refused", count("datasets_refused")));
extra.push(("files_refused", count("files_refused")));
}
// #944: present only when the run re-sent items the server answered 429,
// so a run that fought back-pressure cannot print the same line as one
// that did not.
if count("bulk_retries") > 0 {
extra.push(("bulk_retries", count("bulk_retries")));
}
// #955: present only when the server refused a request as too large and
// the run halved it — a node with a tight `max_actions_per_bulk` or
// `max_body_bytes` is worth knowing about even when the run finished.
if count("bulk_splits") > 0 {
extra.push(("bulk_splits", count("bulk_splits")));
}
// #2058: present only when this run left out dataless placeholders, so a
// corpus with none prints the line it always did.
if skipped_dataless > 0 {
extra.push(("skipped_dataless", skipped_dataless));
}
if !family_lines.is_empty() {
extra.push(("family_junk_warnings", family_lines.len() as u64));
}
extra.extend(coverage.fields());
note_worker_address_space_cap(pr);
let pdf_down = count("pdf_worker_unavailable");
if pdf_down > 0 {
pr.note(&pdf_worker_unavailable_note(pdf_down));
extra.push(("pdf_worker_unavailable", pdf_down));
pr.finish(false, 1, PDF_WORKER_UNAVAILABLE_REASON, &extra);
return;
}
pr.finish(
true,
code,
if code == 3 {
"completed-with-junk"
} else {
"completed"
},
&extra,
);
}
/// `xerj-done` reason when every PDF failed because the isolated parser
/// process could not start (#2336). Exit 1, `ok=false`. Other files in the
/// same run may already be indexed; a corrupt PDF that the worker did parse
/// stays exit 3.
const PDF_WORKER_UNAVAILABLE_REASON: &str = "pdf-worker-unavailable";
fn pdf_worker_unavailable_note(count: u64) -> String {
format!(
"warning: the isolated PDF parser could not start for {}, so no PDF text was indexed. \
Other files in this run were still indexed. This is a worker startup failure (process \
or resource limits). Exit 1 ({PDF_WORKER_UNAVAILABLE_REASON}).",
estimate::count_phrase(count, "PDF file", "PDF files")
)
}
#[cfg(unix)]
fn note_worker_address_space_cap(progress: &Progress) {
if let Some(warning) = extract::rlimit::take_address_space_cap_warning() {
progress.note(warning);
}
}
#[cfg(not(unix))]
fn note_worker_address_space_cap(_progress: &Progress) {}
fn inventory_size_map(inventory: &content::Inventory) -> HashMap<&str, u64> {
inventory
.keys
.iter()
.zip(inventory.files.iter())
.map(|(key, file)| (key.as_str(), file.size))
.collect()
}
/// Print a neural embedding-time estimate when the server measured one.
///
/// Best-effort: a failed identity read does not fail the run (the later pin
/// still does, on a real semantic ingest) and never invents a rate. Zero
/// source bytes print nothing, including a lexical corpus.
fn note_neural_ingest_cost(
es: &Es,
source_bytes: u64,
kind: neural_cost::SourceBytes,
pr: &Progress,
) {
if source_bytes == 0 {
return;
}
let identity = match es.embedding_execution_identity() {
Ok(identity) => identity,
Err(error) => {
pr.note(&format!(
"embedding cost: could not read GET /v1/embedding/identity ({error}); no time estimate printed"
));
return;
}
};
if let Some(message) = neural_cost::note(&identity, source_bytes, kind) {
pr.note(&message);
}
}
fn recount_plan_file_counts(plan: &mut Plan) {
for dataset in &mut plan.datasets {
dataset.file_count = plan
.files
.values()
.filter(|assignment| {
assignment
.assignments
.iter()
.any(|(_, slug)| *slug == dataset.slug)
})
.count();
}
}
/// A schema refusal from [`reconcile_plan`], which tells the operator to
/// rebuild. On the graph path that rebuild is `--fresh` (a new dataset), not
/// a permanent junk row, so these files stay unplanned and the stale-plan
/// note names `--fresh`.
fn schema_evolution_junk(junk: &JunkFile) -> bool {
junk.reason.contains("Stop the watcher and rebuild")
|| junk.reason.contains("no frozen dataset accepts")
|| junk.reason.contains("refusing ambiguous assignment")
|| junk.reason.contains("unsupported dataset/schema evolution")
}
/// Fold files that appeared after a graph plan was frozen into that plan
/// when they fit a dataset it already has (#2314).
///
/// A no-op resume (every key already planned or junk) does not call
/// [`project_reconcile_plan`], so the durable plan is not rewritten just
/// because the projection would re-order junk. Files that need a new dataset
/// are left unplanned: the stale-plan note still names `--fresh`.
fn absorb_compatible_additions(
plan: &mut Plan,
inventory: &content::Inventory,
cfg: &IndexCfg,
state_dir: &Path,
pr: &Progress,
meter: &estimate::Meter,
tally: &ScanTally,
) -> Result<bool> {
let unplanned = inventory.keys.iter().any(|key| {
!key.is_empty()
&& !plan.files.contains_key(key)
&& !plan.junk_files.iter().any(|junk| &junk.file_key == key)
});
if !unplanned {
return Ok(false);
}
let projected = match project_reconcile_plan(inventory, plan, cfg, state_dir, pr, meter, tally)
{
Ok(projected) => projected,
Err(error) => {
pr.note(&format!(
"autoindex: files added after the resume plan was frozen could not be absorbed \
({error:#}); re-run with --fresh to rebuild the plan in place"
));
return Ok(false);
}
};
let inventory_keys: HashSet<&str> = inventory.keys.iter().map(String::as_str).collect();
let mut changed = false;
for (key, assignment) in projected.files {
if !inventory_keys.contains(key.as_str())
|| plan.files.contains_key(&key)
|| plan.junk_files.iter().any(|junk| junk.file_key == key)
{
continue;
}
plan.files.insert(key, assignment);
changed = true;
}
for junk in projected.junk_files {
if !inventory_keys.contains(junk.file_key.as_str())
|| plan.files.contains_key(&junk.file_key)
|| plan
.junk_files
.iter()
.any(|existing| existing.file_key == junk.file_key)
|| schema_evolution_junk(&junk)
{
continue;
}
plan.junk_files.push(junk);
changed = true;
}
for (slug, specs) in projected.incremental_fields {
let dest = plan.incremental_fields.entry(slug).or_default();
for spec in specs {
if dest.iter().any(|existing| existing.name == spec.name) {
continue;
}
dest.push(spec);
changed = true;
}
}
if changed {
recount_plan_file_counts(plan);
}
Ok(changed)
}
/// Drop one live source out of a generation that is about to seal (#2314).
///
/// Returns false when `path` is not a canonical inventory file, so the caller
/// does not retry a failure it cannot attribute.
fn quarantine_changed_source(
plan: &mut Plan,
inventory: &mut content::Inventory,
path: &Path,
detail: &str,
) -> bool {
let Some(index) = inventory.files.iter().position(|file| file.path == path) else {
return false;
};
let key = inventory.keys[index].clone();
let format = plan
.files
.get(&key)
.map(|assignment| {
if assignment.gzip {
format!("{}(gzip)", assignment.family)
} else {
assignment.family.clone()
}
})
.unwrap_or_else(|| "unknown".into());
let file = inventory.files.remove(index);
inventory.keys.remove(index);
inventory.digests.remove(index);
plan.files.remove(&key);
plan.duplicate_files
.retain(|alias| alias.file_key != key && plan.files.contains_key(&alias.file_key));
let error = anyhow::anyhow!("{detail}");
plan.junk_files.push(changed_during_run_junk(
&key, &file.rel, &format, file.size, &error,
));
recount_plan_file_counts(plan);
true
}
#[allow(clippy::too_many_arguments)] // cutover threads the whole run context
fn begin_non_graph_generation(
es: &Es,
journal: &mut state::Journal,
state_dir: &Path,
cfg: &IndexCfg,
root_identity: &str,
inventory: &content::Inventory,
pr: &Progress,
plan: Plan,
// #1062: the run's `--label` Labeler, already constructed (and its
// question set already validated) before the walk began. Sealing is where
// the generated route decides records, so this is where the votes happen:
// one /_decide round trip per noul (per option, for a choice) per record,
// paid at ingest, never at idle.
labeler: Option<&label::Labeler>,
) -> Result<()> {
anyhow::ensure!(
cfg.no_graph,
"non-graph generation cutover requires --no-graph"
);
anyhow::ensure!(
journal.pending_sync.is_none(),
"cannot prepare over an existing pending generation"
);
if journal.committed_manifest.is_none() {
journal.sync_bootstrap_genesis()?;
}
let base = journal
.committed_manifest
.as_ref()
.context("generation cutover has no committed base")?
.clone();
let tx_id = format!("{}-g{}", journal.run_id, base.generation + 1);
let mut plan = plan;
// #2314: a file that changes between the hash and the seal is dropped and
// the seal is retried. The owned copy is what the generation publishes.
let mut sealed = content::Inventory {
files: inventory.files.clone(),
keys: inventory.keys.clone(),
digests: inventory.digests.clone(),
duplicates: inventory.duplicates.clone(),
// Skips are already on `plan`. Sealing must not see them as content.
unreadable: Vec::new(),
};
// #971: the prior committed generation's snapshot is the reuse source for
// sealing. A file whose content digest and preparation identity match its
// entry there is hardlinked instead of re-copied and re-extracted, so the
// snapshot pass of a one-file change costs O(changed), not O(corpus). An
// execution-less base (pre-execution journal) simply seals in full.
let prior_snapshot = base
.execution
.as_ref()
.map(|_| sync_executor::open_committed_snapshot(state_dir, &base))
.transpose()?;
let chunker_identity = prepared_records_identity(cfg)?;
// #2807: read the embedding identity before sealing, so preparation can
// size each record with the vectors the server will add. The same
// identity is pinned after the seal.
let semantic = plan
.datasets
.iter()
.any(|dataset| dataset.semantic_field.is_some());
let embedding_identity = if semantic {
let identity = es
.embedding_execution_identity()
.context("generation cutover could not pin the server embedding execution identity")?;
anyhow::ensure!(
identity.resumable,
"generation cutover requires a resumable embedding execution identity: {}",
identity
.non_resumable_reason
.as_deref()
.unwrap_or("the server did not provide an immutable identity")
);
Some(identity)
} else {
None
};
let vector_dims = embedding_identity
.as_ref()
.and_then(|identity| identity.dimensions);
let (snapshot, mut groups) = {
let mut prepared = None;
let mut groups_out = None;
// One file leaves per attempt, plus the successful seal.
let max_attempts = sealed.files.len().saturating_add(2).max(1);
for _attempt in 0..max_attempts {
let failing: Vec<(std::path::PathBuf, String)> = sealed
.files
.iter()
.zip(sealed.digests.iter())
.filter_map(|(file, digest)| {
let error = content::verify(&file.path, file.size, digest).err()?;
// A lock is not a content change. The snapshot reuses the
// previous generation's blob when the digest and size still
// match, without opening the file (#2352). Quarantining
// here would delete documents that are only temporarily
// unreadable. A lock whose size no longer matches falls
// through to the copy, which reports SourceChanged and is
// skipped on the next attempt.
if error
.downcast_ref::<content::SourceChanged>()
.is_some_and(|changed| changed.locked)
{
return None;
}
Some((file.path.clone(), format!("{error:#}")))
})
.collect();
let mut quarantined = false;
for (path, detail) in failing {
if quarantine_changed_source(&mut plan, &mut sealed, &path, &detail) {
quarantined = true;
pr.note(&format!(
"warning: {} changed while this run was reading it, so it was skipped \
({detail})",
path.display()
));
}
}
if quarantined {
continue;
}
// #1723: derive the content groups and check the plan's projection
// onto them BEFORE sealing. A plan that cannot be accepted used to
// be refused only after the whole corpus was sealed.
let groups = desired_content_groups(&base.groups, &plan, &sealed)?;
sync::preflight_plan_projection(&plan, &groups).with_context(|| {
format!(
"autoindex refused generation {} before sealing any file: the plan built \
from this walk does not project onto its own content groups, so every run \
over this input fails the same way, --fresh included. No snapshot was \
written and no remote data was changed. This is an autoindex defect for \
this corpus; please report it with this message",
base.generation + 1
)
})?;
let preparation_contract = preparation_contract_digest(cfg, &plan)?;
match sync_executor::create_prepared_snapshot_reporting(
state_dir,
&tx_id,
&sealed,
&plan,
&preparation_contract,
cfg.snapshot_max_bytes,
pr,
prior_snapshot.as_ref(),
&chunker_identity,
labeler,
vector_dims,
) {
Ok(snapshot) => {
prepared = Some(snapshot);
groups_out = Some(groups);
break;
}
Err(error) => {
let Some(changed) = error.downcast_ref::<content::SourceChanged>() else {
return Err(error);
};
let path = changed.path.clone();
let detail = changed.detail.clone();
if !quarantine_changed_source(&mut plan, &mut sealed, &path, &detail) {
return Err(error);
}
pr.note(&format!(
"warning: {} changed while this run was sealing it, so it was skipped \
({detail})",
path.display()
));
}
}
}
let snapshot = prepared.context(
"autoindex could not seal a snapshot after skipping files that changed during the \
run",
)?;
(snapshot, groups_out.expect("a sealed snapshot has groups"))
};
// #1062: every vote the generated route makes happens during sealing, so
// the Labeler's counters are final here — the same accounting the legacy
// path prints after its walk, stated where this route's cost was paid.
if let Some(labeler) = labeler {
let (calls, records) = labeler.counters();
pr.note(&format!(
"autoindex: --label: {calls} /_decide call(s) for {records} labelled record(s)"
));
}
// #381: the per-file record cap dropped a file's tail during preparation.
// The generated path seals before the graph worker loop runs, so report it
// here rather than at the shared post-run summary.
let truncated: Vec<String> = snapshot
.files
.iter()
.filter(|f| f.prepared.as_ref().is_some_and(|p| p.truncated))
.filter_map(|f| plan.files.get(&f.content_id).map(|a| a.rel.clone()))
.collect();
note_truncated_files(pr, &truncated);
let identity = if let Some(identity) = embedding_identity {
journal.pin_embedding_identity(
&identity.identity_sha256,
identity.resumable,
identity.dimensions,
identity.non_resumable_reason.as_deref(),
)?;
identity
} else {
crate::esclient::EmbeddingExecutionIdentity {
version: 1,
backend: "disabled".into(),
identity_sha256: "0".repeat(64),
// A disabled embedding execution has no vector width at all. `None`
// says exactly that; any number here would be a fiction the
// generation contract would then hold future runs to.
dimensions: None,
semantic_contract: "disabled-no-semantic-fields-v1".into(),
resumable: true,
non_resumable_reason: None,
ingest_probe_bytes: None,
ingest_probe_passages: None,
ingest_probe_millis: None,
}
};
sync_executor::bind_prepared_counts(&mut groups, &snapshot, &sealed.keys)?;
let (schema_identity, index_identity) = generation_contract_identities(&plan)?;
let desired = sync::GenerationManifest {
generation: base.generation + 1,
execution: Some(sync::ExecutionIdentity {
version: sync::EXECUTION_IDENTITY_VERSION,
root_identity: root_identity.to_owned(),
url: cfg.url.clone(),
prefix: cfg.prefix.clone(),
follow_symlinks: cfg.follow_symlinks,
chunker_identity,
embedding_identity_sha256: identity.identity_sha256,
embedding_backend: identity.backend,
embedding_dimension: identity.dimensions,
embedding_semantic_contract: identity.semantic_contract,
embedding_resumable: identity.resumable,
graph_enabled: false,
brain: "disabled".into(),
detector_identity: DETECTOR_DISABLED_IDENTITY.into(),
schema_identity,
index_identity,
source_policy: sync::SourceExecutionPolicy::DurableSnapshot {
reference: format!("sync-snapshots/{tx_id}"),
snapshot_digest: snapshot.snapshot_digest,
},
}),
plan,
groups,
};
// A failure here is the generation machinery contradicting itself about
// durable state, and the invariant text alone gives the user nothing to
// act on (#283). Name the recovery route; the invariant stays attached as
// the cause so the report keeps its diagnostic value.
let pending = sync::PendingSync::new(tx_id, &base, desired).with_context(|| {
format!(
"autoindex could not derive generation {} from committed generation {}; the durable \
generation state in {} is not internally consistent, and re-running will not repair \
it. No remote data was changed. Rebuild with a new --state-dir and a new --prefix",
base.generation + 1,
base.generation,
state_dir.display()
)
})?;
journal.sync_begin(&pending)
}
/// The desired content groups for a generation: one per planned content
/// file, canonical path first, then its aliases, reconciled against the
/// committed base. Counts are zero until [`sync_executor::bind_prepared_counts`]
/// fills them from the sealed snapshot.
fn desired_content_groups(
base_groups: &[sync::ManifestGroup],
plan: &Plan,
inventory: &content::Inventory,
) -> Result<Vec<sync::ManifestGroup>> {
let aliases_by_content = plan.duplicate_files.iter().fold(
HashMap::<&str, Vec<sync::ManifestPath>>::new(),
|mut aliases, alias| {
aliases
.entry(alias.file_key.as_str())
.or_default()
.push(sync::ManifestPath {
path_id: alias.path_id.clone(),
rel: alias.rel.clone(),
is_symlink: alias.is_symlink.unwrap_or(false),
});
aliases
},
);
let file_by_content = inventory
.keys
.iter()
.zip(&inventory.files)
.zip(&inventory.digests)
.map(|((key, file), digest)| (key.as_str(), (file, digest)))
.collect::<HashMap<_, _>>();
let mut candidates = Vec::with_capacity(plan.files.len());
for (content_id, assignment) in &plan.files {
let (file, digest) = file_by_content
.get(content_id.as_str())
.with_context(|| format!("planned content {content_id} is absent from inventory"))?;
let mut paths = vec![sync::ManifestPath {
path_id: assignment.path_id.clone(),
rel: assignment.rel.clone(),
is_symlink: assignment.is_symlink.unwrap_or(file.is_symlink),
}];
paths.extend(
aliases_by_content
.get(content_id.as_str())
.cloned()
.unwrap_or_default(),
);
candidates.push(sync::DesiredContentGroup {
content_id: content_id.clone(),
content_digest: (*digest).clone(),
content_size: file.size,
dataset_slugs: assignment
.assignments
.iter()
.map(|(_, slug)| slug.clone())
.collect(),
paths,
expected_records: 0,
expected_passages: 0,
expected_vectors: 0,
expected_junk_records: 0,
expected_records_by_dataset: BTreeMap::new(),
});
}
sync::reconcile_groups(base_groups, candidates)
}
#[derive(Debug, PartialEq, Eq)]
struct CliErrorRoute {
exit_code: i32,
stdout: Option<String>,
stderr: Option<String>,
}
fn route_cli_error(error: &anyhow::Error, json_output: bool) -> CliErrorRoute {
if json_output {
// Two distinct refusals reach the JSON route, and both must keep it.
// `UnsafeFreshGenerationError` guards durable *generation* state on the
// `--no-graph` path; `UnsupportedInventoryDeltaError` (#254) guards the
// legacy graph-enabled path against a rerun that would strand live
// documents. Neither supersedes the other — they protect different
// destinations — so routing only one would silently drop the other's
// machine-readable rendering back to a prose stderr line.
if let Some(unsafe_fresh) = error.downcast_ref::<UnsafeFreshGenerationError>() {
return CliErrorRoute {
exit_code: 1,
stdout: Some(unsafe_fresh.to_json().to_string()),
stderr: None,
};
}
if let Some(delta) = error.downcast_ref::<UnsupportedInventoryDeltaError>() {
return CliErrorRoute {
exit_code: 1,
stdout: Some(delta.to_json().to_string()),
stderr: None,
};
}
}
CliErrorRoute {
exit_code: 1,
stdout: None,
stderr: Some(format!("error: {error:#}")),
}
}
/// Entry point for the `xerj autoindex` subcommand (blocking; the server
/// binary calls this via spawn_blocking). Returns the process exit code.
pub fn run_cli() -> i32 {
let args: Vec<String> = xerj_common::argv::args_after_subcommand();
let cmd = match cli::parse(args) {
Ok(c) => c,
Err(e) => {
// #1586: a usage error is the error plus one pointer line. The
// 390-line help page used to follow on stdout, which buried the
// error for anyone reading stdout or the tail of combined output —
// an agent saw help and concluded the run had done something.
eprintln!("error: {e}");
eprintln!("run `xerj autoindex --help` for usage.");
return 2;
}
};
let json_output = matches!(&cmd, Cmd::Index(cfg) if cfg.json);
let res = match cmd {
Cmd::Help => {
cli::print_help();
return 0;
}
Cmd::Index(cfg) => run_index(*cfg),
Cmd::Skills(cfg) => skills::run(*cfg),
Cmd::Map(cfg) => run_map(cfg),
Cmd::Status(cfg) => run_status(cfg),
Cmd::Remove(cfg) => run_remove(cfg),
Cmd::Watch(cfg) => objwatch::run::run(*cfg),
};
match res {
Ok(code) => code,
Err(e) => {
let route = route_cli_error(&e, json_output);
if let Some(stdout) = route.stdout {
println!("{stdout}");
}
if let Some(stderr) = route.stderr {
eprintln!("{stderr}");
}
route.exit_code
}
}
}
/// The hub manifest at the root of a corpus directory. Excluded only by
/// [`run_with_options`]; a folder named the same way is still indexed.
const CORPUS_MANIFEST_REL: &str = "corpus.json";
/// Drop walk entries whose root-relative path is in `exclude`, and every
/// entry the `--exclude <glob>` patterns match (#2483). Both empty returns the
/// walk unchanged, so neither is a global skip of a filename.
///
/// The filter runs after the walk rather than inside it because the walker has
/// no notion of a user glob — ignore rules reach it as parsed ignore files —
/// and because `--walk-only`'s per-folder summary is built from the filtered
/// list, so both exclusion routes drop a path the same way.
fn without_excluded_rels(
files: Vec<walk::FileEntry>,
exclude: &[String],
globs: &[String],
) -> Result<(Vec<walk::FileEntry>, usize)> {
if exclude.is_empty() && globs.is_empty() {
return Ok((files, 0));
}
let matcher = GlobMatcher::compile(globs, "--exclude")?;
let before = files.len();
let kept: Vec<walk::FileEntry> = files
.into_iter()
.filter(|file| !exclude.contains(&file.rel) && !matcher.matches(&file.rel))
.collect();
let dropped = before - kept.len();
Ok((kept, dropped))
}
/// Extensions that are DATA in a cloned reference repo, not reference material
/// (#1985): `xerj corpus index` exists to retrieve code and docs, and one
/// simulation/test-output folder in the field report produced 636,724 records
/// — more than the rest of that corpus together. The gate is by FAMILY, not by
/// size: the cost came from many files, so a size floor would let most of them
/// through. `xerj corpus index --include-data` indexes them anyway.
pub const CORPUS_DATA_EXTS: &[&str] = &[
// Tabular / columnar dumps.
"csv", "tsv", "parquet", "arrow", "feather", "orc", "avro",
// Scientific arrays and dataframes.
"h5", "hdf5", "hdf", "nc", "npy", "npz", "mat", "sav", "dta", "rds", "fits",
// Simulation / capture output.
"out", "sim", "vtk", "pcap", "pcapng",
// Embedded databases and serialized models.
"sqlite", "sqlite3", "db", "pkl", "pickle",
];
/// True when `file` carries a [`CORPUS_DATA_EXTS`] extension (case-insensitive).
fn is_corpus_data_file(file: &walk::FileEntry) -> bool {
file.path
.extension()
.and_then(|e| e.to_str())
.is_some_and(|ext| {
CORPUS_DATA_EXTS
.iter()
.any(|data| ext.eq_ignore_ascii_case(data))
})
}
/// Drop [`is_corpus_data_file`] entries from a corpus inventory. Returns the
/// kept files plus the skipped count and bytes so the run can say what it left
/// out (#1985) instead of silently indexing less than the folder holds.
fn without_corpus_data_files(files: Vec<walk::FileEntry>) -> (Vec<walk::FileEntry>, usize, u64) {
let before = files.len();
let mut skipped_bytes = 0u64;
let kept: Vec<walk::FileEntry> = files
.into_iter()
.filter(|file| {
if is_corpus_data_file(file) {
skipped_bytes += file.size;
false
} else {
true
}
})
.collect();
let dropped = before - kept.len();
(kept, dropped, skipped_bytes)
}
/// Per-extension accounting printed at the end of `xerj corpus index`
/// (#2339, the summary half of #1985).
///
/// `indexed` is what the walk admits after ignore rules, minus the corpus
/// manifest and — unless `include_data` — the data-file families.
/// `ignored data` is those families. A pruned directory is not expanded
/// into extensions; the ignore-rules line names the prune instead. A walk
/// that cannot run yields no lines, and the index verdict still prints.
pub(crate) fn corpus_file_class_summary(root: &Path, include_data: bool) -> Vec<String> {
let Ok((files, ignore)) =
walk::walk_reporting(root, false, ignore_rules::IgnoreOptions::default())
else {
return Vec::new();
};
let files: Vec<walk::FileEntry> = files
.into_iter()
.filter(|file| file.rel != CORPUS_MANIFEST_REL)
.collect();
let (kept, skipped): (Vec<walk::FileEntry>, Vec<walk::FileEntry>) = if include_data {
(files, Vec::new())
} else {
let mut kept = Vec::new();
let mut skipped = Vec::new();
for file in files {
if is_corpus_data_file(&file) {
skipped.push(file);
} else {
kept.push(file);
}
}
(kept, skipped)
};
let mut lines = vec![format!(
"file classes: indexed {} ({} file{})",
format_class_counts(&class_counts(&kept)),
kept.len(),
if kept.len() == 1 { "" } else { "s" },
)];
if !skipped.is_empty() {
lines.push(format!(
"file classes: ignored data {} ({} file{}) — pass --include-data to index them",
format_class_counts(&class_counts(&skipped)),
skipped.len(),
if skipped.len() == 1 { "" } else { "s" },
));
}
if ignore.files_skipped > 0 || ignore.dirs_pruned > 0 {
lines.push(format!(
"file classes: ignore rules skipped {} file{} and pruned {} director{}",
ignore.files_skipped,
if ignore.files_skipped == 1 { "" } else { "s" },
ignore.dirs_pruned,
if ignore.dirs_pruned == 1 { "y" } else { "ies" },
));
}
lines
}
fn class_of(file: &walk::FileEntry) -> String {
file.path
.extension()
.and_then(|ext| ext.to_str())
.map(|ext| ext.to_ascii_lowercase())
.filter(|ext| !ext.is_empty())
.unwrap_or_else(|| "noext".to_string())
}
fn class_counts(files: &[walk::FileEntry]) -> BTreeMap<String, u64> {
let mut counts = BTreeMap::new();
for file in files {
*counts.entry(class_of(file)).or_insert(0) += 1;
}
counts
}
fn format_class_counts(counts: &BTreeMap<String, u64>) -> String {
if counts.is_empty() {
return "none".to_string();
}
let mut ranked: Vec<(&String, &u64)> = counts.iter().collect();
ranked.sort_by(|a, b| b.1.cmp(a.1).then_with(|| a.0.cmp(b.0)));
const SHOW: usize = 12;
let mut parts: Vec<String> = ranked
.iter()
.take(SHOW)
.map(|(name, count)| format!("{name}={count}"))
.collect();
if ranked.len() > SHOW {
parts.push(format!("+{}", ranked.len() - SHOW));
}
parts.join(" ")
}
#[cfg(test)]
mod generation_preflight_tests {
use super::*;
/// A temp corpus holding two byte-identical files, resolved the way a run
/// resolves it: one content file (`a.txt`) and one alias (`b.txt`).
fn duplicate_inventory(dir: &Path) -> content::Inventory {
std::fs::write(dir.join("a.txt"), "same bytes").unwrap();
std::fs::write(dir.join("b.txt"), "same bytes").unwrap();
let files = walk::walk(dir, false).unwrap();
let inventory = content::resolve_reporting(files, &|_| {}).unwrap();
assert_eq!(inventory.files.len(), 1);
assert_eq!(inventory.duplicates.len(), 1);
inventory
}
/// The plan a run builds from `inventory`: every content file assigned to
/// one dataset, its duplicates recorded as aliases.
fn plan_for(inventory: &content::Inventory) -> Plan {
let files: HashMap<String, FileAssignment> = inventory
.files
.iter()
.enumerate()
.map(|(i, file)| {
(
inventory.keys[i].clone(),
FileAssignment {
rel: file.rel.clone(),
path_id: file.rel_id.clone(),
is_symlink: Some(file.is_symlink),
family: "text".into(),
gzip: false,
content_digest: Some(inventory.digests[i].clone()),
assignments: vec![(None, "docs".into())],
as_document: false,
},
)
})
.collect();
Plan {
datasets: vec![PlanDataset {
slug: "docs".into(),
index: "ax-docs".into(),
family: "text".into(),
group: None,
specs: vec![],
time_field: None,
semantic_field: None,
text_analyzer: None,
scope: None,
sampled_records: 1,
file_count: files.len(),
}],
files,
duplicate_files: inventory.duplicates.clone(),
alias_paths_indexed: false,
..Plan::default()
}
}
#[test]
fn a_consistent_plan_passes_the_preflight() {
let dir = tempfile::tempdir().unwrap();
let inventory = duplicate_inventory(dir.path());
let plan = plan_for(&inventory);
let groups = desired_content_groups(&[], &plan, &inventory).unwrap();
sync::preflight_plan_projection(&plan, &groups)
.expect("the plan a run builds must pass the preflight");
}
/// #1723: a plan whose canonical copy is not the lowest native identity —
/// the shape the Windows `rel`-vs-`path_id` ranking produced — is refused
/// by the preflight, i.e. before `create_prepared_snapshot_reporting` seals
/// anything, with the same invariant `PendingSync::new` reports after it.
#[test]
fn a_plan_that_cannot_project_is_refused_before_sealing() {
let dir = tempfile::tempdir().unwrap();
let mut inventory = duplicate_inventory(dir.path());
// Promote the alias to canonical and demote the real canonical to an
// alias. The groups re-rank by `(is_symlink, path_id)` and put `a.txt`
// back first, so the plan's canonical (`b.txt`) disagrees with them.
let alias = inventory.duplicates[0].clone();
let file = inventory.files[0].clone();
inventory.files[0].rel = alias.rel.clone();
inventory.files[0].rel_id = alias.path_id.clone();
inventory.duplicates[0].rel = file.rel.clone();
inventory.duplicates[0].path_id = file.rel_id.clone();
inventory.duplicates[0].duplicate_of = alias.rel.clone();
let plan = plan_for(&inventory);
let groups = desired_content_groups(&[], &plan, &inventory).unwrap();
let err = sync::preflight_plan_projection(&plan, &groups)
.expect_err("a plan that cannot project must be refused");
assert!(
format!("{err:#}").contains("plan canonical projection disagrees with manifest group"),
"{err:#}"
);
}
}
#[cfg(test)]
mod exclude_rels_tests {
use super::*;
fn entry(rel: &str) -> walk::FileEntry {
walk::FileEntry {
path: std::path::PathBuf::from(rel),
rel: rel.to_string(),
rel_id: rel.to_string(),
is_symlink: false,
size: 1,
}
}
#[test]
fn the_corpus_manifest_is_dropped_and_a_nested_copy_is_kept() {
let files = vec![
entry("corpus.json"),
entry("src/lib.rs"),
entry("vendor/corpus.json"),
];
let (kept, dropped) =
without_excluded_rels(files, &[CORPUS_MANIFEST_REL.to_string()], &[]).unwrap();
assert_eq!(dropped, 1);
let rels: Vec<&str> = kept.iter().map(|file| file.rel.as_str()).collect();
assert_eq!(rels, ["src/lib.rs", "vendor/corpus.json"]);
}
#[test]
fn an_empty_exclusion_list_keeps_a_root_corpus_json() {
let files = vec![entry("corpus.json"), entry("README.md")];
let (kept, dropped) = without_excluded_rels(files, &[], &[]).unwrap();
assert_eq!(dropped, 0);
assert_eq!(kept.len(), 2);
}
/// #2483: `--exclude <glob>` leaves a generated tree out of the index
/// without deleting it or editing an ignore file. A pattern with `/` is
/// anchored at the root, so `gen/**` takes the whole folder and nothing
/// that merely ends in the same name elsewhere.
#[test]
fn an_exclude_glob_drops_a_whole_subtree_and_counts_it() {
let files = vec![
entry("src/main.rs"),
entry("gen/deep/generated.java"),
entry("gen/notes.md"),
entry("vendor/gen/kept.md"),
];
let (kept, dropped) = without_excluded_rels(files, &[], &["gen/**".to_string()]).unwrap();
assert_eq!(dropped, 2);
let rels: Vec<&str> = kept.iter().map(|file| file.rel.as_str()).collect();
assert_eq!(rels, ["src/main.rs", "vendor/gen/kept.md"]);
}
/// A pattern without `/` is a NAME pattern and matches at any depth, the
/// same rule `--stub` follows — so one flag can clear build droppings from
/// every folder without listing each one.
#[test]
fn a_bare_exclude_glob_matches_the_name_at_any_depth() {
let files = vec![
entry("app.log"),
entry("logs/app.log"),
entry("deep/nested/trace.log"),
entry("app.log.md"),
];
let (kept, dropped) = without_excluded_rels(files, &[], &["*.log".to_string()]).unwrap();
assert_eq!(dropped, 3);
let rels: Vec<&str> = kept.iter().map(|file| file.rel.as_str()).collect();
assert_eq!(rels, ["app.log.md"]);
}
/// Both exclusion routes apply in one pass: the exact-rel list
/// `corpus index` uses for `corpus.json` and the user's globs.
#[test]
fn an_exclude_glob_composes_with_an_exact_exclusion() {
let files = vec![entry("corpus.json"), entry("gen/x.rs"), entry("src/lib.rs")];
let (kept, dropped) = without_excluded_rels(
files,
&[CORPUS_MANIFEST_REL.to_string()],
&["gen/**".to_string()],
)
.unwrap();
assert_eq!(dropped, 2);
let rels: Vec<&str> = kept.iter().map(|file| file.rel.as_str()).collect();
assert_eq!(rels, ["src/lib.rs"]);
}
/// A pattern over the length limit is reported against `--exclude`, so a
/// rejected glob names the flag to fix instead of surfacing a
/// regex-internal error.
#[test]
fn an_over_long_exclude_glob_names_the_flag() {
let msg = without_excluded_rels(vec![], &[], &["?".repeat(MAX_GLOB_LEN + 1)])
.unwrap_err()
.to_string();
assert!(msg.contains("--exclude"), "{msg}");
assert!(msg.contains(&MAX_GLOB_LEN.to_string()), "{msg}");
}
}
#[cfg(test)]
mod corpus_data_skip_tests {
use super::*;
fn entry(rel: &str, size: u64) -> walk::FileEntry {
walk::FileEntry {
path: std::path::PathBuf::from(rel),
rel: rel.to_string(),
rel_id: rel.to_string(),
is_symlink: false,
size,
}
}
/// #1985: the data families a cloned reference repo ships are dropped —
/// case-insensitively — while source, docs, logs and records stay. The
/// skipped bytes are reported so the run can say what it left out.
#[test]
fn data_families_are_skipped_and_counted_but_source_docs_logs_and_records_stay() {
let files = vec![
entry("src/main.rs", 10),
entry("docs/GUIDE.md", 20),
entry("logs/app.log", 30),
entry("records.jsonl", 40),
entry("tests/fixtures/data.CSV", 1_000),
entry("sim/run1.h5", 2_000),
entry("sim/out.vtk", 3_000),
entry("db/cache.sqlite3", 4_000),
];
let (kept, count, bytes) = without_corpus_data_files(files);
let rels: Vec<&str> = kept.iter().map(|f| f.rel.as_str()).collect();
assert_eq!(
rels,
[
"src/main.rs",
"docs/GUIDE.md",
"logs/app.log",
"records.jsonl"
],
"the data families are skipped; code/docs/logs/records are not"
);
assert_eq!(count, 4);
assert_eq!(bytes, 1_000 + 2_000 + 3_000 + 4_000);
}
/// A file with no extension (a Makefile, a script) is not data by family.
#[test]
fn a_file_without_an_extension_is_kept() {
let (kept, count, bytes) = without_corpus_data_files(vec![entry("Makefile", 1)]);
assert_eq!((kept.len(), count, bytes), (1, 0, 0));
}
/// #2339: the corpus-index tail names indexed extensions and the data
/// families the gate left out. `corpus.json` is bookkeeping. A pruned
/// `node_modules` is the ignore-rules line, not an indexed class.
#[test]
fn corpus_index_summary_splits_indexed_extensions_from_ignored_data() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::create_dir_all(root.join("data")).unwrap();
std::fs::create_dir_all(root.join("node_modules/pkg")).unwrap();
std::fs::write(root.join("src/lib.rs"), "fn a() {}\n").unwrap();
std::fs::write(root.join("README.md"), "docs\n").unwrap();
std::fs::write(root.join("Makefile"), "all:\n").unwrap();
std::fs::write(root.join("data/rows.csv"), "a,b\n").unwrap();
std::fs::write(root.join("data/ROWS.CSV"), "c,d\n").unwrap();
std::fs::write(root.join("sim.h5"), "not-really\n").unwrap();
std::fs::write(root.join("corpus.json"), "{}\n").unwrap();
std::fs::write(root.join("node_modules/pkg/index.js"), "x\n").unwrap();
let lines = corpus_file_class_summary(root, false);
let text = lines.join("\n");
assert!(
text.contains("file classes: indexed md=1 noext=1 rs=1 (3 files)"),
"{text}"
);
assert!(
text.contains(
"file classes: ignored data csv=2 h5=1 (3 files) — pass --include-data to index them"
),
"{text}"
);
assert!(text.contains("pruned"), "{text}");
assert!(!text.contains("corpus.json"), "{text}");
assert!(!text.contains("js="), "{text}");
let included = corpus_file_class_summary(root, true).join("\n");
assert!(
included.contains("csv=2") && included.contains("h5=1") && included.contains("rs=1"),
"{included}"
);
assert!(
!included.contains("ignored data"),
"include-data indexes the data families: {included}"
);
}
}
/// In-process autoindex for the `xerj corpus` lifecycle (issue #977): builds
/// the same argv the wrapper script passed and routes it through the same
/// parse → run → error-route path as `run_cli`, so there is exactly ONE
/// autoindex behaviour.
///
/// The URL is resolved by the WRAPPER (`--url`/`XERJ_URL`) and passed
/// explicitly because `autoindex` itself deliberately ignores `XERJ_URL` (a
/// stale var must not redirect a write — see `cli.rs`). `--fresh` is never
/// forwarded: the build-verify-swap that replaces it lives in `xc.rs`.
pub fn run_with_options(
dir: &std::path::Path,
url: &str,
prefix: &str,
state_dir: Option<&std::path::Path>,
no_graph: bool,
include_data: bool,
) -> i32 {
let mut args = vec![
dir.to_string_lossy().to_string(),
"--url".to_string(),
url.to_string(),
"--prefix".to_string(),
prefix.to_string(),
];
if no_graph {
args.push("--no-graph".to_string());
}
if let Some(sd) = state_dir {
args.push("--state-dir".to_string());
args.push(sd.to_string_lossy().to_string());
}
let cmd = match cli::parse(args) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
return 2;
}
};
let res = match cmd {
Cmd::Index(cfg) => {
// The corpus directory's own manifest is bookkeeping, not a
// source file. A normal folder index leaves `exclude_rels` empty,
// so a project that happens to contain `corpus.json` still indexes it.
let mut cfg = *cfg;
cfg.exclude_rels = vec![CORPUS_MANIFEST_REL.to_string()];
// #1985: a cloned reference repo ships test outputs and datasets;
// index code + docs unless the operator asked for the data too.
cfg.skip_corpus_data = !include_data;
run_index(cfg)
}
_ => return 2,
};
match res {
Ok(code) => code,
Err(e) => {
let route = route_cli_error(&e, false);
if let Some(stdout) = route.stdout {
println!("{stdout}");
}
if let Some(stderr) = route.stderr {
eprintln!("{stderr}");
}
route.exit_code
}
}
}
const GB: u64 = 1 << 30;
/// Junk entries that name a file which also reached `file_done`.
///
/// The catalog holds ONE document per file: `catalog::file_doc` derives its
/// `_id` from the file key alone (`catalog::file_id`). The completion pass and
/// the junk pass both write into the same bulk body, so an entry that appears
/// in both is not two rows, it is one row written twice — and the junk write,
/// which lands second, is the one that survives. The observable damage is that
/// a file which indexed N records is reported as status "junk" with records 0,
/// plus a double count in `junk_file_count` and a double
/// `CodeCoverage::observe`.
///
/// Producers are required to keep the two sets disjoint: a worker that gives up
/// on a file sets `send_err`, which suppresses the completion, and a worker
/// that merely wants to report a partial problem notes it on the progress meter
/// instead. This returns the violations rather than assuming there are none,
/// because the caller is the only place that holds both sets and because the
/// failure is silent everywhere else.
fn shadowed_junk_entries<'a>(
all_junk: &[&'a state::JunkFile],
completed_keys: &HashSet<String>,
) -> Vec<&'a state::JunkFile> {
all_junk
.iter()
.filter(|jf| completed_keys.contains(&jf.file_key))
.copied()
.collect()
}
/// How many entries a human-facing listing prints before it summarises the
/// rest. These lists are bounded by the corpus, not by the fault: unmounting a
/// bind mount under an indexed root makes every content group vanish at once,
/// so an uncapped listing is one rendered entry per journalled file — megabytes
/// of stderr, in the code paths whose entire job is to be read by a person.
const REFUSAL_LIST_CAP: usize = 10;
const SAMPLE_LIMIT_BYTES: u64 = 4 << 20;
const SQLDUMP_SAMPLE_LIMIT: u64 = 64 << 20;
/// Sampling byte cap for Unity assets.
///
/// Unity YAML is a GROUPED family: each `unity_class` is its own cluster, and
/// a class's first document can sit anywhere in the file — `extract/unity.rs`
/// notes real scenes exceed 200 MB. A class whose first document starts past
/// the cap is never sampled, so it gets no entry in `fa.assignments`, and
/// phase B then has nowhere to route its records. Under the old 4 MiB cap
/// that silently became `file_junk`. This cap is set past the size of the
/// scenes the format actually produces so that outcome needs a genuinely
/// pathological file, and when it does happen phase B now names the
/// unsampled group and its record count in `extra_junk` instead of adding
/// them to an anonymous counter.
const UNITY_SAMPLE_LIMIT: u64 = 512 << 20;
/// How many bytes phase A reads from a file of this family before it stops
/// sampling. `None` means the family's extractor caps itself.
///
/// Split out of `scan_file` so tests can shrink it. The consequence of a
/// GROUPED family hitting this cap is not "a slightly thinner sample", it is a
/// whole `unity_class`/SQL table with no dataset to route to in phase B — and
/// the only fixture that reaches it naturally is a half-gigabyte file, which
/// is why that path shipped untested. `SampleLimitOverride` gives the suite a
/// fixture it can afford.
/// Share of a container file's progress credited while it is being split and
/// staged; the rest is credited as the staged records reach the engine.
///
/// A chosen split, informed by one measurement: on the 1 GB synthetic mailbox
/// in `benchmarks/mbox-ingest/` (uncapped node, idle box) the whole mailbox
/// was staged 39 s after its index was created and its records had all been
/// accepted ~170 s in, so extraction was ~23 % of the file's Phase-B time;
/// on a memory-capped node the sending half stretches by minutes while the
/// extraction half does not, so a middle value is used rather than either
/// measured extreme. It only shapes how the bar moves between 0 and 100 —
/// both ends are exact whatever this is — so a mailbox with a different mix
/// (all text, or all attachments) sees a bar that is uneven, never wrong.
const CONTAINER_EXTRACT_PERCENT: u64 = 45;
/// Progress position for "the splitter has reached `offset`" in a file of
/// `size` bytes. `offset` is clamped to `size`: in a gzipped mailbox it counts
/// DECOMPRESSED bytes and runs past the size on disk, and extraction must not
/// spend the share that belongs to sending.
fn container_extract_credit(size: u64, offset: u64) -> u64 {
// u128: a u64 byte position times 45 can overflow a u64.
((u128::from(offset.min(size)) * u128::from(CONTAINER_EXTRACT_PERCENT)) / 100) as u64
}
/// Progress position for "`sent` of `staged` bytes have reached the engine",
/// for a file of `size` bytes.
fn container_send_credit(size: u64, sent: u64, staged: u64) -> u64 {
let base = container_extract_credit(size, size);
if staged == 0 {
return base;
}
let span = u128::from(size - base);
base + ((span * u128::from(sent.min(staged))) / u128::from(staged)) as u64
}
fn sample_limit_bytes(family: Family, path: &Path) -> Option<u64> {
// Only the test override reads the path; the shipped caps are per-family.
#[cfg(not(test))]
let _ = path;
#[cfg(test)]
{
// Scoped to ONE corpus root, not process-global. `cargo test` runs this
// binary multi-threaded, phase A itself runs on `crate::pool`, and a
// bare global would silently re-cap sampling for every unrelated test
// that happened to overlap — a flake that would look like anything but
// its cause.
if let Some((root, bytes)) = SAMPLE_LIMIT_OVERRIDE
.lock()
.unwrap_or_else(|p| p.into_inner())
.as_ref()
{
if path.starts_with(root) {
return Some(*bytes);
}
}
}
match family {
Family::SqlDump => Some(SQLDUMP_SAMPLE_LIMIT),
Family::UnityYaml => Some(UNITY_SAMPLE_LIMIT),
Family::Jsonl | Family::Logs | Family::Csv | Family::TxtLines => Some(SAMPLE_LIMIT_BYTES),
// A mailbox is a stream of whole messages: the splitter checks this
// limit BETWEEN messages, so a sample never ends mid-MIME-part, and a
// multi-GB Takeout export costs phase A a few MB of reading.
Family::Mbox => Some(SAMPLE_LIMIT_BYTES),
Family::Sqlite => Some(1), // signals per-table row cap inside the extractor
Family::Xlsx => Some(1), // likewise a per-sheet row cap
Family::Xls => Some(1), // legacy workbook: same per-sheet row cap
_ => None, // whole-file extractors cap themselves
}
}
/// Test-only phase-A byte cap: `(corpus root, bytes)`, applied only to paths
/// under that root. `None` = off.
#[cfg(test)]
static SAMPLE_LIMIT_OVERRIDE: Mutex<Option<(std::path::PathBuf, u64)>> = Mutex::new(None);
/// Caps phase-A sampling under `root` for the lifetime of the guard.
#[cfg(test)]
pub(crate) struct SampleLimitOverride;
#[cfg(test)]
impl SampleLimitOverride {
pub(crate) fn set(root: &Path, bytes: u64) -> Self {
*SAMPLE_LIMIT_OVERRIDE
.lock()
.unwrap_or_else(|p| p.into_inner()) = Some((root.to_owned(), bytes));
Self
}
}
#[cfg(test)]
impl Drop for SampleLimitOverride {
fn drop(&mut self) {
*SAMPLE_LIMIT_OVERRIDE
.lock()
.unwrap_or_else(|p| p.into_inner()) = None;
}
}
/// Test-only crash injection for the replacement path: the boundary to fail
/// at AND the state directory of the one run it is meant for.
///
/// This was a bare process-wide `AtomicU8` holding only the boundary, consumed
/// by whichever run reached that boundary first. The tests that arm it
/// serialize on `FAILPOINT_TEST_LOCK`, but every OTHER test that drives the
/// legacy path passes the same boundaries under a different lock (or none), so
/// a concurrent test could take the injected crash and fail with someone
/// else's error while the arming test ran clean and failed its `unwrap_err`.
/// Reproduced 2 runs out of 2 on a 32-core machine at load average 50:
/// `this_corpus_finalize_leaves_a_sibling_corpus_alias_document_alone` died of
/// "injected replacement crash boundary 4" and
/// `resume_repairs_kills_after_plan_delete_and_final_bulk_before_file_done`
/// got `Ok(0)`; both pass alone. A lock cannot fix that without naming every
/// present and future consumer; keying the failpoint on the state directory —
/// which every test owns as its own tempdir — makes it unstealable instead.
#[cfg(test)]
static REPLACEMENT_FAILPOINT: Mutex<Option<(u8, std::path::PathBuf)>> = Mutex::new(None);
/// A test-only action run once when phase B starts, for the run that uses the
/// given state directory: the window between phase A's digest and phase B's
/// read, where a live file (a lock file, a log) changes under the run (#1911).
/// Keyed on the state directory for the same reason as
/// [`REPLACEMENT_FAILPOINT`].
#[cfg(test)]
type PhaseBStartHook = (std::path::PathBuf, Box<dyn FnOnce() + Send>);
#[cfg(test)]
static PHASE_B_START_HOOK: Mutex<Option<PhaseBStartHook>> = Mutex::new(None);
#[cfg(test)]
pub(crate) fn arm_phase_b_start_hook(state_dir: &Path, action: impl FnOnce() + Send + 'static) {
*PHASE_B_START_HOOK.lock().unwrap_or_else(|p| p.into_inner()) =
Some((state_dir.to_path_buf(), Box::new(action)));
}
#[cfg(test)]
fn phase_b_start_hook(state_dir: &Path) {
let action = {
let mut armed = PHASE_B_START_HOOK.lock().unwrap_or_else(|p| p.into_inner());
match armed.as_ref() {
Some((dir, _)) if dir == state_dir => armed.take().map(|(_, action)| action),
_ => None,
}
};
if let Some(action) = action {
action();
}
}
#[cfg(not(test))]
#[inline]
fn phase_b_start_hook(_state_dir: &Path) {}
/// A test-only action run once immediately before the hash, after the walk
/// has stored every [`walk::FileEntry`]. That is the window where a lock file
/// disappears between enumeration and the first open (#2352). Keyed on the
/// state directory for the same reason as [`PHASE_B_START_HOOK`].
#[cfg(test)]
type BeforeHashHook = (std::path::PathBuf, Box<dyn FnOnce() + Send>);
#[cfg(test)]
static BEFORE_HASH_HOOK: Mutex<Option<BeforeHashHook>> = Mutex::new(None);
#[cfg(test)]
pub(crate) fn arm_before_hash_hook(state_dir: &Path, action: impl FnOnce() + Send + 'static) {
*BEFORE_HASH_HOOK.lock().unwrap_or_else(|p| p.into_inner()) =
Some((state_dir.to_path_buf(), Box::new(action)));
}
#[cfg(test)]
fn before_hash_hook(state_dir: &Path) {
let action = {
let mut armed = BEFORE_HASH_HOOK.lock().unwrap_or_else(|p| p.into_inner());
match armed.as_ref() {
Some((dir, _)) if dir == state_dir => armed.take().map(|(_, action)| action),
_ => None,
}
};
if let Some(action) = action {
action();
}
}
#[cfg(not(test))]
#[inline]
fn before_hash_hook(_state_dir: &Path) {}
/// Arm [`replacement_failpoint`] for the run that uses `state_dir`, once.
#[cfg(test)]
pub(crate) fn arm_replacement_failpoint(boundary: u8, state_dir: &Path) {
*REPLACEMENT_FAILPOINT
.lock()
.unwrap_or_else(|p| p.into_inner()) = Some((boundary, state_dir.to_path_buf()));
}
#[cfg(test)]
fn replacement_failpoint(boundary: u8, state_dir: &Path) -> Result<()> {
let mut armed = REPLACEMENT_FAILPOINT
.lock()
.unwrap_or_else(|p| p.into_inner());
if armed
.as_ref()
.is_some_and(|(at, dir)| *at == boundary && dir == state_dir)
{
*armed = None;
anyhow::bail!("injected replacement crash boundary {boundary}");
}
Ok(())
}
#[cfg(not(test))]
#[inline]
fn replacement_failpoint(_boundary: u8, _state_dir: &Path) -> Result<()> {
Ok(())
}
/// The first server error, with `limits.max_process_memory_mb` named when
/// the rejection is the parent memory breaker (#2238).
fn server_error_text(outcome: &crate::esclient::BulkOutcome) -> String {
outcome
.first_server_error
.as_deref()
.map(crate::esclient::memory_cap_hint)
.unwrap_or_else(|| "unknown server error".into())
}
/// Send one bulk body and fold its per-item rejections into
/// `rejected_records`.
///
/// This counter is deliberately NOT the parser-junk counter. A record the
/// *backend* refused and a record the *parser* could not read are different
/// failures with different lifetimes: parser junk is durable (journaled per
/// file and replayed on every resume), a backend rejection is not (no
/// `FileDone` records a document that was never accepted). Adding both to one
/// number is what let `junk_records_total` mean two things at once.
///
/// Note where this number can and cannot surface. Any non-zero value here also
/// puts an entry in `bulk_errors`, which aborts the run before the run
/// document exists — so it is reported in the abort message and nowhere else.
fn record_bulk_outcome(
es: &Es,
body: Vec<u8>,
rejected_records: &AtomicU64,
bulk_errors: &Mutex<Vec<String>>,
send_err: &mut Option<String>,
) -> bool {
match es.bulk(body) {
Ok(outcome) => {
if outcome.server_errors > 0 {
// Per-item 429s were already re-sent inside `Es::bulk` for as
// long as the server accepted anything (#944); what reaches
// here did not clear.
*send_err = Some(format!(
"bulk backend failed for {} item(s): {}. Source file was not journaled \
complete; fix the server condition (or wait for it to clear) and rerun \
autoindex — the run resumes from the journal",
outcome.server_errors,
server_error_text(&outcome)
));
return true;
}
if outcome.item_errors > 0 {
rejected_records.fetch_add(outcome.item_errors, Ordering::Relaxed);
if let Some(error) = outcome.first_error {
let mut errors = bulk_errors.lock().unwrap();
if errors.len() < 5 {
errors.push(error);
}
}
}
false
}
Err(error) => {
*send_err = Some(format!("{error:#}"));
true
}
}
}
// ─── phase-B bulk coalescing (#1147) ─────────────────────────────────────
/// One flushed bulk: the body, the tokens with records in it, and the
/// token behind each `_id`.
type PipeJob = (Vec<u8>, Vec<u64>, HashMap<String, u64>);
/// The `_id` an NDJSON bulk action line names, if any.
fn bulk_action_id(action: &[u8]) -> Option<String> {
let value: Value = serde_json::from_slice(action).ok()?;
let op = value.as_object()?.values().next()?;
op.get("_id")?.as_str().map(str::to_owned)
}
/// Shared mutable state of [`BulkPipe`]. One lock covers the buffer and the
/// per-token bookkeeping so a flush is atomic against submissions.
#[derive(Default)]
struct PipeState {
/// NDJSON body under construction. Never holds more than one flush's
/// worth: crossing the cut flushes inline.
buf: Vec<u8>,
docs: usize,
/// Tokens with bytes in `buf`, in submission order. A token appears once
/// even across several chunk submissions (one file larger than the cut).
pending: Vec<u64>,
/// The token that submitted each `_id` in `buf`, so a refused item is
/// charged to its own file rather than to every file in the bulk (#2807).
owners: HashMap<String, u64>,
/// Tokens whose every refused record was over the server's per-document
/// byte limit, with the server's reason. A retry cannot clear that, so the
/// file is set aside instead of failing the run (#2807).
too_large: HashMap<u64, String>,
/// Tokens that also failed for any other reason. Never set aside: one
/// refusal a rerun could clear is enough to fail the run instead.
other_refusal: HashSet<u64>,
/// Bulks in flight per token, so a set-aside purge waits for the file's
/// last records to land before deleting them.
in_flight_tokens: HashMap<u64, usize>,
/// Terminal result per token, observed (and removed) by the token's
/// owner in [`BulkPipe::settle`].
done: std::collections::HashMap<u64, Result<(), String>>,
/// Tokens that saw at least one failed bulk. A file larger than one
/// flush has bytes in SEVERAL bulks; if the first fails and a later
/// one succeeds, the file is still un-journaled — the failure is
/// sticky, exactly like the per-file `send_err` it replaces.
failed: std::collections::HashSet<u64>,
next_token: u64,
/// Workers that may still call [`BulkPipe::submit`]. Decremented by
/// [`BulkPipe::retire`] as each worker drains its queue.
live_workers: usize,
/// Live workers currently parked inside `settle`, or inside `submit`
/// waiting for an in-flight slot or for the bulk carrying their chunk to
/// land (that worker submits again once it does). `live == parked` is
/// the "no more bytes are coming" signal that flushes a residual buffer.
parked_workers: usize,
/// Bulk bodies currently on the wire. Capped at [`MAX_IN_FLIGHT`].
in_flight: usize,
}
/// How many bulk bodies may be on the wire at once. 8 matches the server
/// governor's default `max_concurrent_bulks`: more would queue server-side
/// without adding throughput, fewer re-creates the one-at-a-time pipe the
/// first cut of this change shipped (and which measured 4.7x SLOWER on
/// phase B than the per-file code it replaced — extraction and sending
/// must overlap, not alternate).
const MAX_IN_FLIGHT: usize = 8;
/// ONE bulk buffer shared by every phase-B worker (#1147).
///
/// Phase B used to drain each file's staged records into a buffer that lived
/// inside the per-file job, so the `--bulk-mb` and 5,000-doc flush triggers
/// could never span files: a corpus of 36k one-record advisory JSONs left as
/// 36k one-round-trip bulks, and the measured ceiling was ~12 records/s
/// regardless of node load (issue #1147). The pipe holds one buffer for the
/// whole run: workers submit a file's staged lines in cut-sized chunks tagged
/// with the file's token, and a worker that has submitted its whole file
/// settles on that token.
///
/// Flush triggers, in order:
/// 1. the shared buffer crosses the cut (`--bulk-mb` bytes or the doc cap) —
/// shipped inline by the submitting worker, exactly where the per-file
/// code flushed (it blocks here, so a worker's own chunks stay ordered);
/// 2. half the live workers are parked settling — ship what is buffered
/// rather than wait for a full wave: extraction and sending must OVERLAP,
/// not alternate (the all-parked barrier alone measured 4.7x slower on
/// phase B than the per-file code, which sent 8-wide);
/// 3. every worker that could still add bytes is parked settling — the
/// "nothing more is coming" flush, playing the role of the busy timeout
/// in clickhouse's async-insert queue (which groups per-insert futures
/// behind one flush the same way; `AsynchronousInsertQueue.cpp`, Apache-2.0,
/// read as design, not copied);
/// 4. `retire` — the last worker out drains what remains.
///
/// The pipe lock is NOT held across the wire: a flush detaches the buffer as
/// a job, drops the lock, sends, and resolves tokens on return, so up to
/// [`MAX_IN_FLIGHT`] bulks are on the wire at once. Per-file order still
/// holds: a file's cut chunk has landed before its worker's `submit`
/// returns (sent by that worker, or by another that took the buffer while
/// it was parked on a full wire), so any later job carrying its tail ships
/// after those completed; files interleave arbitrarily, exactly as the 32
/// parallel per-file buffers always did.
///
/// Durability semantics are the per-file code's, unchanged: a token settles
/// `Ok` only after EVERY bulk carrying its records was accepted (server_errors
/// == 0), and a bulk that fails transport settles `Err` for EVERY file whose
/// bytes it held — those files stay un-journaled and are republished by the
/// next run, which converges because records overwrite by deterministic id.
/// A file larger than one flush has bytes in several bulks: once any of them
/// fails, the file's error is sticky — a later successful bulk carrying more
/// of the same file must not clear it (`PipeState::failed`). Per-item
/// rejections stay non-fatal as before: counted, surfaced, and the file still
/// settles.
struct BulkPipe<'a, F> {
send: F,
bulk_cut: usize,
doc_cap: usize,
rejected_records: &'a AtomicU64,
state: Mutex<PipeState>,
ready: Condvar,
}
impl<'a, F> BulkPipe<'a, F>
where
F: Fn(Vec<u8>) -> anyhow::Result<crate::esclient::BulkOutcome>,
{
fn new(
send: F,
bulk_cut: usize,
doc_cap: usize,
rejected_records: &'a AtomicU64,
workers: usize,
) -> Self {
Self {
send,
bulk_cut: bulk_cut.max(1),
doc_cap: doc_cap.max(1),
rejected_records,
state: Mutex::new(PipeState {
live_workers: workers,
..PipeState::default()
}),
ready: Condvar::new(),
}
}
/// Allocate a file's token. Pre-resolved `Ok`: a file whose staging
/// produced no records (all junk, all unrouted) settles instantly.
fn token(&self) -> u64 {
let mut st = self.lock();
let t = st.next_token;
st.next_token += 1;
st.done.insert(t, Ok(()));
t
}
fn lock(&self) -> std::sync::MutexGuard<'_, PipeState> {
self.state.lock().unwrap_or_else(|p| p.into_inner())
}
/// Add one chunk of staged NDJSON lines to the shared buffer, flushing
/// inline if the buffer crossed the cut. Never blocks on the network
/// beyond that inline flush.
fn submit(&self, token: u64, bytes: Vec<u8>, docs: usize) {
if bytes.is_empty() {
return;
}
let mut st = self.lock();
// Bytes are in flight: the pre-resolution from `token` no longer
// holds for this file — unless the file already failed, in which
// case the error is sticky and no later bulk can clear it.
if !st.failed.contains(&token) {
st.done.remove(&token);
}
if !st.pending.contains(&token) {
st.pending.push(token);
}
for action in bytes.split(|b| *b == b'\n').step_by(2) {
if let Some(id) = bulk_action_id(action) {
st.owners.insert(id, token);
}
}
st.buf.extend_from_slice(&bytes);
st.docs += docs;
if st.buf.len() < self.bulk_cut && st.docs < self.doc_cap {
return;
}
// Cut crossed: ship inline, and return only once these bytes have
// landed. If every wire slot is busy, park until a delivery frees
// one: backpressure, exactly like the per-file code blocking inside
// its own bulk send. If another worker ships the buffer meanwhile,
// these bytes with it, that job was this worker's flush. Waiting for
// a job of its own instead parked on an empty buffer for good
// (#2841), and shipping someone else's bytes in its place returned
// while this worker's own chunk was still on the wire.
self.quiesce_locked(st, token);
}
/// The server's reason when this token failed only on records over the
/// per-document byte limit. Taken once, by the file's own worker.
fn take_too_large(&self, token: u64) -> Option<String> {
self.lock().too_large.remove(&token)
}
/// Block until no bulk holding this file's records is buffered or in
/// flight, shipping the buffer while they are still in it. `submit`
/// flushes through this. A failed token settles at its first refusal,
/// while its later chunks may still be on the wire; a purge before they
/// land would leave a junk file half searchable.
fn quiesce(&self, token: u64) {
self.quiesce_locked(self.lock(), token);
}
/// [`Self::quiesce`] under a lock the caller already holds, so `submit`
/// ships the buffer it just crossed the cut with before any other
/// worker can add to it.
fn quiesce_locked<'s>(&'s self, mut st: std::sync::MutexGuard<'s, PipeState>, token: u64) {
loop {
let buffered = st.pending.contains(&token);
if !buffered && !st.in_flight_tokens.contains_key(&token) {
return;
}
if buffered {
if let Some(job) = self.take_job(&mut st) {
drop(st);
let outcome = (self.send)(job.0);
self.deliver(job.1, job.2, outcome);
st = self.lock();
continue;
}
}
st.parked_workers += 1;
let (guard, _) = self
.ready
.wait_timeout(st, std::time::Duration::from_secs(30))
.unwrap_or_else(|p| p.into_inner());
st = guard;
st.parked_workers -= 1;
}
}
/// Whether any bulk carrying this file's records has failed. The drain
/// loop breaks on it, mirroring the per-file `send_err` break it
/// replaced: no point reading and shipping the rest of a file whose
/// earlier records were already refused.
fn failed(&self, token: u64) -> bool {
self.lock().failed.contains(&token)
}
/// Block until the bulk(s) carrying this file's records were accepted.
/// `Ok` means journaled-safe; `Err` is the failure text for the
/// un-journaled path.
fn settle(&self, token: u64) -> Result<(), String> {
let mut st = self.lock();
loop {
if let Some(res) = st.done.remove(&token) {
return res;
}
// This worker is about to park, so `parked + 1` is what the
// conditions look like from in here. All parked: no submission
// can arrive, a residual buffer must ship now. Half parked: ship
// what is there so extraction and sending overlap instead of
// alternating in waves (the wave barrier is what made the first
// cut of this pipe slower than the per-file code).
let all = st.parked_workers + 1 >= st.live_workers;
let half = (st.parked_workers + 1) * 2 >= st.live_workers.max(1);
if !st.buf.is_empty() && (all || half) {
if let Some(job) = self.take_job(&mut st) {
drop(st);
let outcome = (self.send)(job.0);
self.deliver(job.1, job.2, outcome);
st = self.lock();
continue;
}
// Every wire slot is busy: park; a delivery will wake us.
}
st.parked_workers += 1;
let (guard, _) = self
.ready
.wait_timeout(st, std::time::Duration::from_secs(30))
.unwrap_or_else(|p| p.into_inner());
st = guard;
st.parked_workers -= 1;
}
}
/// `n` workers the pipe was sized for will never run (#1122: their
/// threads could not be started). Stop counting them as live so the
/// "all / half parked" ship conditions in [`Self::settle`] are judged
/// against the workers that exist; without this a phantom worker would
/// hold a residual buffer back until a park timeout.
fn abandon_workers(&self, n: usize) {
if n == 0 {
return;
}
let mut st = self.lock();
st.live_workers = st.live_workers.saturating_sub(n);
drop(st);
self.ready.notify_all();
}
/// A worker leaving its loop will submit nothing more. The last one out
/// drains the residual buffer so the run never ends with unflushed bytes.
fn retire(&self) {
let mut st = self.lock();
st.live_workers = st.live_workers.saturating_sub(1);
while !st.buf.is_empty() {
if let Some(job) = self.take_job(&mut st) {
drop(st);
let outcome = (self.send)(job.0);
self.deliver(job.1, job.2, outcome);
st = self.lock();
continue;
}
// Wire full: wait for a delivery to free a slot.
let (guard, _) = self
.ready
.wait_timeout(st, std::time::Duration::from_secs(30))
.unwrap_or_else(|p| p.into_inner());
st = guard;
}
// Live workers may have dropped to zero: anyone still parked must
// re-check whether they are now the last one able to ship.
self.ready.notify_all();
}
/// Detach the buffer as a send job if a wire slot is free. Called with
/// the lock held; the caller drops the lock before sending.
fn take_job(&self, st: &mut PipeState) -> Option<PipeJob> {
if st.buf.is_empty() || st.in_flight >= MAX_IN_FLIGHT {
return None;
}
st.in_flight += 1;
st.docs = 0;
for t in &st.pending {
*st.in_flight_tokens.entry(*t).or_default() += 1;
}
Some((
std::mem::take(&mut st.buf),
std::mem::take(&mut st.pending),
std::mem::take(&mut st.owners),
))
}
/// Resolve a completed job: reclaim the wire slot, settle every token it
/// carried, wake the parked. Same outcome handling as
/// `record_bulk_outcome`, resolved per token instead of through the
/// caller's `send_err`.
fn deliver(
&self,
tokens: Vec<u64>,
owners: HashMap<String, u64>,
outcome: anyhow::Result<crate::esclient::BulkOutcome>,
) {
let mut st = self.lock();
st.in_flight = st.in_flight.saturating_sub(1);
for t in &tokens {
if let Some(n) = st.in_flight_tokens.get_mut(t) {
*n -= 1;
if *n == 0 {
st.in_flight_tokens.remove(t);
}
}
}
match outcome {
Ok(outcome) => {
if outcome.server_errors > 0 {
let msg = format!(
"bulk backend failed for {} item(s): {}. Source file was not journaled \
complete; fix the server condition (or wait for it to clear) and rerun \
autoindex — the run resumes from the journal",
outcome.server_errors,
server_error_text(&outcome)
);
for t in &tokens {
st.failed.insert(*t);
st.other_refusal.insert(*t);
st.too_large.remove(t);
st.done.insert(*t, Err(msg.clone()));
}
} else if outcome.item_errors > 0 {
// Charge each refused record to the file whose `_id` it
// carried: that file is not journaled, so the rerun the
// abort asks for re-sends it, and the files whose records
// were all accepted settle Ok. A refusal without a known
// `_id` fails every file in the bulk. Settling all of them
// Ok journaled a file past a record never stored (#2807).
let mut refused: HashMap<u64, Vec<String>> = HashMap::new();
let mut too_large: HashMap<u64, (bool, String)> = HashMap::new();
let mut unowned = outcome.refused.len() as u64 != outcome.item_errors;
for item in &outcome.refused {
match item.id.as_ref().and_then(|id| owners.get(id)) {
Some(token) => {
refused.entry(*token).or_default().push(item.error.clone());
let entry = too_large
.entry(*token)
.or_insert_with(|| (true, item.error.clone()));
entry.0 &= item.too_large;
}
None => unowned = true,
}
}
// A file set aside for size is junk, not a backend
// rejection, so it is not counted as one.
let mut set_aside = 0u64;
for (t, (all_too_large, reason)) in too_large {
if all_too_large && !unowned && !st.other_refusal.contains(&t) {
set_aside += refused.get(&t).map_or(0, |e| e.len() as u64);
st.too_large.insert(t, reason);
} else {
st.other_refusal.insert(t);
st.too_large.remove(&t);
}
}
self.rejected_records
.fetch_add(outcome.item_errors - set_aside, Ordering::Relaxed);
for t in &tokens {
let errors = refused.get(t);
if unowned || errors.is_some() {
let msg = match errors {
Some(errors) => format!(
"the backend refused {} of this file's record(s): {}",
errors.len(),
errors[0]
),
None => format!(
"the backend refused {} record(s) in the bulk carrying \
this file: {}",
outcome.item_errors,
outcome.first_error.as_deref().unwrap_or("no reason given")
),
};
if unowned {
st.other_refusal.insert(*t);
st.too_large.remove(t);
}
st.failed.insert(*t);
st.done.insert(*t, Err(msg));
} else if !st.failed.contains(t) {
st.done.insert(*t, Ok(()));
}
}
} else {
for t in &tokens {
if !st.failed.contains(t) {
st.done.insert(*t, Ok(()));
}
}
}
}
Err(error) => {
let msg = format!("{error:#}");
for t in &tokens {
st.failed.insert(*t);
st.other_refusal.insert(*t);
st.too_large.remove(t);
st.done.insert(*t, Err(msg.clone()));
}
}
}
self.ready.notify_all();
}
}
// ─── second-brain graph runtime ──────────────────────────────────────────
/// Per-run graph state, shared read-only with the Phase B workers
/// (SECOND_BRAIN_SPEC §6.6). Built after the plan is final because the
/// detectors resolve links against the FULL corpus — a per-file view could
/// not tell "dangling" from "not walked yet".
struct GraphRt {
corpus: detect::CorpusIndex,
detectors: Vec<Box<dyn detect::EdgeDetector>>,
/// Raw-source href pass handle. Lives outside the registry because the
/// HTML extractor strips markup before sectioning, so anchors only exist
/// in the raw bytes — a source the `EdgeDetector` trait deliberately
/// never sees (see `detect::href` module docs).
href_raw: detect::href::Href,
edges_index: String,
brain: String,
/// ONE wall-clock stamp per run: `created_at` is the single
/// non-deterministic edge field (§6.4); per-worker clocks would make two
/// halves of one run disagree about when it happened.
created_at_ms: i64,
/// detector tag → edges written this run (run-summary honesty §6.6.4).
written: Mutex<std::collections::BTreeMap<&'static str, u64>>,
self_dropped: AtomicU64,
/// Edges soft-invalidated by this run: prior-generation edges of replaced
/// files (before this run's writes) plus edges of un-re-read mail files
/// that the corpus-wide pass superseded (after them).
invalidated: AtomicU64,
}
/// Text-section locator → human label ("section 3", "page 2 section 0").
/// `emit_document` section locators are `s{i}`; PDF sections are
/// `p{page}-s{sec}` (extract/pdf.rs — page-major, so stream order IS the
/// lexicographic (page, sec) reading order). Everything else (row/line/byte/
/// table locators) is not a text section, returns None, and must not reach
/// `detect_text`. The label is used verbatim in sequence evidence rationales.
fn section_label(locator: &str) -> Option<String> {
fn digits(s: &str) -> bool {
!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
}
if let Some(rest) = locator.strip_prefix('s') {
return digits(rest).then(|| format!("section {rest}"));
}
let rest = locator.strip_prefix('p')?;
let (page, sec) = rest.split_once("-s")?;
(digits(page) && digits(sec)).then(|| format!("page {page} section {sec}"))
}
// ─── glob matchers (`--stub`, `--exclude`) ────────────────────────────────
/// Longest accepted glob. Far beyond any pattern a person types, and far
/// below the length at which the compiled regex hits its size limit.
const MAX_GLOB_LEN: usize = 4096;
/// Compiled glob patterns for one flag. `--stub` uses it to decide which
/// files become name cards; `--exclude` uses it to leave paths out of the
/// walk's inventory entirely (#2483).
///
/// Glob semantics (gitignore-flavored): `**` crosses `/`, `*` and `?` do
/// not; a pattern without `/` matches against the file NAME anywhere in the
/// tree, a pattern with `/` matches the full root-relative path.
pub struct GlobMatcher {
by_name: Vec<regex::Regex>,
by_path: Vec<regex::Regex>,
}
impl GlobMatcher {
/// `flag` names the option the patterns came from, so a rejected pattern
/// says which one to fix.
pub fn compile(globs: &[String], flag: &str) -> Result<Self> {
let mut by_name = Vec::new();
let mut by_path = Vec::new();
for g in globs {
// `glob_to_regex` escapes every metacharacter, so no glob can
// produce a SYNTACTICALLY invalid regex — the only reachable
// failure is the compiled-size limit, which `?` (→ `[^/]`) and
// `**` (→ `.*`) reach at ~10^5 characters. Caught here by length
// so the message names the flag and the cause instead of
// surfacing a regex-internal "compiled regex exceeds size limit".
if g.len() > MAX_GLOB_LEN {
anyhow::bail!(
"{flag} {}…: pattern is {} characters (limit {MAX_GLOB_LEN})",
g.chars().take(40).collect::<String>(),
g.len()
);
}
let re = regex::Regex::new(&glob_to_regex(g))
.with_context(|| format!("{flag} {g}: invalid pattern"))?;
if g.contains('/') {
by_path.push(re);
} else {
by_name.push(re);
}
}
Ok(Self { by_name, by_path })
}
pub fn is_empty(&self) -> bool {
self.by_name.is_empty() && self.by_path.is_empty()
}
/// `rel` is the root-relative path with forward slashes.
pub fn matches(&self, rel: &str) -> bool {
if self.by_path.iter().any(|re| re.is_match(rel)) {
return true;
}
if self.by_name.is_empty() {
return false;
}
let name = rel.rsplit('/').next().unwrap_or(rel);
self.by_name.iter().any(|re| re.is_match(name))
}
}
fn glob_to_regex(glob: &str) -> String {
let mut out = String::from("^");
let mut chars = glob.chars().peekable();
while let Some(c) = chars.next() {
match c {
'*' => {
if chars.peek() == Some(&'*') {
chars.next();
// `**/` also swallows its slash so `**/x` matches a
// top-level `x`.
if chars.peek() == Some(&'/') {
chars.next();
out.push_str("(?:.*/)?");
} else {
out.push_str(".*");
}
} else {
out.push_str("[^/]*");
}
}
'?' => out.push_str("[^/]"),
other => out.push_str(®ex::escape(&other.to_string())),
}
}
out.push('$');
out
}
/// The synthetic sniff result for a `--stub`-designated file.
///
/// `logical_path` is the file as the CORPUS names it, which under durable
/// preparation is not the path the bytes live at (`blobs/00000000`). A stub's
/// only output is a name card, so taking the name from the content path would
/// title every stub after a blob ordinal — the #294 failure class that
/// `Sniffed::logical_name` exists to prevent.
fn stub_sniffed(logical_path: &Path) -> Sniffed {
Sniffed {
family: Family::Stub,
gzip: false,
binary_kind: None,
csv: None,
encoding: "utf-8",
logical_name: logical_path.file_name().map(std::path::PathBuf::from),
}
}
#[cfg(test)]
mod stub_matcher_tests {
use super::GlobMatcher;
fn m(globs: &[&str]) -> GlobMatcher {
GlobMatcher::compile(
&globs.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
"--stub",
)
.unwrap()
}
#[test]
fn a_bare_pattern_matches_file_names_anywhere() {
let s = m(&["*.csv"]);
assert!(s.matches("unity/Assets/Face/f_roommate_004.csv"));
assert!(s.matches("top.csv"));
assert!(!s.matches("unity/Assets/notes.csv.md"));
}
#[test]
fn a_path_pattern_matches_the_root_relative_path() {
let s = m(&["unity/**/*.csv"]);
assert!(s.matches("unity/Assets/Face/f_roommate_004.csv"));
assert!(s.matches("unity/top.csv"), "**/ also matches zero dirs");
assert!(!s.matches("backend/data/users.csv"), "scoped to unity/");
}
#[test]
fn single_star_does_not_cross_directories() {
let s = m(&["unity/*.csv"]);
assert!(s.matches("unity/top.csv"));
assert!(!s.matches("unity/Assets/deep.csv"));
}
#[test]
fn regex_metacharacters_in_patterns_are_literal() {
let s = m(&["data(v1).csv"]);
assert!(s.matches("x/data(v1).csv"));
assert!(!s.matches("x/dataXv1Y.csv"));
}
#[test]
fn an_invalid_pattern_fails_loudly_at_startup() {
// The old body asserted only that a VALID pattern compiles, so it
// never tested its own name and would have passed against a `compile`
// that could not fail at all.
let msg = match GlobMatcher::compile(&["?".repeat(super::MAX_GLOB_LEN + 1)], "--stub") {
Ok(_) => panic!("an over-long pattern must be refused"),
Err(e) => e.to_string(),
};
assert!(msg.contains("--stub"), "message must name the flag: {msg}");
assert!(
msg.contains(&super::MAX_GLOB_LEN.to_string()),
"message must state the limit: {msg}"
);
}
/// Why the error above is the ONLY reachable one: `glob_to_regex`
/// escapes every metacharacter, so no amount of regex syntax in a glob
/// can produce an invalid pattern. Anything asserting otherwise is
/// asserting something the code makes impossible.
#[test]
fn regex_syntax_in_a_glob_is_never_a_compile_error() {
for g in ["[", "(", "\\", "*?[a-", "a{2,", "(?P<x>", "+", "|", "^$"] {
assert!(
GlobMatcher::compile(&[g.to_string()], "--stub").is_ok(),
"{g} must compile: metacharacters are escaped, not interpreted"
);
}
}
}
// ─── Phase A: per-file scan (sniff + bounded sampling) ───────────────────
struct FileScan {
sniffed: Option<Sniffed>,
sketches: Vec<GroupSketch>,
junk: Option<(String, String)>, // (status, reason)
/// Run-local PDF extraction produced during sampling. This is consumed by
/// Phase B only when it is bound to the same full-content generation.
pdf_spool: Option<extract::pdf::ExtractionSpool>,
pdf_spool_fallbacks: Vec<extract::pdf::SpoolFallback>,
}
/// One sampled group within a file: every field it produced, plus the names
/// that came from the file rather than from the extractor (`FieldOrigin`).
/// Only the latter may decide which dataset the file joins — see `dataset`.
struct GroupSketch {
group: Option<String>,
fields: HashMap<String, infer::FieldAcc>,
key_fields: std::collections::HashSet<String>,
records: u64,
/// Rows in this group. `records` stops at the sample; this does not.
population: u64,
}
fn take_pdf_spool_if_indexable<T>(
spool: &mut Option<T>,
is_junk: bool,
budget: &extract::pdf::ExtractionSpoolBudget,
) -> Option<T> {
if is_junk {
if spool.is_some() {
budget.record_discarded_before_replay();
}
spool.take();
None
} else {
spool.take()
}
}
/// Everything phase A needs beyond the file list and the run config: where a
/// run-local PDF artifact may live, the shared admission budget, the one-line
/// capacity explanation reported when files fall back — and the progress
/// surface those lines go out through, because phase A now reports every file
/// it touches (#241) as well as every artifact it could not keep.
///
/// Grouped so `scan_file` and `build_phase_a` each take one parameter instead
/// of four.
struct PhaseAContext<'a> {
state_dir: &'a Path,
budget: &'a std::sync::Arc<extract::pdf::ExtractionSpoolBudget>,
capacity_warning: Option<&'a str>,
progress: &'a Progress,
/// Throughput evidence for the pre-index estimate. Phase A already parses
/// every file; timing that parse is the only way to price the run on the
/// machine it will actually run on rather than on ours.
meter: &'a estimate::Meter,
/// How much phase-A work THIS run did. Owned by the run, not by the
/// process — see [`ScanTally`].
tally: &'a ScanTally,
}
/// Files that actually ran the Phase-A scan/parse, counted **per run**.
///
/// The incremental re-index fast path skips the parse for byte-identical
/// files, so this is how a test proves an unchanged re-run parses zero files.
///
/// It used to be a process-global `static`, which made that proof unsound
/// (#891): `cargo test` runs one lib test binary multi-threaded, every
/// concurrent run added to the same number, and a test reading it after its own
/// run got a total that included whatever the other tests parsed in the
/// meantime — a false red measured at 2 of 6 and 1 of 6 local suite runs on the
/// branch that found it (#886). One tally is created per `run_index_report`
/// invocation and reaches phase A through [`PhaseAContext`], so cross-run
/// interference is now unrepresentable rather than merely unlikely.
///
/// `Relaxed`: one increment per scanned file, ordered against nothing — the
/// cost has to stay negligible against the parse it counts, and readers only
/// look after their run has joined every phase-A thread.
#[derive(Debug, Default)]
pub(crate) struct ScanTally {
parsed: std::sync::atomic::AtomicUsize,
}
impl ScanTally {
fn record_parse(&self) {
self.parsed
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
/// Files this run ran the Phase-A scan/parse for.
#[cfg(test)]
pub(crate) fn files_parsed(&self) -> usize {
self.parsed.load(std::sync::atomic::Ordering::Relaxed)
}
}
/// Render a byte count in the largest whole binary unit that divides it, so the
/// "skipped: oversized" note reads `2 GB` for the default and `10 MB` for a
/// source-watcher cap (#1233) rather than a raw byte count, while an awkward
/// value still prints exactly in bytes.
fn human_size(bytes: u64) -> String {
const MB: u64 = 1 << 20;
if bytes != 0 && bytes.is_multiple_of(GB) {
format!("{} GB", bytes / GB)
} else if bytes != 0 && bytes.is_multiple_of(MB) {
format!("{} MB", bytes / MB)
} else {
format!("{bytes} bytes")
}
}
/// Scan-time skip for a whole-file family over `--max-file-bytes`.
///
/// Names the file's actual size and the flag that raises this cap. It does
/// not raise the 8 MiB per-document ceiling.
fn oversized_family_reason(family: &str, size: u64, max_file_bytes: u64) -> String {
format!(
"oversized for non-streaming family {family} ({} > {}); raise --max-file-mb",
human_size(size),
human_size(max_file_bytes),
)
}
fn scan_file(
path: &Path,
size: u64,
digest: &str,
ctx: &PhaseAContext<'_>,
sample: usize,
max_file_bytes: u64,
stub: bool,
) -> FileScan {
ctx.tally.record_parse();
let state_dir = ctx.state_dir;
let pdf_spool_budget = ctx.budget;
let mut out = FileScan {
sniffed: None,
sketches: Vec::new(),
junk: None,
pdf_spool: None,
pdf_spool_fallbacks: Vec::new(),
};
let sn = if stub {
stub_sniffed(path)
} else {
match sniff::sniff(path) {
Ok(s) => s,
Err(e) => {
out.junk = Some(match content::unreadable_junk_fields(&e) {
Some((status, reason)) => (status.into(), reason),
None => ("junk".into(), format!("unreadable: {e}")),
});
return out;
}
}
};
if sn.family == Family::Binary {
let kind = sn.binary_kind.clone().unwrap_or_else(|| "unknown".into());
// An archive gets the action, not just the verdict: a Google Takeout
// download IS one `.zip`/`.tgz`, and "binary content (zip)" tells its
// owner nothing about why their mail is not searchable.
let reason = sniff::archive_advice(&kind, sn.gzip)
.or_else(|| sniff::unsupported_document_advice(&kind))
.or_else(|| sniff::unsupported_data_advice(&kind))
.unwrap_or_else(|| format!("binary content ({kind})"));
out.junk = Some(("junk".into(), reason));
out.sniffed = Some(sn);
return out;
}
// whole-file families get a size cap; streaming families don't need one
let whole_file = matches!(
sn.family,
Family::Json
| Family::Html
| Family::Yaml
| Family::TxtProse
| Family::Pdf
| Family::Docx
| Family::Doc
| Family::Pptx
| Family::Epub
| Family::Ipynb
| Family::Man
);
if whole_file && size > max_file_bytes {
out.junk = Some((
"skipped".into(),
oversized_family_reason(sn.family.as_str(), size, max_file_bytes),
));
out.sniffed = Some(sn);
return out;
}
let limit = sample_limit_bytes(sn.family, path);
type GroupAcc = (
HashMap<String, infer::FieldAcc>,
u64,
std::collections::HashSet<String>,
);
let mut groups: HashMap<Option<String>, GroupAcc> = HashMap::new();
// Grouped families keep reading past the per-group sample size: their
// groups (SQL tables, Unity classes) appear all through the file, and
// stopping at the first N records would leave later groups unsampled and
// untyped.
let grouped_family = matches!(
sn.family,
Family::SqlDump | Family::Sqlite | Family::Xlsx | Family::Xls | Family::UnityYaml
);
let mut sink = |rec: extract::RawRecord| -> bool {
let entry = groups.entry(rec.group.clone()).or_default();
if (entry.1 as usize) < sample {
// Every field feeds type inference; only the ones the FILE named
// feed the clustering key, so an extractor that starts emitting a
// new field cannot re-home the file (#178).
let from_file = rec.origin == extract::FieldOrigin::Data;
for (k, v) in &rec.fields {
entry.0.entry(k.clone()).or_default().add(v);
if from_file {
entry.2.insert(k.clone());
}
}
}
entry.1 += 1;
if grouped_family {
true // read on — later tables still need sampling
} else {
(entry.1 as usize) < sample
}
};
// Timed span: the extraction itself, nothing around it. The PDF spool's
// post-parse `content::verify` re-read is deliberately outside it — phase
// B never repeats that read, so charging it here would price a cost the
// estimate is trying to predict away.
let extraction_started = Instant::now();
let extraction_elapsed;
let extraction = if sn.family == Family::Pdf {
let parsed = extract::pdf::extract_and_spool(
path,
state_dir,
size,
digest,
pdf_spool_budget,
&mut sink,
);
extraction_elapsed = extraction_started.elapsed();
match parsed {
Ok((stats, spool, fallback)) => {
// The inventory digest was computed before Phase A. Only hand
// bytes to Phase B when the source still matches that exact
// generation after the parser has finished reading it.
// If no reusable artifact exists, avoid a second full-file
// read: Phase B performs the authoritative generation check
// immediately before its ordinary reparse.
if spool.is_none() {
out.pdf_spool_fallbacks.extend(fallback);
} else {
match content::verify(path, size, digest) {
Ok(()) => {
out.pdf_spool = spool;
out.pdf_spool_fallbacks.extend(fallback);
}
Err(error) => {
if spool.is_some() {
pdf_spool_budget.record_discarded_before_replay();
}
pdf_spool_budget.record_source_generation_changed();
out.pdf_spool_fallbacks.extend(fallback);
out.pdf_spool_fallbacks.push(extract::pdf::SpoolFallback {
category: "source_generation_changed",
message: format!(
"source generation changed after extraction: {error:#}"
),
});
}
}
}
Ok(stats)
}
Err(error) => Err(error),
}
} else {
let parsed = extract::extract(path, &sn, limit, &mut sink);
extraction_elapsed = extraction_started.elapsed();
parsed
};
let mut populations: Vec<(Option<String>, u64)> = Vec::new();
match extraction {
Ok(stats) => {
populations = stats.populations;
if groups.is_empty() {
if let Some(reason) = stats.refusal {
out.junk = Some(("skipped".into(), reason));
} else {
out.junk = Some((
"junk".into(),
format!(
"no records extracted ({} candidate family, {} junk lines)",
sn.family.as_str(),
stats.junk
),
));
}
}
}
Err(e) => {
if groups.is_empty() {
out.junk = Some(("junk".into(), format!("extract failed: {e}")));
}
}
}
// Throughput evidence, but only where the read was provably complete: the
// sampler stops at whichever of the byte cap or the record cap comes
// first, and timing a partial read against the full file size would invent
// a rate this machine never demonstrated. `exact_scan_bytes` owns that
// judgement; a junked file is never timed at all, because phase B will
// not process it.
if out.junk.is_none() {
let sampled = groups.values().map(|(_, records, _)| *records).max();
if let Some(bytes) = sampled.and_then(|records| {
estimate::exact_scan_bytes(sn.family, sn.gzip, size, records, sample)
}) {
ctx.meter.record(sn.family, bytes, extraction_elapsed);
}
}
out.sketches = groups
.into_iter()
.map(|(group, (fields, records, key_fields))| {
let declared = populations
.iter()
.filter(|(g, _)| g == &group)
.map(|(_, n)| *n)
.max()
.unwrap_or(records);
GroupSketch {
group,
fields,
key_fields,
records,
population: declared.max(records),
}
})
.collect();
// CSV, JSONL and logs declare no length, so `records` is the sample: it
// stops at `sample` rows (500 by default) or at the sample byte cap. A
// 100_000-row CSV then looked like a 500-row one, and the dataset caps
// (`dataset::DATASET_CAP_PROTECT_RECORDS`) merged it into a shared index
// as if it were small. When the sample may have stopped early, count on
// with the same extractor up to the protect threshold. That is enough to
// decide the caps and stays bounded however large the file is.
if matches!(sn.family, Family::Csv | Family::Jsonl | Family::Logs) {
let threshold = dataset::DATASET_CAP_PROTECT_RECORDS;
let sample_cut = |s: &GroupSketch| {
s.population < threshold
&& (s.records >= sample as u64 || limit.is_some_and(|l| sn.gzip || size > l))
};
if out.sketches.iter().any(sample_cut) {
let groups_seen = out.sketches.len();
let mut counts: HashMap<Option<String>, u64> = HashMap::new();
let mut count = |rec: extract::RawRecord| -> bool {
*counts.entry(rec.group).or_default() += 1;
counts.len() < groups_seen || counts.values().any(|n| *n < threshold)
};
// A read error part-way still leaves a lower bound: every
// record counted was really there.
let _ = extract::extract(path, &sn, None, &mut count);
for s in &mut out.sketches {
if let Some(&n) = counts.get(&s.group) {
s.population = s.population.max(n);
}
}
}
}
out.sketches.sort_by(|a, b| a.group.cmp(&b.group));
out.sniffed = Some(sn);
out
}
#[cfg(test)]
mod clustering_key_tests {
use super::*;
#[test]
fn perl_code_cap_scan_preserves_the_size_skip_with_a_larger_whole_file_allowance() {
let dir = tempfile::tempdir().unwrap();
let prefix = "sub important_function { return 1; }\n#";
let size = (2 << 20) + 1;
let body = format!("{prefix}{}\n", "x".repeat(size - prefix.len() - 1));
let scanned = scan(dir.path(), "handwritten.pl", &body);
assert_eq!(scanned.sniffed.unwrap().family, Family::Code);
assert!(scanned.sketches.is_empty());
let (status, reason) = scanned.junk.unwrap();
assert_eq!(status, "skipped");
assert!(reason.contains("2097153 bytes"), "{reason}");
assert!(reason.contains("2097152 bytes"), "{reason}");
assert!(reason.contains("--max-file-mb"), "{reason}");
assert!(!reason.contains("no records extracted"), "{reason}");
}
fn scan(dir: &Path, name: &str, body: &str) -> FileScan {
let path = dir.join(name);
std::fs::write(&path, body).unwrap();
let size = std::fs::metadata(&path).unwrap().len();
// Clustering keys are decided by extraction, not by PDF artifact
// reuse: a zero budget keeps these cases on the plain parse path.
let budget = extract::pdf::ExtractionSpoolBudget::new(0, 0);
let progress = Progress::silent();
let meter = estimate::Meter::new();
let ctx = PhaseAContext {
state_dir: dir,
budget: &budget,
capacity_warning: None,
progress: &progress,
meter: &meter,
tally: &ScanTally::default(),
};
scan_file(&path, size, "d0", &ctx, 500, 2 << 30, false)
}
/// The #178 mechanism, from the extractor to the clustering key: a source
/// file that yields symbols and one that yields none produce the SAME
/// (empty) key, so no extractor improvement can move a file between
/// datasets. `defs` still reaches the mapping — it is indexed, just not
/// used to decide identity.
#[test]
fn symbols_never_enter_the_clustering_key() {
let dir = std::env::temp_dir().join("xerj-ax-178-key");
std::fs::create_dir_all(&dir).unwrap();
// #170 now captures the `const`, so this file parses to one symbol and
// GAINS a `defs` field — the case #170 improves. The point of this test
// survives that change: the newly-captured extractor name must still be
// kept out of the clustering key (#180), so a const-only file and a
// fn/struct file still land in ONE dataset rather than re-homing apart.
let table = scan(
&dir,
"table.rs",
"const BYTE_FREQUENCIES: [u8; 2] = [1, 2];\n",
);
let code = scan(&dir, "code.rs", "fn main() {}\nstruct S;\n");
let _ = std::fs::remove_dir_all(&dir);
for s in [&table, &code] {
assert_eq!(s.sketches.len(), 1, "one code record per file");
assert!(
s.sketches[0].key_fields.is_empty(),
"extractor-invented names leaked into the clustering key: {:?}",
s.sketches[0].key_fields
);
}
// #170: the const is now captured, so the table file has `defs` too.
assert!(table.sketches[0].fields.contains_key("defs"));
assert!(code.sketches[0].fields.contains_key("defs"));
// …so the two land in one dataset instead of one dataset each.
let rels = vec!["table.rs".to_string(), "code.rs".to_string()];
let sketches: Vec<dataset::Sketch> = [&table, &code]
.iter()
.enumerate()
.map(|(i, s)| dataset::Sketch {
file_idx: i,
group: s.sketches[0].group.clone(),
family: s.sniffed.as_ref().unwrap().family,
fields: s.sketches[0].fields.clone(),
key_fields: s.sketches[0].key_fields.clone(),
records: s.sketches[0].records,
population: s.sketches[0].population,
})
.collect();
let scopes = vec![String::new(); rels.len()];
let clusters = dataset::cluster(sketches, &rels, &scopes);
assert_eq!(clusters.len(), 1, "{clusters:#?}");
}
/// #2337: a hand-written DDL file, including a routine whose body
/// inserts a row, is code. `scan_file` must not record it as junk.
#[test]
fn a_handwritten_sql_schema_is_code_not_junk() {
let dir = tempfile::tempdir().unwrap();
let body = "-- rule engine\n\
CREATE TABLE rules (\n\
id integer primary key,\n\
code text not null\n\
);\n\
CREATE OR REPLACE FUNCTION apply_slope(percent numeric)\n\
RETURNS text LANGUAGE plpgsql AS $$\n\
BEGIN\n\
INSERT INTO audit(note) VALUES ('slope');\n\
RETURN 'low';\n\
END;\n\
$$;\n";
let scanned = scan(dir.path(), "30_rule_engine.sql", body);
assert!(scanned.junk.is_none(), "DDL was junked: {:?}", scanned.junk);
assert_eq!(
scanned.sniffed.as_ref().map(|s| s.family),
Some(Family::Code)
);
let defs: Vec<String> = scanned
.sketches
.iter()
.filter_map(|s| s.fields.get("defs"))
.flat_map(|v| v.examples.iter().chain(v.raw_values.iter()).cloned())
.collect();
assert!(
defs.iter()
.any(|d| d.contains("table rules") && d.contains("function apply_slope")),
"defs={defs:?} junk={:?}",
scanned.junk
);
}
/// The other half: a data file's own column names ARE the key, so real
/// schemas still drive clustering.
#[test]
fn data_field_names_are_the_clustering_key() {
let dir = std::env::temp_dir().join("xerj-ax-178-data");
std::fs::create_dir_all(&dir).unwrap();
let csv = scan(&dir, "t.csv", "id,email\n1,[email protected]\n2,[email protected]\n");
let _ = std::fs::remove_dir_all(&dir);
let mut names: Vec<&str> = csv.sketches[0]
.key_fields
.iter()
.map(String::as_str)
.collect();
names.sort();
assert_eq!(names, ["email", "id"]);
}
/// #1856: phase A stops at the sample, but the sketch keeps the real
/// length of each array, and the sibling array is not a field of the
/// primary rows.
#[test]
fn a_multi_array_json_file_keeps_each_arrays_population() {
let dir = tempfile::tempdir().unwrap();
let mut functions = Vec::new();
for i in 0..40 {
functions.push(format!(r#"{{"name":"f{i}","addr":{i}}}"#));
}
let body = format!(
r#"{{"functions":[{}],"runs":[{{"label":"boot","start":1}},{{"label":"loop","start":2}},{{"label":"done","start":3}}]}}"#,
functions.join(",")
);
let path = dir.path().join("subsystem_map.json");
std::fs::write(&path, body).unwrap();
let size = std::fs::metadata(&path).unwrap().len();
let budget = extract::pdf::ExtractionSpoolBudget::new(0, 0);
let progress = Progress::silent();
let meter = estimate::Meter::new();
let ctx = PhaseAContext {
state_dir: dir.path(),
budget: &budget,
capacity_warning: None,
progress: &progress,
meter: &meter,
tally: &ScanTally::default(),
};
let scanned = scan_file(&path, size, "d0", &ctx, 2, 2 << 30, false);
let primary = scanned
.sketches
.iter()
.find(|s| s.group.is_none())
.expect("primary array");
assert_eq!(primary.records, 2, "the sample stops at 2");
assert_eq!(primary.population, 40, "the array length is the population");
assert!(
!primary.fields.contains_key("runs"),
"sibling array leaked into the primary fields: {:?}",
primary.fields.keys().collect::<Vec<_>>()
);
let runs = scanned
.sketches
.iter()
.find(|s| s.group.as_deref() == Some("runs"))
.expect("runs group");
assert_eq!(runs.records, 2);
assert_eq!(runs.population, 3);
}
fn csv_body(tag: &str, rows: usize) -> String {
let mut b = format!("{tag}_id,{tag}_name,{tag}_val\n");
for i in 0..rows {
b.push_str(&format!("{i},name{i},{}\n", i * 3));
}
b
}
fn jsonl_body(tag: &str, rows: usize) -> String {
let mut b = String::new();
for i in 0..rows {
b.push_str(&format!(
"{{\"{tag}_id\":{i},\"{tag}_name\":\"name{i}\",\"{tag}_val\":{}}}\n",
i * 3
));
}
b
}
/// Line-record files declare no length, so the sample (500 rows) used to
/// be the population and a 2000-row CSV/JSONL counted as small (#2422).
/// Phase A now counts on to the protect threshold; a 10-row file still
/// reports exactly its 10 rows.
#[test]
fn a_sampled_line_record_file_reports_rows_past_the_sample() {
let dir = tempfile::tempdir().unwrap();
for (name, body) in [
("big.csv", csv_body("b", 2000)),
("big.jsonl", jsonl_body("j", 2000)),
] {
let s = scan(dir.path(), name, &body);
assert_eq!(s.sketches.len(), 1, "{name}");
let sk = &s.sketches[0];
assert_eq!(sk.records, 500, "{name}: the sample still stops at 500");
assert!(
sk.population >= dataset::DATASET_CAP_PROTECT_RECORDS,
"{name}: population {} is the sample, not the file",
sk.population
);
}
let small = scan(dir.path(), "small.csv", &csv_body("s", 10));
assert_eq!(small.sketches[0].records, 10);
assert_eq!(small.sketches[0].population, 10);
}
/// End to end through `cluster()`: past the run cap, 2000-row CSV and
/// JSONL files keep their own datasets, and the 10-row CSVs still merge
/// into one shared CSV dataset.
#[test]
fn past_the_run_cap_large_sampled_csv_and_jsonl_keep_their_own_index() {
let dir = tempfile::tempdir().unwrap();
let mut files: Vec<(String, String)> = Vec::new();
let n_big = dataset::MAX_DATASETS_PER_RUN + 2;
for i in 0..n_big {
files.push((format!("big{i}.csv"), csv_body(&format!("b{i}"), 2000)));
}
files.push(("big.jsonl".into(), jsonl_body("j", 2000)));
let n_small = 3;
for i in 0..n_small {
files.push((format!("small{i}.csv"), csv_body(&format!("s{i}"), 10)));
}
let mut rels = Vec::new();
let mut sketches = Vec::new();
for (idx, (name, body)) in files.iter().enumerate() {
let s = scan(dir.path(), name, body);
assert_eq!(s.sketches.len(), 1, "{name}");
let sk = &s.sketches[0];
sketches.push(dataset::Sketch {
file_idx: idx,
group: sk.group.clone(),
family: s.sniffed.as_ref().unwrap().family,
fields: sk.fields.clone(),
key_fields: sk.key_fields.clone(),
records: sk.records,
population: sk.population,
});
rels.push(name.clone());
}
let scopes = vec![String::new(); rels.len()];
let clusters = dataset::cluster(sketches, &rels, &scopes);
let data: Vec<&dataset::Cluster> = clusters.iter().filter(|c| !c.is_docs).collect();
let home = |idx: usize| {
data.iter()
.find(|c| c.members.contains(&idx))
.unwrap_or_else(|| panic!("{} has no data dataset: {clusters:#?}", rels[idx]))
};
// Every large file — the CSVs and the JSONL — is alone in its dataset.
for (idx, rel) in rels.iter().enumerate().take(n_big + 1) {
assert_eq!(home(idx).members, vec![idx], "{rel} was merged");
}
// The 10-row CSVs share one dataset, rows intact.
let shared = home(n_big + 1);
let mut members = shared.members.clone();
members.sort();
assert_eq!(
members,
(n_big + 1..n_big + 1 + n_small).collect::<Vec<_>>()
);
assert_eq!(shared.records, 10 * n_small as u64);
assert_eq!(data.len(), n_big + 2);
}
}
#[cfg(test)]
mod phase_a_grouping_tests {
use super::*;
pub(super) fn cfg_for(root: &Path) -> IndexCfg {
IndexCfg {
root: root.to_path_buf(),
endpoint_url: None,
stub_globs: Vec::new(),
url: "http://unused.invalid".into(),
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: 10,
bulk_mb: 1,
bulk_timeout_secs: 10,
snapshot_max_bytes: 64 << 30,
prefix: "t".into(),
replace_prefix: false,
prefix_note: None,
state_dir: None,
fresh: true,
follow_symlinks: false,
follow_symlinks_outside_root: false,
ignore: crate::ignore_rules::IgnoreOptions::default(),
max_file_bytes: 2 << 30,
sample: 500,
no_semantic: false,
code_analyzer: Default::default(),
brain: None,
no_graph: true,
// 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: true,
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,
}
}
fn plan_for(root: &Path) -> Plan {
plan_for_cfg(root, &cfg_for(root))
}
fn plan_for_cfg(root: &Path, cfg: &IndexCfg) -> Plan {
let files = walk::walk(root, false).unwrap();
let keys: Vec<String> = files
.iter()
.map(|f| ids::file_key(&f.path, f.size).unwrap())
.collect();
let digests: Vec<String> = (0..files.len()).map(|i| format!("d{i}")).collect();
// Planning is what these cases assert on; a zero budget keeps every
// file on the plain parse path so no artifact is ever retained.
let budget = extract::pdf::ExtractionSpoolBudget::new(0, 0);
let progress = Progress::silent();
let meter = estimate::Meter::new();
let ctx = PhaseAContext {
state_dir: root,
budget: &budget,
capacity_warning: None,
progress: &progress,
meter: &meter,
tally: &ScanTally::default(),
};
build_phase_a(root, &files, &keys, &digests, Vec::new(), &ctx, cfg).plan
}
/// #1978: the semantic cap sees the array's real length, not the 500-row
/// sample. 100_001 short prose rows elect `semantic_text` on the sample
/// and must fall back, with the warning on the field.
#[test]
fn a_long_prose_column_past_the_record_cap_falls_back_to_text() {
let dir = tempfile::tempdir().unwrap();
let note = "The connection pool retries every failed handshake with backoff. \
Each worker owns one socket and never shares it across threads.";
let n = infer::SEMANTIC_DATA_MAX_RECORDS + 1;
let mut body = String::with_capacity((n as usize) * (note.len() + 24));
body.push('[');
for i in 0..n {
if i > 0 {
body.push(',');
}
body.push_str(r#"{"id":"#);
body.push_str(&i.to_string());
body.push_str(r#","note":""#);
body.push_str(note);
body.push_str(r#""}"#);
}
body.push(']');
std::fs::write(dir.path().join("rows.json"), body).unwrap();
let plan = plan_for(dir.path());
let dataset = plan
.datasets
.iter()
.find(|d| d.specs.iter().any(|s| s.name == "note"))
.expect("rows dataset");
assert!(dataset.semantic_field.is_none(), "{dataset:#?}");
let spec = dataset.specs.iter().find(|s| s.name == "note").unwrap();
assert_eq!(spec.es_type, "text");
let notes = spec.notes.join(" ");
assert!(notes.contains("--no-semantic"), "{notes}");
assert!(notes.contains(&n.to_string()), "{notes}");
}
/// A prose column under both caps still elects semantic_text. The cap
/// must not turn every JSON text field into plain text.
#[test]
fn a_short_prose_column_stays_semantic_text() {
let dir = tempfile::tempdir().unwrap();
let note = "The connection pool retries every failed handshake with backoff. \
Each worker owns one socket and never shares it across threads.";
let mut body = String::from("[");
// More than a config document, so the file stays a data dataset.
for i in 0..40 {
if i > 0 {
body.push(',');
}
body.push_str(&format!(r#"{{"id":{i},"note":"{note}"}}"#));
}
body.push(']');
std::fs::write(dir.path().join("rows.json"), body).unwrap();
let plan = plan_for(dir.path());
let dataset = plan
.datasets
.iter()
.find(|d| d.specs.iter().any(|s| s.name == "note"))
.expect("rows dataset");
assert_eq!(
dataset.semantic_field.as_deref(),
Some("note"),
"{dataset:#?}"
);
}
/// #1856: a file shaped like `subsystem_map.json` (one long array of small
/// objects beside a second array) plans two data datasets. The sibling
/// array is not a field, and the short rows do not elect semantic_text.
#[test]
fn a_multi_array_json_file_plans_one_dataset_per_array() {
let dir = tempfile::tempdir().unwrap();
let mut functions = Vec::new();
for i in 0..40 {
functions.push(format!(r#"{{"name":"fn{i}","addr":{i}}}"#));
}
let body = format!(
r#"{{"generated":"2026-01-01","functions":[{}],"runs":[{{"label":"boot","start":1}},{{"label":"loop","start":2}},{{"label":"done","start":3}}]}}"#,
functions.join(",")
);
std::fs::write(dir.path().join("subsystem_map.json"), body).unwrap();
let plan = plan_for(dir.path());
let data: Vec<_> = plan
.datasets
.iter()
.filter(|d| d.family != "docs")
.collect();
assert!(
data.iter().any(|d| d.group.is_none()),
"primary array: {:?}",
plan.datasets
.iter()
.map(|d| (&d.slug, &d.group, d.family.as_str()))
.collect::<Vec<_>>()
);
assert!(
data.iter().any(|d| d.group.as_deref() == Some("runs")),
"runs array: {:?}",
plan.datasets
.iter()
.map(|d| (&d.slug, &d.group))
.collect::<Vec<_>>()
);
let primary = data.iter().find(|d| d.group.is_none()).unwrap();
assert!(primary.semantic_field.is_none(), "{primary:#?}");
assert!(primary.specs.iter().all(|s| s.name != "runs"));
}
/// #1198 end to end through the real planner: `--code-analyzer code` puts
/// `code` on the document dataset that holds source (README included —
/// code and prose share the per-scope dataset), while the default leaves
/// today's election in place.
#[test]
fn code_analyzer_code_elects_code_on_a_dataset_holding_source() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(root.join("server.c"), CODE).unwrap();
std::fs::write(root.join("README.md"), PROSE).unwrap();
let mut cfg = cfg_for(root);
cfg.code_analyzer = infer::CodeAnalyzer::Code;
let with_flag = plan_for_cfg(root, &cfg);
let analyzers: Vec<_> = with_flag
.datasets
.iter()
.map(|d| d.text_analyzer.as_deref())
.collect();
assert_eq!(
analyzers,
vec![Some(infer::CODE_TEXT_ANALYZER)],
"{:?}",
with_flag.datasets
);
let default = plan_for(root);
assert!(
default
.datasets
.iter()
.all(|d| d.text_analyzer.as_deref() != Some(infer::CODE_TEXT_ANALYZER)),
"the default must not elect `code`: {:?}",
default.datasets
);
}
/// #1198: a folder with no file the sniffer routes to the code extractor
/// never gets `code`, flag or not — the dataset is labelled
/// `Family::Code` regardless of content, so the election must look at the
/// members' own families.
#[test]
fn code_analyzer_code_leaves_a_prose_only_dataset_alone() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(root.join("README.md"), PROSE).unwrap();
std::fs::write(
root.join("GUIDE.md"),
format!("{PROSE}\nSee the handler table.\n"),
)
.unwrap();
let mut cfg = cfg_for(root);
cfg.code_analyzer = infer::CodeAnalyzer::Code;
let with_flag = plan_for_cfg(root, &cfg);
assert!(!with_flag.datasets.is_empty());
assert_eq!(
with_flag
.datasets
.iter()
.map(|d| d.text_analyzer.clone())
.collect::<Vec<_>>(),
plan_for(root)
.datasets
.iter()
.map(|d| d.text_analyzer.clone())
.collect::<Vec<_>>(),
"a prose-only dataset keeps today's election"
);
}
/// #1504: desk-phone syslog (`<PRI>Mon dd hh:mm:ss host tag[pid]: msg`)
/// used to plan as `txt-prose`, so timestamp, host and severity were not
/// fields and the stemmer kept the stop word `is`. It plans as `logs`
/// with the english analyzer.
#[test]
fn phone_syslog_plans_as_logs_with_the_english_analyzer() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(
root.join("phones.log"),
"<131>Oct 16 09:06:58 192.168.1.20 SIP [990]: registration failed\n\
<134>Oct 16 09:07:01 192.168.1.20 SIP [990]: call cleared\n\
<131>Oct 16 09:07:02 192.168.1.21 SIP[991]: SIP engine not registered\n\
<134>Oct 16 09:07:03 192.168.1.21 SIP[991]: watchdog reconnect\n\
Oct 16 09:07:04 pbx pbx-phone[990]: configuration loaded\n\
Oct 16 09:07:05 pbx pbx-phone[991]: device is online\n",
)
.unwrap();
let plan = plan_for(root);
let logs: Vec<_> = plan
.datasets
.iter()
.filter(|d| d.family == "logs")
.collect();
assert_eq!(
logs.len(),
1,
"expected one logs dataset, got {:?}",
plan.datasets
.iter()
.map(|d| (
d.slug.as_str(),
d.family.as_str(),
d.text_analyzer.as_deref()
))
.collect::<Vec<_>>()
);
assert_eq!(
logs[0].text_analyzer.as_deref(),
Some(infer::LOG_TEXT_ANALYZER)
);
let names: Vec<&str> = logs[0].specs.iter().map(|s| s.name.as_str()).collect();
for field in ["ts", "host", "program", "message", "severity"] {
assert!(names.contains(&field), "missing {field} in {names:?}");
}
let spec = |name: &str| {
logs[0]
.specs
.iter()
.find(|s| s.name == name)
.unwrap_or_else(|| panic!("missing {name}"))
};
assert_eq!(spec("ts").es_type, "date", "a time window filters on ts");
assert_eq!(logs[0].time_field.as_deref(), Some("ts"));
assert_eq!(spec("host").es_type, "keyword", "a device filter is exact");
assert_eq!(spec("severity").es_type, "keyword");
let body = dataset_create_body(logs[0]);
assert_eq!(
body["settings"]["index.query.default_match_operator"],
json!("and"),
"an omitted match on a log index requires every token"
);
}
/// #1504: vsftpd `xferlog` was already one record per line, but its ctime
/// stamp (`Fri Oct 16 09:06:58 2026`) was not a date, so a time-range
/// filter on the transfer log matched nothing. A prose file does not
/// pick up the log match-operator default.
#[test]
fn xferlog_timestamp_maps_as_date_and_prose_does_not_default_match_to_and() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(
root.join("xferlog"),
"Fri Oct 16 09:06:58 2026 1 10.0.0.7 4242 /uploads/fw.bin b _ o r admin ftp 0 * c\n\
Fri Oct 16 09:07:10 2026 2 10.0.0.8 10 /uploads/invalid.bin b _ o r admin ftp 0 * i\n\
Sat Oct 17 11:00:00 2026 0 10.0.0.9 0 /pub/README a C i a guest ftp 1 guest c\n\
Sun Oct 18 08:30:00 2026 4 10.0.0.7 100 /var/log/a.log b _ o r admin ftp 0 * c\n\
Mon Oct 19 09:06:58 2026 1 10.0.0.7 50 /uploads/cfg.xml b _ i r admin ftp 0 * c\n\
Tue Oct 20 09:06:58 2026 1 10.0.0.4 50 /uploads/cfg.xml b _ i r admin ftp 0 * c\n",
)
.unwrap();
let plan = plan_for(root);
let logs: Vec<_> = plan
.datasets
.iter()
.filter(|d| d.family == "logs")
.collect();
assert_eq!(
logs.len(),
1,
"{:?}",
plan.datasets.iter().map(|d| &d.family).collect::<Vec<_>>()
);
let ts = logs[0]
.specs
.iter()
.find(|s| s.name == "ts")
.expect("xferlog ts");
assert_eq!(ts.es_type, "date", "{ts:?}");
assert!(
ts.date_enc
.as_deref()
.is_some_and(|e| e.contains("asctime")),
"{ts:?}"
);
assert_eq!(logs[0].time_field.as_deref(), Some("ts"));
let host = logs[0].specs.iter().find(|s| s.name == "host").unwrap();
assert_eq!(host.es_type, "keyword");
assert_eq!(
dataset_create_body(logs[0])["settings"]["index.query.default_match_operator"],
json!("and")
);
let prose = tempfile::tempdir().unwrap();
std::fs::write(prose.path().join("README.md"), PROSE).unwrap();
let prose_plan = plan_for(prose.path());
assert!(!prose_plan.datasets.is_empty());
assert!(prose_plan.datasets.iter().all(|d| d.family != "logs"));
for dataset in &prose_plan.datasets {
assert!(
dataset_create_body(dataset)["settings"]
.get("index.query.default_match_operator")
.is_none(),
"a non-log index keeps match's OR default"
);
}
}
const CODE: &str = "// The event loop dispatches every ready connection to a worker.\n\
// Each worker drains its queue before polling for more sockets.\n\
static void dispatch_ready_connections(struct event_loop *loop) {\n\
for (int index = 0; index < loop->ready_count; index++) {\n\
worker_submit(loop->workers, loop->ready[index]);\n\
}\n\
}\n";
const PROSE: &str = "# Overview\n\nThis server accepts client connections and stores \
keys in memory. Every command travels through the same parser before the \
dispatcher routes it to the matching handler function.\n";
/// #173 end to end through the real planner: a tree holding two
/// repositories of source, prose and one-off config JSON yields one
/// document dataset per repository — with `body` elected `semantic_text`
/// — plus the genuine data dataset, instead of one dataset per incidental
/// config schema with no vector arm.
#[test]
fn a_two_repo_tree_plans_one_document_dataset_per_repo() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
for repo in ["valkey", "memcached"] {
std::fs::create_dir_all(root.join(repo).join(".git")).unwrap();
std::fs::write(root.join(repo).join(".git").join("HEAD"), "ref: x").unwrap();
}
std::fs::create_dir_all(root.join("valkey/src")).unwrap();
std::fs::create_dir_all(root.join("valkey/commands")).unwrap();
std::fs::create_dir_all(root.join("memcached/data")).unwrap();
std::fs::write(root.join("valkey/src/server.c"), CODE).unwrap();
std::fs::write(root.join("valkey/README.md"), PROSE).unwrap();
// one-off configs: single-record JSON, each with its own key set
std::fs::write(
root.join("valkey/commands/get.json"),
r#"{"GET": {"summary": "Return the string value stored at the given key.", "arity": 2}}"#,
)
.unwrap();
std::fs::write(
root.join("valkey/commands/set.json"),
r#"{"SET": {"summary": "Store the given string value under the given key.", "arity": 3}}"#,
)
.unwrap();
// distinct bytes — byte-identical files alias into one canonical copy
std::fs::write(root.join("memcached/proto.c"), format!("{CODE}\n// v2\n")).unwrap();
// a genuine data file: recurring rows, real schema
std::fs::write(
root.join("memcached/data/events.csv"),
"id,email,level\n1,[email protected],info\n2,[email protected],warn\n3,[email protected],info\n",
)
.unwrap();
let plan = plan_for(root);
let mut slugs: Vec<&str> = plan.datasets.iter().map(|d| d.slug.as_str()).collect();
slugs.sort();
assert_eq!(
slugs,
["memcached-data", "memcached-docs", "valkey-docs"],
"{:#?}",
plan.datasets
);
// every docs dataset carries the vector arm on body
for d in plan.datasets.iter().filter(|d| d.family == "docs") {
let body = d.specs.iter().find(|s| s.name == "body").unwrap();
assert_eq!(body.es_type, "semantic_text", "{}: {:#?}", d.slug, d.specs);
assert_eq!(d.semantic_field.as_deref(), Some("body"), "{}", d.slug);
}
// the one-off configs were demoted: document-rendered, and their
// config keys never reached the docs mapping
let by_rel: HashMap<&str, &FileAssignment> =
plan.files.values().map(|f| (f.rel.as_str(), f)).collect();
assert!(by_rel["valkey/commands/get.json"].as_document);
assert!(by_rel["valkey/commands/set.json"].as_document);
assert!(!by_rel["valkey/src/server.c"].as_document);
assert!(!by_rel["memcached/data/events.csv"].as_document);
let vdocs = plan
.datasets
.iter()
.find(|d| d.slug == "valkey-docs")
.unwrap();
assert!(
!vdocs.specs.iter().any(|s| s.name.contains("summary")),
"config keys leaked into the docs mapping: {:#?}",
vdocs.specs
);
assert_eq!(vdocs.file_count, 4, "code + prose + 2 demoted configs");
// the CSV kept its real schema
let data = plan
.datasets
.iter()
.find(|d| d.slug == "memcached-data")
.unwrap();
assert!(data.specs.iter().any(|s| s.name == "email"), "{data:#?}");
}
/// A minimal Excel workbook: inline-string text, numbers, and style 1 =
/// built-in date format 14 so a serial reads as a date.
pub(super) fn write_xlsx(path: &Path, sheets: &[(&str, &[&[&str]])]) {
use std::io::Write;
let cell = |r: usize, c: usize, v: &str| {
let at = format!("{}{}", (b'A' + c as u8) as char, r + 1);
match v.strip_prefix('#') {
Some(serial) => format!(r#"<c r="{at}" s="1"><v>{serial}</v></c>"#),
None if v.parse::<f64>().is_ok() => format!(r#"<c r="{at}"><v>{v}</v></c>"#),
None => format!(r#"<c r="{at}" t="inlineStr"><is><t>{v}</t></is></c>"#),
}
};
let ns = r#"xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships""#;
let rel_t = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
let mut z = zip::ZipWriter::new(std::fs::File::create(path).unwrap());
let opts = zip::write::SimpleFileOptions::default();
let mut put = |name: &str, body: String| {
z.start_file(name, opts).unwrap();
z.write_all(body.as_bytes()).unwrap();
};
let list: String = (0..sheets.len())
.map(|i| {
format!(
r#"<sheet name="{}" sheetId="{}" r:id="rId{}"/>"#,
sheets[i].0,
i + 1,
i + 1
)
})
.collect();
put(
"xl/workbook.xml",
format!("<workbook {ns}><sheets>{list}</sheets></workbook>"),
);
let rels: String = (0..sheets.len())
.map(|i| {
format!(
r#"<Relationship Id="rId{}" Type="{rel_t}/worksheet" Target="worksheets/sheet{}.xml"/>"#,
i + 1,
i + 1
)
})
.collect();
put(
"xl/_rels/workbook.xml.rels",
format!(
r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{rels}<Relationship Id="rIdT" Type="{rel_t}/styles" Target="styles.xml"/></Relationships>"#
),
);
put(
"xl/styles.xml",
format!(
r#"<styleSheet {ns}><cellXfs count="2"><xf numFmtId="0"/><xf numFmtId="14"/></cellXfs></styleSheet>"#
),
);
for (i, (_, rows)) in sheets.iter().enumerate() {
let data: String = rows
.iter()
.enumerate()
.map(|(r, cells)| {
let cs: String = cells
.iter()
.enumerate()
.map(|(c, v)| cell(r, c, v))
.collect();
format!(r#"<row r="{}">{cs}</row>"#, r + 1)
})
.collect();
put(
&format!("xl/worksheets/sheet{}.xml", i + 1),
format!("<worksheet {ns}><sheetData>{data}</sheetData></worksheet>"),
);
}
z.finish().unwrap();
}
/// Workbooks through the real planner. Each worksheet is its own group, so
/// the same `Sales` sheet in two quarterly files clusters into ONE data
/// dataset, typed from the cells (a date-formatted serial elects `date`,
/// not `long`). A sheet with no header row is rendered as a document and
/// joins the scope's document dataset beside the README, so one file is
/// assigned to both.
#[test]
fn workbooks_plan_a_dataset_per_sheet_schema_and_documents_for_form_sheets() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(root.join("README.md"), PROSE).unwrap();
for (name, month, revenue) in [("q1", "#46023", "1250"), ("q2", "#46113", "980.5")] {
write_xlsx(
&root.join(format!("{name}.xlsx")),
&[
(
"Sales",
&[
&["Quarterly sales"],
&["Region", "Month", "Revenue"],
&["EMEA", month, revenue],
&["APAC", month, "700"],
],
),
(
"Assumptions",
&[&["Discount rate", "0.08"], &["Owner", "Finance team"]],
),
],
);
}
let plan = plan_for(root);
let sales: Vec<_> = plan
.datasets
.iter()
.filter(|d| d.group.as_deref() == Some("Sales"))
.collect();
assert_eq!(sales.len(), 1, "{:#?}", plan.datasets);
let sales = sales[0];
assert_eq!(sales.file_count, 2, "both quarters share the sheet schema");
let spec = |name: &str| sales.specs.iter().find(|s| s.name == name).unwrap();
assert_eq!(spec("Month").es_type, "date", "{:#?}", sales.specs);
assert!(
spec("Month")
.date_min
.as_deref()
.is_some_and(|d| d.starts_with("2026-01-01")),
"{:#?}",
spec("Month")
);
assert_eq!(spec("Revenue").es_type, "double");
assert!(
!sales.specs.iter().any(|s| s.name == "Quarterly_sales"),
"the title row is not a header"
);
let docs = plan.datasets.iter().find(|d| d.family == "docs").unwrap();
assert_eq!(docs.file_count, 3, "README + each workbook's form sheet");
let by_rel: HashMap<&str, &FileAssignment> =
plan.files.values().map(|f| (f.rel.as_str(), f)).collect();
let mut q1 = by_rel["q1.xlsx"].assignments.clone();
q1.sort();
assert_eq!(
q1,
[
(None, docs.slug.clone()),
(Some("Sales".to_string()), sales.slug.clone())
]
);
assert_eq!(by_rel["q1.xlsx"].family, "xlsx");
}
/// #196: the same tree WITHOUT nested `.git` markers (or with one at the
/// root — a workspace) is ONE scope: a single document corpus.
#[test]
fn a_single_workspace_plans_one_document_dataset() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join(".git")).unwrap();
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::create_dir_all(root.join("wasm/examples")).unwrap();
std::fs::write(root.join("src/a.c"), CODE).unwrap();
std::fs::write(root.join("src/b.c"), CODE).unwrap();
std::fs::write(root.join("README.md"), PROSE).unwrap();
std::fs::write(root.join("wasm/examples/demo.md"), PROSE).unwrap();
let plan = plan_for(root);
assert_eq!(
plan.datasets.len(),
1,
"one workspace, one corpus: {:#?}",
plan.datasets
);
assert_eq!(plan.datasets[0].slug, "docs");
assert_eq!(plan.datasets[0].file_count, 4);
}
/// #2357: `.tsx` under Next.js route directories (`[locale]`, `[token]`)
/// is code in the per-scope docs dataset. A `.gitignore` that names those
/// directories the way they appear on disk (`!app/[locale]/**`) must
/// re-include them; git would read `[locale]` as a character class and
/// leave the file out.
#[test]
fn bracketed_tsx_routes_land_in_the_docs_dataset() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let tsx = root
.join("app")
.join("[locale]")
.join("booking")
.join("[token]")
.join("temple-selection");
std::fs::create_dir_all(&tsx).unwrap();
std::fs::write(
tsx.join("TempleSelectionWrapper.tsx"),
"export function TempleSelectionWrapper() {\n\
const getPujaName = () => \"pushpanjali\";\n\
function calculateCrossLanguageScore(a: string, b: string) {\n\
return a.length - b.length;\n\
}\n\
return getPujaName();\n\
}\n",
)
.unwrap();
std::fs::write(root.join("README.md"), "# Temple booking\n\nNotes.\n").unwrap();
std::fs::write(
root.join(".gitignore"),
"*\n!app/\n!app/[locale]/\n!app/[locale]/**\n!README.md\n",
)
.unwrap();
let plan = plan_for(root);
let rel = "app/[locale]/booking/[token]/temple-selection/TempleSelectionWrapper.tsx";
let file = plan
.files
.values()
.find(|f| f.rel == rel)
.unwrap_or_else(|| {
panic!(
"tsx missing from plan: {:?}",
plan.files
.values()
.map(|f| f.rel.as_str())
.collect::<Vec<_>>()
)
});
assert_eq!(file.family, "code", "{file:#?}");
assert!(
file.assignments.iter().any(|(_, slug)| slug == "docs"),
"code shares the docs dataset: {file:#?}"
);
assert!(
plan.junk_files.iter().all(|junk| junk.rel != rel),
"tsx junked: {:?}",
plan.junk_files
);
let docs = plan
.datasets
.iter()
.find(|dataset| dataset.slug == "docs")
.expect("docs dataset");
assert_eq!(docs.index, "t-docs");
assert_eq!(docs.family, "docs");
assert!(
docs.specs.iter().any(|spec| spec.name == "name"),
"symbol name was not indexed: {docs:#?}"
);
assert!(
docs.specs.iter().any(|spec| spec.name == "defs"),
"defs was not indexed: {docs:#?}"
);
}
}
// ─── Phase A plan building (pure: no server contact) ─────────────────────
/// Repository scope per file: the deepest ancestor directory (root-relative,
/// "/"-separated) containing a `.git` entry, or "" when the file is under
/// none. The walk never descends into `.git` itself, but the marker is still
/// on disk. A `.git` at the autoindex root yields "" for every file — the
/// whole tree is one scope — and so does a tree with no `.git` at all, which
/// is exactly the #173/#196 property: one autoindex of one folder yields a
/// corpus searchable as one corpus, split only at nested repository roots.
fn compute_scopes(root: &Path, rels: &[String]) -> Vec<String> {
let mut cache: HashMap<String, bool> = HashMap::new();
rels.iter()
.map(|rel| {
let mut scope = String::new();
let mut prefix = String::new();
let mut segs = rel.split('/').peekable();
while let Some(seg) = segs.next() {
if segs.peek().is_none() {
break; // final segment is the file name
}
if !prefix.is_empty() {
prefix.push('/');
}
prefix.push_str(seg);
let repo = *cache
.entry(prefix.clone())
.or_insert_with(|| root.join(&prefix).join(".git").exists());
if repo {
scope = prefix.clone();
}
}
scope
})
.collect()
}
/// What phase A produces: the frozen plan, the clusters phase B needs, and
/// the run-local PDF artifacts (index-aligned with `files`) that phase B may
/// replay instead of parsing again. A spool is always optional — every entry
/// may legitimately be `None`.
struct PhaseA {
plan: Plan,
clusters: Vec<dataset::Cluster>,
pdf_spools: Vec<Option<extract::pdf::ExtractionSpool>>,
}
/// Record and report why individual PDFs could not retain a run-local
/// artifact. Reuse is an accelerator, so this is purely informational: every
/// listed file is parsed again by the normal phase B path. Recording is kept
/// even when the budget is globally disabled — the stored examples are the
/// only place the `--json` report explains *why* nothing was reused, and they
/// are already capped at three.
///
/// Reporting goes out through the progress surface, never a bare `eprintln!`:
/// stderr belongs to that surface, so `--progress none` stays silent and
/// `--progress json` stays a single parseable stream (#241).
fn report_pdf_spool_fallbacks(
files: &[walk::FileEntry],
fallbacks: &[(usize, Vec<extract::pdf::SpoolFallback>)],
ctx: &PhaseAContext<'_>,
) {
let pdf_spool_budget = ctx.budget;
let pr = ctx.progress;
let reasons: Vec<(&str, &extract::pdf::SpoolFallback)> = fallbacks
.iter()
.flat_map(|(index, per_file)| {
per_file
.iter()
.map(move |fallback| (files[*index].rel.as_str(), fallback))
})
.collect();
for (path, fallback) in &reasons {
pdf_spool_budget.record_fallback_example(path, fallback.category, &fallback.message);
}
if reasons.is_empty() {
return;
}
if pdf_spool_budget.platform_reuse_is_unavailable() {
pr.note(
"phase A: run-local PDF extraction reuse is unavailable on this platform; \
phase B will use the normal parser",
);
return;
}
pr.note(&format!(
"phase A: {} PDF extraction(s) could not retain a bounded run-local artifact; \
phase B will parse them again safely",
reasons.len()
));
if let Some(warning) = ctx.capacity_warning {
pr.note(&format!(" PDF reuse capacity: {warning}"));
}
for (path, fallback) in reasons.iter().take(3) {
pr.note(&format!(
" PDF reuse fallback for {path}: {}. The PDF is still indexed; phase B parses it again.",
fallback.message
));
}
if reasons.len() > 3 {
pr.note(&format!(
" … and {} more PDF reuse fallback(s)",
reasons.len() - 3
));
}
}
/// Files phase A scans before folding their sketches into clusters. Large
/// enough that the scan pool stays busy across a chunk, small enough that the
/// sketches held at once stay bounded whatever the folder's file count.
// Tests use a tiny chunk so every multi-file phase-A test crosses chunk
// boundaries.
const PHASE_A_CHUNK_FILES: usize = if cfg!(test) { 3 } else { 2048 };
/// Sniff + sample every file, cluster into datasets, and assemble the plan.
/// Pure planning: reads the tree, never the server — which is what makes the
/// #173/#196 grouping behaviour testable end-to-end without a cluster.
fn build_phase_a(
root: &Path,
files: &[walk::FileEntry],
keys: &[String],
digests: &[String],
duplicate_files: Vec<DuplicateFile>,
ctx: &PhaseAContext<'_>,
cfg: &IndexCfg,
) -> PhaseA {
use rayon::prelude::*;
let pdf_spool_budget = ctx.budget;
let pr = ctx.progress;
// Same pool as the digest phase: sniffing and sampling are the other half
// of the CPU-bound phase `--workers` has to bound (#240 §2). Progress is
// reported from inside that pool, so the straggler the ticker names is the
// file a scan-pool thread is genuinely sitting on (#241). Retaining a PDF
// artifact happens inside that same guard, so a file whose extraction is
// spooled is counted exactly like a plainly parsed one.
// Patterns were validated (loudly) at run start; a failure here would be
// a programming error, not user input.
let stub_matcher =
GlobMatcher::compile(&cfg.stub_globs, "--stub").expect("validated at startup");
let rels: Vec<String> = files.iter().map(|f| f.rel.clone()).collect();
let scopes = compute_scopes(root, &rels);
// (family, gzip) per file, from the scan's sniff — reused for assignments
// and demoted-file re-sampling instead of re-sniffing every file.
let mut file_meta: Vec<Option<(Family, bool)>> = Vec::with_capacity(files.len());
let mut junk_files = Vec::new();
let mut pdf_spools: Vec<Option<extract::pdf::ExtractionSpool>> =
(0..files.len()).map(|_| None).collect();
let mut pdf_fallbacks: Vec<(usize, Vec<extract::pdf::SpoolFallback>)> = Vec::new();
// Scan in file-ordered chunks and fold each chunk's sketches into the
// clusters before the next chunk is scanned. Collecting every file's scan
// first held one set of field accumulators per file for the whole folder
// at once: 4.4 GB of client RSS on a 146k-file tree before anything was
// indexed (part of #1122). Folding in file order keeps the clustering
// identical to the collect-all version (see `dataset::Clusterer`).
let mut clusterer = dataset::Clusterer::default();
let mut start = 0usize;
while start < files.len() {
let end = (start + PHASE_A_CHUNK_FILES).min(files.len());
let scans: Vec<FileScan> = crate::pool::install(|| {
files[start..end]
.par_iter()
.zip(digests[start..end].par_iter())
.map(|(f, digest)| {
let _in_flight = pr.file(&f.rel, f.size);
scan_file(
&f.path,
f.size,
digest,
ctx,
cfg.sample,
cfg.max_file_bytes,
stub_matcher.matches(&f.rel),
)
})
.collect()
});
for (offset, mut sc) in scans.into_iter().enumerate() {
let i = start + offset;
file_meta.push(sc.sniffed.as_ref().map(|s| (s.family, s.gzip)));
if !sc.pdf_spool_fallbacks.is_empty() {
pdf_fallbacks.push((i, std::mem::take(&mut sc.pdf_spool_fallbacks)));
}
let family = sc
.sniffed
.as_ref()
.map(|s| s.family)
.unwrap_or(Family::Binary);
// A file that phase A junks is never indexed, so its artifact is
// refunded here rather than held to the phase A→B boundary.
pdf_spools[i] =
take_pdf_spool_if_indexable(&mut sc.pdf_spool, sc.junk.is_some(), pdf_spool_budget);
if let Some((status, reason)) = sc.junk {
junk_files.push(JunkFile {
file_key: keys[i].clone(),
rel: files[i].rel.clone(),
format: format_str(sc.sniffed.as_ref()),
status,
reason,
bytes: files[i].size,
});
continue;
}
for gs in sc.sketches {
clusterer.push(
dataset::Sketch {
file_idx: i,
group: gs.group,
family,
fields: gs.fields,
key_fields: gs.key_fields,
records: gs.records,
population: gs.population,
},
&scopes[i],
);
}
}
start = end;
}
report_pdf_spool_fallbacks(files, &pdf_fallbacks, ctx);
note_worker_address_space_cap(pr);
let mut clusters = clusterer.finish(&rels);
// `{prefix}-{slug}` must not stutter (`logs-logs-syslog`) when the slug's
// first segment is the prefix the operator already chose.
dataset::drop_repeated_prefix(&cfg.prefix, &mut clusters);
dataset::cap_slug_len(&mut clusters);
// Demoted one-off config files (#173) were sampled as flattened records;
// phase B will index them as documents. Re-sample them through the same
// document renderer so the docs dataset's mapping and stats describe what
// actually gets indexed.
for c in clusters.iter_mut().filter(|c| !c.demoted.is_empty()) {
let demoted = c.demoted.clone();
let fields = &mut c.fields;
let mut sampled_total = 0u64;
for m in demoted {
let gzip = file_meta[m].map(|(_, g)| g).unwrap_or(false);
let mut sampled = 0u64;
let mut sink = |rec: extract::RawRecord| -> bool {
if (sampled as usize) < cfg.sample {
for (k, v) in &rec.fields {
fields.entry(k.clone()).or_default().add(v);
}
}
sampled += 1;
(sampled as usize) < cfg.sample
};
// An unreadable file junks at phase B like any other; the plan
// keeps its membership either way.
let _ = extract::extract_as_document(&files[m].path, gzip, &mut sink);
sampled_total += sampled;
}
c.records += sampled_total;
c.population += sampled_total;
}
// per-file assignments
let mut file_assignments: HashMap<String, FileAssignment> = HashMap::new();
for (ci, c) in clusters.iter().enumerate() {
let demoted: std::collections::HashSet<usize> = c.demoted.iter().copied().collect();
for &m in &c.members {
let key = &keys[m];
let (family, gzip) = file_meta[m].unwrap_or((c.family, false));
let fa = file_assignments
.entry(key.clone())
.or_insert_with(|| FileAssignment {
rel: files[m].rel.clone(),
path_id: files[m].rel_id.clone(),
is_symlink: Some(files[m].is_symlink),
family: family.as_str().to_string(),
gzip,
content_digest: Some(digests[m].clone()),
assignments: Vec::new(),
as_document: false,
});
fa.as_document |= demoted.contains(&m);
fa.assignments
.push((c.group.clone(), clusters[ci].slug.clone()));
}
}
let mut datasets = Vec::new();
for c in &clusters {
let mut specs =
infer::infer_fields_with_policy(&c.fields, c.records, cfg.no_semantic, c.is_docs);
// Data datasets only. A document dataset elects every body carrier;
// capping that would drop code and prose from the vector arm. The
// count is the real row count, not the sample: phase A stops at
// `cfg.sample` rows, and a 123_000-row array sampled at 500 looks
// cheap if the cap only sees 500 (#1978).
if !c.is_docs && !cfg.no_semantic {
let population = c.population.max(c.records);
if let Some(hit) = infer::cap_data_semantic(&mut specs, population) {
pr.note(&infer::semantic_fallback_warning(&c.slug, &hit));
}
}
// Unity script-link enrichment fields are stamped by the phase-B
// pipeline (not the extractor), so inference never sees them —
// register them here or they would be dynamic-mapped coarsely.
//
// Registered for EVERY UnityYaml cluster, not only those whose sample
// happened to contain a `script_guid`. Phase B stamps these whenever a
// record carries a resolvable guid, and phase A reads a bounded window
// of the file — so gating the mapping on the sample meant a cluster
// whose sampled window held no `m_Script` got these two fields
// dynamic-mapped at index time instead, feeding the field-budget
// overshoot in #312. Two keyword specs per Unity cluster is a fixed,
// predictable cost; a dynamic mapping is not.
if c.family == Family::UnityYaml {
specs.push(pipeline_keyword_spec("script_path"));
specs.push(pipeline_keyword_spec("script_class"));
}
if c.family == Family::UnityMeta {
specs.push(pipeline_keyword_spec("asset_path"));
}
let time_field = infer::elect_time_field(&specs);
let semantic_field = specs
.iter()
.find(|s| s.es_type == "semantic_text")
.map(|s| s.name.clone());
if let Some(note) = textless_dataset_note(&specs, &c.slug) {
pr.note(¬e);
}
// #1059: the dataset's text-analyzer election, from the same sampled
// accumulators that elected the semantic body above. Deterministic in
// the sample, so the same bytes elect the same analyzer on every run.
// #1198: `--code-analyzer code` overrides it for a dataset holding any
// file the sniffer routed to the code extractor. Per-file family, not
// `c.family`: a docs cluster is labelled `Family::Code` whatever it holds.
let has_code = c
.members
.iter()
.any(|&m| matches!(file_meta[m], Some((Family::Code, _))));
// A pure log cluster (not a docs cluster a log file was demoted
// into). `c.family` is the cluster's own family; docs clusters are
// labelled `Family::Code` by `dataset::cluster`.
let log_dataset = c.family == Family::Logs && !c.is_docs;
let text_analyzer = infer::elect_dataset_analyzer(
&specs,
&c.fields,
has_code,
cfg.code_analyzer,
log_dataset,
)
.map(str::to_string);
datasets.push(PlanDataset {
slug: c.slug.clone(),
index: format!("{}-{}", cfg.prefix, c.slug),
family: if c.is_docs {
"docs".to_string()
} else {
c.family.as_str().to_string()
},
group: c.group.clone(),
specs,
time_field,
semantic_field,
text_analyzer,
// #1230: freeze the cluster's repository scope so the incremental
// reconciler can route a newly added file to the right sibling
// `docs` dataset when forks share a schema. `Some("")` is the root
// scope; it is a real recorded value, distinct from a legacy
// plan's `None`.
scope: Some(c.scope.clone()),
sampled_records: c.records,
file_count: c.members.len(),
});
}
// Aliases of junk/skipped content have no `plan.files` entry and therefore
// no manifest group to attach to, so keeping them made the generation
// cutover fail its own alias-projection invariant on any folder holding
// two byte-identical junk files — two empty files are enough (#283). The
// incremental projection already drops them (`reconcile_plan`'s
// `live_content` filter); the fresh plan must project the same way or a
// no-op re-run would see a changed plan and commit a spurious generation.
let duplicate_files = duplicate_files
.into_iter()
.filter(|alias| file_assignments.contains_key(&alias.file_key))
.collect();
let plan = Plan {
datasets,
files: file_assignments,
junk_files,
duplicate_files,
alias_paths_indexed: true,
refused_datasets: Vec::new(),
incremental_fields: Default::default(),
};
PhaseA {
plan,
clusters,
pdf_spools,
}
}
/// #1158's zero-text warning, the build-time backstop: a dataset whose
/// mapping carries no text-searchable field is invisible to `xerj code`
/// passage search (it reads `body`/`defs`/`title`/`text` and then the index's
/// own text-typed fields — `xerj-common/src/xccode/fields.rs`). The JSON
/// family synthesizes a `text` passage for prose-less records, so it stops
/// hitting this; every other shape (a csv of enums, a keyword-only xml set)
/// still does, and the operator hears it at plan time instead of wondering
/// why every query comes back empty. `None` means the dataset is searchable.
fn textless_dataset_note(specs: &[infer::FieldSpec], slug: &str) -> Option<String> {
let searchable = specs
.iter()
.any(|s| matches!(s.es_type.as_str(), "text" | "semantic_text"));
if searchable {
return None;
}
let field_list = specs
.iter()
.take(6)
.map(|s| format!("{}:{}", s.name, s.es_type))
.collect::<Vec<_>>()
.join(" ");
Some(format!(
"dataset '{slug}' maps no text-searchable field — `xerj code` passage search will \
find nothing in it (sampled fields: {field_list}{}); structured queries over \
typed fields still work",
if specs.len() > 6 { " …" } else { "" }
))
}
// ─── mapping builder ─────────────────────────────────────────────────────
pub const PROVENANCE_FIELDS: &[&str] = &[
"ax_path",
"ax_paths",
"ax_file",
"ax_locator",
"ax_dataset",
"ax_run",
"ax_format",
];
/// Locator note for `xerj autoindex map` and MCP `xerj_map` (#2351).
///
/// Stored fields differ by record kind. This text is the discoverable
/// contract for a `_source` include of `path`, `start_line`, and `end_line`,
/// including indexes written before those aliases existed.
pub const HIT_LOCATOR_HINT: &str = "\
Every record stores its repo-relative path in `ax_path`. Code records also store \
`line`, `start_line` (the same line) and `end_line`. `path` on a code symbol is \
that relative path. Prose stores `start_line` and `end_line`. A `_source` include \
of `path`, `start_line` and `end_line` locates records this version writes. On an \
older index also request `ax_path` and `line`. Unchanged files are not rewritten \
until the next republish or `--fresh`.";
/// Give a staged record the locator names a client asks for (#2351).
///
/// `ax_path` stays the provenance field. `path` is filled with `rel` when
/// the record has none. A code or SQL symbol stores only the file name in
/// `path`; when that name is the basename of `rel`, it becomes `rel`, the
/// same string as `ax_path`. Any other `path` — a log line's
/// `/uploads/fw.bin`, a CSV column — is left as the source wrote it.
/// A numeric `line` is copied into a missing `start_line`, and into a
/// missing `end_line`. Values the extractor already set are not overwritten.
pub(crate) fn align_hit_locators(fields: &mut Map<String, Value>, rel: &str) {
let base = rel.rsplit(['/', '\\']).next().unwrap_or(rel);
let symbol = fields.get("line").is_some_and(|v| v.is_number())
&& fields.get("name").is_some_and(|v| v.is_string())
&& fields.get("kind").is_some_and(|v| v.is_string());
if symbol {
let replace = match fields.get("path").and_then(Value::as_str) {
None => true,
Some(path) => path == base && path != rel,
};
if replace && !rel.is_empty() {
fields.insert("path".into(), Value::String(rel.to_string()));
}
} else if !fields.contains_key("path") && !rel.is_empty() {
fields.insert("path".into(), Value::String(rel.to_string()));
}
if !fields.contains_key("start_line") {
if let Some(line) = fields.get("line").filter(|v| v.is_number()).cloned() {
fields.insert("start_line".into(), line);
}
}
if !fields.contains_key("end_line") {
if let Some(line) = fields.get("line").filter(|v| v.is_number()).cloned() {
fields.insert("end_line".into(), line);
}
}
}
#[cfg(test)]
mod hit_locator_tests {
use super::align_hit_locators;
use serde_json::{json, Value};
fn fields(value: Value) -> serde_json::Map<String, Value> {
value.as_object().cloned().unwrap()
}
#[test]
fn symbol_path_becomes_the_relative_path_and_line_is_aliased() {
let mut doc = fields(json!({
"name": "dailyCheckIn",
"kind": "function",
"path": "dailyCheckIn.ts",
"line": 1,
"end_line": 3
}));
align_hit_locators(&mut doc, "src/bot/dailyCheckIn.ts");
assert_eq!(doc["path"], json!("src/bot/dailyCheckIn.ts"));
assert_eq!(doc["start_line"], json!(1));
assert_eq!(doc["end_line"], json!(3), "a real span is not collapsed");
let once = doc.clone();
align_hit_locators(&mut doc, "src/bot/dailyCheckIn.ts");
assert_eq!(doc, once);
}
#[test]
fn a_content_path_is_not_rewritten() {
let mut doc = fields(json!({
"path": "/uploads/fw.bin",
"message": "wrote firmware"
}));
align_hit_locators(&mut doc, "logs/xferlog");
assert_eq!(doc["path"], json!("/uploads/fw.bin"));
assert!(doc.get("start_line").is_none());
assert!(doc.get("end_line").is_none());
}
#[test]
fn prose_gains_path_without_clobbering_its_span() {
let mut doc = fields(json!({"body": "hello", "start_line": 4, "end_line": 9}));
align_hit_locators(&mut doc, "notes.md");
assert_eq!(doc["path"], json!("notes.md"));
assert_eq!(doc["start_line"], json!(4));
assert_eq!(doc["end_line"], json!(9));
}
}
/// Spec for a field the PIPELINE derives at index time (Unity script-link
/// enrichment): typed keyword in the explicit mapping, zeroed sampling stats
/// because phase-A inference never observes it.
fn pipeline_keyword_spec(name: &str) -> infer::FieldSpec {
infer::FieldSpec {
name: name.into(),
es_type: "keyword".into(),
date_enc: None,
semantic: None,
cardinality_est: 0,
cardinality_overflow: false,
null_ratio: 0.0,
avg_len: 0.0,
coverage: 0.0,
examples: Vec::new(),
notes: vec!["pipeline-derived: resolved from the .meta guid map at index time".into()],
date_min: None,
date_max: None,
date_evidence: Vec::new(),
num_min: None,
num_max: None,
}
}
/// Outcome of building the Unity script-link map, including what did NOT
/// resolve. The failures are the whole point: `script_path`/`script_class`
/// are absent both when a guid is unreadable and when nothing references it,
/// and those two look identical in the index.
#[derive(Debug, Default)]
struct UnityGuidMap {
/// `.meta` guid → root-relative asset path.
map: std::collections::HashMap<String, String>,
/// `.meta` files that could not be read or parsed at all.
unreadable: Vec<(String, String)>,
/// `.meta` files that parsed but carried no `guid:` key.
no_guid: Vec<String>,
}
/// Unity script-link map: `.meta` guid → root-relative asset path.
///
/// Runs on `crate::pool` and under the progress meter. A `.meta` is tiny, but
/// a real Unity project has 10k-500k of them, and this is on the critical
/// path of EVERY run — including a resumed no-op incremental, which otherwise
/// has no work to do at all. Doing that serially and unmetered is the
/// unattributed-stretch pattern of #241: the process sits silent for minutes
/// with the bar parked.
fn build_unity_guid_map(files: &[walk::FileEntry], plan: &Plan, pr: &Progress) -> UnityGuidMap {
use rayon::prelude::*;
let by_rel: HashMap<&str, &Path> = files
.iter()
.map(|f| (f.rel.as_str(), f.path.as_path()))
.collect();
let metas: Vec<&FileAssignment> = plan
.files
.values()
.filter(|fa| fa.family == "unity-meta")
.collect();
if metas.is_empty() {
return UnityGuidMap::default();
}
pr.phase("unity-guids", metas.len() as u64, 0);
#[allow(clippy::type_complexity)]
let parts: Vec<(
Option<(String, String)>,
Option<(String, String)>,
Option<String>,
)> = crate::pool::install(|| {
metas
.par_iter()
.map(|fa| {
let _in_flight = pr.file(&fa.rel, 0);
let Some(asset_rel) = fa.rel.strip_suffix(".meta") else {
return (None, None, None);
};
let Some(path) = by_rel.get(fa.rel.as_str()) else {
return (None, None, None);
};
let mut guid: Option<String> = None;
// The Result is NOT discarded: an unreadable `.meta` is
// how the headline "which scenes use this script?" query
// silently returns nothing.
match extract::unity::extract_meta(path, fa.gzip, &mut |rec| {
guid = rec
.fields
.get("guid")
.and_then(Value::as_str)
.map(str::to_string);
false
}) {
Ok(_) => match guid {
Some(g) => (Some((g, asset_rel.to_string())), None, None),
None => (None, None, Some(fa.rel.clone())),
},
Err(e) => (None, Some((fa.rel.clone(), e.to_string())), None),
}
})
.collect()
});
let mut out = UnityGuidMap::default();
for (hit, bad, missing) in parts {
if let Some((g, rel)) = hit {
out.map.insert(g, rel);
}
if let Some(b) = bad {
out.unreadable.push(b);
}
if let Some(m) = missing {
out.no_guid.push(m);
}
}
out.unreadable.sort();
out.no_guid.sort();
out
}
/// Say out loud what the guid map could not resolve. Without this a broken
/// `.meta` produces no counter, no warning and no report line, and the
/// feature's headline query returns empty in a way that is indistinguishable
/// from a script nothing references.
fn report_unity_guid_map(g: &UnityGuidMap, pr: &Progress) {
if !g.unreadable.is_empty() {
pr.note(&format!(
"unity: {} .meta sidecar(s) could not be read — scripts they name \
will have no script_path/script_class: {}",
g.unreadable.len(),
g.unreadable
.iter()
.take(REFUSAL_LIST_CAP)
.map(|(rel, e)| format!("{rel} ({e})"))
.collect::<Vec<_>>()
.join(", ")
));
}
if !g.no_guid.is_empty() {
pr.note(&format!(
"unity: {} .meta sidecar(s) carry no guid: {}",
g.no_guid.len(),
g.no_guid
.iter()
.take(REFUSAL_LIST_CAP)
.cloned()
.collect::<Vec<_>>()
.join(", ")
));
}
}
/// Stamp pipeline-derived Unity fields onto a record. MonoBehaviour records
/// gain `script_path`/`script_class` when their `script_guid` resolves; meta
/// records gain the root-relative `asset_path` their guid names. Denormalized
/// for one-query answers — `script_guid` remains the authoritative join.
/// Returns the `script_guid` that was present but did NOT resolve, if any.
/// A caller that throws this away recreates the silent-failure bug: the
/// record then ships without `script_path`/`script_class` and the index
/// cannot distinguish "guid is broken" from "nothing references this script".
#[must_use]
fn enrich_unity_fields(
family: Family,
fields: &mut Map<String, Value>,
guid_map: &std::collections::HashMap<String, String>,
rel: &str,
) -> Option<String> {
match family {
Family::UnityYaml => {
let g = fields.get("script_guid").and_then(Value::as_str)?;
let Some(p) = guid_map.get(g) else {
return Some(g.to_string());
};
let p = p.clone();
fields.insert("script_path".into(), Value::String(p.clone()));
if let Some(stem) = Path::new(&p).file_stem().and_then(|s| s.to_str()) {
fields.insert("script_class".into(), Value::String(stem.to_string()));
}
None
}
Family::UnityMeta => {
if let Some(asset_rel) = rel.strip_suffix(".meta") {
fields.insert("asset_path".into(), Value::String(asset_rel.to_string()));
}
None
}
_ => None,
}
}
fn build_mapping(specs: &[infer::FieldSpec]) -> Value {
let mut props = Map::new();
for s in specs {
let m = match s.es_type.as_str() {
"date" => json!({"type": "date", "format": "strict_date_optional_time||epoch_millis"}),
t => json!({"type": t}),
};
props.insert(s.name.clone(), m);
}
for p in PROVENANCE_FIELDS {
props.insert((*p).into(), json!({"type": "keyword"}));
}
json!({"mappings": {"properties": props}})
}
// ─── the main run ────────────────────────────────────────────────────────
/// One file's documents as the previous plan published them.
///
/// Kept across `--fresh`, which deletes the journal (and this plan) before
/// phase B. The new run's content key no longer matches `file_key`, so a
/// delete keyed only on the key about to be written leaves these documents
/// live (#2139).
#[derive(Clone)]
struct PriorPublication {
rel: String,
file_key: String,
indices: Vec<String>,
}
fn prior_publications(
plan: &Plan,
) -> (
HashMap<String, PriorPublication>,
HashMap<String, PriorPublication>,
) {
let index_of: HashMap<&str, &str> = plan
.datasets
.iter()
.map(|dataset| (dataset.slug.as_str(), dataset.index.as_str()))
.collect();
let mut by_rel = HashMap::new();
let mut by_path_id = HashMap::new();
for (key, assignment) in &plan.files {
let mut indices: Vec<String> = assignment
.assignments
.iter()
.filter_map(|(_, slug)| {
index_of
.get(slug.as_str())
.map(|index| (*index).to_string())
})
.collect();
indices.sort();
indices.dedup();
let published = PriorPublication {
rel: assignment.rel.clone(),
file_key: key.clone(),
indices,
};
by_rel.insert(assignment.rel.clone(), published.clone());
if !assignment.path_id.is_empty() {
by_path_id.insert(assignment.path_id.clone(), published);
}
}
(by_rel, by_path_id)
}
/// Selector for every document a file replacement must remove (#2139).
///
/// `ax_file` is the content key this run writes. An ordinary resume keeps the
/// planned key, so that term removes the previous generation. It does not
/// remove a generation published under a different key: `--fresh` rebuilds
/// the key from the new digest, and a later resume only knows the latest
/// one. Per-symbol ids are `code:<line>:<name>`, so those older documents are
/// not overwritten when the declaration moves. `ax_path` is the same path
/// across those keys. `prior` adds the previous key and path when a rename
/// or a key change means the current pair does not name them.
fn replacement_purge_query(
current_key: &str,
current_rel: &str,
prior: Option<&PriorPublication>,
) -> Value {
let mut should = vec![
json!({"term": {"ax_file": current_key}}),
json!({"term": {"ax_path": current_rel}}),
];
if let Some(prior) = prior {
if prior.file_key != current_key {
should.push(json!({"term": {"ax_file": prior.file_key}}));
}
if prior.rel != current_rel {
should.push(json!({"term": {"ax_path": prior.rel}}));
}
}
json!({
"bool": {
"should": should,
"minimum_should_match": 1
}
})
}
/// Files phase B still has work for: planned, with a real content key, and
/// either never finished or finished against different bytes.
///
/// This predicate is evaluated twice per run — once to price the work for the
/// pre-index estimate, once to build the real queue — against two different
/// snapshots of `journal.done`. The two agree by construction: between the two
/// calls the only thing that removes a key from `done` is `file_replace_start`,
/// which is driven from `content_changed`, and for a key in `content_changed`
/// this predicate ignores `done` altogether. Keeping it in one function is what
/// makes "the estimate priced what the run then did" true rather than hoped.
fn pending_for_phase_b(
keys: &[String],
plan: &Plan,
done: &std::collections::HashSet<String>,
content_changed: &std::collections::HashSet<String>,
) -> Vec<usize> {
(0..keys.len())
.filter(|&i| {
!keys[i].is_empty()
&& plan.files.contains_key(&keys[i])
&& (!done.contains(&keys[i]) || content_changed.contains(&keys[i]))
})
.collect()
}
/// #2577: what this `--no-graph` run's options change against the execution
/// identity the committed generation pinned, one phrase per difference. Empty
/// means the run may continue the committed corpus.
///
/// The record-preparation options are pinned only as a digest, so a change
/// there names the options that feed it rather than the old values. The digest
/// carries its contract version as a prefix, which tells a different XERJ
/// build apart from a changed option.
fn no_graph_option_changes(
expected: &sync::ExecutionIdentity,
cfg: &IndexCfg,
root_identity: &str,
) -> Result<Vec<String>> {
let on_off = |on: bool| if on { "on" } else { "off" };
let mut changes = Vec::new();
if expected.root_identity != root_identity {
changes.push(format!(
"the folder was {} and is now {root_identity}",
expected.root_identity
));
}
if expected.url != cfg.url {
changes.push(format!("--url was {} and is now {}", expected.url, cfg.url));
}
if expected.prefix != cfg.prefix {
changes.push(format!(
"--prefix was {} and is now {}",
expected.prefix, cfg.prefix
));
}
if expected.follow_symlinks != cfg.follow_symlinks {
changes.push(format!(
"--follow-symlinks was {} and is now {}",
on_off(expected.follow_symlinks),
on_off(cfg.follow_symlinks)
));
}
let chunker_identity = prepared_records_identity(cfg)?;
if expected.chunker_identity != chunker_identity {
let contract = |identity: &str| {
identity
.rsplit_once('-')
.map(|(contract, _)| contract.to_owned())
.unwrap_or_default()
};
let (was, now) = (
contract(&expected.chunker_identity),
contract(&chunker_identity),
);
changes.push(if was == now {
"one or more record-preparation options differ, or this XERJ build fingerprints \
them differently (--sample, --no-semantic, --pdf-timeout-secs, --label or the \
label file's contents, --max-file-gb, --max-file-mb, --max-file-bytes); only a \
fingerprint of them is saved, so the earlier values cannot be shown"
.to_owned()
} else {
format!("the record-preparation contract was {was} and this XERJ build uses {now}")
});
}
if expected.graph_enabled
|| expected.brain != "disabled"
|| expected.detector_identity != DETECTOR_DISABLED_IDENTITY
{
changes.push(format!(
"relationship detection was on (graph {}, --brain {}) and this run has it off",
on_off(expected.graph_enabled),
expected.brain
));
}
Ok(changes)
}
/// #2577: the plan-derived half of the pinned execution identity. Dataset
/// definitions are frozen across generations, so on the same XERJ build these
/// match; a difference means the build derives different mappings for them.
fn contract_identity_changes(
expected: &sync::ExecutionIdentity,
plan: &Plan,
) -> Result<Vec<String>> {
let (schema_identity, index_identity) = generation_contract_identities(plan)?;
let mut changes = Vec::new();
if expected.schema_identity != schema_identity || expected.index_identity != index_identity {
changes.push(
"this XERJ build derives different schemas, index mappings or catalog mapping \
for the committed datasets than the build that committed them"
.to_owned(),
);
}
Ok(changes)
}
/// #2577: refuse a `--no-graph` run whose options differ from the ones the
/// committed generation pinned. Runs before the reconcile plan is projected;
/// the real run and its `--dry-run` preview share it (#2684).
fn refuse_changed_no_graph_options(
base: &sync::CommittedManifest,
cfg: &IndexCfg,
root_identity: &str,
) -> Result<()> {
match &base.execution {
Some(expected) => refuse_execution_changes(
base.generation,
no_graph_option_changes(expected, cfg, root_identity)?,
),
None => Ok(()),
}
}
/// #2577: refuse a projected plan whose schema, index or embedder identity
/// differs from the committed generation's. Shared by the real run and its
/// `--dry-run` preview (#2684); only reads from the node.
fn refuse_changed_planned_execution(
es: &Es,
base: &sync::CommittedManifest,
plan: &Plan,
) -> Result<()> {
let Some(expected) = &base.execution else {
return Ok(());
};
refuse_execution_changes(base.generation, contract_identity_changes(expected, plan)?)?;
if plan
.datasets
.iter()
.any(|dataset| dataset.semantic_field.is_some())
{
let current = es.embedding_execution_identity()?;
ensure_embedding_execution_unchanged_and_resumable(
¤t,
&expected.embedding_identity_sha256,
&expected.embedding_backend,
expected.embedding_dimension,
&expected.embedding_semantic_contract,
)?;
}
Ok(())
}
fn refuse_execution_changes(generation: u64, changes: Vec<String>) -> Result<()> {
if changes.is_empty() {
return Ok(());
}
anyhow::bail!(
"autoindex execution configuration changed since the committed generation \
{generation}: {}. Nothing was copied and no remote data was changed; generation \
{generation} and its state are intact. Re-run with the options (and the XERJ \
version) generation {generation} was built with to update it, or index the folder \
with a new --prefix and a new --state-dir to build it with the new options",
changes.join("; ")
)
}
/// An unchanged re-index must not fail with a false "embedding execution
/// identity changed" message (#487). The identity changed only when a
/// comparable field differs from what the journal pinned. `resumable` is
/// checked on its own.
///
/// A proxy whose vector width is not confirmed reports `dimensions: None` and
/// `resumable: false` (#2306). That missing width is the resume limit, not a
/// different embedder. A confirmed width that disagrees with the pinned width
/// is a real change and must not be mixed into the corpus.
fn ensure_embedding_execution_unchanged_and_resumable(
current: &crate::esclient::EmbeddingExecutionIdentity,
expected_sha: &str,
expected_backend: &str,
expected_dimension: Option<usize>,
expected_semantic_contract: &str,
) -> anyhow::Result<()> {
let same_embedder = current.identity_sha256 == expected_sha
&& current.backend == expected_backend
&& current.semantic_contract == expected_semantic_contract;
let same_width = current.dimensions == expected_dimension;
if same_embedder && !same_width && !(current.dimensions.is_none() && !current.resumable) {
anyhow::bail!(
"embedding execution identity changed since this autoindex journal was created \
(vector width {} vs {}); refusing to mix vector spaces. No remote mutation was \
attempted. Restore the original identity, or rebuild with a new --state-dir and a \
new --prefix",
dimension_label(expected_dimension),
dimension_label(current.dimensions),
);
}
anyhow::ensure!(
same_embedder && (same_width || (current.dimensions.is_none() && !current.resumable)),
"embedding execution identity changed since this autoindex journal was created; \
refusing to mix vector spaces. No remote mutation was attempted. Restore the \
original identity, or rebuild with a new --state-dir and a new --prefix"
);
anyhow::ensure!(
current.resumable,
"the `{}` embedding backend cannot resume semantic indexing{}. The pinned identity is \
UNCHANGED — this is a backend limitation, not a change, so restoring the identity will \
not help. Follow the reason above. Documents already indexed were kept. If the vector \
width was not confirmed, make the embedding endpoint reachable and rerun — \
already-embedded documents are reused once the same width is confirmed. Rebuild with a \
new --state-dir and a new --prefix only to discard this corpus and start over.",
current.backend,
current
.non_resumable_reason
.as_deref()
.map(|r| format!(": {r}"))
.unwrap_or_default()
);
Ok(())
}
fn dimension_label(width: Option<usize>) -> String {
match width {
Some(width) => width.to_string(),
None => "unreported".to_string(),
}
}
fn select_resume_plan_keys(
files: &[walk::FileEntry],
content_keys: &[String],
plan: &Plan,
journal_path: &Path,
) -> Result<Vec<Option<String>>> {
let mut planned_by_rel: HashMap<&str, &str> = HashMap::new();
let mut planned_by_path_id: HashMap<&str, &str> = HashMap::new();
for (key, assignment) in &plan.files {
if let Some(previous) = planned_by_rel.insert(&assignment.rel, key) {
anyhow::bail!(
"resume plan assigns path {} to both {} and {}; refusing to discard history under \
the same destination. For an isolated rebuild use a new --state-dir, new \
--prefix, and new --brain when graph detection is enabled (or --no-graph); \
explicitly validate and clean the shared catalog and old target",
assignment.rel,
previous,
key
);
}
if !assignment.path_id.is_empty() {
if let Some(previous) = planned_by_path_id.insert(&assignment.path_id, key) {
anyhow::bail!(
"resume plan assigns one native path identity to both {} and {}; refusing to \
discard history under the same destination. For an isolated rebuild use a \
new --state-dir, new --prefix, and new --brain when graph detection is \
enabled (or --no-graph); explicitly validate and clean the shared catalog \
and old target",
previous,
key
);
}
}
}
let current_rels: std::collections::HashSet<&str> =
files.iter().map(|file| file.rel.as_str()).collect();
let current_path_ids: std::collections::HashSet<&str> =
files.iter().map(|file| file.rel_id.as_str()).collect();
let mut claimed = std::collections::HashSet::new();
let mut selected = Vec::with_capacity(files.len());
for (file, content_key) in files.iter().zip(content_keys) {
let exact_path = planned_by_path_id
.get(file.rel_id.as_str())
.or_else(|| planned_by_rel.get(file.rel.as_str()))
.filter(|key| !claimed.contains(**key))
.map(|key| (*key).to_string());
let exact_content = plan
.files
.contains_key(content_key)
.then(|| content_key.clone())
.filter(|key| !claimed.contains(key.as_str()));
let key = if let Some(key) = exact_path.or(exact_content) {
Some(key)
} else {
// Computing the legacy prefix key is intentionally the final
// fallback. Normal resumes are O(files), with no 64 KiB read.
let legacy_key = ids::file_key(&file.path, file.size)?;
if let Some(assignment) = plan.files.get(&legacy_key) {
let has_exact_current_owner = current_rels.contains(assignment.rel.as_str())
|| (!assignment.path_id.is_empty()
&& current_path_ids.contains(assignment.path_id.as_str()));
if claimed.contains(legacy_key.as_str()) || has_exact_current_owner {
anyhow::bail!(
"{} collides with legacy resume key {} already owned by {}. No documents \
were changed; remove or move one of these two files out of the corpus \
and rerun — every other file keeps its resume state. Refusing to discard \
history under the same destination. For an isolated rebuild use a new \
--state-dir, new --prefix, and new --brain when graph detection is \
enabled (or --no-graph); explicitly validate and clean the shared \
catalog and old target. Journal: {}",
file.rel,
legacy_key,
assignment.rel,
journal_path.display()
);
}
Some(legacy_key)
} else if claimed.contains(content_key.as_str()) {
// Another current file already owns this planned key. Ownership
// must stay exclusive — two owners would each run the
// replacement transaction on one ax_file key and delete each
// other's freshly published documents. Divert this file to a
// deterministic path-derived key, the same discriminator scheme
// content::resolve_reporting uses for byte-proven digest
// collisions.
Some(format!(
"{content_key}-claimed-{:032x}",
xxhash_rust::xxh3::xxh3_128(file.rel_id.as_bytes())
))
} else {
None
}
};
if let Some(key) = &key {
claimed.insert(key.clone());
}
selected.push(key);
}
Ok(selected)
}
/// `--fresh` was asked to discard a durable corpus *generation*.
///
/// The generated `--no-graph` path keeps its authority in a committed
/// manifest plus sealed snapshots under the state directory. `--fresh` deletes
/// `journal.ndjson`, and the `gc_snapshots` call that follows every open then
/// sees an empty protected set and removes every sealed snapshot directory —
/// so by the time any later gate could object, the manifest, the pending
/// replay evidence, and the alias/path/stale-record knowledge needed to
/// reconcile the destination are already gone. Refuse before anything is
/// touched.
///
/// This carries no inventory delta on purpose: nothing has been compared yet,
/// and printing empty `added`/`vanished` arrays (as an earlier revision did)
/// is worse than saying plainly which durable state is in the way.
#[derive(Debug)]
struct UnsafeFreshGenerationError {
/// Committed generation number, or `None` when the blocker is an
/// uncommitted pending generation.
committed_generation: Option<u64>,
}
impl UnsafeFreshGenerationError {
fn to_json(&self) -> Value {
json!({
"schema": "xerj.autoindex.unsafe_fresh_generation.v1",
"status": "error",
"error": "unsafe_fresh_existing_generation",
"message": "this attempt made no remote mutations; --fresh cannot discard a durable corpus generation under the same destination because the committed manifest, sealed replay evidence, and alias, path and stale-record cleanup knowledge would be lost",
"blocking_state": match self.committed_generation {
Some(generation) => json!({"kind": "committed_generation", "generation": generation}),
None => json!({"kind": "pending_generation"}),
},
"recovery": {
"resume": "run the same command WITHOUT --fresh: a generated --no-graph journal reconciles additions, changes, deletions and renames incrementally, and replays a pending generation",
"exact_rebuild": "index with a new --state-dir and a new --prefix. Validate the isolated target before switching readers",
"warning": "--fresh is not recovery or destination reconciliation. The global autoindex-catalog and old target are not cleaned automatically; validate and clean them explicitly"
}
})
}
}
impl std::fmt::Display for UnsafeFreshGenerationError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let blocker = match self.committed_generation {
Some(generation) => format!("committed corpus generation {generation}"),
None => "an uncommitted pending corpus generation".to_owned(),
};
write!(
formatter,
"this attempt made no remote mutations. `--fresh` cannot discard {blocker} under the \
same destination: the committed manifest, sealed replay evidence, and the alias, \
path and stale-record cleanup knowledge would be lost, and the existing destination \
may already be partial or stale. Re-run the same command without `--fresh` — a \
generated `--no-graph` journal reconciles additions, changes, deletions and renames \
incrementally. For an exact rebuild, index the current folder with a new \
--state-dir and a new --prefix, and validate the isolated target before switching \
readers. `--fresh` is not recovery or destination reconciliation; the global \
autoindex-catalog and old target require explicit validated cleanup"
)
}
}
impl std::error::Error for UnsafeFreshGenerationError {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct InventoryDeltaEntry {
file_key: String,
path: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct UnsupportedInventoryDelta {
added_content_groups: Vec<InventoryDeltaEntry>,
/// Vanished from the walk AND absent from disk: a genuine user deletion.
/// Refused, because the published documents stay live with no source file
/// behind them and nothing here removes them.
deleted_content_groups: Vec<InventoryDeltaEntry>,
/// Vanished from the walk but STILL ON DISK: the file was excluded by a
/// widened ignore/hidden rule, not removed by the user (#439). Its documents
/// likewise stay live, so the rerun is still refused — but the recovery is
/// different, and leading an operator (or an agent parsing the JSON) to
/// "restore the removed file" is wrong when the file is one `ls` away. A
/// follow-up sweeps these from the destination instead of refusing.
excluded_content_groups: Vec<InventoryDeltaEntry>,
}
/// Everything the refusal needs to name the destination it is protecting.
/// Collected at the gate so the message can list the exact indices and state
/// directory an operator has to act on, instead of describing them abstractly.
#[derive(Debug, Clone, PartialEq, Eq)]
struct RefusalTargets {
state_dir: String,
data_indices: Vec<String>,
edges_index: Option<String>,
}
impl RefusalTargets {
/// The destination a removal refusal would name. The run sweeps deletions
/// instead of returning that error (#2314); the constructor stays so the
/// typed message can still be built from a plan.
#[allow(dead_code)]
fn describe(cfg: &IndexCfg, state_dir: &Path, plan: &Plan) -> Self {
let mut data_indices: Vec<String> = plan.datasets.iter().map(|d| d.index.clone()).collect();
data_indices.sort();
data_indices.dedup();
let edges_index = (!cfg.no_graph).then(|| {
let brain = cfg
.brain
.clone()
.unwrap_or_else(|| derive_brain_name(&cfg.root));
detect::edges_index_name(&brain)
});
Self {
state_dir: state_dir.display().to_string(),
data_indices,
edges_index,
}
}
fn indices_phrase(&self) -> String {
if self.data_indices.is_empty() {
"the indices this plan publishes".to_string()
} else {
self.data_indices.join(", ")
}
}
fn edges_note(&self) -> String {
match &self.edges_index {
Some(edges) => format!(
" Graph edges taught by the removed file(s) stay live in {edges} until that \
index is deleted too."
),
None => String::new(),
}
}
}
/// The #195 zero-live verification failure, as a type rather than a string.
///
/// The journal claims records were made visible; the destination answers with
/// none. That is always a failure, but not always the *same* failure: for a
/// composing caller like `xerj brain` a resume journal that outlived a wiped
/// data directory has a specific, executable recovery (`--fresh` in place),
/// while a write-blocked or unreachable server does not. Only a typed error
/// lets the caller tell them apart — `anyhow::bail!` forces it to either
/// string-match the prose or reprint it verbatim.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZeroLiveVerificationError {
/// Records the resume journal says were published.
pub journal_records: u64,
/// Completed files those records came from.
pub files_done_journaled: usize,
/// Dataset indices that answered with zero live documents.
pub dataset_indices: usize,
/// Directory the resume journal was read from. A new `--data-dir` does
/// not move this directory: the default is keyed by folder, URL, and
/// prefix, so a journal left by an earlier node is reused as-is.
pub state_dir: String,
}
impl std::fmt::Display for ZeroLiveVerificationError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
formatter,
"autoindex verification failed: the resume journal records {} \
record(s) from {} completed file(s), but 0 documents are \
live across the {} dataset index(es). Journal state dir: {}. \
This journal may belong to another data dir (a new --data-dir \
reuses it). The indices exist and look healthy but \
hold nothing — a server-side write rejection (e.g. a disk flood-stage or \
index write block), deleted indices, or an unreadable server can also cause \
this. Fix the server-side condition, then rerun with --fresh to re-index \
from scratch",
self.journal_records, self.files_done_journaled, self.dataset_indices, self.state_dir
)
}
}
impl std::error::Error for ZeroLiveVerificationError {}
/// A dataset index the resume journal says received records, and that answers
/// with zero live documents.
#[derive(Debug, Clone, PartialEq, Eq)]
struct EmptyDataset {
index: String,
/// Exact only when every contributing file targets this dataset alone.
/// A file-wide journal count cannot be copied into several dataset totals.
records: Option<u64>,
files: usize,
}
/// The per-dataset half of the #195 gate (#2407). Summing live documents over
/// every dataset let a populated sibling hide an index that held nothing, so a
/// re-run reported `ok: indexed and searchable` over an empty `-docs` index.
///
/// The journal keeps one record count per file, and a file's groups can feed
/// several datasets, so records are attributed to a file's datasets only as a
/// set: a completed file with records is missing when EVERY dataset it feeds
/// answers zero. A dataset with no count (refused, or the count did not
/// answer) is unknown, not empty, and never makes a file missing.
fn datasets_left_empty(
plan: &Plan,
done: &HashMap<String, FileDone>,
ds_counts: &HashMap<String, u64>,
excluded_file_keys: &HashSet<String>,
) -> Vec<EmptyDataset> {
let mut empty: BTreeMap<String, (Option<u64>, usize)> = BTreeMap::new();
for (key, file) in done {
if file.records == 0 || excluded_file_keys.contains(key) {
continue;
}
let Some(assignment) = plan.files.get(key) else {
continue;
};
let slugs: BTreeSet<&str> = assignment
.assignments
.iter()
.map(|(_, slug)| slug.as_str())
.collect();
if slugs.is_empty() || !slugs.iter().all(|slug| ds_counts.get(*slug) == Some(&0)) {
continue;
}
let records = (slugs.len() == 1).then_some(file.records);
for slug in slugs {
let entry = empty.entry(slug.to_string()).or_insert((Some(0), 0));
entry.0 = entry
.0
.zip(records)
.and_then(|(total, n)| total.checked_add(n));
entry.1 += 1;
}
}
plan.datasets
.iter()
.filter_map(|dataset| {
empty
.get(&dataset.slug)
.map(|(records, files)| EmptyDataset {
index: dataset.index.clone(),
records: *records,
files: *files,
})
})
.collect()
}
#[derive(Debug)]
struct UnsupportedInventoryDeltaError {
delta: UnsupportedInventoryDelta,
targets: RefusalTargets,
}
impl UnsupportedInventoryDeltaError {
fn to_json(&self) -> Value {
let deleted = &self.delta.deleted_content_groups;
let excluded = &self.delta.excluded_content_groups;
// Back-compat: `vanished_content_groups` (the v1 field) stays as the
// union of both causes; `deleted_`/`excluded_content_groups` add the
// #439 distinction without removing anything a v1 consumer reads.
// Globally sorted, matching the pre-split v1 field: the two buckets are
// each sorted, but a mixed run must not expose bucket order to a v1
// consumer that saw one (path, file_key)-sorted list.
let mut vanished: Vec<&InventoryDeltaEntry> =
deleted.iter().chain(excluded.iter()).collect();
vanished.sort_by(|left, right| {
left.path
.cmp(&right.path)
.then_with(|| left.file_key.cmp(&right.file_key))
});
let message = if excluded.is_empty() {
"this attempt made no remote mutations. Files that were indexed under this resume plan no longer exist in the folder, and their documents are still live in the destination; removing files from an indexed folder is not reconciled yet".to_string()
} else if deleted.is_empty() {
"this attempt made no remote mutations. Files that were indexed under this resume plan are STILL ON DISK but the walk no longer yields them — an ignore or hidden-file rule widened to exclude them. They were not removed, and their documents are still live in the destination; sweeping an excluded file's documents in place is not reconciled yet".to_string()
} else {
"this attempt made no remote mutations. Some files indexed under this resume plan no longer exist in the folder (deleted); others are still on disk but the walk no longer yields them because an ignore or hidden-file rule widened (excluded, not removed). Both sets' documents are still live in the destination and neither deletion nor exclusion is reconciled in place yet".to_string()
};
let mut recovery = serde_json::Map::new();
if !deleted.is_empty() {
recovery.insert(
"restore_removed_files".into(),
json!("for the DELETED file(s) only: put them back and rerun; every other file keeps its resume state. Do NOT apply this to the excluded file(s) — they were never removed"),
);
}
if !excluded.is_empty() {
recovery.insert(
"excluded_not_removed".into(),
json!("the excluded file(s) are still on disk — an ignore/hidden rule now matches them, so the walk stopped yielding them. Restoring them is wrong (they were never removed). To keep them indexed, narrow the rule so the walk re-admits them; to drop them from the index, rebuild isolated (below) — their documents cannot yet be swept in place"),
);
}
recovery.insert(
"rebuild_in_place".into(),
json!(format!(
"delete the indices this plan publishes ({}) and the state directory {}, then rerun. This re-extracts and re-embeds the whole corpus.{}",
self.targets.indices_phrase(),
self.targets.state_dir,
self.targets.edges_note().trim_start_matches(' ')
)),
);
recovery.insert(
"rebuild_isolated".into(),
json!("index with a new --state-dir, new --prefix, and (when graph detection is enabled) new --brain; alternatively add --no-graph. Validate the isolated target before switching readers, then clean the old one"),
);
recovery.insert(
"fresh_warning".into(),
json!("--fresh re-extracts the current folder in place and does pick up added and changed files, but it never deletes documents already published for removed or excluded files, so it is refused here"),
);
json!({
"schema": "xerj.autoindex.unsupported_sync_delta.v1",
"status": "error",
"error": "unsupported_content_group_removal",
"message": message,
"vanished_content_groups": vanished,
"deleted_content_groups": deleted,
"excluded_content_groups": excluded,
// Context, not the reason for the refusal: a rerun over a frozen
// plan does not index files added after the plan was frozen.
"added_content_groups": self.delta.added_content_groups,
"recovery": Value::Object(recovery)
})
}
}
impl std::fmt::Display for UnsupportedInventoryDeltaError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Capped like the duplicate and unplanned-file listings above; see
// REFUSAL_LIST_CAP. The machine-readable `--json` rendering keeps the
// full lists, so nothing is lost — only the prose is bounded.
let render = |entries: &[InventoryDeltaEntry]| {
let mut rendered = entries
.iter()
.take(REFUSAL_LIST_CAP)
.map(|entry| format!("{} ({})", entry.path, entry.file_key))
.collect::<Vec<_>>()
.join(", ");
let remaining = entries.len().saturating_sub(REFUSAL_LIST_CAP);
if remaining > 0 {
rendered.push_str(&format!(", … and {remaining} more"));
}
rendered
};
let deleted = &self.delta.deleted_content_groups;
let excluded = &self.delta.excluded_content_groups;
write!(
formatter,
"this attempt made no remote mutations — no documents, aliases, graph edges or \
catalog entries were written."
)?;
if !deleted.is_empty() {
write!(
formatter,
" {} file(s) indexed under this resume plan no longer exist in the folder, and \
their documents are still live in the destination; removing files from an \
indexed folder is not reconciled yet. Deleted content groups [{}].",
deleted.len(),
render(deleted)
)?;
}
if !excluded.is_empty() {
// #439: still on disk, so "restore the removed file" is wrong.
write!(
formatter,
" {} file(s) indexed under this resume plan are still on disk but the walk no \
longer yields them — an ignore or hidden-file rule widened to exclude them, so \
they were not removed. Their documents are still live in the destination; \
sweeping an excluded file's documents in place is not reconciled yet. Excluded \
content groups [{}].",
excluded.len(),
render(excluded)
)?;
}
if !self.delta.added_content_groups.is_empty() {
write!(
formatter,
" Also present but not in the frozen resume plan, so not indexed by this run \
either [{}].",
render(&self.delta.added_content_groups)
)?;
}
write!(formatter, " Recovery, cheapest first:")?;
if !deleted.is_empty() {
write!(
formatter,
" restore the DELETED file(s) and rerun — every other file keeps its resume \
state (this does not apply to the excluded file(s), which were never removed);"
)?;
}
if !excluded.is_empty() {
write!(
formatter,
" for the EXCLUDED file(s), narrow the ignore/hidden rule so the walk re-admits \
them (keeps them indexed), or rebuild isolated to drop them — their documents \
cannot yet be swept in place;"
)?;
}
write!(
formatter,
" rebuild in place by deleting the indices this plan publishes ({}) and the state \
directory {}, then rerunning — this re-extracts and re-embeds the whole corpus.{} \
rebuild isolated with a new --state-dir, a new --prefix and, when graph detection \
is enabled, a new --brain (or --no-graph), validate it, switch readers, then clean \
the old target. `--fresh` picks up added and changed files in place but never \
deletes documents for removed or excluded files, so it is refused here too",
self.targets.indices_phrase(),
self.targets.state_dir,
self.targets.edges_note()
)
}
}
impl std::error::Error for UnsupportedInventoryDeltaError {}
/// Paths of swept content groups, capped the same way a refusal lists them.
fn deleted_group_list(entries: &[InventoryDeltaEntry]) -> String {
let mut rendered = entries
.iter()
.take(REFUSAL_LIST_CAP)
.map(|entry| entry.path.as_str())
.collect::<Vec<_>>()
.join(", ");
let remaining = entries.len().saturating_sub(REFUSAL_LIST_CAP);
if remaining > 0 {
rendered.push_str(&format!(", … and {remaining} more"));
}
rendered
}
/// Whether a plan file that vanished from the walk is still on disk (#439).
///
/// The disk probe uses the file's reversible raw-bytes identity (`path_id`:
/// `unix:<hex>` / `windows:<hex>`), NOT its `rel`. `rel` is a `to_string_lossy`
/// rendering, so a hidden non-UTF-8 name — the exact case #439 was filed for —
/// is stored with `U+FFFD` and no dirent matches it; probing through `rel` would
/// call every such file a deletion. `path_id` round-trips the real bytes. Legacy
/// plans that predate `path_id` fall back to `rel`. An unreadable path counts as
/// present, so a stat failure never produces a "restore the removed file"
/// instruction for a file that is merely inaccessible.
fn vanished_is_on_disk(root: &Path, assignment: &FileAssignment) -> bool {
let rel = decode_stable_path_id(&assignment.path_id)
.unwrap_or_else(|| std::path::PathBuf::from(&assignment.rel));
root.join(rel).try_exists().unwrap_or(true)
}
/// Reverse of `walk::stable_path_id`: reconstruct the real relative path from its
/// `unix:<hex>` / `windows:<hex>` identity, preserving bytes a UTF-8 `rel` loses.
/// Returns `None` for an empty or unrecognised id so the caller falls back.
fn decode_stable_path_id(path_id: &str) -> Option<std::path::PathBuf> {
#[cfg(unix)]
{
if let Some(hex) = path_id.strip_prefix("unix:") {
use std::os::unix::ffi::OsStrExt;
if hex.len() % 2 != 0 {
return None;
}
// `hex.get` (not `hex[..]`) so a non-ASCII byte in a corrupted or
// hand-edited path_id returns None instead of panicking on a
// non-char-boundary slice — the doc contract above.
let bytes: Option<Vec<u8>> = (0..hex.len())
.step_by(2)
.map(|i| {
hex.get(i..i + 2)
.and_then(|pair| u8::from_str_radix(pair, 16).ok())
})
.collect();
return Some(std::path::PathBuf::from(std::ffi::OsStr::from_bytes(
&bytes?,
)));
}
}
#[cfg(windows)]
{
if let Some(hex) = path_id.strip_prefix("windows:") {
use std::os::windows::ffi::OsStringExt;
if hex.len() % 4 != 0 {
return None;
}
let units: Option<Vec<u16>> = (0..hex.len())
.step_by(4)
.map(|i| {
hex.get(i..i + 4)
.and_then(|quad| u16::from_str_radix(quad, 16).ok())
})
.collect();
return Some(std::path::PathBuf::from(std::ffi::OsString::from_wide(
&units?,
)));
}
}
let _ = path_id;
None
}
impl UnsupportedInventoryDelta {
fn between(root: &Path, files: &[walk::FileEntry], keys: &[String], plan: &Plan) -> Self {
let current_keys: std::collections::HashSet<&str> = keys
.iter()
.filter(|key| !key.is_empty())
.map(String::as_str)
.collect();
let durable_keys: std::collections::HashSet<&str> = plan
.files
.keys()
.map(String::as_str)
.chain(plan.junk_files.iter().map(|junk| junk.file_key.as_str()))
.collect();
// Path identity, not just content identity. An in-place EDIT gives the
// same file a new content key, so a key-only comparison reads the
// superseded key as vanished and the new one as added — the SAME path
// listed as both removed and added. That is a replacement, and the file
// is still there to be republished, so it must never be refused.
// Ordinary resume already reaches this conclusion by mapping each file
// onto its planned key (`select_resume_plan_keys`); doing it here makes
// `--fresh`, which has no plan to map through, agree — without making
// the gate more fatal than the open it precedes.
let current_rels: std::collections::HashSet<&str> =
files.iter().map(|file| file.rel.as_str()).collect();
let current_path_ids: std::collections::HashSet<&str> = files
.iter()
.map(|file| file.rel_id.as_str())
.filter(|id| !id.is_empty())
.collect();
let path_survives = |assignment: &FileAssignment| {
current_rels.contains(assignment.rel.as_str())
|| (!assignment.path_id.is_empty()
&& current_path_ids.contains(assignment.path_id.as_str()))
};
let mut added_content_groups: Vec<InventoryDeltaEntry> = files
.iter()
.zip(keys)
.filter(|(_, key)| !key.is_empty() && !durable_keys.contains(key.as_str()))
.map(|(file, key)| InventoryDeltaEntry {
file_key: key.clone(),
path: file.rel.clone(),
})
.collect();
// #439: a plan file absent from the walk is a *deletion* only if it is
// also absent from disk. If it is still on disk, the walk stopped
// yielding it because an ignore/hidden rule widened — an exclusion, not
// a removal — and the accurate recovery is different. `vanished_is_on_disk`
// checks through the reversible raw-bytes identity, so a hidden NON-UTF-8
// name (the case #439 was filed for) is matched on disk rather than read
// as a phantom removal via its lossy `rel`.
let mut deleted_content_groups: Vec<InventoryDeltaEntry> = Vec::new();
let mut excluded_content_groups: Vec<InventoryDeltaEntry> = Vec::new();
for (key, assignment) in &plan.files {
if current_keys.contains(key.as_str()) || path_survives(assignment) {
continue;
}
let entry = InventoryDeltaEntry {
file_key: key.clone(),
path: assignment.rel.clone(),
};
if vanished_is_on_disk(root, assignment) {
excluded_content_groups.push(entry);
} else {
deleted_content_groups.push(entry);
}
}
// Deliberately NOT extended with `plan.junk_files`. A junk/skipped file
// published no documents, no aliases and no graph edges — its entire
// live footprint is one `file:{key}` catalog row, and the stale
// junk-catalog sweep below (#238) deletes that row before dropping the
// plan entry. Removing it therefore strands nothing, so refusing the
// rerun would block a case the pipeline now handles completely. Junk
// keys stay in `durable_keys` above: an unchanged skipped file is still
// not an addition.
let stable_order = |left: &InventoryDeltaEntry, right: &InventoryDeltaEntry| {
left.path
.cmp(&right.path)
.then_with(|| left.file_key.cmp(&right.file_key))
};
added_content_groups.sort_by(stable_order);
excluded_content_groups.sort_by(stable_order);
deleted_content_groups.sort_by(stable_order);
Self {
added_content_groups,
deleted_content_groups,
excluded_content_groups,
}
}
/// Whether the classifier sees a genuine deletion.
///
/// The run does not return [`Self::into_error`] for that anymore (#2314):
/// both gates sweep `deleted_content_groups` with `sweep_excluded_groups`,
/// including `--fresh`, which used to be refused because discarding the
/// journal does not delete published documents. This method stays so the
/// classifier tests can tell a deletion from an exclusion or an addition.
/// An exclusion is swept the same way and is not a refusal (#589).
#[cfg(test)]
fn refuses(&self) -> bool {
!self.deleted_content_groups.is_empty()
}
#[cfg(test)]
fn into_error(self, targets: RefusalTargets) -> anyhow::Error {
UnsupportedInventoryDeltaError {
delta: self,
targets,
}
.into()
}
}
/// [`UnsupportedInventoryDelta::between`], plus dataless placeholders this run
/// deliberately did not hash (#2058).
///
/// Those files are still on disk. Leaving them out of `files` makes the delta
/// call them exclusions, and the exclusion sweep deletes documents that were
/// indexed the last time the bytes were local. An empty `dataless_still_present`
/// takes the original path and clones nothing.
fn inventory_delta(
root: &Path,
files: &[walk::FileEntry],
keys: &[String],
plan: &Plan,
dataless_still_present: &[walk::FileEntry],
) -> UnsupportedInventoryDelta {
if dataless_still_present.is_empty() {
return UnsupportedInventoryDelta::between(root, files, keys, plan);
}
let mut files = files.to_vec();
let mut keys = keys.to_vec();
for file in dataless_still_present {
files.push(file.clone());
keys.push(String::new());
}
UnsupportedInventoryDelta::between(root, &files, &keys, plan)
}
/// Hash-phase denominator on macOS. Carried placeholders are in `files` but
/// are not read, so they are not part of the work the bar describes.
#[cfg(target_os = "macos")]
fn hash_phase_totals(
files: &[walk::FileEntry],
carry: &std::collections::HashMap<String, String>,
all_bytes: u64,
) -> (u64, u64) {
if carry.is_empty() {
return (files.len() as u64, all_bytes);
}
let mut count = 0u64;
let mut bytes = 0u64;
for file in files {
if !carry.contains_key(&file.rel_id) {
count += 1;
bytes += file.size;
}
}
(count, bytes)
}
/// Watch-pass hash totals, minus placeholders whose previous digest is carried
/// instead of read. An empty carry map returns the watch plan's own totals.
#[cfg(target_os = "macos")]
fn watch_hash_totals(
plan: &watch::PassPlan,
files: &[walk::FileEntry],
carry: &std::collections::HashMap<String, String>,
) -> (u64, u64) {
if carry.is_empty() {
return (plan.hash_files, plan.hash_bytes);
}
let mut hash_files = plan.hash_files;
let mut hash_bytes = plan.hash_bytes;
for file in files {
if carry.contains_key(&file.rel_id) && plan.carried(file).is_none() {
hash_files = hash_files.saturating_sub(1);
hash_bytes = hash_bytes.saturating_sub(file.size);
}
}
(hash_files, hash_bytes)
}
fn alias_keys_to_reindex(
previous: &[state::DuplicateFile],
current: &[state::DuplicateFile],
migration_keys: Option<&[String]>,
) -> std::collections::HashSet<String> {
let paths_by_key = |aliases: &[state::DuplicateFile]| {
let mut by_key: HashMap<String, std::collections::BTreeSet<String>> = HashMap::new();
for alias in aliases {
by_key
.entry(alias.file_key.clone())
.or_default()
.insert(alias.rel.clone());
}
by_key
};
let previous = paths_by_key(previous);
let current = paths_by_key(current);
let mut changed = std::collections::HashSet::new();
if let Some(keys) = migration_keys {
changed.extend(keys.iter().cloned());
}
for key in previous.keys().chain(current.keys()) {
if previous.get(key) != current.get(key) {
changed.insert(key.clone());
}
}
changed
}
/// Default second-brain name for a corpus root: `sanitize_slug(basename)`
/// (SECOND_BRAIN_SPEC §6.1), falling back to `"brain"` when the basename
/// sanitizes to nothing (e.g. `/`). Public because `xerj brain` must know
/// the SAME name this pipeline will use — the console URL it prints and
/// opens embeds it — and two copies of this rule would drift.
pub fn derive_brain_name(root: &Path) -> String {
let base = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let name = base
.file_name()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
let slug = dataset::sanitize_slug(&name);
if slug.is_empty() {
"brain".into()
} else {
slug
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
struct DurableDatasetStats {
bytes: u64,
junk: u64,
dropped: u64,
}
/// Source metadata durably represented by each dataset.
///
/// `FileDone` is the commit record for a successfully published canonical
/// source. A source can feed more than one inferred dataset (for example, a
/// workbook or database with multiple tables), so each distinct assigned
/// dataset reports the complete source bytes it depends on. Repeated groups
/// within the same dataset count the source only once. Parser-level junk has
/// no group after extraction rejects it, so it retains the historical
/// attribution to the file's first assigned dataset. Coercion drops retain
/// their exact dataset captured in the completion record.
fn durable_dataset_stats(
plan: &Plan,
done: &HashMap<String, FileDone>,
) -> HashMap<String, DurableDatasetStats> {
let mut stats_by_dataset: HashMap<String, DurableDatasetStats> = HashMap::new();
for (file_key, completed) in done {
let Some(assignment) = plan.files.get(file_key) else {
continue;
};
let assigned_datasets: std::collections::HashSet<&str> = assignment
.assignments
.iter()
.map(|(_, slug)| slug.as_str())
.collect();
for slug in assigned_datasets {
let stats = stats_by_dataset.entry(slug.to_string()).or_default();
stats.bytes = stats.bytes.saturating_add(completed.bytes);
}
if let Some((_, slug)) = assignment.assignments.first() {
let stats = stats_by_dataset.entry(slug.clone()).or_default();
stats.junk = stats.junk.saturating_add(completed.junk);
}
for (slug, dropped) in &completed.dropped_by_dataset {
if assignment
.assignments
.iter()
.any(|(_, assigned)| assigned == slug)
{
let stats = stats_by_dataset.entry(slug.clone()).or_default();
stats.dropped = stats.dropped.saturating_add(*dropped);
}
}
}
stats_by_dataset
}
fn invocation_report_timestamps(
started: chrono::DateTime<chrono::Utc>,
summary_generated_at: chrono::DateTime<chrono::Utc>,
) -> (String, String) {
(started.to_rfc3339(), summary_generated_at.to_rfc3339())
}
fn pin_pending_embedding_identity(
es: &Es,
journal: &mut state::Journal,
pending: &sync::PendingSync,
) -> Result<()> {
if !pending
.desired
.plan
.datasets
.iter()
.any(|dataset| dataset.semantic_field.is_some())
{
return Ok(());
}
let expected = pending
.desired
.execution
.as_ref()
.context("pending semantic generation has no execution identity")?;
let current = es.embedding_execution_identity().context(
"pending semantic generation cannot verify the server embedding execution identity",
)?;
anyhow::ensure!(
current.resumable,
"pending semantic generation cannot resume because the current embedding backend is not \
resumable: {}; restore the original backend, or rebuild with a new --state-dir and a new \
--prefix",
current
.non_resumable_reason
.as_deref()
.unwrap_or("the server did not provide a stable execution identity")
);
anyhow::ensure!(
current.identity_sha256 == expected.embedding_identity_sha256
&& current.backend == expected.embedding_backend
&& current.dimensions == expected.embedding_dimension
&& current.semantic_contract == expected.embedding_semantic_contract
&& current.resumable == expected.embedding_resumable,
"pending semantic generation was prepared for a different embedding execution identity; \
no remote mutation was attempted. Restore the original embedding backend, or rebuild with \
a new --state-dir and a new --prefix. --fresh cannot discard this pending generation"
);
journal.pin_embedding_identity(
¤t.identity_sha256,
current.resumable,
current.dimensions,
current.non_resumable_reason.as_deref(),
)
}
fn finish_generated_run(es: &Es, journal: &mut state::Journal, cfg: &IndexCfg) -> Result<Value> {
let committed = journal
.committed_manifest
.as_ref()
.context("generated run finished without committed generation authority")?;
let execution = committed
.execution
.as_ref()
.context("generated run finished without execution identity")?;
let generation = committed.generation;
let dataset_count = committed.plan.datasets.len();
let committed_refusals: Vec<(String, usize, String)> = committed
.plan
.refused_datasets
.iter()
.map(|refusal| {
(
refusal.dataset.slug.clone(),
refusal.file_keys.len(),
refusal.reason.clone(),
)
})
.collect();
// Same lines the graph route prints (`unextracted_archive_lines`): the
// `--no-graph` route has its own, shorter summary and said nothing either.
let unextracted_archives = {
let junk: Vec<&JunkFile> = committed.plan.junk_files.iter().collect();
unextracted_archive_lines(&junk)
};
// Taken while `committed` still borrows the journal. `journal.finish`
// needs that borrow back, and the printed summary (human and --json)
// lists the same skips the plan recorded (#2056).
let skip_lines = skipped_lines_from_plan(&committed.plan.junk_files);
let skip_doc = {
let refs: Vec<&JunkFile> = committed.plan.junk_files.iter().collect();
skipped_json(&refs)
};
// #2370: owned here, while `committed` still borrows the journal. A no-op
// re-run's catalog document may predate the field; the summary below is
// recomputed from the sealed generation either way.
let family_warnings = family_junk::from_groups(&committed.plan, &committed.groups);
let family_warning_lines: Vec<String> = family_warnings
.iter()
.map(|warning| warning.line())
.collect();
let sync::SourceExecutionPolicy::DurableSnapshot { reference, .. } = &execution.source_policy
else {
anyhow::bail!("generated run does not reference a durable snapshot");
};
let run_id = reference
.strip_prefix("sync-snapshots/")
.context("generated run snapshot reference is not state-relative")?
.to_owned();
let response = es.search(
catalog::CATALOG_INDEX,
&json!({
"size": 2,
"query": {"bool": {"filter": [
{"term": {"run_id": &run_id}},
{"term": {"doc_kind": "run"}}
]}}
}),
)?;
let hits = response
.pointer("/hits/hits")
.and_then(Value::as_array)
.context("generated run summary query has no hits")?;
anyhow::ensure!(
hits.len() == 1,
"generated run summary query returned {} documents; expected exactly one",
hits.len()
);
let summary = hits[0]
.get("_source")
.cloned()
.context("generated run summary hit has no _source")?;
anyhow::ensure!(
summary.get("generation").and_then(Value::as_u64) == Some(generation),
"generated run summary generation disagrees with committed authority"
);
// #944: THIS run's re-sends of items the server answered 429, not a
// property of the committed generation — a re-run that sent nothing
// reports nothing. Present only when it happened.
let mut summary = summary;
let bulk_retries = es.bulk_backpressure_retries();
if bulk_retries > 0 {
summary["bulk_retries"] = json!(bulk_retries);
summary["bulk_items_reissued"] = json!(es.bulk_items_reissued());
}
// #955: requests the server refused as too large and this run halved.
// Present only when it happened, like the line above.
if es.bulk_requests_split() > 0 {
summary["bulk_splits"] = json!(es.bulk_requests_split());
}
if let Some(skipped) = skip_doc {
summary["skipped"] = skipped;
}
// Recomputed from the committed plan, not only copied from the catalog
// document: a no-op re-run reads the previous run document, which may
// predate this field, and a family-wide worker failure must still exit 1.
if let Some(n) = committed.plan.pdf_worker_unavailable_count() {
summary["pdf_worker_unavailable"] = json!(n);
}
// Absent when no family tripped the threshold, so a clean run document
// keeps the fields it already had (#2370).
if !family_warnings.is_empty() {
summary["family_junk_warnings"] = serde_json::to_value(&family_warnings)
.expect("family junk warnings are strings and counts");
}
journal.finish(&summary)?;
if cfg.json {
println!("{summary}");
} else if !cfg.quiet {
let count = |field: &str| summary.get(field).and_then(Value::as_u64).unwrap_or(0);
println!(
"{}",
outcome_headline(
generated_exit_code(&summary),
count("files_junk"),
count("junk_records_total"),
false,
0,
summary
.get("pdf_worker_unavailable")
.and_then(Value::as_u64)
.filter(|n| *n > 0),
// File removal is reported on the graph path. This printer
// is the generated route, which does not sweep membership.
0,
)
);
for line in &family_warning_lines {
println!("{line}");
}
for line in &skip_lines {
println!("{line}");
}
println!(
"generation {} committed — {}, {} live",
generation,
estimate::count_phrase(dataset_count as u64, "dataset", "datasets"),
estimate::count_phrase(
summary
.get("records_total")
.and_then(Value::as_u64)
.unwrap_or(0),
"record",
"records",
),
);
// #929: read from the committed manifest, so a no-op re-run names the
// refused datasets again instead of only the run that met the refusal.
for refusal in &committed_refusals {
println!(
"REFUSED dataset {} ({} file(s) recorded as junk, not indexed): {}",
refusal.0, refusal.1, refusal.2
);
}
if !unextracted_archives.is_empty() {
println!("not indexed — archives are never opened; extract, then run this command on the extracted folder:");
for line in &unextracted_archives {
println!(" {line}");
}
}
// #1103: this printer used to stop at the commit line, so a
// `--no-graph` run taught the user nothing — no data map, no search
// shape — while the interactive summary taught both. The guidance is
// the same text from the same functions; `code_files_indexed` on the
// committed run document is the code-corpus gate (the plan that the
// interactive site reads is not in scope on this resume/watch path).
println!(
"{}",
next_hint(
&cfg.url,
&cfg.prefix,
cfg.api_key.as_deref(),
std::env::var("XERJ_API_KEY").ok().as_deref(),
cfg.api_key_file.as_deref(),
)
);
if summary
.get("code_files_indexed")
.and_then(Value::as_u64)
.unwrap_or(0)
> 0
{
println!("{}", code_search_hint(&cfg.prefix));
}
}
Ok(summary)
}
/// One search page of [`delete_catalog_docs_scoped`], and its page budget.
/// `from + PAGE` stays inside the default `max_result_window` (10k) at the cap,
/// so no page is refused. Named at module scope so the boundary test walks the
/// same numbers the sweep does rather than its own copy of them.
const SCOPED_SWEEP_PAGE: usize = 1_000;
const SCOPED_SWEEP_MAX_PAGES: usize = 10;
/// Delete the `autoindex-catalog` documents whose `_source` matches EVERY
/// `(field, value)` pair **exactly**, whatever type this catalog's mapping
/// gives those fields (#890).
///
/// A plain scoped `_delete_by_query` cannot promise that on this index. The
/// catalog is global across every corpus on the node and it outlives releases,
/// so a field it holds is not necessarily the type this build declares:
/// v1.0.0-rc.15 began writing `prefix` before `catalog::catalog_mapping`
/// declared it, so any catalog an rc.15..rc.67 build wrote to before that
/// mapping landed holds `prefix` as dynamically-inferred **`text`** — which
/// includes catalogs first created by an EARLIER release and only later touched
/// by one of those (see [`install_catalog_mapping`] for that history). A `term`
/// query is not analyzed, but the FIELD is: against
/// `text` it matches when one of the stored value's analyzed TOKENS equals the
/// term. So `{"term": {"prefix": "ax"}}` also reaches a document whose prefix is
/// `ax-2` (tokens `[ax, 2]`) — a **sibling corpus's** document, which is exactly
/// the cross-corpus over-delete #737 drew the scope to prevent, and a delete is
/// not recoverable.
///
/// The scope therefore cannot rest on the query alone. The server-side query
/// stays — it is what keeps the candidate set small — but it is treated as a
/// *filter*, not as the decision: every returned hit is re-checked against the
/// raw scope values here, and only the exact ones are deleted, by `_id`. That is
/// mapping-independent by construction, so it holds on a keyword catalog and on
/// a legacy text one alike, and it holds for the `path`/`file_key` conjunct as
/// well as for the corpus scope. Where the field really is a keyword the result
/// is identical to the delete this replaces, up to the page budget below: past
/// [`SCOPED_SWEEP_MAX_PAGES`] * [`SCOPED_SWEEP_PAGE`] candidates for one scope
/// conjunction this refuses where the old `_delete_by_query` would have kept
/// going.
///
/// It cannot invent coverage the query does not return: on a legacy catalog an
/// analyzed field can also match FEWER documents than it should (a multi-token
/// value like `vendor/LICENSE` produces no token equal to itself, so a `term`
/// finds nothing), and no client-side check can recover a hit the server never
/// sent. That under-match is #755's subject, answered by
/// `catalog::CORPUS_SCOPE_FIELD` and by the by-`_id` sweep in the caller; this
/// function is only about never deleting more than the scope names.
fn delete_catalog_docs_scoped(es: &Es, scope: &[(&str, &str)]) -> Result<()> {
let query = json!({"bool": {"filter": scope
.iter()
.map(|(field, value)| json!({"term": {*field: *value}}))
.collect::<Vec<Value>>()}});
let label = scope
.iter()
.map(|(field, value)| format!("{field}={value}"))
.collect::<Vec<_>>()
.join(", ");
delete_catalog_hits_where(es, &query, &label, |_id, hit| {
// The re-check. A hit whose stored scope value is not byte-equal to
// what the caller asked for belongs to something else — a sibling
// corpus, or another file — and is left alone.
scope.iter().all(|(field, value)| {
hit.pointer("/_source")
.and_then(|source| source.get(*field))
.and_then(Value::as_str)
== Some(*value)
})
})
}
/// The page walk both scoped catalog sweeps share: read the candidate set
/// `query` selects, ask `accept` about every hit, and delete by `_id` exactly
/// the hits it accepts — nothing at all, if it accepts nothing.
///
/// Split out of [`delete_catalog_docs_scoped`] for #905, which needs the same
/// walk under a different per-hit decision (corpus attribution rather than a
/// byte-exact `_source` compare) and must not carry a second copy of the paging
/// rules: the off-by-one those rules encode was a real defect once already (the
/// #890 review follow-up), and one copy of it is enough.
///
/// `accept` is `FnMut` so a caller can record what it declined as it goes.
/// #905's does, because a candidate it cannot attribute to a corpus is one it
/// deliberately leaves behind and therefore has to be able to name.
fn delete_catalog_hits_where(
es: &Es,
query: &Value,
scope_label: &str,
mut accept: impl FnMut(&str, &Value) -> bool,
) -> Result<()> {
let mut ids: Vec<String> = Vec::new();
let mut from = 0usize;
for _ in 0..SCOPED_SWEEP_MAX_PAGES {
// #1212: `search_page`, not `search` — the engine answers a missed
// default search deadline with a partial 200 (`timed_out`), and a
// partial page here would end the sweep early holding a prefix of
// the candidate set: the deletes below would remove only what the
// prefix contained while `Ok(())` reported the sweep complete. (The
// `relation` check below cannot catch it either — a timed-out scan
// can still answer `relation: "eq"` with an under-counted total,
// live-observed against 58,568 real documents answering
// `{value: 0, relation: "eq"}`.) The page variant retries a timed-out
// page instead of returning it, so every page this loop sees is
// complete.
let page = es.search_page(
catalog::CATALOG_INDEX,
&json!({"query": query.clone(), "from": from, "size": SCOPED_SWEEP_PAGE}),
)?;
let hits = page
.pointer("/hits/hits")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
for hit in &hits {
let Some(id) = hit.get("_id").and_then(Value::as_str) else {
continue;
};
if accept(id, hit) {
ids.push(id.to_string());
}
}
from += hits.len();
// The candidate set is exhausted on a short page — and ALSO once the
// hits seen reach an EXACT `hits.total`. Both rules are needed: at
// exactly `SCOPED_SWEEP_MAX_PAGES * SCOPED_SWEEP_PAGE` candidates every
// page comes back full, so the short-page rule alone falls out of the
// loop and refuses while already holding the complete, re-checked set.
//
// `relation: "gte"` is an honest LOWER bound rather than a count (a
// capped hybrid sub-list, a timed-out scan), so it is never trusted to
// end the walk; that case falls back to the short-page rule alone.
let total_is_exact =
page.pointer("/hits/total/relation").and_then(Value::as_str) != Some("gte");
let total = page.pointer("/hits/total/value").and_then(Value::as_u64);
let exhausted = hits.len() < SCOPED_SWEEP_PAGE
|| (total_is_exact && total.is_some_and(|total| from as u64 >= total));
if exhausted {
// The whole candidate set has been seen. Delete the exact ones, in
// requests that stay requests — the same bound, and for the same
// reason, as the duplicate-alias sweep's [`ALIAS_SWEEP_CHUNK`].
for chunk in ids.chunks(ALIAS_SWEEP_CHUNK) {
es.delete_by_query(catalog::CATALOG_INDEX, &json!({"ids": {"values": chunk}}))?;
}
return Ok(());
}
}
// Refusing beats deleting a prefix of the set and reporting success: an
// exclusion that only partly removes data is the #439 exposure. Reaching
// here needs MORE than `SCOPED_SWEEP_MAX_PAGES * SCOPED_SWEEP_PAGE` (10k)
// catalog documents matching one file's scope conjunction. A keyword
// catalog CAN produce that — one content group of 10k+ byte-identical
// files, each carrying its own alias doc — so this is a real, if narrow,
// narrowing of the `_delete_by_query` it replaces, which repeated
// 10k-document passes of its own. It fails CLOSED, and the remedy it names
// is the one the legacy-catalog warning already gives.
Err(anyhow::anyhow!(
"scoped sweep of `{}` still had candidates after {SCOPED_SWEEP_MAX_PAGES} pages of \
{SCOPED_SWEEP_PAGE} for scope [{scope_label}]; refusing to report a partial removal — \
reindex `{}` into an index created with the current mapping",
catalog::CATALOG_INDEX,
catalog::CATALOG_INDEX,
))
}
/// The graph path's catalog gate (#1977).
///
/// `autoindex-catalog` is created empty during prepare, and the data indices
/// are refreshed — and therefore searchable — before this write. The bulk that
/// fills the catalog used to treat a per-item refusal as a warning (#955) and
/// never read the rows back, so a response the client classified as success
/// could leave the index at zero documents and the run at exit 0. `xerj_map`
/// then reports no datasets. The data path already refuses that shape (the
/// zero-live gate, #195). This is the same check for the rows `xerj_map` reads:
/// every published dataset document and the run document, visible by `_id`
/// with the `doc_kind` the map filters on.
///
/// Called only after the catalog refresh, and before the resume journal is
/// finished, so a failure leaves the next invocation of the same command to
/// rewrite these ids.
fn require_visible_catalog_rows(es: &Es, ids: &[String]) -> Result<()> {
// One ids query stays under the default result window. 200 is also the
// point at which a ~210-dataset batch (the #1977 report) takes two
// requests instead of one oversized one.
const CHUNK: usize = 200;
let mut missing_at: Vec<usize> = Vec::new();
for (chunk_index, chunk) in ids.chunks(CHUNK).enumerate() {
let response = es
.search(
catalog::CATALOG_INDEX,
&json!({
"size": chunk.len(),
"query": {"ids": {"values": chunk}},
"_source": ["doc_kind"]
}),
)
.context(
"write catalog: reading the catalog back failed, so this run cannot claim the \
data map was published",
)?;
let hits = response
.pointer("/hits/hits")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let mut seen: HashSet<String> = HashSet::new();
for hit in &hits {
let Some(id) = hit.get("_id").and_then(Value::as_str) else {
continue;
};
let kind = hit.pointer("/_source/doc_kind").and_then(Value::as_str);
let expected = if id.starts_with("run:") {
"run"
} else if id.starts_with("ds:") {
"dataset"
} else {
continue;
};
if kind == Some(expected) {
seen.insert(id.to_string());
}
}
let base = chunk_index * CHUNK;
for (offset, id) in chunk.iter().enumerate() {
if !seen.contains(id) {
missing_at.push(base + offset);
}
}
}
if missing_at.is_empty() {
return Ok(());
}
let shown: Vec<&str> = missing_at
.iter()
.take(8)
.map(|&index| ids[index].as_str())
.collect();
let extra = missing_at.len().saturating_sub(shown.len());
let extra = if extra > 0 {
format!(" (+{extra} more)")
} else {
String::new()
};
anyhow::bail!(
"write catalog: {} of {} catalog document(s) are not visible after the write ({}{extra}). \
The data indices are already indexed; rerun the same command to rewrite the catalog. \
`xerj autoindex map` stays empty until those rows exist",
missing_at.len(),
ids.len(),
shown.join(", "),
)
}
/// #589: sweep the documents an exclusion left behind. A file still on disk
/// that a widened ignore/hidden/`.xerjignore` rule now skips must have its
/// already-published documents removed — an exclusion that cannot remove data
/// already in the index is the #439 data-exposure hole. Deletes the indexed
/// records (by `ax_file`) across the corpus indices and the file's catalog
/// document(s) (by logical `path`).
///
/// The caller sweeps only when there is NO genuine deletion in the same delta
/// (a co-occurring deletion refuses the whole rerun, mutating nothing) and
/// never under `--dry-run`.
///
/// #694: graph edges taught by the excluded file are soft-invalidated too, when
/// this run has a graph (`edges_index` is `Some`). It reuses the replacement
/// hook `detect::invalidate_prior_edges` — the excluded entry's `path` IS the
/// `src_file` the edges carry — so an edge naming a now-excluded file stops
/// being searchable (the bi-temporal record survives for `as_of` time travel,
/// exactly like a replaced file's edges). Under `--no-graph` (`edges_index` is
/// `None`) there is no edges index to touch.
fn sweep_excluded_groups(
es: &Es,
prefix: &str,
plan: &Plan,
excluded: &[InventoryDeltaEntry],
edges_index: Option<&str>,
now_ms: i64,
) -> Result<()> {
// Exact dataset indices from the plan — the same resolution the replacement
// delete path uses (`ds_rt` → `rt.index`); a `{prefix}-*` wildcard would be
// untestable and could reach indices this corpus does not own.
let mut indices: Vec<&str> = plan.datasets.iter().map(|d| d.index.as_str()).collect();
indices.sort_unstable();
indices.dedup();
for entry in excluded {
for index in &indices {
es.delete_by_query(index, &json!({"term": {"ax_file": entry.file_key}}))
.with_context(|| {
format!(
"sweep indexed records for newly-excluded {} in {index}",
entry.path
)
})?;
}
// #737: BOTH catalog deletes are scoped to THIS corpus's `prefix`. The
// `autoindex-catalog` index is shared across corpora; an unscoped `path`
// or `file_key` term would also delete a byte-identical file's catalog
// docs owned by a still-live SIBLING corpus (`current_keys` only guards
// the same corpus). The `prefix` keyword field (written by `file_doc`/
// `duplicate_file_doc`) makes the scope term-queryable.
//
// #755: each scoped delete runs TWICE, once per scope field. `prefix`
// is only a `keyword` on a catalog this build (or #737's) created — on
// an install upgraded from rc.15..rc.67 it is dynamically inferred
// `text`, where a `term` does not match the raw scope value and the
// sweep silently no-ops. `catalog::CORPUS_SCOPE_FIELD` carries the same
// value on a field no older release ever wrote, so it is `keyword`
// everywhere; `prefix` stays for documents written by rc.68..this
// release, which do not carry the new field. Two conjunctive deletes
// rather than one `should` disjunction: each is a query shape the
// engine and this crate already exercise, and neither drops its scope
// term.
//
// #890: neither pass may be a bare `delete_by_query`. On a catalog
// upgraded from rc.15..rc.67 `prefix` is `text`, and a `term` against an
// analyzed field matches TOKENS — `prefix: "ax"` also reaches a sibling
// corpus whose prefix is `ax-2` (tokens `[ax, 2]`), deleting ITS catalog
// documents for a byte-identical file. `delete_catalog_docs_scoped`
// keeps the same query as the candidate filter and then re-checks every
// scope value against the returned `_source` before deleting by `_id`,
// so the scope is exact whatever the catalog's mapping says — for the
// `path`/`file_key` conjunct as much as for the corpus scope.
for scope_field in [catalog::CORPUS_SCOPE_FIELD, "prefix"] {
delete_catalog_docs_scoped(es, &[(scope_field, prefix), ("path", &entry.path)])
.with_context(|| {
format!(
"sweep catalog entry ({scope_field}-scoped) for newly-excluded {}",
entry.path
)
})?;
}
// #693: also purge the file's `file-alias:` duplicate catalog docs
// (`catalog::duplicate_file_doc`). Each carries the DUPLICATE's own
// `path`, so the `path` term above misses them, leaving an excluded
// file's alternate path/filename searchable. Both the main `file:` doc
// and every `file-alias:` doc carry `file_key`, and the delta classifies
// a content group as excluded ONLY when no surviving file bears its key
// (`UnsupportedInventoryDelta::between`: the `current_keys` guard), so a
// `file_key` term cannot strand a still-live byte-identical duplicate in
// the same corpus; the `prefix` filter (#737) guards the cross-corpus axis.
// #755: both scope fields, for the reason given on the delete above.
// #890: and both through the exact scoped delete, for the reason given
// there — an alias sweep runs on the same cross-corpus axis.
for scope_field in [catalog::CORPUS_SCOPE_FIELD, "prefix"] {
delete_catalog_docs_scoped(es, &[(scope_field, prefix), ("file_key", &entry.file_key)])
.with_context(|| {
format!(
"sweep catalog aliases ({scope_field}-scoped) for newly-excluded {}",
entry.path
)
})?;
}
// #739: the two scoped deletes above match only docs that carry the
// `prefix` field, which was added in #737 — a `file:` doc written by a
// pre-#737 binary has no `prefix` value and would survive the sweep on
// the first upgraded run. Delete the main `file:` doc by its exact,
// prefix-encoded `_id` too: it catches legacy and current docs alike and
// is inherently corpus-scoped (a sibling corpus's id differs), so it
// cannot strand or over-delete.
//
// Legacy `file-alias:` docs get the same treatment: `plan` is the
// FROZEN plan (the state before this run), so `duplicate_files` still
// carries every alias's `rel`/`path_id` for a content group being
// excluded now — the same lookup `catalog::duplicate_file_id` needs,
// and the same shape `stale_alias_ids` above already reconstructs ids
// from elsewhere in this file. Building each alias's exact id closes
// the residual the main-doc fix (above) left open: a pre-#737
// `file-alias:` doc has no `prefix` either, so it also survives the
// #693 term-scoped alias sweep on the first upgraded run.
let mut ids = vec![catalog::file_id(prefix, &entry.file_key)];
ids.extend(
plan.duplicate_files
.iter()
.filter(|alias| alias.file_key == entry.file_key)
.map(|alias| {
catalog::duplicate_file_id(prefix, &alias.file_key, &alias.rel, &alias.path_id)
}),
);
es.delete_by_query(catalog::CATALOG_INDEX, &json!({"ids": {"values": ids}}))
.with_context(|| {
format!(
"sweep catalog file/alias docs by id for newly-excluded {}",
entry.path
)
})?;
// #694: soft-invalidate the edges this file taught. `invalidate_prior_edges`
// tolerates a not-yet-created edges index (returns 0), so a graph run whose
// edges index has not been ensured at this point is safe.
if let Some(edges) = edges_index {
detect::invalidate_prior_edges(es, edges, &entry.path, now_ms)
.with_context(|| format!("sweep graph edges for newly-excluded {}", entry.path))?;
// #736: also soft-invalidate INBOUND edges — ones a surviving file
// taught that point AT this now-removed file's anchor node. Without
// this they stay live, pointing at a `dst` whose node is gone. The
// edge's `dst` is the target file's anchor doc id
// `ids::doc_id(slug, file_key, "file")`; a file can anchor in more
// than one dataset, so invalidate for every slug the frozen plan
// assigned it. Same soft-invalidate as the src side (bi-temporal).
if let Some(fa) = plan.files.get(&entry.file_key) {
for (_, slug) in &fa.assignments {
let anchor =
crate::ids::doc_id(slug, &entry.file_key, detect::FILE_CARD_LOCATOR);
detect::invalidate_edges_by_field(es, edges, "dst", &anchor, now_ms)
.with_context(|| {
format!(
"sweep inbound graph edges for newly-excluded {}",
entry.path
)
})?;
}
}
}
}
Ok(())
}
/// What [`carry_over_unread_mail`] loaded.
#[derive(Default)]
struct CarriedMail {
/// Rel paths of the mail files that were carried over (sorted).
rels: std::collections::BTreeSet<String>,
/// Message nodes offered to the detectors.
messages: u64,
}
/// Offer the detectors the message nodes of every mail file this run did NOT
/// re-read, loaded back from the index (`EdgeDetector::carry_over`).
///
/// `email-thread@1` resolves replies at the end of a run, over the messages it
/// was shown. Shown only the files an incremental run re-read, a reply in a
/// changed `Inbox` to a message in an unchanged `Sent` resolved against
/// nothing and its edge was lost; and an unchanged file's reply into a
/// compacted mailbox kept a live edge to a node id that no longer existed
/// (review finding on PR #949). Both are the same defect — resolution over the
/// run instead of over the corpus — and this is the other half of the corpus.
///
/// It runs only when it can matter: some mail file was NOT re-read, and either
/// some mail file WAS, or the previous invocation never reached its summary
/// (its corpus pass may not have run), or an exclusion sweep removed files
/// (`force`). A one-mailbox Takeout never pays for it — a changed mailbox is
/// re-read whole, an unchanged one changes nothing — and neither does a no-op
/// re-run of a finished corpus.
///
/// Read-only. The scan names the files it wants (`ax_file`, in slices) and the
/// one locator shape that is a message node, and asks for five small fields.
fn carry_over_unread_mail(
es: &Es,
gr: &GraphRt,
index_of_slug: &HashMap<&str, &str>,
reread: &std::collections::HashSet<&str>,
force: bool,
) -> Result<CarriedMail> {
let is_mail = |f: &detect::CorpusFile| matches!(f.family.as_str(), "eml" | "mbox");
let mut unread: Vec<&detect::CorpusFile> = Vec::new();
let mut reread_mail = false;
for f in gr.corpus.files.values().filter(|f| is_mail(f)) {
if reread.contains(f.rel.as_str()) {
reread_mail = true;
} else {
unread.push(f);
}
}
if unread.is_empty() || !(reread_mail || force) {
return Ok(CarriedMail::default());
}
// One scan per (index, slice of files). BTreeMap: request order is a
// function of the corpus.
let mut by_index: std::collections::BTreeMap<&str, Vec<&detect::CorpusFile>> =
std::collections::BTreeMap::new();
for f in &unread {
if let Some(index) = index_of_slug.get(f.dataset_slug.as_str()) {
by_index.entry(index).or_default().push(f);
}
}
let source = json!([
"ax_path",
"ax_locator",
"email_message_id",
"email_in_reply_to",
"email_references"
]);
let mut carried = CarriedMail::default();
for (index, group) in by_index {
// What an interrupted run published is not searchable until refreshed.
es.refresh(index)
.with_context(|| format!("refresh {index} before the mail carry-over scan"))?;
for slice in group.chunks(detect::SCAN_TERMS) {
let keys: Vec<&str> = slice.iter().map(|f| f.file_key.as_str()).collect();
let query = json!({"bool": {"filter": [
{"terms": {"ax_file": keys}},
{"bool": {"should": [
{"term": {"ax_locator": "msg-s0"}},
{"wildcard": {"ax_locator": "m*-msg-s0"}}
], "minimum_should_match": 1}}
]}});
detect::scan_by_id(es, index, &query, &source, &mut |id, fields| {
let file = fields
.get("ax_path")
.and_then(Value::as_str)
.and_then(|rel| gr.corpus.files.get(rel))
.filter(|f| is_mail(f) && !reread.contains(f.rel.as_str()));
let (Some(file), Some(locator)) =
(file, fields.get("ax_locator").and_then(Value::as_str))
else {
return;
};
let ctx = detect::RecordCtx {
corpus: &gr.corpus,
file,
locator,
doc_id: id,
fields,
};
for det in &gr.detectors {
det.carry_over(&ctx);
}
carried.messages += 1;
})
.with_context(|| format!("scan {index} for the message nodes of un-re-read mail"))?;
}
}
// Every un-re-read mail file is "carried", including one whose scan found
// nothing: its live edges are re-judged either way.
carried.rels = unread.iter().map(|f| f.rel.clone()).collect();
Ok(carried)
}
/// The edges index this run's graph writes to, or `None` when there is none to
/// sweep: `--no-graph`, or a brain name that fails validation (a run that could
/// never have written edges — the graph phase bails on it before any write).
/// #694: the exclusion sweep uses this to invalidate a removed file's edges,
/// mirroring `edges_index_name(&brain)` at the graph phase without duplicating
/// the `--brain`/`derive_brain_name` fallback.
fn graph_edges_index(cfg: &IndexCfg) -> Option<String> {
if cfg.no_graph {
return None;
}
let brain = cfg
.brain
.clone()
.unwrap_or_else(|| derive_brain_name(&cfg.root));
detect::validate_brain(&brain)
.ok()
.map(|()| detect::edges_index_name(&brain))
}
/// #736: every graph ANCHOR node a plan owns — `ids::doc_id(slug, file_key,
/// FILE_CARD_LOCATOR)` for each dataset the file is assigned to — paired with
/// that file's `rel`. Sorted and deduped so two calls are directly comparable.
///
/// The anchor is the node every cross-file edge points AT (`EdgeDraft::dst` is
/// `CorpusFile::anchor_doc_id` in every detector that links two files), so the
/// anchor set is exactly the set of edge endpoints a plan can own.
///
/// The graph phase compares the PRIOR plan's anchors against this run's. An
/// anchor the prior plan owned and this one does not is SUPERSEDED — its node
/// belongs to a generation this run replaced — so the edges pointing at it
/// (`dst`) and the edges that generation taught (`src_file`) must both be
/// soft-invalidated. A file whose key and dataset assignments are unchanged
/// appears in both sets and is therefore never touched, which is what keeps the
/// #868 byte-identical skip honest: an unchanged file neither re-teaches nor
/// loses its edges.
fn plan_anchor_nodes(plan: &Plan) -> Vec<(String, String)> {
let mut anchors: Vec<(String, String)> = plan
.files
.iter()
.flat_map(|(key, assignment)| {
assignment.assignments.iter().map(move |(_, slug)| {
(
crate::ids::doc_id(slug, key, detect::FILE_CARD_LOCATOR),
assignment.rel.clone(),
)
})
})
.collect();
anchors.sort();
anchors.dedup();
anchors
}
/// Catalog doc id for a time correlation, corpus-prefix-scoped (#673): the
/// `autoindex-catalog` index is shared across corpora, so a time correlation
/// keyed only by dataset slugs would overwrite the same-slug correlation from
/// another corpus. Extracted (#689) so the prefix scoping is unit-testable, the
/// way `KeyCorr::id` is for `corr:`.
fn tcorr_id(prefix: &str, a_dataset: &str, b_dataset: &str) -> String {
format!("tcorr:{prefix}:{a_dataset}:{b_dataset}")
}
#[cfg(test)]
mod tcorr_id_tests {
use super::tcorr_id;
/// #689 (coverage gap from #673): the shared `autoindex-catalog` index means
/// a time correlation keyed by dataset slugs must carry the corpus prefix, or
/// `(reports, orders)` in corpus A overwrites the same-slug correlation in
/// corpus B. `corr:` is pinned by `correlate::tests`; this pins `tcorr:`.
#[test]
fn tcorr_id_is_prefix_scoped_across_corpora() {
// Same slugs, different corpus prefix -> distinct ids (no overwrite).
assert_ne!(
tcorr_id("ax-a", "reports", "orders"),
tcorr_id("ax-b", "reports", "orders"),
"#689: same-slug time correlations from two corpora must not collide"
);
// Idempotent within one corpus.
assert_eq!(
tcorr_id("ax-a", "reports", "orders"),
tcorr_id("ax-a", "reports", "orders"),
);
// The prefix is actually in the id.
assert!(tcorr_id("ax-a", "reports", "orders").starts_with("tcorr:ax-a:"));
}
}
fn run_index(cfg: IndexCfg) -> Result<i32> {
if cfg.watch {
return watch::run(cfg);
}
run_index_report(cfg).map(|(code, _)| code)
}
/// `run_index` with the caller's own phase-A tally, so a test can measure the
/// work of *its* run and nothing else's (#891). Production has no reason to
/// look at the number, which is why the public entry points own a throwaway.
#[cfg(test)]
fn run_index_tallied(cfg: IndexCfg, tally: &ScanTally) -> Result<i32> {
run_index_report_tallied(cfg, tally).map(|(code, _)| code)
}
/// Prefix of the junk reason `sniff::archive_advice` writes for an archive.
const UNEXTRACTED_PREFIX: &str = "unextracted ";
/// The junk files whose reason is an ACTION the user can take right now — an
/// archive autoindex will not open — as `path — reason` lines, sorted, capped.
///
/// A junk reason normally lives in the catalog and in `xerj autoindex map`, and
/// the run prints only a count. For an archive that is the wrong place: someone
/// whose whole Google Takeout download is one `.zip` saw `0 datasets, 0 records
/// live … 1 junk/skipped files … ok=true exit=3` and nothing else — a
/// "successful" empty index with the one sentence that explains it filed where
/// they would never look (review finding on PR #949). These few lines are the
/// run saying it.
const SKIP_LIST_CAP: usize = 20;
/// #2056: names of skipped files, capped, with the reason. The headline stays
/// one `ok:` line; this is the list under it.
fn skipped_lines(junk: &[&JunkFile]) -> Vec<String> {
if junk.is_empty() {
return Vec::new();
}
let mut rows: Vec<&&JunkFile> = junk.iter().collect();
rows.sort_by(|a, b| a.rel.cmp(&b.rel).then(a.reason.cmp(&b.reason)));
let mut lines = vec![format!(
"skipped: {}",
estimate::count_phrase(rows.len() as u64, "file", "files")
)];
for jf in rows.iter().take(SKIP_LIST_CAP) {
lines.push(format!(
" skipped: {} ({}: {})",
jf.rel, jf.status, jf.reason
));
}
if rows.len() > SKIP_LIST_CAP {
lines.push(format!(
" … and {} more; `xerj autoindex map` lists every one",
rows.len() - SKIP_LIST_CAP
));
}
lines
}
fn skipped_lines_from_plan(junk: &[JunkFile]) -> Vec<String> {
let refs: Vec<&JunkFile> = junk.iter().collect();
skipped_lines(&refs)
}
fn skipped_json(junk: &[&JunkFile]) -> Option<Value> {
if junk.is_empty() {
return None;
}
let mut rows: Vec<&&JunkFile> = junk.iter().collect();
rows.sort_by(|a, b| a.rel.cmp(&b.rel).then(a.reason.cmp(&b.reason)));
let total = rows.len();
let files: Vec<Value> = rows
.iter()
.take(SKIP_LIST_CAP)
.map(|jf| {
json!({
"path": jf.rel,
"status": jf.status,
"reason": jf.reason,
})
})
.collect();
let mut doc = json!({ "count": total, "files": files });
if total > SKIP_LIST_CAP {
doc["not_listed"] = json!(total - SKIP_LIST_CAP);
}
Some(doc)
}
fn unextracted_archive_lines(junk: &[&JunkFile]) -> Vec<String> {
const SHOWN: usize = 10;
let mut hits: Vec<&&JunkFile> = junk
.iter()
.filter(|jf| jf.reason.starts_with(UNEXTRACTED_PREFIX))
.collect();
hits.sort_by(|a, b| a.rel.cmp(&b.rel));
let mut lines: Vec<String> = hits
.iter()
.take(SHOWN)
.map(|jf| format!("{} — {}", jf.rel, jf.reason))
.collect();
if hits.len() > SHOWN {
lines.push(format!(
"… and {} more archive(s); `xerj autoindex map` lists every one",
hits.len() - SHOWN
));
}
lines
}
#[cfg(test)]
mod unextracted_archive_tests {
use super::{unextracted_archive_lines, JunkFile};
fn junk(rel: &str, reason: &str) -> JunkFile {
JunkFile {
file_key: rel.into(),
rel: rel.into(),
format: "binary".into(),
status: "junk".into(),
reason: reason.into(),
bytes: 1,
}
}
#[test]
fn names_archives_with_their_command_and_nothing_else() {
let zip = junk(
"takeout-001.zip",
&crate::sniff::archive_advice("zip", false).unwrap(),
);
let tgz = junk(
"a/backup.tgz",
&crate::sniff::archive_advice("tar", true).unwrap(),
);
let png = junk("logo.png", "binary content (png)");
let lines = unextracted_archive_lines(&[&zip, &png, &tgz]);
assert_eq!(lines.len(), 2, "{lines:?}");
// Sorted by path; each line carries the file AND the command to run.
assert!(
lines[0].starts_with("a/backup.tgz — unextracted") && lines[0].contains("tar -xzf")
);
assert!(
lines[1].starts_with("takeout-001.zip — unextracted") && lines[1].contains("unzip")
);
assert!(unextracted_archive_lines(&[&png]).is_empty());
}
#[test]
fn a_folder_of_archives_is_capped_and_says_so() {
let reason = crate::sniff::archive_advice("zip", false).unwrap();
let many: Vec<JunkFile> = (0..14)
.map(|i| junk(&format!("p{i:02}.zip"), &reason))
.collect();
let refs: Vec<&JunkFile> = many.iter().collect();
let lines = unextracted_archive_lines(&refs);
assert_eq!(lines.len(), 11);
assert!(lines[10].contains("4 more archive(s)"), "{}", lines[10]);
}
}
/// #381/#759: the per-file record cap dropped these files' tails. Name them (up
/// to a bound) so a truncated document is identifiable on a multi-file corpus,
/// not merely counted — the "never silent" guarantee is only useful if the user
/// can tell *which* document lost its tail. `None` when nothing was truncated.
fn truncation_note_message(rels: &[String]) -> Option<String> {
if rels.is_empty() {
return None;
}
const SHOWN: usize = 10;
let mut names: Vec<&str> = rels.iter().map(String::as_str).collect();
names.sort_unstable();
let listed = names
.iter()
.take(SHOWN)
.copied()
.collect::<Vec<_>>()
.join(", ");
let more = names.len().saturating_sub(SHOWN);
let tail = if more > 0 {
format!(" (and {more} more)")
} else {
String::new()
};
// Three different caps set `ExtractStats::truncated`, and the note used to
// name only the first — so a mailbox holding one 2.3 GB message was told it
// had "hit the per-file record cap (4096)" with 205 records, and to "raise
// the cap", which is advice for a cap it never reached (review finding on
// PR #949). The flag does not say which cap fired. A path that looks like
// mail keeps all three causes. A plain document does not: telling the
// reader of an 8 MB `.txt` that a later mail message might still be
// indexed is false, and it is the note they actually saw.
let cause = if names.iter().any(|rel| rel_looks_like_mail(rel)) {
format!(
"one of: a single document over the per-document record cap ({} sections; its later \
sections were dropped), a mail message over the {} MB per-message cap (only that \
message's head was parsed; the messages after it are indexed), or a message with more \
MIME parts than the attachment cap (its later parts were dropped). Split the document \
or the message if the dropped part matters (#381)",
extract::MAX_RECORDS_PER_FILE,
extract::eml::MAX_EML >> 20,
)
} else {
format!(
"the per-document record cap is {} sections; later sections were dropped. Split the \
document if the dropped part matters (#381)",
extract::MAX_RECORDS_PER_FILE,
)
};
Some(format!(
"{} file(s) had content cut short that was NOT indexed: {listed}{tail} — {cause}",
names.len(),
))
}
/// The mail caps only apply to a mailbox. The last path component is enough:
/// `inbox.eml`, `lists.mbox`, `note.msg`.
fn rel_looks_like_mail(rel: &str) -> bool {
let name = rel.rsplit(['/', '\\']).next().unwrap_or(rel);
let lower = name.to_ascii_lowercase();
lower.ends_with(".eml") || lower.ends_with(".mbox") || lower.ends_with(".msg")
}
fn note_truncated_files(pr: &Progress, rels: &[String]) {
if let Some(msg) = truncation_note_message(rels) {
pr.note(&msg);
}
}
#[cfg(test)]
mod truncation_note_tests {
use super::truncation_note_message;
#[test]
fn empty_is_none() {
assert!(truncation_note_message(&[]).is_none());
}
#[test]
fn names_the_truncated_files() {
let msg = truncation_note_message(&["docs/big.md".into(), "a/soup.bytes".into()]).unwrap();
// Count, both names (sorted), the cap, and the #381 tag.
assert!(msg.contains("2 file(s)"), "{msg}");
assert!(
msg.contains("a/soup.bytes") && msg.contains("docs/big.md"),
"{msg}"
);
assert!(msg.contains("4096") && msg.contains("#381"), "{msg}");
assert!(!msg.contains("and 0 more"), "{msg}");
assert!(msg.contains("later sections were dropped"), "{msg}");
assert!(!msg.contains("raise the cap"), "{msg}");
// Neither file is mail. The mail caps must not be offered as a reason
// the tail might still be indexed.
assert!(!msg.contains("per-message cap"), "{msg}");
assert!(!msg.contains("MIME parts"), "{msg}");
assert!(!msg.contains("the messages after it are indexed"), "{msg}");
}
#[test]
fn a_mailbox_keeps_the_three_causes() {
let msg = truncation_note_message(&["mail/inbox.mbox".into(), "big.txt".into()]).unwrap();
assert!(
msg.contains("mail/inbox.mbox") && msg.contains("big.txt"),
"{msg}"
);
// The flag does not say which file hit which cap, so a list that
// contains any mailbox still names all three.
assert!(msg.contains("64 MB per-message cap"), "{msg}");
assert!(msg.contains("MIME parts"), "{msg}");
assert!(msg.contains("4096"), "{msg}");
assert!(!msg.contains("their tail"), "{msg}");
assert!(msg.contains("the messages after it are indexed"), "{msg}");
assert!(truncation_note_message(&["Notes.EML".into()])
.unwrap()
.contains("MIME parts"));
assert!(!truncation_note_message(&["notes.eml.txt".into()])
.unwrap()
.contains("MIME parts"));
}
#[test]
fn caps_the_list_and_counts_the_rest() {
let rels: Vec<String> = (0..14).map(|i| format!("f{i:02}.txt")).collect();
let msg = truncation_note_message(&rels).unwrap();
assert!(msg.contains("14 file(s)"), "{msg}");
assert!(msg.contains("(and 4 more)"), "{msg}");
}
}
/// `run_index` plus the machine-readable run summary — the same JSON the
/// run writes to the catalog as `run:{run_id}` (datasets, `records_total`
/// as *live* per-dataset counts, `graph.edges_written` etc.). `xerj brain`
/// composes autoindex through this so it can be honest about what actually
/// got indexed without re-querying or parsing stdout. The summary is
/// `None` when the run ended before a plan produced one (empty folder,
/// `--dry-run`).
pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
run_index_report_tallied(cfg, &ScanTally::default())
}
/// The body of [`run_index_report`], with the run's phase-A tally supplied by
/// the caller instead of created here.
///
/// The tally is per-invocation on purpose: it replaced a process-global counter
/// that every concurrent run in the process wrote to (#891). Every phase-A
/// route this function can take — the legacy `build_phase_a` scan and the
/// generated route's `project_reconcile_plan` — is handed this one tally, so
/// "files parsed by this run" is exactly what it holds.
fn run_index_report_tallied(cfg: IndexCfg, tally: &ScanTally) -> Result<(i32, Option<Value>)> {
run_index_report_inner(cfg, tally, None)
}
/// One pass of a `--watch` session.
///
/// Identical to [`run_index_report`] in every respect but one: the pass carries
/// a digest cache ([`watch::Pass`]) that lets a file the watcher knows did not
/// change skip its re-hash. Nothing else about the run changes — same journal,
/// same plan projection, same publish path, same summary — because a second
/// indexing path is exactly what a watcher must not be.
pub(crate) fn run_index_report_watched(
cfg: IndexCfg,
pass: &watch::Pass,
) -> Result<(i32, Option<Value>)> {
run_index_report_inner(cfg, &ScanTally::default(), Some(pass))
}
/// The argv a legacy `--no-graph` journal prints for its independent rebuild.
///
/// Following the printed advice must rebuild the same corpus the operator asked
/// for, so every flag that changes what gets indexed, or how it is analyzed, is
/// carried: the file selection (`--stub`, `--no-ignore`,
/// `--no-default-ignores`, symlink policy, `--max-file-gb`), the per-record
/// enrichment (`--no-semantic`, `--label`) and the dataset analyzer
/// (`--code-analyzer`). Only the destination changes (`--state-dir`,
/// `--prefix`). `cli::parse` reads this argv back in the tests below.
fn legacy_rebuild_argv(cfg: &IndexCfg, state_dir: &Path, prefix: &str) -> Vec<String> {
let mut argv = vec![
"xerj".to_owned(),
"autoindex".to_owned(),
cfg.root.to_string_lossy().into_owned(),
"--no-graph".to_owned(),
"--url".to_owned(),
cfg.url.clone(),
"--state-dir".to_owned(),
state_dir.to_string_lossy().into_owned(),
"--prefix".to_owned(),
prefix.to_owned(),
"--workers".to_owned(),
cfg.workers.to_string(),
"--pdf-workers".to_owned(),
cfg.pdf_workers.to_string(),
"--pdf-timeout-secs".to_owned(),
cfg.pdf_timeout_secs.to_string(),
"--bulk-mb".to_owned(),
cfg.bulk_mb.to_string(),
"--bulk-timeout-secs".to_owned(),
cfg.bulk_timeout_secs.to_string(),
"--snapshot-max-gb".to_owned(),
(cfg.snapshot_max_bytes >> 30).to_string(),
"--sample".to_owned(),
cfg.sample.to_string(),
];
// Emit the cap in the coarsest flag that expresses it exactly, so the
// printed rebuild command stays readable for the whole-GB common case yet
// round-trips a sub-GB cap (#1233) losslessly. `cli::parse` reads any of
// the three back into the same `max_file_bytes`.
const MB: u64 = 1 << 20;
if cfg.max_file_bytes.is_multiple_of(GB) {
argv.push("--max-file-gb".to_owned());
argv.push((cfg.max_file_bytes / GB).to_string());
} else if cfg.max_file_bytes.is_multiple_of(MB) {
argv.push("--max-file-mb".to_owned());
argv.push((cfg.max_file_bytes / MB).to_string());
} else {
argv.push("--max-file-bytes".to_owned());
argv.push(cfg.max_file_bytes.to_string());
}
if cfg.no_semantic {
argv.push("--no-semantic".to_owned());
}
if let Some(bytes) = cfg.max_index_bytes {
argv.push("--max-index-size".to_owned());
argv.push(bytes.to_string());
}
if let Some(plan) = &cfg.budget_plan {
argv.push("--plan".to_owned());
argv.push(plan.clone());
}
if cfg.drop_indexed {
argv.push("--drop-indexed".to_owned());
}
if cfg.follow_symlinks {
argv.push("--follow-symlinks".to_owned());
}
if cfg.follow_symlinks_outside_root {
argv.push("--follow-symlinks-outside-root".to_owned());
}
for glob in &cfg.stub_globs {
argv.push("--stub".to_owned());
argv.push(glob.clone());
}
if !cfg.ignore.enabled {
argv.push("--no-ignore".to_owned());
} else if !cfg.ignore.defaults {
argv.push("--no-default-ignores".to_owned());
}
if let Some(label) = &cfg.label {
argv.push("--label".to_owned());
argv.push(label.to_string_lossy().into_owned());
}
if cfg.code_analyzer == infer::CodeAnalyzer::Code {
argv.push("--code-analyzer".to_owned());
argv.push(infer::CODE_TEXT_ANALYZER.to_owned());
}
argv
}
/// Run documents in the shared catalog whose `prefix` term-matches.
///
/// A missing catalog is an empty list: the first index of a node has nothing
/// to collide with. Any other search failure is returned — skipping the
/// check on a 401 or a 500 would let the overwrite this guard exists to stop
/// proceed. The caller re-checks the prefix exactly; a legacy analyzed
/// `prefix` field can over-return sibling corpora.
fn catalog_runs(es: &Es) -> Result<Vec<Value>> {
let body = json!({
"size": 500,
"query": {"bool": {"filter": [
{"term": {"doc_kind": "run"}}
]}}
});
let Some(page) = es.search_present(catalog::CATALOG_INDEX, &body)? else {
return Ok(Vec::new());
};
Ok(page
.pointer("/hits/hits")
.and_then(Value::as_array)
.map(|hits| {
hits.iter()
.filter_map(|hit| hit.get("_source").cloned())
.collect()
})
.unwrap_or_default())
}
/// A dataset's time bounds from two size-1 searches sorted on its time field.
///
/// #2427: this used to be one `size:0` search with `min`/`max` aggs. Neither
/// has a columnar fast path, so the node deep-cloned every document into
/// owned values first ("aggregation corpus materialisation", ~2 KB a doc
/// against `limits.max_query_memory_mb`). A 393 k-record dataset priced at
/// 768 MB against the 512 MB default, the node answered 429, and the client
/// re-asked for its full 600 s patience before the run moved on without the
/// bounds. A sort reads doc values and clones nothing — the same shape the
/// generation read-back has used since #1183.
fn dataset_time_range(
es: &Es,
index: &str,
field: &str,
) -> Result<(Option<String>, Option<String>)> {
let bound = |order: &str| -> Result<Option<String>> {
let body = json!({
"size": 1,
"query": {"exists": {"field": field}},
"sort": [{field: {"order": order}}],
"_source": [field]
});
let v = es.search(index, &body)?;
let hit = match v.pointer("/hits/hits/0") {
Some(hit) => hit,
None => return Ok(None),
};
// The stored value first, exactly like the generation read-back
// (`sync_executor::extreme_time`); the sort key (epoch ms for a
// date) only when `_source` lacks the field.
let from_source = hit
.pointer("/_source")
.and_then(|src| src.get(field))
.and_then(|v| match v {
Value::String(s) => Some(s.clone()),
Value::Number(n) => n.as_i64().map(xerj_common::schema::epoch_ms_to_iso8601_utc),
_ => None,
});
Ok(from_source.or_else(|| {
hit.pointer("/sort/0")
.and_then(Value::as_i64)
.map(xerj_common::schema::epoch_ms_to_iso8601_utc)
}))
};
Ok((bound("asc")?, bound("desc")?))
}
fn run_index_report_inner(
mut cfg: IndexCfg,
tally: &ScanTally,
watch: Option<&watch::Pass>,
) -> Result<(i32, Option<Value>)> {
// The very first statement of the function, deliberately: `started` must
// be when this invocation began, not when its summary was built.
let invocation_started = chrono::Utc::now();
// Fix the phase-A pool width BEFORE anything parallel starts: hashing and
// sniffing are the CPU-bound phase, and they used to take every core no
// matter what the caller asked for (#240 §2).
pool::configure(cfg.scan_workers);
// What phase A is *actually* running on. `pool::configure` is first-call-wins
// (rayon pools cannot be resized), so in a process that already indexed once
// — `xerj-server`'s brain endpoint does exactly that — the installed width
// can differ from what this run's plan asked for. Progress must state the
// number the policy got, not the one it requested (#240 + #241).
let scan_threads = pool::width();
extract::pdf::configure_workers(cfg.pdf_workers);
extract::pdf::configure_timeout(cfg.pdf_timeout_secs);
// A mailbox is one file on one Phase-B worker; inside it, messages are
// parsed on a pool of this width, shared by every mailbox in the run.
extract::mbox::configure_parallelism(cfg.workers);
let t0 = Instant::now();
// The progress surface and its ticker are the FIRST things built: every
// later phase reports through them, and the ticker guarantees the stream
// closes with a terminal line even if this function bails (#241). The
// resource plan is announced through the same surface rather than through a
// bare `eprintln!`, so `--quiet` / `--progress none` still means silent and
// `--progress json` still means one machine-readable stream (#240 + #241).
let surface = progress::detect(cfg.progress);
let pr = Progress::new(
surface,
cfg.progress_interval
.unwrap_or_else(|| progress::default_interval(surface)),
);
let ticker = pr.spawn_ticker();
// #768: the wrong-node warning is a safety signal, not routine progress, so
// it goes out FIRST and through `pr.warn` — which, unlike `pr.note`, is not
// silenced by `--quiet`/`Surface::Silent` (a "you may be writing to the
// wrong node" message must still reach the operator) yet stays a well-formed
// event on `--progress json` instead of a bare line. It is emitted before
// any endpoint I/O below, and mirrored into the --json result. map/status
// deliver the same note; they have no progress surface, so they `eprintln`.
if let Some(note) = &cfg.xerj_url_note {
pr.warn(&format!("autoindex: {note}"));
}
// #1845: a rewritten --prefix is said out loud, next to the other
// "this run is not quite what you typed" warning.
if let Some(note) = &cfg.prefix_note {
pr.warn(&format!("autoindex: {note}"));
}
// One throughput meter for the whole run: both phase-A routes (the legacy
// scan and the generated route's `project_reconcile_plan`) feed it, so the
// estimate is built from whatever this invocation actually parsed.
let scan_meter = estimate::Meter::new();
// What this run decided to take from the machine, before it takes it.
pr.note(&format!(
"autoindex: {} scan threads, {} index workers, {} pdf workers, --bulk-mb {} [{}]",
scan_threads,
cfg.workers,
cfg.pdf_workers,
cfg.bulk_mb,
xerj_common::resource::describe(),
));
for note in &cfg.resource_notes {
pr.note(&format!("autoindex: {note}"));
}
pr.note(&format!(
"autoindex: bulk HTTP request timeout: {}s",
cfg.bulk_timeout_secs
));
// The run's bulk load is admitted through one window `--workers` wide, so
// a 429 can shrink what the run offers instead of only delaying it
// (#240 §8). Enabled here and nowhere else: probes have nothing to
// throttle. Its shrink/recover announcements go to stderr, which the
// progress surface owns — so they are emitted exactly when that surface is
// enabled, not merely when `--quiet` is absent.
// #2057: a digit-leading prefix is rejected by the server only when the
// index is created, which used to be after the hash. The name is wrong
// before any walk, and it does not need the node.
if let Some(err) = dataset::index_prefix_error(&cfg.prefix) {
anyhow::bail!("{err}");
}
let es = Es::with_bulk_timeout(&cfg.url, cfg.api_key.clone(), cfg.bulk_timeout_secs)?
.with_bulk_concurrency(cfg.workers, pr.enabled());
// #1102: ping's raw context is honest but teaches a first-time user
// nothing — autoindex is the onboarding verb, so the no-node case here
// gets the same recipe `xerj def` already prints: start one, or aim at
// an existing node. `xerj autoindex map` uses the same wording.
if let Err(e) = es.ping() {
anyhow::bail!("{}", node_ping_failure(&cfg.url, &e));
}
// #2077: the flood-stage write block used to surface only when the first
// bulk was rejected, after walk/hash/scan/prepare (~10 minutes on the
// report). The watermark is the node's data volume, which may not be
// this client's disk, so the probe reads the node. A node that does not
// report the threshold is left alone — a hard-coded 95 would refuse the
// `limits.disk_flood_stage_percent = 99` workaround and a disabled
// watermark. Nothing has been walked or written yet, so bailing here
// leaves no journal and no remote mutation.
// One allocation read (#2077). The refusal bails before the walk. The
// parsed volume is what the budget gate, after the walk and still before
// the hash, compares the estimated index against. A second GET is not made.
// A dry run writes nothing, so a full volume is not a reason to refuse
// it: the plan (and its size) is exactly what a user short on disk needs.
let disk = flood::probe(&es);
if !cfg.dry_run {
if let Some(message) = disk.refusal {
anyhow::bail!("{message}");
}
}
let disk_volume = disk.volume;
// `--label <question-set>` (#1062): every record's payload goes through
// the node's /_decide at ingest and the answers are stamped on as
// label/label_p fields. Loaded and validated HERE, before the walk: a
// bad question set must abort the run before any document is indexed,
// not halfway through it. The Labeler shares the bulk client's base URL
// and auth; its calls are separate one-shot requests (decide is not a
// bulk API) and are counted for the run report. No idle cost exists by
// construction: with the flag absent this is None and no code runs.
let labeler =
match &cfg.label {
Some(path) => {
let set = label::QuestionSet::load(path)?;
pr.note(&format!(
"autoindex: --label: {} question(s) through POST /_decide (index {:?}, k {}) — \
one call per noul, one per option for a choice, per record; p is the raw \
decide confidence, uncalibrated (#1063)",
set.questions.len(),
set.decide_index,
set.k.map(|k| k.to_string()).unwrap_or_else(|| "default".into())
));
Some(label::Labeler::new(es.clone(), set))
}
None => None,
};
let stub_matcher = GlobMatcher::compile(&cfg.stub_globs, "--stub")?;
// An `s3://`/`r2://` positional argument becomes a local mirror directory
// here, before any state is opened: `cfg.root` is rewritten to that mirror,
// so every later phase — walk, hash, plan, journal, reconcile — is the code
// that has always run over a folder. `None` means the argument was a folder
// and nothing at all changes. See `crate::objsource`.
let object_run = objsource::prepare(&mut cfg)?;
// The run's identity. For an object source it is the bucket URL rather than
// the mirror path: the mirror is a cache whose location may move (it follows
// --state-dir), and hashing a cache path into the state key would start a
// second index — re-downloading every object — the first time it did.
let root_str = match &object_run {
Some(run) => run.identity.clone(),
None => cfg
.root
.canonicalize()
.unwrap_or_else(|_| cfg.root.clone())
.to_string_lossy()
.to_string(),
};
let state_dir = cfg
.state_dir
.clone()
.unwrap_or_else(|| state::default_state_dir(&root_str, &cfg.url, &cfg.prefix));
// Same --prefix on a different folder overwrites catalog ids
// `ds:{prefix}:{slug}` and writes into `{prefix}-*` at finalize. The
// journals do not share a state dir (the default key includes the root),
// so nothing local notices a *new* folder. Refuse before preflight
// creates state, and before --dry-run walks the tree. --replace-prefix
// is the explicit opt-in; it prints the same facts and continues.
//
// A journal that already binds this state dir to this root, url, and
// prefix is a resume or an incremental re-run of the same folder,
// including one the local plan / `--fresh` gates are about to refuse.
// Those refusals promise no catalog search and no remote mutation. The
// only remote calls on that path are the readiness GET and the read-only
// flood-stage probe (#2077), so this guard must not search the catalog
// there. A different folder has no such journal and still hits the check.
let mut duplicate_prefixes: Vec<String> = Vec::new();
if !state::journal_continues_folder(&state_dir, &root_str, &cfg.url, &cfg.prefix) {
let runs = catalog_runs(&es)?;
let foreign_roots = catalog::foreign_prefix_roots(&runs, &cfg.prefix, &root_str);
if !foreign_roots.is_empty() {
let message = catalog::prefix_reuse_message(
&cfg.prefix,
&root_str,
&foreign_roots,
cfg.replace_prefix,
);
if cfg.replace_prefix {
// `warn` replaces newlines (they are not a safe display char), so
// each sentence is its own line. The refusal below keeps the
// newlines: it is an error, not a progress record.
for line in message.lines() {
pr.warn(line);
}
} else {
anyhow::bail!("{message}");
}
}
// #2078: the same folder under a second prefix writes a second copy
// and used to say nothing. This is a warning, not a refusal — the
// prefixes do not share catalog ids.
duplicate_prefixes = catalog::other_prefixes_for_root(&runs, &root_str, &cfg.prefix);
if !duplicate_prefixes.is_empty() {
pr.warn(&catalog::same_root_other_prefix_line(
&cfg.prefix,
&duplicate_prefixes,
));
}
}
// Acquire state authority before discovery as well as hashing. A waiter
// must never classify a path snapshot taken while another owner was
// publishing or replacing the durable plan.
let preflight =
state::Journal::preflight(&state_dir, &root_str, &cfg.url, &cfg.prefix, cfg.fresh)?;
let genesis_recovery = preflight
.committed_manifest
.as_ref()
.is_some_and(|manifest| manifest.generation == 0 && manifest.groups.is_empty());
// `--fresh` must be refused before the journal is opened, and only for a
// durable *generation*. `open_after_preflight` deletes journal.ndjson
// whenever `fresh` is set, and the `gc_snapshots` call that follows every
// open then sees an empty protected set and removes every sealed snapshot
// directory — so nothing evaluated later can save a generated corpus.
//
// Scope matters here. A legacy (non-generated) journal keeps `--fresh`
// exactly as it has always behaved: it is a crash-resume boundary, not a
// generation, and `xerj brain` documents and depends on `--fresh` to
// re-index a folder whose server-side data was wiped (brain.rs). Only
// generated state — a pending sync, or a committed manifest past genesis —
// has authority that `--fresh` would silently destroy.
let blocking_generation = if !cfg.fresh {
None
} else if preflight.pending_sync.is_some() {
Some(None)
} else {
preflight
.committed_manifest
.as_ref()
.filter(|_| !genesis_recovery)
.map(|manifest| Some(manifest.generation))
};
if let Some(committed_generation) = blocking_generation {
return Err(UnsafeFreshGenerationError {
committed_generation,
}
.into());
}
if let Some(reason) = preflight.unreadable_plan.as_deref() {
// Only reachable under --fresh; without it the preflight would have
// returned this as an error. It goes through the progress surface, not
// a raw eprintln!, so `--progress none` (which `--quiet` selects) stays
// silent and `--progress json` stays one parseable stream (#241).
pr.note(&format!(
"autoindex: --fresh: the durable resume plan in {} could not be read ({reason}); \
rebuilding it from the current folder. Documents published for files that are no \
longer present cannot be identified from an unreadable plan and are not deleted.",
state_dir.join("journal.ndjson").display()
));
}
// `--dry-run` has to be decided *before* the generated branches, not after
// them. Both of those branches publish and commit, and both return before
// control ever reaches the legacy `cfg.dry_run` check further down — so on
// any already-generated state directory the flag was accepted, ignored, and
// the destination mutated anyway. A projection-only flag that writes is
// worse than one that errors, so this branch is placed where nothing has
// been opened for write yet: the journal is still only preflighted, and
// `gc_snapshots` (which deletes unprotected snapshot directories) has not
// run.
if cfg.dry_run {
if let Some(pending) = &preflight.pending_sync {
println!("{}", serde_json::to_string_pretty(&pending.desired.plan)?);
// stdout is the RESULT, stderr is PROGRESS — so this explanation
// goes through the progress surface, never a bare `eprintln!`
// that `--progress none` could not silence and `--progress json`
// could not parse (#241).
pr.note(&format!(
"(dry run — nothing indexed; corpus generation {} is already sealed and pending \
replay from its own durable snapshot. Re-run without --dry-run to finish it.)",
pending.desired.generation
));
pr.finish(true, 0, "dry-run", &[]);
return Ok((0, None));
}
}
// A durable sync_begin owns the desired generation. Never rediscover and
// replan from a mutable source tree while that transaction is pending.
// Operation handlers are deliberately not enabled by this foundation
// slice; fail with the exact durable transaction rather than accidentally
// executing a different folder snapshot.
if preflight.pending_sync.is_some() {
// #585: a not-yet-committed generation carries the graph mode it was
// BEGUN in (`desired.execution.graph_enabled`). Resuming it under the
// other mode replays and COMMITS that generation on a mismatched
// authority — the #584 cross-path hazard, but for a pending generation
// the committed-manifest guard below never sees it because this branch
// returns first. Refuse before the journal is opened for write and
// before `gc_snapshots`, exactly the way #584 refuses the committed
// case: nothing is mutated.
if let Some(pending) = preflight.pending_sync.as_ref() {
if let Some(exec) = pending.desired.execution.as_ref() {
if exec.graph_enabled == cfg.no_graph {
anyhow::bail!(
"a generation is mid-commit (pending sync {}) begun {}; re-running it {} \
would resume and commit it under a different graph authority and mutate \
the destination. No remote mutation was attempted. Re-run {} to finish \
the pending generation, or rebuild with a new --state-dir and a new \
--prefix.",
pending.tx_id,
if exec.graph_enabled {
"with graph detection"
} else {
"with --no-graph"
},
if cfg.no_graph {
"with --no-graph"
} else {
"on the default graph path"
},
if exec.graph_enabled {
"on the default graph path"
} else {
"with --no-graph"
},
);
}
}
}
let mut journal = state::Journal::open_after_preflight(
preflight,
&root_str,
&cfg.url,
&cfg.prefix,
cfg.bulk_timeout_secs,
cfg.fresh,
)?;
sync_executor::gc_snapshots(&state_dir, &journal)?;
let pending = journal
.pending_sync
.as_ref()
.context("preflight reported a pending generation but authoritative replay did not")?
.clone();
pin_pending_embedding_identity(&es, &mut journal, &pending)?;
pr.phase("replay", 0, 0);
// #933: the durable replay window is the run's --workers, the same
// number that bounds bulk admission, so overlapped operations share
// one AIMD gate with the bulks they send.
let mut backend =
sync_executor::EsSyncBackend::new(&es, &state_dir, cfg.bulk_mb << 20, &pr)
.with_replay_workers(cfg.workers);
sync_executor::replay_pending_operations_reporting(
&state_dir,
&mut journal,
&mut backend,
&pr,
)?;
// Through the progress surface, never a bare `eprintln!`: stderr
// belongs to that surface, so `--progress none` stays silent and
// `--progress json` stays one parseable stream (#241).
pr.note("autoindex: resumed and committed pending corpus generation from durable source");
let summary = finish_generated_run(&es, &mut journal, &cfg)?;
let code = generated_exit_code(&summary);
finish_generated_progress(&pr, code, &summary, 0);
return Ok((code, Some(summary)));
}
// #585 case 2: a --no-graph generation's genesis bootstrap (sync_bootstrap
// committed, nothing beyond generation 0 committed yet — no pending_sync,
// handled above, either) has no execution identity of its own to compare
// a mode against: `validate_genesis` requires `execution: None`, so
// unlike the pending-sync case above, genesis cannot carry
// `graph_enabled`. But the durable record that produced it is
// unambiguous — `preflight.no_graph_genesis` is `true` only when a
// `sync_bootstrap` record actually replayed, and the only caller of
// `sync_bootstrap_genesis` is `begin_non_graph_generation`, only under
// `cfg.no_graph`. Continuing that generation on the default graph path
// would proceed down the legacy `write_plan`/commit path below over the
// same state directory — the #584 cross-path hazard, for the one
// generation-0 case the committed-manifest guard cannot see either
// (`genesis_recovery` exempts it there on purpose, for genuinely legacy
// empty-plan journals that were never no-graph).
//
// `--fresh` is deliberately exempt, the same way `blocking_generation`
// above exempts genesis recovery: nothing has been committed past
// genesis, so discarding and rebuilding in the requested mode is safe —
// which is why `--fresh` is one of the recovery routes the message names.
//
// #718: this refusal is intentionally NOT gated on `!cfg.dry_run`, unlike
// the pending-sync projection above. A dry run previews the run that WOULD
// execute, but this graph-path run would itself be refused, and there is no
// graph-path genesis projection to show (the `--no-graph` dry-run
// projection further below is `!genesis_recovery`-gated). Bailing is
// therefore the honest preview, and it precedes every write, so `--dry-run`
// reaches it before anything is mutated.
if genesis_recovery && preflight.no_graph_genesis && !cfg.no_graph && !cfg.fresh {
anyhow::bail!(
"a --no-graph generation's genesis bootstrap is pending in {} (nothing beyond \
generation 0 committed); continuing it on the default graph path would proceed \
under a different graph authority and mutate the destination. No remote mutation \
was attempted. Re-run with --no-graph to finish the pending generation, re-run with \
--fresh to discard generation 0 and rebuild on the graph path, or rebuild with a new \
--state-dir and a new --prefix.",
state_dir.join("journal.ndjson").display()
);
}
// The object-store transfer phase. It runs AFTER state authority has been
// acquired (two runs over one source must not fetch into the same mirror at
// once) and BEFORE the walk, which then sees ordinary local files.
let mut object_report: Option<objsource::MaterializeReport> = None;
if let Some(run) = &object_run {
pr.note(&format!(
"autoindex: object source {} — mirroring into {}",
run.identity,
run.mirror.display()
));
let mode = if cfg.dry_run {
objsource::MaterializeMode::PlanOnly
} else {
objsource::MaterializeMode::Fetch
};
let report = objsource::materialize(run, &pr, cfg.scan_workers, mode)?;
for line in report.summary_lines() {
pr.note(&format!("autoindex: {line}"));
}
// Not a `note`: what a run costs at the object store is the kind of fact
// an operator has to see even when they asked for quiet, because the
// mistake it prevents is a cron entry that spends a monthly allowance.
for line in report.cost_lines() {
pr.warn(&format!("autoindex: {line}"));
}
if cfg.dry_run && report.pending > 0 {
// stdout is the RESULT. A dry run over an object source that would
// have to transfer bytes stops here instead of transferring them.
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"source": run.identity,
"objects_listed": report.objects_listed,
"objects_admitted": report.admitted,
"objects_to_fetch": report.pending,
"bytes_to_fetch": report.pending_bytes,
"objects_already_local": report.unchanged,
"list_requests_class_a": report.list_requests,
"mirror": run.mirror.display().to_string(),
}))?
);
pr.note(
"(dry run — nothing downloaded and nothing indexed. A discovery plan needs the \
object bytes, and a preview must not pay for them: run without --dry-run to \
fetch and index, or re-run --dry-run once the mirror is current to get the \
plan projection for free.)",
);
pr.finish(
true,
0,
"dry-run-object-source",
&[
("objects", report.admitted),
("objects_to_fetch", report.pending),
("list_requests", report.list_requests),
],
);
return Ok((0, None));
}
object_report = Some(report);
}
// Totals are unknown until the walk returns, so this phase honestly
// reports `pct=unknown` and proves liveness with the clock alone.
pr.phase("walk", 0, 0);
let (discovered_files, ignore_report) = walk::walk_reporting_opts(
&cfg.root,
cfg.follow_symlinks,
cfg.follow_symlinks_outside_root,
cfg.ignore,
)?;
let (discovered_files, excluded) =
without_excluded_rels(discovered_files, &cfg.exclude_rels, &cfg.exclude)?;
if excluded > 0 {
let mut rules = cfg.exclude_rels.clone();
rules.extend(cfg.exclude.iter().map(|glob| format!("--exclude {glob}")));
pr.note(&format!(
"autoindex: left out {excluded} path(s) ({}) — not part of this index",
rules.join(", ")
));
}
let (discovered_files, data_files, data_bytes) = if cfg.skip_corpus_data {
without_corpus_data_files(discovered_files)
} else {
(discovered_files, 0, 0)
};
// #2058: a dataless File Provider placeholder (iCloud and other cloud
// volumes) has a directory entry but no local bytes. Hashing it blocks
// inside `read` until the download finishes, and the progress line used
// to name nothing. `stat` sees `SF_DATALESS` without downloading. On
// macOS those files are skipped, or carried from the previous digest when
// one exists so an evicted file is not treated as deleted. Every other
// target gets the walked list back unchanged and does not stat.
#[cfg(target_os = "macos")]
let dataless_split = dataless::split(
discovered_files,
&dataless::prior_digests(preflight.plan.as_ref()),
);
#[cfg(not(target_os = "macos"))]
let dataless_split = dataless::Split::unchanged(discovered_files);
let mut discovered_files = dataless_split.files;
let dataless_skipped_files = dataless_split.skipped_files;
let dataless_skipped = dataless_skipped_files.len() as u64;
#[cfg(target_os = "macos")]
let dataless_carry = dataless_split.carry;
#[cfg(not(target_os = "macos"))]
let _ = dataless_split.carry;
if data_files > 0 {
let size = if data_bytes >= 1 << 20 {
format!("{:.1} MB", data_bytes as f64 / (1u64 << 20) as f64)
} else {
format!("{} KB", data_bytes.div_ceil(1024))
};
pr.note(&format!(
"autoindex: left out {data_files} data file(s) ({size}): CSV/HDF/simulation output \
is data, not reference code — pass --include-data to index them"
));
}
let mut discovered_bytes: u64 = discovered_files.iter().map(|f| f.size).sum();
pr.note(&format!(
"autoindex: {} files ({} MB) under {}",
discovered_files.len(),
discovered_bytes / (1 << 20),
root_str
));
if let Some(line) = dataless::skip_note(dataless_skipped) {
pr.note(&format!("autoindex: {line}"));
}
#[cfg(target_os = "macos")]
if let Some(line) = dataless::carry_note(dataless_carry.len() as u64) {
pr.note(&format!("autoindex: {line}"));
}
// "Where did my files go?" is answered here, on every run — the rules are
// named, not just the totals (#276).
for line in ignore_report.summary_lines() {
pr.note(&format!("autoindex: {line}"));
}
// `--walk-only` (#1912) is the map of a tree that has not been indexed yet.
// The walk above is the same one `--dry-run` runs, and `summary_lines` is
// the same ignore report. Hashing is the next step, and it reads every
// admitted byte — on a large drive that is the day-long part. Return
// before it. `walk_only` implies `dry_run`, so a pending generation or an
// object download already returned above without writing.
if cfg.walk_only {
let summary = walk::summarise_walk_only(&root_str, &discovered_files, &ignore_report);
if cfg.json {
println!("{}", serde_json::to_string_pretty(&summary)?);
} else {
print!("{}", summary.render());
}
pr.note(
"(walk-only — stopped before hashing; file contents were not hashed and nothing was indexed)",
);
let mut walk_done = vec![
("files", summary.files),
("bytes", summary.bytes),
("ignored_files", ignore_report.files_skipped),
("ignored_dirs", ignore_report.dirs_pruned),
(
"ignored_files_in_pruned_dirs",
ignore_report.files_inside_pruned_dirs,
),
];
if dataless_skipped > 0 {
walk_done.push(("skipped_dataless", dataless_skipped));
}
pr.finish_with_flags(
true,
0,
"walk-only",
&walk_done,
&[(
"ignored_files_in_pruned_dirs_exact",
ignore_report.files_inside_pruned_dirs_is_exact(),
)],
);
return Ok((0, None));
}
// An empty folder is only "nothing to do" when there is also no durable
// state: with a journal present, zero files is a deletion of the whole
// corpus and has to be reconciled, not shrugged off.
if discovered_files.is_empty() && !preflight.journal_exists {
if dataless_skipped > 0 {
println!(
"no indexable files under {root_str} ({dataless_skipped} dataless placeholder{} \
skipped)",
if dataless_skipped == 1 { "" } else { "s" }
);
pr.finish(
true,
0,
"no-files",
&[("skipped_dataless", dataless_skipped)],
);
} else {
println!("no files found under {root_str}");
if let Some(hint) = skipped_links_hint(&ignore_report) {
println!("{hint}");
}
pr.finish(true, 0, "no-files", &[]);
}
return Ok((0, None));
}
// Count, estimate, and — when the default plan does not fit the disk
// budget — stop before hashing. The volume is the allocation row read
// above; this does not probe the disk again.
{
let assessment = budget::assess(&budget::Request {
root: &root_str,
files: &discovered_files,
volume: disk_volume,
max_index_bytes: cfg.max_index_bytes,
no_semantic: cfg.no_semantic,
plan: cfg.budget_plan.as_deref(),
approve: cfg.approve,
duplicate_prefixes: &duplicate_prefixes,
memory_budget: xerj_common::resource::memory_safe_zone_bytes(),
});
for line in &assessment.lines {
if assessment.needs_choice {
pr.note(line);
}
}
let choice = if assessment.needs_choice {
let blocked = gate::detect_prompt_block(pr.enabled());
if let Some(why) = blocked {
pr.note(&format!(
"budget: {}. Re-run with --plan <name> or --yes",
why.explain()
));
budget::Choice::Absent
} else {
budget::read_choice(
&mut std::io::stdin().lock(),
&assessment.plan_names,
|line| {
pr.note(line);
},
)
}
} else {
budget::Choice::Absent
};
match budget::resolve(&assessment, choice) {
budget::Outcome::Stop { code, body } => {
if !body.is_null() {
println!("{}", serde_json::to_string(&body)?);
}
if code == 0 {
pr.note("gate: --approve cancel — nothing was indexed");
pr.finish(true, 0, "cancelled", &[]);
} else {
pr.finish(false, code, "needs-decision", &[]);
}
return Ok((code, None));
}
budget::Outcome::Continue {
keep,
no_semantic,
note,
plan_name,
} => {
if no_semantic {
cfg.no_semantic = true;
}
// A reduced plan filters the walk before hashing and before
// either reconcile. Files it leaves out are then absent from
// the inventory: the `--no-graph` generation emits Delete for
// their groups, and the graph path classifies them as
// exclusions and sweeps their documents. Both are silent
// deletions of data that is still in the folder. Stop and
// list them unless `--drop-indexed` is the explicit yes.
// `--plan` and `--yes` choose what to index; they do not
// agree to delete what is already indexed.
if let Some(keep_rels) = keep.as_ref() {
let mut plans: Vec<&Plan> = Vec::new();
if let Some(manifest) = preflight.committed_manifest.as_ref() {
plans.push(&manifest.plan);
}
if let Some(plan) = preflight.plan.as_ref() {
plans.push(plan);
}
let name = plan_name.as_deref().unwrap_or("reduced");
if let Some(body) =
budget::removal_decision(name, &plans, &discovered_files, keep_rels)
{
if !cfg.drop_indexed {
println!("{}", serde_json::to_string(&body)?);
pr.note(&format!(
"autoindex: {}",
body["accept"]
.as_str()
.unwrap_or("a reduced plan would delete already-indexed files")
));
pr.finish(false, gate::EXIT_NEEDS_DECISION, "needs-decision", &[]);
return Ok((gate::EXIT_NEEDS_DECISION, None));
}
pr.note(&format!(
"autoindex: --drop-indexed: removing {} already-indexed file(s) this \
plan leaves out",
body["would_remove_total"].as_u64().unwrap_or(0)
));
} else if cfg.drop_indexed {
pr.note(
"autoindex: --drop-indexed: this plan leaves out no already-indexed \
file",
);
}
} else if cfg.drop_indexed {
pr.note(
"autoindex: --drop-indexed confirms removal of files a reduced plan \
leaves out, and this run keeps every walked file",
);
}
if let Some(keep) = keep {
let keep: std::collections::HashSet<String> = keep.into_iter().collect();
let before = discovered_files.len();
discovered_files.retain(|f| keep.contains(&f.rel));
discovered_bytes = discovered_files.iter().map(|f| f.size).sum();
pr.note(&format!(
"autoindex: budget plan kept {} of {before} walked files",
discovered_files.len()
));
}
if !note.is_empty() {
pr.note(&format!("autoindex: {note}"));
}
}
}
}
// Full hashing on every run is deliberate: size/mtime/inode fingerprints
// cannot prove byte identity across all supported local and network
// filesystems. A metadata-only shortcut could leave stale live documents
// forever after a same-size rewrite with restored or stale timestamps.
// Hashing reads every byte of the corpus. On a large tree it is minutes of
// real work, and before #241 it was minutes with no output at all.
// Tests delete a file in the gap the walk already closed (#2352).
before_hash_hook(&state_dir);
let mut inventory = match watch {
// A plain run hashes the whole corpus, every time, on purpose: see
// `content::resolve_reporting`.
None => {
// macOS names each file for the duration of its read and does not
// read a dataless placeholder (#2058). Other targets hash the way
// they always have: every admitted byte, no in-flight registration
// on this phase.
#[cfg(target_os = "macos")]
{
let (hash_files, hash_bytes) =
hash_phase_totals(&discovered_files, &dataless_carry, discovered_bytes);
pr.phase("hash", hash_files, hash_bytes);
content::resolve_reporting_carried(
discovered_files,
&|entry| dataless_carry.get(&entry.rel_id).cloned(),
&|_, _, _| {},
&|bytes| pr.item_done(bytes),
Some(pr.as_ref()),
)?
}
#[cfg(not(target_os = "macos"))]
{
pr.phase("hash", discovered_files.len() as u64, discovered_bytes);
content::resolve_reporting(discovered_files, &|bytes| pr.item_done(bytes))?
}
}
// A `--watch` pass hashes what the watcher could not prove unchanged.
// The phase's totals are the files this pass will actually read, so the
// percent and the ETA describe the work being done rather than the work
// a full run would have done.
Some(pass) => {
let plan = pass.plan(&discovered_files);
#[cfg(target_os = "macos")]
let (hash_files, hash_bytes) =
watch_hash_totals(&plan, &discovered_files, &dataless_carry);
#[cfg(not(target_os = "macos"))]
let (hash_files, hash_bytes) = (plan.hash_files, plan.hash_bytes);
let (carried_files, carried_bytes) = (plan.carried_files, plan.carried_bytes);
pr.phase("hash", hash_files, hash_bytes);
pr.note(&format!(
"autoindex: --watch: re-hashing {} file(s) ({} MB); {carried_files} file(s) \
({} MB) carried from the previous pass",
hash_files,
hash_bytes >> 20,
carried_bytes >> 20,
));
let inventory = content::resolve_reporting_carried(
discovered_files,
&|entry| {
#[cfg(target_os = "macos")]
if let Some(digest) = dataless_carry.get(&entry.rel_id) {
return Some(digest.clone());
}
plan.carried(entry)
},
&|entry, digest, fresh| plan.observe(entry, digest, fresh),
&|bytes| pr.item_done(bytes),
#[cfg(target_os = "macos")]
Some(pr.as_ref()),
#[cfg(not(target_os = "macos"))]
None,
)?;
pass.commit(plan);
inventory
}
};
// A locked file that already has a committed digest stays in the inventory
// on `--no-graph`, so the reconcile keeps the previous generation instead
// of deleting it. The graph path must not reinstate: phase A would sniff
// the locked file and junk it under its content key (#2352).
if cfg.no_graph {
if let Some(manifest) = preflight.committed_manifest.as_ref() {
let kept = carry_locked_priors(&mut inventory, &manifest.plan);
note_kept_locked(&pr, &kept);
}
}
note_unreadable(&pr, &inventory.unreadable);
if cfg.no_graph && preflight.committed_manifest.is_some() && !genesis_recovery {
if cfg.dry_run {
let base = preflight
.committed_manifest
.as_ref()
.context("branch guard proved a committed manifest")?;
// #2684: preview the refusal the real run below would make, rather
// than a plan it will not commit.
refuse_changed_no_graph_options(base, &cfg, &root_str)?;
let mut plan = project_reconcile_plan(
&inventory,
&base.plan,
&cfg,
&state_dir,
&pr,
&scan_meter,
tally,
)?;
record_unreadable_skips(&mut plan, &inventory.unreadable);
refuse_changed_planned_execution(&es, base, &plan)?;
let unchanged = serde_json::to_value(&plan)? == serde_json::to_value(&base.plan)?;
let sizes = inventory_size_map(&inventory);
let changed_bytes = if unchanged {
0
} else {
neural_cost::changed_semantic_source_bytes(&base.plan.files, &plan, &sizes)
};
note_neural_ingest_cost(
&es,
changed_bytes,
neural_cost::SourceBytes::SemanticSource,
&pr,
);
println!("{}", serde_json::to_string_pretty(&plan)?);
// stdout is the RESULT, stderr is PROGRESS: the projection above is
// the result, this explanation is progress and goes out through the
// surface that `--progress none` silences (#241).
pr.note(&format!(
"(dry run — nothing indexed; {})",
if unchanged {
format!(
"committed generation {} already describes this folder",
base.generation
)
} else {
format!(
"this is the plan a real run would commit as generation {}",
base.generation + 1
)
}
));
// `ignored_files_in_pruned_dirs` is budget-capped, so the flag
// saying whether it is a total or a floor travels with it (#279).
let mut dry_done = vec![
("files", inventory.files.len() as u64),
("ignored_files", ignore_report.files_skipped),
("ignored_dirs", ignore_report.dirs_pruned),
(
"ignored_files_in_pruned_dirs",
ignore_report.files_inside_pruned_dirs,
),
];
if dataless_skipped > 0 {
dry_done.push(("skipped_dataless", dataless_skipped));
}
pr.finish_with_flags(
true,
0,
"dry-run",
&dry_done,
&[(
"ignored_files_in_pruned_dirs_exact",
ignore_report.files_inside_pruned_dirs_is_exact(),
)],
);
return Ok((0, None));
}
let mut journal = state::Journal::open_after_preflight(
preflight,
&root_str,
&cfg.url,
&cfg.prefix,
cfg.bulk_timeout_secs,
cfg.fresh,
)?;
sync_executor::gc_snapshots(&state_dir, &journal)?;
let base = journal
.committed_manifest
.as_ref()
.context("generated journal lost its committed manifest")?
.clone();
// #2577: refuse a changed option before reconciling or sealing
// anything. Both arms below require these fields to match; the
// changed arm used to find out only after copying the corpus, as a
// false "state not internally consistent" error. The `--dry-run`
// preview above runs the same two checks (#2684).
refuse_changed_no_graph_options(&base, &cfg, &root_str)?;
let mut plan = project_reconcile_plan(
&inventory,
&base.plan,
&cfg,
&state_dir,
&pr,
&scan_meter,
tally,
)?;
record_unreadable_skips(&mut plan, &inventory.unreadable);
refuse_changed_planned_execution(&es, &base, &plan)?;
// Say out loud that the decision gate is not on this route. It is an
// incremental reconcile of an already-committed generation, so the work
// is the *changed* set and is published from a sealed snapshot rather
// than through the phase-B queue the estimate prices. Accepting
// `--max-minutes` here and quietly not applying it would be the
// accepted-and-ignored class from #204 — so the run states the
// exemption instead of leaving the caller to discover it.
if cfg.max_minutes > 0 && cfg.approve.is_none() {
pr.note(&format!(
"gate: --max-minutes {} does not apply to an incremental reconcile of committed \
generation {} — only files that changed are processed, and they are published \
from a sealed snapshot rather than through the queue the estimate prices. Use \
--dry-run to see the projected plan before committing to it",
cfg.max_minutes, base.generation
));
}
if serde_json::to_value(&plan)? == serde_json::to_value(&base.plan)? {
let summary = finish_generated_run(&es, &mut journal, &cfg)?;
let code = generated_exit_code(&summary);
finish_generated_progress(&pr, code, &summary, dataless_skipped);
return Ok((code, Some(summary)));
}
let sizes = inventory_size_map(&inventory);
let changed_bytes =
neural_cost::changed_semantic_source_bytes(&base.plan.files, &plan, &sizes);
note_neural_ingest_cost(
&es,
changed_bytes,
neural_cost::SourceBytes::SemanticSource,
&pr,
);
begin_non_graph_generation(
&es,
&mut journal,
&state_dir,
&cfg,
&root_str,
&inventory,
&pr,
plan,
labeler.as_ref(),
)?;
// #933: the durable replay window is the run's --workers, the same
// number that bounds bulk admission, so overlapped operations share
// one AIMD gate with the bulks they send.
let mut backend =
sync_executor::EsSyncBackend::new(&es, &state_dir, cfg.bulk_mb << 20, &pr)
.with_replay_workers(cfg.workers);
sync_executor::replay_pending_operations_reporting(
&state_dir,
&mut journal,
&mut backend,
&pr,
)?;
let summary = finish_generated_run(&es, &mut journal, &cfg)?;
let code = generated_exit_code(&summary);
finish_generated_progress(&pr, code, &summary, dataless_skipped);
return Ok((code, Some(summary)));
}
if cfg.no_graph && preflight.plan.is_some() && !genesis_recovery {
let replacement_state = state_dir.with_extension("generation-v1");
let replacement_prefix = format!("{}-generation-v1", cfg.prefix);
let reasons = if preflight.legacy_migration_reasons.is_empty() {
"legacy journal has no complete generated-manifest authority".to_owned()
} else {
preflight.legacy_migration_reasons.join("; ")
};
let rebuild_argv = legacy_rebuild_argv(&cfg, &replacement_state, &replacement_prefix);
anyhow::bail!(
"this state directory contains a legacy nonempty plan that cannot become generation \
authority: {reasons}. Start an independent rebuild using this argv JSON (no shell \
quoting required): {:?}. Keep XERJ_API_KEY set when the endpoint requires \
authentication",
rebuild_argv
);
}
// #490: a committed generation manifest is graph-disabled by construction
// (`sync::validate_manifest` requires `!graph_enabled` for every incremental
// generation), and the `--no-graph`/committed re-run above already returned.
// So reaching here with a committed manifest on the default *graph* path
// means the corpus was built `--no-graph` and is being re-run with graph
// detection on. Left to proceed it reconciles the no-graph plan on the graph
// path and mutates the destination — publishing new documents and writing a
// legacy plan record over the committed manifest — before the mismatch ever
// surfaces (as an opaque `legacy plan write cannot follow a committed
// generated manifest`), and then leaves `--fresh` refused. Refuse it here,
// before the journal is opened for write and before `gc_snapshots`, exactly
// the way the graph→no-graph direction above is refused: nothing is mutated.
if !cfg.no_graph && !genesis_recovery {
if let Some(committed) = preflight.committed_manifest.as_ref() {
anyhow::bail!(
"this corpus was indexed with --no-graph (committed generation {}); re-running \
it on the default graph path would reconcile two different authorities and \
mutate the destination. No remote mutation was attempted. Re-run with \
--no-graph to continue the committed corpus incrementally, or rebuild with a \
new --state-dir and a new --prefix.",
committed.generation
);
}
}
// #2314: deletions are swept before the journal opens, so `--fresh` (which
// deletes `journal.ndjson` inside `open_after_preflight`) still has the
// frozen plan to name the indices and keys. `deleted_file_keys` is then
// dropped from the resumed plan so the second gate does not see them.
let mut swept_membership = false;
let mut deleted_file_keys: HashSet<String> = HashSet::new();
// Excluded files intentionally lose their live documents but retain plan
// identity for future inclusion. They are not missing-write evidence.
let mut excluded_file_keys: HashSet<String> = HashSet::new();
if let Some(prior_plan) = preflight.plan.as_ref() {
let comparison_keys = if cfg.fresh {
inventory.keys.clone()
} else {
// Ordinary resume preserves planned-key identity for supported
// same-path replacement and legacy plans.
select_resume_plan_keys(
&inventory.files,
&inventory.keys,
prior_plan,
&state_dir.join("journal.ndjson"),
)?
.into_iter()
.zip(inventory.keys.iter())
.map(|(planned, current)| planned.unwrap_or_else(|| current.clone()))
.collect()
};
// #2314: a file that left the folder used to refuse the rerun, and
// `--fresh` with it, because discarding the journal does not delete
// documents already published. Sweep them here, with the frozen plan
// still in hand, the same way an exclusion is swept. `--dry-run`
// names them and does not mutate.
let still_present = files_still_present(&dataless_skipped_files, &inventory.unreadable);
let delta = inventory_delta(
&cfg.root,
&inventory.files,
&comparison_keys,
prior_plan,
&still_present,
);
if !delta.deleted_content_groups.is_empty() {
deleted_file_keys.extend(
delta
.deleted_content_groups
.iter()
.map(|entry| entry.file_key.clone()),
);
let count = delta.deleted_content_groups.len();
let paths = deleted_group_list(&delta.deleted_content_groups);
if cfg.dry_run {
pr.note(&format!(
"autoindex: {count} file(s) indexed under this resume plan no longer exist in \
the folder ({paths}); a real run removes their documents"
));
} else {
let edges_index = graph_edges_index(&cfg);
sweep_excluded_groups(
&es,
&cfg.prefix,
prior_plan,
&delta.deleted_content_groups,
edges_index.as_deref(),
chrono::Utc::now().timestamp_millis(),
)
.context("sweep deleted content groups")?;
swept_membership = true;
pr.note(&format!(
"autoindex: removed documents for {count} file(s) that no longer exist in the \
folder ({paths})"
));
}
}
// #589: a widened exclusion (file still on disk, newly ignored) is data
// the exclusion must remove — sweep the excluded group's documents and
// continue, rather than leaving them live in the destination. Never
// mutate under --dry-run.
if !delta.excluded_content_groups.is_empty() && !cfg.dry_run {
let edges_index = graph_edges_index(&cfg);
sweep_excluded_groups(
&es,
&cfg.prefix,
prior_plan,
&delta.excluded_content_groups,
edges_index.as_deref(),
chrono::Utc::now().timestamp_millis(),
)
.context("sweep newly-excluded content groups")?;
excluded_file_keys.extend(
delta
.excluded_content_groups
.iter()
.map(|entry| entry.file_key.clone()),
);
}
}
// #736: snapshot the PRIOR plan's anchor nodes HERE, before the journal is
// opened. `--fresh` deletes `journal.ndjson` inside `open_after_preflight`,
// taking the prior plan with it — and `--fresh` is precisely the path that
// supersedes a changed file's anchor, because it rebuilds every key from
// current content instead of mapping each file onto its planned key the way
// `select_resume_plan_keys` does on an ordinary resume. Only a run that can
// write edges has any to invalidate, so `--no-graph` (and an unusable brain
// name) pays nothing here.
let prior_anchor_nodes: Vec<(String, String)> = match preflight.plan.as_ref() {
Some(prior) if graph_edges_index(&cfg).is_some() => plan_anchor_nodes(prior),
_ => Vec::new(),
};
// Same moment as the anchor snapshot: `--fresh` drops the plan inside
// `open_after_preflight`, and phase B needs the previous key to notice
// that the documents it is about to supersede are not under the new one.
let (prior_by_rel, prior_by_path_id) = match preflight.plan.as_ref() {
Some(prior) => prior_publications(prior),
None => (HashMap::new(), HashMap::new()),
};
let mut journal = state::Journal::open_after_preflight(
preflight,
&root_str,
&cfg.url,
&cfg.prefix,
cfg.bulk_timeout_secs,
cfg.fresh,
)?;
sync_executor::gc_snapshots(&state_dir, &journal)?;
let resumed_with_plan = journal.plan.is_some() && !genesis_recovery;
if inventory.files.is_empty() && inventory.unreadable.is_empty() && !resumed_with_plan {
if dataless_skipped > 0 {
println!(
"no indexable files under {root_str} ({dataless_skipped} dataless placeholder{} \
skipped)",
if dataless_skipped == 1 { "" } else { "s" }
);
pr.finish(
true,
0,
"no-files",
&[("skipped_dataless", dataless_skipped)],
);
} else {
println!("no files found under {root_str}");
pr.finish(true, 0, "no-files", &[]);
}
return Ok((0, None));
}
let run_id = journal.run_id.clone();
if journal.resumed {
pr.note(&format!(
"resuming from journal {} ({} files already done)",
journal.path().display(),
journal.done.len()
));
}
let journal_path = journal.path().to_path_buf();
let mut content_changed = std::collections::HashSet::new();
let mut stale_alias_ids = Vec::new();
let mut alias_paths_to_replace = std::collections::HashSet::new();
// #905: the same aliases, under the pre-#416 id scheme that carries no
// corpus prefix. The path sweep below cannot attribute such a document from
// the document itself, so it attributes it by reconstructing the ids THIS
// corpus would have written. Kept in lockstep with `alias_paths_to_replace`
// — both are extended from `previous_aliases` here and from
// `inventory.duplicates` after this block.
let mut own_unprefixed_alias_ids: HashSet<String> = HashSet::new();
let mut plan_changed = journal.plan.is_none();
// #2314: drop completions for files swept before the journal opened, so
// the catalog write below does not advertise them again.
if journal.plan.is_some() {
let forgotten: Vec<String> = deleted_file_keys
.iter()
.filter(|key| journal.done.contains_key(key.as_str()))
.cloned()
.collect();
for key in forgotten {
journal.file_removed(&key)?;
}
}
// Preserve legacy document IDs while upgrading old plans with full digests.
// A later same-size/tail mutation is then detected and reindexed.
if let Some(plan) = &mut journal.plan {
if !deleted_file_keys.is_empty() {
let before = plan.files.len();
plan.files.retain(|key, _| !deleted_file_keys.contains(key));
plan.duplicate_files.retain(|alias| {
!deleted_file_keys.contains(&alias.file_key)
&& plan.files.contains_key(&alias.file_key)
});
if plan.files.len() != before {
recount_plan_file_counts(plan);
plan_changed = true;
}
}
let needs_alias_path_migration = !plan.alias_paths_indexed;
let previous_aliases = plan.duplicate_files.clone();
alias_paths_to_replace.extend(previous_aliases.iter().map(|alias| alias.rel.clone()));
own_unprefixed_alias_ids.extend(previous_aliases.iter().flat_map(|alias| {
catalog::unprefixed_duplicate_file_ids(&alias.file_key, &alias.rel, &alias.path_id)
}));
stale_alias_ids.extend(plan.duplicate_files.iter().map(|old| {
catalog::duplicate_file_id(&cfg.prefix, &old.file_key, &old.rel, &old.path_id)
}));
let selected_plan_keys =
select_resume_plan_keys(&inventory.files, &inventory.keys, plan, &journal_path)?;
for (index, planned_key) in selected_plan_keys.into_iter().enumerate() {
let file = &inventory.files[index];
if let Some(planned_key) = planned_key {
if !plan.files.contains_key(&planned_key) {
// The file was diverted off a planned key exclusively
// owned by another current file. Record the divergence in
// the durable plan so every resume deterministically skips
// this path instead of racing one ax_file key.
if !plan
.junk_files
.iter()
.any(|junk| junk.file_key == planned_key)
{
let owner = plan
.files
.get(&inventory.keys[index])
.map(|assignment| assignment.rel.as_str())
.unwrap_or("another file");
plan.junk_files.push(JunkFile {
file_key: planned_key.clone(),
rel: file.rel.clone(),
format: "unknown".into(),
status: "skipped".into(),
reason: format!(
"content resolves to planned key {} owned by {owner}; skipped to \
keep key ownership exclusive (remove one of the two files and \
rerun to index the survivor)",
inventory.keys[index]
),
bytes: file.size,
});
plan_changed = true;
}
inventory.keys[index] = planned_key;
continue;
}
let assignment = plan.files.get_mut(&planned_key).expect("planned key");
if assignment.rel != file.rel {
content_changed.insert(planned_key.clone());
plan_changed = true;
}
if assignment
.content_digest
.as_deref()
.is_some_and(|digest| digest != inventory.digests[index])
{
content_changed.insert(planned_key.clone());
plan_changed = true;
}
if assignment.path_id != file.rel_id
|| assignment.content_digest.as_deref()
!= Some(inventory.digests[index].as_str())
{
plan_changed = true;
}
assignment.rel = file.rel.clone();
assignment.path_id = file.rel_id.clone();
assignment.content_digest = Some(inventory.digests[index].clone());
inventory.keys[index] = planned_key;
}
}
let key_by_path: HashMap<&str, &str> = inventory
.files
.iter()
.zip(inventory.keys.iter())
.map(|(file, key)| (file.rel.as_str(), key.as_str()))
.collect();
for duplicate in &mut inventory.duplicates {
if let Some(key) = key_by_path.get(duplicate.duplicate_of.as_str()) {
duplicate.file_key = (*key).to_string();
}
}
let current_alias_ids: std::collections::HashSet<String> = inventory
.duplicates
.iter()
.map(|alias| {
catalog::duplicate_file_id(&cfg.prefix, &alias.file_key, &alias.rel, &alias.path_id)
})
.collect();
stale_alias_ids.retain(|id| !current_alias_ids.contains(id));
// The historical global flag cannot identify which live documents
// already carry ax_paths. Its one-time migration must rewrite every
// canonical key; ordinary alias changes remain scoped per key.
// A key whose entire duplicate group was deleted has no current file
// to republish; scheduling it would strand a pending replacement that
// every later run re-journals without ever committing.
let current_keys: std::collections::HashSet<&str> =
inventory.keys.iter().map(String::as_str).collect();
content_changed.extend(
alias_keys_to_reindex(
&previous_aliases,
&inventory.duplicates,
needs_alias_path_migration.then_some(inventory.keys.as_slice()),
)
.into_iter()
.filter(|key| current_keys.contains(key.as_str())),
);
if needs_alias_path_migration {
plan.alias_paths_indexed = true;
plan_changed = true;
}
if previous_aliases != inventory.duplicates {
plan_changed = true;
}
plan.duplicate_files = inventory.duplicates.clone();
if absorb_compatible_additions(plan, &inventory, &cfg, &state_dir, &pr, &scan_meter, tally)?
{
plan_changed = true;
}
}
alias_paths_to_replace.extend(inventory.duplicates.iter().map(|alias| alias.rel.clone()));
own_unprefixed_alias_ids.extend(inventory.duplicates.iter().flat_map(|alias| {
catalog::unprefixed_duplicate_file_ids(&alias.file_key, &alias.rel, &alias.path_id)
}));
let files = inventory.files.clone();
let keys = inventory.keys.clone();
let digests = inventory.digests.clone();
let duplicate_files = inventory.duplicates.clone();
let paths_discovered = files.len() + duplicate_files.len();
let planned_bytes: u64 = files.iter().map(|f| f.size).sum();
if !duplicate_files.is_empty() {
pr.note(&format!(
"autoindex: {} byte-identical duplicate path(s) will reuse canonical content",
duplicate_files.len()
));
for duplicate in duplicate_files.iter().take(REFUSAL_LIST_CAP) {
pr.note(&format!(
" duplicate: {} → {}",
duplicate.rel, duplicate.duplicate_of
));
}
let remaining = duplicate_files.len().saturating_sub(REFUSAL_LIST_CAP);
if remaining > 0 {
pr.note(&format!(" … and {remaining} more"));
}
}
// ── Phase A: inference (skipped when a frozen plan exists) ──────────
// Only what end-of-run correlation needs; the phase-A clusters (every
// field's full accumulator) are dropped as soon as the plan is built.
let mut key_stats: Option<correlate::KeyStats> = None;
let mut pdf_spools: Vec<Option<extract::pdf::ExtractionSpool>> =
(0..files.len()).map(|_| None).collect();
// Both worker widths come from the one resource policy (#240), and since
// that policy may set them apart, the spool's headroom is sized for the
// wider phase: phase-A scan threads are what hold artifact descriptors
// open, phase-B workers are what hold bulk buffers. Reserving for the
// larger of the two can only make this optional accelerator hand capacity
// back — never take headroom the run still needs.
//
// `--no-graph` is the exception, and it is a decision this rebase had to
// make between two landed changes. #248's artifact is a phase A→B
// accelerator, but every `--no-graph` route below returns from the
// generated path — which publishes from its own sealed snapshot and never
// reaches the legacy phase B. A retained artifact could therefore never be
// replayed, so admission is disabled instead of spooling gigabytes nothing
// will read. Nothing observable changes: the generated run document does
// not carry `pdf_extraction_reuse`.
let (pdf_spool_budget, pdf_spool_capacity_warning) = if cfg.no_graph {
(extract::pdf::ExtractionSpoolBudget::new(0, 0), None)
} else {
extract::pdf::ExtractionSpoolBudget::for_state_dir(
&state_dir,
cfg.workers.max(scan_threads),
cfg.pdf_workers,
cfg.bulk_mb,
)
};
let phase_a_context = PhaseAContext {
state_dir: &state_dir,
budget: &pdf_spool_budget,
capacity_warning: pdf_spool_capacity_warning.as_deref(),
progress: &pr,
meter: &scan_meter,
tally,
};
let mut plan: Plan = if let Some(p) = journal.plan.clone().filter(|_| !genesis_recovery) {
p
} else {
pr.phase("scan", files.len() as u64, planned_bytes);
// Named with the width phase A is really running at: `--workers` only
// started governing this phase in #240, so "how wide is it right now"
// is exactly the question the reader has.
pr.note(&format!(
"phase A: sniffing + sampling {} files with {scan_threads} threads…",
files.len()
));
let PhaseA {
plan,
clusters,
pdf_spools: spools,
} = build_phase_a(
&cfg.root,
&files,
&keys,
&digests,
duplicate_files.clone(),
&phase_a_context,
&cfg,
);
pdf_spools = spools;
pr.note(&estimate::phase_a_line(
plan.datasets.len() as u64,
plan.junk_files.len() as u64,
));
key_stats = Some(correlate::key_stats(&clusters));
drop(clusters);
plan
};
let unreadable_keys: HashSet<String> = inventory
.unreadable
.iter()
.map(|item| content::unreadable_file_key(&item.file.rel_id))
.collect();
if record_unreadable_skips(&mut plan, &inventory.unreadable) {
plan_changed = true;
}
// Second gate, after key selection has settled. Deletions the first gate
// already swept are gone from the plan. Anything still classified as a
// deletion here (a key the first comparison missed) is swept the same way
// rather than refusing the run (#2314). An exclusion sweep removes a
// file's documents without this run re-reading anything; a reply edge from
// a surviving mailbox into the swept one would stay live. The corpus-wide
// mail pass below re-derives those edges when this is set (see
// `carry_over_unread_mail`).
let mut swept_excluded = false;
if resumed_with_plan {
let still_present = files_still_present(&dataless_skipped_files, &inventory.unreadable);
let delta = inventory_delta(&cfg.root, &files, &keys, &plan, &still_present);
if !delta.deleted_content_groups.is_empty() {
let gone: HashSet<String> = delta
.deleted_content_groups
.iter()
.map(|entry| entry.file_key.clone())
.collect();
let count = delta.deleted_content_groups.len();
let paths = deleted_group_list(&delta.deleted_content_groups);
if cfg.dry_run {
pr.note(&format!(
"autoindex: {count} file(s) indexed under this resume plan no longer exist in \
the folder ({paths}); a real run removes their documents"
));
} else {
swept_membership = true;
let edges_index = graph_edges_index(&cfg);
sweep_excluded_groups(
&es,
&cfg.prefix,
&plan,
&delta.deleted_content_groups,
edges_index.as_deref(),
chrono::Utc::now().timestamp_millis(),
)
.context("sweep deleted content groups")?;
pr.note(&format!(
"autoindex: removed documents for {count} file(s) that no longer exist in the \
folder ({paths})"
));
}
plan.files.retain(|key, _| !gone.contains(key));
plan.duplicate_files.retain(|alias| {
!gone.contains(&alias.file_key) && plan.files.contains_key(&alias.file_key)
});
recount_plan_file_counts(&mut plan);
plan_changed = true;
for key in &gone {
deleted_file_keys.insert(key.clone());
if journal.done.contains_key(key) {
journal.file_removed(key)?;
}
}
}
// #589: sweep documents left behind by a widened exclusion (see gate
// above). Never mutate under --dry-run.
if !delta.excluded_content_groups.is_empty() && !cfg.dry_run {
swept_excluded = true;
let edges_index = graph_edges_index(&cfg);
sweep_excluded_groups(
&es,
&cfg.prefix,
&plan,
&delta.excluded_content_groups,
edges_index.as_deref(),
chrono::Utc::now().timestamp_millis(),
)
.context("sweep newly-excluded content groups")?;
excluded_file_keys.extend(
delta
.excluded_content_groups
.iter()
.map(|entry| entry.file_key.clone()),
);
}
}
// ── stale junk-catalog sweep (#238) ──────────────────────────────────
//
// A junk/skipped file is never indexed and never enters the graph corpus
// — both walk `plan.files`, which by construction does not contain it. Its
// ENTIRE live footprint is one `file:{key}` catalog document, so removing
// that document is a complete removal, unlike an indexed file where
// dropping the catalog entry while its records stay live would be a lie.
//
// The durable plan is the only thing that remembers the document exists:
// nothing else in a run remembers a file it deliberately did not read. So
// the sweep is driven from the plan, and the plan entry may be dropped
// only after the delete has actually landed — the same order quickwit's
// GC keeps, deleting split files first and removing metastore records
// only for the deletes that succeeded (quickwit,
// quickwit/quickwit-index-management/src/garbage_collection.rs:484-534,
// Apache-2.0; approach only, no code taken). Dropping the record first
// would strand the document exactly as before.
//
// A key that is somehow BOTH planned and junk is left alone: deleting
// `file:{key}` would take out a live indexed file's catalog entry, and an
// immortal junk row is the cheaper of those two failures.
let live_keys: std::collections::HashSet<&str> = keys.iter().map(String::as_str).collect();
let stale_junk_keys: std::collections::HashSet<String> = plan
.junk_files
.iter()
.filter(|junk| {
!live_keys.contains(junk.file_key.as_str())
&& !plan.files.contains_key(&junk.file_key)
// A file that vanished or is locked this run has no content
// key, so it is not in `live_keys`. Dropping the skip in the
// same run would hide the only record of it (#2352). The next
// run, once the walk no longer lists it, does not put the key
// in `unreadable_keys` and the row is swept.
&& !unreadable_keys.contains(&junk.file_key)
})
.map(|junk| junk.file_key.clone())
.collect();
// ── estimate → work order → decision gate ────────────────────────────
//
// Everything below happens BEFORE the first remote mutation: no index has
// been created, no mapping upgraded, no plan persisted, no document
// written. That placement is the whole point — a run that stops here has
// cost the user a read of their folder and nothing else.
let pending = pending_for_phase_b(&keys, &plan, &journal.done_keys(), &content_changed);
let scan_rates = scan_meter.rates();
let planned_for_estimate: Vec<estimate::PlannedFile> = pending
.iter()
.map(|&i| estimate::PlannedFile {
family: plan.files[&keys[i]].family.clone(),
bytes: files[i].size,
})
.collect();
let run_estimate = estimate::Estimate::compute(&planned_for_estimate, &scan_rates, cfg.workers);
let work_items: Vec<order::Item> = pending
.iter()
.map(|&i| order::Item {
index: i,
band: order::band_from_family_str(&files[i].rel, &plan.files[&keys[i]].family),
bytes: files[i].size,
})
.collect();
let bands = order::summarize(&work_items);
let rel_bytes: Vec<(String, u64)> = pending
.iter()
.map(|&i| (files[i].rel.clone(), files[i].size))
.collect();
let rel_family_bytes: Vec<(String, String, u64)> = pending
.iter()
.map(|&i| {
(
files[i].rel.clone(),
plan.files[&keys[i]].family.clone(),
files[i].size,
)
})
.collect();
let heaviest = gate::heaviest_directories(&rel_bytes, 5);
pr.note(&format!("estimate: {}", run_estimate.headline()));
pr.note(&format!("estimate: basis — {}", run_estimate.basis));
for family in &run_estimate.families {
pr.note(&format!(
" estimate: {:<10} {} {:>9} at {}/s measured over {} / {} → {}",
family.family,
estimate::count_files_column(family.planned_files),
estimate::human_bytes(family.planned_bytes),
estimate::human_bytes(family.bytes_per_sec as u64),
estimate::count_phrase(family.measured_files, "file", "files"),
estimate::human_bytes(family.measured_bytes),
estimate::human_secs(family.seconds_of_work),
));
}
for family in &run_estimate.unmeasured_families {
pr.note(&format!(
" estimate: {:<10} {} {:>9} NOT priced — {}",
family.family,
estimate::count_files_column(family.planned_files),
estimate::human_bytes(family.planned_bytes),
family.reason,
));
}
for exclude in &run_estimate.excludes {
pr.note(&format!(" estimate excludes: {exclude}"));
}
pr.note(&order::work_order_line(&bands, cfg.workers));
for band in &bands {
pr.note(&format!(" {:<16} {}", band.band, band.why));
}
if gate::over_threshold(&run_estimate, cfg.max_minutes) {
let semantic_datasets: Vec<String> = plan
.datasets
.iter()
.filter(|dataset| dataset.semantic_field.is_some())
.map(|dataset| dataset.slug.clone())
.collect();
// Decided once, before anything is printed, and used for both halves:
// whether to touch stdin at all, and what the payload says about why
// nobody was asked. `pr.enabled()` is the missing third condition —
// `--quiet` / `--progress none` routes every `pr.note` below to
// nothing, so without it the gate printed no question and then waited
// on stdin for the answer to it.
let prompt_blocked = gate::detect_prompt_block(pr.enabled());
let request = gate::DecisionRequest {
root: root_str.clone(),
estimate: &run_estimate,
max_minutes: cfg.max_minutes,
bands: bands.clone(),
heaviest: heaviest.clone(),
without_generated: gate::without_generated_directories(
&run_estimate,
&scan_rates,
&heaviest,
&rel_family_bytes,
),
semantic_datasets,
total_datasets: plan.datasets.len(),
graph_files: if cfg.no_graph {
0
} else {
pending.len() as u64
},
prompt_blocked,
};
match cfg.approve {
Some(answer) => pr.note(&format!(
"gate: {} — answered with --approve {}",
request.reason(),
answer.as_str()
)),
None if cfg.dry_run => pr.note(&format!(
"gate: a real run would STOP here and exit {} — {}",
gate::EXIT_NEEDS_DECISION,
request.reason()
)),
None => {
for line in request.prose() {
pr.note(&line);
}
// Ask only where an answer can arrive AND the question was
// actually shown. A pipe, a CI job or an agent has no one at
// the keyboard; a quiet run has someone at the keyboard who
// was shown nothing. Blocking on stdin in either case is an
// invisible deadlock — the failure this gate was added to
// prevent, not to introduce. When it is blocked, stdin is not
// opened at all.
let answer = gate::answer_from_terminal(
prompt_blocked,
|| std::io::stdin().lock(),
|line| pr.note(line),
);
match answer {
Some(gate::Approval::Proceed) => pr.note("gate: proceeding"),
Some(gate::Approval::Fast) => {
// Not honourable mid-run: --no-semantic decides the
// mappings this plan was inferred with. Saying so beats
// silently indexing semantically anyway (#204).
pr.note(
"gate: 'fast' changes the inferred mappings, so it cannot be applied \
to a plan that is already frozen. Nothing was indexed — re-run the \
same command with --approve fast",
);
println!("{}", request.to_json());
pr.finish(false, gate::EXIT_NEEDS_DECISION, "needs-decision", &[]);
return Ok((gate::EXIT_NEEDS_DECISION, None));
}
Some(gate::Approval::Cancel) => {
pr.note("gate: cancelled — nothing was indexed");
pr.finish(true, 0, "cancelled", &[]);
return Ok((0, None));
}
None => {
println!("{}", request.to_json());
pr.finish(false, gate::EXIT_NEEDS_DECISION, "needs-decision", &[]);
return Ok((gate::EXIT_NEEDS_DECISION, None));
}
}
}
}
} else if cfg.max_minutes > 0 && run_estimate.gate_seconds().is_some() {
// Say what the silence means. "Under the threshold" is a statement
// about the floor, not a promise about the run, and an agent relaying
// it to a person needs the difference.
pr.note(&format!(
"gate: not triggered — the measured extraction floor {} is under --max-minutes {}. \
That is NOT a promise the run finishes in {} minutes: server, network and embedding \
time are not measured before indexing starts",
run_estimate.range_text(),
cfg.max_minutes,
cfg.max_minutes
));
}
if cfg.approve == Some(gate::Approval::Cancel) {
pr.note("gate: --approve cancel — nothing was indexed");
pr.finish(true, 0, "cancelled", &[]);
return Ok((0, None));
}
let sizes = inventory_size_map(&inventory);
note_neural_ingest_cost(
&es,
neural_cost::semantic_source_bytes(&plan, &sizes),
neural_cost::SourceBytes::SemanticSource,
&pr,
);
if cfg.dry_run {
println!("{}", serde_json::to_string_pretty(&plan)?);
pr.note("(dry run — nothing indexed)");
// As above: the count is capped, so the completeness flag ships with it.
let mut dry_done = vec![
("files", files.len() as u64),
("ignored_files", ignore_report.files_skipped),
("ignored_dirs", ignore_report.dirs_pruned),
(
"ignored_files_in_pruned_dirs",
ignore_report.files_inside_pruned_dirs,
),
];
if dataless_skipped > 0 {
dry_done.push(("skipped_dataless", dataless_skipped));
}
pr.finish_with_flags(
true,
0,
"dry-run",
&dry_done,
&[(
"ignored_files_in_pruned_dirs_exact",
ignore_report.files_inside_pruned_dirs_is_exact(),
)],
);
return Ok((0, None));
}
if cfg.no_graph && !resumed_with_plan {
// #929: install the mappings BEFORE anything is sealed, so a dataset
// the server refuses leaves the plan while it still coherently can. The
// generation is then derived from the plan that was actually accepted.
let sizes: HashMap<&str, u64> = inventory
.keys
.iter()
.zip(&inventory.files)
.map(|(key, file)| (key.as_str(), file.size))
.collect();
let (plan, installed_identity) = preflight_generation_mappings(&es, plan, &sizes, &pr)?;
begin_non_graph_generation(
&es,
&mut journal,
&state_dir,
&cfg,
&root_str,
&inventory,
&pr,
plan,
labeler.as_ref(),
)?;
// #933: the durable replay window is the run's --workers, the same
// number that bounds bulk admission, so overlapped operations share
// one AIMD gate with the bulks they send.
let mut backend =
sync_executor::EsSyncBackend::new(&es, &state_dir, cfg.bulk_mb << 20, &pr)
.with_replay_workers(cfg.workers)
.with_installed_mappings(installed_identity);
sync_executor::replay_pending_operations_reporting(
&state_dir,
&mut journal,
&mut backend,
&pr,
)?;
let summary = finish_generated_run(&es, &mut journal, &cfg)?;
let code = generated_exit_code(&summary);
finish_generated_progress(&pr, code, &summary, dataless_skipped);
return Ok((code, Some(summary)));
}
if plan
.datasets
.iter()
.any(|dataset| dataset.semantic_field.is_some())
{
let identity = es
.embedding_execution_identity()
.context("semantic autoindex could not pin the server embedding execution identity")?;
journal.pin_embedding_identity(
&identity.identity_sha256,
identity.resumable,
identity.dimensions,
identity.non_resumable_reason.as_deref(),
)?;
// #1189: name the live backend in the run output. A server started
// with mode=proxy that had silently degraded to lexical was
// indistinguishable here until the vectors came back wrong.
pr.note(&format!(
"semantic autoindex embedding backend: {} ({}resumable)",
identity.backend,
if identity.resumable { "" } else { "non-" }
));
if !identity.resumable {
pr.note(&format!(
"semantic autoindex cannot resume this embedding backend: {}",
identity
.non_resumable_reason
.as_deref()
.unwrap_or("the server did not provide an immutable embedding identity")
));
}
}
// ── create indices with explicit mappings ────────────────────────────
// Two round trips per dataset; a 135-dataset plan is a real wait.
pr.phase("prepare", plan.datasets.len() as u64, 0);
// #929: the same split the generated path makes (`install_dataset_mappings`).
// A server REFUSAL of one dataset's mapping costs that dataset, not the run
// — but only while the plan is still this invocation's to change. A resumed
// plan is already durable and may already have published files under the
// dataset, so dropping it there would strand live documents; that case
// stays fatal, exactly as before.
let mut refused: Vec<MappingRefusal> = Vec::new();
for d in &plan.datasets {
// The same create body the generated route installs
// (`dataset_create_body`): frozen mapping, `ax_paths`, the #1093
// strict-unknown-fields mark, and — when the profiler marked this
// dataset's prose semantic — the #1059 stemming analyzer declaration
// in `settings.analysis.analyzer.default`.
let installed = es
.ensure_index(&d.index, &dataset_create_body(d))
.with_context(|| format!("create index {}", d.index))
.and_then(|()| {
es.update_mapping(&d.index, &graph_mapping_upgrade(&plan, d))
.with_context(|| format!("upgrade alias-path mapping for {}", d.index))
});
match installed {
Ok(()) => {}
Err(error)
if !resumed_with_plan
&& error.downcast_ref::<esclient::MappingRefused>().is_some() =>
{
refused.push((d.slug.clone(), refusal_reason(&error)));
}
Err(error) => return Err(error),
}
pr.item_done(0);
}
if !refused.is_empty() {
let sizes: HashMap<&str, u64> = keys
.iter()
.zip(&files)
.map(|(key, file)| (key.as_str(), file.size))
.collect();
let before = plan.files.len();
refuse_datasets(&mut plan, &refused, &sizes);
for refusal in &plan.refused_datasets {
pr.warn(&format!(
"autoindex: dataset {} REFUSED by the server — {} file(s) recorded as junk and NOT \
indexed; every other dataset continues. {}",
refusal.dataset.slug,
refusal.file_keys.len(),
refusal.reason
));
}
pr.warn(&format!(
"autoindex: {} dataset(s) refused, {} of {before} file(s) not indexed — this run will \
exit 3 and name them in its summary (`datasets_refused`)",
plan.refused_datasets.len(),
before - plan.files.len(),
));
plan_changed = true;
}
es.ensure_index(catalog::CATALOG_INDEX, &catalog::catalog_mapping())?;
es.update_mapping(
catalog::CATALOG_INDEX,
&json!({"properties": {
"duplicate_of": {"type": "keyword"},
// `started` intentionally stays out of this additive upgrade. A
// catalog written by v1.0.0-rc.4 has a dynamically inferred TEXT
// `started`, and asking the engine to add it as `date` is refused
// 400 — which `es.update_mapping` turns into an `Err`, aborting
// the run before any document work. `catalog::catalog_mapping`
// declares it `date` for a fresh catalog, so the field is
// permanently bimodal across installs; its doc comment carries the
// full tripwire and the measured refusal.
"summary_generated_at": {"type": "date", "format": "strict_date_optional_time||epoch_millis"},
"invocation_telemetry_scope": {"type": "keyword"},
// Safe to add here, unlike `started`: no release ever wrote this
// field, so no existing catalog has a conflicting inferred type.
"junk_records_this_run": {"type": "long"}
}}),
)
.context("upgrade autoindex catalog mapping")?;
// #755: `prefix` is deliberately absent from the additive upgrade above for
// exactly the `started` reason — rc.15..rc.67 inferred it as TEXT from the
// run document, so declaring it `keyword` here would 400 and abort this
// path too. `catalog::CORPUS_SCOPE_FIELD` is the way out: no release ever
// wrote it, so it is always installable, and it gives this path the same
// exact corpus scope the generated path gets. Separate from the PUT above
// so a pre-existing conflict in one of those fields cannot take it down.
//
// Through `install_catalog_mapping`, so this path is fail-soft on exactly
// the same terms as the generated one: if something outside autoindex has
// written `corpus_scope` into the shared catalog as text — which is how the
// #755 repro creates its legacy state in the first place — the run states
// what it lost and continues, rather than reproducing the abort this change
// exists to remove.
install_catalog_mapping(
&es,
&json!({"properties": {catalog::CORPUS_SCOPE_FIELD: {"type": "keyword"}}}),
&pr,
)
.context("install autoindex catalog corpus-scope mapping")?;
// A replacement transaction starts before the effective new plan is
// persisted and before live visibility changes. If the process dies at
// any later boundary, journal replay removes the older file_done and
// deterministically schedules a delete-before-replace repair.
let generation_by_key: HashMap<&str, &str> = keys
.iter()
.zip(digests.iter())
.map(|(key, digest)| (key.as_str(), digest.as_str()))
.collect();
// Snapshot whether live records may already exist before this run starts
// any new publication intents. Fresh first publications can skip the
// delete/refresh round trip; replacements and crash repairs cannot.
// Read before the journal moves behind its mutex: did the previous
// invocation reach its summary? (`Journal::interrupted`.)
let journal_interrupted = journal.interrupted;
let mut cleanup_required: std::collections::HashSet<String> = journal
.done
.keys()
.chain(journal.pending_replacements.keys())
.cloned()
.collect();
let mut replacements: Vec<&String> = content_changed
.iter()
.filter(|key| {
let desired = generation_by_key.get(key.as_str()).copied();
journal.done.contains_key(key.as_str())
|| journal
.pending_replacements
.get(key.as_str())
.is_some_and(|pending| Some(pending.as_str()) != desired)
})
.collect();
replacements.sort();
for key in replacements {
journal.file_replace_start(
key,
generation_by_key
.get(key.as_str())
.copied()
.unwrap_or("unknown"),
)?;
}
// #2076: journals written before the stale-plan status stored post-plan
// files as status "skipped" inside `junk_files`. Promote them once so a
// later resume keeps reporting a stale plan instead of ordinary junk.
for junk in &mut plan.junk_files {
if junk.status != STALE_RESUME_PLAN_STATUS && is_stale_resume_skip(junk) {
junk.status = STALE_RESUME_PLAN_STATUS.to_string();
plan_changed = true;
}
}
// Persist only an effective plan change. Repeating the full plan on every
// no-op resume caused journal growth proportional to plan_size × runs.
if plan_changed {
journal.write_plan(&plan)?;
}
replacement_failpoint(1, &state_dir).context("after durable replacement plan")?;
let unity_guid_map = build_unity_guid_map(&files, &plan, &pr);
report_unity_guid_map(&unity_guid_map, &pr);
// ── Phase B: full-stream extraction + bulk indexing ─────────────────
struct DsRt {
index: String,
plan: HashMap<String, coerce::Coerce>,
records: AtomicU64,
}
let mut ds_rt: HashMap<String, DsRt> = HashMap::new();
for d in &plan.datasets {
ds_rt.insert(
d.slug.clone(),
DsRt {
index: d.index.clone(),
plan: coerce::plan_from_specs(&d.specs),
records: AtomicU64::new(0),
},
);
}
let done0 = journal.done_keys();
let planned_junk: std::collections::HashSet<&str> = plan
.junk_files
.iter()
.map(|j| j.file_key.as_str())
.collect();
let mut new_unplanned: Vec<JunkFile> = Vec::new();
// The same predicate the estimate above priced — see `pending_for_phase_b`
// for why the two snapshots of `journal.done` cannot disagree.
let mut todo: Vec<usize> = pending_for_phase_b(&keys, &plan, &done0, &content_changed);
for i in 0..files.len() {
if keys[i].is_empty() || done0.contains(&keys[i]) && !content_changed.contains(&keys[i]) {
continue;
}
if !plan.files.contains_key(&keys[i]) && !planned_junk.contains(keys[i].as_str()) {
// File appeared after the plan was frozen. Recorded so a later
// deletion can sweep the catalog row (#238), but not as junk:
// counting it there made the resume look like completed-with-junk
// (#2076). The frozen graph plan cannot absorb it; `--fresh`
// rebuilds the plan in place.
new_unplanned.push(JunkFile {
file_key: keys[i].clone(),
rel: files[i].rel.clone(),
format: "unknown".into(),
status: STALE_RESUME_PLAN_STATUS.into(),
reason: STALE_RESUME_PLAN_FILE_REASON.into(),
bytes: files[i].size,
});
}
}
// Previously recorded stale-plan files are already in `plan.junk_files`,
// so a second resume would otherwise say nothing. List every one still on
// disk, new and remembered.
let live_keys_now: HashSet<&str> = keys.iter().map(String::as_str).collect();
let mut stale_rels: Vec<&str> = new_unplanned.iter().map(|jf| jf.rel.as_str()).collect();
for junk in &plan.junk_files {
if is_stale_resume_skip(junk) && live_keys_now.contains(junk.file_key.as_str()) {
stale_rels.push(junk.rel.as_str());
}
}
stale_rels.sort_unstable();
stale_rels.dedup();
if !stale_rels.is_empty() {
// The frozen plan cannot absorb files discovered after it was written.
// Say so on stderr rather than leaving it to the catalog: a rerun that
// quietly ignores new files is the bug this gate exists to surface.
// Routed through the progress surface, which owns stderr (#241): a raw
// eprintln! here would break `--progress json`'s single parseable
// stream, and `--quiet` already selects `--progress none`.
pr.note(&format!(
"autoindex: {} file(s) were skipped because the resumed plan is stale: they \
appeared after the resume plan was frozen and were NOT indexed:",
stale_rels.len()
));
for rel in stale_rels.iter().take(REFUSAL_LIST_CAP) {
pr.note(&format!(" not in plan, skipped: {rel}"));
}
let remaining = stale_rels.len().saturating_sub(REFUSAL_LIST_CAP);
if remaining > 0 {
pr.note(&format!(" … and {remaining} more"));
}
pr.note(
"autoindex: re-run with --fresh to rebuild the plan in place and include them (ids \
stay idempotent)",
);
}
if resumed_with_plan {
// Legacy journals predate intent-before-publication and may have live
// partial records without either file_done or file_replace_start.
// Conservatively clean every resumed planned todo once. Only a plan
// created in this process can prove that its first publication is
// genuinely fresh and skip the delete round trip.
cleanup_required.extend(todo.iter().map(|&i| keys[i].clone()));
}
// #2139: `--fresh` rebuilds every content key and wipes `journal.done`
// first, so the set above is empty. The file is then republished under
// the new key and the previous key's symbol documents stay live. A later
// ordinary resume only deletes the latest key, which is how one function
// ends up indexed at several line numbers. Schedule a purge for every
// path whose published key just changed. Unchanged keys are not scheduled:
// their ids already overwrite, and a delete per unchanged file is the
// refresh cost #1224 removed.
let mut superseded: HashMap<String, PriorPublication> = HashMap::new();
for (i, file) in files.iter().enumerate() {
let prior = prior_by_path_id
.get(&file.rel_id)
.or_else(|| prior_by_rel.get(&file.rel));
if let Some(prior) = prior {
if prior.file_key != keys[i] {
cleanup_required.insert(keys[i].clone());
superseded.insert(file.rel.clone(), prior.clone());
}
}
}
let todo_set: std::collections::HashSet<usize> = todo.iter().copied().collect();
for (index, spool) in pdf_spools.iter_mut().enumerate() {
if spool.is_none() {
continue;
}
if todo_set.contains(&index) {
pdf_spool_budget.record_phase_b_eligible();
} else {
pdf_spool_budget.record_discarded_before_replay();
spool.take();
}
}
// Every publication, including a fresh one, receives durable intent
// before its first bulk. A failed fresh publication therefore skips the
// unnecessary delete now but is recognized as pending and cleaned on the
// next run.
let mut intent_keys: Vec<&str> = todo.iter().map(|&i| keys[i].as_str()).collect();
intent_keys.sort_unstable();
intent_keys.dedup();
for key in intent_keys {
let generation = generation_by_key.get(key).copied().unwrap_or("unknown");
if journal
.pending_replacements
.get(key)
.is_none_or(|pending| pending != generation)
{
journal.file_replace_start(key, generation)?;
}
}
// ── second-brain graph: corpus table, structural edges, invalidation ──
// (SECOND_BRAIN_SPEC §6.6.1/§6.6.3.) Runs after plan finalization so the
// detectors see the whole corpus, and BEFORE any Phase B publication so
// replacement invalidation can only ever see prior-generation edges —
// running it later would invalidate this run's own fresh edges.
let bulk_cut = cfg.bulk_mb << 20;
// Parser junk this invocation read out of source files (durable: it is
// journaled per file and replayed on resume).
let junk_records = AtomicU64::new(0);
// Records the backend refused in a bulk response (invocation-local: no
// journal record exists for a document that was never accepted).
let rejected_records = AtomicU64::new(0);
// Files whose section stream hit the per-file record cap (#381): the tail
// was dropped, so it is surfaced BY NAME after the run, not silently lost.
let truncated_files = Mutex::new(Vec::<String>::new());
let bulk_errors = Mutex::new(Vec::<String>::new());
let graph: Option<GraphRt> = if cfg.no_graph {
None
} else {
pr.phase("graph", files.len() as u64, 0);
let brain = match &cfg.brain {
Some(b) => b.clone(),
None => derive_brain_name(&cfg.root),
};
if let Err(reason) = detect::validate_brain(&brain) {
anyhow::bail!(
"brain name '{brain}' is invalid: {reason}. Pass an explicit --brain <name> \
or disable relationship detection with --no-graph"
);
}
// Corpus resolution table: every planned file's rel → identity +
// anchor node. valid_at comes from the file mtime (§6.4) so an
// unchanged corpus re-emits byte-identical edge_ids and re-runs
// converge by overwrite, exactly like ids::doc_id does for nodes.
let mut corpus_files = Vec::new();
for (i, f) in files.iter().enumerate() {
let key = &keys[i];
if key.is_empty() {
continue;
}
let Some(fa) = plan.files.get(key) else {
continue; // junk or post-freeze files carry no node docs
};
let slug = fa
.assignments
.iter()
.find(|(g, _)| g.is_none())
.map(|(_, s)| s.clone())
.or_else(|| fa.assignments.iter().map(|(_, s)| s.clone()).min());
let Some(slug) = slug else { continue };
let mtime_ms = std::fs::metadata(&f.path)
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as i64)
.unwrap_or(0);
corpus_files.push(detect::corpus_file(
&f.rel, key, &slug, &fa.family, mtime_ms,
));
pr.item_done(0);
}
let corpus = detect::CorpusIndex::build(corpus_files);
let detectors = detect::default_detectors();
let edges_index = detect::edges_index_name(&brain);
let created_at_ms = chrono::Utc::now().timestamp_millis();
es.ensure_index(&edges_index, &detect::edge_index_mapping())
.with_context(|| format!("create edges index {edges_index}"))?;
let mut nodes_indices: Vec<&str> = plan.datasets.iter().map(|d| d.index.as_str()).collect();
nodes_indices.sort_unstable();
nodes_indices.dedup();
detect::ensure_brain_meta(
&es,
&edges_index,
&brain,
&nodes_indices.join(","),
created_at_ms,
)?;
// Replacement invalidation FIRST: soft-invalidate every live edge a
// replaced file taught in earlier runs. The bi-temporal record stays
// queryable (`as_of` time travel); nothing is deleted.
let mut invalidated = 0u64;
{
let mut replaced_rels: Vec<&str> = todo
.iter()
.filter(|&&i| cleanup_required.contains(&keys[i]))
.map(|&i| files[i].rel.as_str())
.collect();
// #736: `cleanup_required` is the journal's own record of what is
// already live, so it is EMPTY after `--fresh` wiped the journal —
// and `--fresh` is the one path that gives a content-changed file a
// new `file_key`, hence a new anchor node. Nothing above notices, so
// the prior generation's edges stayed live: the ones the old anchor
// taught (`src_file`) AND the ones a surviving file taught pointing
// AT it (`dst`), which is the inbound half #736 was filed for. An
// ordinary resume supersedes no anchor (`select_resume_plan_keys`
// preserves the planned key across an in-place edit), so this set is
// empty there and the resume behaviour is unchanged.
let live_anchors: std::collections::HashSet<String> = plan_anchor_nodes(&plan)
.into_iter()
.map(|(anchor, _)| anchor)
.collect();
let superseded: Vec<&(String, String)> = prior_anchor_nodes
.iter()
.filter(|(anchor, _)| !live_anchors.contains(anchor))
.collect();
replaced_rels.extend(superseded.iter().map(|(_, rel)| rel.as_str()));
replaced_rels.sort_unstable();
replaced_rels.dedup();
// #2640: one batched sweep for every replaced file, not one
// search/bulk/refresh round each. After `--fresh` on a switched
// branch this set is most of the corpus, and the per-file refresh
// storm is what made the phase take hours.
invalidated += detect::invalidate_edges_by_field_values(
&es,
&edges_index,
"src_file",
&replaced_rels,
created_at_ms,
)
.with_context(|| {
format!(
"invalidate prior edges taught by {} replaced files",
replaced_rels.len()
)
})?;
// The inbound half. Keyed on the SUPERSEDED anchor only — never on a
// surviving file — so an unchanged file's edges are left exactly as
// they are (#868). This runs before any edge this run writes, and
// this run's edges name the NEW anchor, so it can only ever match
// prior generations. Same soft-invalidate as the src side: the
// bi-temporal record survives for `as_of` time travel.
let mut superseded_anchors: Vec<&str> = superseded
.iter()
.map(|(anchor, _)| anchor.as_str())
.collect();
superseded_anchors.sort_unstable();
superseded_anchors.dedup();
invalidated += detect::invalidate_edges_by_field_values(
&es,
&edges_index,
"dst",
&superseded_anchors,
created_at_ms,
)
.with_context(|| {
format!(
"invalidate inbound edges to {} superseded anchor nodes",
superseded_anchors.len()
)
})?;
}
// Structural detection (samedir chains) + bulk write, cut at the same
// --bulk-mb threshold as node bulks.
let mut structural = Vec::new();
for det in &detectors {
det.detect_structure(&corpus, &mut structural);
}
let assembled = detect::assemble(&structural, &edges_index, created_at_ms);
let mut written: std::collections::BTreeMap<&'static str, u64> =
std::collections::BTreeMap::new();
{
let mut send_err: Option<String> = None;
let mut buf: Vec<u8> = Vec::new();
for edge in &assembled.edges {
buf.extend_from_slice(&edge.ndjson);
*written.entry(edge.detector).or_default() += 1;
if buf.len() >= bulk_cut
&& record_bulk_outcome(
&es,
std::mem::take(&mut buf),
&rejected_records,
&bulk_errors,
&mut send_err,
)
{
break;
}
}
if send_err.is_none() && !buf.is_empty() {
record_bulk_outcome(&es, buf, &rejected_records, &bulk_errors, &mut send_err);
}
if let Some(e) = send_err {
anyhow::bail!("write structural graph edges to {edges_index}: {e}");
}
}
pr.note(&format!(
"graph: brain '{brain}' → {edges_index}; {} structural edges, {} prior edges \
invalidated ({} detectors live)",
assembled.edges.len(),
invalidated,
detectors.len()
));
Some(GraphRt {
corpus,
detectors,
href_raw: detect::href::Href::default(),
edges_index,
brain,
created_at_ms,
written: Mutex::new(written),
self_dropped: AtomicU64::new(assembled.self_dropped),
invalidated: AtomicU64::new(invalidated),
})
};
// Value first, then biggest-first inside each band — `crate::order` owns
// the rule and the reasoning, and the bands were already printed with the
// estimate above so the order is explained rather than asserted. The queue
// is drained with `pop()`, so this is the start order reversed.
//
// This replaces a plain ascending sort by size. That rule was right about
// scheduling (a huge file must not be left to serialise the tail) and
// silent about value: a user who stopped early got whatever was largest,
// which on a source tree is `node_modules`. `order` keeps the scheduling
// property inside each band and adds a critical-path exception so a file
// that genuinely dominates the run still starts first.
todo = {
let items: Vec<order::Item> = todo
.iter()
.map(|&i| order::Item {
index: i,
band: order::band_from_family_str(&files[i].rel, &plan.files[&keys[i]].family),
bytes: files[i].size,
})
.collect();
order::start_order_as_pop_queue(&items, cfg.workers)
};
let n_todo = todo.len();
// Percent and ETA are bytes-based, never file-count-based. The queue is
// biggest-first, so a files-done percent races to ~100% and then sits
// there for minutes on the one big file still in flight (#241 §5/§6).
// A replayed PDF still costs its own bytes to stage and send, so a spooled
// file counts toward the same denominator as a parsed one.
let todo_bytes: u64 = todo.iter().map(|&i| files[i].size).sum();
let n_pdf_spools = todo
.iter()
.filter(|&&index| pdf_spools[index].is_some())
.count();
pr.phase("index", n_todo as u64, todo_bytes);
pr.note(&format!(
"phase B: indexing {} files with {} workers → {}",
n_todo, cfg.workers, cfg.url
));
phase_b_start_hook(&state_dir);
if n_pdf_spools > 0 {
pr.note(&format!(
"phase B: reusing {n_pdf_spools} run-local PDF extraction(s); these PDFs will not be \
parsed a second time"
));
}
// Move each optional artifact into its sole Phase-B job. A replay cannot
// be retried or retained accidentally after staging begins.
let queue = Mutex::new(
todo.into_iter()
.map(|index| {
let spool = pdf_spools[index].take();
(index, spool)
})
.collect::<Vec<_>>(),
);
let mut paths_by_key: HashMap<String, Vec<String>> = files
.iter()
.zip(keys.iter())
.map(|(file, key)| (key.clone(), vec![file.rel.clone()]))
.collect();
for duplicate in &plan.duplicate_files {
paths_by_key
.entry(duplicate.file_key.clone())
.or_default()
.push(duplicate.rel.clone());
}
for paths in paths_by_key.values_mut() {
paths.sort();
paths.dedup();
}
let journal_mx = Mutex::new(&mut journal);
let files_done = AtomicU64::new(0);
let records_total = AtomicU64::new(0);
let extra_junk = Mutex::new(Vec::<JunkFile>::new());
// #1147: ONE bulk buffer for every worker. The per-file drain below used
// to build a buffer inside each job, so `bulk_cut` could only ever flush
// one file's records and a many-small-files corpus paid one HTTP
// round-trip per file (~12 records/s measured). The same cut, now crossed
// by whatever the workers are staging concurrently, is what fills a bulk.
let worker_count = cfg.workers.min(n_todo.max(1));
let pipe = {
let es = &es;
let rejected = &rejected_records;
BulkPipe::new(
move |body| es.bulk(body),
bulk_cut,
5000,
rejected,
worker_count,
)
};
// One staging worker. Named (rather than written inline in `spawn`) so
// the current thread can run it too when no worker thread starts.
let worker = || {
loop {
// #2177: the node stopped accepting connections. Every later
// `_bulk` fails the same way, and `Es` has already latched, so
// stop this worker instead of walking the rest of the queue.
// `retire` still flushes a residual buffer; that flush hits the
// latch and returns immediately.
if es.node_is_down() {
pipe.retire();
break;
}
let (i, pdf_spool) = match queue.lock().unwrap().pop() {
Some(job) => job,
None => {
// This worker will submit nothing more; the last
// one out drains the shared buffer (#1147).
pipe.retire();
break;
}
};
// The file's slot in the shared bulk buffer. Allocated
// before staging so every exit path below can settle it.
let file_token = pipe.token();
let f = &files[i];
// Counts this file done on EVERY exit path below, junk
// included: progress measures work drained from the queue,
// and a `continue` that skipped the count would park the
// bar short of 100% forever.
let in_flight = pr.file(&f.rel, f.size);
let key = &keys[i];
let expected_digest = &digests[i];
let fa = plan.files.get(key).unwrap();
let asg: HashMap<Option<String>, String> = fa.assignments.iter().cloned().collect();
let sn = if stub_matcher.matches(&f.rel) {
Ok(stub_sniffed(Path::new(&f.rel)))
} else {
sniff::sniff(&f.path)
};
let sn = match sn {
Ok(s) => s,
Err(e) => {
let (status, reason) = match content::unreadable_junk_fields(&e) {
Some((status, reason)) => (status.into(), reason),
None => ("junk".into(), format!("unreadable at index time: {e}")),
};
extra_junk.lock().unwrap().push(JunkFile {
file_key: key.clone(),
rel: f.rel.clone(),
format: "unknown".into(),
status,
reason,
bytes: f.size,
});
continue;
}
};
let mut file_records = 0u64;
let mut file_junk = 0u64;
// Groups phase B saw that phase A never sampled, so they
// have no dataset to route to. Silently counting these as
// junk is how a whole Unity class (or SQL table) can
// vanish from a run with nothing in the report to say so.
let mut unrouted_groups: std::collections::BTreeMap<String, u64> =
std::collections::BTreeMap::new();
// `script_guid`s this file referenced that no `.meta` in
// the tree defines. These are exactly the records that
// ship without script_path/script_class, which is what
// makes the headline query come back empty.
let mut unresolved_script_guids: std::collections::BTreeMap<String, u64> =
std::collections::BTreeMap::new();
let mut file_dropped_by_dataset: HashMap<String, u64> = HashMap::new();
let mut send_err: Option<String> = None;
// Edges this file teaches — buffered apart from the node
// staging file (different target index) and sent only
// after the node bulks are accepted (§6.7).
let mut edge_drafts: Vec<detect::EdgeDraft> = Vec::new();
// (doc id, label) of the last staged text section — the
// sequence detector's predecessor. Stream order is the
// only source that can name a PDF page boundary's
// predecessor (p2-s0 follows the LAST section of page 1).
let mut prev_section: Option<(String, String)> = None;
let mut staged = match stage::Stage::create_in(&state_dir) {
Ok(file) => file,
Err(error) => {
let mut errors = bulk_errors.lock().unwrap();
if errors.len() < 5 {
errors.push(format!(
"create per-file staging area for {}: {error}",
f.rel
));
}
continue;
}
};
// #1911: a file that changed since phase A hashed it (a lock
// file, a log, a sqlite -wal) is ONE skipped file, not a reason
// to abort every other file's run. Nothing of it is staged yet.
if let Err(error) = content::verify(&f.path, f.size, expected_digest) {
extra_junk.lock().unwrap().push(changed_during_run_junk(
key,
&f.rel,
&format_str(Some(&sn)),
f.size,
&error,
));
continue;
}
// File-card anchor node (§6.6.2a): one card doc per corpus
// file, staged BEFORE the file's records. Its
// deterministic id is `CorpusFile.anchor_doc_id` — the
// node every file-level edge (wikilink/mdlink/href/
// pathcite/cratecite/samedir dst, sequence opener src)
// terminates at. Row/line/page families have no `s0`
// section doc, so without the card those edges pointed at
// ghosts. Not counted as an extracted record: it is
// derived anchor infrastructure, not file content.
if let Some(gr) = graph.as_ref() {
if let Some(cf) = gr.corpus.files.get(&f.rel) {
if let Some(rt) = ds_rt.get(&cf.dataset_slug) {
let name = f.rel.rsplit('/').next().unwrap_or(&f.rel);
let mut fields = Map::new();
fields.insert("title".into(), Value::String(name.to_string()));
fields.insert("ax_path".into(), Value::String(f.rel.clone()));
fields.insert(
"ax_paths".into(),
Value::Array(
paths_by_key
.get(key)
.into_iter()
.flatten()
.cloned()
.map(Value::String)
.collect(),
),
);
fields.insert("ax_file".into(), Value::String(key.clone()));
fields.insert(
"ax_locator".into(),
Value::String(detect::FILE_CARD_LOCATOR.into()),
);
fields.insert("ax_dataset".into(), Value::String(cf.dataset_slug.clone()));
fields.insert("ax_run".into(), Value::String(run_id.clone()));
fields.insert("ax_format".into(), Value::String(format_str(Some(&sn))));
align_hit_locators(&mut fields, &f.rel);
let action = json!({"index": {
"_index": rt.index, "_id": cf.anchor_doc_id}});
if let Err(error) =
writeln!(&mut staged, "{}\n{}", action, Value::Object(fields))
{
send_err = Some(format!("stage file card for {}: {error}", f.rel));
}
}
}
}
{
let mut sink = |rec: extract::RawRecord| -> bool {
let Some(slug) = asg.get(&rec.group).or_else(|| asg.get(&None)) else {
file_junk += 1;
*unrouted_groups
.entry(rec.group.clone().unwrap_or_else(|| "(ungrouped)".into()))
.or_insert(0) += 1;
return true;
};
let Some(rt) = ds_rt.get(slug) else {
file_junk += 1;
return true;
};
// Progress INSIDE a mailbox. One Takeout mbox is
// the whole corpus, so crediting its bytes only
// when the file finishes left the bar at 0.0% and
// `since_progress_s` climbing for the entire run.
// Every mbox record says how far into the file its
// message began; that is the position.
if sn.family == Family::Mbox {
if let Some(offset) = extract::mbox::locator_offset(&rec.locator) {
in_flight.advance_to(container_extract_credit(f.size, offset));
}
}
let mut fields = rec.fields;
// BEFORE coercion, not after: these are ordinary
// record fields once stamped, and a field that
// skips `coerce_record` is a field the dataset
// plan never validated.
if let Some(unresolved) =
enrich_unity_fields(sn.family, &mut fields, &unity_guid_map.map, &f.rel)
{
*unresolved_script_guids.entry(unresolved).or_insert(0u64) += 1;
}
let dropped = coerce::coerce_record(&mut fields, &rt.plan);
if dropped > 0 {
let durable = file_dropped_by_dataset.entry(slug.clone()).or_default();
*durable = durable.saturating_add(dropped as u64);
}
fields.insert("ax_path".into(), Value::String(f.rel.clone()));
fields.insert(
"ax_paths".into(),
Value::Array(
paths_by_key
.get(key)
.into_iter()
.flatten()
.cloned()
.map(Value::String)
.collect(),
),
);
fields.insert("ax_file".into(), Value::String(key.clone()));
fields.insert("ax_locator".into(), Value::String(rec.locator.clone()));
fields.insert("ax_dataset".into(), Value::String(slug.clone()));
fields.insert("ax_run".into(), Value::String(run_id.clone()));
fields.insert("ax_format".into(), Value::String(format_str(Some(&sn))));
// #2351: after provenance, before the labeler, so a
// `_source` include of path/start_line/end_line locates
// the record that gets indexed.
align_hit_locators(&mut fields, &f.rel);
// `--label` (#1062): decide the record BEFORE it is
// staged — after coerce, which would drop fields
// the plan does not describe, and before the bulk
// action is built, so what /_decide said is what
// gets indexed. A failed decide fails the run: an
// unlabelled corpus the operator believes is
// labelled is the #204 defect class, not a warning.
if let Some(labeler) = labeler.as_ref() {
match labeler.label_fields(&fields) {
Ok(pairs) => {
for (name, value) in pairs {
fields.insert(name, value);
}
}
Err(error) => {
send_err = Some(format!(
"label {} (record {}): {error:#}",
f.rel, rec.locator
));
return false;
}
}
}
let id = ids::doc_id(slug, key, &rec.locator);
let action = json!({"index": {"_index": rt.index, "_id": id}});
let doc = Value::Object(fields);
if let Err(error) = writeln!(
&mut staged,
"{}\n{}",
action,
serde_json::to_string(&doc).unwrap_or_else(|_| "{}".into())
) {
send_err = Some(format!("stage extracted records for {}: {error}", f.rel));
return false;
}
rt.records.fetch_add(1, Ordering::Relaxed);
file_records += 1;
// Textual edge detection (§6.6.2), after the node
// action is staged: `body` is the exact section
// string the node doc carries, and `id` is the
// section node the evidence lives in.
if let Some(gr) = graph.as_ref() {
// Structured (field-level) detection first: it
// is offered every record, text section or not
// — an email's locators (`m{off}-msg-s0`) are
// deliberately not text sections, and its
// thread edges come from parsed headers.
if let (Some(cf), Some(staged_fields)) =
(gr.corpus.files.get(&f.rel), doc.as_object())
{
let ctx = detect::RecordCtx {
corpus: &gr.corpus,
file: cf,
locator: &rec.locator,
doc_id: &id,
fields: staged_fields,
};
for det in &gr.detectors {
det.detect_record(&ctx, &mut edge_drafts);
}
}
if let Some(label) = section_label(&rec.locator) {
if let (Some(cf), Some(body)) = (
gr.corpus.files.get(&f.rel),
doc.get("body").and_then(Value::as_str),
) {
let ctx = detect::SectionCtx {
corpus: &gr.corpus,
file: cf,
section_label: &label,
prev_section: prev_section
.as_ref()
.map(|(pid, pl)| (pid.as_str(), pl.as_str())),
section_doc_id: &id,
text: body,
};
for det in &gr.detectors {
det.detect_text(&ctx, &mut edge_drafts);
}
prev_section = Some((id.clone(), label));
}
}
}
true
};
// Demoted one-off config files (#173) index as
// documents — their key sets are configuration, not a
// schema (see `dataset` module docs).
//
// `as_document` deliberately outranks artifact replay.
// It decides the record *shape*: phase A built this
// dataset's mapping by re-sampling the file through
// `extract_as_document`, whereas an artifact replays
// PDF-parser page records. Replaying here would publish
// records the frozen plan does not describe. Today no
// PDF can reach this branch (`demotable_family` is
// JSON/YAML/XML only), so this is a guard that keeps
// the precedence right if that set ever widens — the
// artifact is refunded rather than replayed.
let res = if fa.as_document {
if pdf_spool.is_some() {
pdf_spool_budget.record_discarded_before_replay();
}
drop(pdf_spool);
extract::extract_as_document(&f.path, sn.gzip, &mut sink)
} else if sn.family == Family::Pdf {
match pdf_spool {
Some(spool) => {
match spool.replay(f.size, expected_digest, &mut sink) {
Ok(stats) => Ok(stats),
Err(replay_error) => {
// Replay verifies the complete
// artifact before `deliver`
// invokes the sink, so falling
// back here cannot duplicate a
// partially staged record stream.
pdf_spool_budget.record_replay_fallback(&f.rel, &replay_error);
pdf_spool_budget.record_reparse();
extract::extract(&f.path, &sn, None, &mut sink).with_context(
|| {
format!(
"reparse {} after run-local PDF artifact \
verification failed: {replay_error:#}",
f.rel
)
},
)
}
}
}
None => {
pdf_spool_budget.record_reparse();
extract::extract(&f.path, &sn, None, &mut sink)
}
}
} else {
extract::extract(&f.path, &sn, None, &mut sink)
};
match res {
Ok(stats) => {
file_junk += stats.junk;
if stats.truncated {
truncated_files.lock().unwrap().push(f.rel.clone());
}
if stats.oversize_values > 0 {
let ceiling = xerj_common::document_limit::MAX_INDEXED_DOCUMENT_BYTES;
let tail = if stats.records > 0 {
"The rest of the file was indexed."
} else {
"Nothing else in the file was indexed."
};
pr.note(&format!(
"{} ({} bytes): {} JSON value(s) were not indexed (over the {ceiling}-byte limit for one document). {tail} This ceiling is fixed and is not raised by --max-file-mb or limits.max_process_memory_mb; split the value into smaller documents.",
f.rel, f.size, stats.oversize_values,
));
}
}
Err(e) => {
// #2314: extract fails when the file shrinks or vanishes
// after the pre-extract verify. That is one skipped
// file. A genuine extract error, with the bytes still
// what phase A hashed, still aborts the run.
if let Err(changed) = content::verify(&f.path, f.size, expected_digest) {
extra_junk.lock().unwrap().push(changed_during_run_junk(
key,
&f.rel,
&format_str(Some(&sn)),
f.size,
&changed,
));
continue;
}
send_err = Some(format!("extract {}: {e}", f.rel));
extra_junk.lock().unwrap().push(JunkFile {
file_key: key.clone(),
rel: f.rel.clone(),
format: format_str(Some(&sn)),
status: "junk".into(),
reason: format!("extract failed at index time: {e}"),
bytes: f.size,
});
}
}
if !unresolved_script_guids.is_empty() {
let total: u64 = unresolved_script_guids.values().sum();
pr.note(&format!(
"unity: {}: {total} MonoBehaviour record(s) reference {} \
script guid(s) no .meta defines — they ship without \
script_path/script_class: {}",
f.rel,
unresolved_script_guids.len(),
unresolved_script_guids
.keys()
.take(REFUSAL_LIST_CAP)
.cloned()
.collect::<Vec<_>>()
.join(", ")
));
}
if !unrouted_groups.is_empty() {
let total: u64 = unrouted_groups.values().sum();
let named = unrouted_groups
.iter()
.take(REFUSAL_LIST_CAP)
.map(|(g, n)| format!("{g} ({n})"))
.collect::<Vec<_>>()
.join(", ");
let more = unrouted_groups.len().saturating_sub(REFUSAL_LIST_CAP);
let suffix = if more > 0 {
format!(" and {more} more")
} else {
String::new()
};
// A NOTE, never an `extra_junk` entry. This file
// still reaches `journal.file_done` — `send_err`
// is untouched — and every junk entry is turned
// into a catalog document under the same
// `file:{file_key}` id as that completion
// (`catalog::file_doc`, `catalog.rs`). Pushing one
// here put two documents with one id in the same
// bulk, and the later one wins: a file that
// indexed N records was reported as status "junk"
// with records 0, `junk_file_count` counted it
// twice, and `code_coverage.observe` ran for it
// twice. The dropped records are already carried
// on that file's own completion as `junk`
// (`file_junk` below), which is where a per-file
// drop count belongs.
pr.note(&format!(
"{}: {total} record(s) dropped: group(s) never sampled in \
phase A, so they have no dataset — {named}{suffix}",
f.rel
));
}
}
// Raw-source href pass: the HTML extractor strips markup
// before sectioning, so `<a href>` evidence exists only in
// the raw bytes (detect::href module docs). The second
// content::verify below still covers this re-read.
if send_err.is_none() {
if let Some(gr) = graph.as_ref() {
if let Some(cf) = gr.corpus.files.get(&f.rel).filter(|cf| cf.family == "html") {
if let Ok(Some(bytes)) =
extract::read_whole(&f.path, sn.gzip, extract::MAX_WHOLE_FILE)
{
let (raw, _) = sniff::decode_text(&bytes);
gr.href_raw
.detect_raw_html(&gr.corpus, cf, &raw, &mut edge_drafts);
}
}
}
}
if send_err.is_none() {
// #1911: changed while it was being extracted. Its records are
// only staged locally (visibility starts below), so skipping it
// here leaves nothing of it on the node from this run.
if let Err(error) = content::verify(&f.path, f.size, expected_digest) {
extra_junk.lock().unwrap().push(changed_during_run_junk(
key,
&f.rel,
&format_str(Some(&sn)),
f.size,
&error,
));
continue;
}
}
// Finish buffered compression before the first remote mutation.
// ENOSPC can surface here even when every earlier write succeeded;
// keep the previous records live and the replacement pending then.
// Reference: tantivy 3a55bc98, src/directory/mmap_directory/mod.rs:
// 372-376 flushes the temporary writer before publishing its file.
// The stage is consumed here whether or not the send runs: an
// early error drops it, and the unnamed file goes with it.
let staged_len = staged.raw_bytes();
let mut reader = None;
if send_err.is_none() {
match staged.into_reader() {
Ok((r, _disk)) => reader = Some(r),
Err(error) => {
send_err = Some(format!("finish staged records for {}: {error}", f.rel));
}
}
} else {
drop(staged);
}
// Visibility begins only after extraction and the second
// full-content verification and stage finalization.
// Delete-before-replace makes a retry clean up any partial prior attempt.
if send_err.is_none() && cleanup_required.contains(key) {
let prior = superseded.get(&f.rel);
let mut indices: Vec<String> = fa
.assignments
.iter()
.filter_map(|(_, slug)| ds_rt.get(slug).map(|rt| rt.index.clone()))
.collect();
if let Some(prior) = prior {
indices.extend(prior.indices.iter().cloned());
}
indices.sort();
indices.dedup();
// One query: the key this run writes, and the path. The path
// term is what removes a previous generation whose key this
// run no longer uses (#2139). `prior` adds that generation's
// own key and path when either differs (a `--fresh` key
// change, or a rename).
let query = replacement_purge_query(key, &f.rel, prior);
for index in &indices {
if let Err(error) = es.delete_by_query(index, &query) {
send_err = Some(format!(
"remove prior records for {} before replacement: {error:#}",
f.rel
));
break;
}
}
if send_err.is_none() {
if let Err(error) = replacement_failpoint(2, &state_dir) {
send_err = Some(format!("{error:#}"));
}
}
}
if let Some(mut reader) = reader.filter(|_| send_err.is_none()) {
// The second half of a mailbox's bar: staged bytes
// handed to the engine, out of staged bytes in total.
// Credit is taken at submission: the shared buffer
// (#1147) may hold these bytes for a moment before a
// flush carries them, and the bar measures reading
// work, not wire time.
let credit_send = sn.family == Family::Mbox;
let mut staged_sent = 0u64;
// A LOCAL chunk, not the bulk: chunks join whatever
// the other workers are staging in the shared buffer,
// so a small file stops paying for its own round-trip.
let mut chunk: Vec<u8> = Vec::with_capacity(bulk_cut + (1 << 20));
let mut docs = 0usize;
loop {
// A bulk already carrying this file's records was
// refused: stop reading. The sticky error comes
// back from `settle` below (the pre-resolution
// from a successful tail bulk must not clear it).
if pipe.failed(file_token) {
break;
}
let mut action = Vec::new();
match reader.read_until(b'\n', &mut action) {
Ok(0) => break,
Ok(_) => {}
Err(error) => {
send_err = Some(format!("read staged action for {}: {error}", f.rel));
break;
}
}
let mut document = Vec::new();
match reader.read_until(b'\n', &mut document) {
Ok(0) => {
send_err = Some(format!(
"staged record for {} ended without a document",
f.rel
));
break;
}
Ok(_) => {}
Err(error) => {
send_err = Some(format!("read staged document for {}: {error}", f.rel));
break;
}
}
chunk.extend_from_slice(&action);
chunk.extend_from_slice(&document);
staged_sent += (action.len() + document.len()) as u64;
docs += 1;
if chunk.len() >= bulk_cut || docs >= 5000 {
pipe.submit(file_token, std::mem::take(&mut chunk), docs);
docs = 0;
chunk.reserve(bulk_cut);
if credit_send {
in_flight.advance_to(container_send_credit(
f.size,
staged_sent,
staged_len,
));
}
}
}
if !chunk.is_empty() && !pipe.failed(file_token) {
pipe.submit(file_token, chunk, docs);
}
}
// The file's records are in the shared buffer, possibly
// already flushed inline; settle blocks until the bulk
// carrying them was accepted. Until it returns Ok, the
// records are NOT durably in and neither the edges below
// nor the journal commit may run.
if send_err.is_none() {
if let Err(e) = pipe.settle(file_token) {
match pipe.take_too_large(file_token) {
// The server refused a record as too large, which the
// same record will hit on every rerun: set the file
// aside and keep going, as for any junk file (#2807).
// Its accepted records are removed first, so a junk
// file is never half searchable.
Some(reason) => {
pipe.quiesce(file_token);
let query = replacement_purge_query(key, &f.rel, None);
let indices: BTreeSet<String> = fa
.assignments
.iter()
.filter_map(|(_, slug)| ds_rt.get(slug).map(|rt| rt.index.clone()))
.collect();
for index in &indices {
if let Err(error) = es.delete_by_query(index, &query) {
send_err = Some(format!(
"{}: remove its records after the server refused one as \
too large: {error:#}",
f.rel
));
break;
}
}
if send_err.is_none() {
extra_junk.lock().unwrap().push(JunkFile {
file_key: key.clone(),
rel: f.rel.clone(),
format: format_str(Some(&sn)),
status: "junk".into(),
reason: format!(
"set aside at index time: the server refused a record \
from this file: {reason}. On a semantic field the \
vectors the server adds count toward that limit; \
`--no-semantic` indexes the file without them"
),
bytes: f.size,
});
pr.note(&format!(
"{}: set aside, the server refused a record from it as \
over its per-document size limit",
f.rel
));
continue;
}
}
None => send_err = Some(format!("{}: {e}", f.rel)),
}
}
}
// Second-brain edges for this file (§6.7): only after the
// node bulks were accepted, so an edge never precedes its
// own src doc. A failed edge send leaves the file
// un-journaled — the whole file (nodes AND edges) is
// republished on the next run, which converges because
// both sides overwrite by deterministic _id.
if send_err.is_none() && !edge_drafts.is_empty() {
if let Some(gr) = graph.as_ref() {
let out = detect::assemble(&edge_drafts, &gr.edges_index, gr.created_at_ms);
gr.self_dropped
.fetch_add(out.self_dropped, Ordering::Relaxed);
// Counted per file, not from the shared total, which
// other workers move at the same time.
let edge_refused = AtomicU64::new(0);
let mut ebuf: Vec<u8> = Vec::new();
for edge in &out.edges {
ebuf.extend_from_slice(&edge.ndjson);
if ebuf.len() >= bulk_cut
&& record_bulk_outcome(
&es,
std::mem::take(&mut ebuf),
&edge_refused,
&bulk_errors,
&mut send_err,
)
{
break;
}
}
if send_err.is_none() && !ebuf.is_empty() {
record_bulk_outcome(&es, ebuf, &edge_refused, &bulk_errors, &mut send_err);
}
// A refused edge is a failed send too: leave the file
// un-journaled so the rerun republishes it (#2807).
let refused = edge_refused.load(Ordering::Relaxed);
rejected_records.fetch_add(refused, Ordering::Relaxed);
if send_err.is_none() && refused > 0 {
send_err = Some(format!(
"{}: the backend refused {refused} of this file's graph edge(s)",
f.rel
));
}
if send_err.is_none() {
let mut written = gr.written.lock().unwrap();
for edge in &out.edges {
*written.entry(edge.detector).or_default() += 1;
}
}
}
}
if let Some(e) = send_err {
// endpoint trouble: record, do NOT journal file_done
let mut be = bulk_errors.lock().unwrap();
if be.len() < 5 {
be.push(e);
}
continue;
}
if let Err(error) = replacement_failpoint(4, &state_dir) {
let mut errors = bulk_errors.lock().unwrap();
if errors.len() < 5 {
errors.push(format!("{error:#}"));
}
continue;
}
records_total.fetch_add(file_records, Ordering::Relaxed);
junk_records.fetch_add(file_junk, Ordering::Relaxed);
let (commit_result, journal_path) = {
let mut journal = journal_mx.lock().unwrap();
let path = journal.path().display().to_string();
let result = journal.file_done(&FileDone {
file_key: key.clone(),
path: f.rel.clone(),
records: file_records,
junk: file_junk,
bytes: f.size,
dropped_by_dataset: file_dropped_by_dataset,
generation: Some(expected_digest.clone()),
});
(result, path)
};
match commit_result {
Ok(()) => {}
Err(error) => {
let mut errors = bulk_errors.lock().unwrap();
if errors.len() < 5 {
errors.push(format!(
"durably commit completed source {} to {}: {error:#}. \
Live records may be present, but the file remains pending; \
repair journal storage and rerun autoindex",
f.rel, journal_path
));
}
continue;
}
}
// Workers no longer print. A worker can block for minutes
// inside one file, so a worker-driven heartbeat cannot
// bound silence; the ticker thread can, and does.
files_done.fetch_add(1, Ordering::Relaxed);
}
};
// #1122: `Builder::spawn_scoped` returns `Ok`, then the child panics
// if it cannot map an alternate signal stack. Release builds are
// panic=abort, so that panic takes the process down. `thread_spawn::scope`
// uses `pthread_create` and does not install that stack. A refusal is
// an error: workers that did start share the queue, the pipe stops
// counting the ones that never did, and if none started this thread
// works the queue itself. The failed closure is dropped unrun.
// #2428: a refused spawn is retried with backoff first; a transient
// `EAGAIN` must not cost the run a worker, let alone the run.
xerj_common::thread_spawn::scope(|scope| {
let mut started = 0usize;
for _ in 0..worker_count {
match crate::sync_executor::spawn_scoped_with_backoff(
scope,
&xerj_common::thread_spawn::StdSpawn,
xerj_common::thread_spawn::spawn_allowed,
"autoindex-worker",
crate::sync_executor::WORKER_SPAWN_ATTEMPTS,
crate::sync_executor::WORKER_SPAWN_BACKOFF,
worker,
) {
Ok(_) => started += 1,
Err(error) => {
pr.note(&format!(
"autoindex: could not start indexing worker {} of {worker_count} \
({error}); continuing with {}",
started + 1,
started.max(1)
));
break;
}
}
}
if started == 0 && worker_count > 0 {
pipe.abandon_workers(worker_count - 1);
worker();
} else {
pipe.abandon_workers(worker_count - started);
}
});
// `--label` run accounting (#1062): the decide call count is the cost the
// flag added to this run — stated after the walk, where the operator can
// weigh it against the record count.
if let Some(labeler) = labeler.as_ref() {
let (calls, records) = labeler.counters();
pr.note(&format!(
"autoindex: --label: {calls} /_decide call(s) for {records} labelled record(s)"
));
}
// Corpus-wide edges (§6.6.2, `EdgeDetector::detect_corpus`): the pass for
// relationships that only exist once EVERY document has been read —
// sharedterm cannot know which words are distinctive until it has seen the
// whole run. It runs after Phase B for the same reason per-file edges are
// written after their file's nodes: an edge must never precede the docs it
// points at. Skipped when Phase B already failed — that run bails below,
// and edges over a half-read corpus would be edges over a lie.
if let Some(gr) = &graph {
if bulk_errors.lock().unwrap().is_empty() {
pr.phase("graph-corpus", gr.detectors.len() as u64, 0);
// Mail files this run did not re-read still belong to the corpus
// the thread edges are a function of. Their message nodes come
// back from the index BEFORE the corpus pass, so the pass resolves
// over every message, not over the ones this invocation read.
let reread: std::collections::HashSet<&str> =
todo_set.iter().map(|&i| files[i].rel.as_str()).collect();
let index_of_slug: HashMap<&str, &str> = ds_rt
.iter()
.map(|(slug, rt)| (slug.as_str(), rt.index.as_str()))
.collect();
let carried = match carry_over_unread_mail(
&es,
gr,
&index_of_slug,
&reread,
journal_interrupted || swept_excluded || swept_membership,
) {
Ok(carried) => carried,
Err(e) => {
bulk_errors.lock().unwrap().push(format!(
"carry over un-re-read mail for thread edges: {e:#}"
));
CarriedMail::default()
}
};
if carried.messages > 0 {
pr.note(&format!(
"graph: {} message(s) of {} mail file(s) this run did not re-read were \
loaded back from the index so reply edges resolve over the whole corpus",
carried.messages,
carried.rels.len()
));
}
let mut drafts = Vec::new();
for det in &gr.detectors {
det.detect_corpus(&gr.corpus, &mut drafts);
pr.item_done(0);
}
// The edges of carried files that STILL hold, by id. Anything live
// under those files that is not in here was superseded.
let carried_keep: std::collections::HashSet<String> = drafts
.iter()
.filter(|d| {
d.edge_type == detect::emailthread::REPLIES_TO
&& carried.rels.contains(&d.src_file)
&& d.src != d.dst
})
.map(|d| detect::edge_id(&d.src, d.edge_type, &d.dst, d.valid_at_ms))
.collect();
if !drafts.is_empty() {
let out = detect::assemble(&drafts, &gr.edges_index, gr.created_at_ms);
gr.self_dropped
.fetch_add(out.self_dropped, Ordering::Relaxed);
let mut send_err: Option<String> = None;
let mut buf: Vec<u8> = Vec::new();
for edge in &out.edges {
buf.extend_from_slice(&edge.ndjson);
if buf.len() >= bulk_cut
&& record_bulk_outcome(
&es,
std::mem::take(&mut buf),
&rejected_records,
&bulk_errors,
&mut send_err,
)
{
break;
}
}
if send_err.is_none() && !buf.is_empty() {
record_bulk_outcome(&es, buf, &rejected_records, &bulk_errors, &mut send_err);
}
match send_err {
Some(e) => bulk_errors
.lock()
.unwrap()
.push(format!("write corpus-wide graph edges: {e}")),
None => {
let mut written = gr.written.lock().unwrap();
for edge in &out.edges {
*written.entry(edge.detector).or_default() += 1;
}
}
}
}
// AFTER the new edges are written, never before: a crash between
// the two leaves a superseded edge live for one more run, not a
// reply with no edge at all.
if !carried.rels.is_empty() && bulk_errors.lock().unwrap().is_empty() {
let rels: Vec<&str> = carried.rels.iter().map(String::as_str).collect();
match detect::invalidate_edges_except(
&es,
&gr.edges_index,
detect::emailthread::REPLIES_TO,
&rels,
&carried_keep,
gr.created_at_ms,
) {
Ok(n) => {
gr.invalidated.fetch_add(n, Ordering::Relaxed);
}
Err(e) => bulk_errors
.lock()
.unwrap()
.push(format!("invalidate superseded reply edges: {e:#}")),
}
}
}
}
let bulk_errs = bulk_errors.into_inner().unwrap();
if !bulk_errs.is_empty() {
// A dead node already names itself, the connect error, and the
// command that resumes (#2177). The generic bulk wrap would bury
// that under "fix the embedding configuration".
if let Some(down) = bulk_errs.iter().find(|e| esclient::is_node_down_report(e)) {
anyhow::bail!("{down}");
}
// `bulk_errors` keeps only the first five distinct errors, so without
// the counter the operator cannot tell one refused document from ten
// thousand. That is the whole reason backend rejections are counted
// apart from parser junk: this is the only place the number is ever
// reported, because a run that gets here writes no run document and
// no map.
let rejected = rejected_records.load(Ordering::Relaxed);
let scale = if rejected > 0 {
format!(" The backend refused {rejected} record(s).")
} else {
String::new()
};
anyhow::bail!(
"autoindex stopped with bulk/backend failures: {}.{} Failed source files were not \
journaled complete; fix the reported server or embedding configuration and rerun \
the same command to resume safely",
bulk_errs.join(" | "),
scale
);
}
// ── finalize: refresh, verify, correlate, catalog ────────────────────
//
// This block was 47-64% of every measured run and emitted NOTHING between
// the last phase-B line and the final summary (#241 §1). Its work is fully
// countable before each loop starts, so it is reported like any other
// phase — split into named sub-phases because the mix of one-shot refreshes
// and per-dataset round trips has no single honest denominator.
// #2234: one wildcard `POST /{prefix}-*/_refresh` made this phase a single
// request with denominator 1. The server refreshed the matches one index
// at a time, so a large index with a segment merge in progress held the
// whole call (and this phase printed nothing until it returned). Refresh
// each index this run wrote, name it on the bar while the request is in
// flight, and do not retry a timeout five more times. The server refreshes
// a multi-index target concurrently; one index here is one request so the
// wait, if there is one, is that index's own budget.
pr.phase(
"finalize-refresh",
plan.datasets.len() as u64 + graph.is_some() as u64,
0,
);
let mut refresh_failures: Vec<String> = Vec::new();
for dataset in &plan.datasets {
let _waiting = pr.file(&dataset.index, 0);
if let Err(error) = es.refresh_once(&dataset.index) {
refresh_failures.push(format!("{}: {error:#}", dataset.index));
}
}
// The dot-prefixed edges index is outside the {prefix}-* pattern.
if let Some(gr) = &graph {
let _waiting = pr.file(&gr.edges_index, 0);
if let Err(error) = es.refresh_once(&gr.edges_index) {
refresh_failures.push(format!("{}: {error:#}", gr.edges_index));
}
}
if !refresh_failures.is_empty() {
// #1635: swallowing a refresh failure (`.ok()`) turned it back into a
// green run whose documents were not all refreshed. Name every index
// that did not refresh. Documents already written stay indexed.
anyhow::bail!(
"finalize-refresh failed for {} index(es): {}. Documents already written stay \
indexed and rerunning the same command resumes",
refresh_failures.len(),
refresh_failures.join(" | ")
);
}
// live per-dataset counts + time ranges (every claim traces to a run)
pr.phase("finalize-count", plan.datasets.len() as u64, 0);
let mut ds_counts: HashMap<String, u64> = HashMap::new();
let mut ds_timerange: HashMap<String, (Option<String>, Option<String>)> = HashMap::new();
// A count that did not answer is not a zero. `unwrap_or(0)` used to
// turn a timeout, a 500, or a `timed_out` size:0 page into "0 live
// documents", and the gate below then aborted a run whose records
// were already journaled (#195's last resort, fired on the wrong
// input). Unknown counts skip the gate and are named in the summary.
let mut count_unknown: Vec<String> = Vec::new();
for d in &plan.datasets {
let _counted = pr.file(&d.index, 0);
match es.count(&d.index) {
Ok(cnt) => {
ds_counts.insert(d.slug.clone(), cnt);
}
Err(error) => {
count_unknown.push(format!("{}: {error:#}", d.index));
}
}
if let Some(t) = &d.time_field {
if let Ok(range) = dataset_time_range(&es, &d.index, t) {
ds_timerange.insert(d.slug.clone(), range);
}
}
}
// ── zero-live verification gate (#195) ───────────────────────────────
//
// The journal's completed files claim records were made visible; the
// live counts above are what the server actually answers with. When the
// journal says records landed but ZERO documents are live across every
// dataset index, the run must not report success: the user (or agent)
// would be left with green, mapped, empty indices and no way to tell
// "the corpus has no match" from "nothing was ever written". This is
// the last-resort catch for any rejection path the per-bulk
// classification does not recognise.
let (files_done_journaled, journal_records, left_empty) = {
let journal = journal_mx.lock().unwrap();
let left_empty = datasets_left_empty(&plan, &journal.done, &ds_counts, &excluded_file_keys);
// #2314: a file swept because it left the folder is still in
// `journal.done` until the next plan write forgets to republish it.
// Those records are supposed to be gone. Counting them made a folder
// that had just been emptied look like a write that never landed.
let mut files_done_journaled = 0usize;
let mut journal_records = 0u64;
for (key, done) in &journal.done {
if plan.files.contains_key(key) && !excluded_file_keys.contains(key) {
files_done_journaled += 1;
journal_records += done.records;
}
}
(files_done_journaled, journal_records, left_empty)
};
let live_records: u64 = ds_counts.values().sum();
if !count_unknown.is_empty() {
pr.warn(&format!(
"finalize-count: {} dataset index(es) did not answer a count, so the \
all-indices zero-live check was not applied. Independently confirmed \
empty datasets are still checked. The journal records {journal_records} \
record(s). {}",
count_unknown.len(),
count_unknown.join(" | ")
));
} else if journal_records > 0 && live_records == 0 {
// Typed, not `bail!`: a caller that composes this pipeline can only
// tell "the journal outlived its destination" from "the server
// rejected our writes" if the condition carries a type. `xerj brain`
// downcasts it (brain.rs) to offer the in-place rebuild instead of
// printing this text raw. Peer precedent for classifying a
// recoverable condition rather than folding it into a generic error:
// redb's `Database::do_repair` returns `DatabaseError::RepairAborted`
// as its own variant (redb/src/db.rs:994, Apache-2.0/MIT) so the
// caller can distinguish it from ordinary corruption.
return Err(ZeroLiveVerificationError {
journal_records,
files_done_journaled,
dataset_indices: plan.datasets.len(),
state_dir: state_dir.display().to_string(),
}
.into());
}
if !left_empty.is_empty() {
// A confirmed empty target still matters when another count is unknown.
// This is not evidence that the entire destination was wiped.
let named: Vec<String> = left_empty
.iter()
.map(|d| match d.records {
Some(records) => format!(
"{} ({} record(s) from {} file(s))",
d.index, records, d.files
),
None => format!(
"{} ({} contributing file(s); record count not attributable per dataset)",
d.index, d.files
),
})
.collect();
anyhow::bail!(
"autoindex verification failed: {} of the {} dataset index(es) hold 0 live \
documents although completed files have journaled records and every target \
of those files returned zero: {}. Counts from files shared by several \
datasets cannot be assigned to a particular target. Other datasets may be \
live or unverified; the run is not reported as indexed. Check server-side \
write refusals and whether the target indices were deleted. Journal \
state dir: {}. Fix the cause, then rerun with --fresh to re-index from scratch",
left_empty.len(),
plan.datasets.len(),
named.join(", "),
state_dir.display()
);
}
// correlations
let mut key_corrs: Vec<correlate::KeyCorr> = Vec::new();
if let Some(stats) = &key_stats {
let cands = correlate::candidates(stats, &plan.datasets);
key_corrs = correlate::key_overlaps(&cands);
// One live query per candidate overlap, and the bound is known before
// the loop starts — `phase=finalize-correlate items=37/135` needs no
// new bookkeeping at all (#241 §8).
pr.phase("finalize-correlate", key_corrs.len() as u64, 0);
for c in key_corrs.iter_mut() {
let _query = pr.file(
&format!("{}.{} ~ {}.{}", c.a_slug, c.a_field, c.b_slug, c.b_field),
0,
);
correlate::confirm(&es, c, 20).ok();
}
// keep only live-confirmed overlaps in the report
key_corrs.retain(|c| c.confirmed.map(|(n, _)| n > 0).unwrap_or(false));
} else {
pr.note("(resumed run: key-overlap correlations kept from the original run's catalog)");
}
let timed: Vec<&PlanDataset> = plan
.datasets
.iter()
.filter(|d| d.time_field.is_some())
.collect();
pr.phase("finalize-histogram", timed.len() as u64, 0);
let mut series = Vec::new();
for d in timed {
if let Some(t) = &d.time_field {
let _query = pr.file(&d.index, 0);
if let Ok(Some(s)) = correlate::fetch_histogram(&es, &d.slug, &d.index, t) {
series.push(s);
}
}
}
let time_corrs = correlate::time_alignment(&series);
// ── catalog write ────────────────────────────────────────────────────
// Alias IDs changed as identity evolved. Remove by logical path first so
// catalogs created by any previous identity scheme cannot survive beside
// the one current alias document. One CHUNK of paths per candidate walk —
// see [`alias_sweep_query`] for why the query stays unscoped, and
// [`sweep_duplicate_aliases`] for where the corpus scope is applied instead.
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;
// #905: candidates at this corpus's duplicate paths that name no corpus and
// are not this corpus's own reconstructed ids. Left in place, and reported.
let mut stranded_aliases: Vec<String> = Vec::new();
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) = sweep_duplicate_aliases(
&es,
&cfg.prefix,
chunk,
&own_unprefixed_alias_ids,
&mut stranded_aliases,
) {
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(¬e);
}
}
for note in stranded_alias_notes(&stranded_aliases) {
pr.note(¬e);
}
let mut cat_buf: Vec<u8> = Vec::new();
let push_doc = |id: &str, doc: &Value, buf: &mut Vec<u8>| {
let action = json!({"index": {"_index": catalog::CATALOG_INDEX, "_id": id}});
buf.extend_from_slice(action.to_string().as_bytes());
buf.push(b'\n');
buf.extend_from_slice(doc.to_string().as_bytes());
buf.push(b'\n');
};
for id in &stale_alias_ids {
let action = json!({"delete": {"_index": catalog::CATALOG_INDEX, "_id": id}});
cat_buf.extend_from_slice(action.to_string().as_bytes());
cat_buf.push(b'\n');
}
// Junk/skipped files that left the corpus (#238). Deletes lead the buffer
// so a key that is re-reported in the same run — a junk file whose bytes
// changed, a legacy plan key rewritten under the current scheme — is
// deleted before its replacement document is indexed, never after.
let mut swept_junk_keys: Vec<&str> = stale_junk_keys.iter().map(String::as_str).collect();
swept_junk_keys.sort_unstable();
for key in &swept_junk_keys {
let action = json!({"delete": {
"_index": catalog::CATALOG_INDEX,
"_id": catalog::file_id(&cfg.prefix, key),
}});
cat_buf.extend_from_slice(action.to_string().as_bytes());
cat_buf.push(b'\n');
}
// #381/#759: the per-file record cap dropped these files' tails. Report them
// by name (never silent) so a genuinely large legitimate document is visible.
let truncated = truncated_files.into_inner().unwrap();
note_truncated_files(&pr, &truncated);
// dataset docs
let mut junk_records_by_run: u64 = junk_records.load(Ordering::Relaxed);
let (dataset_stats, durable_junk_records) = {
let journal = journal_mx.lock().unwrap();
let stats = durable_dataset_stats(&plan, &journal.done);
// One definition of "junk records" per map. The dataset docs below
// report the durable per-file commits, so the run doc must too:
// reporting the invocation-local counter there made a no-op resume
// publish `junk_records_total: 0` next to dataset docs that showed
// the real number, in the same `xerj autoindex map` output. The
// per-dataset values are this same total attributed to each file's
// first assigned dataset, so they sum back to it for every file the
// frozen plan still describes.
let durable_junk: u64 = journal.done.values().map(|done| done.junk).sum();
(stats, durable_junk)
};
for d in &plan.datasets {
let sample_queries = catalog::build_sample_queries(d, &key_corrs);
let mut notes = Vec::new();
let durable = dataset_stats.get(&d.slug).copied().unwrap_or_default();
let dropped = durable.dropped;
if dropped > 0 {
notes.push(format!(
"{dropped} field values could not be coerced to the inferred types and were dropped (records still indexed)"
));
}
if let Some(g) = &d.group {
notes.push(format!("source table: {g}"));
}
for s in &d.specs {
for n in &s.notes {
notes.push(format!("{}: {}", s.name, n));
}
}
// formats incl gz flag
let mut formats: Vec<String> = plan
.files
.values()
.filter(|fa| fa.assignments.iter().any(|(_, s)| s == &d.slug))
.map(|fa| {
if fa.gzip {
format!("{}(gzip)", fa.family)
} else {
fa.family.clone()
}
})
.collect();
formats.sort();
formats.dedup();
let (tmin, tmax) = ds_timerange.get(&d.slug).cloned().unwrap_or((None, None));
if !ds_counts.contains_key(&d.slug) {
notes.push(
"record_count unavailable: the node did not answer a count, so 0 here is not a measurement"
.to_string(),
);
}
let (id, doc) = catalog::dataset_doc(&catalog::DatasetDocInput {
prefix: &cfg.prefix,
pd: d,
record_count: *ds_counts.get(&d.slug).unwrap_or(&0),
junk_records: durable.junk,
bytes: durable.bytes,
file_count: d.file_count,
formats,
time_min: tmin,
time_max: tmax,
sample_queries,
notes,
run_id: &run_id,
});
push_doc(&id, &doc, &mut cat_buf);
}
// file docs — indexed (from journal) + junk/skipped (from plan + this run)
//
// The same pass produces this path's code/AST coverage (`CodeCoverage`):
// the journal's completions are the corpus, not just this invocation's
// slice, so a resume reports what is live rather than what it re-parsed.
let mut code_coverage = CodeCoverage::default();
let mut completed_keys: HashSet<String> = HashSet::new();
// Format strings of files this run actually indexed. The family warning
// uses the same set the catalog file docs do, including deletions left out.
let mut indexed_formats: Vec<String> = Vec::new();
{
let j = journal_mx.lock().unwrap();
for fd in j.done.values() {
// A swept deletion stays in an older file_done until
// `file_removed` replays. Do not advertise it (#2314).
if deleted_file_keys.contains(&fd.file_key) {
continue;
}
completed_keys.insert(fd.file_key.clone());
let current_path = plan
.files
.get(&fd.file_key)
.map(|assignment| assignment.rel.as_str())
.unwrap_or(&fd.path);
let fmt = plan
.files
.get(&fd.file_key)
.map(|fa| {
if fa.gzip {
format!("{}(gzip)", fa.family)
} else {
fa.family.clone()
}
})
.unwrap_or_else(|| "unknown".into());
code_coverage.observe(&fmt, fd.records);
indexed_formats.push(fmt.clone());
let (id, doc) = catalog::file_doc(
&cfg.prefix,
&fd.file_key,
current_path,
&fmt,
"indexed",
None,
fd.records,
fd.junk,
fd.bytes,
&run_id,
);
push_doc(&id, &doc, &mut cat_buf);
}
}
let extra = extra_junk.into_inner().unwrap();
let mut all_junk: Vec<&JunkFile> = plan
.junk_files
.iter()
.filter(|junk| !stale_junk_keys.contains(&junk.file_key))
.collect();
all_junk.extend(extra.iter());
all_junk.extend(new_unplanned.iter());
// Disjointness from the journal completions above is ENFORCED here, not
// merely asserted in a comment: `catalog::file_doc` derives its `_id` from
// the file key alone, so a junk entry for a file that also reached
// `file_done` is a second document with an id the completion already used
// — and the bulk applies them in order, so the junk one wins. A file that
// indexed N records would be reported in the catalog as status "junk" with
// records 0. See `shadowed_junk_entries`.
let shadowed = shadowed_junk_entries(&all_junk, &completed_keys);
// Debug builds stop on the producer's defect; release builds keep the
// truthful document and say what they dropped.
debug_assert!(
shadowed.is_empty(),
"junk entry for a file that reached file_done: {:?}",
shadowed.iter().map(|jf| &jf.rel).collect::<Vec<_>>()
);
if !shadowed.is_empty() {
// Not fatal: the completion document is the correct one and it is
// already staged, so dropping the junk entry restores the truth. It is
// still a defect in whichever producer emitted it, so say so.
pr.note(&format!(
"internal: {} junk entr(ies) named a file that also completed and \
were dropped so the catalog keeps the indexed record: {}",
shadowed.len(),
shadowed
.iter()
.take(REFUSAL_LIST_CAP)
.map(|jf| jf.rel.as_str())
.collect::<Vec<_>>()
.join(", ")
));
all_junk.retain(|jf| !completed_keys.contains(&jf.file_key));
}
// #2370: indexed formats and the junk list are both final here. Stale-plan
// skips stay in `all_junk` for the catalog and are ignored by the warning.
let family_warnings = family_junk::warnings(
indexed_formats.iter().map(String::as_str),
all_junk.iter().copied(),
);
let family_warning_lines: Vec<String> = family_warnings
.iter()
.map(|warning| warning.line())
.collect();
// Counted now: every later reader of this number outlives the borrows
// `all_junk` holds on `plan` and `new_unplanned`, which the durable
// junk-plan update below mutates.
//
// #2076 / #346: files the frozen plan predates stay in this list so the
// catalog row can be swept when they leave the folder (#238), but they are
// not junk. `files_junk` is unusable input only; `skipped_appeared` is the
// stale-plan count, on the first resume and on every resume after it.
let skipped_appeared = all_junk
.iter()
.filter(|jf| is_stale_resume_skip(jf))
.count();
let junk_file_count = all_junk.len() - skipped_appeared;
// Owned here: the resume-plan update below mutates the junk list these
// borrow. The count stays `skipped_appeared`; the summary names the paths
// (#2372).
let appeared_paths = stale_resume_appeared_paths(&all_junk);
debug_assert_eq!(appeared_paths.len(), skipped_appeared);
let appeared_lines = stale_resume_summary_lines(&appeared_paths);
let appeared_json = stale_resume_summary_json(&appeared_paths);
let unextracted_archives = unextracted_archive_lines(&all_junk);
for jf in &all_junk {
code_coverage.observe(&jf.format, 0);
let (id, doc) = catalog::file_doc(
&cfg.prefix,
&jf.file_key,
&jf.rel,
&jf.format,
&jf.status,
Some(&jf.reason),
0,
0,
jf.bytes,
&run_id,
);
push_doc(&id, &doc, &mut cat_buf);
junk_records_by_run += 0; // junk FILES tracked separately from junk records
}
for duplicate in &plan.duplicate_files {
let (id, doc) = catalog::duplicate_file_doc(
&cfg.prefix,
&duplicate.file_key,
&duplicate.rel,
&duplicate.path_id,
&duplicate.duplicate_of,
duplicate.bytes,
&run_id,
);
push_doc(&id, &doc, &mut cat_buf);
}
for c in &key_corrs {
let mut v = c.to_value();
v["run_id"] = json!(run_id);
push_doc(&c.id(&cfg.prefix), &v, &mut cat_buf);
}
for (i, tc) in time_corrs.iter().enumerate() {
// Prefix-scoped for the same cross-corpus reason as `corr:` above (#673):
// time correlations are keyed by dataset slugs and share the catalog.
let i_fallback = i.to_string();
let id = tcorr_id(
&cfg.prefix,
tc.get("a_dataset").and_then(|v| v.as_str()).unwrap_or(""),
tc.get("b_dataset")
.and_then(|v| v.as_str())
.unwrap_or(&i_fallback),
);
let mut v = tc.clone();
v["run_id"] = json!(run_id);
push_doc(&id, &v, &mut cat_buf);
}
let wall = t0.elapsed().as_secs_f64();
let (started, summary_generated_at) =
invocation_report_timestamps(invocation_started, chrono::Utc::now());
let total_records: u64 = ds_counts.values().sum();
// #904: ingest throughput, so the cost of a slow embedder (#366) is
// visible in the summary itself rather than something an operator has
// to derive by hand from the elapsed line. The numerator is what THIS
// run submitted. Dividing the live catalog count by `wall` makes a
// no-op resume claim tens of thousands of docs/sec. `wall` can be 0.0
// on a sub-millisecond run; reporting 0 docs/sec there is more honest
// than a divide-by-zero `inf`.
let docs_per_sec = ingest_docs_per_sec(records_total.load(Ordering::Relaxed), wall);
// Run-summary honesty (§6.6.4): what the detectors wrote AND what they
// could not resolve — a dangling [[link]] is a fact about the corpus, not
// something to swallow.
let graph_summary = graph.as_ref().map(|gr| {
let written = gr.written.lock().unwrap();
let mut counters = detect::DetectorCounters::default();
for det in &gr.detectors {
let c = det.counters();
counters.unresolved += c.unresolved;
counters.ambiguous += c.ambiguous;
counters.capped += c.capped;
}
let raw = gr.href_raw.counters();
counters.unresolved += raw.unresolved;
counters.ambiguous += raw.ambiguous;
let by_detector: Map<String, Value> = written
.iter()
.map(|(tag, n)| ((*tag).to_string(), json!(n)))
.collect();
json!({
"brain": gr.brain,
"edges_index": gr.edges_index,
"edges_written": written.values().sum::<u64>(),
"by_detector": by_detector,
"edges_unresolved": counters.unresolved,
"edges_ambiguous": counters.ambiguous,
"edges_capped": counters.capped,
"edges_self_dropped": gr.self_dropped.load(Ordering::Relaxed),
"edges_invalidated": gr.invalidated.load(Ordering::Relaxed),
})
});
// A resume intentionally reuses and upserts the durable run id. Timing
// and detector counters therefore describe this latest invocation,
// while corpus descriptors describe the durable live run state.
// What the object store was asked for, when the source was one. Part of the
// run document because "how much did indexing this bucket cost" has to be
// answerable after the fact, not only from a terminal that has scrolled.
let object_source_summary = object_report.as_ref().map(|report| {
json!({
"objects_listed": report.objects_listed,
"objects_admitted": report.admitted,
"objects_downloaded": report.downloaded,
"bytes_downloaded": report.bytes_downloaded,
"objects_unchanged_not_downloaded": report.unchanged,
"objects_removed_locally": report.removed,
"objects_vanished_between_list_and_get": report.vanished,
"objects_without_etag": report.without_etag,
"list_requests_class_a": report.list_requests,
"get_requests_class_b": report.read_requests,
"transfer_ms": report.elapsed_ms,
"keys_skipped_by_rule": report
.skipped
.iter()
.map(|(rule, count)| (rule.clone(), json!(count)))
.collect::<Map<String, Value>>(),
})
});
let mut run_doc = json!({
"doc_kind": "run",
"run_id": run_id,
"root": root_str,
"object_source": object_source_summary,
"url": cfg.url,
"prefix": cfg.prefix,
"started": started,
"summary_generated_at": summary_generated_at,
"invocation_telemetry_scope": "latest_invocation_of_durable_run",
"files_total": paths_discovered,
"unique_content_files": files.len(),
"files_indexed": journal_mx.lock().unwrap().done.len(),
"duplicate_files": plan.duplicate_files.len(),
"files_junk": junk_file_count,
// The junk a user can act on, by name and with the command to run —
// so a `--json` caller sees why a Takeout `.zip` indexed nothing
// without a second command (`unextracted_archive_lines`).
"unextracted_archives": unextracted_archives,
"records_total": total_records,
// Two numbers, one definition each, neither of them overlapping.
//
// `junk_records_total` is the durable corpus descriptor: the same
// definition as every dataset doc's `junk_records`, summed over every
// `FileDone` in the journal. It survives a no-op resume.
//
// `junk_records_this_run` is the same *kind* of failure narrowed to
// the files this invocation actually parsed. It is the NARROWER of the
// two, not the wider: every file counted here also committed a
// `FileDone` that the total sums. On an unchanged resume it reads 0
// while the total stays non-zero — which is the whole defect this
// change exists to fix, seen from the other side.
//
// Backend rejections are deliberately absent. They are a different
// failure, and they can never be reported here anyway: a per-item
// rejection populates `bulk_errors`, which aborts the run above,
// before this document exists. Publishing a
// `records_rejected_by_backend` field would ship a number that is
// provably always 0 — see `record_bulk_outcome` and
// `backend_rejected_records_abort_the_run_before_any_map_is_written`.
"junk_records_total": durable_junk_records,
"junk_records_this_run": junk_records_by_run,
// This-run submission accounting (#195): what THIS invocation sent
// and had accepted, vs `records_total` above which is the live
// server-side count. A healthy run keeps these consistent; a
// mismatch is visible without reading a server log.
"files_submitted_this_run": files_done.load(Ordering::Relaxed),
"records_submitted_this_run": records_total.load(Ordering::Relaxed),
"wall_seconds": (wall * 10.0).round() / 10.0,
"docs_per_sec": (docs_per_sec * 10.0).round() / 10.0,
"workers": cfg.workers,
// The whole resource decision, so a run can be explained after the
// fact from its own summary rather than from the machine it ran on.
// `scan_workers` is the width phase A actually ran at — see the
// first-call-wins note at the top of this function; a requested width
// that lost that race would make the summary a record of an intention
// rather than of a run.
"scan_workers": scan_threads,
"pdf_workers": cfg.pdf_workers,
"bulk_mb": cfg.bulk_mb,
"cores_available": xerj_common::resource::cores(),
// `null` on a platform with no RAM probe — the summary reports what the
// run actually knew, never a stand-in number (#240).
"memory_safe_zone_mb": xerj_common::resource::memory_safe_zone_bytes()
.map(|b| b / (1024 * 1024)),
// What the server's backpressure did to the offered load. A final
// limit below `workers` means this run met real congestion and
// answered it, which is the difference between a slow run and a run
// that was making the machine worse (#240 §8).
"bulk_concurrency_final": es.bulk_concurrency_limit(),
"bulk_congestion_events": es.bulk_congestion_events(),
"resource_notes": cfg.resource_notes,
// #768: mirror the wrong-node warning here too (null when it did not
// fire), so a --json consumer sees the same safety signal stderr does.
"xerj_url_note": cfg.xerj_url_note,
"semantic": !cfg.no_semantic,
"pdf_extraction_reuse": pdf_spool_budget.report(),
});
if let Some(g) = &graph_summary {
run_doc["graph"] = g.clone();
}
// #929: a corpus that lacks a dataset says so in its own run document.
for (key, value) in plan.refused_run_fields() {
run_doc[key] = value;
}
// Appended rather than written into the literal above: `serde_json::json!`
// recurses once per key and that literal is already 30 deep — the same
// reason `catalog::catalog_mapping` inserts its tail fields.
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);
}
// #346: present only when files appeared after the plan was frozen, so a
// healthy run document is unchanged and any reader finding this key knows
// the index is incomplete for that many files (distinct from unparseable
// `junk`).
if skipped_appeared > 0 {
run_doc["skipped_appeared"] = json!(skipped_appeared);
}
// #2372: additive. `skipped_appeared` stays the count. These name the
// first paths, how many were not listed, and the `--fresh` recovery.
// Absent when nothing appeared, including `skipped_appeared_not_listed`
// when every path fit in the summary.
for (key, value) in &appeared_json {
run_doc[key.as_str()] = value.clone();
}
// #2314: present only when this run deleted documents for files that left
// the folder. A later unchanged rerun does not set it, so exit 0 there is
// a real no-op and not another removal.
let files_removed = if swept_membership {
deleted_file_keys.len() as u64
} else {
0
};
if files_removed > 0 {
run_doc["files_removed"] = json!(files_removed);
}
// #2056: the exit-3 headline stays one line. The paths themselves are a
// separate list, capped, with the reason. Present only when something
// was skipped, so a clean run document is unchanged.
if let Some(skipped) = skipped_json(&all_junk) {
run_doc["skipped"] = skipped;
}
// #2336: present only when every PDF failed to start the isolated parser.
// A single corrupt PDF stays ordinary junk and does not set the field.
let pdf_worker_unavailable = plan.pdf_worker_unavailable_count();
if let Some(n) = pdf_worker_unavailable {
run_doc["pdf_worker_unavailable"] = json!(n);
}
// #2370: omitted when no family tripped the threshold, so a clean run
// document keeps every field it had. Added, not renamed.
if !family_warnings.is_empty() {
run_doc["family_junk_warnings"] = serde_json::to_value(&family_warnings)
.expect("family junk warnings are strings and counts");
}
// Owned lines: the resume-plan update below mutates `plan.junk_files`,
// which `all_junk` borrows. The summary prints these after that update.
let skip_lines = skipped_lines(&all_junk);
push_doc(&format!("run:{run_id}"), &run_doc, &mut cat_buf);
if !cat_buf.is_empty() {
// #955: one document per file — this body grows with the corpus, and
// it used to go out as ONE request whatever `--bulk-mb` said. Past the
// engine's 50,000-action limit the answer is a single 413 item, which
// is not a `server_error`, so the check below let a run report success
// with NO catalog written. Windowed like every other bulk.
let outcome = es
.bulk_windowed(cat_buf, cfg.bulk_mb << 20)
.context("write catalog")?;
// The catalog is the data map every later `map`/`status`/agent query
// reads; a rejected catalog bulk (e.g. a write block that engaged
// mid-run) must not be swallowed into a "success" exit (#195).
if outcome.server_errors > 0 {
anyhow::bail!(
"write catalog: bulk backend failed for {} item(s): {}. Fix the reported \
server condition and rerun the same command",
outcome.server_errors,
outcome
.first_server_error
.as_deref()
.unwrap_or("unknown server error")
);
}
// A refused catalog document is a dataset or file `xerj autoindex map`
// will not show. Warning and exiting 0 left a ~210-index batch with
// an empty catalog and no signal to rerun (#1977). Same rule as the
// generation path's `check_bulk_outcome`: a catalog item the server
// refused fails the run, before the journal is finished, so the same
// command rewrites it.
if outcome.item_errors > 0 {
anyhow::bail!(
"write catalog: the server refused {} catalog document(s): {}. The data indices \
are already indexed, but `xerj autoindex map` would be missing those entries. \
Rerun the same command to rewrite the catalog",
outcome.item_errors,
outcome.first_error.as_deref().unwrap_or("no reason given")
);
}
// Refresh is what makes the rows searchable. Swallowing a failure
// (`.ok()`) reported success over a catalog `xerj_map` could not see.
es.refresh(catalog::CATALOG_INDEX)
.context("write catalog: refresh autoindex-catalog so the new rows are searchable")?;
let mut published_ids: Vec<String> = plan
.datasets
.iter()
.map(|dataset| format!("ds:{}:{}", cfg.prefix, dataset.slug))
.collect();
published_ids.push(format!("run:{run_id}"));
require_visible_catalog_rows(&es, &published_ids)?;
}
pr.item_done(0);
// ── durable junk record, written last (#238) ─────────────────────────
//
// Only now is the plan allowed to claim what the catalog holds: the
// documents above are written and the swept ones deleted. A failed
// catalog bulk bailed out before this point with the plan untouched, so
// the next run recomputes the identical additions and removals and
// retries them — losing a record here is what makes a document immortal.
//
// Post-freeze skipped files are re-derived on every rerun, so this
// converges: once they are in the plan they are `planned_junk`, the
// additions are empty, and no further plan record is appended.
if !new_unplanned.is_empty() || !stale_junk_keys.is_empty() {
plan.junk_files
.retain(|junk| !stale_junk_keys.contains(&junk.file_key));
plan.junk_files.append(&mut new_unplanned);
journal_mx
.lock()
.unwrap()
.write_plan(&plan)
.context("record junk/skipped catalog entries in the resume plan")?;
}
journal_mx.lock().unwrap().finish(&run_doc)?;
// ── summary ──────────────────────────────────────────────────────────
let junk_total_records = junk_records.load(Ordering::Relaxed);
// Exit 3 means "completed, and something about this run is recorded
// rather than fatal" (`cli.rs` EXIT CODES). Junk is the everyday case.
// Backend rejections are not consulted and must not be: a rejected item
// aborts the run with 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.
//
// A failed alias sweep and a swept deletion land here too, on 3 rather
// than on a code of their own: inventing another success code would break
// every caller that already branches on 0/3. The `reason` is what tells
// them apart. A removal is not exit 0: that is what the run printed when
// the documents stayed live (#2314). A PDF worker that could not start is
// exit 1: exit 3 would call a missing PDF family success (#2336).
let code = if pdf_worker_unavailable.is_some() {
1
} else if junk_total_records > 0
|| junk_file_count > 0
|| alias_sweep_error.is_some()
|| skipped_appeared > 0
|| files_removed > 0
{
3
} else {
0
};
if cfg.json {
println!("{run_doc}");
} else if !cfg.quiet {
println!(
"{}",
outcome_headline(
code,
junk_file_count as u64,
junk_total_records,
alias_sweep_error.is_some(),
skipped_appeared as u64,
pdf_worker_unavailable,
files_removed,
)
);
for line in &family_warning_lines {
println!("{line}");
}
for line in &appeared_lines {
println!("{line}");
}
for line in &skip_lines {
println!("{line}");
}
println!(
"{}",
estimate::done_summary_line(
wall,
plan.datasets.len() as u64,
total_records,
plan.duplicate_files.len() as u64,
junk_total_records,
junk_file_count as u64,
docs_per_sec,
)
);
// Indexed-vs-submitted honesty line (#195): the live count against
// what this run actually submitted, so a silent-rejection mismatch
// is visible in the client output alone. Units differ on purpose: a
// source record (e.g. one prose file) can expand to several section
// documents, but submitted records with ZERO live documents is
// always a defect (and fails above, before this line prints).
println!(
"{}",
indexed_vs_submitted_line(
total_records,
records_total.load(Ordering::Relaxed),
files_done.load(Ordering::Relaxed),
)
);
if !unextracted_archives.is_empty() {
println!("not indexed — archives are never opened; extract, then run this command on the extracted folder:");
for line in &unextracted_archives {
println!(" {line}");
}
}
let mut rows: Vec<(&String, u64)> = plan
.datasets
.iter()
.map(|d| (&d.index, *ds_counts.get(&d.slug).unwrap_or(&0)))
.collect();
rows.sort_by_key(|r| std::cmp::Reverse(r.1));
for (idx, cnt) in rows {
println!(" {idx:<40} {cnt:>10} docs");
}
if let Some(g) = &graph_summary {
let by: Vec<String> = g["by_detector"]
.as_object()
.map(|m| m.iter().map(|(tag, n)| format!("{tag} {n}")).collect())
.unwrap_or_default();
println!(
"graph: {} edges → {} ({}); {} unresolved, {} ambiguous, {} capped, {} self-dropped, {} invalidated",
g["edges_written"],
g["edges_index"].as_str().unwrap_or(""),
if by.is_empty() { "no detections".to_string() } else { by.join(", ") },
g["edges_unresolved"],
g["edges_ambiguous"],
g["edges_capped"],
g["edges_self_dropped"],
g["edges_invalidated"],
);
}
println!(
"{}",
next_hint(
&cfg.url,
&cfg.prefix,
cfg.api_key.as_deref(),
std::env::var("XERJ_API_KEY").ok().as_deref(),
cfg.api_key_file.as_deref(),
)
);
// This line is where an agent learns how to search. Only printed when
// source code was actually indexed; for a PDF or log corpus it would
// be noise. The text itself is shared with the generated-run printer
// via `code_search_hint` (#1103).
let indexed_code = plan.files.values().any(|fa| fa.family == "code");
if indexed_code {
println!("{}", code_search_hint(&cfg.prefix));
}
// A mixed corpus needs one more thing said out loud. Code volume
// swamps prose on shared vocabulary: in a blind run, a question about
// documentation ("exit code 3") matched WordPress PHP on `exit` and
// `code` and returned nothing but source, costing a wasted round trip.
// The agent worked out the fix itself afterwards — scope the query —
// which is exactly the sort of thing that should not have to be
// rediscovered.
let indexed_prose = plan
.files
.values()
.any(|fa| fa.family.starts_with("txt") || fa.family == "html");
if indexed_code && indexed_prose {
let mut fams: Vec<&str> = plan.files.values().map(|fa| fa.family.as_str()).collect();
fams.sort_unstable();
fams.dedup();
println!("{}", mixed_corpus_hint(&fams));
}
}
// Terminal line, in every progress mode but `none` (which `--quiet`
// selects, and which prints nothing by definition). Exit 3 means
// "completed, some files were unparseable" — success — and an agent reading
// a bare `3` off a silent stream reads failure (#241 §9). Say it in words.
if let Some(warning) = code_coverage.warning() {
pr.note(&warning);
}
let mut done_fields = vec![
("files", files_done.load(Ordering::Relaxed)),
("records", total_records),
("datasets", plan.datasets.len() as u64),
("junk_files", junk_file_count as u64),
];
done_fields.extend(code_coverage.fields());
// #944: present only when the run re-sent items the server answered 429.
if es.bulk_backpressure_retries() > 0 {
done_fields.push(("bulk_retries", es.bulk_backpressure_retries()));
}
// #955: present only when the server refused a request as too large.
if es.bulk_requests_split() > 0 {
done_fields.push(("bulk_splits", es.bulk_requests_split()));
}
// #929: only when it happened, so a whole corpus prints the line it always
// did and one that lost a dataset cannot print the same one.
if !plan.refused_datasets.is_empty() {
done_fields.push(("datasets_refused", plan.refused_datasets.len() as u64));
done_fields.push((
"files_refused",
plan.refused_datasets
.iter()
.map(|refusal| refusal.file_keys.len() as u64)
.sum(),
));
}
if alias_sweep_error.is_some() {
done_fields.push((
"catalog_alias_sweep_failures",
alias_sweep_failed.len() as u64,
));
}
// #346: surface files-skipped-because-they-appeared-after-freeze on the
// terminal line, distinct from `junk_files`, so a re-run whose index is
// silently incomplete is visible instead of below the noise floor.
if skipped_appeared > 0 {
done_fields.push(("skipped_appeared", skipped_appeared as u64));
}
// Remainder only. The paths themselves are not `key=value` numbers: a
// path may contain spaces, and readers split the plain `xerj-done` line
// on spaces. They are named on the lines above and in the JSON fields.
if let Some(rest) = appeared_json
.get("skipped_appeared_not_listed")
.and_then(Value::as_u64)
{
done_fields.push(("skipped_appeared_not_listed", rest));
}
if files_removed > 0 {
done_fields.push(("files_removed", files_removed));
}
if dataless_skipped > 0 {
done_fields.push(("skipped_dataless", dataless_skipped));
}
if let Some(n) = pdf_worker_unavailable {
done_fields.push(("pdf_worker_unavailable", n));
pr.note(&pdf_worker_unavailable_note(n));
}
// #2370: same lines as stdout, on the progress stream, including `--quiet`.
for line in &family_warning_lines {
pr.warn(line);
}
if !family_warnings.is_empty() {
done_fields.push(("family_junk_warnings", family_warnings.len() as u64));
}
note_worker_address_space_cap(&pr);
// #2372: immediately before the terminal line, so an agent that reads the
// summary (and not the mid-run note) sees the paths and `--fresh`.
// `--progress json` also gets the fields on the terminal object; the
// plain line stays numeric.
for line in &appeared_lines {
pr.note(line);
}
if !appeared_json.is_empty() {
pr.set_done_json(appeared_json.clone());
}
// #2411: new files absent from a frozen plan need a rebuild. Do not mark
// that stale-plan outcome ok. Other exit-3 outcomes still use their existing
// flags (for example datasets_refused); ok alone is not full coverage.
let complete = pdf_worker_unavailable.is_none() && skipped_appeared == 0;
pr.finish(
complete,
code,
// A worker that cannot start wins the `reason`: exit 3 would call a
// missing PDF family success (#2336). A stale plan is next, because
// junk is the everyday state and `completed-with-junk` is what hid
// those files (#2076). The alias-sweep failure needs an operator,
// and ordinary junk does not.
if pdf_worker_unavailable.is_some() {
PDF_WORKER_UNAVAILABLE_REASON
} else if skipped_appeared > 0 {
STALE_RESUME_PLAN_REASON
} else if alias_sweep_error.is_some() {
ALIAS_SWEEP_FAILED_REASON
} else if files_removed > 0 {
FILES_REMOVED_REASON
} else if code == 3 {
"completed-with-junk"
} else {
"completed"
},
&done_fields,
);
drop(ticker);
Ok((code, Some(run_doc)))
}
/// Dataless placeholders plus files another process holds locked (#2352).
///
/// Both are still on disk. Leaving them out of the inventory makes
/// [`inventory_delta`] call them exclusions and delete documents indexed the
/// last time the bytes could be read. A file that no longer exists is not
/// included: a rerun sweeps it.
fn files_still_present(
dataless: &[walk::FileEntry],
unreadable: &[content::UnreadableSource],
) -> Vec<walk::FileEntry> {
let mut present = dataless.to_vec();
present.extend(
unreadable
.iter()
.filter(|item| item.kind == content::ReadFailureKind::Locked)
.map(|item| item.file.clone()),
);
present
}
/// Keep a locked file that already has a committed digest in the inventory.
///
/// `--no-graph` emits Delete for a content group that is absent from the
/// inventory. The unchanged fast path carries the assignment without opening
/// the file, and the seal hardlinks the previous blob when the size still
/// matches. Graph runs must not call this.
fn carry_locked_priors(inventory: &mut content::Inventory, prior: &Plan) -> Vec<String> {
let mut carried = Vec::new();
let mut remaining = Vec::new();
for item in std::mem::take(&mut inventory.unreadable) {
if item.kind != content::ReadFailureKind::Locked {
remaining.push(item);
continue;
}
let matched = prior.files.iter().find(|(_, assignment)| {
(!item.file.rel_id.is_empty()
&& !assignment.path_id.is_empty()
&& assignment.path_id == item.file.rel_id)
|| assignment.rel == item.file.rel
});
let Some((key, assignment)) = matched else {
remaining.push(item);
continue;
};
let Some(digest) = assignment.content_digest.clone() else {
remaining.push(item);
continue;
};
if inventory.keys.iter().any(|existing| existing == key) {
remaining.push(item);
continue;
}
let key = key.clone();
carried.push(item.file.rel.clone());
inventory.files.push(item.file);
inventory.keys.push(key);
inventory.digests.push(digest);
}
remaining.sort_by(|left, right| left.file.rel.cmp(&right.file.rel));
inventory.unreadable = remaining;
carried.sort();
carried
}
fn note_unreadable(pr: &Progress, unreadable: &[content::UnreadableSource]) {
if unreadable.is_empty() {
return;
}
let absent = unreadable
.iter()
.filter(|item| item.kind == content::ReadFailureKind::Absent)
.count();
let locked = unreadable.len() - absent;
pr.note(&format!(
"autoindex: skipped {} file(s) that could not be read after they were enumerated \
({absent} no longer exist, {locked} held locked by another process)",
unreadable.len()
));
for item in unreadable.iter().take(REFUSAL_LIST_CAP) {
pr.note(&format!(" skipped: {}", item.file.rel));
}
let remaining = unreadable.len().saturating_sub(REFUSAL_LIST_CAP);
if remaining > 0 {
pr.note(&format!(" … and {remaining} more"));
}
}
fn note_kept_locked(pr: &Progress, rels: &[String]) {
if rels.is_empty() {
return;
}
pr.note(&format!(
"autoindex: {} file(s) could not be opened because another process holds them locked; \
the previous generation's copy was kept",
rels.len()
));
for rel in rels.iter().take(REFUSAL_LIST_CAP) {
pr.note(&format!(" kept: {rel}"));
}
let remaining = rels.len().saturating_sub(REFUSAL_LIST_CAP);
if remaining > 0 {
pr.note(&format!(" … and {remaining} more"));
}
}
/// One `skipped` row per file the hash could not open (#2352).
///
/// The key is `axabsent-` plus the path identity, not a content digest. A row
/// already present (a resume) is left as it is.
fn record_unreadable_skips(plan: &mut Plan, unreadable: &[content::UnreadableSource]) -> bool {
let mut added = false;
for item in unreadable {
let key = content::unreadable_file_key(&item.file.rel_id);
if plan.files.contains_key(&key) || plan.junk_files.iter().any(|junk| junk.file_key == key)
{
continue;
}
plan.junk_files.push(JunkFile {
file_key: key,
rel: item.file.rel.clone(),
format: "unknown".into(),
status: "skipped".into(),
reason: content::unreadable_skip_reason(&item.detail, item.kind),
bytes: item.file.size,
});
added = true;
}
if added {
recount_plan_file_counts(plan);
}
added
}
/// The catalog entry for a source file that changed between phase A's digest
/// and phase B's read (#1911).
///
/// That used to land in `bulk_errors`, which aborts the whole run after phase B:
/// one live lock file on Windows stopped a 1,894-file run at ~258 s and left
/// its partial indices and journal for hand cleanup — and every retry met the
/// same still-changing file. It is now one `skipped` file with the reason, the
/// run finishes (exit 3, like any other skipped file), and because the file is
/// never journaled done, the next run picks up whatever it then holds.
fn changed_during_run_junk(
file_key: &str,
rel: &str,
format: &str,
bytes: u64,
error: &anyhow::Error,
) -> JunkFile {
JunkFile {
file_key: file_key.to_string(),
rel: rel.to_string(),
format: format.to_string(),
status: "skipped".into(),
reason: format!(
"changed while this run was reading it, so it was skipped and nothing from it was \
made visible ({error:#}); rerun to index its current content"
),
bytes,
}
}
fn format_str(sn: Option<&Sniffed>) -> String {
match sn {
Some(s) if s.gzip => format!("{}(gzip)", s.family.as_str()),
Some(s) => s.family.as_str().to_string(),
None => "unknown".into(),
}
}
// ─── map subcommand ──────────────────────────────────────────────────────
/// What autoindex and `xerj map` say when the node does not answer.
///
/// A connect error is the common first-run miss (`xerj map` with nothing
/// listening). An auth failure is the opposite — the node is up — so it must
/// not tell the reader to start one.
fn node_ping_failure(url: &str, err: &anyhow::Error) -> String {
if esclient::Es::ping_failure_is_auth(err) {
format!("the node at {url} answered, but authentication failed.\n{err:#}")
} else {
let loopback = loopback_retry_hint(url).unwrap_or_default();
format!(
"no XERJ node reachable at {url} ({err:#})\n\n\
Start one, then re-run this command:\n \
xerj --insecure --data-dir ./.xerj-data &\n\n\
(or point at an existing node with --url / $XERJ_URL){loopback}"
)
}
}
/// #2688 — the client defaults to `http://localhost:9200` while the node binds
/// `127.0.0.1` by default. Where `localhost` resolves to `::1` first (seen on
/// Windows) a running node looks absent, so a `localhost` URL gets the same
/// URL with the IPv4 loopback spelled out. Any other host gets nothing.
fn loopback_retry_hint(url: &str) -> Option<String> {
let mut parsed = reqwest::Url::parse(url).ok()?;
if !parsed.host_str()?.eq_ignore_ascii_case("localhost") {
return None;
}
parsed.set_host(Some("127.0.0.1")).ok()?;
let mut retry = parsed.to_string();
if !url.ends_with('/') && retry.ends_with('/') {
retry.pop();
}
Some(format!(
"\n\nIf a node is running, `localhost` may have resolved to an address it does \
not listen on (it binds 127.0.0.1 by default). Try:\n --url {retry}"
))
}
#[cfg(test)]
mod node_ping_failure_tests {
use super::node_ping_failure;
#[test]
fn an_unreachable_node_gets_the_start_recipe() {
let err = anyhow::anyhow!(
"endpoint unreachable: http://127.0.0.1:9: Connection refused (os error 111)"
);
let msg = node_ping_failure("http://127.0.0.1:9", &err);
assert!(
msg.contains("no XERJ node reachable at http://127.0.0.1:9"),
"{msg}"
);
assert!(
msg.contains("xerj --insecure --data-dir ./.xerj-data"),
"{msg}"
);
assert!(msg.contains("--url"), "{msg}");
assert!(!msg.contains("authentication failed"), "{msg}");
assert!(!msg.contains("may have resolved"), "{msg}");
}
#[test]
fn a_refused_localhost_url_suggests_the_ipv4_loopback() {
let err = anyhow::anyhow!(
"endpoint unreachable: http://localhost:9200: Connection refused (os error 10061)"
);
let msg = node_ping_failure("http://localhost:9200", &err);
assert!(msg.ends_with("--url http://127.0.0.1:9200"), "{msg}");
assert!(
msg.contains("xerj --insecure --data-dir ./.xerj-data"),
"{msg}"
);
// The caller's scheme, case and port are kept.
let msg = node_ping_failure("https://LocalHost:9443", &err);
assert!(msg.ends_with("--url https://127.0.0.1:9443"), "{msg}");
// An auth failure on localhost is not a resolution problem.
let auth = anyhow::anyhow!("GET / failed (HTTP 401)");
let msg = node_ping_failure("http://localhost:9200", &auth);
assert!(!msg.contains("127.0.0.1"), "{msg}");
}
#[test]
fn an_auth_failure_does_not_say_the_node_is_down() {
let err = anyhow::anyhow!("GET / failed (HTTP 401)");
let msg = node_ping_failure("http://127.0.0.1:9200", &err);
assert!(msg.contains("authentication failed"), "{msg}");
assert!(!msg.contains("no XERJ node reachable"), "{msg}");
assert!(!msg.contains("xerj --insecure"), "{msg}");
}
}
fn run_remove(cfg: cli::RemoveCfg) -> Result<i32> {
if let Some(note) = &cfg.xerj_url_note {
eprintln!("autoindex: {note}");
}
// `--quiet` is the indexing gate's "do not prompt" switch. The same rule
// here: a silenced terminal must not ask a question nobody will see.
let prompt = {
use std::io::IsTerminal;
std::io::stdin().is_terminal() && !cfg.quiet
};
let report = remove::execute(remove::RemoveRequest {
url: cfg.url,
api_key: cfg.api_key,
prefix: cfg.prefix,
root: cfg.root,
yes: cfg.yes,
prompt,
state_dir: cfg.state_dir,
uncataloged: cfg.uncataloged,
})?;
println!(
"{}",
serde_json::to_string_pretty(&report.body).unwrap_or_else(|_| report.body.to_string())
);
if !cfg.quiet {
eprintln!("{}", report.summary);
}
Ok(report.exit_code)
}
fn run_map(cfg: MapCfg) -> Result<i32> {
let report_stage = cfg.report.as_ref().map(map_report::prepare).transpose()?;
if let Some(note) = &cfg.xerj_url_note {
eprintln!("autoindex: {note}");
}
let es = Es::new(&cfg.url, cfg.api_key.clone())?;
// The same first-run miss as `xerj search`: nothing is listening, and a
// raw `endpoint unreachable` does not say how to start a node.
if let Err(e) = es.ping() {
anyhow::bail!("{}", node_ping_failure(&cfg.url, &e));
}
let fetch = |query: Value, size: usize, sort: Option<Value>| -> Result<Vec<Value>> {
let mut body = json!({"query": query, "size": size});
if let Some(s) = sort {
body["sort"] = s;
}
let v = es
.search_present(catalog::CATALOG_INDEX, &body)?
.ok_or_else(|| {
anyhow::anyhow!(
"autoindex catalog {} is missing (HTTP 404). {}",
catalog::CATALOG_INDEX,
catalog::MAP_NAMESPACE_HINT
)
})?;
Ok(v.pointer("/hits/hits")
.and_then(|h| h.as_array())
.map(|arr| {
arr.iter()
.filter_map(|h| h.get("_source").cloned())
.collect()
})
.unwrap_or_default())
};
// `--prefix` scoping runs server-side first, so a node holding more
// catalog docs than one fetch returns (500 datasets / 200 correlations /
// 500 runs across every corpus) still answers for the requested corpus.
// The server filter over-approximates (`{prefix}-` also matches a longer
// hyphenated prefix; a phrase on a legacy text-inferred `prefix` matches a
// superset); the exact `catalog::*_matches_prefix` retains below decide.
let scoped_prefix = cfg.prefix.as_deref().map(|p| format!("{p}-"));
let mut ds_must = vec![json!({"term": {"doc_kind": "dataset"}})];
if let Some(slug) = &cfg.dataset {
ds_must.push(json!({"term": {"slug": slug}}));
}
if let Some(sp) = &scoped_prefix {
ds_must.push(json!({"prefix": {"index_name": sp}}));
}
let ds_query = json!({"bool": {"must": ds_must}});
let mut datasets = fetch(ds_query, 500, Some(json!([{"record_count": "desc"}])))?;
if let Some(prefix) = cfg.prefix.as_deref() {
datasets.retain(|d| catalog::dataset_matches_prefix(d, prefix));
}
if datasets.is_empty() {
if let Some(prefix) = cfg.prefix.as_deref() {
eprintln!(
"no autoindex datasets match --prefix {prefix} at {} (catalog {})",
cfg.url,
catalog::CATALOG_INDEX
);
} else {
eprintln!(
"no autoindex datasets match at {} (catalog {})",
cfg.url,
catalog::CATALOG_INDEX
);
}
eprintln!("{}", catalog::MAP_NAMESPACE_HINT);
return Ok(1);
}
let mut run_must = vec![json!({"term": {"doc_kind": "run"}})];
if let Some(prefix) = cfg.prefix.as_deref() {
// `term` on the declared keyword `prefix`; `match_phrase` covers a
// pre-#737 catalog where `prefix` was inferred as `text` and a term
// on a hyphenated value matches nothing.
run_must.push(json!({"bool": {
"should": [
{"term": {"prefix": prefix}},
{"match_phrase": {"prefix": prefix}}
],
"minimum_should_match": 1
}}));
}
let mut runs = fetch(json!({"bool": {"must": run_must}}), 500, None)?;
if let Some(prefix) = cfg.prefix.as_deref() {
runs.retain(|r| {
r.get("prefix")
.or_else(|| r.get(catalog::CORPUS_SCOPE_FIELD))
.and_then(Value::as_str)
== Some(prefix)
});
}
runs.sort_by_key(|r| {
std::cmp::Reverse(
r.get("started")
.and_then(|s| s.as_str())
.unwrap_or("")
.to_string(),
)
});
let correlations = {
let mut corr_must = vec![json!({"term": {"doc_kind": "correlation"}})];
if let Some(sp) = &scoped_prefix {
corr_must.push(json!({"prefix": {"a_index": sp}}));
corr_must.push(json!({"prefix": {"b_index": sp}}));
}
let mut all = fetch(json!({"bool": {"must": corr_must}}), 200, None)?;
if let Some(prefix) = cfg.prefix.as_deref() {
all.retain(|c| catalog::correlation_matches_prefix(c, prefix));
}
// stale-correlation hygiene: catalog docs upsert by deterministic id,
// so older runs' correlations linger — show only the latest run that
// produced each corr_kind.
for kind in ["key_overlap", "time_alignment"] {
let latest = all
.iter()
.filter(|c| c.get("corr_kind").and_then(|k| k.as_str()) == Some(kind))
.filter_map(|c| c.get("run_id").and_then(|r| r.as_str()))
.max()
.map(|s| s.to_string());
all.retain(|c| {
c.get("corr_kind").and_then(|k| k.as_str()) != Some(kind)
|| c.get("run_id")
.and_then(|r| r.as_str())
.map(|s| s.to_string())
== latest
});
}
all
};
// #971: junk and duplicate documents are current state, not generation
// scratch. Ids are content-derived and upserted in place, and publication
// now rewrites only the documents that changed — an unchanged file's
// document keeps the run_id of the generation that last touched it.
// Filtering by the single latest run would therefore hide every file the
// newest run did not rewrite (touch one file in 10,000 and the map would
// show one junk entry instead of hundreds). Scope by the corpus prefixes
// the run documents name instead — same output as the old filter for a
// single-corpus node, and for a multi-corpus node it stops hiding every
// corpus except the one that ran last. (`prefix` is a mapped keyword
// since #737; on a pre-rc.68 catalog it was inferred, where a term
// matches only while the value has no separator — the same legacy caveat
// the scoped sweeps in `catalog.rs` document.)
let prefixes: Vec<String> = match cfg.prefix.as_deref() {
Some(prefix) => vec![prefix.to_string()],
None => runs
.iter()
.filter_map(|run| run.get("prefix"))
.filter_map(Value::as_str)
.collect::<BTreeSet<_>>()
.into_iter()
.map(String::from)
.collect::<Vec<_>>(),
};
let prefix_filter = (!prefixes.is_empty()).then(|| {
let mut should = Vec::with_capacity(prefixes.len() * 2);
for prefix in &prefixes {
should.push(json!({"term": {"prefix": prefix}}));
should.push(json!({"term": {catalog::CORPUS_SCOPE_FIELD: prefix}}));
}
json!({"bool": {
"should": should,
"minimum_should_match": 1
}})
});
let mut junk_must = vec![json!({"term": {"doc_kind": "file"}})];
if let Some(filter) = prefix_filter.clone() {
junk_must.push(filter);
}
let mut junk_files = fetch(
json!({"bool": {"must": junk_must,
"must_not": [
{"term": {"status": "indexed"}},
{"term": {"status": "duplicate"}}
]}}),
500,
None,
)?;
let mut duplicate_must = vec![
json!({"term": {"doc_kind": "file"}}),
json!({"term": {"status": "duplicate"}}),
];
if let Some(filter) = prefix_filter {
duplicate_must.push(filter);
}
let mut duplicate_files = fetch(json!({"bool": {"must": duplicate_must}}), 500, None)?;
if let Some(prefix) = cfg.prefix.as_deref() {
junk_files.retain(|f| catalog::file_matches_prefix(f, prefix));
duplicate_files.retain(|f| catalog::file_matches_prefix(f, prefix));
}
if let Some(output) = &cfg.report {
let report =
map_report::Report::collect(&es, &runs, &datasets, &junk_files, output.redact_paths);
report.publish(report_stage.expect("report staging was prepared"), output)?;
println!("report: {}", output.path.display());
return Ok(0);
}
if cfg.json {
let (start, end) =
catalog::detail_bounds(datasets.len(), cfg.detail_offset, cfg.detail_limit);
let truncated = start > 0 || end < datasets.len();
let body = if truncated {
let summary: Vec<Value> = datasets
.iter()
.map(|d| {
json!({
"index_name": d.get("index_name"),
"slug": d.get("slug"),
"record_count": d.get("record_count"),
"file_count": d.get("file_count"),
})
})
.collect();
json!({
"run": runs.first(),
"datasets_total": datasets.len(),
"detail_offset": start,
"datasets": &datasets[start..end],
"datasets_summary": summary,
"detail_note": "field detail is paged; `autoindex map --dataset <slug>` or `--offset`/`--limit`",
"correlations": correlations,
"junk_files": junk_files,
"duplicate_files": duplicate_files,
"gotchas": catalog::GOTCHAS,
})
} else {
json!({
"run": runs.first(),
"datasets": datasets,
"correlations": correlations,
"junk_files": junk_files,
"duplicate_files": duplicate_files,
"gotchas": catalog::GOTCHAS,
})
};
println!("{}", serde_json::to_string_pretty(&body)?);
} else {
print!(
"{}",
catalog::render_map_page(
runs.first(),
&datasets,
&correlations,
&junk_files,
&duplicate_files,
junk_files.len() as u64,
cfg.detail_offset,
cfg.detail_limit,
)
);
// Second-brain summary (§6.1): live edge count straight from the
// edges index, scoped by `exists src` so the meta doc never counts.
if let Some(g) = runs.first().and_then(|r| r.get("graph")) {
if let (Some(brain), Some(edges_index)) = (
g.get("brain").and_then(Value::as_str),
g.get("edges_index").and_then(Value::as_str),
) {
let live = es
.search(
edges_index,
&json!({
"size": 0,
"track_total_hits": true,
"query": {"bool": {
"filter": [{"exists": {"field": "src"}}],
"must_not": [{"exists": {"field": "invalid_at"}}]
}}
}),
)
.ok()
.and_then(|v| v.pointer("/hits/total/value").and_then(Value::as_u64));
match live {
Some(n) => println!("\ngraph: {n} live edges in {edges_index} (brain {brain})"),
None => {
println!("\ngraph: brain {brain} — edges index {edges_index} unreachable")
}
}
}
}
}
Ok(0)
}
// ─── catalog summary (reused by `xerj feedback`) ─────────────────────────
/// A compact, factual view of what the latest autoindex run put on a node.
///
/// `xerj feedback` uses it to auto-fill the "what was indexed" line of a field
/// report without re-deriving the catalog queries `run_map` already owns. It is
/// deliberately read-only and narrow: the latest run document and the dataset
/// documents, nothing else. Everything else the caller needs (correlations,
/// junk, gotchas) belongs to the full `autoindex map`, not to a one-line
/// summary.
pub struct CatalogSummary {
/// The most recent `doc_kind: run` document, if any run has been recorded.
pub run: Option<Value>,
/// Dataset documents for the sentence in [`CatalogSummary::one_line`].
///
/// When the latest run carries a `run_id` and the catalog has dataset docs
/// stamped with that id, this is only those docs (most records first). A
/// catalog that predates `run_id` on dataset docs keeps the unscoped list,
/// because those docs cannot be told apart from this run.
pub datasets: Vec<Value>,
}
impl CatalogSummary {
/// A single honest sentence for a field report's "Pointed at" line, or
/// `None` when nothing was indexed (so the caller emits a placeholder
/// rather than a sentence that says "0 records"). Never fabricates: every
/// number here comes straight from the catalog the server wrote.
pub fn one_line(&self) -> Option<String> {
// The record total and the dataset count have to describe the same
// run. Pairing `records_total` from the newest run document with
// `datasets.len()` counted every `doc_kind: dataset` doc on the shared
// catalog (other prefixes, older runs), so a field report said the
// last run's records were spread across the whole node.
let scoped = self.datasets_for_latest_run();
if scoped.is_empty() && self.datasets.is_empty() {
return None;
}
let get = |v: &Value, k: &str| v.get(k).cloned().unwrap_or(Value::Null);
let records_from_run = self
.run
.as_ref()
.and_then(|r| get(r, "records_total").as_u64());
let (records, dataset_count) = if scoped.is_empty() {
// Dataset docs are present, but none belong to this run. Report
// the run document's own total and omit the dataset count. With
// no total, say nothing rather than summing the other runs.
let records = records_from_run?;
(records, None)
} else {
let records = records_from_run.unwrap_or_else(|| {
scoped
.iter()
.filter_map(|d| d.get("record_count").and_then(Value::as_u64))
.sum()
});
(records, Some(scoped.len()))
};
let mut sentence = match dataset_count {
Some(n) => format!("{records} records across {n} dataset(s)"),
None => format!("{records} records"),
};
if let Some(root) = self
.run
.as_ref()
.and_then(|r| r.get("root"))
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
{
sentence.push_str(&format!(" under {root}"));
}
if let Some(run_id) = self
.run
.as_ref()
.and_then(|r| r.get("run_id"))
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
{
sentence.push_str(&format!(" (autoindex run {run_id})"));
}
Some(sentence)
}
/// Dataset docs that belong to the latest run.
///
/// A matching `run_id` wins. When no dataset doc carries that id, untagged
/// docs (catalogs written before dataset docs stored `run_id`) are kept,
/// and docs tagged with a *different* run are dropped so they cannot inflate
/// the count.
fn datasets_for_latest_run(&self) -> Vec<&Value> {
let run_id = self
.run
.as_ref()
.and_then(|r| r.get("run_id"))
.and_then(Value::as_str)
.filter(|s| !s.is_empty());
let Some(run_id) = run_id else {
return self.datasets.iter().collect();
};
let matched: Vec<&Value> = self
.datasets
.iter()
.filter(|d| d.get("run_id").and_then(Value::as_str) == Some(run_id))
.collect();
if !matched.is_empty() {
return matched;
}
let any_other_run = self.datasets.iter().any(|d| {
d.get("run_id")
.and_then(Value::as_str)
.is_some_and(|s| !s.is_empty())
});
if any_other_run {
Vec::new()
} else {
self.datasets.iter().collect()
}
}
}
/// Fetch the [`CatalogSummary`] from a running node's `autoindex-catalog`.
///
/// Reuses the same catalog index and query shapes as `run_map`, minus the
/// correlation/junk/duplicate passes a one-line summary does not need. Any
/// failure — endpoint unreachable, auth rejected, no catalog yet — is returned
/// as an `Err`, so `xerj feedback` can degrade to a template placeholder
/// instead of inventing a number (the repo's honest-claims rule).
pub fn fetch_catalog_summary(url: &str, api_key: Option<String>) -> Result<CatalogSummary> {
let es = Es::new(url, api_key)?;
es.ping()?;
let fetch = |query: Value, size: usize, sort: Option<Value>| -> Result<Vec<Value>> {
let mut body = json!({"query": query, "size": size});
if let Some(s) = sort {
body["sort"] = s;
}
let v = es.search(catalog::CATALOG_INDEX, &body)?;
Ok(v.pointer("/hits/hits")
.and_then(|h| h.as_array())
.map(|arr| {
arr.iter()
.filter_map(|h| h.get("_source").cloned())
.collect()
})
.unwrap_or_default())
};
let mut runs = fetch(json!({"term": {"doc_kind": "run"}}), 50, None)?;
runs.sort_by_key(|r| {
std::cmp::Reverse(
r.get("started")
.and_then(|s| s.as_str())
.unwrap_or("")
.to_string(),
)
});
let run = runs.into_iter().next();
let run_id = run
.as_ref()
.and_then(|r| r.get("run_id"))
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(str::to_string);
// Scope the dataset query to the latest run so a catalog with more than
// the fetch cap of older datasets cannot crowd this run's docs out of the
// page. An empty scoped page falls back to the unscoped list: catalogs
// written before dataset docs stored `run_id` have nothing to match, and
// [`CatalogSummary::one_line`] still refuses to count docs tagged with a
// different run.
let dataset_sort = Some(json!([{"record_count": "desc"}]));
let mut datasets = if let Some(id) = &run_id {
fetch(
json!({"bool": {"filter": [
{"term": {"doc_kind": "dataset"}},
{"term": {"run_id": id}},
]}}),
500,
dataset_sort.clone(),
)?
} else {
Vec::new()
};
if datasets.is_empty() {
datasets = fetch(json!({"term": {"doc_kind": "dataset"}}), 500, dataset_sort)?;
}
Ok(CatalogSummary { run, datasets })
}
// ─── status subcommand ───────────────────────────────────────────────────
struct JournalFacts {
root: String,
files_done: u64,
records: u64,
finished: bool,
generation: Option<u64>,
generation_files: Option<u64>,
generation_records: Option<u64>,
graph_line: Option<String>,
/// `url` from the `kind: run` record. Empty on a journal written before
/// that field existed.
url: String,
}
fn read_journal_facts(jp: &Path) -> JournalFacts {
let mut facts = JournalFacts {
root: String::new(),
files_done: 0,
records: 0,
finished: false,
generation: None,
generation_files: None,
generation_records: None,
graph_line: None,
url: String::new(),
};
let Ok(f) = std::fs::File::open(jp) else {
return facts;
};
for line in std::io::BufReader::new(f).lines().map_while(|l| l.ok()) {
let Ok(v) = serde_json::from_str::<Value>(&line) else {
continue;
};
match v.get("kind").and_then(|k| k.as_str()) {
Some("run") => {
facts.root = v.get("root").and_then(|r| r.as_str()).unwrap_or("").into();
if let Some(url) = v.get("url").and_then(|u| u.as_str()) {
facts.url = url.to_string();
}
}
Some("file_done") => {
facts.files_done += 1;
facts.records += v.get("records").and_then(|r| r.as_u64()).unwrap_or(0);
}
Some("finish") => {
facts.finished = true;
facts.generation = v.pointer("/summary/generation").and_then(Value::as_u64);
facts.generation_files =
v.pointer("/summary/files_indexed").and_then(Value::as_u64);
facts.generation_records =
v.pointer("/summary/records_total").and_then(Value::as_u64);
// Latest finish wins — the summary embeds the run
// doc, whose `graph` block is the edge count of
// record for this journal.
if let Some(g) = v.pointer("/summary/graph").filter(|graph| !graph.is_null()) {
facts.graph_line = Some(format!(
"graph: {} edges written to {} (brain {})",
g.get("edges_written").and_then(Value::as_u64).unwrap_or(0),
g.get("edges_index").and_then(Value::as_str).unwrap_or("?"),
g.get("brain").and_then(Value::as_str).unwrap_or("?"),
));
}
}
_ => {}
}
}
facts
}
/// Two endpoint strings name the same node when they match after trimming
/// and stripping one trailing slash. `http://127.0.0.1:9200/` and
/// `http://127.0.0.1:9200` are the same journal.
fn urls_identify_same_endpoint(recorded: &str, current: &str) -> bool {
fn norm(s: &str) -> &str {
s.trim().trim_end_matches('/')
}
norm(recorded) == norm(current)
}
/// Status word for one journal line.
///
/// A journal whose `run` record names a different node is not this
/// endpoint's run. Printing `in progress` or `FINISHED` there makes
/// `autoindex status` look like another node's work is this node's.
/// An empty recorded URL is a journal from before `url` was written;
/// those keep the old words.
fn journal_progress_label(finished: bool, journal_url: &str, current_url: &str) -> String {
let recorded = journal_url.trim().trim_end_matches('/');
if !recorded.is_empty() && !urls_identify_same_endpoint(recorded, current_url) {
return format!("other endpoint {recorded}");
}
if finished {
"FINISHED".to_string()
} else {
"in progress".to_string()
}
}
fn run_status(cfg: StatusCfg) -> Result<i32> {
if let Some(note) = &cfg.xerj_url_note {
eprintln!("autoindex: {note}");
}
// journals
let dirs: Vec<std::path::PathBuf> = match &cfg.state_dir {
Some(d) => vec![d.clone()],
None => {
let base = xerj_common::home::home_dir()
.unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
.join(".xerj")
.join("autoindex");
std::fs::read_dir(&base)
.map(|rd| rd.flatten().map(|e| e.path()).collect())
.unwrap_or_default()
}
};
let mut aborted: Vec<remove::AbortedIndex> = Vec::new();
for d in dirs {
let jp = d.join("journal.ndjson");
if !jp.exists() {
continue;
}
let facts = read_journal_facts(&jp);
let label = journal_progress_label(facts.finished, &facts.url, &cfg.url);
println!(
"journal {} — root {} — {} files done, {} records, {}{}",
jp.display(),
facts.root,
facts.generation_files.unwrap_or(facts.files_done),
facts.generation_records.unwrap_or(facts.records),
label,
facts
.generation
.map(|generation| format!(" (generation {generation})"))
.unwrap_or_default()
);
if let Some(line) = facts.graph_line {
println!(" {line}");
}
// #2391: an unfinished journal is the only record of indices a build
// created before it wrote a catalog run. The prefix is the one the
// journal recorded, not `--prefix`: a leftover of another prefix is
// still a leftover. A missing or unreadable journal adds nothing; a
// finished one is not an orphan source.
if let Ok(text) = std::fs::read_to_string(&jp) {
aborted.extend(remove::unfinished_journal_indices(&text, &cfg.url, true));
}
}
// live indices
if let Ok(es) = Es::new(&cfg.url, cfg.api_key.clone()) {
if es.ping().is_ok() {
let pat = format!("{}-", cfg.prefix);
let all_live = es.cat_indices().unwrap_or_default();
let mut live: Vec<(String, u64)> = all_live
.iter()
.filter(|(name, _)| name.starts_with(&pat) || name == catalog::CATALOG_INDEX)
.cloned()
.collect();
// A catalog the node cannot read is not treated as empty: that
// would flag the working index. A missing catalog is empty, which
// is the aborted build. One prefix's failure does not suppress
// another prefix's leftovers.
let live_names: Vec<String> = all_live.iter().map(|(name, _)| name.clone()).collect();
let mut flags = Vec::new();
let mut prefixes: Vec<&str> = aborted.iter().map(|item| item.prefix.as_str()).collect();
prefixes.sort_unstable();
prefixes.dedup();
for prefix in prefixes {
let Ok(cataloged) = remove::cataloged_index_names(&es, prefix) else {
continue;
};
let subset: Vec<remove::AbortedIndex> = aborted
.iter()
.filter(|item| item.prefix == prefix)
.cloned()
.collect();
flags.extend(remove::orphan_flags(&live_names, &cataloged, &subset));
}
let flagged: std::collections::BTreeSet<&str> =
flags.iter().map(|(name, _)| name.as_str()).collect();
for (name, _) in &flags {
if live.iter().any(|(shown, _)| shown == name) {
continue;
}
if let Some(pair) = all_live.iter().find(|(shown, _)| shown == name) {
live.push(pair.clone());
}
}
live.sort();
println!("\nlive indices at {}:", cfg.url);
for (name, docs) in &live {
if flagged.contains(name.as_str()) {
println!(" {name:<40} {docs:>10} docs ORPHAN aborted build, no catalog run");
} else {
println!(" {name:<40} {docs:>10} docs");
}
}
let mut by_prefix: std::collections::BTreeMap<&str, Vec<(String, String)>> =
std::collections::BTreeMap::new();
for (name, root) in &flags {
let prefix = aborted
.iter()
.find(|item| item.name == *name)
.map(|item| item.prefix.as_str())
.unwrap_or(cfg.prefix.as_str());
by_prefix
.entry(prefix)
.or_default()
.push((name.clone(), root.clone()));
}
for (prefix, group) in &by_prefix {
for line in remove::orphan_status_lines(prefix, group) {
println!("{line}");
}
}
}
}
Ok(0)
}
#[cfg(test)]
mod journal_status_tests {
use super::{journal_progress_label, read_journal_facts};
use std::fs;
fn write_journal(name: &str, body: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("xerj-status-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let path = dir.join("journal.ndjson");
fs::write(&path, body).unwrap();
path
}
#[test]
fn another_endpoints_journal_is_not_in_progress() {
let path = write_journal(
"other-open",
"{\"v\":1,\"kind\":\"run\",\"root\":\"/repo\",\"url\":\"http://127.0.0.1:9201\",\"prefix\":\"ax\"}\n\
{\"kind\":\"file_done\",\"records\":3}\n",
);
let facts = read_journal_facts(&path);
assert_eq!(facts.root, "/repo");
assert_eq!(facts.files_done, 1);
assert_eq!(facts.records, 3);
assert!(!facts.finished);
let label = journal_progress_label(facts.finished, &facts.url, "http://127.0.0.1:9200");
assert_eq!(label, "other endpoint http://127.0.0.1:9201");
assert!(!label.contains("in progress"));
assert!(!label.contains("FINISHED"));
let finished = write_journal(
"other-done",
"{\"kind\":\"run\",\"root\":\"/other\",\"url\":\"http://10.0.0.2:9200/\"}\n\
{\"kind\":\"finish\",\"summary\":{\"generation\":4,\"files_indexed\":2,\"records_total\":9}}\n",
);
let facts = read_journal_facts(&finished);
assert!(facts.finished);
assert_eq!(facts.generation, Some(4));
assert_eq!(facts.generation_files, Some(2));
assert_eq!(facts.generation_records, Some(9));
let label = journal_progress_label(facts.finished, &facts.url, "http://127.0.0.1:9200");
assert_eq!(label, "other endpoint http://10.0.0.2:9200");
assert!(!label.contains("in progress"));
assert!(!label.contains("FINISHED"));
let _ = fs::remove_dir_all(path.parent().unwrap());
let _ = fs::remove_dir_all(finished.parent().unwrap());
}
#[test]
fn this_endpoint_and_a_legacy_journal_keep_the_old_words() {
assert_eq!(
journal_progress_label(true, "http://127.0.0.1:9200/", "http://127.0.0.1:9200"),
"FINISHED"
);
assert_eq!(
journal_progress_label(false, " http://127.0.0.1:9200 ", "http://127.0.0.1:9200/"),
"in progress"
);
// No `url` on the run record: a journal from before the field existed.
let path = write_journal("legacy", "{\"kind\":\"run\",\"root\":\"/old\"}\n");
let facts = read_journal_facts(&path);
assert!(facts.url.is_empty());
assert_eq!(
journal_progress_label(facts.finished, &facts.url, "http://127.0.0.1:9200"),
"in progress"
);
let _ = fs::remove_dir_all(path.parent().unwrap());
}
}
#[cfg(test)]
mod section_label_tests {
use super::section_label;
/// The two text-section locator grammars (§6.6.2) and their labels; every
/// other locator shape must be None so row/line/byte records never reach
/// `detect_text`.
#[test]
fn labels_only_text_section_locators() {
assert_eq!(section_label("s0").as_deref(), Some("section 0"));
assert_eq!(section_label("s17").as_deref(), Some("section 17"));
assert_eq!(section_label("p1-s0").as_deref(), Some("page 1 section 0"));
assert_eq!(
section_label("p12-s3").as_deref(),
Some("page 12 section 3")
);
for not_a_section in [
"s", "sx", "s1x", "p1", "p1-s", "p-s1", "px-s1", "b1024", "row7", "file", "line3",
"p1-s2-x",
] {
assert_eq!(section_label(not_a_section), None, "{not_a_section}");
}
}
}
#[cfg(test)]
mod unsafe_fresh_generation_tests {
use super::*;
#[test]
fn cli_error_routing_separates_typed_json_from_unrelated_human_errors() {
let typed: anyhow::Error = UnsafeFreshGenerationError {
committed_generation: Some(7),
}
.into();
let route = route_cli_error(&typed, true);
assert_eq!(route.exit_code, 1);
assert!(route.stderr.is_none());
let stdout = route.stdout.unwrap();
let value: Value = serde_json::from_str(&stdout).unwrap();
assert_eq!(value["schema"], "xerj.autoindex.unsafe_fresh_generation.v1");
assert_eq!(value["error"], "unsafe_fresh_existing_generation");
assert_eq!(value["blocking_state"]["kind"], "committed_generation");
assert_eq!(value["blocking_state"]["generation"], 7);
// The refusal must never print an empty inventory delta it never
// computed: it names the durable state that is in the way instead.
assert!(value.get("added_content_groups").is_none());
assert!(format!("{typed:#}").contains("committed corpus generation 7"));
let pending: anyhow::Error = UnsafeFreshGenerationError {
committed_generation: None,
}
.into();
let pending_value: Value =
serde_json::from_str(&route_cli_error(&pending, true).stdout.unwrap()).unwrap();
assert_eq!(
pending_value["blocking_state"]["kind"],
"pending_generation"
);
let unrelated = anyhow::anyhow!("endpoint unavailable");
let route = route_cli_error(&unrelated, true);
assert_eq!(route.exit_code, 1);
assert!(route.stdout.is_none());
assert_eq!(route.stderr.as_deref(), Some("error: endpoint unavailable"));
}
}
#[cfg(test)]
mod inventory_delta_tests {
use super::*;
use std::path::PathBuf;
fn file(path: &str) -> walk::FileEntry {
walk::FileEntry {
path: PathBuf::from(path),
rel: path.to_owned(),
rel_id: format!("id:{path}"),
is_symlink: false,
size: 1,
}
}
fn assignment(path: &str) -> FileAssignment {
FileAssignment {
rel: path.to_owned(),
path_id: format!("id:{path}"),
family: "csv".into(),
gzip: false,
content_digest: Some(format!("digest:{path}")),
assignments: vec![(None, "rows".into())],
as_document: false,
is_symlink: Some(false),
}
}
fn targets() -> RefusalTargets {
RefusalTargets {
state_dir: "/state".into(),
data_indices: vec!["ax-rows".into()],
edges_index: Some(".xerj-memory-corpus-edges".into()),
}
}
/// A root under which no plan file exists, so every vanished group is a
/// genuine deletion (#439) — the behaviour these classifier tests assert.
fn nowhere() -> &'static Path {
Path::new("/xerj-439-no-such-root")
}
#[test]
fn only_a_removed_content_group_refuses_a_rerun() {
let mut plan = Plan::default();
plan.files.insert("keep".into(), assignment("keep.csv"));
assert!(!UnsupportedInventoryDelta::between(
nowhere(),
&[file("keep.csv")],
&["keep".into()],
&plan
)
.refuses());
// An added file is skipped by the frozen plan, not a refusal: the
// documented rerun-then---fresh workflow has to keep working.
let added = UnsupportedInventoryDelta::between(
nowhere(),
&[file("keep.csv"), file("new.csv")],
&["keep".into(), "new".into()],
&plan,
);
assert_eq!(added.added_content_groups.len(), 1);
assert!(!added.refuses(), "an addition alone must not fail the run");
// A removal leaves live documents with no source file behind them.
assert!(UnsupportedInventoryDelta::between(nowhere(), &[], &[], &plan).refuses());
}
/// #2058: a dataless placeholder left out of the hash is still on disk.
/// Omitting it from the inventory would classify the previous group as an
/// exclusion, and the exclusion sweep would delete documents that were
/// indexed the last time the bytes were local.
#[test]
fn a_dataless_placeholder_kept_out_of_the_hash_is_not_an_exclusion() {
let mut plan = Plan::default();
plan.files.insert("cloud".into(), assignment("cloud.txt"));
let present = [file("cloud.txt")];
let delta = inventory_delta(nowhere(), &[], &[], &plan, &present);
assert!(delta.deleted_content_groups.is_empty());
assert!(delta.excluded_content_groups.is_empty());
assert!(!delta.refuses());
assert!(UnsupportedInventoryDelta::between(nowhere(), &[], &[], &plan).refuses());
let empty = inventory_delta(nowhere(), &[], &[], &plan, &[]);
assert!(empty.refuses());
assert_eq!(empty.deleted_content_groups.len(), 1);
}
#[test]
fn classifier_sorts_added_and_vanished_groups() {
let mut plan = Plan::default();
plan.files.insert("keep".into(), assignment("keep.csv"));
plan.junk_files.push(JunkFile {
file_key: "junk".into(),
rel: "broken.pdf".into(),
format: "pdf".into(),
status: "junk".into(),
reason: "fixture".into(),
bytes: 1,
});
assert!(
!UnsupportedInventoryDelta::between(
nowhere(),
&[file("keep.csv"), file("broken.pdf")],
&["keep".into(), "junk".into()],
&plan,
)
.refuses(),
"unchanged durable junk is neither added nor vanished"
);
plan.files.insert("old-z".into(), assignment("z-old.csv"));
plan.files.insert("old-a".into(), assignment("a-old.csv"));
let delta = UnsupportedInventoryDelta::between(
nowhere(),
&[
file("keep.csv"),
file("broken.pdf"),
file("z-new.csv"),
file("m-new.csv"),
],
&["keep".into(), "junk".into(), "new-z".into(), "new-m".into()],
&plan,
);
assert_eq!(
delta
.added_content_groups
.iter()
.map(|entry| entry.path.as_str())
.collect::<Vec<_>>(),
["m-new.csv", "z-new.csv"]
);
assert_eq!(
delta
.deleted_content_groups
.iter()
.map(|entry| entry.path.as_str())
.collect::<Vec<_>>(),
["a-old.csv", "z-old.csv"]
);
}
#[test]
fn refusal_names_the_removed_files_and_every_recovery_route() {
let mut plan = Plan::default();
plan.files.insert("gone".into(), assignment("gone.csv"));
let error =
UnsupportedInventoryDelta::between(nowhere(), &[], &[], &plan).into_error(targets());
let message = format!("{error:#}");
assert!(message.contains("gone.csv"), "{message}");
assert!(
message.contains("no longer exist in the folder"),
"{message}"
);
assert!(message.contains("made no remote mutations"), "{message}");
assert!(message.contains("restore the DELETED file(s)"), "{message}");
assert!(message.contains("ax-rows"), "{message}");
assert!(message.contains("/state"), "{message}");
assert!(message.contains(".xerj-memory-corpus-edges"), "{message}");
assert!(message.contains("new --state-dir"), "{message}");
assert!(message.contains("`--fresh`"), "{message}");
}
/// #439: a plan file that vanished from the walk but is STILL ON DISK was
/// excluded by a widened ignore/hidden rule, not removed. It must classify
/// as excluded (not deleted), and the refusal must not tell an operator (or
/// an agent parsing the JSON) to restore a file that is one `ls` away.
#[test]
fn an_excluded_still_on_disk_group_is_not_reported_as_a_deletion() {
let root = tempfile::tempdir().unwrap();
std::fs::write(root.path().join("secret.csv"), "id,value\n1,live\n").unwrap();
let mut plan = Plan::default();
plan.files.insert("secret".into(), assignment("secret.csv"));
// The walk yields nothing (the file is now excluded) though it is on disk.
let delta = UnsupportedInventoryDelta::between(root.path(), &[], &[], &plan);
assert!(
delta.deleted_content_groups.is_empty(),
"an on-disk file must not be classified as a deletion"
);
assert_eq!(
delta
.excluded_content_groups
.iter()
.map(|entry| entry.path.as_str())
.collect::<Vec<_>>(),
["secret.csv"]
);
// #589: an excluded-only delta is now SWEPT, not refused — the rerun
// continues after `sweep_excluded_groups` removes its documents, so
// `refuses()` (deletion-only) is false here. `into_error`'s excluded
// wording still applies when a genuine deletion co-occurs (both sets
// stay live in that case), so it is still exercised below as a direct
// message-builder check.
assert!(
!delta.refuses(),
"#589: an excluded-only delta is swept, not refused"
);
let error = delta.into_error(targets());
let message = format!("{error:#}");
assert!(message.contains("secret.csv"), "{message}");
assert!(
message.contains("still on disk"),
"the excluded message must say the file is still on disk: {message}"
);
assert!(
!message.contains("restore the DELETED"),
"an excluded (never-removed) file must not be offered as a deletion to restore: {message}"
);
// The machine-readable schema carries the split and the excluded route,
// and omits the restore instruction when nothing was actually deleted.
let json = error
.downcast_ref::<UnsupportedInventoryDeltaError>()
.expect("typed refusal")
.to_json();
assert_eq!(json["excluded_content_groups"].as_array().unwrap().len(), 1);
assert!(json["recovery"].get("excluded_not_removed").is_some());
assert!(
json["recovery"].get("restore_removed_files").is_none(),
"no deleted files, so no restore instruction: {json}"
);
// Back-compat: the v1 union field still lists it.
assert_eq!(json["vanished_content_groups"].as_array().unwrap().len(), 1);
}
/// #589 (fail-before, WIP): the purge half of #439. An exclusion (a file
/// still on disk that a widened ignore/hidden/`.xerjignore` rule now skips)
/// is data the exclusion must REMOVE from the index, not a reason to refuse
/// the whole rerun. With NO genuine deletion present, the reconcile must
/// PROCEED — sweeping the excluded group's published documents — unlike a
/// real deletion, which stays refused. Today `refuses()` conflates the two.
///
/// Un-ignore when the sweep lands; that change also flips the
/// `assert!(delta.refuses())` in
/// `an_excluded_still_on_disk_group_is_not_reported_as_a_deletion` (the
/// excluded-only case no longer produces a refusal).
#[test]
fn an_excluded_only_delta_is_swept_not_refused() {
let root = tempfile::tempdir().unwrap();
std::fs::write(root.path().join("secret.csv"), "id,value\n1,live\n").unwrap();
let mut plan = Plan::default();
plan.files.insert("secret".into(), assignment("secret.csv"));
// The walk yields nothing (the file is now excluded) though it is on disk.
let delta = UnsupportedInventoryDelta::between(root.path(), &[], &[], &plan);
assert!(
delta.deleted_content_groups.is_empty(),
"no genuine deletion — the file is still on disk"
);
assert_eq!(
delta
.excluded_content_groups
.iter()
.map(|e| e.path.as_str())
.collect::<Vec<_>>(),
["secret.csv"],
);
// #589: an excluded-only delta must NOT refuse the rerun — the excluded
// group is swept from the destination and the run continues.
assert!(
!delta.refuses(),
"#589: an excluded-only delta must be swept, not refused"
);
}
/// #439's headline case (CHANGELOG): a hidden NON-UTF-8 name still on disk.
/// Its `rel` is a lossy `U+FFFD` rendering that matches no dirent, so a probe
/// through `rel` would call it a deletion; the reversible `path_id` matches
/// the real bytes and classifies it excluded.
#[cfg(unix)]
#[test]
fn a_non_utf8_excluded_name_is_matched_on_disk_via_path_id() {
use std::os::unix::ffi::OsStrExt;
let root = tempfile::tempdir().unwrap();
let raw = b".secret_\xff\xfe.csv";
let name = std::ffi::OsStr::from_bytes(raw);
std::fs::write(root.path().join(name), "id\n1\n").unwrap();
let rel_lossy = std::path::Path::new(name).to_string_lossy().into_owned();
let mut path_id = String::from("unix:");
for byte in raw {
use std::fmt::Write;
write!(path_id, "{byte:02x}").unwrap();
}
let mut plan = Plan::default();
plan.files.insert(
"secret".into(),
FileAssignment {
rel: rel_lossy.clone(),
path_id,
family: "csv".into(),
gzip: false,
content_digest: Some("digest".into()),
assignments: vec![(None, "rows".into())],
as_document: false,
is_symlink: Some(false),
},
);
// Proof that path_id is load-bearing: the lossy rel does NOT resolve.
assert!(
!root.path().join(&rel_lossy).try_exists().unwrap_or(false),
"the lossy rel must not resolve on disk — that is why path_id is needed"
);
let delta = UnsupportedInventoryDelta::between(root.path(), &[], &[], &plan);
assert!(
delta.deleted_content_groups.is_empty(),
"a non-UTF-8 name still on disk must not be a deletion: {:?}",
delta.deleted_content_groups
);
assert_eq!(delta.excluded_content_groups.len(), 1);
}
/// #439 robustness: a corrupted or hand-edited `path_id` must return None
/// (so the caller falls back to `rel`), never panic — including a non-ASCII
/// byte inside the hex region, which naive `hex[i..i + 2]` slicing panics on.
#[test]
fn decode_stable_path_id_rejects_malformed_ids_without_panicking() {
assert!(decode_stable_path_id("").is_none());
assert!(decode_stable_path_id("id:legacy").is_none());
#[cfg(unix)]
{
assert_eq!(
decode_stable_path_id("unix:2e63").unwrap(),
std::path::PathBuf::from(".c")
);
assert!(decode_stable_path_id("unix:2").is_none(), "odd length");
assert!(decode_stable_path_id("unix:zz").is_none(), "non-hex");
assert!(
decode_stable_path_id("unix:aéb").is_none(),
"multibyte char in hex must not panic"
);
}
}
/// The prose refusal is bounded by REFUSAL_LIST_CAP, not by the corpus: an
/// unmounted bind mount under an indexed root vanishes every group at once,
/// and rendering 82k entries into one String is megabytes of stderr in the
/// one path whose job is to be read. `--json` still carries all of them.
#[test]
fn refusal_prose_caps_its_listings_while_json_keeps_every_entry() {
let mut plan = Plan::default();
let total = REFUSAL_LIST_CAP * 3;
for i in 0..total {
plan.files.insert(
format!("gone{i:03}"),
assignment(&format!("gone{i:03}.csv")),
);
}
let error =
UnsupportedInventoryDelta::between(nowhere(), &[], &[], &plan).into_error(targets());
let message = format!("{error:#}");
assert!(message.contains("gone000.csv"), "{message}");
assert!(
message.contains(&format!(", … and {} more", total - REFUSAL_LIST_CAP)),
"{message}"
);
// The tail past the cap must not be rendered at all, not merely elided.
let last = format!("gone{:03}.csv", total - 1);
assert!(!message.contains(&last), "{message}");
assert_eq!(
message.matches(".csv (").count(),
REFUSAL_LIST_CAP,
"{message}"
);
let stdout = route_cli_error(&error, true)
.stdout
.expect("the typed refusal renders as JSON under --json");
let value: Value = serde_json::from_str(&stdout).unwrap();
assert_eq!(
value["vanished_content_groups"].as_array().unwrap().len(),
total
);
}
#[test]
fn refusal_prose_below_the_cap_has_no_more_tail() {
let mut plan = Plan::default();
plan.files.insert("gone".into(), assignment("gone.csv"));
let error =
UnsupportedInventoryDelta::between(nowhere(), &[], &[], &plan).into_error(targets());
let message = format!("{error:#}");
assert!(!message.contains("… and "), "{message}");
}
#[test]
fn cli_error_routing_separates_typed_json_from_unrelated_human_errors() {
let typed = UnsupportedInventoryDelta {
added_content_groups: Vec::new(),
deleted_content_groups: vec![InventoryDeltaEntry {
file_key: "key".into(),
path: "gone.csv".into(),
}],
excluded_content_groups: Vec::new(),
}
.into_error(targets());
let route = route_cli_error(&typed, true);
assert_eq!(route.exit_code, 1);
assert!(route.stderr.is_none());
let stdout = route.stdout.unwrap();
let value: Value = serde_json::from_str(&stdout).unwrap();
assert_eq!(value["schema"], "xerj.autoindex.unsupported_sync_delta.v1");
assert_eq!(value["error"], "unsupported_content_group_removal");
assert_eq!(value["vanished_content_groups"][0]["path"], "gone.csv");
assert!(value["recovery"]["rebuild_in_place"]
.as_str()
.unwrap()
.contains("ax-rows"));
let unrelated = anyhow::anyhow!("endpoint unavailable");
let route = route_cli_error(&unrelated, true);
assert_eq!(route.exit_code, 1);
assert!(route.stdout.is_none());
assert_eq!(route.stderr.as_deref(), Some("error: endpoint unavailable"));
}
}
#[cfg(test)]
mod duplicate_integration_tests {
use super::*;
use std::collections::HashSet;
use std::fs;
use std::io::Write;
fn legacy_assignment(rel: &str) -> FileAssignment {
FileAssignment {
rel: rel.to_string(),
path_id: String::new(),
is_symlink: None,
family: "txt".to_string(),
gzip: false,
content_digest: None,
assignments: vec![(None, "text".to_string())],
as_document: false,
}
}
#[test]
fn legacy_prefix_collision_has_one_deterministic_owner() {
let corpus = tempfile::tempdir().unwrap();
let mut a = vec![b'x'; 65_537];
let mut b = a.clone();
a[65_536] = b'a';
b[65_536] = b'b';
fs::write(corpus.path().join("a.txt"), a).unwrap();
fs::write(corpus.path().join("b.txt"), b).unwrap();
let files = walk::walk(corpus.path(), false).unwrap();
let inventory = content::resolve_reporting(files.clone(), &|_| {}).unwrap();
let legacy = ids::file_key(&files[0].path, files[0].size).unwrap();
assert_eq!(
legacy,
ids::file_key(&files[1].path, files[1].size).unwrap()
);
// The exact historical owner sorts second. It must retain the legacy
// key; the earlier collision sibling must never steal or share it.
let mut plan = Plan::default();
plan.files
.insert(legacy.clone(), legacy_assignment("b.txt"));
let error = select_resume_plan_keys(
&inventory.files,
&inventory.keys,
&plan,
Path::new("/state/journal.ndjson"),
)
.unwrap_err();
let message = format!("{error:#}");
assert!(message.contains("collides with legacy resume key"));
// Recovery advice must stay scoped to the two colliding files and
// keep an exact rebuild isolated from the old destination.
assert!(message.contains("remove or move one of these two files"));
assert!(message.contains("/state/journal.ndjson"));
assert!(message.contains("new --state-dir, new --prefix, and new --brain"));
}
#[test]
fn planned_key_claimed_by_path_diverts_the_content_claimant_deterministically() {
let corpus = tempfile::tempdir().unwrap();
// a.txt was planned under its old digest; its content has since
// changed, while b.txt now holds exactly the bytes a.txt was planned
// with — so b.txt's content key IS the planned key a.txt claims by rel.
fs::write(corpus.path().join("a.txt"), b"rewritten content\n").unwrap();
fs::write(corpus.path().join("b.txt"), b"original planned content\n").unwrap();
let inventory =
content::resolve_reporting(walk::walk(corpus.path(), false).unwrap(), &|_| {}).unwrap();
let planned_key = inventory.keys[1].clone();
let mut plan = Plan::default();
plan.files
.insert(planned_key.clone(), legacy_assignment("a.txt"));
let selected = select_resume_plan_keys(
&inventory.files,
&inventory.keys,
&plan,
Path::new("/state/journal.ndjson"),
)
.unwrap();
assert_eq!(selected[0].as_deref(), Some(planned_key.as_str()));
let diverted = selected[1].as_deref().expect("diverted key");
assert_ne!(diverted, planned_key);
assert!(diverted.starts_with(&format!("{planned_key}-claimed-")));
// The divergence is a pure function of (digest, path identity):
// resumes select the same exclusive owner and the same diverted key.
let again = select_resume_plan_keys(
&inventory.files,
&inventory.keys,
&plan,
Path::new("/state/journal.ndjson"),
)
.unwrap();
assert_eq!(selected, again);
}
#[test]
fn one_alias_change_invalidates_only_its_content_key() {
let alias = |file_key: &str, rel: &str| state::DuplicateFile {
file_key: file_key.to_string(),
rel: rel.to_string(),
path_id: format!("id:{rel}"),
is_symlink: Some(false),
duplicate_of: format!("{file_key}.txt"),
bytes: 10,
};
let previous = vec![alias("a", "a-copy.txt"), alias("c", "c-copy.txt")];
let current = vec![
alias("a", "a-copy.txt"),
alias("b", "b-copy.txt"),
alias("c", "c-copy.txt"),
];
assert_eq!(
alias_keys_to_reindex(&previous, ¤t, None),
HashSet::from(["b".to_string()])
);
assert_eq!(
alias_keys_to_reindex(¤t, &previous, None),
HashSet::from(["b".to_string()])
);
assert_eq!(
alias_keys_to_reindex(
&previous,
¤t,
Some(&["a".to_string(), "b".to_string(), "c".to_string()])
),
HashSet::from(["a".to_string(), "b".to_string(), "c".to_string()])
);
}
/// #487: an UNCHANGED re-index on a backend with `resumable == false`
/// (`neural`/`proxy`) must report the resume LIMITATION, not a false
/// "identity changed" — and must surface the backend's own reason rather
/// than sending the user to a remedy (restore the identity) that cannot work.
#[test]
fn unchanged_reindex_on_non_resumable_backend_reports_resume_limit_not_identity_change() {
let current = crate::esclient::EmbeddingExecutionIdentity {
version: 1,
backend: "neural".into(),
identity_sha256: "6e51e5ce3e46".into(),
dimensions: None,
semantic_contract: "semantic_text-derived-vector.v1".into(),
resumable: false,
non_resumable_reason: Some("identity is derived from the model name".into()),
ingest_probe_bytes: None,
ingest_probe_passages: None,
ingest_probe_millis: None,
};
// All comparable fields match → the identity did NOT change.
let err = ensure_embedding_execution_unchanged_and_resumable(
¤t,
"6e51e5ce3e46",
"neural",
None,
"semantic_text-derived-vector.v1",
)
.unwrap_err()
.to_string();
assert!(
err.contains("cannot resume") && !err.contains("identity changed"),
"must report the resume limitation, not a false identity change: {err}"
);
assert!(
err.contains("derived from the model name"),
"should surface the backend's own non_resumable_reason: {err}"
);
// A GENUINE change still reports "identity changed".
let changed = crate::esclient::EmbeddingExecutionIdentity {
identity_sha256: "DIFFERENT".into(),
resumable: true,
..current.clone()
};
let err2 = ensure_embedding_execution_unchanged_and_resumable(
&changed,
"6e51e5ce3e46",
"neural",
None,
"semantic_text-derived-vector.v1",
)
.unwrap_err()
.to_string();
assert!(
err2.contains("identity changed"),
"a real identity change must still report it: {err2}"
);
// A confirmed width that disagrees with the pinned width is a real
// change. An unconfirmed width on a non-resumable backend is not.
let wider = crate::esclient::EmbeddingExecutionIdentity {
dimensions: Some(768),
resumable: true,
non_resumable_reason: None,
..current.clone()
};
let err3 = ensure_embedding_execution_unchanged_and_resumable(
&wider,
"6e51e5ce3e46",
"neural",
None,
"semantic_text-derived-vector.v1",
)
.unwrap_err()
.to_string();
assert!(
err3.contains("identity changed") && err3.contains("768"),
"a different vector width must be reported as a change: {err3}"
);
let unconfirmed = crate::esclient::EmbeddingExecutionIdentity {
dimensions: None,
resumable: false,
non_resumable_reason: Some("vector width was not confirmed".into()),
..current
};
let err4 = ensure_embedding_execution_unchanged_and_resumable(
&unconfirmed,
"6e51e5ce3e46",
"neural",
Some(384),
"semantic_text-derived-vector.v1",
)
.unwrap_err()
.to_string();
assert!(
err4.contains("cannot resume") && !err4.contains("identity changed"),
"an unconfirmed width is a resume limit, not a changed identity: {err4}"
);
assert!(err4.contains("vector width was not confirmed"), "{err4}");
}
#[test]
fn duplicate_content_keeps_journal_and_live_id_cardinality_equal_on_resume() {
let corpus = tempfile::tempdir().unwrap();
let state_dir = tempfile::tempdir().unwrap();
let body = "quarterly revenue was 42\noperating income was 7\n";
fs::write(corpus.path().join("report-original.txt"), body).unwrap();
fs::write(corpus.path().join("report-copy.txt"), body).unwrap();
let discovered = walk::walk(corpus.path(), false).unwrap();
let inventory = content::resolve_reporting(discovered, &|_| {}).unwrap();
assert_eq!(inventory.files.len(), 1);
assert_eq!(inventory.duplicates.len(), 1);
let mut live_ids = HashSet::new();
let mut records = 0u64;
let sniffed = sniff::sniff(&inventory.files[0].path).unwrap();
extract::extract(&inventory.files[0].path, &sniffed, None, &mut |record| {
live_ids.insert(ids::doc_id("text", &inventory.keys[0], &record.locator));
records += 1;
true
})
.unwrap();
let mut journal = state::Journal::open(
state_dir.path(),
"corpus",
"http://engine",
"test",
300,
false,
)
.unwrap();
journal
.write_plan(&Plan {
duplicate_files: inventory.duplicates.clone(),
..Plan::default()
})
.unwrap();
journal
.file_done(&FileDone {
file_key: inventory.keys[0].clone(),
path: inventory.files[0].rel.clone(),
records,
junk: 0,
bytes: inventory.files[0].size,
dropped_by_dataset: HashMap::new(),
generation: Some(inventory.digests[0].clone()),
})
.unwrap();
drop(journal);
let resumed = state::Journal::open(
state_dir.path(),
"corpus",
"http://engine",
"test",
300,
false,
)
.unwrap();
assert!(resumed.resumed);
assert_eq!(
resumed.done.values().map(|f| f.records).sum::<u64>(),
records
);
assert_eq!(records as usize, live_ids.len());
let done = resumed.done_keys();
assert!(inventory.keys.iter().all(|key| done.contains(key)));
let aliases = &resumed.plan.unwrap().duplicate_files;
assert_eq!(aliases, &inventory.duplicates);
}
#[test]
fn mutation_after_more_than_one_bulk_is_staged_and_retry_replaces_stale_locators() {
let corpus = tempfile::tempdir().unwrap();
let path = corpus.path().join("large.csv");
let mut csv = String::from("id,value\n");
for id in 0..6_001 {
csv.push_str(&format!("{id},old-{id}\n"));
}
fs::write(&path, csv).unwrap();
let inventory =
content::resolve_reporting(walk::walk(corpus.path(), false).unwrap(), &|_| {}).unwrap();
let expected_size = inventory.files[0].size;
let expected_digest = inventory.digests[0].clone();
let sniffed = sniff::sniff(&path).unwrap();
let mut staged = tempfile::NamedTempFile::new().unwrap();
let mut staged_docs = 0usize;
extract::extract(&path, &sniffed, None, &mut |record| {
writeln!(
staged,
"{}\n{}",
record.locator,
Value::Object(record.fields)
)
.unwrap();
staged_docs += 1;
if staged_docs == 5_001 {
// A shorter source replaces the file while extraction is in
// progress, after the production 5,000-document bulk cut.
fs::write(&path, "id,value\n0,new-0\n1,new-1\n").unwrap();
}
true
})
.unwrap();
assert!(staged_docs > 5_000);
let mut live: HashSet<String> = (0..6_001).map(|id| format!("row:{id}")).collect();
assert!(content::verify(&path, expected_size, &expected_digest).is_err());
// Verification precedes delete/visibility, so a rejected attempt has
// not mixed any staged records into the old live set.
assert_eq!(live.len(), 6_001);
// The retry's delete-before-replace removes every old locator before
// the now-short source becomes visible.
live.clear();
let retry_sniffed = sniff::sniff(&path).unwrap();
extract::extract(&path, &retry_sniffed, None, &mut |record| {
live.insert(record.locator);
true
})
.unwrap();
assert_eq!(live, HashSet::from(["r0".into(), "r1".into()]));
}
}
#[cfg(test)]
mod map_metadata_tests {
use super::*;
fn assignment(slugs: &[&str]) -> FileAssignment {
FileAssignment {
rel: "report.dat".into(),
path_id: "path:report.dat".into(),
is_symlink: Some(false),
family: "json".into(),
gzip: false,
content_digest: Some("digest".into()),
assignments: slugs
.iter()
.enumerate()
.map(|(group, slug)| (Some(format!("group-{group}")), (*slug).to_string()))
.collect(),
as_document: false,
}
}
fn dataset(slug: &str) -> PlanDataset {
PlanDataset {
slug: slug.into(),
index: format!("ax-{slug}"),
family: "text".into(),
group: None,
specs: vec![],
time_field: None,
semantic_field: None,
text_analyzer: None,
scope: None,
sampled_records: 1,
file_count: 1,
}
}
fn done(key: &str, records: u64) -> (String, FileDone) {
(
key.into(),
FileDone {
file_key: key.into(),
path: format!("{key}.dat"),
records,
junk: 0,
bytes: 1,
dropped_by_dataset: HashMap::new(),
generation: None,
},
)
}
/// #2407: a live sibling must not hide a dataset that holds nothing. The
/// prose file wrote only to `docs`, which answers 0 while `json` is live.
/// A file that also feeds a live dataset cannot be shown missing (the
/// journal has one count per file), and a dataset with no count is
/// unknown, not empty.
#[test]
fn a_dataset_left_empty_beside_a_live_sibling_is_named() {
let plan = Plan {
datasets: vec![dataset("docs"), dataset("json"), dataset("mixed")],
files: HashMap::from([
("prose-1".into(), assignment(&["docs"])),
("prose-2".into(), assignment(&["docs"])),
("rows".into(), assignment(&["json"])),
("both".into(), assignment(&["mixed", "json"])),
("unknown".into(), assignment(&["refused"])),
]),
..Plan::default()
};
let journal = HashMap::from([
done("prose-1", 3),
done("prose-2", 2),
done("rows", 120),
done("both", 4),
done("unknown", 9),
// Swept from the folder: in the journal, not in the plan (#2314).
done("gone", 7),
]);
let counts = HashMap::from([
("docs".to_string(), 0),
("json".to_string(), 120),
("mixed".to_string(), 0),
]);
assert_eq!(
datasets_left_empty(&plan, &journal, &counts, &HashSet::new()),
[EmptyDataset {
index: "ax-docs".into(),
records: Some(5),
files: 2,
}]
);
let deliberately_excluded = HashSet::from(["prose-1".into(), "prose-2".into()]);
assert!(
datasets_left_empty(&plan, &journal, &counts, &deliberately_excluded).is_empty(),
"intentional exclusion sweeps are not missing writes"
);
// Every dataset live: nothing to name.
let live = HashMap::from([
("docs".to_string(), 5),
("json".to_string(), 120),
("mixed".to_string(), 0),
]);
assert!(datasets_left_empty(&plan, &journal, &live, &HashSet::new()).is_empty());
// A file whose every dataset is empty names each of them.
let both_empty = HashMap::from([
("docs".to_string(), 5),
("json".to_string(), 0),
("mixed".to_string(), 0),
]);
let ambiguous = datasets_left_empty(&plan, &journal, &both_empty, &HashSet::new());
assert!(
ambiguous.iter().all(|dataset| dataset.records.is_none()),
"one file's shared count must not be duplicated into each dataset: {ambiguous:?}"
);
let named: Vec<String> = datasets_left_empty(&plan, &journal, &both_empty, &HashSet::new())
.into_iter()
.map(|d| d.index)
.collect();
assert_eq!(named, ["ax-json", "ax-mixed"]);
}
#[test]
fn unchanged_resume_keeps_durable_assignment_aware_dataset_bytes() {
let _guard = state::FILE_DONE_IO_FAILPOINT_TEST_LOCK
.lock()
.unwrap_or_else(|p| p.into_inner());
let state_dir = tempfile::tempdir().unwrap();
let plan = Plan {
files: HashMap::from([
(
"shared".into(),
assignment(&["quarterly", "quarterly", "annual"]),
),
("quarterly-only".into(), assignment(&["quarterly"])),
]),
..Plan::default()
};
let mut initial = state::Journal::open(
state_dir.path(),
"corpus",
"http://engine",
"ax",
300,
false,
)
.unwrap();
initial.write_plan(&plan).unwrap();
initial
.file_done(&FileDone {
file_key: "shared".into(),
path: "report.dat".into(),
records: 10,
junk: 5,
bytes: 100,
dropped_by_dataset: HashMap::from([("quarterly".into(), 7), ("annual".into(), 3)]),
generation: Some("digest".into()),
})
.unwrap();
initial
.file_done(&FileDone {
file_key: "quarterly-only".into(),
path: "quarterly.json".into(),
records: 2,
junk: 2,
bytes: 23,
dropped_by_dataset: HashMap::from([("quarterly".into(), 11)]),
generation: Some("digest-2".into()),
})
.unwrap();
let before_resume = durable_dataset_stats(&plan, &initial.done);
drop(initial);
// Opening the same durable run appends only an invocation-level
// resume record. No source is processed and no FileDone is appended.
let resumed = state::Journal::open(
state_dir.path(),
"corpus",
"http://engine",
"ax",
300,
false,
)
.unwrap();
let after_unchanged_resume =
durable_dataset_stats(resumed.plan.as_ref().unwrap(), &resumed.done);
assert_eq!(before_resume, after_unchanged_resume);
assert_eq!(after_unchanged_resume["quarterly"].bytes, 123);
assert_eq!(after_unchanged_resume["annual"].bytes, 100);
assert_eq!(after_unchanged_resume["quarterly"].junk, 7);
assert_eq!(after_unchanged_resume["annual"].junk, 0);
assert_eq!(after_unchanged_resume["quarterly"].dropped, 18);
assert_eq!(after_unchanged_resume["annual"].dropped, 3);
}
#[test]
fn invocation_started_is_not_derived_from_summary_generation() {
let started = chrono::DateTime::parse_from_rfc3339("2026-08-04T00:29:05.673023686Z")
.unwrap()
.with_timezone(&chrono::Utc);
let summary_generated_at =
chrono::DateTime::parse_from_rfc3339("2026-08-04T00:31:37.937589283Z")
.unwrap()
.with_timezone(&chrono::Utc);
let (reported_started, reported_summary_generated_at) =
invocation_report_timestamps(started, summary_generated_at);
assert_eq!(reported_started, "2026-08-04T00:29:05.673023686+00:00");
assert_eq!(
reported_summary_generated_at,
"2026-08-04T00:31:37.937589283+00:00"
);
assert_ne!(reported_started, reported_summary_generated_at);
}
#[test]
fn catalog_mapping_declares_latest_invocation_telemetry_fields() {
let mapping = catalog::catalog_mapping();
assert_eq!(
mapping.pointer("/mappings/properties/started/type"),
Some(&json!("date"))
);
assert_eq!(
mapping.pointer("/mappings/properties/summary_generated_at/type"),
Some(&json!("date"))
);
assert_eq!(
mapping.pointer("/mappings/properties/invocation_telemetry_scope/type"),
Some(&json!("keyword"))
);
assert_eq!(
mapping.pointer("/mappings/properties/started/format"),
Some(&json!("strict_date_optional_time||epoch_millis"))
);
assert_eq!(
mapping.pointer("/mappings/properties/summary_generated_at/format"),
Some(&json!("strict_date_optional_time||epoch_millis"))
);
}
}
#[cfg(test)]
mod generation_contract_identity_tests {
use super::*;
#[test]
fn field_report_footer_honours_the_opt_out() {
// issue #1903: `xerj corpus index` printed it under XERJ_DISABLE_FEEDBACK=true
let on = with_field_report_if("next: x".to_string(), true);
assert!(on.contains(xerj_common::feedback::AUTO_SEND_LINE), "{on}");
let off = with_field_report_if("next: x".to_string(), false);
assert_eq!(off, "next: x");
assert!(!xerj_common::feedback::enabled_from(
["xerj", "corpus", "index", "lz4", "--disable-feedback"],
None
));
assert!(!xerj_common::feedback::enabled_from(
["xerj", "corpus", "index", "lz4"],
Some("true".to_string())
));
}
fn dataset(slug: &str, index: &str, family: &str) -> PlanDataset {
PlanDataset {
slug: slug.into(),
index: index.into(),
family: family.into(),
group: None,
specs: Vec::new(),
time_field: None,
semantic_field: None,
text_analyzer: None,
scope: None,
sampled_records: 0,
file_count: 0,
}
}
#[test]
fn contract_identities_are_order_independent_and_change_with_contracts() {
let mut first = Plan {
datasets: vec![
dataset("b", "prefix-b", "csv"),
dataset("a", "prefix-a", "json"),
],
..Plan::default()
};
let expected = generation_contract_identities(&first).unwrap();
first.datasets.reverse();
assert_eq!(generation_contract_identities(&first).unwrap(), expected);
first.datasets[0].family = "text".into();
let schema_changed = generation_contract_identities(&first).unwrap();
assert_ne!(schema_changed.0, expected.0);
first.datasets[0].family = "json".into();
first.datasets[0].index = "different-a".into();
let index_changed = generation_contract_identities(&first).unwrap();
assert_eq!(index_changed.0, expected.0);
assert_ne!(index_changed.1, expected.1);
}
/// #755 — `index_identity` is a FROZEN ON-DISK CONTRACT, not a free-running
/// digest. Every committed generation writes it into its journal execution
/// record, and the next run requires equality in two places: the
/// incremental-reconcile no-change arm ("autoindex execution configuration
/// changed since the committed generation; rebuild with a new --state-dir
/// and a new --prefix") and `provision_generation` ("desired generation
/// index identity disagrees with its frozen mappings"). So adding a
/// property to `catalog::catalog_mapping()` — which is hashed into that
/// identity — does not plan a fresh generation: it aborts the next run of
/// every state dir an older binary committed, permanently on the no-change
/// arm, because that arm writes no new generation to heal with. That is the
/// same abort-on-upgrade class #755 exists to remove, which is why
/// `catalog::CORPUS_SCOPE_FIELD` is installed additively in
/// `ensure_generation_mappings` (outside the hash) instead of declared in
/// the mapping.
///
/// Both halves are pinned, so updating the fixture to match a changed
/// mapping still fails: the serialized mapping against the copy captured
/// from the shipped tree, and the digests against literals measured by
/// compiling v1.0.0-rc.71 itself.
#[test]
fn catalog_mapping_is_the_frozen_on_disk_contract() {
assert_eq!(
serde_json::to_string(&catalog::catalog_mapping()).unwrap(),
frozen_contract::CATALOG_MAPPING_JSON,
"the catalog mapping is hashed into every committed generation's \
`index_identity`; changing it aborts the next run of every existing \
state dir. Install new catalog fields additively in \
`ensure_generation_mappings` instead"
);
let single = Plan {
datasets: vec![dataset("a", "ax-a", "json")],
..Plan::default()
};
let (schema_identity, index_identity) = generation_contract_identities(&single).unwrap();
assert_eq!(
index_identity, "2efb962fc36e015915c287ce8bb90e55",
"measured on v1.0.0-rc.71: this exact digest is in the field, frozen \
in committed journals"
);
assert_eq!(schema_identity, "fa78053f17039af9bbe0238a415f2268");
assert_eq!(index_identity, frozen_contract::index_identity(&single));
// Not only the one-dataset shape: the shipped-side mirror has to agree
// for any plan, since a real journal's plan is whatever was scanned.
let many = Plan {
datasets: vec![dataset("b", "ax-b", "csv"), dataset("a", "ax-a", "json")],
..Plan::default()
};
assert_eq!(
generation_contract_identities(&many).unwrap().1,
frozen_contract::index_identity(&many)
);
}
/// #1059: the stemming-analyzer election rides the plan but NOT the frozen
/// identities. If this ever breaks — the analyzer declared inside
/// `build_mapping`, or a serialized spec field carrying it — the next run
/// of every existing state dir aborts on the no-change arm with "autoindex
/// execution configuration changed since the committed generation", which
/// is exactly the upgrade-abort class the frozen-contract work removed.
#[test]
fn electing_the_stemming_analyzer_does_not_move_the_frozen_identities() {
let mut plan = Plan {
datasets: vec![dataset("a", "ax-a", "json")],
..Plan::default()
};
let before = generation_contract_identities(&plan).unwrap();
plan.datasets[0].text_analyzer = Some(infer::STEMMING_TEXT_ANALYZER.to_string());
let after = generation_contract_identities(&plan).unwrap();
assert_eq!(
before, after,
"the analyzer declaration must stay outside the hashed contract"
);
}
/// ONBOARDING-401-REPRO.md §3: a *successful* run signed off by printing
/// `next:` commands that carried no credential, so against an auth-enabled
/// server (the default) every one of them answered 401 — including the
/// `xerj autoindex map` line `xerj brain` prints after "your second brain
/// is ready". The run's own key and url must ride into the hints.
#[test]
fn next_hint_carries_the_runs_credential() {
// Key came from `--api-key` (or a file), not the environment: print it
// literally, because nothing else in the user's shell holds it.
let hint = next_hint("http://localhost:9510", "ax", Some("s3cret"), None, None);
assert!(
hint.contains("--api-key \"s3cret\""),
"map hint must carry the key, got: {hint}"
);
assert!(
hint.contains(
"xerj search --url http://localhost:9510 --prefix ax --api-key \"s3cret\""
),
"search hint must carry the url, prefix, and key, got: {hint}"
);
// Nothing is left as an un-runnable `GET /…` sketch.
assert!(
!hint.contains("search via GET"),
"hints must be runnable commands, got: {hint}"
);
// The key is already exported: reference the variable instead of
// echoing the admin secret into a banner people paste into issues.
let hint = next_hint(
"http://localhost:9200",
"ax",
Some("s3cret"),
Some("s3cret"),
None,
);
assert!(
!hint.contains("s3cret"),
"must not echo a secret already in the environment, got: {hint}"
);
assert!(
hint.contains("--api-key \"$XERJ_API_KEY\"")
&& hint.contains("xerj search --url http://localhost:9200 --prefix ax --api-key \"$XERJ_API_KEY\""),
"must reference the exported variable, got: {hint}"
);
// A different value in the environment is not the run's credential.
let hint = next_hint(
"http://localhost:9200",
"ax",
Some("s3cret"),
Some("other"),
None,
);
assert!(
hint.contains("--api-key \"s3cret\""),
"a stale env var must not shadow the run's key, got: {hint}"
);
// Open server: no credential to carry, and none invented.
let hint = next_hint("http://localhost:9200", "ax", None, Some("ignored"), None);
assert!(
!hint.contains("api-key") && !hint.contains("Authorization"),
"an auth-free server must get auth-free hints, got: {hint}"
);
assert!(hint.contains("xerj autoindex map --url http://localhost:9200"));
assert!(
hint.contains(xerj_common::feedback::AUTO_SEND_LINE),
"the indexing footer must carry the field-report permission line, got: {hint}"
);
assert!(
hint.contains("xerj search --url http://localhost:9200 --prefix ax"),
"an auth-free search hint is still the CLI, got: {hint}"
);
let code = code_search_hint("smoke-anyhow");
assert!(
code.contains("xerj search --prefix smoke-anyhow")
&& code.contains("xerj def --prefix smoke-anyhow"),
"{code}"
);
assert!(
!code.contains("curl"),
"the code hint must not send the reader to a raw search, got: {code}"
);
}
/// #1843: exit 3 read as failure because nothing an agent reads FIRST
/// said otherwise. Every finished run's stdout summary now opens with an
/// `ok:` line that names the exit code in words, and an exit-3 line says
/// what was recorded instead of hiding it.
#[test]
fn a_finished_run_leads_with_an_ok_line_that_spells_out_exit_3() {
let clean = outcome_headline(0, 0, 0, false, 0, None, 0);
assert!(clean.starts_with("ok: indexed and searchable"), "{clean}");
assert!(clean.contains("exit 0"), "{clean}");
let junk = outcome_headline(3, 1, 0, false, 0, None, 0);
assert!(junk.starts_with("ok: indexed and searchable"), "{junk}");
assert!(
junk.contains("exit 3 (completed-with-junk) is SUCCESS, not an error"),
"{junk}"
);
assert!(junk.contains("1 file recorded as junk"), "{junk}");
assert!(junk.contains("xerj autoindex"), "{junk}");
assert!(!junk.contains('\n'), "one line: {junk}");
let both = outcome_headline(3, 2, 5, false, 0, None, 0);
assert!(both.contains("2 files and 5 records"), "{both}");
let removed = outcome_headline(3, 0, 0, false, 0, None, 1);
assert!(
removed.contains("exit 3 (files-removed) is SUCCESS, not an error"),
"{removed}"
);
assert!(
removed.contains("no longer exist in the folder"),
"{removed}"
);
assert!(
!removed.contains("recorded as junk"),
"a removal is not junk: {removed}"
);
assert!(!removed.contains('\n'), "one line: {removed}");
let removed_and_junk = outcome_headline(3, 1, 0, false, 0, None, 2);
assert!(
removed_and_junk.contains("Also recorded as junk: 1 file"),
"{removed_and_junk}"
);
let stale = outcome_headline(3, 0, 0, false, 2, None, 0);
// #2411: the prefix is the contract. `ok:` says "this folder is
// searchable"; a stale plan leaves files on disk out of the index, so
// the line must not claim that.
assert!(stale.starts_with("not ok:"), "{stale}");
assert!(stale.contains("does not cover this folder"), "{stale}");
assert!(stale.contains("not searchable"), "{stale}");
assert!(stale.contains("exit 3 (stale-resume-plan)"), "{stale}");
assert!(
stale.contains("2 files skipped because the resumed plan is stale"),
"{stale}"
);
assert!(stale.contains("--fresh"), "{stale}");
assert!(
!stale.contains("recorded as junk"),
"a stale plan is not junk: {stale}"
);
assert!(!stale.contains('\n'), "one line: {stale}");
let stale_and_junk = outcome_headline(3, 1, 0, false, 2, None, 0);
assert!(
stale_and_junk.contains("Also recorded as junk: 1 file"),
"{stale_and_junk}"
);
let sweep = outcome_headline(3, 4, 0, true, 0, None, 0);
let pdfs = outcome_headline(1, 4, 0, false, 0, Some(4), 0);
assert!(pdfs.starts_with("not ok:"), "{pdfs}");
assert!(pdfs.contains("4 PDF files"), "{pdfs}");
assert!(pdfs.contains(PDF_WORKER_UNAVAILABLE_REASON), "{pdfs}");
assert!(!pdfs.contains("is SUCCESS"), "{pdfs}");
assert!(sweep.starts_with("ok: indexed and searchable"), "{sweep}");
assert!(sweep.contains(ALIAS_SWEEP_FAILED_REASON), "{sweep}");
assert!(sweep.contains("rerun the same command"), "{sweep}");
}
/// Resume of an already-indexed tokio tree printed
/// `submitted 0 source records from 0 files` beside 11246 live documents
/// and `(66096.3 docs/sec)`. The live count is the catalog; the rate is
/// this run's submissions.
#[test]
fn resume_that_sends_nothing_says_already_indexed_and_rates_zero() {
let line = indexed_vs_submitted_line(11246, 0, 0);
assert!(
line.contains("submitted 0 source records from 0 files"),
"{line}"
);
assert!(
line.contains("(already indexed; nothing new to send)"),
"{line}"
);
assert!(
!indexed_vs_submitted_line(11246, 11246, 861).contains("already indexed"),
"a first run that submitted records must keep the bare line"
);
assert!(
!indexed_vs_submitted_line(0, 0, 0).contains("already indexed"),
"an empty corpus is not already indexed"
);
assert_eq!(ingest_docs_per_sec(0, 0.2), 0.0);
assert_eq!(ingest_docs_per_sec(0, 0.0), 0.0);
assert_eq!(ingest_docs_per_sec(10, 2.0), 5.0);
// Live documents must not leak into the rate. The old formula was
// `11246 / 0.17 ≈ 66096`.
assert_eq!(ingest_docs_per_sec(0, 11246.0 / 66096.3), 0.0);
}
/// A tokio index stored CHANGELOG.md as `txt-lines` in `text`. The done
/// banner pasted a `match` on `body` only, so following it cannot see
/// that file. The hint names `text` and the run's `ax_format` values.
#[test]
fn mixed_corpus_hint_names_text_and_does_not_match_body_only() {
let hint = mixed_corpus_hint(&["code", "json", "txt-lines", "txt-prose"]);
assert!(
hint.contains("values in this run: code, json, txt-lines, txt-prose"),
"{hint}"
);
assert!(hint.contains("`text`"), "{hint}");
assert!(hint.contains("`body`"), "{hint}");
assert!(
hint.contains("ax_format"),
"the scope field must still be named, got: {hint}"
);
assert!(
!hint.contains("\"match\""),
"must not teach a body-only JSON filter, got: {hint}"
);
assert!(
!hint.contains("<text>"),
"must not leave a JSON placeholder, got: {hint}"
);
let empty = mixed_corpus_hint(&[]);
assert!(empty.contains("none recorded"), "{empty}");
assert!(!empty.contains("\"match\""), "{empty}");
}
/// A blind onboarding run found `autoindex` discovering `./data/admin.key`
/// on its own and then printing that admin key verbatim in its completion
/// banner. The reader never typed the secret, so echoing it into copyable
/// output is a disclosure — and this banner is exactly what people paste
/// into bug reports. Reference the file instead; `$(cat …)` still pastes.
#[test]
fn a_discovered_key_is_referenced_by_path_never_echoed() {
let path = std::path::Path::new("./data/admin.key");
let hint = next_hint(
"http://localhost:9200",
"ax",
Some("s3cret"),
None,
Some(path),
);
assert!(
!hint.contains("s3cret"),
"a key discovered on disk must never be echoed, got: {hint}"
);
assert!(
hint.contains("$(cat ./data/admin.key)"),
"the hint must read the key back from its file, got: {hint}"
);
}
#[test]
fn internal_contract_versions_are_explicit() {
assert_eq!(PREPARED_RECORDS_IDENTITY, "prepared-records-v1");
assert_eq!(DOCUMENT_IDS_IDENTITY, "document-ids-v1");
assert_eq!(DETECTOR_DISABLED_IDENTITY, "disabled");
}
}
/// #1059 — the stemming-analyzer declaration on the dataset index-create
/// body: what it carries, what it must never touch, and what an index that
/// already exists does with it (nothing).
#[cfg(test)]
mod stem_default_tests {
use super::*;
use crate::infer::FieldSpec;
use serde_json::json;
fn dataset(slug: &str, text_analyzer: Option<&str>) -> PlanDataset {
let spec = FieldSpec {
name: "body".into(),
es_type: "semantic_text".into(),
date_enc: None,
semantic: None,
cardinality_est: 0,
cardinality_overflow: false,
null_ratio: 0.0,
avg_len: 240.0,
coverage: 1.0,
examples: vec![],
notes: vec![],
date_min: None,
date_max: None,
date_evidence: vec![],
num_min: None,
num_max: None,
};
PlanDataset {
slug: slug.into(),
index: format!("ax-{slug}"),
family: "text".into(),
group: None,
specs: vec![spec],
time_field: None,
semantic_field: Some("body".into()),
text_analyzer: text_analyzer.map(str::to_string),
scope: None,
sampled_records: 1,
file_count: 1,
}
}
/// A dataset the profiler marked semantic declares the stemming analyzer
/// as `settings.analysis.analyzer.default` on the CREATE body — the
/// surface #937/#991 made honoured at flush, segment query and merge —
/// while the mapping itself is byte-identical to a dataset that declares
/// nothing (the mapping is the frozen on-disk contract; the analyzer must
/// stay outside it).
#[test]
fn a_semantic_dataset_declares_the_stemming_analyzer_on_the_create_body() {
let body = dataset_create_body(&dataset("prose", Some(infer::STEMMING_TEXT_ANALYZER)));
assert_eq!(
body.pointer("/settings/analysis/analyzer/default/type"),
Some(&json!("stemmer")),
"{body}"
);
// The mapping side is untouched: same properties as an undeclaring
// dataset, no per-field `analyzer` keys (the accepted-and-ignored
// surface), and `ax_paths` still present.
let undeclaring = dataset_create_body(&dataset("prose", None));
assert_eq!(
body["mappings"], undeclaring["mappings"],
"the analyzer declaration must not touch the mapping"
);
assert_eq!(
body.pointer("/mappings/properties/body"),
Some(&json!({"type": "semantic_text"}))
);
assert_eq!(
body.pointer("/mappings/properties/ax_paths"),
Some(&json!({"type": "keyword"}))
);
assert!(body.pointer("/mappings/properties/body/analyzer").is_none());
}
/// #1198: a code dataset elected under `--code-analyzer code` declares the
/// built-in `code` analyzer on the CREATE body, through the same #1059
/// path: the mapping is byte-identical to an undeclaring dataset's, and
/// the frozen identities do not move (existing state dirs never abort).
#[test]
fn a_code_analyzer_dataset_declares_code_on_the_create_body_outside_the_identities() {
let body = dataset_create_body(&dataset("code", Some(infer::CODE_TEXT_ANALYZER)));
assert_eq!(
body.pointer("/settings/analysis/analyzer/default/type"),
Some(&json!("code")),
"{body}"
);
let undeclaring = dataset_create_body(&dataset("code", None));
assert_eq!(body["mappings"], undeclaring["mappings"]);
let mut plan = Plan {
datasets: vec![dataset("code", None)],
..Plan::default()
};
let before = generation_contract_identities(&plan).unwrap();
plan.datasets[0].text_analyzer = Some(infer::CODE_TEXT_ANALYZER.to_string());
assert_eq!(before, generation_contract_identities(&plan).unwrap());
}
/// A dataset with no profiler-marked prose sends no ANALYZER settings —
/// the create body's analysis side is empty, so the server keeps
/// `standard`'s exact term space for identifier/enum data. The #1093
/// strict-mark is the one setting every create body carries (see
/// `every_create_body_marks_the_index_strict_on_unknown_fields`).
#[test]
fn a_non_semantic_dataset_sends_no_analyzer_settings() {
let body = dataset_create_body(&dataset("events", None));
assert!(body.pointer("/settings/analysis").is_none(), "{body}");
assert_eq!(
body.pointer("/mappings/properties/ax_paths"),
Some(&json!({"type": "keyword"}))
);
}
/// #2351: `start_line` is mapped on docs/code beside `end_line`, outside
/// `build_mapping`, so a frozen generation identity does not move. A
/// prose spec that already declared `start_line` is not sent again by
/// the graph upgrade. A log dataset does not gain the field.
#[test]
fn start_line_is_mapped_for_code_without_touching_the_generation_identity() {
let mut code = dataset("code", None);
code.family = "code".into();
assert!(code.specs.iter().all(|spec| spec.name != "start_line"));
let plan = Plan {
datasets: vec![code.clone()],
..Plan::default()
};
let before = generation_contract_identities(&plan).unwrap();
let body = dataset_create_body(&code);
assert_eq!(
body.pointer("/mappings/properties/start_line/type"),
Some(&json!("long")),
"{body}"
);
assert_eq!(
body.pointer("/mappings/properties/end_line/type"),
Some(&json!("long"))
);
assert_eq!(before, generation_contract_identities(&plan).unwrap());
let upgrade = graph_mapping_upgrade(&plan, &code);
assert_eq!(
upgrade.pointer("/properties/start_line/type"),
Some(&json!("long")),
"{upgrade}"
);
let mut prose = dataset("docs", None);
prose.family = "docs".into();
let mut declared = prose.specs[0].clone();
declared.name = "start_line".into();
declared.es_type = "long".into();
prose.specs.push(declared);
let prose_plan = Plan {
datasets: vec![prose.clone()],
..Plan::default()
};
let prose_upgrade = graph_mapping_upgrade(&prose_plan, &prose);
assert!(
prose_upgrade.pointer("/properties/start_line").is_none(),
"prose already maps start_line: {prose_upgrade}"
);
assert_eq!(
prose_upgrade.pointer("/properties/end_line/type"),
Some(&json!("long")),
"{prose_upgrade}"
);
let mut logs = dataset("logs", None);
logs.family = "logs".into();
let logs_body = dataset_create_body(&logs);
assert!(
logs_body
.pointer("/mappings/properties/start_line")
.is_none(),
"{logs_body}"
);
}
/// #1093: every dataset index THIS build creates is strict on unknown
/// lookup fields, either spelling of the settings object — the explicit
/// full schema makes a wrong field name a mistake, not a probe. It rides
/// the create body only (never `build_mapping`), so the frozen identity
/// digests do not move.
#[test]
fn every_create_body_marks_the_index_strict_on_unknown_fields() {
let semantic = dataset_create_body(&dataset("prose", Some(infer::STEMMING_TEXT_ANALYZER)));
assert_eq!(
semantic.pointer("/settings/index.query.strict_unknown_fields"),
Some(&json!(true)),
"{semantic}"
);
let plain = dataset_create_body(&dataset("events", None));
assert_eq!(
plain.pointer("/settings/index.query.strict_unknown_fields"),
Some(&json!(true)),
"{plain}"
);
// The analyzer declaration survives beside it.
assert_eq!(
semantic.pointer("/settings/analysis/analyzer/default/type"),
Some(&json!("stemmer")),
"{semantic}"
);
}
/// The declaration survives the journal round-trip, because a pending
/// generation replayed after a restart provisions its indexes from the
/// DESERIALIZED plan: an analyzer marker lost to serialization would
/// create that index unstemmed.
#[test]
fn the_analyzer_election_survives_the_journal_round_trip() {
let plan = Plan {
datasets: vec![dataset("prose", Some(infer::STEMMING_TEXT_ANALYZER))],
..Plan::default()
};
let round: Plan = serde_json::from_value(serde_json::to_value(&plan).unwrap()).unwrap();
assert_eq!(
round.datasets[0].text_analyzer.as_deref(),
Some(infer::STEMMING_TEXT_ANALYZER)
);
// A plan frozen by an older build deserializes with no election —
// the honest value for an index that already exists unstemmed.
let legacy = serde_json::json!({
"slug": "events", "index": "ax-events", "family": "json",
"specs": [], "sampled_records": 0, "file_count": 0
});
let legacy: PlanDataset = serde_json::from_value(legacy).unwrap();
assert_eq!(legacy.text_analyzer, None);
assert!(dataset_create_body(&legacy)
.pointer("/settings/analysis")
.is_none());
}
}
#[cfg(test)]
mod code_coverage_tests {
use super::*;
fn captured(buffer: &std::sync::Arc<Mutex<Vec<u8>>>) -> String {
String::from_utf8(buffer.lock().unwrap().clone()).unwrap()
}
/// The exact line that made #294 survivable for a whole release: over a
/// corpus of three source files and one `.md`, with every source file
/// junked, the run printed `files=4 records=1` — indistinguishable from a
/// healthy one-file corpus. Coverage plus a warning is what makes those
/// two runs print different lines.
#[test]
fn the_generated_terminal_line_carries_coverage_and_warns_when_no_code_indexed() {
let (pr, buffer) = progress::Progress::capture(
progress::Surface::Plain,
std::time::Duration::from_secs(3600),
);
finish_generated_progress(
&pr,
3,
&json!({
"files_indexed": 4,
"records_total": 1,
"generation": 1,
"code_files": 3,
"code_files_indexed": 0,
"code_files_junked": 3,
}),
0,
);
let text = captured(&buffer);
let done = text
.lines()
.find(|line| line.starts_with("xerj-done "))
.unwrap_or_else(|| panic!("{text}"));
assert!(
done.contains("code_files=3 code_files_indexed=0 code_files_junked=3"),
"{done}"
);
assert!(
text.lines()
.any(|line| line.starts_with("warning:") && line.contains("NONE")),
"a corpus that indexed no source code is warned about in words: {text}"
);
assert!(
text.trim_end()
.lines()
.next_back()
.unwrap()
.starts_with("xerj-done "),
"the terminal line stays terminal — the warning precedes it: {text}"
);
}
#[test]
fn a_healthy_corpus_reports_its_coverage_without_a_warning() {
let (pr, buffer) = progress::Progress::capture(
progress::Surface::Plain,
std::time::Duration::from_secs(3600),
);
finish_generated_progress(
&pr,
0,
&json!({
"files_indexed": 4,
"records_total": 8,
"generation": 1,
"code_files": 3,
"code_files_indexed": 3,
"code_files_junked": 0,
}),
0,
);
let text = captured(&buffer);
assert!(
text.contains("code_files=3 code_files_indexed=3 code_files_junked=0"),
"{text}"
);
assert!(
!text.contains("skipped_dataless"),
"a run that skipped nothing keeps the terminal line it had: {text}"
);
assert!(!text.contains("warning:"), "{text}");
}
#[test]
fn every_pdf_failing_to_start_ends_the_run_as_a_worker_outage() {
let (pr, buffer) = progress::Progress::capture(
progress::Surface::Plain,
std::time::Duration::from_secs(3600),
);
finish_generated_progress(
&pr,
3,
&json!({
"files_indexed": 2,
"records_total": 4,
"generation": 1,
"code_files": 0,
"code_files_indexed": 0,
"code_files_junked": 0,
"pdf_worker_unavailable": 2,
}),
0,
);
let text = captured(&buffer);
let done = text
.lines()
.find(|line| line.starts_with("xerj-done "))
.unwrap_or_else(|| panic!("{text}"));
assert!(done.contains("ok=false"), "{done}");
assert!(done.contains("exit=1"), "{done}");
assert!(done.contains("reason=pdf-worker-unavailable"), "{done}");
assert!(done.contains("pdf_worker_unavailable=2"), "{done}");
assert!(
text.lines()
.any(|line| line.starts_with("warning:") && line.contains("isolated PDF parser")),
"{text}"
);
assert!(
text.trim_end()
.lines()
.next_back()
.unwrap()
.starts_with("xerj-done "),
"the warning precedes the terminal line: {text}"
);
}
/// #2370: the terminal line of a run that dropped a family is not the line
/// of a clean run. The warning names the family, the count, and the reason,
/// and it precedes `xerj-done`.
#[test]
fn a_junked_family_is_warned_on_the_terminal_line() {
let (pr, buffer) = progress::Progress::capture(
progress::Surface::Plain,
std::time::Duration::from_secs(3600),
);
finish_generated_progress(
&pr,
3,
&json!({
"files_indexed": 2,
"records_total": 4,
"generation": 1,
"code_files": 2,
"code_files_indexed": 2,
"code_files_junked": 0,
"files_junk": 4,
"family_junk_warnings": [{
"family": "pdf",
"files": 4,
"junk_files": 4,
"indexed_files": 0,
"extent": "all",
"top_reason": "could not start the isolated PDF parser",
"top_reason_files": 4
}]
}),
0,
);
let text = captured(&buffer);
let done = text
.lines()
.find(|line| line.starts_with("xerj-done "))
.unwrap_or_else(|| panic!("{text}"));
assert!(done.contains("family_junk_warnings=1"), "{done}");
assert!(done.contains("exit=3"), "{done}");
assert!(
text.lines().any(|line| {
line.starts_with("warning: pdf family:")
&& line.contains("all 4 files")
&& line.contains("could not start the isolated PDF parser")
}),
"{text}"
);
assert!(
text.trim_end()
.lines()
.next_back()
.unwrap()
.starts_with("xerj-done "),
"the warning precedes the terminal line: {text}"
);
}
/// `--quiet` drops notes and the terminal line. A dropped family is a
/// safety warning: it still has to reach stderr (#2370).
#[test]
fn a_junked_family_warning_is_not_silenced_by_quiet() {
let (pr, buffer) = progress::Progress::capture(
progress::Surface::Silent,
std::time::Duration::from_secs(3600),
);
finish_generated_progress(
&pr,
3,
&json!({
"files_indexed": 1,
"records_total": 1,
"generation": 1,
"code_files": 1,
"code_files_indexed": 1,
"code_files_junked": 0,
"family_junk_warnings": [{
"family": "pdf",
"files": 4,
"junk_files": 4,
"indexed_files": 0,
"extent": "all",
"top_reason": "worker down",
"top_reason_files": 4
}]
}),
0,
);
let text = captured(&buffer);
assert!(
text.contains("warning: pdf family:") && text.contains("worker down"),
"{text}"
);
assert!(
!text.contains("xerj-done"),
"quiet still prints no terminal line: {text}"
);
}
#[test]
fn a_clean_summary_does_not_grow_a_family_warning_on_the_terminal_line() {
let (pr, buffer) = progress::Progress::capture(
progress::Surface::Plain,
std::time::Duration::from_secs(3600),
);
finish_generated_progress(
&pr,
0,
&json!({
"files_indexed": 3,
"records_total": 9,
"generation": 1,
"code_files": 3,
"code_files_indexed": 3,
"code_files_junked": 0,
}),
0,
);
let text = captured(&buffer);
assert!(!text.contains("family_junk_warnings"), "{text}");
assert!(!text.contains("warning:"), "{text}");
}
#[test]
fn skipped_dataless_placeholders_are_counted_on_the_terminal_line() {
let (pr, buffer) = progress::Progress::capture(
progress::Surface::Plain,
std::time::Duration::from_secs(3600),
);
finish_generated_progress(
&pr,
0,
&json!({
"files_indexed": 1,
"records_total": 1,
"generation": 2,
"code_files": 0,
"code_files_indexed": 0,
"code_files_junked": 0,
}),
3,
);
let text = captured(&buffer);
let done = text
.lines()
.find(|line| line.starts_with("xerj-done "))
.unwrap_or_else(|| panic!("{text}"));
assert!(done.contains("skipped_dataless=3"), "{done}");
}
/// A corpus with no source code in it at all must not start warning, and a
/// gzipped source file is still a source file.
#[test]
fn coverage_counts_families_not_compression_and_stays_quiet_without_code() {
let mut coverage = CodeCoverage::default();
coverage.observe("txt-prose", 4);
coverage.observe("csv", 0);
assert_eq!(coverage, CodeCoverage::default());
assert!(coverage.warning().is_none());
coverage.observe("code", 1);
coverage.observe("code(gzip)", 0);
assert_eq!(
(coverage.files, coverage.indexed, coverage.junked),
(2, 1, 1)
);
assert!(
coverage.warning().is_none(),
"partial loss is reported by the counters, not by the warning"
);
assert_eq!(
coverage.fields(),
[
("code_files", 2),
("code_files_indexed", 1),
("code_files_junked", 1)
]
);
}
/// 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)]
mod failure_resume_http_tests;
#[cfg(test)]
mod incremental_reconcile_http_tests;
#[cfg(test)]
mod label_http_tests;
#[cfg(test)]
mod refused_dataset_tests;
/// The Unity PIPELINE half — `build_unity_guid_map` + `enrich_unity_fields`
/// + the plan's field registration, driven through the real phase-A planner.
///
/// The PR that introduced Unity support tested `extract::unity::*` thoroughly
/// and this half not at all, which is why the sample-conditional mapping
/// registration survived review: no unit test of an extractor can see a bug
/// whose cause is what phase A sampled.
#[cfg(test)]
mod unity_pipeline_tests {
use super::*;
const GUID: &str = "abc123def4560000";
/// A scene whose MonoBehaviour group's FIRST document has no `m_Script`
/// and whose SECOND one does. With `sample: 1`, phase A therefore never
/// sees `script_guid` — but phase B still stamps `script_path` from the
/// second record. That gap is the bug.
fn scene_with_late_script_ref() -> String {
format!(
"%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n\
--- !u!1 &1\nGameObject:\n m_Name: Player\n\
--- !u!114 &2\nMonoBehaviour:\n m_Name: NoScriptYet\n speed: 1\n\
--- !u!114 &3\nMonoBehaviour:\n m_Name: HasScript\n \
m_Script: {{fileID: 11500000, guid: {GUID}, type: 3}}\n"
)
}
fn write_project(dir: &Path) {
std::fs::create_dir_all(dir.join("Assets/Scripts")).unwrap();
std::fs::create_dir_all(dir.join("Assets/Scenes")).unwrap();
std::fs::write(
dir.join("Assets/Scripts/PlayerController.cs.meta"),
format!("fileFormatVersion: 2\nguid: {GUID}\nMonoImporter:\n serializedVersion: 2\n"),
)
.unwrap();
std::fs::write(
dir.join("Assets/Scenes/Main.unity"),
scene_with_late_script_ref(),
)
.unwrap();
}
fn plan_for(root: &Path, sample: usize) -> (Plan, Vec<walk::FileEntry>) {
let files = walk::walk(root, false).unwrap();
let keys: Vec<String> = files
.iter()
.map(|f| ids::file_key(&f.path, f.size).unwrap())
.collect();
let digests: Vec<String> = (0..files.len()).map(|i| format!("d{i}")).collect();
let budget = extract::pdf::ExtractionSpoolBudget::new(0, 0);
let progress = Progress::silent();
let meter = estimate::Meter::new();
let ctx = PhaseAContext {
state_dir: root,
budget: &budget,
capacity_warning: None,
progress: &progress,
meter: &meter,
tally: &ScanTally::default(),
};
let mut cfg = super::phase_a_grouping_tests::cfg_for(root);
cfg.sample = sample;
let plan = build_phase_a(root, &files, &keys, &digests, Vec::new(), &ctx, &cfg).plan;
(plan, files)
}
/// #1158's zero-text warning: a dataset whose sampled fields are all
/// keyword/numeric warns, one with any text-searchable spec does not.
#[test]
fn a_dataset_with_no_text_searchable_field_warns_at_plan_time() {
let kw = |name: &str| {
let mut s = pipeline_keyword_spec(name);
s.es_type = "keyword".into();
s
};
let warned = textless_dataset_note(&[kw("sha256"), kw("size")], "gitsnap");
let Some(note) = warned else {
panic!("a keyword-only dataset must warn");
};
assert!(note.contains("gitsnap"), "{note}");
assert!(note.contains("sha256:keyword"), "{note}");
assert!(note.contains("passage search"), "{note}");
let mut text = kw("summary");
text.es_type = "text".into();
assert!(
textless_dataset_note(&[kw("id"), text.clone()], "advisories").is_none(),
"a dataset with a text field is searchable"
);
text.es_type = "semantic_text".into();
assert!(
textless_dataset_note(&[kw("id"), text], "advisories").is_none(),
"semantic_text counts as searchable too"
);
}
#[test]
fn the_guid_map_resolves_a_meta_sidecar_to_its_asset_path() {
let dir = tempfile::tempdir().unwrap();
write_project(dir.path());
let (plan, files) = plan_for(dir.path(), 500);
let g = build_unity_guid_map(&files, &plan, &Progress::silent());
assert_eq!(
g.map.get(GUID).map(String::as_str),
Some("Assets/Scripts/PlayerController.cs"),
"guid must resolve to the asset the .meta sits beside"
);
assert!(g.unreadable.is_empty(), "{:?}", g.unreadable);
assert!(g.no_guid.is_empty(), "{:?}", g.no_guid);
}
/// Blocker: `script_path`/`script_class` were registered in the explicit
/// mapping only when the SAMPLE happened to contain `script_guid`. Phase A
/// reads a bounded window, so a cluster whose window held no `m_Script`
/// got them dynamic-mapped at index time instead — the field-budget
/// overshoot of #312.
#[test]
fn script_link_fields_are_mapped_even_when_the_sample_never_saw_a_script_guid() {
let dir = tempfile::tempdir().unwrap();
write_project(dir.path());
let (plan, _) = plan_for(dir.path(), 1);
let mb = plan
.datasets
.iter()
.find(|d| d.group.as_deref() == Some("MonoBehaviour"))
.expect("a MonoBehaviour cluster must exist");
assert!(
!mb.specs.iter().any(|s| s.name == "script_guid"),
"precondition: with sample=1 the sampled window must NOT contain \
script_guid, or this test proves nothing"
);
for want in ["script_path", "script_class"] {
assert!(
mb.specs.iter().any(|s| s.name == want),
"{want} must be in the explicit mapping regardless of what the \
sample saw; specs = {:?}",
mb.specs.iter().map(|s| &s.name).collect::<Vec<_>>()
);
}
}
/// End to end over the two halves: the guid map built from `.meta` files
/// resolves the `script_guid` an extractor emitted, and the enrichment
/// stamps both denormalized fields. This is the feature's headline query
/// ("which scenes use this script?") reduced to its mechanism.
#[test]
fn enrichment_resolves_a_script_guid_to_path_and_class() {
let dir = tempfile::tempdir().unwrap();
write_project(dir.path());
let (plan, files) = plan_for(dir.path(), 500);
let g = build_unity_guid_map(&files, &plan, &Progress::silent());
let mut fields = Map::new();
fields.insert("script_guid".into(), Value::String(GUID.into()));
let unresolved = enrich_unity_fields(
Family::UnityYaml,
&mut fields,
&g.map,
"Assets/Scenes/Main.unity",
);
assert_eq!(unresolved, None, "a defined guid must resolve");
assert_eq!(fields["script_path"], "Assets/Scripts/PlayerController.cs");
assert_eq!(fields["script_class"], "PlayerController");
}
/// Blocker: an unresolvable `script_guid` produced no counter, no warning
/// and no report line — the record shipped without `script_path`, and
/// "no users" and "broken link" became the same answer.
#[test]
fn an_unresolvable_script_guid_is_reported_not_swallowed() {
let mut fields = Map::new();
fields.insert("script_guid".into(), Value::String("deadbeef".into()));
let unresolved = enrich_unity_fields(
Family::UnityYaml,
&mut fields,
&std::collections::HashMap::new(),
"Assets/Scenes/Main.unity",
);
assert_eq!(
unresolved.as_deref(),
Some("deadbeef"),
"the caller must be told which guid failed"
);
assert!(!fields.contains_key("script_path"));
}
/// The enrichment was moved to run BEFORE `coerce_record` so its fields
/// are validated like every other field instead of bypassing coercion.
/// That only works if the plan actually carries them — this drives the
/// real `coerce::plan_from_specs` over the real planned specs and asserts
/// both fields survive the round trip with their values intact.
#[test]
fn enriched_fields_survive_the_coercion_they_now_pass_through() {
let dir = tempfile::tempdir().unwrap();
write_project(dir.path());
let (plan, files) = plan_for(dir.path(), 500);
let g = build_unity_guid_map(&files, &plan, &Progress::silent());
let mb = plan
.datasets
.iter()
.find(|d| d.group.as_deref() == Some("MonoBehaviour"))
.expect("a MonoBehaviour cluster must exist");
let coerce_plan = coerce::plan_from_specs(&mb.specs);
assert!(
coerce_plan.contains_key("script_path"),
"the coercion plan must know the field, else it would pass through \
unvalidated exactly as it did before"
);
let mut fields = Map::new();
fields.insert("script_guid".into(), Value::String(GUID.into()));
let _ = enrich_unity_fields(
Family::UnityYaml,
&mut fields,
&g.map,
"Assets/Scenes/Main.unity",
);
let dropped = coerce::coerce_record(&mut fields, &coerce_plan);
assert_eq!(dropped, 0, "nothing may be dropped: {fields:?}");
assert_eq!(fields["script_path"], "Assets/Scripts/PlayerController.cs");
assert_eq!(fields["script_class"], "PlayerController");
}
/// The failures the map collects have to reach a person. Counting them
/// into a struct nobody prints is the same silence in a different place.
#[test]
fn the_guid_map_failures_are_printed_with_names_and_counts() {
let (pr, buffer) = progress::Progress::capture(
progress::Surface::Plain,
std::time::Duration::from_secs(3600),
);
let g = UnityGuidMap {
map: std::collections::HashMap::new(),
unreadable: vec![("Assets/A.cs.meta".into(), "permission denied".into())],
no_guid: vec!["Assets/B.cs.meta".into()],
};
report_unity_guid_map(&g, &pr);
let text = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
assert!(text.contains("Assets/A.cs.meta"), "{text}");
assert!(text.contains("permission denied"), "{text}");
assert!(text.contains("Assets/B.cs.meta"), "{text}");
assert!(text.contains("no guid"), "{text}");
// A healthy map must stay quiet — a warning on every clean run is a
// warning nobody reads.
let (pr2, buf2) = progress::Progress::capture(
progress::Surface::Plain,
std::time::Duration::from_secs(3600),
);
report_unity_guid_map(&UnityGuidMap::default(), &pr2);
assert!(String::from_utf8(buf2.lock().unwrap().clone())
.unwrap()
.is_empty());
}
/// Blocker: `build_unity_guid_map` discarded `extract_meta`'s `Result`.
/// An unparseable `.meta` therefore produced silence.
#[test]
fn a_meta_that_carries_no_guid_is_recorded() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("Assets")).unwrap();
// Sniffs as UnityMeta (first line is `fileFormatVersion:` and a line
// starts `guid:`) but the value is a YAML integer, so `extract_meta`
// recovers no guid STRING — the sidecar is real and still unusable.
std::fs::write(
dir.path().join("Assets/Broken.cs.meta"),
"fileFormatVersion: 2\nguid: 12345\nMonoImporter:\n serializedVersion: 2\n",
)
.unwrap();
let (plan, files) = plan_for(dir.path(), 500);
let g = build_unity_guid_map(&files, &plan, &Progress::silent());
assert!(g.map.is_empty(), "no guid should have resolved");
assert_eq!(
g.no_guid,
vec!["Assets/Broken.cs.meta".to_string()],
"the .meta with no usable guid must be named, not silently skipped"
);
}
}
#[cfg(test)]
mod container_progress_tests {
use super::{container_extract_credit, container_send_credit, CONTAINER_EXTRACT_PERCENT};
/// Whatever the split, the two stages together cover the file EXACTLY:
/// extraction ends where sending starts, sending ends on the file's size.
#[test]
fn the_two_stages_meet_and_end_on_the_file_size() {
for size in [0u64, 1, 99, 100, 1_073_777_879, u64::MAX] {
let seam = container_extract_credit(size, size);
assert_eq!(container_send_credit(size, 0, 1000), seam, "size={size}");
assert_eq!(container_send_credit(size, 1000, 1000), size, "size={size}");
assert!(seam <= size);
// Nothing staged (every entry was junk): stay at the seam; the
// guard's drop credits the rest.
assert_eq!(container_send_credit(size, 0, 0), seam);
}
assert_eq!(
container_extract_credit(1000, 1000),
10 * CONTAINER_EXTRACT_PERCENT
);
}
#[test]
fn credit_is_monotonic_and_never_overflows() {
let size = u64::MAX;
let mut last = 0;
for offset in [0, 1, u64::MAX / 3, u64::MAX / 2, u64::MAX - 1, u64::MAX] {
let c = container_extract_credit(size, offset);
assert!(c >= last && c <= size);
last = c;
}
let mut last = container_extract_credit(size, size);
for sent in [0u64, 1, 500, 999, 1000, 5000] {
let c = container_send_credit(size, sent, 1000);
assert!(c >= last && c <= size, "sent={sent}");
last = c;
}
}
/// A gzipped mailbox reports DECOMPRESSED offsets, which run past the size
/// on disk. Extraction must stop at its own share.
#[test]
fn a_decompressed_offset_past_the_file_size_is_clamped() {
let size = 1000;
assert_eq!(
container_extract_credit(size, 50_000),
container_extract_credit(size, size)
);
}
}
#[cfg(test)]
mod bulk_pipe_tests {
use super::{AtomicU64, BulkPipe, Mutex, Ordering};
use crate::esclient::BulkOutcome;
fn outcome() -> BulkOutcome {
BulkOutcome {
item_errors: 0,
refused: Vec::new(),
server_errors: 0,
first_error: None,
first_server_error: None,
throttled_out: 0,
exhausted_after: None,
}
}
/// A send function that records every body it was handed.
fn recording_send(
bodies: &Mutex<Vec<Vec<u8>>>,
) -> impl Fn(Vec<u8>) -> anyhow::Result<BulkOutcome> + '_ {
move |body| {
bodies.lock().unwrap().push(body);
Ok(outcome())
}
}
/// #1147's headline: many small files share ONE bulk instead of paying
/// one round-trip each. With a single worker, the residual flush happens
/// at settle time (the "no more bytes are coming" trigger).
#[test]
fn small_files_coalesce_into_one_bulk() {
let bodies = Mutex::new(Vec::new());
let rejected = AtomicU64::new(0);
let pipe = BulkPipe::new(recording_send(&bodies), 1 << 20, 5000, &rejected, 1);
let t1 = pipe.token();
let t2 = pipe.token();
let t3 = pipe.token();
pipe.submit(t1, b"action1\ndoc1\n".to_vec(), 1);
pipe.submit(t2, b"action2\ndoc2\n".to_vec(), 1);
pipe.submit(t3, b"action3\ndoc3\n".to_vec(), 1);
assert!(
bodies.lock().unwrap().is_empty(),
"under the cut, nothing flushes early"
);
pipe.settle(t1).expect("t1 accepted");
pipe.settle(t2).expect("t2 accepted");
pipe.settle(t3).expect("t3 accepted");
pipe.retire();
let bodies = bodies.lock().unwrap();
assert_eq!(
bodies.len(),
1,
"the single-worker residual flush is one body"
);
assert_eq!(
bodies[0],
b"action1\ndoc1\naction2\ndoc2\naction3\ndoc3\n".to_vec(),
"one body, input order"
);
}
/// A file's chunk larger than the cut flushes INLINE — one huge file must
/// not wait for the end of the run (and must not blow memory).
#[test]
fn an_oversized_chunk_flushes_inline() {
let bodies = Mutex::new(Vec::new());
let rejected = AtomicU64::new(0);
let pipe = BulkPipe::new(recording_send(&bodies), 64, 5000, &rejected, 1);
let t = pipe.token();
let big: Vec<u8> = vec![b'x'; 200];
pipe.submit(t, big, 3);
assert_eq!(
bodies.lock().unwrap().len(),
1,
"crossing the cut flushes immediately"
);
pipe.settle(t).expect("accepted");
pipe.retire();
}
/// #1122: workers whose threads never started must stop counting as
/// live. A pipe sized for four with three abandoned is a one-worker pipe:
/// that worker's residual buffer ships as soon as it settles, instead of
/// parking for a 30 s timeout waiting on three workers that do not exist.
#[test]
fn abandoned_workers_do_not_hold_back_the_residual_buffer() {
let bodies = Mutex::new(Vec::new());
let rejected = AtomicU64::new(0);
let pipe = BulkPipe::new(recording_send(&bodies), 64, 5000, &rejected, 4);
pipe.abandon_workers(3);
let t = pipe.token();
pipe.submit(t, vec![b'x'; 10], 1);
assert!(bodies.lock().unwrap().is_empty(), "below the cut: buffered");
let started = std::time::Instant::now();
pipe.settle(t).expect("accepted");
assert!(
started.elapsed() < std::time::Duration::from_secs(10),
"the lone live worker shipped its own residual, took {:?}",
started.elapsed()
);
assert_eq!(bodies.lock().unwrap().len(), 1);
pipe.retire();
}
/// A transport failure settles Err for EVERY file whose bytes rode that
/// body — the un-journaled-on-failure contract the journal's resume
/// depends on.
#[test]
fn a_failed_bulk_fails_every_file_it_carried() {
let rejected = AtomicU64::new(0);
let pipe = BulkPipe::new(
|_body| Err(anyhow::anyhow!("connection reset by peer")),
1 << 20,
5000,
&rejected,
1,
);
let t1 = pipe.token();
let t2 = pipe.token();
pipe.submit(t1, b"a\n".to_vec(), 1);
pipe.submit(t2, b"b\n".to_vec(), 1);
let e1 = pipe.settle(t1).expect_err("t1 must fail");
let e2 = pipe.settle(t2).expect_err("t2 must fail");
assert_eq!(e1, e2, "one failed body, one failure for all its files");
assert!(
e1.contains("connection reset"),
"the cause is preserved: {e1}"
);
}
/// A file larger than one flush has bytes in SEVERAL bulks. If the first
/// bulk fails and a later one succeeds, the file's failure is STICKY:
/// settling Ok would journal the source complete while most of its
/// records were never accepted — the exact hole
/// `existing_completion_is_invalidated_and_partial_visibility_is_deleted_on_resume`
/// caught in the first cut of this pipe (fail on bulk 1 of 2, the tail
/// bulk succeeded, the file journaled complete).
#[test]
fn a_later_successful_bulk_does_not_erase_an_earlier_failure() {
let rejected = AtomicU64::new(0);
let attempts = Mutex::new(0);
let pipe = BulkPipe::new(
{
let attempts = &attempts;
move |_body| {
let mut n = attempts.lock().unwrap();
*n += 1;
if *n == 1 {
Err(anyhow::anyhow!("connection reset by peer"))
} else {
Ok(outcome())
}
}
},
// doc_cap 1: every submit flushes, so one file spans two bulks.
1 << 20,
1,
&rejected,
1,
);
let big_file = pipe.token();
let other_file = pipe.token();
pipe.submit(big_file, b"first-chunk\n".to_vec(), 1);
assert!(pipe.failed(big_file), "the failed bulk marked its file");
assert!(!pipe.failed(other_file));
// The next bulk carries the SAME file's tail plus another file, and
// succeeds.
pipe.submit(big_file, b"second-chunk\n".to_vec(), 1);
pipe.submit(other_file, b"other\n".to_vec(), 1);
let err = pipe
.settle(big_file)
.expect_err("sticky: bulk 2 succeeding must not clear bulk 1's failure");
assert!(
err.contains("connection reset"),
"the FIRST cause is kept: {err}"
);
pipe.settle(other_file)
.expect("the healthy file still settles Ok");
pipe.retire();
}
/// server_errors (the backend refused items) also settles Err — that is
/// the "do not journal the source file complete" arm of #944/#956.
#[test]
fn server_errors_settle_err_without_poisoning_later_batches() {
let rejected = AtomicU64::new(0);
let attempts = Mutex::new(0);
let pipe = BulkPipe::new(
{
let attempts = &attempts;
move |_body| {
let mut n = attempts.lock().unwrap();
*n += 1;
if *n == 1 {
Ok(BulkOutcome {
server_errors: 2,
first_server_error: Some("cluster block".into()),
..outcome()
})
} else {
Ok(outcome())
}
}
},
1 << 20,
5000,
&rejected,
1,
);
let bad = pipe.token();
pipe.submit(bad, b"a\n".to_vec(), 1);
let err = pipe.settle(bad).expect_err("refused items do not journal");
assert!(err.contains("cluster block"), "{err}");
let good = pipe.token();
pipe.submit(good, b"b\n".to_vec(), 1);
pipe.settle(good).expect("the pipe keeps working");
pipe.retire();
}
/// A refused record fails only the file whose `_id` it carried, so that
/// file is not journaled; a neighbour in the same bulk settles Ok (#2807).
/// A refusal the pipe cannot attribute fails every file in the bulk.
/// #2807: a file is set aside only when every refusal it got was a size
/// refusal. A size refusal in one bulk and a mapping refusal in a later one
/// must fail the run, not set the file aside; the flag is not sticky.
#[test]
fn a_file_with_any_other_refusal_is_not_set_aside() {
let rejected = AtomicU64::new(0);
let calls = AtomicU64::new(0);
let pipe = BulkPipe::new(
|_body| {
let first = calls.fetch_add(1, Ordering::Relaxed) == 0;
Ok(BulkOutcome {
item_errors: 1,
refused: vec![crate::esclient::RefusedItem {
id: Some(if first { "a-1" } else { "a-2" }.into()),
error: if first { "too large" } else { "mapper refused" }.into(),
too_large: first,
}],
first_error: Some("refused".into()),
..outcome()
})
},
1,
5000,
&rejected,
1,
);
let a = pipe.token();
pipe.submit(a, b"{\"index\":{\"_id\":\"a-1\"}}\n{}\n".to_vec(), 1);
pipe.submit(a, b"{\"index\":{\"_id\":\"a-2\"}}\n{}\n".to_vec(), 1);
pipe.settle(a).unwrap_err();
pipe.quiesce(a);
assert_eq!(calls.load(Ordering::Relaxed), 2, "both bulks landed");
assert_eq!(pipe.take_too_large(a), None);
pipe.retire();
}
#[test]
fn a_refused_record_fails_only_its_own_file() {
let rejected = AtomicU64::new(0);
let refused = |id: Option<&str>| crate::esclient::RefusedItem {
id: id.map(str::to_owned),
error: "mapper refused field".into(),
too_large: false,
};
let pipe = BulkPipe::new(
|_body| {
Ok(BulkOutcome {
item_errors: 1,
refused: vec![refused(Some("a-1"))],
first_error: Some("mapper refused field".into()),
..outcome()
})
},
1 << 20,
5000,
&rejected,
2,
);
let a = pipe.token();
let b = pipe.token();
pipe.submit(a, b"{\"index\":{\"_id\":\"a-1\"}}\n{}\n".to_vec(), 1);
pipe.submit(b, b"{\"index\":{\"_id\":\"b-1\"}}\n{}\n".to_vec(), 1);
let error = pipe.settle(a).unwrap_err();
assert!(
error.contains("refused 1 of this file's record(s)"),
"{error}"
);
pipe.settle(b)
.expect("a file whose records were all accepted settles Ok");
assert_eq!(rejected.load(Ordering::Relaxed), 1);
pipe.retire();
let rejected = AtomicU64::new(0);
let pipe = BulkPipe::new(
|_body| {
Ok(BulkOutcome {
item_errors: 1,
refused: vec![refused(None)],
first_error: Some("mapper refused field".into()),
..outcome()
})
},
1 << 20,
5000,
&rejected,
1,
);
let t = pipe.token();
pipe.submit(t, b"a\n".to_vec(), 3);
assert!(
pipe.settle(t).is_err(),
"an unattributed refusal fails the file"
);
pipe.retire();
}
/// A file whose staging produced nothing (all junk / unrouted) settles
/// instantly: the journal records zero records and no bulk is sent.
#[test]
fn a_file_with_no_records_settles_without_sending() {
let bodies = Mutex::new(Vec::new());
let rejected = AtomicU64::new(0);
let pipe = BulkPipe::new(recording_send(&bodies), 1 << 20, 5000, &rejected, 1);
let t = pipe.token();
pipe.settle(t).expect("pre-resolved");
pipe.retire();
assert!(bodies.lock().unwrap().is_empty());
}
/// Sends must OVERLAP, not alternate: the first cut of this pipe held the
/// lock across the wire (one bulk at a time), and phase B on the rustsec
/// corpus measured 4.7x SLOWER than the per-file code it replaced —
/// extraction and sending serialized behind a full-wave barrier. Here N
/// cut-crossing submits from N threads must put more than one body on
/// the wire at once.
#[test]
fn wire_slots_overlap_instead_of_serializing() {
let rejected = AtomicU64::new(0);
let concurrent = AtomicU64::new(0);
let peak = AtomicU64::new(0);
let pipe = BulkPipe::new(
{
let concurrent = &concurrent;
let peak = &peak;
move |_body| {
let now = concurrent.fetch_add(1, Ordering::SeqCst) + 1;
peak.fetch_max(now, Ordering::SeqCst);
std::thread::sleep(std::time::Duration::from_millis(60));
concurrent.fetch_sub(1, Ordering::SeqCst);
Ok(outcome())
}
},
64,
5000,
&rejected,
4,
);
let tokens: Vec<_> = (0..4).map(|_| pipe.token()).collect();
std::thread::scope(|s| {
for t in tokens {
let pipe = &pipe;
s.spawn(move || {
pipe.submit(t, vec![b'x'; 200], 1);
pipe.settle(t).expect("accepted");
});
}
});
pipe.retire();
assert!(
peak.load(Ordering::SeqCst) >= 2,
"at least two bodies were on the wire together, peak={}",
peak.load(Ordering::SeqCst)
);
}
/// The concurrent shape phase B actually runs: many workers, many small
/// files. Coalescing must happen (far fewer bodies than files) with every
/// token settling Ok and no deadlock — the parked/live accounting is what
/// this test would hang on if it were wrong.
#[test]
fn many_workers_many_files_coalesce_without_deadlock() {
let bodies = Mutex::new(Vec::new());
let rejected = AtomicU64::new(0);
let pipe = BulkPipe::new(
{
let bodies = &bodies;
move |body| {
std::thread::sleep(std::time::Duration::from_millis(2));
bodies.lock().unwrap().push(body);
Ok(outcome())
}
},
1 << 20,
5000,
&rejected,
8,
);
const WORKERS: usize = 8;
const FILES_PER_WORKER: usize = 40;
std::thread::scope(|s| {
for w in 0..WORKERS {
let pipe = &pipe;
s.spawn(move || {
for i in 0..FILES_PER_WORKER {
let t = pipe.token();
pipe.submit(t, format!("w{w}-f{i}\n").into_bytes(), 1);
pipe.settle(t).expect("every file accepted");
}
pipe.retire();
});
}
});
let n = bodies.lock().unwrap().len();
assert!(
n < WORKERS * FILES_PER_WORKER,
"{WORKERS}x{FILES_PER_WORKER} files left as {n} bodies — no coalescing happened"
);
}
/// #2841: with every wire slot busy, two workers cross the cut and park.
/// When a slot frees, the first one awake ships the whole buffer, the
/// other's bytes with it. The other wakes to an empty buffer, so it can
/// never take a job of its own; it must still return once its bytes were
/// accepted. It used to park again, every 30 s, for good, and the run
/// stalled at 16 and 32 workers on a 26-file corpus.
#[test]
fn a_worker_whose_bytes_another_worker_shipped_returns() {
use std::sync::Condvar;
use std::time::{Duration, Instant};
// 'static, so a worker that never returns fails this test instead
// of hanging it inside a thread scope.
let gate: &'static (Mutex<bool>, Condvar) =
Box::leak(Box::new((Mutex::new(false), Condvar::new())));
let on_wire: &'static AtomicU64 = Box::leak(Box::new(AtomicU64::new(0)));
let rejected: &'static AtomicU64 = Box::leak(Box::new(AtomicU64::new(0)));
let pipe = &*Box::leak(Box::new(BulkPipe::new(
move |_body| {
on_wire.fetch_add(1, Ordering::SeqCst);
let (open, cv) = gate;
let mut open = open.lock().unwrap();
while !*open {
open = cv.wait(open).unwrap();
}
Ok(outcome())
},
64,
5000,
rejected,
10,
)));
let wait_until = |what: &str, ok: &dyn Fn() -> bool| {
let deadline = Instant::now() + Duration::from_secs(10);
while !ok() {
assert!(Instant::now() < deadline, "timed out waiting for {what}");
std::thread::sleep(Duration::from_millis(5));
}
};
// Fill every wire slot with a body the gate holds.
for _ in 0..super::MAX_IN_FLIGHT {
let t = pipe.token();
std::thread::spawn(move || pipe.submit(t, vec![b'x'; 200], 1));
}
wait_until("every wire slot to be busy", &|| {
on_wire.load(Ordering::SeqCst) == super::MAX_IN_FLIGHT as u64
});
let (tx, rx) = std::sync::mpsc::channel();
let mut tokens = Vec::new();
for parked in 1..=2 {
let t = pipe.token();
tokens.push(t);
let tx = tx.clone();
std::thread::spawn(move || {
pipe.submit(t, vec![b'y'; 200], 1);
tx.send(t).unwrap();
});
wait_until("a worker to park on the full wire", &|| {
pipe.lock().parked_workers == parked
});
}
let (open, cv) = gate;
*open.lock().unwrap() = true;
cv.notify_all();
for _ in 0..2 {
rx.recv_timeout(Duration::from_secs(10))
.expect("both parked workers return once their bytes were shipped");
}
for t in tokens {
pipe.settle(t).expect("accepted");
}
assert_eq!(
on_wire.load(Ordering::SeqCst),
super::MAX_IN_FLIGHT as u64 + 1,
"the two parked workers' bytes rode one body"
);
}
/// A parked worker whose chunk another worker shipped must not return
/// until that chunk has landed, even when the wire frees up and the
/// buffer holds someone else's bytes it could ship instead. Returning
/// early let a file's tail settle `Ok` while its earlier chunk was still
/// on the wire, so a later failure of that chunk went unread.
#[test]
fn a_parked_worker_returns_only_after_its_own_chunk_lands() {
use std::sync::Condvar;
use std::time::{Duration, Instant};
type Gate = (Mutex<bool>, Condvar);
fn hold(gate: &Gate) {
let mut open = gate.0.lock().unwrap();
while !*open {
open = gate.1.wait(open).unwrap();
}
}
fn open(gate: &Gate) {
*gate.0.lock().unwrap() = true;
gate.1.notify_all();
}
let leak_gate =
|| -> &'static Gate { Box::leak(Box::new((Mutex::new(false), Condvar::new()))) };
// Seven bodies of `x` and one of `z` fill the wire; the parked
// workers' shared body (it carries `a`) is held on its own gate.
let x_gate = leak_gate();
let z_gate = leak_gate();
let a_gate = leak_gate();
let on_wire: &'static AtomicU64 = Box::leak(Box::new(AtomicU64::new(0)));
let rejected: &'static AtomicU64 = Box::leak(Box::new(AtomicU64::new(0)));
let pipe = &*Box::leak(Box::new(BulkPipe::new(
move |body: Vec<u8>| {
on_wire.fetch_add(1, Ordering::SeqCst);
if body.contains(&b'a') {
hold(a_gate);
} else if body.first() == Some(&b'x') {
hold(x_gate);
} else if body.first() == Some(&b'z') {
hold(z_gate);
}
Ok(outcome())
},
64,
5000,
rejected,
10,
)));
let wait_until = |what: &str, ok: &dyn Fn() -> bool| {
let deadline = Instant::now() + Duration::from_secs(10);
while !ok() {
assert!(Instant::now() < deadline, "timed out waiting for {what}");
std::thread::sleep(Duration::from_millis(5));
}
};
for (fill, byte) in [(super::MAX_IN_FLIGHT - 1, b'x'), (1, b'z')] {
let busy = pipe.lock().in_flight + fill;
for _ in 0..fill {
let t = pipe.token();
std::thread::spawn(move || pipe.submit(t, vec![byte; 200], 1));
}
wait_until("the wire to fill", &|| pipe.lock().in_flight == busy);
}
assert_eq!(pipe.lock().in_flight, super::MAX_IN_FLIGHT);
let (tx, rx) = std::sync::mpsc::channel();
let mut tokens = Vec::new();
for (parked, byte) in [(1, b'a'), (2, b'b')] {
let t = pipe.token();
tokens.push(t);
let tx = tx.clone();
std::thread::spawn(move || {
pipe.submit(t, vec![byte; 200], 1);
tx.send(t).unwrap();
});
wait_until("a worker to park on the full wire", &|| {
pipe.lock().parked_workers == parked
});
}
// One slot frees: one parked worker ships both chunks, held on the
// wire; the other parks again with its chunk in flight.
open(z_gate);
wait_until("the shared body to go out", &|| {
on_wire.load(Ordering::SeqCst) == super::MAX_IN_FLIGHT as u64 + 1
});
wait_until("the other worker to park again", &|| {
pipe.lock().parked_workers == 1
});
// Another file's sub-cut chunk waits in the buffer, then the rest of
// the wire frees up.
let c = pipe.token();
tokens.push(c);
pipe.submit(c, vec![b'c'; 10], 1);
open(x_gate);
wait_until("the x bodies to land", &|| pipe.lock().in_flight == 1);
std::thread::sleep(Duration::from_millis(200));
assert!(
rx.try_recv().is_err(),
"a worker returned while its chunk was still on the wire"
);
open(a_gate);
for _ in 0..2 {
rx.recv_timeout(Duration::from_secs(10))
.expect("both workers return once their chunk has landed");
}
pipe.retire();
for t in tokens {
pipe.settle(t).expect("accepted");
}
}
}
#[cfg(test)]
mod legacy_rebuild_argv_tests {
use super::*;
fn parse_index(argv: &[String]) -> IndexCfg {
match cli::parse(argv.to_vec()).expect("the rebuild argv must parse") {
cli::Cmd::Index(cfg) => *cfg,
other => panic!("expected an index command, got {other:?}"),
}
}
fn strings(args: &[&str]) -> Vec<String> {
args.iter().map(|s| s.to_string()).collect()
}
/// Following the printed rebuild advice must index the same corpus the same
/// way: read the argv back through `cli::parse` and compare every setting
/// that changes what is indexed or how it is analyzed.
fn assert_round_trip(original: &[&str]) {
let cfg = parse_index(&strings(original));
let state = Path::new("state.generation-v1");
let argv = legacy_rebuild_argv(&cfg, state, "ax-generation-v1");
assert_eq!(&argv[..2], ["xerj", "autoindex"]);
let rebuilt = parse_index(&argv[2..]);
assert_eq!(rebuilt.root, cfg.root);
assert_eq!(rebuilt.url, cfg.url);
assert_eq!(rebuilt.state_dir.as_deref(), Some(state));
assert_eq!(rebuilt.prefix, "ax-generation-v1");
assert!(rebuilt.no_graph);
assert_eq!(rebuilt.code_analyzer, cfg.code_analyzer, "{argv:?}");
assert_eq!(rebuilt.stub_globs, cfg.stub_globs, "{argv:?}");
assert_eq!(rebuilt.ignore.enabled, cfg.ignore.enabled, "{argv:?}");
assert_eq!(rebuilt.ignore.defaults, cfg.ignore.defaults, "{argv:?}");
assert_eq!(rebuilt.label, cfg.label, "{argv:?}");
assert_eq!(rebuilt.no_semantic, cfg.no_semantic);
assert_eq!(rebuilt.follow_symlinks, cfg.follow_symlinks);
assert_eq!(
rebuilt.follow_symlinks_outside_root,
cfg.follow_symlinks_outside_root
);
assert_eq!(rebuilt.max_file_bytes, cfg.max_file_bytes);
assert_eq!(rebuilt.sample, cfg.sample);
assert_eq!(rebuilt.workers, cfg.workers);
assert_eq!(rebuilt.bulk_mb, cfg.bulk_mb);
assert_eq!(rebuilt.budget_plan, cfg.budget_plan, "{argv:?}");
assert_eq!(rebuilt.drop_indexed, cfg.drop_indexed, "{argv:?}");
}
#[test]
fn rebuild_argv_carries_every_setting_that_shapes_the_index() {
assert_round_trip(&[
"data",
"--no-graph",
"--code-analyzer",
"code",
"--stub",
"*.bin",
"--stub",
"vendor/**",
"--no-default-ignores",
"--label",
"questions.json",
"--no-semantic",
"--follow-symlinks",
"--sample",
"80",
]);
assert_round_trip(&["data", "--no-graph", "--no-ignore"]);
// #1233: a sub-GB cap must survive the rebuild-advice round-trip, which
// the old integer-GB flag could not express.
assert_round_trip(&["data", "--no-graph", "--max-file-mb", "10"]);
assert_round_trip(&["data", "--no-graph", "--max-file-bytes", "4096"]);
assert_round_trip(&["data", "--no-graph", "--max-file-gb", "3"]);
assert_round_trip(&[
"data",
"--no-graph",
"--plan",
"code-and-docs",
"--drop-indexed",
]);
}
/// #1233: the "skipped: oversized" note renders the byte cap in the
/// coarsest whole binary unit, so it reads `2 GB` / `10 MB` rather than a
/// raw byte count, and falls back to exact bytes when neither divides.
#[test]
fn human_size_reads_in_the_coarsest_whole_unit() {
assert_eq!(human_size(2 << 30), "2 GB");
assert_eq!(human_size(10 << 20), "10 MB");
assert_eq!(human_size(4096), "4096 bytes");
assert_eq!(human_size(0), "0 bytes");
}
#[test]
fn an_oversized_family_skip_names_the_file_size_and_the_flag() {
assert_eq!(
oversized_family_reason("json", 3 << 30, 2 << 30),
"oversized for non-streaming family json (3 GB > 2 GB); raise --max-file-mb"
);
}
/// #1233 back-compat: an index built before sub-GB caps existed serialised
/// its cap as the top-level `max_file_gb` integer. A whole-GB cap must still
/// produce that exact key (so the prepared-records digest is unchanged and
/// the index resumes), while a genuinely sub-GB cap gets a distinct key and
/// therefore a distinct, non-resumable digest.
#[test]
fn prepared_records_identity_is_byte_compatible_for_whole_gb_caps() {
let base = parse_index(&strings(&["data", "--no-graph"]));
assert_eq!(
base.label, None,
"this test assumes the default (no label set)"
);
let ident = |bytes: u64| {
let mut c = base.clone();
c.max_file_bytes = bytes;
prepared_records_identity(&c).unwrap()
};
let two_gb = ident(2 << 30);
let ten_mb = ident(10 << 20);
let one_gb = ident(1 << 30);
assert_ne!(two_gb, ten_mb, "a sub-GB cap is a different contract");
assert_ne!(one_gb, two_gb, "different whole-GB caps differ");
// The whole-GB value serialises the historical top-level `max_file_gb`
// integer key: the digest is the xxh3 of the JSON, so matching it to a
// value hand-built with that exact key (the pre-#1233 wire form) proves
// existing indexes still re-derive their digest and resume. serde_json
// sorts keys, so insertion order here is irrelevant.
let expected = serde_json::json!({
"contract": PREPARED_RECORDS_IDENTITY,
"sample": base.sample,
"no_semantic": base.no_semantic,
"pdf_timeout_secs": base.pdf_timeout_secs,
"label": serde_json::Value::Null,
"max_file_gb": 2,
});
let want = format!(
"{}-{:032x}",
PREPARED_RECORDS_IDENTITY,
xxhash_rust::xxh3::xxh3_128(&serde_json::to_vec(&expected).unwrap())
);
assert_eq!(
two_gb, want,
"whole-GB cap must keep the historical wire form"
);
}
#[test]
fn rebuild_argv_for_default_settings_adds_no_optional_flags() {
assert_round_trip(&["data", "--no-graph"]);
let cfg = parse_index(&strings(&["data", "--no-graph"]));
let argv = legacy_rebuild_argv(&cfg, Path::new("s"), "p");
for flag in [
"--code-analyzer",
"--stub",
"--no-ignore",
"--no-default-ignores",
"--label",
] {
assert!(!argv.iter().any(|a| a == flag), "{flag} in {argv:?}");
}
}
}
/// #2368: `xerj autoindex map <folder>` previews a folder that has not been
/// indexed. The preview is the `--dry-run` discovery path, so this test runs
/// that command against a node that accepts reads and refuses to pretend a
/// write succeeded: any bulk, document, or mapping request fails the test.
#[cfg(test)]
mod map_folder_preview {
use super::{cli, run_index};
use std::io::{BufRead, BufReader, Read, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
struct Node {
url: String,
requests: Arc<Mutex<Vec<(String, String)>>>,
stop: Arc<AtomicBool>,
join: Option<std::thread::JoinHandle<()>>,
}
impl Node {
fn start() -> Self {
let listener = crate::test_loopback::bind();
listener.set_nonblocking(true).unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let requests = Arc::new(Mutex::new(Vec::new()));
let stop = Arc::new(AtomicBool::new(false));
let requests_bg = Arc::clone(&requests);
let stop_bg = Arc::clone(&stop);
let join = std::thread::spawn(move || {
while !stop_bg.load(Ordering::Relaxed) {
match listener.accept() {
Ok((mut stream, _)) => {
stream.set_nonblocking(false).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut request_line = String::new();
if reader.read_line(&mut request_line).unwrap_or(0) == 0 {
continue;
}
let mut content_length = 0usize;
loop {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
break;
}
if line == "\r\n" || line.is_empty() {
break;
}
if let Some(value) =
line.to_ascii_lowercase().strip_prefix("content-length:")
{
content_length = value.trim().parse().unwrap_or(0);
}
}
if content_length > 0 {
let mut body = vec![0; content_length];
let _ = reader.read_exact(&mut body);
}
let mut parts = request_line.split_whitespace();
let method = parts.next().unwrap_or("").to_string();
let path = parts.next().unwrap_or("").to_string();
requests_bg
.lock()
.unwrap()
.push((method.clone(), path.clone()));
let (status, body) = if method == "GET" && path == "/" {
(200, r#"{"ok":true}"#)
} else if method == "GET" && path.starts_with("/_cat/allocation") {
(
200,
r#"[{"disk.percent":"10","disk.avail":"1073741824b","disk.flood_stage":"95","disk.threshold_enabled":"true","disk.flood_blocked":"false"}]"#,
)
} else {
(404, r#"{"error":"absent"}"#)
};
let reason = if status == 200 { "OK" } else { "Not Found" };
let _ = write!(
stream,
"HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(5));
}
Err(error) => panic!("accept failed: {error}"),
}
}
});
Self {
url,
requests,
stop,
join: Some(join),
}
}
fn requests(&self) -> Vec<(String, String)> {
self.requests.lock().unwrap().clone()
}
}
impl Drop for Node {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(join) = self.join.take() {
let _ = join.join();
}
}
}
#[test]
fn map_folder_previews_an_unindexed_folder_and_writes_no_index() {
let node = Node::start();
let root = tempfile::tempdir().unwrap();
let state = tempfile::tempdir().unwrap();
let marker = "map-preview-marker-2368";
std::fs::write(
root.path().join("readme.md"),
format!("# Notes\n\n{marker}\n"),
)
.unwrap();
std::fs::write(root.path().join("plain.txt"), "a short note\n").unwrap();
let before = std::fs::read(root.path().join("readme.md")).unwrap();
let args = vec![
"map".to_string(),
root.path().display().to_string(),
"--url".to_string(),
node.url.clone(),
"--prefix".to_string(),
"mappreview".to_string(),
"--state-dir".to_string(),
state.path().display().to_string(),
"--quiet".to_string(),
"--max-minutes".to_string(),
"0".to_string(),
];
let cmd = cli::parse(args).expect("map <folder> must parse");
let cli::Cmd::Index(cfg) = cmd else {
panic!("map <folder> must take the dry-run index path, got {cmd:?}");
};
assert!(cfg.dry_run, "the preview must not index");
assert_eq!(cfg.prefix, "mappreview");
let code = run_index(*cfg).expect("preview of an unindexed folder");
assert_eq!(code, 0, "a preview that finishes is exit 0");
assert_eq!(
std::fs::read(root.path().join("readme.md")).unwrap(),
before,
"the preview must not rewrite the folder"
);
// `--dry-run` opens the journal and appends the run header before it
// prints the plan. The preview is that path, so the header is present
// and nothing past it (no plan, no file completion, no generation) is.
let journal = std::fs::read_to_string(state.path().join("journal.ndjson"))
.expect("the preview opens the same resume journal --dry-run opens");
let mut kinds = Vec::new();
for line in journal.lines().filter(|line| !line.is_empty()) {
let record: serde_json::Value = serde_json::from_str(line).expect(line);
kinds.push(
record
.get("kind")
.and_then(|kind| kind.as_str())
.unwrap_or("")
.to_string(),
);
}
assert_eq!(
kinds,
vec!["run".to_string()],
"the preview journal must be only the run header, not indexing work: {journal}"
);
let requests = node.requests();
assert!(
requests.iter().any(|(m, p)| m == "GET" && p == "/"),
"the preview contacts the node: {requests:?}"
);
assert!(
requests
.iter()
.any(|(m, p)| m == "POST" && p.contains("autoindex-catalog")),
"the preview checks the catalog before discovering: {requests:?}"
);
let writes: Vec<_> = requests
.iter()
.filter(|(method, path)| {
method == "PUT"
|| method == "DELETE"
|| path.contains("_bulk")
|| path.contains("_doc")
|| path.contains("_mapping")
|| path.contains("_update")
})
.collect();
assert!(
writes.is_empty(),
"map <folder> must not write an index: {writes:?}"
);
}
}
#[cfg(test)]
mod dataset_time_range_tests {
use super::*;
use std::io::Read;
use std::sync::Arc;
const T_MIN: i64 = 1_790_812_800_000; // 2026-10-01T00:00:00Z
const T_MAX: i64 = 1_790_985_600_000; // 2026-10-03T00:00:00Z
fn iso(ms: i64) -> String {
xerj_common::schema::epoch_ms_to_iso8601_utc(ms)
}
fn read_body(stream: &mut std::net::TcpStream) -> Value {
stream
.set_read_timeout(Some(std::time::Duration::from_secs(2)))
.unwrap();
let mut request = Vec::new();
let mut buffer = [0u8; 4096];
loop {
let count = stream.read(&mut buffer).unwrap_or(0);
if count == 0 {
break;
}
request.extend_from_slice(&buffer[..count]);
if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
let length = headers
.lines()
.find_map(|l| l.strip_prefix("content-length:")?.trim().parse().ok())
.unwrap_or(0usize);
if request.len() >= end + 4 + length {
return serde_json::from_slice(&request[end + 4..end + 4 + length])
.unwrap_or(Value::Null);
}
}
}
Value::Null
}
/// A node that behaves like xerj on a large index: any aggregation that
/// needs the corpus is refused by the per-query memory guard, while a
/// sorted size-1 search answers from doc values.
#[test]
fn time_bounds_come_from_sorted_searches_not_materialising_aggs() {
let listener = crate::test_loopback::bind();
let address = listener.local_addr().unwrap();
let bodies = Arc::new(Mutex::new(Vec::<Value>::new()));
let seen = Arc::clone(&bodies);
let server = std::thread::spawn(move || {
for stream in listener.incoming().take(2) {
let mut stream = stream.unwrap();
let body = read_body(&mut stream);
seen.lock().unwrap().push(body.clone());
let (status, reply) = if body.get("aggs").is_some() {
(
"429 Too Many Requests",
json!({"error":{"type":"circuit_breaking_exception","reason":"[request] query allocation (768.2mb) would exceed limits.max_query_memory_mb=512MB at [aggregation corpus materialisation]"},"status":429}),
)
} else {
let asc = body.pointer("/sort/0/t/order") == Some(&json!("asc"));
let key = if asc { T_MIN } else { T_MAX };
(
"200 OK",
json!({"hits":{"total":{"value":3},"hits":[
{"_id":"x","_source":{"t":iso(key)},"sort":[key]}]}}),
)
};
let reply = reply.to_string();
let _ = write!(
stream,
"HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}",
reply.len()
);
}
});
let es = Es::new(&format!("http://{address}"), None).unwrap();
let range = dataset_time_range(&es, "i", "t").unwrap();
server.join().unwrap();
assert_eq!(range, (Some(iso(T_MIN)), Some(iso(T_MAX))));
for body in bodies.lock().unwrap().iter() {
assert!(body.get("aggs").is_none(), "materialising agg sent: {body}");
assert_eq!(body.get("size"), Some(&json!(1)), "{body}");
}
}
}
/// The line printed when a walk found no files but skipped links, naming the
/// flags that would index them (#2823). `None` when no link was skipped.
pub(crate) fn skipped_links_hint(report: &ignore_rules::IgnoreReport) -> Option<String> {
let count = |rule: &str| {
report
.by_rule
.get(rule)
.map_or(0, |c| c.files.saturating_add(c.dirs))
};
let not_followed = count(ignore_rules::NOT_FOLLOWED_RULE);
let outside = count(ignore_rules::ESCAPED_ROOT_RULE);
let total = not_followed.saturating_add(outside);
if total == 0 {
return None;
}
let flags = if outside > 0 {
"--follow-symlinks --follow-symlinks-outside-root"
} else {
"--follow-symlinks (add --follow-symlinks-outside-root for targets outside the folder)"
};
Some(format!(
"{total} symlink{} skipped: links are not followed by default. To index them, rerun with {flags}",
if total == 1 { " was" } else { "s were" }
))
}
#[cfg(test)]
mod skipped_links_hint_tests {
use super::skipped_links_hint;
use crate::ignore_rules::{IgnoreReport, RuleCount, ESCAPED_ROOT_RULE, NOT_FOLLOWED_RULE};
#[test]
fn no_skipped_links_no_hint() {
assert_eq!(skipped_links_hint(&IgnoreReport::default()), None);
}
#[test]
fn unfollowed_links_name_the_flags() {
let mut report = IgnoreReport::default();
report.by_rule.insert(
NOT_FOLLOWED_RULE.to_string(),
RuleCount {
files: 3,
..RuleCount::default()
},
);
let hint = skipped_links_hint(&report).expect("links skipped: a hint");
assert!(hint.starts_with("3 symlinks were skipped"), "{hint}");
assert!(hint.contains("--follow-symlinks "), "{hint}");
assert!(hint.contains("--follow-symlinks-outside-root"), "{hint}");
}
#[test]
fn escaped_links_ask_for_both_flags() {
let mut report = IgnoreReport::default();
report.by_rule.insert(
ESCAPED_ROOT_RULE.to_string(),
RuleCount {
dirs: 1,
..RuleCount::default()
},
);
let hint = skipped_links_hint(&report).expect("escaped link: a hint");
assert!(
hint.contains("1 symlink was skipped")
&& hint.ends_with("--follow-symlinks --follow-symlinks-outside-root"),
"{hint}"
);
}
}