Skip to content

armgit / xerj

Public Imported from GitHub
0

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

fix(api,common): escalate low-confidence history votes to local decide tier (#1094)

Christian M. Todief7e7d4a7abb7
diff --git a/engine/crates/xerj-api/src/systemone_api.rs b/engine/crates/xerj-api/src/systemone_api.rs
index 25a2b999b..d35d42c5e 100644
--- a/engine/crates/xerj-api/src/systemone_api.rs
+++ b/engine/crates/xerj-api/src/systemone_api.rs
@@ -186,10 +186,11 @@ pub enum DecideTier {
/// 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)]
+#[derive(Debug, Clone, PartialEq)]
pub(crate) enum HistorySupport {
- /// Labelled neighbours came back.
- Supported,
+ /// Labelled neighbours came back; the `f64` is the winning label's share
+ /// of the total vote weight (`0.0..=1.0`).
+ Supported(f64),
/// No `[decisions] index` is configured at all.
NotConfigured,
/// The configured index does not exist or could not be searched; the
@@ -202,9 +203,25 @@ pub(crate) enum HistorySupport {
/// 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> {
+///
+/// When `local_enabled` is true and a history vote's winning share is strictly
+/// below `escalate_below` (`#1094`), the question escalates to
+/// `DecideTier::Local` so the local head answers and caches its judgement into
+/// the history index. When `local_enabled` is false, a low-share vote still
+/// resolves to `DecideTier::History`.
+pub(crate) fn resolve_tier(
+ support: &HistorySupport,
+ escalate_below: f64,
+ local_enabled: bool,
+) -> Option<DecideTier> {
match support {
- HistorySupport::Supported => Some(DecideTier::History),
+ HistorySupport::Supported(share) => {
+ if local_enabled && *share < escalate_below {
+ Some(DecideTier::Local)
+ } else {
+ Some(DecideTier::History)
+ }
+ }
HistorySupport::NotConfigured
| HistorySupport::Unusable(_)
| HistorySupport::NoLabelledNeighbour => {
@@ -893,7 +910,13 @@ pub async fn systemone(
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() {
+ if resolve_tier(
+ &HistorySupport::NoLabelledNeighbour,
+ cfg.escalate_below,
+ local_enabled,
+ )
+ .is_some()
+ {
local_needed.push((i, labels_for(question, &cfg)));
} else {
unsupported.push(id.clone());
@@ -905,8 +928,28 @@ pub async fn systemone(
for (w, label) in &labelled {
*weight_by_label.entry(label).or_insert(0.0) += *w;
}
+ let (best_label, best_weight) = weight_by_label
+ .iter()
+ .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
+ .expect("non-empty");
let share =
|label: &str| weight_by_label.get(label).copied().unwrap_or(0.0) / total;
+ let winning_share = match &question.kind {
+ Kind::Noul => *best_weight / total,
+ Kind::Choice { options } => options
+ .iter()
+ .map(|o| share(o.as_str()))
+ .fold(0.0_f64, f64::max),
+ };
+ if resolve_tier(
+ &HistorySupport::Supported(winning_share),
+ cfg.escalate_below,
+ local_enabled,
+ ) == Some(DecideTier::Local)
+ {
+ local_needed.push((i, labels_for(question, &cfg)));
+ continue;
+ }
match &question.kind {
Kind::Noul => {
// Exactly the documented fields — clients parse answers
@@ -943,10 +986,6 @@ pub async fn systemone(
);
}
}
- let (best_label, best_weight) = weight_by_label
- .iter()
- .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
- .expect("non-empty");
let mut evidence_value = json!({
"tier": DecideTier::History.as_str(),
"source": DecideTier::History.as_str(),
@@ -969,7 +1008,7 @@ pub async fn systemone(
evidence.insert(id.clone(), evidence_value);
}
Err(failure) => {
- match resolve_tier(&failure, local_enabled) {
+ match resolve_tier(&failure, cfg.escalate_below, local_enabled) {
Some(DecideTier::Local) => {
local_needed.push((i, labels_for(question, &cfg)));
}
@@ -1246,16 +1285,28 @@ pub async fn decide(
} 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(),
+ // The ladder, /_decide-shaped: an empty, unreachable, or below-floor
+ // 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, total, weight_by_label) = match &neighbours {
+ Ok(n) if n.is_empty() => (HistorySupport::NoLabelledNeighbour, 0.0, BTreeMap::new()),
+ Ok(n) => {
+ let total: f64 = n.iter().map(|(w, _, _)| *w).sum();
+ let mut by_label: BTreeMap<String, f64> = BTreeMap::new();
+ for (w, label, _) in n {
+ *by_label.entry(label.to_string()).or_insert(0.0) += *w;
+ }
+ let winning_share = if total > 0.0 {
+ by_label.values().copied().fold(0.0_f64, f64::max) / total
+ } else {
+ 0.0
+ };
+ (HistorySupport::Supported(winning_share), total, by_label)
+ }
+ Err(failure) => (failure.clone(), 0.0, BTreeMap::new()),
};
- if resolve_tier(&support, local.is_some()) == Some(DecideTier::Local) {
+ if resolve_tier(&support, cfg.escalate_below, local.is_some()) == Some(DecideTier::Local) {
#[cfg(feature = "decide-local")]
{
let Some(local) = local.as_ref() else {
@@ -1273,11 +1324,6 @@ pub async fn decide(
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 {
- *weight_by_label.entry(label.to_string()).or_insert(0.0) += *w;
- }
// The calibrated quantity (#1063): the positive label's share — the same
// quantity a noul answers on the wire — NOT the winner's share that
// `confidence` reports. `confidence` keeps its raw meaning and the
@@ -1906,31 +1952,57 @@ mod tests {
]
}
- /// 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.
+ /// Tier 1 wins wherever it has confident support (`share >= escalate_below`).
+ /// When the local head is armed and the history winner's share falls below
+ /// `escalate_below`, the question escalates to tier 2 (`Local`) so the
+ /// flywheel does not freeze once BM25 starts matching split neighbours
+ /// (#1094). Without the local tier armed, low-share history votes stay on
+ /// `History` and answer or abstain as before. 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),
+ resolve_tier(&support, 0.8, false),
None,
"{support:?}: no local tier → the documented error stands"
);
}
assert_eq!(
- resolve_tier(&HistorySupport::Supported, false),
+ resolve_tier(&HistorySupport::Supported(1.0), 0.8, false),
Some(DecideTier::History)
);
- // History wins even with the local tier armed.
+ // Confident history (`share >= escalate_below`) wins even with the local tier armed.
assert_eq!(
- resolve_tier(&HistorySupport::Supported, true),
+ resolve_tier(&HistorySupport::Supported(1.0), 0.8, true),
Some(DecideTier::History)
);
+ assert_eq!(
+ resolve_tier(&HistorySupport::Supported(0.8), 0.8, true),
+ Some(DecideTier::History),
+ "at the floor (`share == escalate_below`) history holds"
+ );
+ // Split / low-share history (`share < escalate_below`) escalates to local
+ // when armed, and stays on history when not (#1094).
+ assert_eq!(
+ resolve_tier(&HistorySupport::Supported(2.0 / 3.0), 0.8, true),
+ Some(DecideTier::Local),
+ "a 2-to-1 split (0.667 < 0.8) escalates to the local head when armed"
+ );
+ assert_eq!(
+ resolve_tier(&HistorySupport::Supported(2.0 / 3.0), 0.8, false),
+ Some(DecideTier::History),
+ "without a local tier, low-share history stays on history"
+ );
+ assert_eq!(
+ resolve_tier(&HistorySupport::Supported(0.5), 0.0, true),
+ Some(DecideTier::History),
+ "escalate_below = 0.0 disables confidence escalation"
+ );
for support in no_support_classes() {
assert_eq!(
- resolve_tier(&support, true),
+ resolve_tier(&support, 0.8, true),
Some(DecideTier::Local),
"{support:?}: the local head answers what history cannot"
);
@@ -2078,6 +2150,31 @@ mod tests {
}
}
+ /// `[decisions] escalate_below` defaults to 0.8 (matching the gate's
+ /// confidence bar so split BM25 votes escalate to tier 2 and unfreeze the
+ /// flywheel) and validates `0.0..=1.0` (#1094).
+ #[test]
+ fn escalate_below_is_configurable_and_range_checked() {
+ assert_eq!(DecisionsConfig::default().escalate_below, 0.8);
+ let cfg = xerj_common::config::Config::from_toml_str(
+ "[decisions]\nindex = \"judgements\"\nescalate_below = 0.65\n",
+ )
+ .expect("toml");
+ assert_eq!(cfg.decisions.escalate_below, 0.65);
+ let disabled = xerj_common::config::Config::from_toml_str(
+ "[decisions]\nescalate_below = 0.0\n",
+ )
+ .expect("0.0 disables confidence escalation");
+ assert_eq!(disabled.decisions.escalate_below, 0.0);
+ for bad in ["-0.1", "1.1", "nan"] {
+ let err = xerj_common::config::Config::from_toml_str(&format!(
+ "[decisions]\nescalate_below = {bad}\n"
+ ))
+ .expect_err(bad);
+ assert!(err.to_string().contains("escalate_below"), "{bad}: {err}");
+ }
+ }
+
/// The cached answer's document is the flywheel's contract: the
/// configured text/label fields (so it votes like any seeded example) and
/// the fixed p / source / ts the issue names. Nothing else — a cached
diff --git a/engine/crates/xerj-api/tests/decide_flywheel.rs b/engine/crates/xerj-api/tests/decide_flywheel.rs
index a76b53468..1b6181b5c 100644
--- a/engine/crates/xerj-api/tests/decide_flywheel.rs
+++ b/engine/crates/xerj-api/tests/decide_flywheel.rs
@@ -521,4 +521,85 @@ mod write_back {
.await;
assert_eq!(st, StatusCode::NOT_FOUND, "no index was created: {st} {r}");
}
+
+ /// Issue #1094: once the history index has BM25 support for common stop
+ /// words, split votes whose winning share is below `escalate_below` (default
+ /// 0.8) MUST escalate to `local` on both `/_decide` and `/v1/systemone` and
+ /// write the local judgement back into `[decisions] index` — unfreezing the
+ /// flywheel instead of locking the cache at 12 documents.
+ #[tokio::test]
+ async fn split_history_below_escalate_below_escalates_to_local_and_writes_back() {
+ let ln = local_node("history", 0.0).await;
+ let node = &ln.node;
+ node.create_index("history").await;
+ // Two seeded neighbours sharing the token `refund` with opposite labels:
+ // rank 0 gets weight 1.0, rank 1 gets weight 0.5 → winning share 2/3 ≈ 0.6667 < 0.8.
+ node.put_doc(
+ "history",
+ "h_true",
+ json!({"text": "refund money back request", "label": "true"}),
+ )
+ .await;
+ node.put_doc(
+ "history",
+ "h_false",
+ json!({"text": "refund inquiry status", "label": "not true"}),
+ )
+ .await;
+ node.refresh("history").await;
+ assert_eq!(node.docs("history").await.len(), 2);
+
+ // 1. `/_decide` escalates the split 2/3 vote (< 0.8) to `local` and caches the judgement.
+ let (st, r) = node
+ .decide(json!({"index": "history", "question": "refund money back check"}))
+ .await;
+ assert!(st.is_success(), "{st} {r}");
+ assert_eq!(
+ r["tier"], "local",
+ "split history vote (2/3 < 0.8) must escalate to local: {r}"
+ );
+ assert_eq!(r["source"], "local", "{r}");
+ let docs = node.wait_for_docs("history", 3).await;
+ assert_eq!(docs.len(), 3, "local escalation wrote back to history: {docs:?}");
+
+ // 2. `/v1/systemone` on another split index also escalates and writes back.
+ let ln2 = local_node("history_s1", 0.0).await;
+ let node2 = &ln2.node;
+ node2.create_index("history_s1").await;
+ node2
+ .put_doc(
+ "history_s1",
+ "s_true",
+ json!({"text": "invoice payment dispute", "label": "true"}),
+ )
+ .await;
+ node2
+ .put_doc(
+ "history_s1",
+ "s_false",
+ json!({"text": "invoice summary receipt", "label": "not true"}),
+ )
+ .await;
+ node2.refresh("history_s1").await;
+
+ let (st, r2) = node2
+ .systemone(json!({
+ "state": {"documents": {"doc_0": "invoice payment question"}},
+ "questions": {"d0": {"type": "noul", "instructions": "Is `documents.doc_0` a dispute?"}}
+ }))
+ .await;
+ assert!(st.is_success(), "{st} {r2}");
+ assert_eq!(
+ r2["decisions"]["evidence"]["d0"]["tier"], "local",
+ "split history vote on /v1/systemone escalates to local: {r2}"
+ );
+ assert_eq!(r2["decisions"]["evidence"]["d0"]["source"], "local", "{r2}");
+ let docs2 = node2.wait_for_docs("history_s1", 3).await;
+ assert_eq!(
+ docs2.len(),
+ 3,
+ "/v1/systemone escalation wrote back to history_s1: {docs2:?}"
+ );
+ }
}
+
diff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rs
index 565a83060..354ee4686 100644
--- a/engine/crates/xerj-common/src/config.rs
+++ b/engine/crates/xerj-common/src/config.rs
@@ -1,6 +1,6 @@
//! xerj configuration system.
//!
-//! Configuration is intentionally minimal: **132 settings** versus
+//! Configuration is intentionally minimal: **133 settings** versus
//! Elasticsearch's 3000+. Every option is named, documented, and has a sensible
//! production-ready default. The format is TOML, loaded from a single file.
//!
@@ -99,7 +99,7 @@ pub struct Config {
/// Second-stage reranking provider — 3 settings. Inert until a key is set.
pub rerank: RerankProviderConfig,
/// Typed decisions answered from a labelled-history index by
- /// nearest-neighbour vote — 8 settings. Inert until `decisions.index`
+ /// nearest-neighbour vote — 9 settings. Inert until `decisions.index`
/// names an index that exists.
pub decisions: DecisionsConfig,
/// Corpus Hub hosted read-only endpoints (`/_hub/v1/…`) — 2 settings.
@@ -108,7 +108,7 @@ pub struct Config {
pub hub: HubConfig,
}
-// 24 sub-configs, 132 leaf settings in total. Do not maintain that sum by hand
+// 24 sub-configs, 133 leaf settings in total. Do not maintain that sum by hand
// — `journey_zero_config` in xerj-engine/tests/product_experience.rs counts a
// serialised `Config::default()` and fails if this comment and the module
// header stop matching. `Default` is derived: every field is a sub-config that
@@ -391,6 +391,19 @@ impl Config {
)));
}
+ // Decisions: escalate_below is a winning-vote-share floor in 0.0..=1.0
+ // (0.0 disables confidence escalation; #1094).
+ if !self.decisions.escalate_below.is_finite()
+ || !(0.0..=1.0).contains(&self.decisions.escalate_below)
+ {
+ return Err(XerjError::config(format!(
+ "decisions.escalate_below must be in 0.0..=1.0 (got {}); it is the winning \
+ vote-share floor below which tier 1 escalates to the local decision tier, and \
+ 0.0 disables confidence escalation",
+ self.decisions.escalate_below
+ )));
+ }
+
self.engine.validate()?;
// Cluster: fail closed rather than expose an unauthenticated Raft
@@ -550,7 +563,7 @@ impl Config {
}
// ═════════════════════════════════════════════════════════════════════════════
-// Sub-configs (132 user-facing settings total; counted by
+// Sub-configs (133 user-facing settings total; counted by
// `journey_zero_config`, not by hand)
// ═════════════════════════════════════════════════════════════════════════════
@@ -2651,7 +2664,7 @@ impl RerankProviderConfig {
/// weighted nearest-neighbour vote over a labelled-history index — the
/// retrieval analogue of a judge model, with the evidence staying on the node.
///
-/// **8 settings.**
+/// **9 settings.**
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct DecisionsConfig {
@@ -2672,6 +2685,13 @@ pub struct DecisionsConfig {
/// `/_decide` abstains below this vote share (0 = never abstain; the
/// `/v1/systemone` wire has no abstain field and errors instead).
pub min_confidence: f64,
+ /// Winning vote-share floor in `0.0..=1.0` below which a tier-1 history
+ /// vote escalates to the tier-2 local decision head when armed
+ /// (`XERJ_DECIDE_MODE=local`, issue #1094). Default `0.8` matches the
+ /// flywheel gate's confidence bar so low-confidence history hits do not
+ /// freeze write-back; `0.0` disables confidence escalation. With no local
+ /// tier armed, a vote below this floor still answers from history.
+ pub escalate_below: f64,
/// How much more a human correction weighs in the vote than a cached or
/// seeded example, when the history document carries `human: true`
/// (issue #1061). 2.0 — the issue's ≥ 2x floor for corrections — is the
@@ -2694,6 +2714,7 @@ impl Default for DecisionsConfig {
text_field: "text".to_string(),
positive_label: "true".to_string(),
min_confidence: 0.0,
+ escalate_below: 0.8,
human_weight: 2.0,
calibration: CalibrationMethod::None,
}
@@ -3674,7 +3695,7 @@ mod tests {
("lifecycle", 1),
("wal_tap", 10),
("rerank", 3),
- ("decisions", 8),
+ ("decisions", 9),
("hub", 2),
];
@@ -3718,7 +3739,7 @@ mod tests {
"the section table must sum to the whole config"
);
assert_eq!(
- total, 132,
+ total, 133,
"the total settings count changed. It is quoted in this module's \
header, in xerj-common/src/lib.rs, in engine/README.md, in \
xerj.default.toml and in EXPECTED_SETTINGS in \
diff --git a/engine/crates/xerj-common/src/lib.rs b/engine/crates/xerj-common/src/lib.rs
index f78dfedfd..7ccbe11dc 100644
--- a/engine/crates/xerj-common/src/lib.rs
+++ b/engine/crates/xerj-common/src/lib.rs
@@ -7,13 +7,13 @@
//! ## Design philosophy
//!
//! Unlike Elasticsearch's 3000+ configuration knobs, xerj deliberately exposes
-//! **132 settings**, each meaningful and production-tested. Every default
+//! **133 settings**, each meaningful and production-tested. Every default
//! is chosen so that a fresh deployment with zero configuration changes performs
//! well for the majority of workloads.
//!
//! ## Modules
//!
-//! - [`config`] — TOML-based configuration (132 settings)
+//! - [`config`] — TOML-based configuration (133 settings)
//! - [`feedback`] — the bug/UX-report invitation shared by every `--help`
//! - [`error`] — Unified error type ([`XerjError`])
//! - [`types`] — Core domain types (documents, fields, IDs)
diff --git a/engine/crates/xerj-engine/tests/product_experience.rs b/engine/crates/xerj-engine/tests/product_experience.rs
index 7f5065c13..5a46fb0ac 100644
--- a/engine/crates/xerj-engine/tests/product_experience.rs
+++ b/engine/crates/xerj-engine/tests/product_experience.rs
@@ -753,7 +753,7 @@ fn count_settings(value: &serde_json::Value) -> usize {
/// Settings in a default `Config`, measured by `count_settings`. Quoted in
/// `xerj-common/src/config.rs`; keep the two in step.
-const EXPECTED_SETTINGS: usize = 132;
+const EXPECTED_SETTINGS: usize = 133;
#[tokio::test]
async fn journey_zero_config() {
diff --git a/engine/xerj.default.toml b/engine/xerj.default.toml
index efd0b121e..de30f7fd2 100644
--- a/engine/xerj.default.toml
+++ b/engine/xerj.default.toml
@@ -1,6 +1,6 @@
# xerj Default Configuration
# ============================================================
-# This file sets 55 of XERJ's 132 user-facing settings to their
+# This file sets 55 of XERJ's 133 user-facing settings to their
# production-ready defaults, and describes the rest in comments.
# Every value here IS the default, so copying this file changes
# nothing until you edit it (a test enforces that). The complete
@@ -679,6 +679,7 @@ access_log = false
# text_field = "text"
# positive_label = "true" # the label a noul's probability is the share of
# min_confidence = 0.0 # /_decide abstains below this
+# escalate_below = 0.8 # escalate tier-1 vote to tier-2 local head below this winning share (0.0 disables; #1094)
# human_weight = 2.0 # vote-weight multiplier for history docs carrying human: true
# calibration = "none" # none | isotonic | temperature — p_cal beside every p_raw (#1063)