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
fix(xerj-code): distinguish a not-loaded corpus from a genuine no-match (#475)
xerj-orge2619d7346e1
diff --git a/tools/xerj-code/scripts/xc.py b/tools/xerj-code/scripts/xc.pyindex 3377ca4b2..f80499d80 100755--- a/tools/xerj-code/scripts/xc.py+++ b/tools/xerj-code/scripts/xc.py@@ -49,6 +49,62 @@ def load_state(corpus):return json.load(fh)+def live_index_count(prefix):+ """How many indices under `prefix*` actually exist on the target server.++ `state/<corpus>.json` records that a corpus was once indexed, and against+ which url. It is NOT proof the corpus is loaded on the server THIS process+ is querying: the state entry survives a data-dir swap, a server restart onto+ an empty dir, or an XERJ_URL pointed at a different node. When that happens+ the prefix resolves to zero indices and every query returns "no match" —+ indistinguishable from a genuinely bad query, which is the exact failure+ reference-coding exists to prevent (an agent concludes "no reference" and+ starts guessing). So the count is checked explicitly.++ Returns an int on success (0 meaning "in state/ but not loaded here"), or+ None when the server is unreachable/unparseable — in which case the caller+ must NOT claim "0 live indices": the ordinary search path will report the+ transport failure honestly instead.+ """+ req = urllib.request.Request(f"{URL}/_cat/indices/{prefix}*?format=json&h=index")+ try:+ with urllib.request.urlopen(req, timeout=30) as resp:+ data = json.load(resp)+ except urllib.error.HTTPError as e:+ # A 404 on a wildcard means "no such indices" -> 0 loaded. Any other+ # HTTP status is an ambiguous server condition, not a clean zero.+ return 0 if e.code == 404 else None+ except (urllib.error.URLError, ValueError):+ return None+ if not isinstance(data, list):+ return None+ return len(data)+++def require_loaded(state):+ """Fail with a DISTINCT, actionable message when the corpus is not loaded.++ Kept deliberately separate from the empty-result path in main(): "0 live+ indices here" and "the corpus is loaded but nothing matched your query" are+ different diagnoses with different fixes, and collapsing them is the bug this+ guard closes.+ """+ prefix = state["prefix"]+ count = live_index_count(prefix)+ if count is None:+ return # server unreachable/ambiguous — let the search path report it.+ if count == 0:+ name = state.get("corpus", "?")+ stamp = state.get("indexed_at", "?")+ against = state.get("url")+ hint = (f" It was indexed against {against}." if against and against != URL+ else " It was indexed against a different data dir or server.")+ die(f"corpus '{name}' is in state/ (indexed {stamp}) but has 0 live "+ f"indices ('{prefix}*') on {URL}.{hint} Re-run xc-index.sh {name}, "+ f"or set XERJ_URL to the node that has it. (This is NOT a 'no "+ f"match' — the corpus simply is not loaded on this server.)", code=3)++def check_fresh(state, stale_ok):"""A stale index returns code that no longer exists, with false confidence."""stamp = state.get("indexed_at")@@ -436,10 +492,47 @@ def provenance(src):return f"{path}:{line}" if line else path+def list_corpora():+ """Show every state/ entry and whether it is actually loaded HERE.++ The whole point: freshness in state/ does not imply the corpus is queryable+ on this server. This prints the live index count per corpus so an agent can+ see the real, loadable corpus set without hitting _cat/indices by hand — and+ without mistaking an over-advertised ledger for the truth.+ """+ state_dir = os.path.join(ROOT, "state")+ if not os.path.isdir(state_dir):+ die(f"no state directory at {state_dir} — nothing indexed yet")+ entries = sorted(f[:-5] for f in os.listdir(state_dir) if f.endswith(".json"))+ if not entries:+ die(f"no corpora in {state_dir} — run xc-index.sh <corpus>")+ print(f"corpora in state/ (queried against {URL}):")+ loaded = 0+ for name in entries:+ try:+ with open(os.path.join(state_dir, f"{name}.json")) as fh:+ st = json.load(fh)+ except (OSError, ValueError):+ print(f" {name:<18} !! unreadable state file")+ continue+ prefix = st.get("prefix", f"xc-{name}")+ stamp = (st.get("indexed_at") or "?")[:10]+ count = live_index_count(prefix)+ if count is None:+ status = "server unreachable/ambiguous"+ elif count == 0:+ status = "NOT loaded here (0 indices) — stale/other-server"+ else:+ loaded += 1+ status = f"loaded — {count} index(es)"+ print(f" {name:<18} {stamp} {prefix:<18} {status}")+ print(f"\n{loaded} of {len(entries)} corpora are actually loaded on {URL}.")++def main():ap = argparse.ArgumentParser(description="retrieve reference passages")- ap.add_argument("corpus")- ap.add_argument("query")+ ap.add_argument("corpus", nargs="?")+ ap.add_argument("query", nargs="?")ap.add_argument("-k", type=int, default=5, help="max passages (default 5)")ap.add_argument("--lang", help="restrict to a file extension, e.g. rs")ap.add_argument("--stale-ok", action="store_true", help="answer from an old index anyway")@@ -481,10 +574,26 @@ def main():help="retrieval arm (default bm25 — best top-3 on both corpora)")ap.add_argument("--hybrid", action="store_const", const="hybrid", dest="mode",help="shorthand for --mode hybrid (lexical + vector, RRF-fused)")+ ap.add_argument("--list", action="store_true",+ help="list state/ corpora and whether each is loaded HERE, "+ "then exit (no corpus/query needed)")args = ap.parse_args()+ if args.list:+ list_corpora()+ return+ if not args.corpus or not args.query:+ ap.error("the following arguments are required: corpus, query "+ "(or pass --list)")+state = load_state(args.corpus)age = check_fresh(state, args.stale_ok)+ # A corpus can be in state/ yet have zero live indices on THIS server (it+ # was indexed against another data dir / node). Catch that here with a+ # distinct, actionable error — never let it fall through to the generic+ # "no passage matches" path, which reads as a bad query and sends the agent+ # off to guess. This is the fix for the state-ledger trust trap.+ require_loaded(state)note = Noneif args.mode == "hybrid":diff --git a/tools/xerj-code/tests/test_state_ledger.py b/tools/xerj-code/tests/test_state_ledger.pynew file mode 100755index 000000000..c307d3abb--- /dev/null+++ b/tools/xerj-code/tests/test_state_ledger.py@@ -0,0 +1,188 @@+#!/usr/bin/env python3+"""Regression tests for the state-ledger guard in xc.py.++The bug (dogfood 2026-08-18): a corpus can be listed in `state/` while having+ZERO live indices on the server xc.py is querying — it was indexed against a+different data dir / node. Before this guard, querying such a corpus returned+the SAME "No passage matches — corpus is likely wrong, fall back" message as a+genuinely bad query, so an agent concluded "no reference exists" and started+guessing: the exact failure reference-coding exists to prevent.++These tests pin the three outcomes, distinguishing them by exit code AND by+message, with the HTTP layer (urllib) mocked so no live server is needed:++ 1. in state/ but 0 live indices -> exit 3, DISTINCT "not loaded here" error+ 2. loaded, query matches nothing -> exit 1, ordinary "No passage ... matches"+ 3. loaded, query matches -> exit 0, normal answer with provenance++Offline by design: XERJ_CODE_HOME points at a throwaway dir and urlopen is+replaced, so nothing touches the network or the real ~/.xerj-code.+"""+import importlib.util+import io+import json+import os+import sys+import tempfile+import urllib.error+from contextlib import redirect_stderr, redirect_stdout+from datetime import datetime, timezone++HERE = os.path.dirname(os.path.abspath(__file__))+XC_PATH = os.path.join(HERE, "..", "scripts", "xc.py")++PREFIX = "xc-fixture"+CORPUS = "fixture"+++class FakeResp:+ """Minimal context-manager response json.load() can read."""+ def __init__(self, payload):+ self._data = json.dumps(payload).encode()++ def read(self, *a):+ return self._data++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False+++def make_urlopen(indices, search_hits):+ """A urlopen stand-in dispatching on the request URL.++ `indices` is the list _cat/indices returns (its length is the live count).+ `search_hits` is the hits array _search returns.+ """+ def fake_urlopen(req, timeout=None):+ url = req.full_url if hasattr(req, "full_url") else str(req)+ if "/_cat/indices/" in url:+ return FakeResp(indices)+ if "/_mapping" in url:+ # One index, mapping `body`+`defs`+`title` so resolve_fields keeps+ # the multi-field query and semantic_indices finds no semantic_text.+ return FakeResp({+ f"{PREFIX}-1": {"mappings": {"properties": {+ "body": {"type": "text"},+ "defs": {"type": "text"},+ "title": {"type": "text"},+ }}}+ })+ if "/_search" in url:+ return FakeResp({"hits": {"total": {"value": len(search_hits)},+ "hits": search_hits}})+ raise urllib.error.URLError(f"unexpected url in test: {url}")+ return fake_urlopen+++def load_xc():+ """Import xc.py fresh so module-level ROOT/URL pick up the test env."""+ for m in [k for k in sys.modules if k == "xc_under_test"]:+ del sys.modules[m]+ spec = importlib.util.spec_from_file_location("xc_under_test", XC_PATH)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++def write_state(home):+ os.makedirs(os.path.join(home, "state"), exist_ok=True)+ os.makedirs(os.path.join(home, "corpora", CORPUS), exist_ok=True)+ now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+ with open(os.path.join(home, "state", f"{CORPUS}.json"), "w") as fh:+ json.dump({"corpus": CORPUS, "indexed_at": now, "prefix": PREFIX,+ "url": "http://localhost:9999"}, fh)+ with open(os.path.join(home, "corpora", CORPUS, "corpus.json"), "w") as fh:+ json.dump({"repos": [{"repo": "acme", "licence": "MIT"}]}, fh)+++def run_query(mod, indices, search_hits, argv):+ """Run xc.main() with urlopen mocked; return (exit_code, stdout, stderr)."""+ mod.urllib.request.urlopen = make_urlopen(indices, search_hits)+ out, err = io.StringIO(), io.StringIO()+ code = 0+ saved = sys.argv+ sys.argv = ["xc.py"] + argv+ try:+ with redirect_stdout(out), redirect_stderr(err):+ mod.main()+ except SystemExit as e:+ code = e.code if isinstance(e.code, int) else 1+ finally:+ sys.argv = saved+ return code, out.getvalue(), err.getvalue()+++def main():+ passed = failed = 0++ def check(name, cond, detail=""):+ nonlocal passed, failed+ if cond:+ passed += 1+ print(f" ok — {name}")+ else:+ failed += 1+ print(f" FAIL — {name} {detail}")++ home = tempfile.mkdtemp(prefix="xc-ledger-test-")+ os.environ["XERJ_CODE_HOME"] = home+ os.environ["XERJ_URL"] = "http://localhost:9200"+ write_state(home)+ mod = load_xc()++ HIT = [{"_index": f"{PREFIX}-1", "_id": "d1", "_score": 12.3,+ "_source": {"body": "fn parse_two_way() { /* the algorithm */ }",+ "path": "acme/src/lib.rs", "line": 42,+ "symbols": [{"name": "parse_two_way", "kind": "fn",+ "line": 1}]}}]++ # Case 1: in state/ but ZERO live indices -> distinct "not loaded here".+ code, out, err = run_query(mod, indices=[], search_hits=[],+ argv=[CORPUS, "two way string search"])+ blob = out + err+ check("case1 exit code is 3 (distinct, not 1)", code == 3, f"got {code}")+ check("case1 message says 0 live indices", "0 live" in blob, repr(blob))+ check("case1 message is explicitly NOT a no-match",+ "NOT a 'no match'" in blob, repr(blob))+ check("case1 does NOT emit the ordinary no-match line",+ "No passage in" not in blob, repr(blob))+ check("case1 is actionable (re-run xc-index.sh)",+ "xc-index.sh" in blob, repr(blob))++ # Case 2: loaded (1 index) but the query matches nothing -> ordinary miss.+ code, out, err = run_query(mod, indices=[{"index": f"{PREFIX}-1"}],+ search_hits=[],+ argv=[CORPUS, "nonexistent xyzzy plugh"])+ blob = out + err+ check("case2 exit code is 1 (ordinary empty-result)", code == 1, f"got {code}")+ check("case2 uses the no-match wording", "No passage in" in blob, repr(blob))+ check("case2 does NOT claim the corpus is unloaded",+ "0 live" not in blob and "not loaded" not in blob, repr(blob))++ # Case 3: loaded and the query matches -> normal answer with provenance.+ code, out, err = run_query(mod, indices=[{"index": f"{PREFIX}-1"}],+ search_hits=HIT,+ argv=[CORPUS, "two way parse_two_way"])+ blob = out + err+ check("case3 exit code is 0 (success)", code == 0, f"got {code}")+ check("case3 shows provenance file:line", "acme/src/lib.rs:42" in blob,+ repr(blob))+ check("case3 shows the retrieved definition",+ "parse_two_way" in blob, repr(blob))++ # Case 4: --list distinguishes loaded from not-loaded per entry.+ code, out, err = run_query(mod, indices=[], search_hits=[], argv=["--list"])+ blob = out + err+ check("list exit code is 0", code == 0, f"got {code}")+ check("list flags the fixture as NOT loaded",+ "NOT loaded here" in blob, repr(blob))++ print(f"\n{passed} passed, {failed} failed")+ sys.exit(1 if failed else 0)+++if __name__ == "__main__":+ main()