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
bench: add pinned rust-vulns batch retrieval evaluation
Jarvisccc159ffecf9
diff --git a/.github/workflows/batch-retrieval.yml b/.github/workflows/batch-retrieval.ymlnew file mode 100644index 000000000..997067e54--- /dev/null+++ b/.github/workflows/batch-retrieval.yml@@ -0,0 +1,30 @@+name: Batch retrieval harness++on:+ pull_request:+ paths:+ - 'tools/benchmarks/batch-retrieval/**'+ - '.github/workflows/batch-retrieval.yml'+ push:+ branches: [main]+ paths:+ - 'tools/benchmarks/batch-retrieval/**'+ - '.github/workflows/batch-retrieval.yml'++permissions:+ contents: read++concurrency:+ group: batch-retrieval-${{ github.ref }}+ cancel-in-progress: true++jobs:+ harness:+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with:+ python-version: '3.12'+ - run: python3 tools/benchmarks/batch-retrieval/test_run.pydiff --git a/docs/recipes/batch-search.md b/docs/recipes/batch-search.mdindex eb382858d..e628c1ead 100644--- a/docs/recipes/batch-search.md+++ b/docs/recipes/batch-search.md@@ -72,8 +72,15 @@ The batch path uses `_msearch` rather than repeated `_search` calls. Plain-textitems reuse the mapping-aware search query and code-path demotion; the engine's`_msearch` renderer returns stored evidence, not `_search`'s extracted `_passage`field. Rerank/judge and per-item scopes/options are not exposed here. No latency,-model-token savings, rust-vulns accuracy or confidence claim is made.+model-token savings or confidence claim is made by this recipe.++For a pinned rust-vulns retrieval evaluation comparing 50-item batches with+one-item calls over both CLI and persistent MCP, see+[the batch retrieval harness](../../tools/benchmarks/batch-retrieval/README.md).+It measures labelled ID lookup, known-item text hit@3, retrieval abstentions,+warm task latency and payload BPE tokens; these are not generated-answer or+complete agent-task cost measurements.This is the batch retrieval part of [#1801](https://github.com/xerj-org/xerj/issues/1801).-Full answer/abstain calibration, alias-aware ID discovery and the requested-rust-vulns evaluation remain separate work; this does not close that issue.+Full answer/abstain calibration and alias-aware ID discovery remain separate+work; the adapter and retrieval evaluation do not close that issue.diff --git a/scripts/bench/README.md b/scripts/bench/README.mdindex e248bef62..25a5cbd7a 100644--- a/scripts/bench/README.md+++ b/scripts/bench/README.md@@ -140,6 +140,7 @@ So that every headline maps to a runnable thing from one place:| Claim | Harness in this repo ||---|---|+| Batch vs one-item retrieval on a pinned rust-vulns pack (CLI/MCP correctness, warm latency and payload BPE tokens; not generated-answer accuracy) | `tools/benchmarks/batch-retrieval/` (`run.py`; protocol and reproduction in its README) || 2.7x / 26x / up-to-278x fewer output tokens (reference coding) | `docs/case-studies/reference-coding/CASE_STUDY.md` + the 3-arm Harbor harness `tools/benchmarks/harbor-3arm/` (`run_matrix.sh`) || nDCG@10 rows (BM25 0.6572 / MiniLM 0.6764 / hybrid 0.6993 on SciFact) | `benchmarks/beir-hybrid/` (`load.py`, `eval.py`, raw output in `results/`) || Banking77 0.933 / SMS spam 0.983 decisions-from-history | `benchmarks/decisions-as-retrieval/` (`eval.py`, raw output in `results/`) |diff --git a/tools/benchmarks/batch-retrieval/README.md b/tools/benchmarks/batch-retrieval/README.mdnew file mode 100644index 000000000..8ab194ed3--- /dev/null+++ b/tools/benchmarks/batch-retrieval/README.md@@ -0,0 +1,137 @@+# 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 use that same binary.++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.++Both request `size: 3`, no `max_tokens`. All requests run at concurrency one.+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.diff --git a/tools/benchmarks/batch-retrieval/cases.json b/tools/benchmarks/batch-retrieval/cases.jsonnew file mode 100644index 000000000..9419bb035--- /dev/null+++ b/tools/benchmarks/batch-retrieval/cases.json@@ -0,0 +1,529 @@+[+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-0",+ "identifier": "RUSTSEC-2021-0003",+ "field": "id"+ },+ "expected_ids": [+ "RUSTSEC-2021-0003"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-1",+ "identifier": "RUSTSEC-2019-0012",+ "field": "id"+ },+ "expected_ids": [+ "RUSTSEC-2019-0012"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-2",+ "identifier": "RUSTSEC-2022-0013",+ "field": "id"+ },+ "expected_ids": [+ "RUSTSEC-2022-0013"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-3",+ "identifier": "RUSTSEC-2020-0071",+ "field": "id"+ },+ "expected_ids": [+ "RUSTSEC-2020-0071"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-4",+ "identifier": "RUSTSEC-2020-0019",+ "field": "id"+ },+ "expected_ids": [+ "RUSTSEC-2020-0019"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-5",+ "identifier": "RUSTSEC-2018-0018",+ "field": "id"+ },+ "expected_ids": [+ "RUSTSEC-2018-0018"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-6",+ "identifier": "RUSTSEC-2019-0031",+ "field": "id"+ },+ "expected_ids": [+ "RUSTSEC-2019-0031"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-7",+ "identifier": "RUSTSEC-2023-0005",+ "field": "id"+ },+ "expected_ids": [+ "RUSTSEC-2023-0005"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-8",+ "identifier": "RUSTSEC-2024-0346",+ "field": "id"+ },+ "expected_ids": [+ "RUSTSEC-2024-0346"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-9",+ "identifier": "GHSA-9gqx-53gp-c8g3",+ "field": "id"+ },+ "expected_ids": [+ "GHSA-9gqx-53gp-c8g3"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-10",+ "identifier": "GHSA-794x-2rpg-rfgr",+ "field": "id"+ },+ "expected_ids": [+ "GHSA-794x-2rpg-rfgr"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-11",+ "identifier": "RUSTSEC-2025-0152",+ "field": "id"+ },+ "expected_ids": [+ "RUSTSEC-2025-0152"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-12",+ "identifier": "RUSTSEC-2026-0028",+ "field": "id"+ },+ "expected_ids": [+ "RUSTSEC-2026-0028"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-13",+ "identifier": "GHSA-52h2-m2cf-9jh6",+ "field": "id"+ },+ "expected_ids": [+ "GHSA-52h2-m2cf-9jh6"+ ]+ },+ {+ "kind": "canonical",+ "input": {+ "key": "canonical-14",+ "identifier": "RUSTSEC-2024-0448",+ "field": "id"+ },+ "expected_ids": [+ "RUSTSEC-2024-0448"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-0",+ "identifier": "CVE-2022-23523",+ "field": "aliases"+ },+ "expected_ids": [+ "GHSA-52h2-m2cf-9jh6"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-1",+ "identifier": "GHSA-6v2j-vr4h-f632",+ "field": "aliases"+ },+ "expected_ids": [+ "RUSTSEC-2025-0152"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-2",+ "identifier": "CVE-2021-28031",+ "field": "aliases"+ },+ "expected_ids": [+ "RUSTSEC-2021-0030"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-3",+ "identifier": "GHSA-3qm2-rfqw-fmrw",+ "field": "aliases"+ },+ "expected_ids": [+ "RUSTSEC-2021-0030"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-4",+ "identifier": "CVE-2021-28307",+ "field": "aliases"+ },+ "expected_ids": [+ "RUSTSEC-2021-0038"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-5",+ "identifier": "GHSA-7qcc-g2m9-8533",+ "field": "aliases"+ },+ "expected_ids": [+ "RUSTSEC-2021-0038"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-6",+ "identifier": "CVE-2026-75857",+ "field": "aliases"+ },+ "expected_ids": [+ "GHSA-g29h-pfmp-qp9r"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-7",+ "identifier": "GHSA-x958-rvg6-956w",+ "field": "aliases"+ },+ "expected_ids": [+ "RUSTSEC-2025-0041"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-8",+ "identifier": "CVE-2026-35373",+ "field": "aliases"+ },+ "expected_ids": [+ "GHSA-jcjr-rh8q-7xqf"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-9",+ "identifier": "GHSA-5wjr-9356-4wc8",+ "field": "aliases"+ },+ "expected_ids": [+ "RUSTSEC-2026-0384"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-10",+ "identifier": "CVE-2024-36400",+ "field": "aliases"+ },+ "expected_ids": [+ "RUSTSEC-2024-0343"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-11",+ "identifier": "GHSA-9hc7-6w9r-wj94",+ "field": "aliases"+ },+ "expected_ids": [+ "RUSTSEC-2024-0343"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-12",+ "identifier": "CVE-2019-16140",+ "field": "aliases"+ },+ "expected_ids": [+ "RUSTSEC-2019-0016"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-13",+ "identifier": "GHSA-xg7c-246g-6qpv",+ "field": "aliases"+ },+ "expected_ids": [+ "RUSTSEC-2026-0219"+ ]+ },+ {+ "kind": "alias",+ "input": {+ "key": "alias-14",+ "identifier": "CVE-2026-35364",+ "field": "aliases"+ },+ "expected_ids": [+ "GHSA-m976-87wm-48fm"+ ]+ },+ {+ "kind": "missing",+ "input": {+ "key": "missing-0",+ "identifier": "RUSTSEC-2021-00030",+ "field": "id"+ },+ "expected_ids": []+ },+ {+ "kind": "missing",+ "input": {+ "key": "missing-1",+ "identifier": "RUSTSEC-2019-00120",+ "field": "id"+ },+ "expected_ids": []+ },+ {+ "kind": "missing",+ "input": {+ "key": "missing-2",+ "identifier": "RUSTSEC-2022-00130",+ "field": "id"+ },+ "expected_ids": []+ },+ {+ "kind": "missing",+ "input": {+ "key": "missing-3",+ "identifier": "RUSTSEC-2020-00710",+ "field": "id"+ },+ "expected_ids": []+ },+ {+ "kind": "missing",+ "input": {+ "key": "missing-4",+ "identifier": "RUSTSEC-2020-00190",+ "field": "id"+ },+ "expected_ids": []+ },+ {+ "kind": "missing",+ "input": {+ "key": "missing-5",+ "identifier": "RUSTSEC-2018-00180",+ "field": "id"+ },+ "expected_ids": []+ },+ {+ "kind": "missing",+ "input": {+ "key": "missing-6",+ "identifier": "RUSTSEC-2019-00310",+ "field": "id"+ },+ "expected_ids": []+ },+ {+ "kind": "missing",+ "input": {+ "key": "missing-7",+ "identifier": "RUSTSEC-2023-00050",+ "field": "id"+ },+ "expected_ids": []+ },+ {+ "kind": "missing",+ "input": {+ "key": "missing-8",+ "identifier": "RUSTSEC-2024-03460",+ "field": "id"+ },+ "expected_ids": []+ },+ {+ "kind": "missing",+ "input": {+ "key": "missing-9",+ "identifier": "GHSA-9gqx-53gp-c8g30",+ "field": "id"+ },+ "expected_ids": []+ },+ {+ "kind": "text",+ "input": {+ "key": "text-0",+ "query": "SmallVec insert_many buffer overflow"+ },+ "expected_ids": [+ "RUSTSEC-2021-0003"+ ],+ "label_basis": "Buffer overflow in SmallVec::insert_many"+ },+ {+ "kind": "text",+ "input": {+ "key": "text-1",+ "query": "SmallVec grow memory corruption"+ },+ "expected_ids": [+ "RUSTSEC-2019-0012"+ ],+ "label_basis": "Memory corruption in SmallVec::grow()"+ },+ {+ "kind": "text",+ "input": {+ "key": "text-2",+ "query": "regex large repetitions empty sub-expressions parsing"+ },+ "expected_ids": [+ "RUSTSEC-2022-0013"+ ],+ "label_basis": "Regexes with large repetitions on empty sub-expressions take a very long time to parse"+ },+ {+ "kind": "text",+ "input": {+ "key": "text-3",+ "query": "time crate potential segfault"+ },+ "expected_ids": [+ "RUSTSEC-2020-0071"+ ],+ "label_basis": "Potential segfault in the time crate"+ },+ {+ "kind": "text",+ "input": {+ "key": "text-4",+ "query": "tokio rustls reads excessive memory usage"+ },+ "expected_ids": [+ "RUSTSEC-2020-0019"+ ],+ "label_basis": "tokio-rustls reads may cause excessive memory usage"+ },+ {+ "kind": "text",+ "input": {+ "key": "text-5",+ "query": "smallvec uninitialized value any type"+ },+ "expected_ids": [+ "RUSTSEC-2018-0018"+ ],+ "label_basis": "smallvec creates uninitialized value of any type"+ },+ {+ "kind": "text",+ "input": {+ "key": "text-6",+ "query": "spin no longer actively maintained"+ },+ "expected_ids": [+ "RUSTSEC-2019-0031"+ ],+ "label_basis": "spin is no longer actively maintained"+ },+ {+ "kind": "text",+ "input": {+ "key": "text-7",+ "query": "tokio ReadHalf unsplit unsound"+ },+ "expected_ids": [+ "RUSTSEC-2023-0005"+ ],+ "label_basis": "`tokio::io::ReadHalf<T>::unsplit` is Unsound"+ },+ {+ "kind": "duplicate",+ "input": {+ "key": "canonical-0",+ "identifier": "RUSTSEC-2021-0003",+ "field": "id"+ },+ "expected_ids": [+ "RUSTSEC-2021-0003"+ ]+ },+ {+ "kind": "invalid",+ "input": {+ "key": "invalid",+ "query": 17+ },+ "expected_ids": []+ }+]diff --git a/tools/benchmarks/batch-retrieval/requirements.txt b/tools/benchmarks/batch-retrieval/requirements.txtnew file mode 100644index 000000000..f4432a2a7--- /dev/null+++ b/tools/benchmarks/batch-retrieval/requirements.txt@@ -0,0 +1 @@+tiktoken==0.12.0diff --git a/tools/benchmarks/batch-retrieval/run.py b/tools/benchmarks/batch-retrieval/run.pynew file mode 100644index 000000000..8fdd012cd--- /dev/null+++ b/tools/benchmarks/batch-retrieval/run.py@@ -0,0 +1,438 @@+#!/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'+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 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):+ 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]})+ 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 = args.binary.resolve(strict=True)+ binary_sha = sha(binary.read_bytes())+ env = child_env()+ version = subprocess.check_output([str(binary), '--version'], text=True, env=env).strip()+ 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_version': version, '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': {}}+ with tempfile.TemporaryDirectory(prefix='xerj-batch-retrieval-') as temp:+ work = Path(temp)+ try:+ 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 --git a/tools/benchmarks/batch-retrieval/test_run.py b/tools/benchmarks/batch-retrieval/test_run.pynew file mode 100644index 000000000..af4863462--- /dev/null+++ b/tools/benchmarks/batch-retrieval/test_run.py@@ -0,0 +1,88 @@+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_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):+ 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_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()