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
systemone: local zero-shot decision head, tier 2 of the decide ladder (#1057)
xerj-orgbdc26d5820cc
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 72898ecb5..e99c033e4 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -30,16 +30,48 @@ So the node speaks the wire:Both surfaces are one mechanism, in`engine/crates/xerj-api/src/systemone_api.rs`; the end-to-end tests are-`engine/crates/xerj-api/tests/systemone_http.rs`. The acceptance gate for the-wire — the pip-installed `jev-reranker`, unmodified, ranking off a XERJ node —-is [benchmarks/systemone-gate](../benchmarks/systemone-gate).+`engine/crates/xerj-api/tests/systemone_http.rs`, and the local tier's are+`engine/crates/xerj-api/tests/systemone_local_decide.rs`. The acceptance gate+for the wire — the pip-installed `jev-reranker`, unmodified, ranking off a+XERJ node — is [benchmarks/systemone-gate](../benchmarks/systemone-gate).++## The decide ladder++Both surfaces answer through one ordered ladder, per question (#1057):++1. **History vote** — where `[decisions] index` returns labelled support, the+ vote wins. It is the measured tier and it shows its evidence.+2. **Local zero-shot head** (off by default; feature `decide-local` ++ `XERJ_DECIDE_MODE=local` + `XERJ_DECIDE_MODEL_DIR`) — a ModernBERT-class+ candle classifier loaded from a local model directory holding+ `config.json`, `tokenizer.json` and `model.safetensors`. It answers every+ no-support outcome: no `[decisions] index` at all, a configured index that+ is missing, a question whose payload retrieves no labelled neighbour. No+ download path, no outbound client — the directory arrives the way any other+ air-gapped asset does.+3. **Hosted key** — reserved, not built. When tiers 1 and 2 cannot answer, the+ documented errors stand rather than a fabricated probability.++Tier 2 scores one NLI (premise, hypothesis) pair per candidate label — premise+= the payload, hypothesis = "This example is {label}." — reads the entailment+probability, and renormalises across the question's labels. A `noul` is scored+as two competing statements (the positive label and its negation); a `choice`+scores its own options. The trained model is the open `xerj-decide` artifact+([#1064](https://github.com/xerj-org/xerj/issues/1064)); the loader here is+validated end to end against a deterministic test fixture, so **no accuracy,+ECE, or latency number is claimed for tier 2 until that artifact is measured**.++The tier that answered is per-question evidence: `decisions.evidence.<id>.tier`+is `history` or `local`, and a local answer carries+`model: "xerj-decide-local-1"` — the same never-a-Jev-name discipline as the+vote's own id.## Set it up```toml# xerj.toml[decisions]-index = "judgements" # an index of labelled examples; empty (the default) = both endpoints 503+index = "judgements" # an index of labelled examples; empty (the default) = both endpoints 503 (unless the local tier below is armed)k = 10label_field = "label"text_field = "text"@@ -121,19 +153,26 @@ Two deliberate breaks from the hosted API, both tested so they cannot regress:A question whose vote finds no labelled neighbour carries no information;inventing a probability is the silent-fake defect class this projecttreats as a bug. `/_decide` says the same thing as `abstain` + `reason`.+ The local tier is the documented exception: armed, it answers those same+ questions with the head's probabilities instead (200 where the vote 422'd,+ and no 503 on a node with no `[decisions] index` at all). Request-shape+ refusals — no payload to classify — are never rescued by it.`score` questions (2–10 ordinal levels) have no vote analogue and nobenchmark: 422, naming the alternative.## `POST /_decide`-The audit surface. Per request: `index` (required), `question` (required),-`k` (default the configured 10, clamped 1..100), `positive_label` (default-the configured one). The response returns the label, its confidence, the-verdict (`abstain` below `decisions.min_confidence`, or when no labelled-neighbour exists), and the **neighbours** — each with `_id`, `label`,-`_score` (the engine's own BM25 score), `weight` (1/rank), and the text — so-every answer can be checked against the evidence that produced it.+The audit surface. Per request: `index` (required — optional when the local+tier is armed), `question` (required), `k` (default the configured 10,+clamped 1..100), `positive_label` (default the configured one). The response+returns the label, its confidence, the verdict (`abstain` below+`decisions.min_confidence`, or when no labelled neighbour exists), the **tier**+that answered, and the **neighbours** — each with `_id`, `label`, `_score`+(the engine's own BM25 score), `weight` (1/rank), and the text — so every+answer can be checked against the evidence that produced it. A local-tier+answer has no neighbours (having none is what tier 2 means) and carries+`tier: "local"`, `model: "xerj-decide-local-1"`.```shcurl -s localhost:9200/_decide -H 'content-type: application/json' \diff --git a/engine/Cargo.lock b/engine/Cargo.lockindex 3852e2d1f..92ae58529 100644--- a/engine/Cargo.lock+++ b/engine/Cargo.lock@@ -7248,6 +7248,7 @@ dependencies = ["serde","serde_json","sha2 0.10.9",+ "tempfile","thiserror 2.0.18","tokenizers","tokio",@@ -7281,6 +7282,7 @@ dependencies = ["tracing","tracing-subscriber","uuid",+ "xerj-ai","xerj-common","xerj-engine","xerj-query",diff --git a/engine/crates/xerj-ai/Cargo.toml b/engine/crates/xerj-ai/Cargo.tomlindex 40304ad65..14cbb9348 100644--- a/engine/crates/xerj-ai/Cargo.toml+++ b/engine/crates/xerj-ai/Cargo.toml@@ -39,12 +39,18 @@ sha2 = { version = "0.10", optional = true }default = []# Bundles the neural BERT embedder. Adds ~candle + tokenizers to the build.neural = ["dep:candle-core", "dep:candle-nn", "dep:candle-transformers", "dep:tokenizers", "dep:hf-hub", "dep:sha2"]+# Local zero-shot decision head (issue #1057, tier 2 of the System One decide+# ladder): a ModernBERT-class candle classifier loaded from a local model+# directory. Deliberately does NOT include hf-hub — this tier has no download+# path and adds nothing to the published egress inventory.+decide-local = ["dep:candle-core", "dep:candle-nn", "dep:candle-transformers", "dep:tokenizers"]# Experimental local ONNX backend; xerj-server exposes it only when the# feature is propagated and explicitly selected at runtime.onnx-experimental = ["dep:ort", "dep:tokenizers", "dep:sha2"][dev-dependencies]tokio = { version = "1", features = ["full"] }+tempfile = { workspace = true }[[example]]name = "onnx_experimental"diff --git a/engine/crates/xerj-ai/src/decide.rs b/engine/crates/xerj-ai/src/decide.rsnew file mode 100644index 000000000..429f4b2eb--- /dev/null+++ b/engine/crates/xerj-ai/src/decide.rs@@ -0,0 +1,692 @@+//! Local zero-shot decision head — tier 2 of the System One decide ladder.+//!+//! [`crate::neural`] answers *what is this text about* with vectors; this+//! module answers *what is this text* with probabilities over labels, in+//! process, via the same candle path. It is the rung below the history vote+//! in `xerj-api`'s decide ladder (issue #1057): when the `[decisions]`+//! history index has support the vote wins, and this head answers what the+//! history cannot — a node with no labelled history at all, or a question+//! whose payload retrieves no labelled neighbour.+//!+//! # The contract: pair scoring, not a fixed vocabulary+//!+//! A classifier head has a fixed `id2label`; decision questions arrive with+//! arbitrary labels (`noul` positive labels, `choice` criteria options), so a+//! fixed-vocabulary head cannot answer them. The head therefore loads an+//! NLI-shaped sequence-pair scorer — `id2label` must name `entailment` — and+//! scores one (premise, hypothesis) pair per candidate label, premise = the+//! payload text, hypothesis = [`hypothesis`] applied to the label. The+//! entailment probability of each hypothesis is renormalised across the+//! question's labels to a distribution that sums to 1. This is the+//! zero-shot-classification design the HF pipeline made standard, and it is+//! the shape the open `xerj-decide` model (issue #1064) is trained against:+//! v1.1 loads through this path unchanged.+//!+//! # Local files only — no egress+//!+//! Unlike [`crate::neural`], this module has **no hub download**: there is no+//! `hf-hub` dependency and no network code, so it adds nothing to the+//! published egress inventory. Weights are read from a configured directory+//! holding `config.json`, `tokenizer.json` and `model.safetensors` — the same+//! three files [`crate::neural::NeuralConfig::local_dir`] expects. A+//! deployment gets a checkpoint onto the machine the same way it gets any+//! other air-gapped asset.+//!+//! Weights load as F32 safetensors. candle 0.9 no longer ships the quantized+//! safetensors `VarBuilder` that earlier versions had (`gguf` is the only+//! quantized container left), so "quantized weights" in the issue's sense+//! would mean a gguf loader — deliberately not built here; the ≤ 300 MB+//! download budget is a property of the trained artifact (#1064), not of the+//! loader.+//!+//! Compiled only under the `decide-local` cargo feature.++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex, OnceLock, Weak};++use anyhow::{anyhow, Context, Result};+use candle_core::{DType, Device, IndexOp, Tensor};+use candle_nn::VarBuilder;+use candle_transformers::models::modernbert::{Config, ModernBertForSequenceClassification};+use tokenizers::{Encoding, Tokenizer, TruncationParams};++use crate::microbatch::group_by_padded_cost;++/// Cap on tokens per (premise, hypothesis) pair. Decision payloads are SMS-+/// and ticket-shaped, and every extra token is paid by every pair in the+/// batch; 512 covers the payload shapes the benchmarks use with headroom.+pub const MAX_TOKENS: usize = 512;++/// Rows in one forward pass — the same knee the neural embedder measured+/// ([`crate::neural`]): throughput climbs to 64 rows on CPU and then+/// flattens.+const MAX_BATCH_ROWS: usize = 64;++/// Ceiling on `rows × padded_sequence_length` for one forward pass, bounding+/// the activation memory one call can allocate. Same value as the neural+/// embedder's.+const PADDED_TOKEN_BUDGET: usize = 4_096;++/// How one label becomes an NLI hypothesis. Deterministic and part of the+/// model contract (#1064 trains against exactly this sentence); a template+/// is required because a bare label word is not a premise-hypothesis+/// statement an NLI head was trained to judge.+pub fn hypothesis(label: &str) -> String {+ format!("This example is {label}.")+}++/// The competing hypothesis for a `noul`: a binary question is scored as two+/// candidate statements, the positive label and its negation, so the answer+/// is a comparison rather than one unopposed score.+pub fn negation_hypothesis(label: &str) -> String {+ format!("This example is not {label}.")+}++/// How to obtain the decision model. A directory, not a hub id — see the+/// module header: this tier has no download path.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct DecideConfig {+ /// Directory holding `config.json`, `tokenizer.json` and+ /// `model.safetensors`.+ pub model_dir: PathBuf,+}++/// One scoring request: a payload and the candidate labels to judge it+/// against. `hypotheses` are full hypothesis strings (build them with+/// [`hypothesis`] / [`negation_hypothesis`]) so the caller controls label+/// wording; this module only scores what it is handed.+#[derive(Debug, Clone)]+pub struct ScoreRequest {+ pub premise: String,+ pub hypotheses: Vec<String>,+}++/// A loaded ModernBERT-class zero-shot decision head. Cheap to share behind+/// an `Arc`; scoring takes `&self`.+pub struct DecideModel {+ model: ModernBertForSequenceClassification,+ tokenizer: Tokenizer,+ device: Device,+ /// Row of the classifier head that means "entailment", resolved from+ /// `id2label` at load time.+ entailment: usize,+ pad_token_id: u32,+ /// The label vocabulary, for diagnostics (`/_decide`, `/v1/models`).+ labels: Vec<String>,+}++impl DecideModel {+ /// The classifier's own label vocabulary, index-ordered.+ pub fn labels(&self) -> &[String] {+ &self.labels+ }++ /// Load the model from a local directory. **Blocking** — callers run+ /// this off the async executor (see [`DecideHandle`]).+ pub fn load(cfg: &DecideConfig) -> Result<Self> {+ let dir = &cfg.model_dir;+ let config_path = dir.join("config.json");+ let tokenizer_path = dir.join("tokenizer.json");+ let weights_path = dir.join("model.safetensors");+ for (name, path) in [+ ("config.json", &config_path),+ ("tokenizer.json", &tokenizer_path),+ ("model.safetensors", &weights_path),+ ] {+ if !path.exists() {+ return Err(anyhow!(+ "decide model dir {} is missing {name} (candle requires safetensors \+ weights, not pytorch_model.bin)",+ dir.display()+ ));+ }+ }++ let config_json = std::fs::read_to_string(&config_path)+ .with_context(|| format!("read decide config {}", config_path.display()))?;+ let config: Config = serde_json::from_str(&config_json)+ .with_context(|| format!("parse decide config {}", config_path.display()))?;+ let (entailment, labels) = entailment_index(&config)+ .with_context(|| format!("decide config {}", config_path.display()))?;++ let mut tokenizer = Tokenizer::from_file(&tokenizer_path)+ .map_err(|e| anyhow!("load tokenizer {}: {e}", tokenizer_path.display()))?;+ // Padding is applied per batch in [`Self::score_blocking`], so that+ // one long pair cannot charge every short pair its length — the same+ // discipline as [`crate::neural`].+ tokenizer.with_padding(None);+ tokenizer+ .with_truncation(Some(TruncationParams {+ max_length: MAX_TOKENS.min(config.max_position_embeddings.max(1)),+ ..Default::default()+ }))+ .map_err(|e| anyhow!("configure decide tokenizer truncation: {e}"))?;++ let device = Device::Cpu;+ let vb = unsafe {+ VarBuilder::from_mmaped_safetensors(+ std::slice::from_ref(&weights_path),+ DType::F32,+ &device,+ )+ .with_context(|| format!("map decide weights {}", weights_path.display()))?+ };+ let model = ModernBertForSequenceClassification::load(vb, &config)+ .map_err(|e| anyhow!("load ModernBERT classifier: {e}"))?;++ Ok(Self {+ model,+ tokenizer,+ device,+ entailment,+ pad_token_id: config.pad_token_id,+ labels,+ })+ }++ /// Score every request's hypotheses against its premise. Returns, per+ /// request, one probability per hypothesis (input order) summing to 1.+ /// **Blocking / CPU-bound** — call via `spawn_blocking`.+ ///+ /// All pairs across all requests are flattened and pushed through the+ /// model in length-homogeneous batches, so a request's cost is paid once+ /// for all of its labels.+ pub fn score_blocking(&self, requests: &[ScoreRequest]) -> Result<Vec<Vec<f32>>> {+ if requests.is_empty() {+ return Ok(Vec::new());+ }+ let mut pairs: Vec<(String, String)> = Vec::new();+ let mut spans: Vec<(usize, usize)> = Vec::with_capacity(requests.len()); // (start, len)+ for req in requests {+ if req.hypotheses.is_empty() {+ return Err(anyhow!(+ "a score request with no hypotheses cannot be scored"+ ));+ }+ spans.push((pairs.len(), req.hypotheses.len()));+ for hypothesis in &req.hypotheses {+ pairs.push((req.premise.clone(), hypothesis.clone()));+ }+ }++ let encodings = self+ .tokenizer+ .encode_batch(pairs, true)+ .map_err(|e| anyhow!("tokenize decide pairs: {e}"))?;+ let lengths: Vec<usize> = encodings+ .iter()+ .map(|enc| enc.get_ids().len().min(MAX_TOKENS))+ .collect();++ // Entailment probability per pair, input order. With template+ // post-processing every encoding holds at least [CLS] and [SEP], so+ // a length of 0 cannot occur.+ let mut entailment_probs: Vec<f32> = vec![0.0; lengths.len()];+ for rows in group_by_padded_cost(&lengths, MAX_BATCH_ROWS, PADDED_TOKEN_BUDGET) {+ let seq_len = rows.iter().map(|&i| lengths[i]).max().unwrap_or(0);+ if seq_len == 0 {+ continue;+ }+ let probs = self.forward_padded(&encodings, &rows, &lengths, seq_len)?;+ for (row, prob) in rows.into_iter().zip(probs) {+ entailment_probs[row] = prob;+ }+ }++ // Renormalise each request's hypothesis scores to sum to 1.+ let mut out = Vec::with_capacity(requests.len());+ for (start, count) in spans {+ let scores = &entailment_probs[start..start + count];+ let total: f32 = scores.iter().sum();+ if !total.is_finite() || total <= 0.0 {+ return Err(anyhow!(+ "decide model returned zero entailment mass for a question's \+ hypotheses; refusing to fabricate a uniform distribution"+ ));+ }+ out.push(scores.iter().map(|p| p / total).collect());+ }+ Ok(out)+ }++ /// Run one rectangular forward pass over `rows` and read the entailment+ /// column of the classifier's softmax. Returns one probability per row,+ /// in `rows` order.+ fn forward_padded(+ &self,+ encodings: &[Encoding],+ rows: &[usize],+ lengths: &[usize],+ seq_len: usize,+ ) -> Result<Vec<f32>> {+ let batch = rows.len();+ let mut ids: Vec<u32> = Vec::with_capacity(batch * seq_len);+ let mut mask: Vec<u32> = Vec::with_capacity(batch * seq_len);+ for &row in rows {+ let len = lengths[row];+ ids.extend_from_slice(&encodings[row].get_ids()[..len]);+ ids.resize(ids.len() + (seq_len - len), self.pad_token_id);+ mask.extend_from_slice(&encodings[row].get_attention_mask()[..len]);+ mask.resize(mask.len() + (seq_len - len), 0);+ }+ let input_ids = Tensor::from_vec(ids, (batch, seq_len), &self.device)+ .map_err(|e| anyhow!("build decide input_ids tensor: {e}"))?;+ let attention_mask = Tensor::from_vec(mask, (batch, seq_len), &self.device)+ .map_err(|e| anyhow!("build decide attention_mask tensor: {e}"))?;+ // The classifier's forward already softmaxes over its label rows.+ let probs = self+ .model+ .forward(&input_ids, &attention_mask)+ .map_err(|e| anyhow!("modernbert forward: {e}"))?;+ let entailment = probs+ .i((.., self.entailment))+ .map_err(|e| anyhow!("read entailment column: {e}"))?;+ entailment+ .to_vec1::<f32>()+ .map_err(|e| anyhow!("read entailment probabilities: {e}"))+ }+}++/// Resolve the entailment row from `id2label`, and the label vocabulary in+/// index order. An NLI-shaped head is this module's whole contract — a+/// fixed-vocabulary classifier cannot score arbitrary labels, so anything+/// else is refused at load with the label set it found.+fn entailment_index(config: &Config) -> Result<(usize, Vec<String>)> {+ let classifier = config.classifier_config.as_ref().ok_or_else(|| {+ anyhow!("config.json has no id2label/label2id classifier block — not a classifier")+ })?;+ let mut labels: Vec<(usize, String)> = classifier+ .id2label+ .iter()+ .filter_map(|(idx, label)| idx.parse::<usize>().ok().map(|i| (i, label.clone())))+ .collect();+ labels.sort_by_key(|(idx, _)| *idx);+ if labels.is_empty() {+ return Err(anyhow!("config.json id2label is empty"));+ }+ let entailment = labels+ .iter()+ .find(|(_, label)| label.to_lowercase().contains("entailment"))+ .map(|(idx, _)| *idx)+ .ok_or_else(|| {+ let found: Vec<&str> = labels.iter().map(|(_, l)| l.as_str()).collect();+ anyhow!(+ "the decision head must be NLI-shaped with an \"entailment\" label; \+ id2label is {found:?}"+ )+ })?;+ Ok((entailment, labels.into_iter().map(|(_, l)| l).collect()))+}++// ─────────────────────────────────────────────────────────────────────────────+// The lazy handle — the same shape as `embedder::NeuralHandle`+// ─────────────────────────────────────────────────────────────────────────────++type DecideCell = tokio::sync::OnceCell<Arc<DecideModel>>;++/// Process-scoped registry of lazily loaded decision models, so every+/// `AppState` (or test node) configured with the same directory shares one+/// loaded copy. Weak values: the registry coordinates sharing without+/// extending a model's lifetime.+fn shared_decide_cell(cfg: &DecideConfig) -> Arc<DecideCell> {+ static CELLS: OnceLock<Mutex<HashMap<DecideConfig, Weak<DecideCell>>>> = OnceLock::new();+ let mut cells = CELLS+ .get_or_init(|| Mutex::new(HashMap::new()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ if let Some(cell) = cells.get(cfg).and_then(Weak::upgrade) {+ return cell;+ }+ cells.retain(|_, cell| cell.strong_count() > 0);+ let cell = Arc::new(DecideCell::new());+ cells.insert(cfg.clone(), Arc::downgrade(&cell));+ cell+}++/// A lazily-loaded decision head. The model loads on the first score, off+/// the async executor; later calls reuse the shared `Arc`. Cheap to clone:+/// a config path and the shared cell.+#[derive(Clone)]+pub struct DecideHandle {+ cfg: DecideConfig,+ cell: Arc<DecideCell>,+}++impl DecideHandle {+ pub fn new(cfg: DecideConfig) -> Self {+ let cell = shared_decide_cell(&cfg);+ Self { cfg, cell }+ }++ /// The configured model directory, for diagnostics.+ pub fn model_dir(&self) -> &Path {+ &self.cfg.model_dir+ }++ /// Get-or-load the model. The first caller pays the blocking load;+ /// concurrent callers await the same init. A load failure is sticky for+ /// the process (the OnceCell holds the error), which is the honest+ /// behaviour for a mis-configured model directory: every request says+ /// so until the operator fixes the directory and restarts.+ async fn get(&self) -> Result<Arc<DecideModel>> {+ self.cell+ .get_or_try_init(|| async {+ let cfg = self.cfg.clone();+ let model = tokio::task::spawn_blocking(move || DecideModel::load(&cfg))+ .await+ .map_err(|e| anyhow!("decide model load task panicked: {e}"))??;+ tracing::info!(+ model_dir = %self.cfg.model_dir.display(),+ "local decision head loaded (ModernBERT-class, candle)"+ );+ Ok::<_, anyhow::Error>(Arc::new(model))+ })+ .await+ .cloned()+ }++ /// [`DecideModel::score_blocking`], off the async executor.+ pub async fn score(&self, requests: Vec<ScoreRequest>) -> Result<Vec<Vec<f32>>> {+ let model = self.get().await?;+ tokio::task::spawn_blocking(move || model.score_blocking(&requests))+ .await+ .map_err(|e| anyhow!("decide score task panicked: {e}"))?+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn fixture_dir(tag: &str) -> std::path::PathBuf {+ let dir = tempfile::tempdir().expect("tempdir").keep();+ crate::decide::testing::write_fixture(&dir)+ .unwrap_or_else(|e| panic!("write decide fixture {tag}: {e:#}"));+ dir+ }++ #[test]+ fn loads_and_scores_noul_and_choice_pairs_deterministically() {+ let model = DecideModel::load(&DecideConfig {+ model_dir: fixture_dir("roundtrip"),+ })+ .expect("load fixture");+ assert_eq!(+ model+ .labels()+ .iter()+ .map(String::as_str)+ .collect::<Vec<_>>(),+ vec!["contradiction", "neutral", "entailment"],+ "fixture is NLI-shaped"+ );++ let requests = vec![+ ScoreRequest {+ premise: "urgent prize claim call now".into(),+ hypotheses: vec![hypothesis("spam"), negation_hypothesis("spam")],+ },+ ScoreRequest {+ premise: "hi it is me again about dinner".into(),+ hypotheses: vec![+ hypothesis("billing"),+ hypothesis("tech"),+ hypothesis("spam"),+ ],+ },+ ];+ let first = model.score_blocking(&requests).expect("score");+ let second = model.score_blocking(&requests).expect("score again");+ assert_eq!(first.len(), 2, "one score vector per request");+ assert_eq!(first[0].len(), 2, "noul: positive + negation");+ assert_eq!(first[1].len(), 3, "choice: one hypothesis per option");+ for (i, scores) in first.iter().enumerate() {+ let sum: f32 = scores.iter().sum();+ assert!(+ (sum - 1.0).abs() < 1e-4,+ "request {i} scores sum to {sum}: {scores:?}"+ );+ assert!(+ scores.iter().all(|p| (0.0..=1.0).contains(p)),+ "probabilities in [0,1]: {scores:?}"+ );+ }+ // Same inputs, same outputs — CPU forward with fixed batching is+ // deterministic, and the tier's answers must be reproducible.+ assert_eq!(first, second, "scoring must be deterministic");+ }++ #[test]+ fn a_missing_model_file_is_named_at_load() {+ let dir = tempfile::tempdir().expect("tempdir");+ let err = DecideModel::load(&DecideConfig {+ model_dir: dir.path().to_path_buf(),+ })+ .err()+ .expect("load must fail");+ let msg = format!("{err:#}");+ assert!(msg.contains("config.json"), "{msg}");+ }++ #[test]+ fn a_head_without_an_entailment_label_is_refused() {+ let dir = tempfile::tempdir().expect("tempdir").keep();+ crate::decide::testing::write_fixture(&dir).expect("write fixture");+ let config_path = dir.join("config.json");+ let mut config: serde_json::Value = std::fs::read_to_string(&config_path)+ .expect("read")+ .parse()+ .expect("parse");+ config["id2label"] = serde_json::json!({"0": "neg", "1": "pos"});+ config["label2id"] = serde_json::json!({"neg": "0", "pos": "1"});+ std::fs::write(&config_path, config.to_string()).expect("rewrite");+ let err = DecideModel::load(&DecideConfig { model_dir: dir })+ .err()+ .expect("load must fail");+ let msg = format!("{err:#}");+ assert!(msg.contains("entailment"), "{msg}");+ assert!(msg.contains("NLI-shaped"), "{msg}");+ }++ #[test]+ fn handles_sharing_by_config_and_stay_lazy() {+ let cfg = DecideConfig {+ model_dir: fixture_dir("sharing"),+ };+ let first = DecideHandle::new(cfg.clone());+ let second = DecideHandle::new(cfg);+ assert!(Arc::ptr_eq(&first.cell, &second.cell));+ assert!(first.cell.get().is_none(), "construction must remain lazy");+ }+}++/// Test-support: writes a tiny, deterministic, NLI-shaped ModernBERT+/// classifier into a directory. The fixture is untrained — its scores are+/// reproducible arithmetic, not judgement quality — so it exists to prove+/// the loading and scoring path end to end, never to say anything about+/// accuracy (that is `benchmarks/decisions-as-retrieval`'s job, against the+/// real trained model).+#[doc(hidden)]+pub mod testing {+ use super::*;+ use std::collections::BTreeMap;++ /// A tiny wordpiece vocabulary: specials first, then the words the tests+ /// speak. Anything else tokenises to `[UNK]`, which the model handles.+ const VOCAB: &[&str] = &[+ "[PAD]",+ "[UNK]",+ "[CLS]",+ "[SEP]",+ "this",+ "example",+ "is",+ "not",+ "spam",+ "ham",+ "billing",+ "tech",+ "refund",+ "shipping",+ "money",+ "back",+ "urgent",+ "prize",+ "claim",+ "call",+ "now",+ "hi",+ "it",+ "me",+ "again",+ "about",+ "dinner",+ "message",+ "subscription",+ "cancel",+ ];++ struct TinyConfig {+ vocab_size: usize,+ hidden: usize,+ layers: usize,+ intermediate: usize,+ labels: usize,+ }++ /// Deterministic pseudo-random fill in (-0.5, 0.5): a plain LCG keeps the+ /// fixture byte-stable across runs and machines.+ fn lcg(seed: &mut u32) -> f32 {+ *seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);+ ((*seed >> 8) as f32 / 16_777_216.0) - 0.5+ }++ fn tensor(seed: &mut u32, shape: &[usize]) -> Result<Tensor> {+ let len: usize = shape.iter().product();+ let values: Vec<f32> = (0..len).map(|_| lcg(seed)).collect();+ Ok(Tensor::from_vec(values, shape, &Device::Cpu)?)+ }++ fn ones(len: usize) -> Result<Tensor> {+ Ok(Tensor::ones((len,), DType::F32, &Device::Cpu)?)+ }++ /// Write the fixture and return the [`DecideConfig`] naming it.+ pub fn write_fixture(dir: &Path) -> Result<DecideConfig> {+ let tiny = TinyConfig {+ vocab_size: VOCAB.len(),+ hidden: 32,+ layers: 2,+ intermediate: 64,+ labels: 3,+ };+ std::fs::create_dir_all(dir)?;++ // config.json — the classifier block rides at the top level+ // (candle's Config flattens it in).+ let id2label: BTreeMap<String, String> = [+ ("0", "contradiction"),+ ("1", "neutral"),+ ("2", "entailment"),+ ]+ .iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ let label2id: BTreeMap<String, String> = id2label+ .iter()+ .map(|(k, v)| (v.clone(), k.clone()))+ .collect();+ let config = serde_json::json!({+ "model_type": "modernbert",+ "architectures": ["ModernBertForSequenceClassification"],+ "vocab_size": tiny.vocab_size,+ "hidden_size": tiny.hidden,+ "num_hidden_layers": tiny.layers,+ "num_attention_heads": 4,+ "intermediate_size": tiny.intermediate,+ "max_position_embeddings": 512,+ "layer_norm_eps": 1e-12,+ "pad_token_id": 0,+ "global_attn_every_n_layers": 3,+ "global_rope_theta": 10_000.0,+ "local_attention": 128,+ "local_rope_theta": 10_000.0,+ "id2label": id2label,+ "label2id": label2id,+ "classifier_pooling": "cls",+ });+ std::fs::write(dir.join("config.json"), config.to_string())?;++ // tokenizer.json — a real wordpiece tokenizer with BERT template+ // post-processing, so pair encoding produces [CLS] a [SEP] b [SEP].+ // The vocab is fed through the standard one-token-per-line file (line+ // number = id) because that is the builder's vocab input that does+ // not depend on the hasher of a map we build ourselves.+ let vocab_path = dir.join("vocab.txt");+ std::fs::write(&vocab_path, VOCAB.join("\n") + "\n")?;+ let model = tokenizers::models::wordpiece::WordPieceBuilder::default()+ .files(vocab_path.to_string_lossy().into_owned())+ .unk_token("[UNK]".into())+ .continuing_subword_prefix("##".into())+ .build()+ .map_err(|e| anyhow!("build wordpiece: {e}"))?;+ std::fs::remove_file(&vocab_path).ok();+ let mut tokenizer = tokenizers::Tokenizer::new(model);+ tokenizer.with_normalizer(Some(tokenizers::normalizers::BertNormalizer::default()));+ tokenizer.with_pre_tokenizer(Some(tokenizers::pre_tokenizers::bert::BertPreTokenizer));+ let post = tokenizers::processors::template::TemplateProcessing::builder()+ .try_single("[CLS] $A [SEP]")+ .map_err(|e| anyhow!("single template: {e}"))?+ .try_pair("[CLS] $A [SEP] $B:1 [SEP]:1")+ .map_err(|e| anyhow!("pair template: {e}"))?+ .special_tokens(vec![("[CLS]", 2u32), ("[SEP]", 3u32)])+ .build()+ .map_err(|e| anyhow!("template processor: {e}"))?;+ tokenizer.with_post_processor(Some(post));+ tokenizer+ .save(dir.join("tokenizer.json"), true)+ .map_err(|e| anyhow!("save tokenizer: {e}"))?;++ // model.safetensors — every tensor ModernBertForSequenceClassification+ // loads, under the names its loader asks for.+ let mut seed = 0x5eed_1234u32;+ let mut tensors: HashMap<String, Tensor> = HashMap::new();+ let h = tiny.hidden;+ tensors.insert(+ "model.embeddings.tok_embeddings.weight".into(),+ tensor(&mut seed, &[tiny.vocab_size, h])?,+ );+ tensors.insert("model.embeddings.norm.weight".into(), ones(h)?);+ for layer in 0..tiny.layers {+ let p = format!("model.layers.{layer}");+ tensors.insert(+ format!("{p}.attn.Wqkv.weight"),+ tensor(&mut seed, &[3 * h, h])?,+ );+ tensors.insert(format!("{p}.attn.Wo.weight"), tensor(&mut seed, &[h, h])?);+ tensors.insert(+ format!("{p}.mlp.Wi.weight"),+ tensor(&mut seed, &[2 * tiny.intermediate, h])?,+ );+ tensors.insert(+ format!("{p}.mlp.Wo.weight"),+ tensor(&mut seed, &[h, tiny.intermediate])?,+ );+ tensors.insert(format!("{p}.mlp_norm.weight"), ones(h)?);+ }+ tensors.insert("model.final_norm.weight".into(), ones(h)?);+ tensors.insert("head.dense.weight".into(), tensor(&mut seed, &[h, h])?);+ tensors.insert("head.norm.weight".into(), ones(h)?);+ tensors.insert(+ "classifier.weight".into(),+ tensor(&mut seed, &[tiny.labels, h])?,+ );+ tensors.insert("classifier.bias".into(), tensor(&mut seed, &[tiny.labels])?);+ candle_core::safetensors::save(&tensors, dir.join("model.safetensors"))?;++ Ok(DecideConfig {+ model_dir: dir.to_path_buf(),+ })+ }+}diff --git a/engine/crates/xerj-ai/src/lib.rs b/engine/crates/xerj-ai/src/lib.rsindex 38632096a..812b74a71 100644--- a/engine/crates/xerj-ai/src/lib.rs+++ b/engine/crates/xerj-ai/src/lib.rs@@ -8,8 +8,10 @@//! - [`embed`] — Embedding proxy: async HTTP client for OpenAI-compatible embedding APIs//! - [`local`] — Built-in zero-config deterministic text embedder (feature hashing)//! - [`neural`] — Built-in neural BERT sentence embedder via candle (feature `neural`)-//! - `microbatch` — Length-aware batching shared by the two in-process-//! encoders, so one long passage cannot pad a whole window up to its length+//! - [`decide`] — Built-in zero-shot decision head: a ModernBERT-class candle+//! classifier answering noul/choice with no history index (feature `decide-local`)+//! - `microbatch` — Length-aware batching shared by the in-process encoders,+//! so one long passage cannot pad a whole window up to its length//! - `onnx` — Experimental MiniLM-compatible FP32 ONNX backend//! (feature `onnx-experimental`; server feature + explicit runtime selection required)//! - [`chunker`] — Text chunking with sentence-aware splitting and overlap@@ -21,10 +23,16 @@//! keeping it around shadowed the real API and invited accidental use.pub mod chunker;+#[cfg(feature = "decide-local")]+pub mod decide;pub mod embed;pub mod embedder;pub mod local;-#[cfg(any(feature = "neural", feature = "onnx-experimental"))]+#[cfg(any(+ feature = "neural",+ feature = "onnx-experimental",+ feature = "decide-local"+))]pub mod microbatch;#[cfg(feature = "neural")]pub mod neural;diff --git a/engine/crates/xerj-api/Cargo.toml b/engine/crates/xerj-api/Cargo.tomlindex d10784b1d..b6671d26b 100644--- a/engine/crates/xerj-api/Cargo.toml+++ b/engine/crates/xerj-api/Cargo.toml@@ -10,6 +10,12 @@ authors.workspace = true# example (#903) and for anyone linking this crate directly. The shipped# binary turns it on through `xerj-server`'s own `neural` feature.neural = ["xerj-engine/neural"]+# Local zero-shot decision head (issue #1057): tier 2 of the System One+# decide ladder, answering /v1/systemone and /_decide when the history+# index has no support. Mirrors how `neural` is gated — off by default,+# enabled by whoever links this crate (the xerj-server wiring is a+# follow-up).+decide-local = ["dep:xerj-ai", "xerj-ai/decide-local"]onnx-experimental = ["xerj-engine/onnx-experimental"][dependencies]@@ -18,6 +24,9 @@ xerj-engine = { path = "../xerj-engine" }xerj-query = { path = "../xerj-query" }xerj-rerank = { path = "../xerj-rerank" }xerj-wasm = { path = "../xerj-wasm" }+# Local decision head (feature `decide-local`); no other purpose, so the+# dependency itself is optional.+xerj-ai = { path = "../xerj-ai", optional = true }# Note: this crate intentionally does NOT depend on xerj-console-api.# Xerj Console is a peer product mounted at the server level (`xerj-server`)# via Router::merge. Engine API and Xerj Console API are decoupled — thediff --git a/engine/crates/xerj-api/src/state.rs b/engine/crates/xerj-api/src/state.rsindex 2473ce0f4..9e2e9e330 100644--- a/engine/crates/xerj-api/src/state.rs+++ b/engine/crates/xerj-api/src/state.rs@@ -544,6 +544,15 @@ pub struct AppState {/// the environment again. A test points a node at its own stub by replacing/// this field, so parallel tests never race on process-wide env state.pub rerank: Arc<xerj_rerank::ProviderSettings>,+ /// The System One decide-ladder settings (tier 2 local head armed or+ /// not) — the same injection seam as `rerank`, for+ /// [`crate::systemone_api`].+ ///+ /// Resolved once here from `XERJ_DECIDE_MODE` / `XERJ_DECIDE_MODEL_DIR`+ /// (the env half of a future `--decide-mode` server flag) and never read+ /// from the environment again. A test arms a node by replacing this+ /// field, so parallel tests never race on process-wide env state.+ pub decide: Arc<crate::systemone_api::DecideSettings>,}impl AppState {@@ -582,8 +591,10 @@ impl AppState {&config.rerank.api_key,&config.rerank.endpoint,));+ let decide = Arc::new(crate::systemone_api::DecideSettings::from_env());Self {rerank,+ decide,config: Arc::new(config),engine: Arc::new(engine),metrics: Arc::new(metrics),diff --git a/engine/crates/xerj-api/src/systemone_api.rs b/engine/crates/xerj-api/src/systemone_api.rsindex 788a8d24b..38f870306 100644--- a/engine/crates/xerj-api/src/systemone_api.rs+++ b/engine/crates/xerj-api/src/systemone_api.rs@@ -1,6 +1,6 @@-//! The local judge: System One wire-compatible decisions from a vote.+//! The local judge: System One wire-compatible decisions from a ladder.//!-//! Two surfaces, one mechanism:+//! Two surfaces, one ladder://!//! - `POST /v1/systemone` (native router) speaks TypeSafe's documented System//! One request/response shape, so a client written for their API —@@ -17,6 +17,28 @@//! an ordinary search against an ordinary index. That is the point of the//! feature — the same interface, with the evidence staying home.//!+//! # The decide ladder (#1057)+//!+//! Both surfaces answer through the same ordered ladder, per question:+//!+//! 1. **History vote** — when `[decisions] index` is configured and returns+//! labelled support, the vote wins. It is the measured tier and it shows+//! its evidence.+//! 2. **Local zero-shot head** (feature `decide-local`,+//! `XERJ_DECIDE_MODE=local`, the env half of `--decide-mode local`) — a+//! ModernBERT-class candle classifier ([`xerj_ai::decide`]) loaded from+//! `XERJ_DECIDE_MODEL_DIR`. It answers every no-support outcome: no+//! `[decisions] index` at all, a configured index that is missing, and a+//! question whose payload retrieves no labelled neighbour. Its model echo+//! is [`LOCAL_MODEL_ID`] — the same never-a-Jev-name discipline.+//! 3. **Hosted key** — reserved, not built. When tiers 1 and 2 cannot+//! answer, the documented errors stand rather than a fabricated+//! probability.+//!+//! The default build (no `decide-local`, or the mode unset) behaves exactly+//! as before: 503 with no `[decisions]` index, 422 `no_support` / on a+//! history that cannot answer.+//!//! # The wire contract, and where we deliberately break it//!//! Request: `{ state, model, questions: { id: { type, instructions, criteria } } }`.@@ -34,7 +56,8 @@//! acknowledged and skipped: judge rules are not retrieval vocabulary.//! References that resolve to nothing, and a payload with no text at all,//! are 422s naming the question — never a confident vote on text the-//! question never saw.+//! question never saw. (These are request-shape refusals: the local head+//! does not rescue them, because there is no payload to classify.)//!//! Response: `{ model, answers, usage }` with `answers` keyed exactly by the//! question ids sent and each answer carrying only its documented fields —@@ -46,14 +69,25 @@//! 1. `model` is echoed as `xerj-history-vote-1`, never as a Jev model name.//! Echoing `jev-1.13.0` would claim these probabilities are the hosted//! model's. The requested name is reported as `decisions.requested_model`.+//! When the local tier answered (all or part of the request), the echo is+//! still `xerj-history-vote-1` for wire compatibility, `decisions.model`+//! names the tier that answered each question per-question in+//! `decisions.evidence.*.tier`, and `decisions.local_model` names the+//! local head.//! 2. A question with no support — an empty history, or no labelled//! neighbour — is a 422 naming the question ids. Zero support must not//! become a fabricated 0.5. (`/_decide` says the same thing as `abstain`.)+//! The local tier is the documented exception: enabled, it answers those+//! same questions with the head's probabilities instead.//!//! `score` questions (2–10 ordinal levels, weighted-average answer) have no//! vote analogue and no benchmark: 422, in the docs.use std::collections::BTreeMap;+#[cfg(feature = "decide-local")]+use std::path::Path;+#[cfg(feature = "decide-local")]+use std::path::PathBuf;use std::time::Instant;use axum::extract::State;@@ -69,6 +103,11 @@ use crate::state::AppState;/// The model id this endpoint truthfully is. Never a Jev name.pub const MODEL_ID: &str = "xerj-history-vote-1";+/// The model id the local zero-shot tier truthfully is — the same discipline+/// as [`MODEL_ID`]: never a Jev name, because these probabilities are the+/// local head's, not a hosted judge's.+pub const LOCAL_MODEL_ID: &str = "xerj-decide-local-1";+/// One question's vote text is bounded so a caller cannot make the node/// search for a novel of its choosing; matches the rerank stage's philosophy/// of caller-chosen cost with a server-side ceiling.@@ -79,6 +118,260 @@ const MAX_CHOICE_OPTIONS: usize = 255;/// than the rerank stage would judge.const MAX_QUESTIONS: usize = 300;+// ─────────────────────────────────────────────────────────────────────────────+// The decide ladder (#1057)+// ─────────────────────────────────────────────────────────────────────────────++/// The tiers of the decide ladder, in resolution order. History wins where+/// it has support; the local head answers what history cannot; the hosted+/// tier is reserved and unbuilt, so the ladder bottoms out in the documented+/// errors rather than a guess.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DecideTier {+ /// Tier 1: the weighted nearest-neighbour vote over `[decisions] index`.+ History,+ /// Tier 2: the local zero-shot decision head (feature `decide-local`,+ /// `XERJ_DECIDE_MODE=local`).+ Local,+ /// Tier 3: a hosted decision provider key. Not yet built — see the+ /// module header. When [`resolve_tier`] returns `None` the caller+ /// answers with today's error contract.+ Hosted,+}++/// What the history index said for one question. The ladder treats every+/// no-support outcome the same way: the local head may answer it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum HistorySupport {+ /// Labelled neighbours came back.+ Supported,+ /// No `[decisions] index` is configured at all.+ NotConfigured,+ /// The configured index does not exist or could not be searched; the+ /// string is the cause, surfaced to the operator when no tier can+ /// answer.+ Unusable(String),+ /// The index answered with no labelled neighbour.+ NoLabelledNeighbour,+}++/// Resolve the ladder for one question. Pure, and unit-tested: the order is+/// the contract.+pub(crate) fn resolve_tier(support: &HistorySupport, local_enabled: bool) -> Option<DecideTier> {+ match support {+ HistorySupport::Supported => Some(DecideTier::History),+ HistorySupport::NotConfigured+ | HistorySupport::Unusable(_)+ | HistorySupport::NoLabelledNeighbour => {+ if local_enabled {+ Some(DecideTier::Local)+ } else {+ None // Hosted is not built; the caller answers with the error.+ }+ }+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// DecideSettings — the node's ladder configuration+// ─────────────────────────────────────────────────────────────────────────────++/// The node's decide-ladder configuration, resolved once at boot and held in+/// [`AppState`] — the same seam `state.rerank` uses. The runtime switch is+/// `XERJ_DECIDE_MODE` / `XERJ_DECIDE_MODEL_DIR` (the env half of+/// `--decide-mode local`; the CLI flag lands with the xerj-server wiring),+/// mirroring how `XERJ_EMBED_MODE` backs `--embed-mode`.+#[derive(Clone, Default)]+pub struct DecideSettings {+ /// The local tier, when enabled and compiled in.+ #[cfg(feature = "decide-local")]+ local: Option<LocalTier>,+}++impl std::fmt::Debug for DecideSettings {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ // Not the handle: whether the tier is armed. The model directory is+ // in the logs and the error bodies, not needed on every Debug print.+ f.debug_struct("DecideSettings")+ .field("local", &self.local_available())+ .finish()+ }+}++/// The enabled local tier: a lazily-loaded decision head and the directory+/// it loads from.+#[cfg(feature = "decide-local")]+#[derive(Clone)]+pub struct LocalTier {+ handle: xerj_ai::decide::DecideHandle,+}++impl DecideSettings {+ /// The default node: history vote only, today's error contract.+ pub fn history_only() -> Self {+ Self::default()+ }++ /// A node with the local tier enabled, pointing at `model_dir`. Public+ /// so tests can arm a node directly and the xerj-server `--decide-mode`+ /// wiring can construct the same thing.+ #[cfg(feature = "decide-local")]+ pub fn local(model_dir: PathBuf) -> Self {+ Self {+ local: Some(LocalTier {+ handle: xerj_ai::decide::DecideHandle::new(xerj_ai::decide::DecideConfig {+ model_dir,+ }),+ }),+ }+ }++ /// Resolve the settings from raw strings — pure, and unit-tested.+ /// Returns the settings plus an operator-facing warning when the request+ /// could not be honoured as asked (unknown mode, missing directory,+ /// feature not compiled in). A warning, never a panic: a boot that+ /// dies inside state construction hides the message that explains it.+ pub fn resolve(mode: &str, model_dir: Option<&str>) -> (Self, Option<String>) {+ let mode = mode.trim().to_ascii_lowercase();+ match mode.as_str() {+ "" | "history" => (Self::history_only(), None),+ "local" => Self::resolve_local(model_dir),+ other => (+ Self::history_only(),+ Some(format!(+ "XERJ_DECIDE_MODE={other:?} is not a decide mode; use history or local"+ )),+ ),+ }+ }++ #[cfg_attr(not(feature = "decide-local"), allow(unused_variables))]+ fn resolve_local(model_dir: Option<&str>) -> (Self, Option<String>) {+ #[cfg(feature = "decide-local")]+ {+ match model_dir.map(str::trim).filter(|d| !d.is_empty()) {+ Some(dir) => {+ let path = PathBuf::from(dir);+ if path.is_dir() {+ (Self::local(path), None)+ } else {+ // Arm it anyway: the first request then fails loudly+ // naming the directory, which is the honest failure+ // for a mode the operator explicitly asked for.+ (+ Self::local(path),+ Some(format!(+ "XERJ_DECIDE_MODEL_DIR={dir:?} is not a directory; the \+ local decide tier is armed and its first request will \+ name this path until the model directory is in place"+ )),+ )+ }+ }+ None => (+ Self::history_only(),+ Some(+ "XERJ_DECIDE_MODE=local needs XERJ_DECIDE_MODEL_DIR naming the \+ directory holding config.json, tokenizer.json and \+ model.safetensors; staying on the history vote"+ .to_string(),+ ),+ ),+ }+ }+ #[cfg(not(feature = "decide-local"))]+ {+ (+ Self::history_only(),+ Some(+ "XERJ_DECIDE_MODE=local was requested but this binary was built \+ without the decide-local feature; rebuild with \+ `cargo build --release -p xerj-server --features decide-local`"+ .to_string(),+ ),+ )+ }+ }++ /// Read [`Self::resolve`]'s inputs from the environment and log any+ /// warning. Read exactly once, at [`AppState`] construction — the same+ /// resolve-once discipline as `state.rerank`, so request paths never+ /// race on process-wide env state.+ pub fn from_env() -> Self {+ let mode = std::env::var("XERJ_DECIDE_MODE").unwrap_or_default();+ let dir = std::env::var("XERJ_DECIDE_MODEL_DIR").ok();+ let (settings, warning) = Self::resolve(&mode, dir.as_deref());+ if let Some(warning) = warning {+ tracing::error!("{warning}");+ }+ settings+ }++ /// Whether the local tier can answer (compiled in, enabled, model not+ /// yet necessarily loaded — the load is lazy and its failure surfaces on+ /// the request that triggered it).+ pub fn local_available(&self) -> bool {+ #[cfg(feature = "decide-local")]+ {+ self.local.is_some()+ }+ #[cfg(not(feature = "decide-local"))]+ {+ false+ }+ }++ /// The armed local tier, cloned, when compiled in and enabled. `None`+ /// otherwise — including when the feature is off, so a call site needs no+ /// cfg of its own to ask "is there a local tier on this node?" (Only the+ /// code that USES the tier is feature-gated.)+ #[cfg(feature = "decide-local")]+ pub(crate) fn local_tier(&self) -> Option<LocalTier> {+ self.local.clone()+ }++ #[cfg(not(feature = "decide-local"))]+ pub(crate) fn local_tier(&self) -> Option<std::convert::Infallible> {+ None+ }+}++#[cfg(feature = "decide-local")]+impl LocalTier {+ /// The configured model directory, surfaced in error bodies.+ pub(crate) fn model_dir(&self) -> &Path {+ self.handle.model_dir()+ }++ /// Score one request per question. The head loads lazily on first use,+ /// and the forward pass runs off the async executor+ /// ([`xerj_ai::decide`]).+ pub(crate) async fn score(+ &self,+ requests: Vec<xerj_ai::decide::ScoreRequest>,+ ) -> anyhow::Result<Vec<Vec<f32>>> {+ self.handle.score(requests).await+ }+}++/// The candidate labels one question is judged against, in order — the local+/// head's label vocabulary for that question. Pure, and always compiled: it+/// is the shared definition of what "an answer" is for each kind, used by the+/// tier check above and the local scoring pass below.+fn labels_for(question: &Question, cfg: &DecisionsConfig) -> Vec<String> {+ match &question.kind {+ // A noul is scored as two competing statements — the positive label+ // and its negation — so the answer is a comparison, never one+ // unopposed score. `hypothesis("not spam")` reads exactly+ // `negation_hypothesis("spam")`.+ Kind::Noul => vec![+ cfg.positive_label.clone(),+ format!("not {}", cfg.positive_label),+ ],+ Kind::Choice { options } => options.clone(),+ }+}+// ─────────────────────────────────────────────────────────────────────────────// POST /v1/systemone// ─────────────────────────────────────────────────────────────────────────────@@ -89,7 +382,8 @@ pub async fn systemone() -> axum::response::Response {let started = Instant::now();let cfg = state.config.decisions.clone();- if cfg.index.is_empty() {+ let local_enabled = state.decide.local_available();+ if cfg.index.is_empty() && !local_enabled {return not_configured();}@@ -114,109 +408,263 @@ pub async fn systemone(}}- // One vote per question. Collected first so a no-support question fails- // the whole request — the wire has no per-question error field, and a- // half-answered judgement history would look like a ranking.+ // One ladder resolution per question. Unsupported questions are+ // collected first so a no-support question still fails the whole+ // request when no tier can answer it — the wire has no per-question+ // error field, and a half-answered judgement history would look like a+ // ranking.let mut answers = serde_json::Map::new();let mut evidence = serde_json::Map::new();let mut unsupported: Vec<String> = Vec::new();- for (id, question) in &parsed {- let neighbours = match vote_neighbours(&state, &cfg, &question.vote_text).await {- Ok(n) => n,- Err(resp) => return resp, // index missing / search failure: surfaced, not guessed+ // (index into `parsed`, the question's candidate labels). The labels are+ // resolved per kind here so the local scoring pass below never re-parses+ // the question.+ let mut local_needed: Vec<(usize, Vec<String>)> = Vec::new();+ for (i, (id, question)) in parsed.iter().enumerate() {+ let support = if cfg.index.is_empty() {+ Err(HistorySupport::NotConfigured)+ } else {+ vote_neighbours(&state, &cfg, &question.vote_text).await};- let labelled: Vec<(f64, &str)> = neighbours- .iter()- .map(|(w, label, _)| (*w, label.as_str()))- .collect();- if labelled.is_empty() {- unsupported.push(id.clone());- continue;- }- let total: f64 = labelled.iter().map(|(w, _)| *w).sum();- let mut weight_by_label: BTreeMap<&str, f64> = BTreeMap::new();- for (w, label) in &labelled {- *weight_by_label.entry(label).or_insert(0.0) += *w;- }- let share = |label: &str| weight_by_label.get(label).copied().unwrap_or(0.0) / total;- match &question.kind {- Kind::Noul => {- // Exactly the documented fields — clients parse answers- // strictly and break on extras.- answers.insert(- id.clone(),- json!({ "type": "noul", "noul": round6(share(&cfg.positive_label)) }),- );- }- Kind::Choice { options } => {- let criteria_total: f64 = options+ match support {+ Ok(neighbours) => {+ let labelled: Vec<(f64, &str)> = neighbours.iter()- .map(|o| weight_by_label.get(o.as_str()).copied().unwrap_or(0.0))- .sum();- if criteria_total <= 0.0 {- unsupported.push(id.clone());+ .map(|(w, label, _)| (*w, label.as_str()))+ .collect();+ // A choice also needs weight on at least one of ITS options;+ // neighbours that share no label with the criteria cannot+ // answer the question asked.+ let criteria_ok = match &question.kind {+ Kind::Noul => true,+ Kind::Choice { options } => options.iter().any(|o| {+ labelled+ .iter()+ .any(|(w, label)| *label == o.as_str() && *w > 0.0)+ }),+ };+ if labelled.is_empty() || !criteria_ok {+ // Tier 2: the local head answers what the history+ // cannot; without it the documented errors stand.+ if resolve_tier(&HistorySupport::NoLabelledNeighbour, local_enabled).is_some() {+ local_needed.push((i, labels_for(question, &cfg)));+ } else {+ unsupported.push(id.clone());+ }continue;}- let mut probabilities = serde_json::Map::new();- for option in options {- probabilities.insert(- option.clone(),- json!(round6(- weight_by_label.get(option.as_str()).copied().unwrap_or(0.0) / total- )),- );+ let total: f64 = labelled.iter().map(|(w, _)| *w).sum();+ let mut weight_by_label: BTreeMap<&str, f64> = BTreeMap::new();+ for (w, label) in &labelled {+ *weight_by_label.entry(label).or_insert(0.0) += *w;+ }+ let share =+ |label: &str| weight_by_label.get(label).copied().unwrap_or(0.0) / total;+ match &question.kind {+ Kind::Noul => {+ // Exactly the documented fields — clients parse answers+ // strictly and break on extras.+ answers.insert(+ id.clone(),+ json!({ "type": "noul", "noul": round6(share(&cfg.positive_label)) }),+ );+ }+ Kind::Choice { options } => {+ let mut probabilities = serde_json::Map::new();+ for option in options {+ probabilities.insert(+ option.clone(),+ json!(round6(+ weight_by_label.get(option.as_str()).copied().unwrap_or(0.0)+ / total+ )),+ );+ }+ let (winner, _) = options+ .iter()+ .map(|o| (o, weight_by_label.get(o.as_str()).copied().unwrap_or(0.0)))+ .max_by(|(a, aw), (b, bw)| aw.partial_cmp(bw).unwrap().then(a.cmp(b)))+ .expect("non-empty options");+ answers.insert(+ id.clone(),+ json!({+ "type": "choice",+ "choice": winner,+ "confidence": round6(weight_by_label.get(winner.as_str()).copied().unwrap_or(0.0) / total),+ "probabilities": Value::Object(probabilities),+ }),+ );+ }}- let (winner, _) = options+ let (best_label, best_weight) = weight_by_label.iter()- .map(|o| (o, weight_by_label.get(o.as_str()).copied().unwrap_or(0.0)))- .max_by(|(a, aw), (b, bw)| aw.partial_cmp(bw).unwrap().then(a.cmp(b)))- .expect("non-empty options");- answers.insert(+ .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())+ .expect("non-empty");+ evidence.insert(id.clone(),json!({- "type": "choice",- "choice": winner,- "confidence": round6(weight_by_label.get(winner.as_str()).copied().unwrap_or(0.0) / total),- "probabilities": Value::Object(probabilities),+ "tier": "history",+ "label": best_label,+ "support": round6(best_weight / total),+ "neighbours": labelled.len(),+ "found": neighbours.len(),}),);}+ Err(failure) => {+ match resolve_tier(&failure, local_enabled) {+ Some(DecideTier::Local) => {+ local_needed.push((i, labels_for(question, &cfg)));+ }+ _ => {+ // Unusable is surfaced as the index error it is;+ // NotConfigured cannot occur (guarded above).+ let HistorySupport::Unusable(cause) = failure else {+ unreachable!("NotConfigured is guarded at the top of the handler");+ };+ return index_error(&cfg.index, &cause);+ }+ }+ }}- let (best_label, best_weight) = weight_by_label- .iter()- .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())- .expect("non-empty");- evidence.insert(- id.clone(),- json!({- "label": best_label,- "support": round6(best_weight / total),- "neighbours": labelled.len(),- "found": neighbours.len(),- }),- );}if !unsupported.is_empty() {return no_support(&unsupported, &cfg);}+ // Tier 2: score every local-bound question in one batched pass. A model+ // that cannot load is an honest failure — never a fabricated answer and+ // never a silent fallthrough to the errors the operator switched away+ // from.+ #[cfg_attr(not(feature = "decide-local"), allow(unused_mut))]+ let mut local_answered = 0usize;+ #[cfg(feature = "decide-local")]+ if !local_needed.is_empty() {+ let Some(local) = state.decide.local_tier() else {+ unreachable!("local_needed is only populated when the local tier is armed");+ };+ let requests: Vec<xerj_ai::decide::ScoreRequest> = local_needed+ .iter()+ .map(|(i, labels)| {+ let question = &parsed[*i].1;+ xerj_ai::decide::ScoreRequest {+ premise: question.vote_text.clone(),+ hypotheses: labels+ .iter()+ .map(|l| xerj_ai::decide::hypothesis(l))+ .collect(),+ }+ })+ .collect();+ let scores = match local.score(requests).await {+ Ok(scores) => scores,+ Err(e) => return local_unavailable(&e, local.model_dir()),+ };+ for ((i, labels), scores) in local_needed.iter().zip(scores) {+ let (id, question) = &parsed[*i];+ let mut by_label: serde_json::Map<String, Value> = serde_json::Map::new();+ for (label, score) in labels.iter().zip(&scores) {+ by_label.insert(label.clone(), json!(round6(*score as f64)));+ }+ match &question.kind {+ Kind::Noul => {+ // The positive label is `labels[0]`; its negation is+ // `labels[1]`. The pair sums to 1, so the positive's+ // share is the noul.+ answers.insert(+ id.clone(),+ json!({ "type": "noul", "noul": round6(scores[0] as f64) }),+ );+ }+ Kind::Choice { options } => {+ // `labels_for` made labels == options, in order, so the+ // per-option score is a direct zip.+ let score_of = |option: &str| {+ scores[options+ .iter()+ .position(|o| o == option)+ .expect("every option is a scored label")]+ };+ let winner = options+ .iter()+ .max_by(|a, b| {+ score_of(a)+ .partial_cmp(&score_of(b))+ .unwrap()+ .then(a.cmp(b))+ })+ .expect("non-empty options");+ let mut probabilities = serde_json::Map::new();+ for option in options {+ probabilities+ .insert(option.clone(), json!(round6(score_of(option) as f64)));+ }+ answers.insert(+ id.clone(),+ json!({+ "type": "choice",+ "choice": winner,+ "confidence": round6(score_of(winner) as f64),+ "probabilities": Value::Object(probabilities),+ }),+ );+ }+ }+ let (best_label, best_score) = labels+ .iter()+ .zip(&scores)+ .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())+ .expect("labels are non-empty");+ evidence.insert(+ id.clone(),+ json!({+ "tier": "local",+ "model": LOCAL_MODEL_ID,+ "label": best_label,+ "support": round6(*best_score as f64),+ "hypotheses": Value::Object(by_label),+ }),+ );+ local_answered += 1;+ }+ }++ let index_echo = if cfg.index.is_empty() {+ LOCAL_MODEL_ID.to_string()+ } else {+ cfg.index.clone()+ };state.metrics.record_query(- &cfg.index,- "systemone_vote",+ &index_echo,+ if local_answered > 0 {+ "systemone_local"+ } else {+ "systemone_vote"+ },started.elapsed().as_secs_f64(),);+ let mut decisions = serde_json::Map::new();+ decisions.insert("index".into(), json!(index_echo));+ decisions.insert("k".into(), json!(cfg.k));+ decisions.insert("model".into(), json!(MODEL_ID));+ decisions.insert(+ "requested_model".into(),+ json!(body.get("model").and_then(Value::as_str).unwrap_or("")),+ );+ decisions.insert("evidence".into(), Value::Object(evidence));+ decisions.insert(+ "took_ms".into(),+ json!(started.elapsed().as_millis() as u64),+ );+ if local_answered > 0 {+ decisions.insert("local_model".into(), json!(LOCAL_MODEL_ID));+ decisions.insert("local_answered".into(), json!(local_answered));+ }Json(json!({"model": MODEL_ID,"answers": Value::Object(answers),"usage": { "input_tokens": 0, "output_tokens": 0 },- "decisions": {- "index": cfg.index,- "k": cfg.k,- "model": MODEL_ID,- "requested_model": body.get("model").and_then(Value::as_str).unwrap_or(""),- "evidence": Value::Object(evidence),- "took_ms": started.elapsed().as_millis() as u64,- }+ "decisions": Value::Object(decisions),})).into_response()}@@ -225,37 +673,56 @@ pub async fn systemone(// GET /v1/models// ─────────────────────────────────────────────────────────────────────────────-/// The official SDKs list models before calling. One truthful entry.+/// The official SDKs list models before calling. Truthful entries only: the+/// vote, and — when the local tier is armed — the local head, each under its+/// own never-a-Jev-name id.pub async fn models(State(state): State<AppState>) -> axum::response::Response {let configured = !state.config.decisions.index.is_empty();- Json(json!({- "models": [{- "name": MODEL_ID,- "description": if configured {- "Weighted nearest-neighbour vote over the configured decisions index — local, no egress"- } else {- "Weighted nearest-neighbour vote over a labelled-history index (no [decisions] index configured: /v1/systemone answers 503)"- },- "release_date": "2026-09-20",- }]- }))- .into_response()+ let local = state.decide.local_available();+ let vote_description = if configured {+ "Weighted nearest-neighbour vote over the configured decisions index — local, no egress"+ } else if local {+ "Weighted nearest-neighbour vote over a labelled-history index (no [decisions] index \+ configured: /v1/systemone answers from the local decision head)"+ } else {+ "Weighted nearest-neighbour vote over a labelled-history index (no [decisions] index \+ configured: /v1/systemone answers 503)"+ };+ let mut models = vec![json!({+ "name": MODEL_ID,+ "description": vote_description,+ "release_date": "2026-09-20",+ })];+ if local {+ models.push(json!({+ "name": LOCAL_MODEL_ID,+ "description": "Local zero-shot decision head (ModernBERT-class, candle) — answers \+ noul and choice with no history index; local files only, no egress",+ "release_date": "2026-09-29",+ }));+ }+ Json(json!({ "models": models })).into_response()}// ─────────────────────────────────────────────────────────────────────────────// POST /_decide// ─────────────────────────────────────────────────────────────────────────────-/// The audit surface: the same vote, naming its index per request, returning-/// the neighbours it judged by, and abstaining instead of erroring.+/// The audit surface: the same ladder as `/v1/systemone`, naming its index+/// per request, returning the neighbours it judged by, and abstaining instead+/// of erroring. The local tier is the one difference in kind: with it armed,+/// `index` becomes optional — a caller with no labelled history at all still+/// gets an answer, tier-tagged.pub async fn decide(State(state): State<AppState>,Json(body): Json<Value>,) -> axum::response::Response {let started = Instant::now();let defaults = &state.config.decisions;+ let local = state.decide.local_tier();let index = match body.get("index").and_then(Value::as_str) {Some(i) if !i.trim().is_empty() => i.to_string(),+ _ if local.is_some() => String::new(),_ => return unprocessable("`index` must name the judgement-history index"),};let question = match body.get("question").and_then(Value::as_str) {@@ -281,11 +748,38 @@ pub async fn decide(cfg.label_field = defaults.label_field.clone();cfg.text_field = defaults.text_field.clone();- let neighbours =- match vote_neighbours(&state, &cfg, &clip(&question, MAX_VOTE_TEXT_CHARS)).await {- Ok(n) => n,- Err(resp) => return resp,- };+ let neighbours = if cfg.index.is_empty() {+ Err(HistorySupport::NotConfigured)+ } else {+ vote_neighbours(&state, &cfg, &clip(&question, MAX_VOTE_TEXT_CHARS)).await+ };+ // The ladder, /_decide-shaped: an empty or unreachable history hands the+ // question to the local head; with no tier able to answer, the audit+ // surface does what it always did — abstain on zero support, error on an+ // unusable index.+ let support = match &neighbours {+ Ok(n) if n.is_empty() => HistorySupport::NoLabelledNeighbour,+ Ok(_) => HistorySupport::Supported,+ Err(failure) => failure.clone(),+ };+ if resolve_tier(&support, local.is_some()) == Some(DecideTier::Local) {+ #[cfg(feature = "decide-local")]+ {+ let Some(local) = local.as_ref() else {+ unreachable!("resolve_tier names Local only when the tier is armed");+ };+ return decide_local(&state, local, &question, &positive, &index, k, started).await;+ }+ }+ let neighbours = match neighbours {+ Ok(n) => n,+ Err(failure) => {+ let HistorySupport::Unusable(cause) = failure else {+ unreachable!("NotConfigured implies the local tier, which answered above")+ };+ return index_error(&cfg.index, &cause);+ }+ };let total: f64 = neighbours.iter().map(|(w, _, _)| *w).sum();let mut weight_by_label: BTreeMap<String, f64> = BTreeMap::new();for (w, label, _) in &neighbours {@@ -340,6 +834,7 @@ pub async fn decide("confidence": round6(confidence),"abstain": abstain,"neighbours": neighbour_list,+ "tier": "history","took_ms": started.elapsed().as_millis() as u64,});if let Some(r) = reason {@@ -348,6 +843,66 @@ pub async fn decide(Json(resp).into_response()}+/// The local tier's `/_decide` answer: the head's probabilities over the+/// positive label and its negation, tier-tagged, abstaining by the same+/// `decisions.min_confidence` rule the history vote uses. `neighbours` is+/// empty — having none is exactly what tier 2 means here.+#[cfg(feature = "decide-local")]+async fn decide_local(+ state: &AppState,+ local: &LocalTier,+ question: &str,+ positive: &str,+ index: &str,+ k: usize,+ started: Instant,+) -> axum::response::Response {+ let defaults = &state.config.decisions;+ let labels = [positive.to_string(), format!("not {positive}")];+ let requests = vec![xerj_ai::decide::ScoreRequest {+ premise: clip(question, MAX_VOTE_TEXT_CHARS),+ hypotheses: labels+ .iter()+ .map(|l| xerj_ai::decide::hypothesis(l))+ .collect(),+ }];+ let scores = match local.score(requests).await {+ Ok(scores) => scores,+ Err(e) => return local_unavailable(&e, local.model_dir()),+ };+ let scores = &scores[0];+ let (label, confidence) = if scores[0] >= scores[1] {+ (labels[0].clone(), scores[0] as f64)+ } else {+ (labels[1].clone(), scores[1] as f64)+ };+ let abstain = confidence < defaults.min_confidence;+ state.metrics.record_query(+ LOCAL_MODEL_ID,+ "decide_local",+ started.elapsed().as_secs_f64(),+ );+ let mut resp = json!({+ "index": index,+ "k": k,+ "positive_label": positive,+ "label": label,+ "confidence": round6(confidence),+ "abstain": abstain,+ "neighbours": [],+ "tier": "local",+ "model": LOCAL_MODEL_ID,+ "took_ms": started.elapsed().as_millis() as u64,+ });+ if abstain {+ resp["reason"] = json!(format!(+ "confidence {:.3} below decisions.min_confidence {:.3}",+ confidence, defaults.min_confidence+ ));+ }+ Json(resp).into_response()+}+// ─────────────────────────────────────────────────────────────────────────────// The vote// ─────────────────────────────────────────────────────────────────────────────@@ -486,15 +1041,17 @@ fn parse_question(id: &str, q: &Value, state_val: &Value) -> Result<Question, St}/// One weighted-neighbour record: (weight, label, hit). Unlabelled hits are-/// dropped here — they carry no vote.+/// dropped here — they carry no vote. An index that cannot be reached at all+/// is [`HistorySupport::Unusable`] carrying the cause, so the decide ladder+/// can offer the question to the next tier instead of pre-baking the error.async fn vote_neighbours(state: &AppState,cfg: &DecisionsConfig,text: &str,-) -> Result<Vec<(f64, String, xerj_query::executor::Hit)>, axum::response::Response> {+) -> Result<Vec<(f64, String, xerj_query::executor::Hit)>, HistorySupport> {let idx = match state.engine.get_index(&cfg.index) {Ok(i) => i,- Err(e) => return Err(index_error(&cfg.index, &e.to_string())),+ Err(e) => return Err(HistorySupport::Unusable(e.to_string())),};// The text field is configuration, not a literal — build the match by// hand so the field name is data, not syntax.@@ -508,14 +1065,14 @@ async fn vote_neighbours(let search_req = match parse_request(&query_body) {Ok(r) => r,Err(e) => {- return Err(unprocessable(&format!(+ return Err(HistorySupport::Unusable(format!("internal query would not parse: {e}")))}};let result = match idx.search(&search_req).await {Ok(r) => r,- Err(e) => return Err(index_error(&cfg.index, &e.to_string())),+ Err(e) => return Err(HistorySupport::Unusable(e.to_string())),};let mut out = Vec::with_capacity(result.hits.len());for (i, hit) in result.hits.into_iter().enumerate() {@@ -647,6 +1204,25 @@ fn index_error(index: &str, cause: &str) -> axum::response::Response {)}+/// The local tier could not answer — the model directory is wrong or the+/// weights will not load. 503, naming the directory and the env var, because+/// the tier was explicitly armed: every request fails loudly until the+/// operator fixes it, never with a fabricated probability and never by+/// silently falling back to the errors the operator switched away from.+#[cfg(feature = "decide-local")]+fn local_unavailable(err: &anyhow::Error, model_dir: &Path) -> axum::response::Response {+ error_body(+ 503,+ "local_decide_unavailable",+ format!(+ "the local decision tier could not answer: {err:#}. The model directory is {} \+ (set by XERJ_DECIDE_MODEL_DIR) and must hold config.json, tokenizer.json and \+ model.safetensors",+ model_dir.display()+ ),+ )+}+fn no_support(ids: &[String], cfg: &DecisionsConfig) -> axum::response::Response {error_body(422,@@ -665,3 +1241,133 @@ fn no_support(ids: &[String], cfg: &DecisionsConfig) -> axum::response::Response),)}++// ─────────────────────────────────────────────────────────────────────────────+// Tests — the ladder's order is the contract, so it is unit-tested directly+// ─────────────────────────────────────────────────────────────────────────────++#[cfg(test)]+mod tests {+ use super::*;++ fn no_support_classes() -> Vec<HistorySupport> {+ vec![+ HistorySupport::NotConfigured,+ HistorySupport::Unusable("index gone".into()),+ HistorySupport::NoLabelledNeighbour,+ ]+ }++ /// Tier 1 wins wherever it has support — even with the local head armed,+ /// it never overrides measured evidence. Every no-support class falls to+ /// the local head when armed, and to nothing (the documented errors) when+ /// not. The hosted tier is reserved: it never resolves.+ #[test]+ fn tier_order_is_history_then_local_then_the_documented_errors() {+ for support in no_support_classes() {+ assert_eq!(+ resolve_tier(&support, false),+ None,+ "{support:?}: no local tier → the documented error stands"+ );+ }+ assert_eq!(+ resolve_tier(&HistorySupport::Supported, false),+ Some(DecideTier::History)+ );+ // History wins even with the local tier armed.+ assert_eq!(+ resolve_tier(&HistorySupport::Supported, true),+ Some(DecideTier::History)+ );+ for support in no_support_classes() {+ assert_eq!(+ resolve_tier(&support, true),+ Some(DecideTier::Local),+ "{support:?}: the local head answers what history cannot"+ );+ }+ }++ #[test]+ fn resolve_defaults_to_history_only_without_a_warning() {+ for mode in ["", " ", "history", "History"] {+ let (settings, warning) = DecideSettings::resolve(mode, None);+ assert!(+ !settings.local_available(),+ "{mode:?}: default node is history-only"+ );+ assert!(warning.is_none(), "{mode:?}: {warning:?}");+ }+ }++ #[test]+ fn an_unknown_mode_stays_on_history_and_names_the_valid_ones() {+ let (settings, warning) = DecideSettings::resolve("hosted", None);+ assert!(!settings.local_available());+ let warning = warning.expect("warning");+ assert!(warning.contains("hosted"), "{warning}");+ assert!(warning.contains("local"), "{warning}");+ assert!(warning.contains("history"), "{warning}");+ }++ #[cfg(feature = "decide-local")]+ #[test]+ fn local_mode_arms_only_with_a_model_dir() {+ // The mode without a directory: history stays, the warning names the+ // env var and the files it expects.+ let (settings, warning) = DecideSettings::resolve("local", None);+ assert!(!settings.local_available(), "no dir → not armed");+ let warning = warning.expect("warning");+ assert!(warning.contains("XERJ_DECIDE_MODEL_DIR"), "{warning}");+ assert!(warning.contains("model.safetensors"), "{warning}");++ // A real directory: armed, silent.+ let dir = tempfile::tempdir().expect("tempdir");+ let (settings, warning) = DecideSettings::resolve("local", dir.path().to_str());+ assert!(settings.local_available(), "dir present → armed");+ assert!(warning.is_none(), "{warning:?}");++ // A missing directory: still armed — the operator asked for the tier,+ // so its first request names the path rather than the node quietly+ // pretending to be history-only.+ let (settings, warning) =+ DecideSettings::resolve("local", Some("/nonexistent/xerj-decide"));+ assert!(+ settings.local_available(),+ "armed even when the dir is absent"+ );+ let warning = warning.expect("warning");+ assert!(warning.contains("/nonexistent/xerj-decide"), "{warning}");+ }++ #[cfg(not(feature = "decide-local"))]+ #[test]+ fn local_mode_without_the_feature_warns_to_rebuild() {+ let (settings, warning) = DecideSettings::resolve("local", Some("/any/dir"));+ assert!(!settings.local_available());+ let warning = warning.expect("warning");+ assert!(warning.contains("decide-local"), "{warning}");+ }++ #[test]+ fn labels_for_gives_a_noul_two_sides_and_a_choice_its_options() {+ let cfg = DecisionsConfig::default();+ let noul = Question {+ vote_text: "payload".into(),+ kind: Kind::Noul,+ };+ assert_eq!(+ labels_for(&noul, &cfg),+ vec!["true".to_string(), "not true".to_string()],+ "a noul is a comparison, never one unopposed score"+ );+ let choice = Question {+ vote_text: "payload".into(),+ kind: Kind::Choice {+ options: vec!["billing".into(), "tech".into()],+ },+ };+ assert_eq!(labels_for(&choice, &cfg), vec!["billing", "tech"]);+ }+}diff --git a/engine/crates/xerj-api/tests/systemone_local_decide.rs b/engine/crates/xerj-api/tests/systemone_local_decide.rsnew file mode 100644index 000000000..bd617b3e1--- /dev/null+++ b/engine/crates/xerj-api/tests/systemone_local_decide.rs@@ -0,0 +1,388 @@+//! End-to-end checks for tier 2 of the decide ladder — the local zero-shot+//! head answering what the history vote cannot (issue #1057).+//!+//! Every test here arms a node with a TINY UNTRAINED ModernBERT-class fixture+//! (`xerj_ai::decide::testing::write_fixture`). The fixture proves the+//! loading/scoring path end to end; its probabilities are reproducible+//! arithmetic, NOT judgement quality — nothing here measures accuracy (that+//! is `benchmarks/decisions-as-retrieval` against the real trained model,+//! issue #1064). What IS under test:+//!+//! - the 503/422 → 200 transition: a node with no `[decisions] index` at all,+//! and a question whose payload retrieves no labelled neighbour, answer+//! from the local head instead of erroring;+//! - the tier ORDER: where the history vote has support it still wins,+//! per-question, in the same request;+//! - the model echo: `xerj-decide-local-1` / `xerj-history-vote-1`, never a+//! Jev name;+//! - honest failure: a local tier armed at a missing model directory fails+//! loudly naming the path, never with a fabricated probability.+//!+//! Compiled only with the `decide-local` feature — the default build's+//! contract is `systemone_http.rs`'s business.++#![cfg(feature = "decide-local")]++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::{json, Value};+use tower::ServiceExt;++use xerj_api::state::AppState;+use xerj_api::systemone_api::{DecideSettings, LOCAL_MODEL_ID, MODEL_ID};++struct Node {+ native: axum::Router,+ app: axum::Router,+ _dir: tempfile::TempDir,+ _model_dir: tempfile::TempDir,+}++/// A node with the local tier armed at a fresh fixture, and `[decisions]+/// index` set to `index` ("" for none — the no-history node this feature+/// exists for).+async fn local_node(index: &str) -> Node {+ let dir = tempfile::tempdir().expect("tempdir");+ let model_dir = tempfile::tempdir().expect("model tempdir");+ xerj_ai::decide::testing::write_fixture(model_dir.path())+ .unwrap_or_else(|e| panic!("write decide fixture: {e:#}"));++ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ config.storage.wal_sync = xerj_common::config::WalSync::Async;+ config.decisions.index = index.to_string();+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");+ let mut state = AppState::new(config, engine, metrics);+ // The injection seam, not the environment: replacing the field keeps+ // parallel tests from racing on process-wide env state.+ state.decide = std::sync::Arc::new(DecideSettings::local(model_dir.path().to_path_buf()));+ Node {+ native: xerj_api::router::build_native_router(state.clone()),+ app: xerj_api::router::build_es_compat_router(state),+ _dir: dir,+ _model_dir: model_dir,+ }+}++impl Node {+ async fn call(+ &self,+ router: &axum::Router,+ method: &str,+ path: &str,+ body: Value,+ ) -> (StatusCode, Value) {+ let response = router+ .clone()+ .oneshot(+ Request::builder()+ .method(method)+ .uri(path)+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .expect("request"),+ )+ .await+ .expect("response");+ let status = response.status();+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .expect("body");+ (+ status,+ serde_json::from_str(&String::from_utf8_lossy(&bytes)).unwrap_or(Value::Null),+ )+ }++ async fn systemone(&self, body: Value) -> (StatusCode, Value) {+ self.call(&self.native.clone(), "POST", "/v1/systemone", body)+ .await+ }+ async fn decide(&self, body: Value) -> (StatusCode, Value) {+ self.call(&self.app.clone(), "POST", "/_decide", body).await+ }+ async fn put_doc(&self, index: &str, id: &str, text: &str, label: &str) {+ let (st, b) = self+ .call(+ &self.app.clone(),+ "PUT",+ &format!("/{index}/_doc/{id}"),+ json!({"text": text, "label": label}),+ )+ .await;+ assert!(st.is_success(), "index {index}/{id}: {st} {b}");+ }+ async fn create_index(&self, index: &str) {+ let (st, b) = self+ .call(+ &self.app.clone(),+ "PUT",+ &format!("/{index}"),+ json!({"mappings": {"properties": {+ "text": {"type": "text"},+ "label": {"type": "keyword"}+ }}}),+ )+ .await;+ assert!(st.is_success(), "create {index}: {st} {b}");+ }+ async fn refresh(&self, index: &str) {+ let (st, b) = self+ .call(+ &self.app.clone(),+ "POST",+ &format!("/{index}/_refresh"),+ json!({}),+ )+ .await;+ assert!(st.is_success(), "refresh {index}: {st} {b}");+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// The 503 → 200 transition: no [decisions] index at all+// ─────────────────────────────────────────────────────────────────────────────++/// The node this tier exists for: no labelled history anywhere, and /v1/systemone+/// still answers both question kinds — 200 where the same request used to 503,+/// with probabilities that are real numbers in range, and a model echo that is+/// the local head's own id, never the Jev name the client asked for.+#[tokio::test]+async fn no_history_node_answers_noul_and_choice_from_the_local_head() {+ let node = local_node("").await;+ let (st, r) = node+ .systemone(json!({+ "state": {+ "documents": {+ "doc_0": "urgent prize claim call now",+ "doc_1": "hi it is me again about dinner"+ }+ },+ "model": "jev-1.13.0",+ "questions": {+ "d0": {"type": "noul", "instructions": "Is `documents.doc_0` spam?"},+ "d1": {"type": "noul", "instructions": "Is `documents.doc_1` spam?"},+ "c0": {"type": "choice", "instructions": "Route `documents.doc_0`.",+ "criteria": {"billing": "", "tech": "", "spam": ""}}+ }+ }))+ .await;+ assert_eq!(st, StatusCode::OK, "{r}");+ assert_eq!(r["model"], MODEL_ID, "wire echo stays the vote id: {r}");+ assert_ne!(r["model"], "jev-1.13.0");+ assert_eq!(r["decisions"]["local_model"], LOCAL_MODEL_ID, "{r}");+ for id in ["d0", "d1"] {+ let noul = r["answers"][id]["noul"]+ .as_f64()+ .unwrap_or_else(|| panic!("{id} noul is a number: {r}"));+ assert!((0.0..=1.0).contains(&noul), "{id} noul {noul}: {r}");+ }+ let probs = r["answers"]["c0"]["probabilities"]+ .as_object()+ .expect("choice probabilities: {r}");+ assert_eq!(probs.len(), 3, "{r}");+ let sum: f64 = probs.values().filter_map(|v| v.as_f64()).sum();+ assert!((sum - 1.0).abs() < 1e-3, "choice probs sum to {sum}: {r}");+ assert!(+ r["answers"]["c0"]["choice"]+ .as_str()+ .is_some_and(|c| probs.contains_key(c)),+ "winner is one of the options: {r}"+ );+ // Every answer says which tier produced it.+ for id in ["d0", "d1", "c0"] {+ assert_eq!(r["decisions"]["evidence"][id]["tier"], "local", "{r}");+ assert_eq!(+ r["decisions"]["evidence"][id]["model"], LOCAL_MODEL_ID,+ "{r}"+ );+ }+}++/// The local head never rescues request-shape refusals: a question with no+/// payload to classify is still a 422 naming it.+#[tokio::test]+async fn local_mode_does_not_rescue_a_question_with_no_payload() {+ let node = local_node("").await;+ let (st, r) = node+ .systemone(json!({+ "state": {"documents": {}},+ "questions": {+ "d0": {"type": "noul", "instructions": "Is `documents.doc_0` spam?"}+ }+ }))+ .await;+ assert_eq!(st, StatusCode::UNPROCESSABLE_ENTITY, "{r}");+ assert!(+ r["error"]["reason"]+ .as_str()+ .is_some_and(|s| s.contains("`d0`")),+ "{r}"+ );+}++// ─────────────────────────────────────────────────────────────────────────────+// The tier order, in one request+// ─────────────────────────────────────────────────────────────────────────────++/// With a seeded history AND the local tier armed, history answers what it+/// can (refund → noul 1.0 by vote arithmetic, evidence tier "history") and the+/// local head answers what it cannot (a payload with no labelled neighbour) —+/// the same request, 200, per-question evidence.+#[tokio::test]+async fn history_still_wins_where_it_has_support_local_answers_the_rest() {+ let node = local_node("history").await;+ node.create_index("history").await;+ node.put_doc(+ "history",+ "h1",+ "refund refund refund asked for money back",+ "true",+ )+ .await;+ node.put_doc("history", "h2", "refund policy says money back", "true")+ .await;+ node.refresh("history").await;++ let (st, r) = node+ .systemone(json!({+ "state": {+ "documents": {+ "doc_0": "refund asked for money back",+ "doc_1": "zzzqqq nothing like the history"+ }+ },+ "questions": {+ "d0": {"type": "noul", "instructions": "Is `documents.doc_0` about refunds?"},+ "d1": {"type": "noul", "instructions": "Is `documents.doc_1` about refunds?"}+ }+ }))+ .await;+ assert_eq!(st, StatusCode::OK, "mixed support is not an error: {r}");+ // History tier: every neighbour of doc_0 is `true` → noul 1.0, and the+ // evidence shows the vote, not the model.+ assert!(+ (r["answers"]["d0"]["noul"].as_f64().unwrap_or(0.0) - 1.0).abs() < 1e-9,+ "{r}"+ );+ assert_eq!(r["decisions"]["evidence"]["d0"]["tier"], "history", "{r}");+ // Local tier for the question history had no neighbour for.+ assert_eq!(r["decisions"]["evidence"]["d1"]["tier"], "local", "{r}");+ assert_eq!(+ r["decisions"]["evidence"]["d1"]["model"], LOCAL_MODEL_ID,+ "{r}"+ );+ let noul = r["answers"]["d1"]["noul"].as_f64().unwrap_or(-1.0);+ assert!((0.0..=1.0).contains(&noul), "{r}");+}++/// /_decide with no `index` field at all: a 200 tier-tagged local answer where+/// the history-only node 422s. (The audit surface keeps its abstain semantics:+/// the local answer abstains by the same min_confidence rule.)+#[tokio::test]+async fn decide_without_an_index_answers_from_the_local_tier() {+ let node = local_node("").await;+ let (st, r) = node+ .decide(json!({"question": "urgent prize claim call now", "positive_label": "spam"}))+ .await;+ assert_eq!(st, StatusCode::OK, "{r}");+ assert_eq!(r["tier"], "local", "{r}");+ assert_eq!(r["model"], LOCAL_MODEL_ID, "{r}");+ assert_eq!(r["positive_label"], "spam", "{r}");+ let label = r["label"].as_str().expect("label: {r}");+ assert!(+ label == "spam" || label == "not spam",+ "one of the two competing hypotheses: {r}"+ );+ let confidence = r["confidence"].as_f64().expect("confidence: {r}");+ assert!((0.0..=1.0).contains(&confidence), "{r}");+ assert_eq!(+ r["neighbours"].as_array().map(Vec::len).unwrap_or_default(),+ 0,+ "tier 2 has no neighbours — that is what it means: {r}"+ );+}++/// The other half of the /_decide ladder: with an index configured but missing+/// on the node (Unusable), the history-only contract is a 422 — the local tier+/// turns it into a 200 local answer instead.+#[tokio::test]+async fn decide_over_a_missing_index_falls_to_the_local_tier() {+ let node = local_node("history").await;+ // No such index is created; the tier is armed.+ let (st, r) = node+ .decide(json!({"index": "history", "question": "urgent prize claim call now"}))+ .await;+ assert_eq!(st, StatusCode::OK, "{r}");+ assert_eq!(r["tier"], "local", "{r}");+}++// ─────────────────────────────────────────────────────────────────────────────+// Honest failure+// ─────────────────────────────────────────────────────────────────────────────++/// A local tier armed at a directory with no model in it: the request fails+/// loudly, naming the path and the env var — never a fabricated probability+/// and never a silent fallthrough to the error the operator switched away+/// from.+#[tokio::test]+async fn an_armed_tier_with_no_model_fails_loudly_naming_the_directory() {+ let empty_model = tempfile::tempdir().expect("model tempdir");+ let data_dir = tempfile::tempdir().expect("data tempdir");+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = data_dir.path().to_string_lossy().into_owned();+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");+ let mut state = AppState::new(config, engine, metrics);+ state.decide = std::sync::Arc::new(DecideSettings::local(empty_model.path().to_path_buf()));+ let native = xerj_api::router::build_native_router(state.clone());+ let response = native+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/v1/systemone")+ .header("content-type", "application/json")+ .body(Body::from(+ json!({+ "state": "urgent prize claim call now",+ "questions": {"q": {"type": "noul", "instructions": "spam?"}}+ })+ .to_string(),+ ))+ .expect("request"),+ )+ .await+ .expect("response");+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .expect("body");+ let r: Value = serde_json::from_str(&String::from_utf8_lossy(&bytes)).unwrap_or(Value::Null);+ let reason = r["error"]["reason"].as_str().unwrap_or_default();+ assert!(+ reason.contains("config.json") && reason.contains("XERJ_DECIDE_MODEL_DIR"),+ "the error names the missing files and the env var: {r}"+ );+ assert_eq!(r["error"]["type"], "local_decide_unavailable", "{r}");+}++/// /v1/models keeps its discipline: the local head appears under its own+/// never-a-Jev-name id when armed.+#[tokio::test]+async fn models_lists_the_local_head_under_its_own_id() {+ let node = local_node("").await;+ let (st, r) = node+ .call(&node.native.clone(), "GET", "/v1/models", json!({}))+ .await;+ assert!(st.is_success(), "{st} {r}");+ let names: Vec<&str> = r["models"]+ .as_array()+ .expect("models")+ .iter()+ .filter_map(|m| m["name"].as_str())+ .collect();+ assert!(names.contains(&MODEL_ID), "{names:?}");+ assert!(names.contains(&LOCAL_MODEL_ID), "{names:?}");+ assert!(!names.iter().any(|n| n.starts_with("jev")), "{names:?}");+}