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
Apply default search word budgets without promising byte limits
xerj-orgea6a47951260
diff --cc docs/recipes/batch-search.mdindex e628c1ead,eb382858d..03b09a1ee--- a/docs/recipes/batch-search.md+++ b/docs/recipes/batch-search.md@@@ -53,7 -53,7 +53,9 @@@ An unreadable mapping fails exact-ID itsearch-query fallback. Exact ID fields must be flat and keyword-mapped whereverpresent, with indexing enabled. Nested fields are outside this first version.--`max_tokens` optionally caps the entire successful response JSON, using the++`max_tokens` defaults to 8,000 when omitted or null, for both MCP and++`xerj batch-search`. Pass a larger integer to request more. It caps the entire++successful response JSON, using thesame UAX #29 word counter as the other MCP search tools. This is **not BPE**.If binding, the adapter removes raw `hit` bodies starting at later items,then extra hits; it retains every item outcome and at least one citation per@@@ -61,7 -61,7 +63,8 @@@ matched item. `hits_omitted` counts omicounter and limit. A nonbinding budget leaves the response byte-identical.If the remaining statuses, errors and citations cannot fit, the whole callreturns an explicit error naming the minimum required budget. Split the batch--or increase the budget. Errors are outside the budget and are never truncated.++or increase the budget. Errors are outside the budget and are never truncated. This is a word budget,++not a byte cap or a guarantee that output fits a host's display limit.CLI exit codes: `0` all items completed (including abstentions); `3` one or moreper-item errors (the JSON still contains all outcomes); `2` invalid CLI/inputdiff --cc engine/crates/xerj-mcp/src/batch.rsindex fe161ec08,fe161ec08..a153b9cec--- a/engine/crates/xerj-mcp/src/batch.rs+++ b/engine/crates/xerj-mcp/src/batch.rs@@@ -10,7 -10,7 +10,7 @@@ const MAX_RESPONSE_BYTES: usize = 32 *pub(crate) fn spec() -> Value {json!({"name":"xerj_batch_search",-- "description": "Search 1..50 IDs or questions in one call, in input order. Shares the CLI xerj batch-search adapter. Each result has its zero-based position, optional caller key, and status hits, abstain (only a complete empty search), or error. Hits carry citations: index/id plus file/line or record locator when available. This retrieves evidence, not generated answers or calibrated confidence. Use identifier plus an explicitly keyword-mapped field for exact IDs; query takes plain text or an ES query clause. One bad item never discards its siblings; identical inputs remain separate. Uses one _msearch request, plus at most one mapping read. Optional max_tokens caps the entire successful JSON response using StandardTokenizer UAX #29 words, not BPE. Budgeting removes raw hit bodies, then extra hits, retaining each item's status and at least one citation per matched item. If that minimum cannot fit, returns an actionable tool error, never truncated JSON or a false abstention. Errors are not truncated.",++ "description": "Search 1..50 IDs or questions in one call, in input order. Shares the CLI xerj batch-search adapter. Each result has its zero-based position, optional caller key, and status hits, abstain (only a complete empty search), or error. Hits carry citations: index/id plus file/line or record locator when available. This retrieves evidence, not generated answers or calibrated confidence. Use identifier plus an explicitly keyword-mapped field for exact IDs; query takes plain text or an ES query clause. One bad item never discards its siblings; identical inputs remain separate. Uses one _msearch request, plus at most one mapping read. Omitted or null max_tokens defaults to 8000 UAX #29 words and caps the entire successful JSON response using StandardTokenizer UAX #29 words, not BPE. Budgeting removes raw hit bodies, then extra hits, retaining each item's status and at least one citation per matched item. If that minimum cannot fit, returns an actionable tool error, never truncated JSON or a false abstention. Errors are not truncated.","inputSchema":{"type":"object", "additionalProperties":false,"properties":{@@@ -26,7 -26,7 +26,7 @@@"index":{"type":"string","description":"Index or pattern; alternative to prefix. Defaults to ax-*."},"prefix":{"type":"string","description":"Autoindex prefix, e.g. project searches project-*. Cannot combine with index."},"size":{"type":"integer","minimum":1,"maximum":50,"default":3,"description":"Maximum hits per item."},-- "max_tokens":{"type":"integer","minimum":32,"description":format!("Whole-response budget counted with {} (not BPE); minimum 32. A successful response NEVER exceeds it. Preserves ordered item outcomes and at least one citation per matched item, removing raw bodies first. Refuses if that minimum cannot fit; split the batch or increase the budget. Errors are outside this budget.", token_budget::TOKENIZER_NAME)}++ "max_tokens":{"type":"integer","minimum":32,"default":token_budget::DEFAULT_MAX_TOKENS,"description":format!("Whole-response budget counted with {} (not BPE or a byte cap); minimum 32. Omitted or null defaults to 8000 words; pass a larger integer for more. A successful response NEVER exceeds it. Preserves ordered item outcomes and at least one citation per matched item, removing raw bodies first. Refuses if that minimum cannot fit; split the batch or increase the budget. Errors are outside this budget.", token_budget::TOKENIZER_NAME)}},"required":["queries"]}})diff --cc engine/crates/xerj-mcp/src/batch_cli.rsindex 4744cc9d6,c22c0e8bb..1862b2ea4--- a/engine/crates/xerj-mcp/src/batch_cli.rs+++ b/engine/crates/xerj-mcp/src/batch_cli.rs@@@ -22,7 -22,7 +22,8 @@@ Output is one JSON object with orderedauthoritative even for duplicate keys. status is hits, abstain (complete emptysearch only), or error. Hits contain citations and raw evidence, not generatedanswers or calibrated confidence. A miss does not discard its siblings.--max_tokens counts the entire JSON as UAX #29 words, not model/BPE tokens.++max_tokens defaults to 8000 when omitted or null; pass a larger integer for more.++It counts the entire JSON as UAX #29 words, not bytes or model/BPE tokens.It removes raw bodies and then extra hits, retaining every item outcome andone citation per matched item; an insufficient budget is an error, not truncation.diff --cc engine/crates/xerj-mcp/src/lib.rsindex 58ecf43ab,617ba0318..97d853897--- a/engine/crates/xerj-mcp/src/lib.rs+++ b/engine/crates/xerj-mcp/src/lib.rs@@@ -99,7 -99,10 +99,11 @@@//! text NEVER exceeds the budget. Enforcement lives in [`token_budget`],//! counted with one named tokenizer (XERJ's `StandardTokenizer`, UAX #29//! words), with duplicate passages removed before budgeting and- //! over-budget hits reduced to locators.+ //! over-budget hits reduced to locators. Omitting `max_tokens` applies+ //! [`token_budget::DEFAULT_MAX_TOKENS`] rather than leaving the response-//! unbounded, so a result too large for the host's tool-output limit is-//! trimmed with an accounting block instead of being spilled to a file.++//! unbounded. The batch tool and `xerj batch-search` use the same default++//! over their whole successful JSON response. This word count is neither a++//! byte cap nor a model/BPE token count and cannot guarantee a host output limit.mod batch;mod batch_cli;@@@ -878,6 -869,6 +882,7 @@@ fn max_tokens_arg_schema() -> Valuejson!({"type": "integer","minimum": token_budget::MIN_MAX_TOKENS,++ "default": token_budget::DEFAULT_MAX_TOKENS,"description": format!("Token budget for this response: the returned text NEVER exceeds it. Tokens are \counted with {} — the same word split the engine's own analyzer uses for BM25. \@@@ -889,9 -880,12 +894,12 @@@listed as LOCATORS ONLY (file:line, index/id) rather than dropped, and the \response's `_token_budget` block accounts for every hit: kept, locator-only, \deduped, dropped. Errors are never truncated — a refusal you cannot read \- end-to-end is worse than a long response. Minimum {}.",+ end-to-end is worse than a long response. Minimum {}; when omitted the budget is \- {} (about 45 KB), so a response stays inside a host's tool-output limit unless you \- ask for more.",++ {} UAX #29 words. This is not a byte cap or a guarantee against host output \++ limits. Pass a larger integer to request more.",token_budget::TOKENIZER_NAME,token_budget::MIN_MAX_TOKENS,+ token_budget::DEFAULT_MAX_TOKENS,)})}diff --cc engine/crates/xerj-mcp/src/token_budget.rsindex 3ebd4e822,192f3f30d..bcdfbbde7--- a/engine/crates/xerj-mcp/src/token_budget.rs+++ b/engine/crates/xerj-mcp/src/token_budget.rs@@@ -60,6 -60,18 +60,15 @@@ pub const TOKENIZER_ID: &str = "standar/// budget it cannot honor.pub const MIN_MAX_TOKENS: usize = 32;+ /// Budget applied when the caller passes no `max_tokens` (#2491).+ ///-/// Without a default the response was unbounded, and an agent whose host caps-/// tool output had the result spilled to a temp file instead of shown inline —-/// it then spent extra steps reading the file back, which is exactly the cost-/// the budget exists to avoid. ~8000 word tokens is roughly 45 KB of text:-/// far more than any useful search response (a typical 10-hit page is a few-/// hundred), and comfortably inside the tool-output limits MCP hosts impose.-/// A caller that wants more says so — any value above [`MIN_MAX_TOKENS`] is-/// accepted — so this bounds the default, not the ceiling.++/// Six individual search tools, the batch tool and `xerj batch-search` apply++/// this UAX #29 word budget to successful output. Long identifiers and++/// punctuation can occupy many bytes while counting as few words: this is++/// neither a byte cap nor a model-context/BPE limit. Callers may request any++/// value at or above [`MIN_MAX_TOKENS`]; errors remain untruncated.+ pub const DEFAULT_MAX_TOKENS: usize = 8_000;+/// Tokens reserved for the `_token_budget` accounting block before any hit is/// admitted. The block's fixed fields (keys + counts) measure ~14 word tokens;/// locator stubs inside it are charged against the content budget separately,@@@ -81,9 -93,15 +90,12 @@@ const TRUNCATION_MARKER: &str = "\n[tru/// floor is an error, never a silent drop — the `opt_typed` policy: an agent/// that asked for a budget and silently got none would trust a response whose/// size it cannot predict.+ ///-/// Absent means [`DEFAULT_MAX_TOKENS`], not unbounded (#2491): a response that-/// overflows the host's tool-output limit is one the agent cannot read inline,-/// so "no budget asked for" must not degrade into "no budget applied". The-/// return is still an `Option` because a caller may want to skip budgeting-/// entirely for a response it already knows is short.++/// Absent or null means [`DEFAULT_MAX_TOKENS`] (#2491). The `Option` shape is++/// retained for internal response paths that bypass budgeting explicitly.pub fn opt_max_tokens(args: &Value) -> Result<Option<usize>, String> {match args.get("max_tokens") {- None | Some(Value::Null) => Ok(None),+ None | Some(Value::Null) => Ok(Some(DEFAULT_MAX_TOKENS)),Some(v) => match v.as_u64() {Some(n) if n as usize >= MIN_MAX_TOKENS => Ok(Some(n as usize)),_ => Err(format!(@@@ -639,6 -664,45 +658,57 @@@ mod tests}}+ /// #2491: a search that passes no `max_tokens` used to return whatever the+ /// engine produced, and a response past the host's tool-output limit was+ /// spilled to a temp file instead of shown to the agent. Absent now means- /// `DEFAULT_MAX_TOKENS`, so the same call is bounded and still readable.++ /// `DEFAULT_MAX_TOKENS`, so the same call stays within this word budget.+ #[test]+ fn an_unbudgeted_search_response_is_bounded_by_default() {- // Wide enough that an unbounded response overruns any plausible host- // limit: 400 hits carrying 400 lines of body each.++ // A response larger than the default word budget: 400 hits++ // carrying 400 lines of body each.+ let resp = search_response(+ (1..=400)+ .map(|i| code_hit(&format!("repo/src/module_{i}.rs"), 10 * i, 400))+ .collect(),+ );+ let unbounded = count_tokens(&resp);+ assert!(+ unbounded > DEFAULT_MAX_TOKENS,+ "the fixture must be big enough to need the default cap: {unbounded}"+ );++ let budget = opt_max_tokens(&json!({}))+ .expect("absent max_tokens is not an error")+ .expect("absent max_tokens must apply the default budget");+ assert_eq!(budget, DEFAULT_MAX_TOKENS);++ let out = budget_json_response(&resp, budget);+ let used = count_tokens(&out);+ assert!(+ used <= DEFAULT_MAX_TOKENS,+ "default budget {DEFAULT_MAX_TOKENS} exceeded: {used}\n---\n{out}\n---"+ );+ // Bounded by dropping content, not by dropping the answer: the+ // accounting block has to say what went, or the agent cannot tell a+ // short corpus from a truncated one.+ assert!(+ out.contains("_token_budget"),+ "the response must account for what the budget cut:\n{out}"+ );+ }+++ #[test]++ fn word_budget_does_not_claim_a_byte_limit() {++ let resp = search_response(vec![json!({++ "_index": "docs", "_id": "long", "_source": {++ "body": "x".repeat(100_000)++ }++ })]);++ assert!(resp.len() > 100_000);++ assert!(count_tokens(&resp) < DEFAULT_MAX_TOKENS);++ assert_eq!(budget_json_response(&resp, DEFAULT_MAX_TOKENS), resp);++ }++// ── JSON surface: per-tool budget enforcement ──────────────────────────/// xerj_search shape: definition-first hits over an autoindex corpus,diff --cc tools/benchmarks/batch-retrieval/README.mdindex 064f1b50a,000000000..71f776815mode 100644,000000..100644--- a/tools/benchmarks/batch-retrieval/README.md+++ b/tools/benchmarks/batch-retrieval/README.md@@@ -1,194 -1,0 +1,199 @@@+# Batch retrieval on rust-vulns++Reproduce the retrieval-evaluation part of [#1801](https://github.com/xerj-org/xerj/issues/1801).+The CLI and MCP adapter shipped in [#2333](https://github.com/xerj-org/xerj/pull/2333).+This harness measures that implementation; it changes no engine or MCP behavior.++## Run++From the repository root, with Python 3.9+ and GitHub CLI installed:++```sh+set -eu+(cd engine && cargo +1.97.1 build --locked --offline --release -j 32 -p xerj-server)+XERJ_BENCH_ROOT=$(pwd)+XERJ_BENCH_TMP=$(mktemp -d)+python3 -m venv "$XERJ_BENCH_TMP/venv"+"$XERJ_BENCH_TMP/venv/bin/pip" install -r tools/benchmarks/batch-retrieval/requirements.txt+gh release download pack-rust-vulns-2026-10-24 --repo xerj-org/xerj \+ --pattern rust-vulns-pack.zip --dir "$XERJ_BENCH_TMP"+"$XERJ_BENCH_TMP/venv/bin/python" tools/benchmarks/batch-retrieval/run.py \+ --pack "$XERJ_BENCH_TMP/rust-vulns-pack.zip" \+ --binary "$XERJ_BENCH_ROOT/engine/target/release/xerj" \+ --engine-commit "$(git rev-parse HEAD)" \+ --output "$XERJ_BENCH_TMP/run" --repeats 5+```++The offline Cargo build needs cached dependencies; omit `--offline` on a first+build. Cargo runs from `engine/` to load its target-specific configuration.+Use a release binary built from the+declared engine commit; the harness records its SHA-256 and version but cannot+prove its source ancestry. Indexing and timing execute a private copy of the+exact byte snapshot that was hashed; changing the original binary mid-run+cannot change the measured executable.++The archive is pinned by its GitHub release asset SHA-256:+`54f0419e6d944635eeaf9199923064278c36fd578213db60ca77cc85d2a69e3d`.+It contains 2,051 identity-resolved records from RustSec and OSV (CC0-1.0).+The harness hashes the archive before opening it, checks manifest shard hashes+and counts, and reads ZIP members directly without extraction. It uses no Hub+pack installation, signature verification, or executable code from the archive.+The digest pins the bytes under evaluation; it is not a signature claim.++All index data is written under a fresh, private temporary directory on random+loopback ports. No existing node, index, corpus configuration or admin key is+used. The complete records are ingested with explicit keyword `id`/`aliases`+and text `title`/`body` mappings, `dynamic: false`, plus synthetic source+locators. This tests the adapter on the real pack, not autoindex schema inference+or Hub routing. Setup, bulk status, post-refresh count and final count are+checked. Children shut down normally; restart checks that the same data survives.+The temporary index is removed on exit. A failed run retains logs in the output+directory. Choose a new output path after a failed or interrupted run: existing+output directories are refused, including successful results.++The corpus is public advisory text. Only the operator can write the fresh+scratch and output directories in the intended usage. Output includes advisory+IDs/citations, public pack metadata, hardware metadata, counts and digests;+it excludes credentials and raw local source paths. Benchmark children remove+inherited proxy and `XERJ_*` configuration and disable automatic feedback so+the test only talks to its private node. No model, reranker or embedding+provider is called. The first tokenizer setup may download its fixed table.++## Workload and scoring++`cases.json` fixes the input order and labels before the run:++| Kind | Items | Success criterion |+|---|---:|---|+| Canonical ID | 15 | Exactly the labelled canonical advisory |+| CVE/GHSA alias | 15 | Exactly the labelled canonical advisory, through the explicit `aliases` field |+| Near-miss ID | 10 | `abstain: true`, `reason: no_hits` |+| Text | 8 | At least one labelled advisory in the first three hits |+| Duplicate | 1 | Same input/key as the first item; separate positional result |+| Invalid item | 1 | Independent query-validation error; never an abstention |++The eight text queries are hand-authored, title-informed known-item lookups.+Their `label_basis` is the advisory title, not a model-generated judgment.+They do not form an exhaustive relevance set: the text metric is labelled+hit@3, not answer accuracy, nDCG, full recall or calibrated confidence.+Canonical and alias targets are validated against the **full** pack before+starting the node. Canonical selection includes the eight text targets and a+SHA-256-ordered sample; aliases alternate CVE/GHSA from that ordering. Missing+IDs append `0` to a real ID and are checked absent. There are 49 valid retrieval+items and one expected item error per trial. Report error isolation separately+from retrieval accuracy; the valid-item abstention denominator is 49.++Every returned hit must cite its actual stored index and canonical ID. Exact+lookups reject extra wrong IDs. Errors, timeouts and transport failures are+never counted as successful misses. Quality is scored independently in every+trial. Ranked evidence, citations and outcomes must also agree across both+arms, both transports, warmups and repeats. A quality failure exits 1 and writes+the failed scores; malformed output, failed setup or parity failure exits 1+without publishing a successful report. Do not publish speed or cost gains+from a failed run.++## What is timed and counted++For each transport the two arms are:++- **Batch:** one `xerj_batch_search` call containing all 50 items.+- **Single:** 50 sequential one-item calls to the **same adapter**. This holds+ query semantics, mapping lookup, response schema and citation policy fixed.+ It is not a comparison with `xerj_search`, `xerj code`, grep or an LLM.++These are tool-call counts, not observed HTTP request counts: the intentionally+invalid item is rejected locally and mapping reads are part of the adapter.+- Both request `size: 3`, no `max_tokens`. All requests run at concurrency one.++Protocol version 2 requests `size: 3` and `max_tokens: 1000000` in every arm.++This explicit UAX #29 word allowance keeps retrieval evidence independent of++adapter defaults; a response carrying `_token_budget` fails the run. All++requests run at concurrency one. The earlier committed macOS/Linux receipts++used no explicit budget and predate the adapter's default. Their raw evidence++is retained unchanged; request payloads and token counts differ from version 2.+One full warmup per arm is discarded. Five measured repeats alternate arm+order. CLI runs before MCP on the same refreshed, unchanged index. Caches stay+warm; no cache-flush, cold-query or read-under-write claim is made.++CLI timing includes spawning a process per call. MCP uses one initialized,+persistent stdio session; initialization and process startup are excluded.+Task latency covers the complete group of calls and JSON handling, with+scoring, hashing and BPE counting outside the timed loop. Report median,+minimum, maximum and every per-trial/per-call wall time. These are local warm+end-to-end measurements, not engine-only latency.++Tokens use `tiktoken==0.12.0`, `cl100k_base`, on the exact UTF-8 JSON lines sent+and received. CLI counts stdin/stdout; MCP counts `tools/call` request/response+envelopes including the tool name and escaped content. Each line is tokenized+separately and counts are summed, not tokenized after concatenation. Byte counts+and SHA-256 digests accompany each call. MCP initialization, tool schemas,+system prompts, conversation history and reasoning are excluded. These are+payload BPE tokens, not billed model usage or complete agent-task token cost.+They are unrelated to the adapter's UAX #29 `max_tokens` word budget.++## Harness checks++```sh+python3 tools/benchmarks/batch-retrieval/test_run.py+```++The stdlib tests cover wrong/extra IDs, error-versus-miss scoring, citation+identity, labelled hit@3, positional correspondence, parity, archive pinning,+duplicate preservation and per-call wire accounting. CI runs these checks+without downloading the corpus, tokenizer or a model. Real-node evaluation is+the explicit command above, not a network-dependent merge gate.++Generated answers, automatic alias-field discovery, confidence calibration and+escalation remain separate work under #1801 and its related issues. This+evaluation alone does not close #1801.++## Measured run: 2026-10-25++[Raw per-call and per-item receipts](results/2026-10-25-macos-arm64.json),+from clean harness commit `f016e078d61bd3a2b94ea140ef3515ef1a266705` and a+Rust 1.97.1 release build of engine commit+`7e1554734c5b26f7c4f85ee7b5ba838148fe1089` (`xerj v1.0.0-rc.99`).+macOS arm64, Apple M4, 16 GiB RAM; `XERJ_NUM_CPUS=4`.+This was a shared developer laptop, with warm caches and concurrency one.+The command above ran with `--repeats 5`; the earlier two-repeat smoke is not+included in these receipts. The receipt records the binary, pack and query+SHA-256 values, full public pack manifest and source provenance.++| Transport / arm | Calls per 50 items | Task median ms (min–max) | Input BPE tokens | Output BPE tokens |+|---|---:|---:|---:|---:|+| CLI / batch | 1 | 26.487 (26.209–27.632) | 1,071 | 87,676 |+| CLI / single | 50 | 487.739 (480.636–491.249) | 1,757 | 87,872 |+| Persistent MCP / batch | 1 | 15.410 (15.340–16.186) | 1,101 | 100,591 |+| Persistent MCP / single | 50 | 29.515 (28.871–29.931) | 3,306 | 102,257 |++Token totals are per complete 50-item trial and were identical in all five+repeats for each arm. The CLI median ratio is 18.41x, including process startup;+the persistent MCP ratio is 1.92x. They do not measure server-only speedup.+Batching reduced input payload tokens by 39.04% (CLI) / 66.70% (MCP), but output+payload tokens by only 0.22% / 1.63%. Full stored advisory bodies dominate+output. This run does not support a large output-token-savings claim.++All four arms and five repeats scored 49/49 valid retrieval items correctly:+31/31 exact lookups including the duplicate, 8/8 labelled text hit@3, and+10/10 intended misses. Each trial abstained on 10/49 valid items (20.41%),+with zero false abstentions on the 39 labelled answerable items. The separate+invalid item returned its query-validation error without losing siblings.+Every returned hit had a checked index/ID citation; ranked evidence and+citations matched across modes, transports and repeats. The index retained+2,051 records before and after graceful restart. This is a small fixed+known-item workload, not an estimate of general advisory QA accuracy.++## Independent Linux verification: 2026-10-28++[Linux receipts](results/2026-10-28-linux-x86_64.json) repeat the same pinned+pack and workload with five measured repeats per arm, using a scoped release+build of `4af41af87f86e036142503d0e38fc84e2a41bd81` (rc.100 plus the reviewed+SQL/Markdown/empty-file fixes). All four arms passed 49/49 retrieval items in+every repeat, kept the expected per-item validation error separate, and+matched ranked evidence and citations. The node retained 2,051 records across+graceful restart. Payload token totals matched the earlier macOS receipt.++This was a shared Linux host; a separate conformance run also executed during+this review. The receipt retains the observed timings, but this run does not+isolate a version, platform, or throughput improvement. Wrong-archive and+existing-output CLI controls also failed before publication, with exit 1 and+exit 2 respectively; the existing-output sentinel remained unchanged.diff --cc tools/benchmarks/batch-retrieval/run.pyindex 450e6796b,000000000..13262cc58mode 100644,000000..100644--- a/tools/benchmarks/batch-retrieval/run.py+++ b/tools/benchmarks/batch-retrieval/run.py@@@ -1,449 -1,0 +1,456 @@@+#!/usr/bin/env python3+"""Pinned rust-vulns retrieval comparison; no model calls or answer generation."""+import argparse+import contextlib+import hashlib+import importlib.metadata+import io+import json+import os+from pathlib import Path+import platform+import queue+import socket+import statistics+import subprocess+import sys+import tempfile+import threading+import time+import urllib.request+import zipfile++HERE = Path(__file__).resolve().parent+ROOT = HERE.parents[2]+INDEX = 'advisories'++# Hold evidence policy fixed across all four arms, independent of adapter defaults.++MAX_TOKENS = 1_000_000+PACK_SHA256 = '54f0419e6d944635eeaf9199923064278c36fd578213db60ca77cc85d2a69e3d'+PACK_TAG = 'pack-rust-vulns-2026-10-24'+++def wire(value):+ return json.dumps(value, ensure_ascii=False, separators=(',', ':')) + '\n'+++def sha(data):+ return hashlib.sha256(data).hexdigest()+++def freeze_binary(data, work):+ binary = work / 'xerj'+ binary.write_bytes(data)+ binary.chmod(0o700)+ return binary+++def read_pack(path):+ # Read once: both the digest and records refer to these exact bytes. No extraction.+ data = path.read_bytes()+ if sha(data) != PACK_SHA256:+ raise ValueError('pack SHA256 mismatch; use the pinned release in README.md')+ with zipfile.ZipFile(io.BytesIO(data)) as z:+ manifest = json.loads(z.read('manifest.json'))+ if manifest['format_version'] != 1 or manifest['pack'] != 'rust-vulns':+ raise ValueError('unsupported pack manifest')+ records = []+ for name, entry in sorted(manifest['files'].items()):+ blob = z.read(name)+ if sha(blob) != entry['sha256']:+ raise ValueError('manifest checksum mismatch: ' + name)+ if name.startswith('records-') and name.endswith('.jsonl'):+ records.extend(json.loads(line) for line in blob.splitlines())+ if len(records) != manifest['counts']['records']:+ raise ValueError('pack record count mismatch')+ ids = [r['id'] for r in records]+ if len(set(ids)) != len(ids) or not all(ids):+ raise ValueError('pack has empty or duplicate canonical IDs')+ return records, manifest+++def validate_cases(cases, records):+ if len(cases) != 50:+ raise ValueError('expected the committed 50-item workload')+ ids = {r['id'] for r in records}+ for case in cases:+ expected = set(case['expected_ids'])+ if not expected <= ids:+ raise ValueError('label names an absent canonical ID')+ if case['kind'] in ('canonical', 'alias', 'missing', 'duplicate'):+ item = case['input']+ actual = {r['id'] for r in records+ if item['identifier'] in ([r[item['field']]] if item['field'] == 'id'+ else r[item['field']])}+ if expected != actual:+ raise ValueError('exact-ID gold differs from pack: ' + item['key'])+++def ordered_rows(response, items):++ if '_token_budget' in response:++ raise ValueError('benchmark requires full evidence; response budget bound')+ rows = response.get('results')+ if not isinstance(rows, list) or len(rows) != len(items):+ raise ValueError('response count mismatch')+ for position, (row, item) in enumerate(zip(rows, items)):+ if row.get('position') != position or row.get('key') != item['key']:+ raise ValueError('response position/key mismatch')+ return rows+++def score(case, row):+ status = row.get('status')+ retrieved, citations = [], []+ if status == 'hits':+ if row.get('abstain') is not False or not row.get('hits'):+ raise ValueError('malformed hits outcome')+ for entry in row['hits']:+ citation, hit = entry['citation'], entry['hit']+ if (citation.get('_index') != INDEX or citation.get('_id') != hit['_id']+ or hit['_index'] != INDEX or hit['_source']['id'] != hit['_id']):+ raise ValueError('citation does not identify the stored advisory')+ retrieved.append(hit['_id'])+ citations.append(citation)+ elif status == 'abstain':+ if row.get('abstain') is not True or row.get('reason') != 'no_hits' or row.get('hits'):+ raise ValueError('malformed abstention')+ elif status == 'error':+ if 'error' not in row:+ raise ValueError('missing item error')+ else:+ raise ValueError('unknown outcome')+ expected = set(case['expected_ids'])+ if case['kind'] == 'invalid':+ correct = status == 'error'+ elif not expected:+ correct = status == 'abstain'+ elif case['kind'] == 'text':+ correct = status == 'hits' and bool(expected.intersection(retrieved))+ else:+ correct = status == 'hits' and set(retrieved) == expected+ return {'key': case['input']['key'], 'kind': case['kind'], 'status': status,+ 'expected_ids': sorted(expected), 'retrieved_ids': retrieved,+ 'citations': citations, 'correct': correct,+ **({'error': row['error']} if status == 'error' else {})}+++def evidence_signature(rows):+ # Compare ranked identity + citation, not volatile timing or local positions.+ return [(r['status'], [(h['citation'], h['hit']['_source']) for h in r.get('hits', [])],+ r.get('error'), r.get('reason')) for r in rows]+++def request(url, method, path, value=None, ndjson=False):+ data = (value.encode() if ndjson else wire(value).encode()) if value is not None else None+ req = urllib.request.Request(url + path, data, method=method,+ headers={'Content-Type': 'application/x-ndjson' if ndjson+ else 'application/json'})+ # This harness only talks to its own loopback node; never inherit proxy routing.+ with urllib.request.build_opener(urllib.request.ProxyHandler({})).open(req, timeout=30) as r:+ return json.load(r)+++def child_env():+ env = {k: v for k, v in os.environ.items()+ if k.lower() not in ('all_proxy', 'http_proxy', 'https_proxy', 'no_proxy')+ and not k.startswith('XERJ_')}+ env.update(XERJ_DISABLE_FEEDBACK='true', XERJ_AUTH='', XERJ_NUM_CPUS='4')+ return env+++def hardware():+ if platform.system() == 'Darwin':+ return {'cpu_model': subprocess.check_output(['sysctl', '-n', 'machdep.cpu.brand_string'], text=True).strip(),+ 'memory_bytes': int(subprocess.check_output(['sysctl', '-n', 'hw.memsize'], text=True))}+ if platform.system() == 'Linux':+ cpu = next((line.split(':', 1)[1].strip() for line in Path('/proc/cpuinfo').read_text().splitlines()+ if line.startswith('model name')), platform.machine())+ return {'cpu_model': cpu,+ 'memory_bytes': os.sysconf('SC_PHYS_PAGES') * os.sysconf('SC_PAGE_SIZE')}+ raise ValueError('this harness supports macOS and Linux')+++def stop(child):+ if child.poll() is None:+ child.terminate()+ try:+ child.wait(timeout=20)+ except subprocess.TimeoutExpired:+ child.kill()+ child.wait(timeout=5)+ raise RuntimeError('child required SIGKILL')+ if child.returncode != 0:+ raise RuntimeError('child exited with status ' + str(child.returncode))+++def node(binary, work, env):+ # Reserve distinct ports during config construction, then release for startup.+ with contextlib.ExitStack() as stack:+ ports = []+ for _ in range(2):+ sock = stack.enter_context(socket.socket())+ sock.bind(('127.0.0.1', 0))+ ports.append(sock.getsockname()[1])+ url = 'http://127.0.0.1:' + str(ports[0])+ config = work / 'node.toml'+ config.write_text('[server]\nbind_address="127.0.0.1"\nes_compat_port=' + str(ports[0])+ + '\nrest_port=' + str(ports[1]) + '\ngrpc_port=0\ndata_dir='+ + json.dumps(str(work / 'data'))+ + '\n[limits]\ndisk_flood_stage_percent=0\n')+ with (work / 'node.log').open('a') as log:+ child = subprocess.Popen([str(binary), '--insecure', '-c', str(config)],+ cwd=work, env=env, stdout=log, stderr=log)+ try:+ deadline = time.monotonic() + 60+ while True:+ if child.poll() is not None:+ raise RuntimeError('node exited before readiness; see node.log')+ try:+ request(url, 'GET', '/')+ break+ except OSError:+ if time.monotonic() >= deadline:+ raise RuntimeError('node readiness timeout')+ time.sleep(.1)+ yield url+ finally:+ stop(child)+++def ingest(url, records):+ request(url, 'PUT', '/' + INDEX, {'mappings': {'dynamic': False, 'properties': {+ 'id': {'type': 'keyword'}, 'aliases': {'type': 'keyword'},+ 'body': {'type': 'text'}, 'title': {'type': 'text'},+ 'ax_path': {'type': 'keyword'}, 'ax_locator': {'type': 'keyword'}}}})+ for start in range(0, len(records), 100):+ lines = []+ for r in records[start:start + 100]:+ lines.extend([wire({'index': {'_index': INDEX, '_id': r['id']}}),+ wire(dict(r, ax_path='rust-vulns/records', ax_locator=r['id']))])+ result = request(url, 'POST', '/_bulk', ''.join(lines), ndjson=True)+ if result.get('errors') is not False:+ raise ValueError('bulk item errors: ' + wire(result))+ request(url, 'POST', '/' + INDEX + '/_refresh')+ if request(url, 'GET', '/' + INDEX + '/_count')['count'] != len(records):+ raise ValueError('indexed count differs from pack')+++class MCP:+ def __init__(self, binary, url, work, env):+ self.log = (work / 'mcp.log').open('w')+ self.child = subprocess.Popen([str(binary), 'mcp', '--url', url], cwd=work,+ env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=self.log, text=True)+ self.inbox = queue.Queue()+ self.reader = threading.Thread(target=self.read, daemon=True)+ self.reader.start()+ self.sequence = 0+ try:+ self.rpc('initialize', {'protocolVersion': '2025-06-18', 'capabilities': {},+ 'clientInfo': {'name': 'batch-retrieval-eval', 'version': '1'}})+ except BaseException:+ self.close()+ raise++ def read(self):+ for line in self.child.stdout:+ self.inbox.put(line)+ self.inbox.put(None)++ def rpc(self, method, params):+ self.sequence += 1+ sent = wire({'jsonrpc': '2.0', 'id': self.sequence, 'method': method, 'params': params})+ self.child.stdin.write(sent)+ self.child.stdin.flush()+ try:+ received = self.inbox.get(timeout=45)+ except queue.Empty:+ raise RuntimeError('MCP response deadline exceeded')+ if received is None:+ raise RuntimeError('MCP stdout closed unexpectedly')+ reply = json.loads(received)+ if reply.get('id') != self.sequence or 'error' in reply:+ raise ValueError('MCP response ID/error: ' + received)+ return sent, received, reply['result']++ def call(self, args):+ start = time.perf_counter_ns()+ sent, received, result = self.rpc('tools/call', {'name': 'xerj_batch_search', 'arguments': args})+ elapsed = (time.perf_counter_ns() - start) / 1e6+ if result.get('isError'):+ raise ValueError('batch-wide MCP error: ' + wire(result))+ return sent, received, json.loads(result['content'][0]['text']), elapsed++ def close(self):+ self.child.stdin.close()+ try:+ self.child.wait(timeout=5)+ except subprocess.TimeoutExpired:+ stop(self.child)+ self.child.stdout.close()+ self.log.close()+ self.reader.join(timeout=1)+ if self.child.returncode != 0:+ raise RuntimeError('MCP exit ' + str(self.child.returncode))+++def cli_call(binary, url, work, env, args):+ sent = wire(args)+ start = time.perf_counter_ns()+ result = subprocess.run([str(binary), 'batch-search', '--input', '-', '--url', url],+ input=sent, capture_output=True, text=True, cwd=work, env=env, timeout=45)+ elapsed = (time.perf_counter_ns() - start) / 1e6+ response = json.loads(result.stdout) if result.stdout else {}+ rows = ordered_rows(response, args['queries'])+ expected_exit = 3 if any(r['status'] == 'error' for r in rows) else 0+ if result.returncode != expected_exit:+ raise ValueError('CLI failed: ' + result.stderr)+ return sent, result.stdout, response, elapsed+++def trial(call, cases, batch, encoding):+ groups = [cases] if batch else [[c] for c in cases]+ calls, rows = [], []+ # No scoring, hashing or tokenization inside the timed task loop.+ start = time.perf_counter_ns()- captures = [call({'index': INDEX, 'size': 3, 'queries': [c['input'] for c in group]})++ captures = [call({'index': INDEX, 'size': 3, 'max_tokens': MAX_TOKENS, 'queries': [c['input'] for c in group]})+ for group in groups]+ elapsed = (time.perf_counter_ns() - start) / 1e6+ for group, (sent, received, response, call_ms) in zip(groups, captures):+ rows.extend(ordered_rows(response, [c['input'] for c in group]))+ calls.append({'elapsed_ms': call_ms, 'request_bytes': len(sent.encode()),+ 'response_bytes': len(received.encode()),+ 'input_bpe_tokens': len(encoding.encode(sent, disallowed_special=())),+ 'output_bpe_tokens': len(encoding.encode(received, disallowed_special=())),+ 'request_sha256': sha(sent.encode()), 'response_sha256': sha(received.encode())})+ scores = [score(c, r) for c, r in zip(cases, rows)]+ return {'task_elapsed_ms': elapsed, 'calls': calls, 'items': scores}, rows+++def summarize(trials):+ first = trials[0]['items']+ by_kind = {kind: {'items': sum(i['kind'] == kind for i in first),+ 'correct': sum(i['correct'] for i in first if i['kind'] == kind)}+ for kind in sorted({i['kind'] for i in first})}+ return {'by_kind_first_trial': by_kind,+ 'retrieval_items_per_trial': sum(i['kind'] != 'invalid' for i in first),+ 'retrieval_correct_per_trial': [sum(i['correct'] for i in t['items']+ if i['kind'] != 'invalid') for t in trials],+ 'task_ms_median': statistics.median(t['task_elapsed_ms'] for t in trials),+ 'task_ms_min': min(t['task_elapsed_ms'] for t in trials),+ 'task_ms_max': max(t['task_elapsed_ms'] for t in trials),+ 'tool_calls_per_trial': len(trials[0]['calls']),+ **{key + '_per_trial': [sum(c[key] for c in t['calls']) for t in trials]+ for key in ('input_bpe_tokens', 'output_bpe_tokens', 'request_bytes', 'response_bytes')},+ 'correct_items_per_trial': [sum(i['correct'] for i in t['items']) for t in trials],+ 'abstain_items_per_trial': [sum(i['status'] == 'abstain' for i in t['items']) for t in trials],+ 'error_items_per_trial': [sum(i['status'] == 'error' for i in t['items']) for t in trials]}+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--pack', type=Path, required=True)+ parser.add_argument('--binary', type=Path, required=True)+ parser.add_argument('--engine-commit', required=True, help='source commit used to build --binary (operator declaration)')+ parser.add_argument('--output', type=Path, required=True, help='new directory; refuses existing paths')+ parser.add_argument('--repeats', type=int, default=5)+ args = parser.parse_args()+ if args.repeats < 2:+ parser.error('--repeats must be at least 2')+ if args.output.exists():+ parser.error('--output already exists; choose a new directory (nothing overwritten)')+ # All input and dependencies are validated before node startup or output publication.+ import tiktoken+ encoding = tiktoken.get_encoding('cl100k_base')+ records, manifest = read_pack(args.pack)+ case_bytes = (HERE / 'cases.json').read_bytes()+ cases = json.loads(case_bytes)+ validate_cases(cases, records)+ binary_data = args.binary.resolve(strict=True).read_bytes()+ binary_sha = sha(binary_data)+ env = child_env()+ host = hardware()+ args.output.mkdir(parents=True, exist_ok=False)+ report = {'schema_version': 1, 'date_utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),+ 'binary_sha256': binary_sha,+ 'engine_source_commit_declared': args.engine_commit,+ 'harness_commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip(),+ 'harness_dirty': bool(subprocess.check_output(['git', 'status', '--porcelain'], cwd=ROOT)),+ 'platform': platform.platform(), 'cpu': platform.processor(), 'logical_cpus': os.cpu_count(),+ 'hardware': host,+ 'python': platform.python_version(), 'xerj_num_cpus': 4,+ 'tokenizer': {'package': 'tiktoken', 'version': importlib.metadata.version('tiktoken'),+ 'encoding': encoding.name, 'scope': 'exact CLI stdin/stdout or MCP tools/call JSON lines'},+ 'pack_tag': PACK_TAG, 'pack_sha256': PACK_SHA256, 'manifest': manifest,+ 'cases_sha256': sha(case_bytes), 'repeats': args.repeats,+ 'protocol': {'concurrency': 1, 'warmups_per_arm': 1, 'cache': 'warm; no cache flush',+ 'order': 'alternate batch/single by repeat; CLI then MCP',+ 'baseline': 'same xerj_batch_search adapter, one-item envelope per call',+ 'indexing': 'full pack; explicit keyword id/aliases, text title/body; dynamic=false',+ 'node': 'fresh private loopback node; lexical default; no model or reranker',+ 'cli': 'process startup included per call',- 'mcp': 'one persistent session; initialize excluded', 'size': 3}, 'arms': {}}++ 'mcp': 'one persistent session; initialize excluded', 'size': 3,++ 'version': 2, 'max_tokens': MAX_TOKENS,++ 'budget_tokenizer': 'standard-uax29-words',++ 'budget_policy': 'fail if response budgeting binds; require full evidence'}, 'arms': {}}+ with tempfile.TemporaryDirectory(prefix='xerj-batch-retrieval-') as temp:+ work = Path(temp)+ try:+ # Execute the same private byte snapshot we hashed, even if Cargo+ # or another operator replaces the original executable during a run.+ binary = freeze_binary(binary_data, work)+ report['binary_version'] = subprocess.check_output(+ [str(binary), '--version'], text=True, cwd=work, env=env).strip()+ with node(binary, work, env) as url:+ ingest(url, records)+ reference = None+ for transport in ('cli', 'mcp'):+ mcp = MCP(binary, url, work, env) if transport == 'mcp' else None+ try:+ call = mcp.call if mcp else lambda a: cli_call(binary, url, work, env, a)+ trials = {'batch': [], 'single': []}+ for repeat in range(-1, args.repeats):+ for mode in (('batch', 'single') if repeat % 2 == 0 else ('single', 'batch')):+ result, rows = trial(call, cases, mode == 'batch', encoding)+ signature = evidence_signature(rows)+ if reference is None:+ reference = signature+ elif signature != reference:+ raise ValueError('ranked evidence/citation/outcome parity failure')+ if repeat >= 0:+ trials[mode].append(result)+ print(transport, mode, repeat + 1, 'correct',+ sum(i['correct'] for i in result['items']), '/', len(cases), flush=True)+ for mode, values in trials.items():+ report['arms'][transport + '_' + mode] = {'summary': summarize(values), 'trials': values}+ finally:+ if mcp:+ mcp.close()+ report['final_document_count'] = request(url, 'GET', '/' + INDEX + '/_count')['count']+ if report['final_document_count'] != len(records):+ raise ValueError('benchmark changed document count')+ with node(binary, work, env) as url:+ report['restart_document_count'] = request(url, 'GET', '/' + INDEX + '/_count')['count']+ if report['restart_document_count'] != len(records):+ raise ValueError('document count changed across graceful restart')+ finally:+ for name in ('node.log', 'mcp.log'):+ if (work / name).exists():+ (args.output / name).write_bytes((work / name).read_bytes())+ report['quality_pass'] = all(i['correct'] for arm in report['arms'].values()+ for t in arm['trials'] for i in t['items'])+ report['parity_pass'] = True+ report['graceful_shutdown'] = True+ staging = args.output / 'results.json.tmp'+ staging.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')+ staging.replace(args.output / 'results.json')+ print(json.dumps({k: a['summary'] for k, a in report['arms'].items()}, indent=2))+ return 0 if report['quality_pass'] else 1+++if __name__ == '__main__':+ try:+ sys.exit(main())+ except (ValueError, RuntimeError, OSError, subprocess.SubprocessError) as error:+ print('error:', error, file=sys.stderr)+ sys.exit(1)diff --cc tools/benchmarks/batch-retrieval/test_run.pyindex c5eb50fac,000000000..337966812mode 100644,000000..100644--- a/tools/benchmarks/batch-retrieval/test_run.py+++ b/tools/benchmarks/batch-retrieval/test_run.py@@@ -1,100 -1,0 +1,105 @@@+import importlib.util+import unittest+import tempfile+from pathlib import Path++spec = importlib.util.spec_from_file_location('batch_eval', Path(__file__).with_name('run.py'))+eval = importlib.util.module_from_spec(spec)+spec.loader.exec_module(eval)+++def hit(identifier='known', citation_id=None):+ return {'citation': {'_index': 'advisories', '_id': citation_id or identifier},+ 'hit': {'_index': 'advisories', '_id': identifier, '_source': {'id': identifier}}}+++class ScoringTests(unittest.TestCase):+ def test_executed_snapshot_does_not_reopen_mutable_binary(self):+ with tempfile.TemporaryDirectory() as temp:+ work = Path(temp)+ original = work / 'input'+ original.write_bytes(b'first binary')+ data = original.read_bytes()+ original.write_bytes(b'replacement binary')+ frozen = eval.freeze_binary(data, work)+ self.assertEqual(frozen.read_bytes(), data)+ self.assertEqual(eval.sha(frozen.read_bytes()), eval.sha(data))+ self.assertTrue(frozen.stat().st_mode & 0o100)++ def test_wrong_archive_is_refused_before_parsing(self):+ with tempfile.TemporaryDirectory() as temp:+ pack = Path(temp) / 'pack.zip'+ pack.write_bytes(b'untrusted archive')+ with self.assertRaisesRegex(ValueError, 'SHA256 mismatch'):+ eval.read_pack(pack)++ def test_grouping_counts_exact_wire_and_preserves_duplicates(self):+ cases = [{'kind': 'missing', 'input': {'key': 'same', 'identifier': 'no', 'field': 'id'},+ 'expected_ids': []}] * 2+ def call(args):++ self.assertEqual(args["max_tokens"], 1_000_000)+ response = {'results': [{'position': i, 'key': 'same', 'status': 'abstain',+ 'abstain': True, 'reason': 'no_hits'}+ for i in range(len(args['queries']))]}+ return eval.wire(args), eval.wire(response), response, 1.0+ class Encoding:+ def encode(self, text, **kwargs):+ return list(text)+ batch, _ = eval.trial(call, cases, True, Encoding())+ single, _ = eval.trial(call, cases, False, Encoding())+ self.assertEqual((len(batch['calls']), len(single['calls'])), (1, 2))+ self.assertEqual(len(batch['items']), 2)+ for result in (batch, single):+ self.assertTrue(all(i['correct'] for i in result['items']))+ for receipt in result['calls']:+ self.assertEqual(receipt['input_bpe_tokens'], receipt['request_bytes'])+ self.assertEqual(receipt['output_bpe_tokens'], receipt['response_bytes'])+++ def test_budgeted_evidence_is_refused(self):++ with self.assertRaisesRegex(ValueError, 'full evidence'):++ eval.ordered_rows({'_token_budget': {}, 'results': []}, [])+++ def test_wrong_id_is_not_correct(self):+ case = {'input': {'key': 'q'}, 'kind': 'canonical', 'expected_ids': ['known']}+ row = {'status': 'hits', 'abstain': False, 'hits': [hit('wrong')]}+ self.assertFalse(eval.score(case, row)['correct'])++ def test_error_is_never_a_miss(self):+ case = {'input': {'key': 'q'}, 'kind': 'missing', 'expected_ids': []}+ self.assertFalse(eval.score(case, {'status': 'error', 'error': 'timeout'})['correct'])++ def test_citation_must_identify_actual_hit(self):+ with self.assertRaisesRegex(ValueError, 'citation'):+ eval.score({'input': {'key': 'q'}, 'kind': 'canonical', 'expected_ids': ['known']},+ {'status': 'hits', 'abstain': False, 'hits': [hit(citation_id='wrong')]})++ def test_empty_miss_and_expected_item_error_are_separate(self):+ self.assertTrue(eval.score({'input': {'key': 'q'}, 'kind': 'missing', 'expected_ids': []},+ {'status': 'abstain', 'abstain': True, 'reason': 'no_hits'})['correct'])+ self.assertTrue(eval.score({'input': {'key': 'q'}, 'kind': 'invalid', 'expected_ids': []},+ {'status': 'error', 'error': 'bad query'})['correct'])++ def test_extra_wrong_hit_fails_exact_lookup(self):+ self.assertFalse(eval.score({'input': {'key': 'q'}, 'kind': 'alias', 'expected_ids': ['known']},+ {'status': 'hits', 'abstain': False,+ 'hits': [hit(), hit('wrong')]})['correct'])++ def test_text_uses_labelled_hit_at_k(self):+ self.assertTrue(eval.score({'input': {'key': 'q'}, 'kind': 'text', 'expected_ids': ['known']},+ {'status': 'hits', 'abstain': False,+ 'hits': [hit('other'), hit()]})['correct'])++ def test_reordered_or_missing_positions_refused(self):+ with self.assertRaisesRegex(ValueError, 'position'):+ eval.ordered_rows({'results': [{'position': 1}]}, [{'key': 'x'}])+ with self.assertRaisesRegex(ValueError, 'count'):+ eval.ordered_rows({'results': []}, [{'key': 'x'}])++ def test_different_ranked_evidence_fails_parity(self):+ a = [{'status': 'hits', 'hits': [hit()]}]+ b = [{'status': 'hits', 'hits': [hit('wrong')]}]+ self.assertNotEqual(eval.evidence_signature(a), eval.evidence_signature(b))+++if __name__ == '__main__':+ unittest.main()