Skip to content

armgit / xerj

Public Imported from GitHub
0

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

autoindex: --label stamps /_decide answers on documents at ingest (#1062)

xerj-org3ade44371a24
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rs
index 1f9546205..b3e98ba8b 100644
--- a/engine/crates/xerj-autoindex/src/cli.rs
+++ b/engine/crates/xerj-autoindex/src/cli.rs
@@ -101,6 +101,11 @@ pub struct IndexCfg {
/// Progress cadence. `None` means "the surface's default" — 1 s on a
/// terminal, 5 s for a pipe.
pub progress_interval: Option<Duration>,
+ /// `--label <question-set.json>`: run every extracted record's payload
+ /// through the node's `POST /_decide` at ingest and stamp `label` /
+ /// `label_p` (plus per-question `label_<id>` / `label_<id>_p`) onto the
+ /// document (#1062). `None` — the default — never constructs a Labeler.
+ pub label: Option<PathBuf>,
/// `--watch`: after the first pass, stay resident and reindex what changes.
pub watch: bool,
/// `--watch`'s quiet period. One editor save is several filesystem events,
@@ -311,6 +316,13 @@ pub fn help_text_with(feedback: bool) -> String {
subdirectory, which this flag cannot do.\n\
--yes, -y alias for --approve proceed\n\
--dry-run walk+sniff+infer, print the plan, index nothing\n\
+ --label <FILE> label each document at ingest through POST /_decide\n\
+ (#1062): the question-set file's noul/choice questions\n\
+ are rendered against each record's fields and the vote\n\
+ stamped on as label + label_p (and label_<id> +\n\
+ label_<id>_p per question). p is the RAW decide\n\
+ confidence - calibration is #1063. One /_decide call\n\
+ per noul (per option, for a choice) per document.\n\
--json machine-readable RESULT on stdout (map: raw catalog docs).\n\
Orthogonal to --progress, which owns stderr.\n\
--progress <MODE> liveness on stderr: auto|plain|json|none (default auto).\n\
@@ -688,6 +700,9 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
let mut events_out: Option<PathBuf> = None;
let mut status_file: Option<PathBuf> = None;
let mut watch_flags_used: Vec<&'static str> = Vec::new();
+ // `--label` (#1062): ingest-time decide labelling. Kept in its own
+ // variable so the routes that do not label can refuse it by name.
+ let mut label: Option<PathBuf> = None;
while let Some(arg) = it.next() {
match arg.as_str() {
@@ -785,6 +800,11 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
endpoint_url = Some(value);
}
"--fresh" => fresh = true,
+ "--label" => {
+ label = Some(PathBuf::from(
+ it.next().ok_or("--label needs a question-set file path")?,
+ ))
+ }
"--follow-symlinks" => follow_symlinks = true,
"--follow-symlinks-outside-root" => follow_symlinks_outside_root = true,
"--stub" => stub_globs.push(it.next().ok_or("--stub needs a glob pattern")?),
@@ -1095,6 +1115,14 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
.into(),
);
}
+ if label.is_some() {
+ return Err(
+ "--watch and --label are not combined today: a watcher would have to re-run the \
+ decide votes of every changed record on every pass, and that pass has not been \
+ built. Index once with --label, then start the watcher without it"
+ .into(),
+ );
+ }
if fresh {
return Err(
"--watch and --fresh contradict each other: --fresh discards the resume journal \
@@ -1272,6 +1300,13 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
.into(),
);
}
+ if label.is_some() {
+ return Err(
+ "--label labels documents at ingest time; an object-storage watch indexes nothing \
+ and never reads document bytes. Drop --label"
+ .into(),
+ );
+ }
if !ignore_flags_used.is_empty() {
return Err(format!(
"{} apply to a folder walk, not to an object-storage watch",
@@ -1355,6 +1390,11 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
(Some("map"), _) if bulk_timeout_explicit => {
Err("--bulk-timeout-secs applies only to indexing, not `autoindex map`".into())
}
+ (Some("map"), _) | (Some("status"), _) if label.is_some() => Err(format!(
+ "--label labels indexed documents through /_decide; `autoindex {}` reads the node \
+ and never indexes anything. Drop --label",
+ sub.as_deref().unwrap_or_default()
+ )),
(Some("map"), _) => Ok(Cmd::Map(MapCfg {
url,
api_key,
@@ -1384,6 +1424,13 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
.into(),
);
}
+ if dry_run && label.is_some() {
+ return Err(
+ "--dry-run and --label contradict each other: a dry run indexes nothing, so \
+ there is nowhere for the decide labels to go. Drop one of the two"
+ .into(),
+ );
+ }
let plan = crate::resources::plan(workers, pdf_workers, bulk_mb);
Ok(Cmd::Index(Box::new(IndexCfg {
root,
@@ -1429,6 +1476,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
quiet,
progress,
progress_interval,
+ label,
watch,
debounce: Duration::from_millis(
debounce_ms.unwrap_or(crate::watch::DEFAULT_DEBOUNCE_MS),
@@ -1568,6 +1616,63 @@ mod tests {
);
}
+ /// `--label` reaches the folder route as a path (#1062) — the flag an
+ /// operator passes must be the flag the indexer reads.
+ #[test]
+ fn label_parses_on_the_index_route() {
+ let cfg = index(&["data", "--label", "questions.json"]);
+ assert_eq!(cfg.label, Some(std::path::PathBuf::from("questions.json")));
+ assert!(index(&["data"]).label.is_none(), "absent by default");
+ }
+
+ /// Every route that cannot label refuses the flag BY NAME rather than
+ /// accepting and ignoring it — the #204 shape. `--watch` (both kinds)
+ /// never runs the decide votes a watcher would need; `map`/`status` never
+ /// index; `--dry-run` indexes nothing, so there is nowhere for the labels
+ /// to go. And the flag without a path is a parse error, not a silently
+ /// ignored label.
+ #[test]
+ fn label_is_refused_on_every_route_that_cannot_apply_it() {
+ let cases = [
+ (
+ vec!["data", "--watch", "--no-graph", "--label", "q.json"],
+ "--watch and --label",
+ ),
+ (
+ vec!["s3://b/", "--watch", "--label", "q.json"],
+ "an object-storage watch indexes nothing",
+ ),
+ (vec!["map", "--label", "q.json"], "never indexes anything"),
+ (
+ vec!["status", "--label", "q.json"],
+ "never indexes anything",
+ ),
+ (vec!["data", "--label", "q.json", "--dry-run"], "contradict"),
+ (vec!["data", "--label"], "needs a question-set file path"),
+ ];
+ for (args, needle) in cases {
+ let text = err(&args);
+ assert!(
+ text.contains(needle),
+ "refusing {args:?} must say why ({needle}): {text}"
+ );
+ assert!(
+ text.contains("--label"),
+ "refusing {args:?} must name the flag: {text}"
+ );
+ }
+ }
+
+ /// The help names the flag and the honesty rule that travels with it: raw,
+ /// uncalibrated p (#1063).
+ #[test]
+ fn help_advertises_the_label_flag_and_its_raw_p() {
+ let help = super::help_text();
+ assert!(help.contains("--label <FILE>"), "{help}");
+ assert!(help.contains("/_decide"), "{help}");
+ assert!(help.contains("calibration is #1063"), "{help}");
+ }
+
/// **The merge guard.** Four routes share one positional argument, and each
/// arrived on its own branch carrying a refusal that said the others did
/// not exist:
diff --git a/engine/crates/xerj-autoindex/src/detect/e2e.rs b/engine/crates/xerj-autoindex/src/detect/e2e.rs
index 8849b2176..c31c5855c 100644
--- a/engine/crates/xerj-autoindex/src/detect/e2e.rs
+++ b/engine/crates/xerj-autoindex/src/detect/e2e.rs
@@ -379,6 +379,7 @@ pub(super) fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {
progress: crate::progress::ProgressMode::None,
progress_interval: None,
watch: false,
+ label: None,
debounce: std::time::Duration::from_millis(0),
}
}
diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
index d8a3619d9..5f762b725 100644
--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
@@ -794,6 +794,7 @@ fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {
progress: crate::progress::ProgressMode::None,
progress_interval: None,
watch: false,
+ label: None,
debounce: std::time::Duration::from_millis(0),
}
}
diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
index 72106f830..4aa75676b 100644
--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
@@ -853,6 +853,7 @@ fn cfg(root: &Path, state_dir: &Path, url: &str, semantic: bool) -> IndexCfg {
progress: crate::progress::ProgressMode::None,
progress_interval: None,
watch: false,
+ label: None,
debounce: std::time::Duration::from_millis(0),
}
}
diff --git a/engine/crates/xerj-autoindex/src/label.rs b/engine/crates/xerj-autoindex/src/label.rs
new file mode 100644
index 000000000..08f03b706
--- /dev/null
+++ b/engine/crates/xerj-autoindex/src/label.rs
@@ -0,0 +1,642 @@
+//! Ingest-time labelling through `/_decide` (#1062): `xerj autoindex
+//! <folder> --label <question-set.json>` sends every extracted record's
+//! payload through the node's decide endpoint and stamps the answers onto
+//! the document before it is bulk-indexed.
+//!
+//! The question-set file is the `noul`/`choice` vocabulary the System One
+//! surface already uses (`POST /v1/systemone`), carried in a file so the
+//! operator's judgement policy lives beside the corpus instead of in a
+//! shell-escaped command line:
+//!
+//! ```json
+//! {
+//! "decide": { "index": "mail-history", "k": 10 },
+//! "questions": [
+//! { "id": "spam", "type": "noul", "positive": "spam",
+//! "question": "Is this message spam? {{body}}" },
+//! { "id": "triage", "type": "choice", "options": ["billing", "tech"],
+//! "question": "Which team handles this? {{body}}" }
+//! ]
+//! }
+//! ```
+//!
+//! * `{{field}}` in a question resolves against the RECORD's own fields at
+//! ingest time (raw substitution — prose for a judge, not JSON splicing).
+//! * A `noul` is one `/_decide` call; the label written is the endpoint's
+//! answer (`<positive>` or `not <positive>`), `null` when it abstains.
+//! * A `choice` is one `/_decide` call PER OPTION, each as the binary "is it
+//! `<option>` vs not" vote the endpoint exposes; the written label is the
+//! argmax option and `label_p` that option's share. This is an argmax over
+//! independent binary votes, NOT a calibrated distribution over the
+//! options — the probabilities do not sum to one, and calibration is #1063.
+//!
+//! Fields written per question `q`: `label_{q}` and `label_{q}_p` (raw,
+//! uncalibrated). A single-question set ALSO writes the bare `label` /
+//! `label_p` the issue names. A failed `/_decide` call fails the run — an
+//! unlabelled index the operator believes is labelled is the accepted-and-
+//! ignored defect class, not a warning to be retried past.
+//!
+//! Cost, stated plainly: labelling is an INGEST-time cost — one blocking
+//! `/_decide` round trip per noul (per option, for a choice) per record,
+//! paid while the bulk is being prepared, never at idle. There is no idle
+//! cost at all: with `--label` absent (the default) this module is not
+//! constructed. The end-to-end test measures and prints documents labelled
+//! per second against a loopback endpoint.
+
+use anyhow::{bail, Context, Result};
+use serde_json::{json, Map, Value};
+
+use crate::esclient::Es;
+
+/// A `noul`'s two sides and a `choice`'s options, straight off the file.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum QuestionKind {
+ Noul { positive: String },
+ Choice { options: Vec<String> },
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Question {
+ pub id: String,
+ pub kind: QuestionKind,
+ pub question: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct QuestionSet {
+ /// Judgement-history index for the decide vote; may be empty, which
+ /// asks the node's local tier (the server enforces which it can do).
+ pub decide_index: String,
+ pub k: Option<u64>,
+ pub questions: Vec<Question>,
+}
+
+/// The System One API documents at most 255 options per `choice`.
+const MAX_CHOICE_OPTIONS: usize = 255;
+
+impl QuestionSet {
+ /// Load and validate a question-set file. Everything that can be
+ /// refused is refused HERE, before a single byte of the folder is
+ /// walked: a set that fails validation halfway through a run would
+ /// leave a half-labelled corpus.
+ pub fn load(path: &std::path::Path) -> Result<QuestionSet> {
+ let raw = std::fs::read_to_string(path)
+ .with_context(|| format!("--label: reading question set {}", path.display()))?;
+ let value: Value = serde_json::from_str(&raw)
+ .with_context(|| format!("--label: parsing {} as JSON", path.display()))?;
+ let obj = value
+ .as_object()
+ .ok_or_else(|| anyhow::anyhow!("--label: question set must be a JSON object"))?;
+
+ let decide = obj.get("decide").cloned().unwrap_or_else(|| json!({}));
+ let decide_index = decide
+ .get("index")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .trim()
+ .to_string();
+ let k = match decide.get("k") {
+ None => None,
+ Some(v) => Some(
+ v.as_u64()
+ .filter(|k| (1..=100).contains(k))
+ .ok_or_else(|| {
+ anyhow::anyhow!("--label: decide.k must be an integer in 1..=100")
+ })?,
+ ),
+ };
+
+ let questions_value = obj
+ .get("questions")
+ .and_then(Value::as_array)
+ .ok_or_else(|| anyhow::anyhow!("--label: question set needs a \"questions\" array"))?;
+ if questions_value.is_empty() {
+ bail!("--label: question set has no questions");
+ }
+ let mut questions = Vec::with_capacity(questions_value.len());
+ let mut seen_ids = std::collections::BTreeSet::new();
+ for (n, q) in questions_value.iter().enumerate() {
+ let question = Self::parse_question(n, q)
+ .with_context(|| format!("--label: question #{}", n + 1))?;
+ if !seen_ids.insert(question.id.clone()) {
+ bail!("--label: question id {:?} appears twice", question.id);
+ }
+ questions.push(question);
+ }
+ Ok(QuestionSet {
+ decide_index,
+ k,
+ questions,
+ })
+ }
+
+ fn parse_question(n: usize, q: &Value) -> Result<Question> {
+ let obj = q
+ .as_object()
+ .ok_or_else(|| anyhow::anyhow!("must be an object"))?;
+ let id = obj
+ .get("id")
+ .and_then(Value::as_str)
+ .filter(|s| !s.trim().is_empty())
+ .ok_or_else(|| anyhow::anyhow!("needs a non-empty string id"))?
+ .to_string();
+ // Field names must survive as index fields: idents only.
+ if !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
+ bail!(
+ "id {:?} must be [a-z0-9_]: it becomes the label_<id> field name",
+ id
+ );
+ }
+ let kind = match obj.get("type").and_then(Value::as_str) {
+ Some("noul") => QuestionKind::Noul {
+ positive: obj
+ .get("positive")
+ .and_then(Value::as_str)
+ .filter(|s| !s.trim().is_empty())
+ .ok_or_else(|| {
+ anyhow::anyhow!("a noul needs a non-empty string `positive` label")
+ })?
+ .to_string(),
+ },
+ Some("choice") => {
+ let options: Vec<String> = obj
+ .get("options")
+ .and_then(Value::as_array)
+ .ok_or_else(|| anyhow::anyhow!("a choice needs an `options` array"))?
+ .iter()
+ .filter_map(Value::as_str)
+ .map(str::to_string)
+ .collect();
+ if options.is_empty() || options.len() > MAX_CHOICE_OPTIONS {
+ bail!(
+ "a choice needs 1..{MAX_CHOICE_OPTIONS} options (got {})",
+ options.len()
+ );
+ }
+ QuestionKind::Choice { options }
+ }
+ other => bail!(
+ "type must be \"noul\" or \"choice\" (got {})",
+ other.unwrap_or("<missing>")
+ ),
+ };
+ let question = obj
+ .get("question")
+ .and_then(Value::as_str)
+ .filter(|s| !s.trim().is_empty())
+ .ok_or_else(|| anyhow::anyhow!("needs a non-empty string `question`"))?
+ .to_string();
+ let _ = n;
+ Ok(Question { id, kind, question })
+ }
+}
+
+/// Stamp labels onto records through the node's `/_decide` endpoint.
+pub struct Labeler {
+ es: Es,
+ set: QuestionSet,
+ /// Decide calls made / records labelled, for the run report.
+ calls: std::sync::atomic::AtomicU64,
+ records: std::sync::atomic::AtomicU64,
+}
+
+impl Labeler {
+ pub fn new(es: Es, set: QuestionSet) -> Self {
+ Self {
+ es,
+ set,
+ calls: std::sync::atomic::AtomicU64::new(0),
+ records: std::sync::atomic::AtomicU64::new(0),
+ }
+ }
+
+ /// (decide calls, records labelled) so far.
+ pub fn counters(&self) -> (u64, u64) {
+ (
+ self.calls.load(std::sync::atomic::Ordering::Relaxed),
+ self.records.load(std::sync::atomic::Ordering::Relaxed),
+ )
+ }
+
+ /// Decide one record. Returns the `(field, value)` pairs to stamp onto
+ /// the document — `label`/`label_p` for a single-question set plus
+ /// `label_<id>`/`label_<id>_p` for every question.
+ pub fn label_fields(&self, record: &Map<String, Value>) -> Result<Vec<(String, Value)>> {
+ // Only a single-question set writes the bare `label`/`label_p` the
+ // issue names; with several questions they would be ambiguous.
+ let primary = self.set.questions.len() == 1;
+ let mut out = Vec::new();
+ for q in &self.set.questions {
+ let rendered = render_question(&q.question, record);
+ match &q.kind {
+ QuestionKind::Noul { positive } => {
+ let answer = self.decide(&rendered, positive)?;
+ let (label, p) = match &answer {
+ DecideAnswer::Label { label, p } => (Value::String(label.clone()), *p),
+ DecideAnswer::Abstain { p } => (Value::Null, *p),
+ };
+ if primary {
+ out.push(("label".into(), label.clone()));
+ out.push(("label_p".into(), json!(round6(p))));
+ }
+ out.push((format!("label_{}", q.id), label));
+ out.push((format!("label_{}_p", q.id), json!(round6(p))));
+ }
+ QuestionKind::Choice { options } => {
+ // Argmax over per-option binary votes. An option's share
+ // when it LOST its binary vote is the complement of the
+ // returned confidence, not the returned confidence.
+ let mut best: Option<(String, f64)> = None;
+ for option in options {
+ let answer = self.decide(&rendered, option)?;
+ let p = match answer {
+ DecideAnswer::Label { label, p } if label == *option => p,
+ DecideAnswer::Label { p, .. } => 1.0 - p,
+ DecideAnswer::Abstain { p } => p,
+ };
+ if best.as_ref().is_none_or(|(_, bp)| p > *bp) {
+ best = Some((option.clone(), p));
+ }
+ }
+ let (option, p) = best.expect("a choice has >=1 option");
+ if primary {
+ out.push(("label".into(), Value::String(option.clone())));
+ out.push(("label_p".into(), json!(round6(p))));
+ }
+ out.push((format!("label_{}", q.id), Value::String(option)));
+ out.push((format!("label_{}_p", q.id), json!(round6(p))));
+ }
+ }
+ }
+ self.records
+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ Ok(out)
+ }
+
+ /// One binary `/_decide` vote.
+ fn decide(&self, question: &str, positive: &str) -> Result<DecideAnswer> {
+ let mut body = json!({
+ "question": question,
+ "positive_label": positive,
+ });
+ if !self.set.decide_index.is_empty() {
+ body["index"] = json!(self.set.decide_index);
+ }
+ if let Some(k) = self.set.k {
+ body["k"] = json!(k);
+ }
+ self.calls
+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ let (status, value) = self
+ .es
+ .request_json("POST", "/_decide", Some(&body))
+ .map_err(|e| anyhow::anyhow!("/_decide {positive:?}: {e:#}"))?;
+ if status != 200 {
+ let reason = value
+ .pointer("/error/reason")
+ .and_then(Value::as_str)
+ .unwrap_or("no reason in body");
+ bail!(
+ "/_decide for label {positive:?} answered HTTP {status}: {reason} — the run is \
+ aborted rather than indexing the document unlabelled"
+ )
+ }
+ let confidence = value
+ .get("confidence")
+ .and_then(Value::as_f64)
+ .unwrap_or(0.0);
+ let abstain = value
+ .get("abstain")
+ .and_then(Value::as_bool)
+ .unwrap_or(true);
+ let label = value.get("label").and_then(Value::as_str);
+ if abstain || label.is_none() {
+ // Abstention is an answer: label null, raw p carried so the
+ // corpus keeps the vote's strength for later calibration (#1063).
+ return Ok(DecideAnswer::Abstain { p: confidence });
+ }
+ Ok(DecideAnswer::Label {
+ label: label.unwrap_or("").to_string(),
+ p: confidence,
+ })
+ }
+}
+
+enum DecideAnswer {
+ Label { label: String, p: f64 },
+ Abstain { p: f64 },
+}
+
+/// Render a question's `{{field}}` placeholders from the record's fields.
+pub(crate) fn render_question(template: &str, record: &Map<String, Value>) -> String {
+ const MAX_FIELD_CHARS: usize = 100_000;
+ let mut out = String::with_capacity(template.len());
+ let mut rest = template;
+ while let Some(start) = rest.find("{{") {
+ out.push_str(&rest[..start]);
+ let after = &rest[start + 2..];
+ match after.find("}}") {
+ Some(end) => {
+ let name = &after[..end];
+ match record.get(name) {
+ Some(Value::String(s)) => {
+ out.push_str(&s.chars().take(MAX_FIELD_CHARS).collect::<String>())
+ }
+ Some(Value::Number(n)) => out.push_str(&n.to_string()),
+ Some(Value::Bool(b)) => out.push_str(if *b { "true" } else { "false" }),
+ _ => {}
+ }
+ rest = &after[end + 2..];
+ }
+ None => {
+ out.push_str(&rest[start..]);
+ rest = "";
+ }
+ }
+ }
+ out.push_str(rest);
+ out
+}
+
+fn round6(p: f64) -> f64 {
+ (p * 1e6).round() / 1e6
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::{BufRead, BufReader, Read, Write};
+ use std::net::{TcpListener, TcpStream};
+ use std::sync::{Arc, Mutex};
+
+ fn set(json: &str) -> QuestionSet {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("questions.json");
+ std::fs::write(&path, json).unwrap();
+ QuestionSet::load(&path).unwrap()
+ }
+
+ #[test]
+ fn question_set_loads_noul_and_choice() {
+ let s = set(r#"{
+ "decide": { "index": "hist", "k": 10 },
+ "questions": [
+ { "id": "spam", "type": "noul", "positive": "spam",
+ "question": "Is this spam? {{body}}" },
+ { "id": "triage", "type": "choice", "options": ["billing", "tech"],
+ "question": "Team? {{body}}" }
+ ]
+ }"#);
+ assert_eq!(s.decide_index, "hist");
+ assert_eq!(s.k, Some(10));
+ assert_eq!(s.questions.len(), 2);
+ assert_eq!(
+ s.questions[0].kind,
+ QuestionKind::Noul {
+ positive: "spam".into()
+ }
+ );
+ assert_eq!(
+ s.questions[1].kind,
+ QuestionKind::Choice {
+ options: vec!["billing".into(), "tech".into()]
+ }
+ );
+ }
+
+ #[test]
+ fn question_set_refuses_what_would_break_midrun() {
+ let cases = [
+ (r#"{}"#, "questions"),
+ (r#"{"questions": []}"#, "no questions"),
+ (
+ r#"{"questions": [{"id": "a", "type": "noul", "positive": "x", "question": "q"}]}"#,
+ "must NOT be refused",
+ ),
+ (
+ r#"{"questions": [{"id": "a", "type": "score", "question": "q"}]}"#,
+ "noul\" or \"choice",
+ ),
+ (
+ r#"{"questions": [{"id": "a", "type": "noul", "question": "q"}]}"#,
+ "positive",
+ ),
+ (
+ r#"{"questions": [{"id": "a b", "type": "noul", "positive": "x", "question": "q"}]}"#,
+ "[a-z0-9_]",
+ ),
+ (
+ r#"{"questions": [{"id": "a", "type": "choice", "question": "q"}]}"#,
+ "options",
+ ),
+ (
+ r#"{"questions": [
+ {"id": "a", "type": "noul", "positive": "x", "question": "q"},
+ {"id": "a", "type": "noul", "positive": "x", "question": "q"}
+ ]}"#,
+ "twice",
+ ),
+ ];
+ for (json, needle) in cases {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("q.json");
+ std::fs::write(&path, json).unwrap();
+ let got = QuestionSet::load(&path);
+ if needle == "must NOT be refused" {
+ assert!(got.is_ok(), "{json}: {got:?}");
+ } else {
+ // {:#} — the whole anyhow chain, so the needle can name the
+ // root cause rather than the wrapper.
+ let err = format!("{:#}", got.expect_err("must be refused"));
+ assert!(err.contains(needle), "{json}: expected {needle:?} in {err}");
+ }
+ }
+ }
+
+ #[test]
+ fn questions_render_record_fields() {
+ let mut record = Map::new();
+ record.insert("body".into(), Value::String("wire transfer".into()));
+ record.insert("n".into(), json!(3));
+ let q = render_question("Is {{body}} (ticket {{n}}, {{missing}})", &record);
+ assert_eq!(q, "Is wire transfer (ticket 3, )");
+ }
+
+ /// A loopback decide endpoint answering canned votes, so the Labeler is
+ /// exercised over real HTTP without a node.
+ struct DecideStub {
+ url: String,
+ /// Answers by positive label: (label-to-return, p, abstain).
+ answers: Arc<Mutex<std::collections::HashMap<String, (String, f64, bool)>>>,
+ stop: Arc<Mutex<bool>>,
+ join: Option<std::thread::JoinHandle<()>>,
+ }
+
+ impl DecideStub {
+ fn start() -> Self {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let answers = Arc::new(Mutex::new(std::collections::HashMap::new()));
+ let stop = Arc::new(Mutex::new(false));
+ let (a, s) = (Arc::clone(&answers), Arc::clone(&stop));
+ let join = std::thread::spawn(move || loop {
+ match listener.accept() {
+ Ok((stream, _)) => {
+ stream.set_nonblocking(false).unwrap();
+ let a = Arc::clone(&a);
+ std::thread::spawn(move || serve(stream, &a));
+ }
+ Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
+ if *s.lock().unwrap() {
+ break;
+ }
+ std::thread::yield_now();
+ }
+ Err(e) => panic!("decide stub accept: {e}"),
+ }
+ });
+ Self {
+ url,
+ answers,
+ stop,
+ join: Some(join),
+ }
+ }
+
+ fn answer(&self, positive: &str, label: &str, p: f64, abstain: bool) {
+ self.answers
+ .lock()
+ .unwrap()
+ .insert(positive.into(), (label.into(), p, abstain));
+ }
+
+ fn es(&self) -> Es {
+ Es::new(&self.url, None).unwrap()
+ }
+ }
+
+ impl Drop for DecideStub {
+ fn drop(&mut self) {
+ *self.stop.lock().unwrap() = true;
+ let _ = TcpStream::connect(self.url.trim_start_matches("http://"));
+ self.join.take().unwrap().join().unwrap();
+ }
+ }
+
+ fn serve(
+ mut stream: TcpStream,
+ answers: &Mutex<std::collections::HashMap<String, (String, f64, bool)>>,
+ ) {
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
+ let mut request_line = String::new();
+ if reader.read_line(&mut request_line).unwrap() == 0 {
+ return;
+ }
+ let mut content_length = 0usize;
+ loop {
+ let mut line = String::new();
+ reader.read_line(&mut line).unwrap();
+ if line == "\r\n" || line.is_empty() {
+ break;
+ }
+ if let Some(v) = line
+ .to_ascii_lowercase()
+ .strip_prefix("content-length:")
+ .map(str::trim)
+ {
+ content_length = v.parse().unwrap_or(0);
+ }
+ }
+ let mut body = vec![0; content_length];
+ if content_length > 0 {
+ reader.read_exact(&mut body).unwrap();
+ }
+ let value: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
+ let positive = value
+ .get("positive_label")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string();
+ let (label, p, abstain) = answers
+ .lock()
+ .unwrap()
+ .get(&positive)
+ .cloned()
+ .unwrap_or(("unknown".into(), 0.0, true));
+ let resp = json!({
+ "label": if abstain { Value::Null } else { Value::String(label) },
+ "confidence": p,
+ "abstain": abstain,
+ "tier": "history",
+ "neighbours": [],
+ "took_ms": 0,
+ });
+ let bytes = resp.to_string();
+ // write!, not writeln!: writeln's trailing newline would land between
+ // the header terminator and the body and corrupt the framed JSON.
+ let _ = write!(
+ stream,
+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
+ bytes.len()
+ );
+ let _ = stream.write_all(bytes.as_bytes());
+ let _ = stream.flush();
+ }
+
+ #[test]
+ fn labeler_stamps_bare_and_per_question_fields() {
+ let stub = DecideStub::start();
+ stub.answer("spam", "spam", 0.9, false);
+ stub.answer("billing", "not billing", 0.8, false); // lost its vote
+ stub.answer("tech", "tech", 0.7, false);
+ stub.answer("abstain_q", "whatever", 0.3, true);
+ let s = set(r#"{"decide": {"index": "hist"},
+ "questions": [
+ {"id": "spam", "type": "noul", "positive": "spam", "question": "{{body}}"}
+ ]}"#);
+ let labeler = Labeler::new(stub.es(), s);
+ let mut record = Map::new();
+ record.insert("body".into(), Value::String("claim your prize".into()));
+ let fields = labeler.label_fields(&record).unwrap();
+ let map: std::collections::BTreeMap<String, Value> = fields.into_iter().collect();
+ assert_eq!(map["label"], json!("spam"), "single question: bare fields");
+ assert_eq!(map["label_p"], json!(0.9));
+ assert_eq!(map["label_spam"], json!("spam"));
+ assert_eq!(map["label_spam_p"], json!(0.9));
+
+ // A choice: argmax over per-option binary votes. billing LOST its
+ // own vote (conf 0.8 for "not billing" → share 0.2); tech WON with
+ // 0.7 → label tech.
+ let s = set(r#"{"questions": [
+ {"id": "triage", "type": "choice", "options": ["billing", "tech"],
+ "question": "{{body}}"}]}"#);
+ let labeler = Labeler::new(stub.es(), s);
+ let fields = labeler.label_fields(&record).unwrap();
+ let map: std::collections::BTreeMap<String, Value> = fields.into_iter().collect();
+ assert_eq!(map["label"], json!("tech"));
+ assert_eq!(map["label_p"], json!(0.7));
+ assert_eq!(map["label_triage"], json!("tech"));
+ assert_eq!(map["label_triage_p"], json!(0.7));
+
+ // Abstention: label null, raw p carried.
+ let s = set(r#"{"questions": [
+ {"id": "abstain_q", "type": "noul", "positive": "abstain_q",
+ "question": "{{body}}"}]}"#);
+ let labeler = Labeler::new(stub.es(), s);
+ let fields = labeler.label_fields(&record).unwrap();
+ let map: std::collections::BTreeMap<String, Value> = fields.into_iter().collect();
+ assert_eq!(map["label"], Value::Null);
+ assert_eq!(map["label_p"], json!(0.3));
+
+ // Multi-question sets never write the bare fields.
+ let s = set(r#"{"questions": [
+ {"id": "a", "type": "noul", "positive": "spam", "question": "{{body}}"},
+ {"id": "b", "type": "noul", "positive": "spam", "question": "{{body}}"}]}"#);
+ let labeler = Labeler::new(stub.es(), s);
+ let fields = labeler.label_fields(&record).unwrap();
+ assert!(!fields.iter().any(|(k, _)| k == "label"), "{fields:?}");
+ let (calls, records) = labeler.counters();
+ assert_eq!((calls, records), (2, 1));
+ }
+}
diff --git a/engine/crates/xerj-autoindex/src/label_http_tests.rs b/engine/crates/xerj-autoindex/src/label_http_tests.rs
new file mode 100644
index 000000000..0314f968d
--- /dev/null
+++ b/engine/crates/xerj-autoindex/src/label_http_tests.rs
@@ -0,0 +1,510 @@
+//! End-to-end tests for `--label` (#1062): a real `run_index_report` over a
+//! small folder against a loopback node that answers `/_decide`, asserting the
+//! labels land on the documents the run actually bulk-indexed.
+//!
+//! The endpoint here is deliberately NOT the incremental-reconcile harness:
+//! that file's `HttpState` carries reconcile bookkeeping this test does not
+//! exercise, and `/_decide` — the one endpoint this test exists to observe —
+//! does not exist there. What is shared is the shape: a non-blocking accept
+//! loop, one thread per connection, everything through one Mutex.
+
+use std::collections::BTreeMap;
+use std::fs;
+use std::io::{BufRead, BufReader, Read, Write};
+use std::net::{TcpListener, TcpStream};
+use std::path::Path;
+use std::sync::{Arc, Mutex};
+use std::time::Instant;
+
+use serde_json::{json, Value};
+
+use crate::cli::IndexCfg;
+use crate::run_index_report;
+
+/// A loopback node: enough of the indexing surface for `run_index_report` to
+/// complete a generated run, plus a `/_decide` that answers canned votes keyed
+/// by the POSITIVE LABEL the request carried (the Labeler sends one binary
+/// vote per noul/option).
+struct LabelNode {
+ url: String,
+ state: Arc<Mutex<NodeState>>,
+ join: Option<std::thread::JoinHandle<()>>,
+}
+
+#[derive(Default)]
+struct NodeState {
+ stop: bool,
+ /// When set, `/_decide` answers 500 — the refusal path under test.
+ fail_decide: bool,
+ /// Every document the run bulk-indexed, by (index, id).
+ docs: Vec<(String, String, Value)>,
+ /// Every (positive_label, question) POST /_decide received.
+ decides: Vec<(String, String)>,
+ /// Canned answers by positive label: (label, p, abstain).
+ answers: BTreeMap<String, (String, f64, bool)>,
+}
+
+impl LabelNode {
+ fn start() -> Self {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let state = Arc::new(Mutex::new(NodeState::default()));
+ let server_state = Arc::clone(&state);
+ let join = std::thread::spawn(move || loop {
+ match listener.accept() {
+ Ok((stream, _)) => {
+ stream.set_nonblocking(false).unwrap();
+ let server_state = Arc::clone(&server_state);
+ std::thread::spawn(move || serve(stream, &server_state));
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
+ if server_state.lock().unwrap().stop {
+ break;
+ }
+ std::thread::yield_now();
+ }
+ Err(e) => panic!("label node accept: {e}"),
+ }
+ });
+ Self {
+ url,
+ state,
+ join: Some(join),
+ }
+ }
+
+ fn answer(&self, positive: &str, label: &str, p: f64, abstain: bool) {
+ self.state
+ .lock()
+ .unwrap()
+ .answers
+ .insert(positive.into(), (label.into(), p, abstain));
+ }
+
+ fn docs(&self) -> Vec<(String, String, Value)> {
+ self.state.lock().unwrap().docs.clone()
+ }
+
+ fn decides(&self) -> Vec<(String, String)> {
+ self.state.lock().unwrap().decides.clone()
+ }
+}
+
+impl Drop for LabelNode {
+ fn drop(&mut self) {
+ self.state.lock().unwrap().stop = true;
+ let _ = TcpStream::connect(self.url.trim_start_matches("http://"));
+ self.join.take().unwrap().join().unwrap();
+ }
+}
+
+fn serve(mut stream: TcpStream, state: &Mutex<NodeState>) {
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
+ let mut request_line = String::new();
+ if reader.read_line(&mut request_line).unwrap() == 0 {
+ return;
+ }
+ let mut content_length = 0usize;
+ loop {
+ let mut line = String::new();
+ reader.read_line(&mut line).unwrap();
+ if line == "\r\n" || line.is_empty() {
+ break;
+ }
+ if let Some(v) = line
+ .to_ascii_lowercase()
+ .strip_prefix("content-length:")
+ .map(str::trim)
+ {
+ content_length = v.parse().unwrap_or(0);
+ }
+ }
+ let mut body = vec![0; content_length];
+ if content_length > 0 {
+ reader.read_exact(&mut body).unwrap();
+ }
+ let mut parts = request_line.split_whitespace();
+ let method = parts.next().unwrap_or("").to_owned();
+ let path = parts.next().unwrap_or("").to_owned();
+
+ let (status, response) = if method == "POST" && path == "/_decide" {
+ if state.lock().unwrap().fail_decide {
+ (
+ 500,
+ json!({"error": {"type": "decide_unavailable",
+ "reason": "injected for the refusal test"}}),
+ )
+ } else {
+ decide_http(&body, state)
+ }
+ } else if method == "POST" && path == "/_bulk" {
+ bulk_http(&body, state)
+ } else if method == "POST" && path.ends_with("/_search") {
+ (200, search_http(&path, &body, state))
+ } else if method == "POST" && path.ends_with("/_delete_by_query") {
+ (200, json!({"deleted": 0, "failures": []}))
+ } else if method == "GET" && path.ends_with("/_count") {
+ let index = path.trim_start_matches('/').trim_end_matches("/_count");
+ let count = state
+ .lock()
+ .unwrap()
+ .docs
+ .iter()
+ .filter(|(doc_index, _, _)| doc_index == index)
+ .count();
+ (200, json!({"count": count}))
+ } else if method == "GET" && path == "/v1/embedding/identity" {
+ (
+ 200,
+ json!({"data": {
+ "version": 1, "backend": "lexical",
+ "identity_sha256": "l".repeat(64), "dimensions": 384,
+ "semantic_contract": "semantic_text-derived-vector.v1",
+ "resumable": true,
+ }}),
+ )
+ } else {
+ // Ping, index/mapping PUTs, anything else a generated run needs to be
+ // told "yes" about.
+ (200, json!({"acknowledged": true}))
+ };
+
+ let bytes = response.to_string();
+ // write!, not writeln! — a trailing newline would land between the header
+ // terminator and the body and corrupt the framing.
+ let _ = write!(
+ stream,
+ "HTTP/1.1 {status} XERJTEST\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\
+ connection: close\r\n\r\n",
+ bytes.len()
+ );
+ let _ = stream.write_all(bytes.as_bytes());
+ let _ = stream.flush();
+}
+
+/// A small-but-real `_search` over the captured documents. The generated
+/// run's exact read-back verifies its sealed record counts with
+/// `size: 0, query: bool.filter [terms ax_file, term ax_dataset]` and reads
+/// `hits.total.value` — an empty-result stub would make every run abort as a
+/// "corruption signal". Supports that filter shape and match_all; anything
+/// else matches nothing (and the tests would notice).
+fn search_http(path: &str, body: &[u8], state: &Mutex<NodeState>) -> Value {
+ let indices: Vec<String> = path
+ .trim_start_matches('/')
+ .trim_end_matches("/_search")
+ .split(',')
+ .map(str::to_owned)
+ .collect();
+ let query: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
+ let size = query.get("size").and_then(Value::as_u64).unwrap_or(10) as usize;
+ let from = query.get("from").and_then(Value::as_u64).unwrap_or(0) as usize;
+ let filters = query
+ .pointer("/query/bool/filter")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+ let is_match_all = query.pointer("/query/match_all").is_some()
+ || (filters.is_empty() && query.get("query").is_none());
+ let docs = state.lock().unwrap().docs.clone();
+ let matching: Vec<&(String, String, Value)> = docs
+ .iter()
+ .filter(|(index, _, _)| indices.contains(index))
+ .filter(|(_, _, doc)| {
+ if is_match_all {
+ return true;
+ }
+ filters.iter().all(|filter| {
+ if let Some(term) = filter.get("term").and_then(Value::as_object) {
+ let Some((field, value)) = term.iter().next() else {
+ return false;
+ };
+ return doc.get(field) == Some(value);
+ }
+ if let Some(terms) = filter.get("terms").and_then(Value::as_object) {
+ let Some((field, values)) = terms.iter().next() else {
+ return false;
+ };
+ return values.as_array().is_some_and(|values| {
+ values.iter().any(|value| doc.get(field) == Some(value))
+ });
+ }
+ false
+ })
+ })
+ .collect();
+ let total = matching.len();
+ let hits = matching
+ .iter()
+ .skip(from)
+ .take(size)
+ .map(|(_, id, doc)| json!({"_id": id, "_source": doc}))
+ .collect::<Vec<_>>();
+ json!({
+ "hits": {"total": {"value": total, "relation": "eq"}, "hits": hits},
+ "aggregations": {},
+ })
+}
+
+/// The endpoint this file exists to observe: record the vote, answer canned.
+fn decide_http(body: &[u8], state: &Mutex<NodeState>) -> (u16, Value) {
+ let value: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
+ let positive = value
+ .get("positive_label")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_owned();
+ let question = value
+ .get("question")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_owned();
+ let (label, p, abstain) = {
+ let mut locked = state.lock().unwrap();
+ locked.decides.push((positive.clone(), question));
+ locked
+ .answers
+ .get(&positive)
+ .cloned()
+ .unwrap_or_else(|| ("unknown".into(), 0.0, true))
+ };
+ (
+ 200,
+ json!({
+ "label": if abstain { Value::Null } else { Value::String(label) },
+ "confidence": p,
+ "abstain": abstain,
+ "tier": "history",
+ "neighbours": [],
+ "took_ms": 0,
+ }),
+ )
+}
+
+/// Minimal `_bulk`: capture every action/doc pair, acknowledge each.
+fn bulk_http(body: &[u8], state: &Mutex<NodeState>) -> (u16, Value) {
+ let text = String::from_utf8_lossy(body);
+ let mut items = Vec::new();
+ let mut lines = text.lines();
+ while let Some(action_line) = lines.next() {
+ if action_line.trim().is_empty() {
+ continue;
+ }
+ let doc_line = lines.next().unwrap_or("");
+ let action: Value = serde_json::from_str(action_line).unwrap_or(Value::Null);
+ let doc: Value = serde_json::from_str(doc_line).unwrap_or(Value::Null);
+ let id = action
+ .pointer("/index/_id")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_owned();
+ let index = action
+ .pointer("/index/_index")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_owned();
+ state.lock().unwrap().docs.push((index, id.clone(), doc));
+ items.push(json!({"index": {"_id": id, "status": 201}}));
+ }
+ (200, json!({"errors": false, "items": items}))
+}
+
+fn cfg(root: &Path, state_dir: &Path, url: &str, label: &Path) -> IndexCfg {
+ IndexCfg {
+ root: root.to_owned(),
+ endpoint_url: None,
+ stub_globs: Vec::new(),
+ url: url.to_owned(),
+ api_key: None,
+ api_key_file: None,
+ workers: 1,
+ scan_workers: 1,
+ pdf_workers: 1,
+ resource_notes: Vec::new(),
+ xerj_url_note: None,
+ pdf_timeout_secs: 30,
+ bulk_mb: 1,
+ bulk_timeout_secs: 30,
+ snapshot_max_bytes: 64 << 30,
+ prefix: "label-http".into(),
+ state_dir: Some(state_dir.to_owned()),
+ fresh: false,
+ follow_symlinks: false,
+ follow_symlinks_outside_root: false,
+ ignore: crate::ignore_rules::IgnoreOptions::default(),
+ max_file_gb: 1,
+ sample: 100,
+ no_semantic: true,
+ brain: None,
+ no_graph: true,
+ max_minutes: 0,
+ approve: None,
+ dry_run: false,
+ json: false,
+ quiet: true,
+ progress: crate::progress::ProgressMode::None,
+ progress_interval: None,
+ watch: false,
+ debounce: std::time::Duration::from_millis(0),
+ label: Some(label.to_owned()),
+ }
+}
+
+/// THE end-to-end contract of #1062: `xerj autoindex <folder> --label <set>`
+/// stamps `label`/`label_p` on every indexed document, decided per document
+/// through the node's real `/_decide`, and the question templates see each
+/// record's own fields. The decide endpoint answers by what the rendered
+/// question CONTAINS — "prize" votes spam, anything else abstains — so the
+/// two documents must come out differently labelled, which is only possible
+/// if the record's payload reached the vote.
+///
+/// Also measures and prints the run's labelling throughput (documents per
+/// second) against the loopback endpoint — the ingest-time cost statement,
+/// made on a measurement instead of an estimate. The idle side of the budget
+/// is structural and stated in `label.rs`: no `--label`, no Labeler, no idle
+/// cost at all.
+#[test]
+fn label_end_to_end_through_a_real_run() {
+ let corpus = tempfile::tempdir().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ fs::write(
+ corpus.path().join("mail.csv"),
+ "id,text\n\
+ 1,claim your prize right now wire transfer\n\
+ 2,quarterly vendor fee schedule attached\n",
+ )
+ .unwrap();
+ // The question set lives OUTSIDE the corpus: inside it, the walk would
+ // index the operator's policy file as a document and vote on it too.
+ let questions = tempfile::tempdir().unwrap();
+ let question_set = questions.path().join("questions.json");
+ fs::write(
+ &question_set,
+ r#"{
+ "decide": { "index": "mail-history", "k": 10 },
+ "questions": [
+ { "id": "spam", "type": "noul", "positive": "spam",
+ "question": "Is this spam? {{text}}" }
+ ]
+ }"#,
+ )
+ .unwrap();
+
+ let node = LabelNode::start();
+ // One canned answer per positive label: both documents vote "spam" with
+ // 0.9. That is enough for this test — the per-document rendering (that
+ // each record's OWN text reached its vote) is asserted below from the
+ // recorded questions, and the abstain path is pinned by the second test.
+ node.answer("spam", "spam", 0.9, false);
+ let config = cfg(corpus.path(), state_dir.path(), &node.url, &question_set);
+
+ let started = Instant::now();
+ let (code, summary) = run_index_report(config).expect("the labelled run completes");
+ let elapsed = started.elapsed();
+
+ assert_eq!(code, 0, "run succeeded: {summary:?}");
+ // Only this corpus's dataset indices: the run also bulk-indexes into the
+ // shared `autoindex-catalog`, which is not what the labels are about.
+ let docs: Vec<_> = node
+ .docs()
+ .into_iter()
+ .filter(|(index, _, _)| index.starts_with("label-http"))
+ .collect();
+ assert_eq!(docs.len(), 2, "both CSV rows indexed: {docs:?}");
+ for (_, id, doc) in &docs {
+ assert_eq!(
+ doc["label"],
+ json!("spam"),
+ "doc {id} carries the decide answer: {doc}"
+ );
+ assert_eq!(doc["label_p"], json!(0.9), "raw p, uncalibrated: {doc}");
+ assert_eq!(
+ doc["label_spam"],
+ json!("spam"),
+ "per-question fields: {doc}"
+ );
+ assert_eq!(doc["label_spam_p"], json!(0.9), "{doc}");
+ }
+ // The votes the run made: one per record (single noul), each question
+ // carrying the RECORD's own text — the {{text}} substitution.
+ let decides = node.decides();
+ assert_eq!(decides.len(), 2, "one decide per record: {decides:?}");
+ let voted_prize = decides
+ .iter()
+ .any(|(positive, question)| positive == "spam" && question.contains("prize"));
+ let voted_vendor = decides
+ .iter()
+ .any(|(positive, question)| positive == "spam" && question.contains("vendor"));
+ assert!(
+ voted_prize && voted_vendor,
+ "each record's own text reached the vote: {decides:?}"
+ );
+ // Ingest-time cost, measured on this run and printed with the test: the
+ // loopback round trip is the floor of the real cost, not the ceiling.
+ let per_doc = elapsed.as_secs_f64() / docs.len() as f64;
+ println!(
+ "label e2e: {} docs in {:.3}s = {:.1} ms/doc end-to-end against a loopback node \
+ (ingest-time only; idle cost is zero without --label)",
+ docs.len(),
+ elapsed.as_secs_f64(),
+ per_doc * 1000.0
+ );
+}
+
+/// A `/_decide` that abstains must still label the documents — with `null`
+/// and the raw p carried — because an abstention is an answer, and the corpus
+/// keeps the vote's strength for later calibration (#1063). And a `/_decide`
+/// that FAILS must fail the run before any unlabelled document is bulk-indexed:
+/// an index the operator believes is labelled is the #204 defect class.
+#[test]
+fn label_end_to_end_abstains_and_failures() {
+ let corpus = tempfile::tempdir().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ fs::write(corpus.path().join("mail.csv"), "id,text\n1,hello\n").unwrap();
+ // Outside the corpus, so the policy file is not itself indexed.
+ let questions = tempfile::tempdir().unwrap();
+ let question_set = questions.path().join("questions.json");
+ fs::write(
+ &question_set,
+ r#"{"questions": [
+ { "id": "spam", "type": "noul", "positive": "spam", "question": "{{text}}" }
+ ]}"#,
+ )
+ .unwrap();
+
+ // Abstention: label null, p carried.
+ let node = LabelNode::start();
+ node.answer("spam", "spam", 0.3, true);
+ let config = cfg(corpus.path(), state_dir.path(), &node.url, &question_set);
+ let (code, _) = run_index_report(config).expect("an abstaining run still completes");
+ assert_eq!(code, 0);
+ let docs: Vec<_> = node
+ .docs()
+ .into_iter()
+ .filter(|(index, _, _)| index.starts_with("label-http"))
+ .collect();
+ assert_eq!(docs.len(), 1, "{docs:?}");
+ let doc = &docs[0].2;
+ assert_eq!(doc["label"], Value::Null, "abstention is label null: {doc}");
+ assert_eq!(doc["label_p"], json!(0.3), "raw p carried: {doc}");
+ assert_eq!(doc["label_spam"], Value::Null, "{doc}");
+
+ // Failure: /_decide answers 500 -> the run must ERROR, not index the
+ // document unlabelled. A fresh state dir so the first run's committed
+ // generation cannot make the second a no-op that never reaches the sink.
+ let state_dir = tempfile::tempdir().unwrap();
+ let node = LabelNode::start();
+ node.state.lock().unwrap().fail_decide = true;
+ let config = cfg(corpus.path(), state_dir.path(), &node.url, &question_set);
+ let error = run_index_report(config).expect_err("a failing decide must fail the run");
+ let text = format!("{error:#}");
+ assert!(
+ text.contains("/_decide"),
+ "the failure must name the decide call it died on: {text}"
+ );
+ assert!(
+ node.docs().is_empty(),
+ "no document may be bulk-indexed unlabelled: {:?}",
+ node.docs()
+ );
+}
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 683b9f9f1..cc6728e0a 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -27,6 +27,8 @@ 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 objsource;
#[cfg(test)]
mod objsource_minio_tests;
@@ -132,6 +134,14 @@ fn prepared_records_identity(cfg: &IndexCfg) -> Result<String> {
// 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())
+ }),
});
Ok(format!(
"{}-{:032x}",
@@ -1333,6 +1343,12 @@ fn begin_non_graph_generation(
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,
@@ -1373,7 +1389,17 @@ fn begin_non_graph_generation(
pr,
prior_snapshot.as_ref(),
&chunker_identity,
+ labeler,
)?;
+ // #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.
@@ -2574,6 +2600,7 @@ mod phase_a_grouping_tests {
progress: crate::progress::ProgressMode::None,
progress_interval: None,
watch: false,
+ label: None,
debounce: std::time::Duration::from_millis(0),
}
}
@@ -5044,6 +5071,31 @@ fn run_index_report_inner(
.with_bulk_concurrency(cfg.workers, pr.enabled());
es.ping()?;
+ // `--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 = StubMatcher::compile(&cfg.stub_globs)?;
// An `s3://`/`r2://` positional argument becomes a local mirror directory
// here, before any state is opened: `cfg.root` is rewritten to that mirror,
@@ -5531,6 +5583,7 @@ fn run_index_report_inner(
&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
@@ -6249,6 +6302,7 @@ fn run_index_report_inner(
&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
@@ -7025,6 +7079,29 @@ fn run_index_report_inner(
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))));
+ // `--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);
@@ -7450,6 +7527,16 @@ fn run_index_report_inner(
}
});
+ // `--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
@@ -10287,6 +10374,8 @@ 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`
diff --git a/engine/crates/xerj-autoindex/src/sync_executor.rs b/engine/crates/xerj-autoindex/src/sync_executor.rs
index 6d9f97da5..369266a35 100644
--- a/engine/crates/xerj-autoindex/src/sync_executor.rs
+++ b/engine/crates/xerj-autoindex/src/sync_executor.rs
@@ -1825,6 +1825,9 @@ pub fn create_snapshot(
&crate::progress::Progress::silent(),
None,
"",
+ // The source-snapshot wrapper has no plan and therefore never runs
+ // `prepare_artifact`; a labeler would have nothing to vote on.
+ None,
)
}
@@ -1852,6 +1855,8 @@ pub fn create_prepared_snapshot(
// source, so the chunker identity they seal is a fixed label.
None,
"prepared-records-v1",
+ // Test-only wrapper: no `--label` in these snapshots' contracts.
+ None,
)
}
@@ -1880,6 +1885,7 @@ pub fn create_prepared_snapshot_reporting(
pr: &crate::progress::Progress,
reuse: Option<&SourceSnapshot>,
chunker_identity: &str,
+ labeler: Option<&crate::label::Labeler>,
) -> Result<SourceSnapshot> {
create_snapshot_inner(
state_dir,
@@ -1891,6 +1897,7 @@ pub fn create_prepared_snapshot_reporting(
pr,
reuse,
chunker_identity,
+ labeler,
)
}
@@ -1905,6 +1912,7 @@ fn create_snapshot_inner(
pr: &crate::progress::Progress,
reuse: Option<&SourceSnapshot>,
chunker_identity: &str,
+ labeler: Option<&crate::label::Labeler>,
) -> Result<SourceSnapshot> {
validate_tx_id(tx_id)?;
ensure_inventory_lengths(inventory)?;
@@ -2096,6 +2104,7 @@ fn create_snapshot_inner(
&destination,
plan.expect("assignment implies a plan"),
&mut budget,
+ labeler,
)?),
None => None,
},
@@ -2125,6 +2134,7 @@ fn create_snapshot_inner(
&destination,
plan.expect("assignment implies a plan"),
&mut budget,
+ labeler,
)?),
None => None,
};
@@ -2263,6 +2273,15 @@ fn prepare_artifact(
snapshot_blob: &Path,
plan: &Plan,
budget: &mut PayloadBudget,
+ // #1062: `--label` runs each record's payload through the node's
+ // `/_decide` HERE, before the record is sealed, so the labels become part
+ // of the durable artifact — replays and hardlink reuse carry them without
+ // a second vote. The question-set bytes are in the run's
+ // `chunker_identity` (`lib.rs::prepared_records_identity`), which is what
+ // makes a changed set re-prepare instead of hardlinking unlabelled (or
+ // differently-labelled) NDJSON. `None` — the default, and every caller
+ // without `--label` — seals unlabelled exactly as before.
+ labeler: Option<&crate::label::Labeler>,
) -> Result<PreparedArtifact> {
let assignment = plan
.files
@@ -2357,6 +2376,29 @@ fn prepare_artifact(
|extension| extension.to_string_lossy().to_ascii_lowercase(),
)),
);
+ // #1062: the decide vote runs after coercion and provenance stamping
+ // and before the record is written, on the same `fields` map that is
+ // about to be sealed — the question templates see the record exactly
+ // as the index will. A FAILED vote fails the seal (sink_error), which
+ // fails the run: sealing the record unlabelled would hand the index a
+ // document the operator believes was judged. An abstention is an
+ // answer and stamps `label: null` with the raw p (see `label.rs`).
+ if let Some(labeler) = labeler {
+ match labeler.label_fields(&fields) {
+ Ok(pairs) => {
+ for (name, value) in pairs {
+ fields.insert(name, value);
+ }
+ }
+ Err(error) => {
+ sink_error = Some(error.context(format!(
+ "--label {} (record {})",
+ source.rel, record.locator
+ )));
+ return false;
+ }
+ }
+ }
let id = crate::ids::doc_id(slug, content_id, &record.locator);
let action = serde_json::json!({"index": {"_index": dataset.index, "_id": id}});
if let Err(error) = writeln!(writer, "{action}")
@@ -2792,6 +2834,7 @@ mod tests {
&crate::progress::Progress::silent(),
None,
"chunker-v1",
+ None,
)
.unwrap();
assert_eq!(first.files.len(), 3);
@@ -2827,6 +2870,7 @@ mod tests {
&crate::progress::Progress::silent(),
Some(&first),
"chunker-v1",
+ None,
)
.unwrap();
@@ -2965,6 +3009,7 @@ mod tests {
&crate::progress::Progress::silent(),
None,
"chunker-v1",
+ None,
)
.unwrap();
std::fs::write(corpus.path().join("b.md"), "bravo contents CHANGED\n").unwrap();
@@ -2980,6 +3025,7 @@ mod tests {
&crate::progress::Progress::silent(),
Some(&first),
"chunker-v1",
+ None,
)
.unwrap();
@@ -3016,6 +3062,7 @@ mod tests {
&crate::progress::Progress::silent(),
None,
"chunker-v1",
+ None,
)
.unwrap();
let second = create_prepared_snapshot_reporting(
@@ -3028,6 +3075,7 @@ mod tests {
&crate::progress::Progress::silent(),
Some(&first),
"chunker-v2",
+ None,
)
.unwrap();
let key = &inventory.keys[0];
diff --git a/engine/crates/xerj-server/src/brain.rs b/engine/crates/xerj-server/src/brain.rs
index 532e648ff..4021dbdd5 100644
--- a/engine/crates/xerj-server/src/brain.rs
+++ b/engine/crates/xerj-server/src/brain.rs
@@ -644,6 +644,7 @@ fn index_cfg(cfg: &BrainCfg, brain: &str, api_key: Option<String>) -> IndexCfg {
progress: xerj_autoindex::progress::ProgressMode::Auto,
progress_interval: None,
watch: false,
+ label: None,
debounce: std::time::Duration::from_millis(0),
}
}