← Back to Pull requests

feat: add reproducible RAG retrieval benchmark #17

Open
Xander-Xai opened this pull request with 3013 lines diff across 27 files
View on GitHub
Xander-Xai Xander-Xai commented on Oct 02, 2026 05:31 UTC
Author

Why

The repository had implementation evidence and local runtime evidence, but no
reproducible retrieval-quality evidence. Every retrieval-quality number was
either absent or untraceable, which made retrieval claims unfalsifiable.

This PR builds the measurement harness and deliberately ships no benchmark
result: in this environment no retrieval backend and no corpus are available, so
every configuration honestly reports BLOCKED with a reason instead of a number.

What

  • deterministic, dependency-light retrieval metrics (no RAGAS evaluator)

  • configuration matrix (BM25 / dense / hybrid+RRF / +BiEncoder / +CrossEncoder)

  • per-stage latency with null (never 0) for stages that never ran

  • automatic provenance (git sha + dirty flag, dataset/config sha256, environment)

  • artifact set per run: metadata.json, environment.json,

  • retrieval_metrics.json, latency_metrics.json, per_query_results.jsonl,
    report.md (+ comparison.md when >= 2 configs execute)
  • CI-safe deterministic tests (48) using a fixture retriever
  • python -m benchmarks.retrieval_benchmark --list-configs
    python -m benchmarks.retrieval_benchmark --config bm25 --limit 5
    

    Metrics

  • Recall@1 / 3 / 5 / 10

  • HitRate@1 / 3 / 5 / 10

  • MRR@10

  • NDCG@10 (binary relevance — the dataset has no graded relevance)
  • Current breakdown

  • overall

  • business_type

  • difficulty
  • Not included:

  • visual_required: missing for 301/301 samples

  • complexity_label: not stored (0/301)
  • Neither label was fabricated. See docs/benchmark-data-quality.md.

    Relevance truth

    The golden set has no doc_id / chunk_id / sample_id, so matching is
    level2_normalized_exact_text: NFKC + whitespace normalization + trim. Stable-id
    matching is implemented and will be preferred automatically if a future dataset
    exposes ids. No LLM judge, embedding similarity threshold or fuzzy threshold is
    used anywhere in the canonical path.

    Current status: framework REPO_VERIFIED, result PENDING

    | config | status | reason |
    |---|---|---|
    | bm25 | BLOCKED | Elasticsearch unreachable; no corpus containing the ground truth |
    | dense | BLOCKED | Qdrant unreachable; BGE weights absent; no corpus |
    | hybrid_rrf | BLOCKED | both backends + corpus unavailable |
    | hybrid_rrf_biencoder | BLOCKED | + BiEncoder weights absent |
    | hybrid_rrf_biencoder_crossencoder | BLOCKED | + CrossEncoder weights not wired to a validated path |

    A real benchmark additionally requires a corpus that contains the golden-set
    passages. Indexing the ground truth itself would make every configuration score
    recall 1.0 by construction, so that shortcut is deliberately refused and recorded
    as corpus_does_not_contain_ground_truth.

    Evidence boundary

    Repository benchmark results are not historical production metrics. No benchmark
    number is published in this PR, and no configuration reports EXECUTED.

    Validation

    Real results on ffca11c:

    repo consistency      : Repository consistency check passed.
    benchmark tests       : 48 passed
    consistency tests     : 73 passed
    evaluation tests      : 64 passed
    full tests            : 940 passed, 15 skipped   (baseline was 892 passed, 15 skipped)
    ruff check            : All checks passed!
    ruff format --check   : 245 files already formatted
    compileall            : OK
    git diff --check      : clean
    

    Smoke runs (--limit 5 and --limit 20, --allow-dirty) produced a complete
    artifact set with executed: none and the blocking reasons recorded.

    Not included

    No Kubernetes / Kafka / GraphRAG / Agent / MCP / SSO, no microservice rewrite,
    no RAGAS evaluator expansion, no 4B/14B serving benchmark, no label fabrication,
    no reuse of historical production numbers.

    Diff: 3013 lines (+3013 / -0) across 27 files Reviewer: Xander-Xai Review duration: 38m
    All Vouch review confidence checks passed
    Residual risk 0.33 = Change Risk (0.86) × (1 − Review Confidence (0.61)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.86 · 3013 lines diff across 27 files
    0.86
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.85 · 5 substantive comment(s)
    0.85
    Model 3 · Review Timing & Attention
    Session adequacy: 51% · Reviewer familiarity: 50%
    61%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    31 items
    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 02, 2026 05:34 UTC
    Code Review
    benchmarks/retrieval_benchmark.py:1
    @@ -0,0 +1,210 @@
    +"""Command-line entry point for the retrieval benchmark.
    +
    +Examples
    +--------
    +List what the current environment can actually execute::
    +
    +    python -m benchmarks.retrieval_benchmark --list-configs
    +
    +Attempt a real run (writes an artifact set even when everything is blocked)::
    +
    +    python -m benchmarks.retrieval_benchmark --config bm25 --limit 5
    +
    +The CLI has no flag that installs a fake retriever. A synthetic retriever can
    +only be supplied programmatically by tests, and any run that used one is flagged
    +in its artifacts.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import sys
    +from pathlib import Path
    +
    +from benchmarks import backends, report
    +from benchmarks.dataset import (
    +    DEFAULT_DATASET_PATH,
    +    DatasetError,
    +    bucket_coverage,
    +    load_queries,
    +    load_rows,
    +    sample_ids_hash,
    +    sha256_file,
    +)
    +from benchmarks.models import STATUS_EXECUTED
    +from benchmarks.provenance import (
    +    collect_environment,
    +    git_provenance,
    +    new_run_id,
    +    now_utc,
    +    render_environment,
    +    sha256_json,
    +    write_gitignore_entry,
    +)
    +from benchmarks.runner import DEFAULT_TOP_K, run_configuration, summarize_run, write_per_query_jsonl
    +
    +DEFAULT_OUTPUT_DIR = "artifacts/benchmarks"
    +
    +
    +def build_parser() -> argparse.ArgumentParser:
    +    parser = argparse.ArgumentParser(
    +        prog="python -m benchmarks.retrieval_benchmark",
    +        description="Deterministic retrieval benchmark (no RAGAS evaluator required).",
    +    )
    +    parser.add_argument("--config", help="single configuration to run")
    +    parser.add_argument("--configs", help="comma-separated configurations to run")
    +    parser.add_argument("--dataset", default=DEFAULT_DATASET_PATH, help="golden set JSONL path")
    +    parser.add_argument("--limit", type=int, default=None, help="only use the first N samples")
    +    parser.add_argument("--sample-id", action="append", default=None, help="run only this sample id (repeatable)")
    +    parser.add_argument("--top-k", type=int, default=DEFAULT_TOP_K, help="retrieval depth (default 10)")

    <sub><sub>!P1 Badge</sub></sub> Require retrieval depth to cover every reported cutoff

    When --top-k is less than 10 (for example, --top-k 5), the runner retrieves only that many items but still labels metrics as Recall@10, MRR@10, and NDCG@10. Relevant results at ranks 6–10 can never be observed, so these values are silently understated. Reject depths below the largest metric cutoff or retrieve at least 10 items independently of the requested output depth.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 02, 2026 05:34 UTC
    Code Review
    benchmarks/backends.py:1
    @@ -0,0 +1,256 @@
    +"""Retrieval backends for the benchmark.
    +
    +Every backend is probed before it is used, and a backend that cannot answer a
    +real probe is reported as unavailable. The harness never substitutes a stand-in
    +retriever for a missing one: a benchmark that silently ranks with a fake backend
    +would produce numbers that look like retrieval quality while measuring nothing.
    +
    +Two independent things are required for a meaningful measurement:
    +
    +1. a **live retrieval service** (Elasticsearch / Qdrant) and real model assets;
    +2. a **corpus that actually contains the ground-truth passages**.
    +
    +Requirement 2 is easy to overlook. The golden set stores ground truth as passage
    +*text*; the operator corpus is their own private material. Indexing the golden
    +set passages themselves and then measuring recall would be self-referential —
    +every configuration would trivially reach recall 1.0 — so this module refuses that
    +shortcut and reports the corpus requirement explicitly instead.
    +"""
    +
    +from __future__ import annotations
    +
    +import json
    +import socket
    +import urllib.error
    +import urllib.request
    +from dataclasses import dataclass
    +from typing import Any
    +
    +from benchmarks.models import BackendAvailability
    +
    +PROBE_TIMEOUT_SECONDS = 2.0
    +
    +REASON_OK = "available"
    +REASON_SERVICE_UNREACHABLE = "service_unreachable"
    +REASON_SERVICE_NO_DATA = "service_reachable_but_empty"
    +REASON_MODEL_UNAVAILABLE = "model_assets_unavailable"
    +REASON_CORPUS_UNRESOLVED = "corpus_does_not_contain_ground_truth"
    +REASON_NOT_CONFIGURED = "not_configured"
    +
    +
    +class BenchmarkUnavailable(RuntimeError):
    +    """Raised when a backend is asked to retrieve without being available."""
    +
    +
    +def _http_get(url: str) -> tuple[bool, Any]:
    +    """Return ``(ok, payload)`` for a short-timeout GET."""
    +    try:
    +        with urllib.request.urlopen(url, timeout=PROBE_TIMEOUT_SECONDS) as response:  # noqa: S310 - operator-configured http(s) endpoint
    +            body = response.read()
    +    except (urllib.error.URLError, OSError, ValueError):

    <sub><sub>!P2 Badge</sub></sub> Authenticate the Elasticsearch availability probe

    In the repository's standard Compose deployment, Elasticsearch has xpack.security.enabled=true and requires the elastic credentials, but this request ignores ELASTICSEARCH_USERNAME and ELASTICSEARCH_PASSWORD. The resulting HTTP 401 is caught as an unavailable service, so a healthy secured Elasticsearch instance is falsely reported as unreachable even though the production BM25Retriever supports basic authentication.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 02, 2026 05:34 UTC
    Code Review
    benchmarks/retrieval_benchmark.py:1
    @@ -0,0 +1,210 @@
    +"""Command-line entry point for the retrieval benchmark.
    +
    +Examples
    +--------
    +List what the current environment can actually execute::
    +
    +    python -m benchmarks.retrieval_benchmark --list-configs
    +
    +Attempt a real run (writes an artifact set even when everything is blocked)::
    +
    +    python -m benchmarks.retrieval_benchmark --config bm25 --limit 5
    +
    +The CLI has no flag that installs a fake retriever. A synthetic retriever can
    +only be supplied programmatically by tests, and any run that used one is flagged
    +in its artifacts.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import sys
    +from pathlib import Path
    +
    +from benchmarks import backends, report
    +from benchmarks.dataset import (
    +    DEFAULT_DATASET_PATH,
    +    DatasetError,
    +    bucket_coverage,
    +    load_queries,
    +    load_rows,
    +    sample_ids_hash,
    +    sha256_file,
    +)
    +from benchmarks.models import STATUS_EXECUTED
    +from benchmarks.provenance import (
    +    collect_environment,
    +    git_provenance,
    +    new_run_id,
    +    now_utc,
    +    render_environment,
    +    sha256_json,
    +    write_gitignore_entry,
    +)
    +from benchmarks.runner import DEFAULT_TOP_K, run_configuration, summarize_run, write_per_query_jsonl
    +
    +DEFAULT_OUTPUT_DIR = "artifacts/benchmarks"
    +
    +
    +def build_parser() -> argparse.ArgumentParser:
    +    parser = argparse.ArgumentParser(
    +        prog="python -m benchmarks.retrieval_benchmark",
    +        description="Deterministic retrieval benchmark (no RAGAS evaluator required).",
    +    )
    +    parser.add_argument("--config", help="single configuration to run")
    +    parser.add_argument("--configs", help="comma-separated configurations to run")
    +    parser.add_argument("--dataset", default=DEFAULT_DATASET_PATH, help="golden set JSONL path")
    +    parser.add_argument("--limit", type=int, default=None, help="only use the first N samples")
    +    parser.add_argument("--sample-id", action="append", default=None, help="run only this sample id (repeatable)")
    +    parser.add_argument("--top-k", type=int, default=DEFAULT_TOP_K, help="retrieval depth (default 10)")
    +    parser.add_argument("--output-dir", default=DEFAULT_OUTPUT_DIR, help="artifact root directory")
    +    parser.add_argument(
    +        "--allow-dirty",
    +        action="store_true",
    +        help="allow running with a dirty working tree (recorded as git_dirty=true)",
    +    )
    +    parser.add_argument(
    +        "--require-results",
    +        action="store_true",
    +        help="exit non-zero when no configuration executed (useful to fail CI on blocked runs)",
    +    )
    +    parser.add_argument("--list-configs", action="store_true", help="print configuration availability and exit")
    +    return parser
    +
    +
    +def _resolve_configs(args: argparse.Namespace) -> list[str]:
    +    if args.config and args.configs:
    +        raise SystemExit("use either --config or --configs, not both")
    +    if args.config:
    +        return [args.config]
    +    if args.configs:
    +        return [item.strip() for item in args.configs.split(",") if item.strip()]
    +    return ["bm25", "dense", "hybrid_rrf"]
    +
    +
    +def _print_configs(dataset_queries: int) -> int:
    +    print("configurations (availability probed live):\n")
    +    for name, description in backends.CONFIG_DESCRIPTIONS.items():
    +        availability = backends.evaluate_config(name, dataset_queries)
    +        state = "EXECUTABLE" if availability.available else "BLOCKED"
    +        print(f"  {name:36s} {state:12s} {description}")
    +        if not availability.available:
    +            print(f"  {'':36s} reasons: {availability.describe()}")
    +            if availability.detail:
    +                print(f"  {'':36s} detail:  {availability.detail}")
    +    print("\nNote: a configuration is only reported EXECUTABLE when every required backend")
    +    print("and the benchmark corpus answered a real probe. No stand-in retriever is used.")
    +    return 0
    +
    +
    +def main(argv: list[str] | None = None) -> int:
    +    parser = build_parser()
    +    args = parser.parse_args(argv)
    +
    +    repo_root = Path(__file__).resolve().parents[1]
    +    dataset_path = Path(args.dataset)
    +    if not dataset_path.is_file():
    +        print(f"dataset not found: {dataset_path}", file=sys.stderr)
    +        return 2
    +
    +    try:
    +        rows = load_rows(dataset_path)
    +    except DatasetError as exc:
    +        print(f"dataset error: {exc}", file=sys.stderr)
    +        return 2
    +
    +    if args.list_configs:
    +        return _print_configs(len(rows))
    +
    +    configs = _resolve_configs(args)
    +    unknown = [name for name in configs if name not in backends.CONFIG_DESCRIPTIONS]
    +    if unknown:
    +        print(f"unknown configuration(s): {', '.join(unknown)}", file=sys.stderr)
    +        return 2
    +
    +    git_sha, git_dirty = git_provenance(repo_root)
    +    if git_dirty and not args.allow_dirty:
    +        print(
    +            "refusing to run on a dirty working tree; commit your changes or pass --allow-dirty "
    +            "(the artifact will record git_dirty=true)",
    +            file=sys.stderr,
    +        )
    +        return 3
    +
    +    try:
    +        queries = load_queries(dataset_path, limit=args.limit, sample_ids=args.sample_id)
    +    except DatasetError as exc:
    +        print(f"dataset error: {exc}", file=sys.stderr)
    +        return 2
    +
    +    run_id = new_run_id()
    +    config_payload = {"configs": configs, "top_k": args.top_k, "dataset_sha256": sha256_file(dataset_path)}
    +    metadata = {
    +        "run_id": run_id,
    +        "timestamp_utc": now_utc(),
    +        "git_sha": git_sha,
    +        "git_dirty": git_dirty,
    +        "dataset_path": str(dataset_path),
    +        "dataset_sha256": sha256_file(dataset_path),
    +        "sample_count": len(queries),
    +        "sample_ids_hash": sample_ids_hash(queries),
    +        "config_name": configs[0] if len(configs) == 1 else "multi",
    +        "config_sha256": sha256_json(config_payload),
    +        "requested_configs": configs,
    +        "top_k": args.top_k,
    +        "allow_dirty": bool(args.allow_dirty),
    +        "synthetic_retriever": False,
    +        "results_are_benchmark": True,
    +    }
    +    environment = render_environment(collect_environment())
    +    coverage = bucket_coverage(rows)

    <sub><sub>!P2 Badge</sub></sub> Compute coverage from the selected query subset

    For runs using --limit or --sample-id, rows still contains the entire dataset while the benchmark executes only queries. Thus the artifact can record metadata.sample_count=5 but report dataset coverage for all 301 rows, and field/bucket availability may be attributed to samples that were not benchmarked. Build coverage from the selected queries' raw rows so the report describes the actual run.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 02, 2026 05:34 UTC
    Code Review
    benchmarks/dataset.py:1
    @@ -0,0 +1,133 @@
    +"""Golden-set loading for the retrieval benchmark.
    +
    +Only fields that actually exist in the dataset are read. Missing metadata is
    +never inferred: ``visual_required`` and a stored complexity label are absent from
    +the current golden set, so the loader does not emit them and the benchmark does
    +not produce those breakdowns.
    +"""
    +
    +from __future__ import annotations
    +
    +import hashlib
    +import json
    +from collections.abc import Sequence
    +from pathlib import Path
    +from typing import Any
    +
    +from benchmarks.models import BenchmarkQuery, RelevantItem
    +from benchmarks.relevance import STABLE_ID_FIELDS, relevant_items_from_texts, stable_id_from
    +
    +DEFAULT_DATASET_PATH = "tests/evaluation/golden_set.jsonl"
    +
    +# Fields that would be required for Level-1 (stable id) relevance matching.
    +_STABLE_ID_KEYS = tuple(field for field in STABLE_ID_FIELDS)
    +
    +# Labels reported by the loader so downstream artifacts can state honestly which
    +# breakdowns exist and which do not.
    +KNOWN_UNAVAILABLE_BUCKETS = ("visual_required", "complexity")
    +
    +
    +class DatasetError(RuntimeError):
    +    """Raised when the dataset cannot support a trustworthy benchmark."""
    +
    +
    +def sha256_file(path: str | Path) -> str:
    +    digest = hashlib.sha256()
    +    with open(path, "rb") as handle:
    +        for chunk in iter(lambda: handle.read(65536), b""):
    +            digest.update(chunk)
    +    return digest.hexdigest()
    +
    +
    +def load_rows(path: str | Path) -> list[dict[str, Any]]:
    +    rows: list[dict[str, Any]] = []
    +    with open(path, encoding="utf-8") as handle:
    +        for line_number, line in enumerate(handle, start=1):
    +            if not line.strip():
    +                continue
    +            try:
    +                rows.append(json.loads(line))
    +            except json.JSONDecodeError as exc:
    +                raise DatasetError(f"{path}:{line_number}: invalid JSON ({exc})") from exc
    +    if not rows:
    +        raise DatasetError(f"{path}: dataset is empty")
    +    return rows
    +
    +
    +def detect_relevance_level(rows: Sequence[dict[str, Any]]) -> str:
    +    """Whether ground truth can be matched by stable id (``level1``) or only by text."""
    +    if not rows:
    +        return "level2_normalized_exact_text"
    +    if any(row.get(_STABLE_ID_KEYS) for row in rows):
    +        return "level1_stable_id"

    <sub><sub>!P2 Badge</sub></sub> Check stable-ID fields individually

    For any custom --dataset containing doc_id, chunk_id, or source_id, this passes the whole tuple to dict.get as one key instead of checking each field. JSON rows therefore always fall through to level2_normalized_exact_text, even though load_queries separately detects and uses the stable ID, causing the artifact to misreport the relevance strategy used by the run.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Oct 02, 2026 05:34 UTC
    Reviewer

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: ffca11c4a3

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    </details>

    Xander-Xai Xander-Xai commented on Oct 02, 2026 05:38 UTC
    Author

    @codex review

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 02, 2026 05:41 UTC
    Code Review
    benchmarks/backends.py:1
    @@ -0,0 +1,256 @@
    +"""Retrieval backends for the benchmark.
    +
    +Every backend is probed before it is used, and a backend that cannot answer a
    +real probe is reported as unavailable. The harness never substitutes a stand-in
    +retriever for a missing one: a benchmark that silently ranks with a fake backend
    +would produce numbers that look like retrieval quality while measuring nothing.
    +
    +Two independent things are required for a meaningful measurement:
    +
    +1. a **live retrieval service** (Elasticsearch / Qdrant) and real model assets;
    +2. a **corpus that actually contains the ground-truth passages**.
    +
    +Requirement 2 is easy to overlook. The golden set stores ground truth as passage
    +*text*; the operator corpus is their own private material. Indexing the golden
    +set passages themselves and then measuring recall would be self-referential —
    +every configuration would trivially reach recall 1.0 — so this module refuses that
    +shortcut and reports the corpus requirement explicitly instead.
    +"""
    +
    +from __future__ import annotations
    +
    +import json
    +import socket
    +import urllib.error
    +import urllib.request
    +from dataclasses import dataclass
    +from typing import Any
    +
    +from benchmarks.models import BackendAvailability
    +
    +PROBE_TIMEOUT_SECONDS = 2.0
    +
    +REASON_OK = "available"
    +REASON_SERVICE_UNREACHABLE = "service_unreachable"
    +REASON_SERVICE_NO_DATA = "service_reachable_but_empty"
    +REASON_MODEL_UNAVAILABLE = "model_assets_unavailable"
    +REASON_CORPUS_UNRESOLVED = "corpus_does_not_contain_ground_truth"
    +REASON_NOT_CONFIGURED = "not_configured"
    +
    +
    +class BenchmarkUnavailable(RuntimeError):
    +    """Raised when a backend is asked to retrieve without being available."""
    +
    +
    +def _http_get(url: str) -> tuple[bool, Any]:
    +    """Return ``(ok, payload)`` for a short-timeout GET."""
    +    try:
    +        with urllib.request.urlopen(url, timeout=PROBE_TIMEOUT_SECONDS) as response:  # noqa: S310 - operator-configured http(s) endpoint
    +            body = response.read()
    +    except (urllib.error.URLError, OSError, ValueError):
    +        return False, None
    +    try:
    +        return True, json.loads(body)
    +    except (json.JSONDecodeError, UnicodeDecodeError):
    +        return True, body.decode("utf-8", errors="replace")
    +
    +
    +def _tcp_reachable(host: str, port: int) -> bool:
    +    try:
    +        with socket.create_connection((host, port), timeout=PROBE_TIMEOUT_SECONDS):
    +            return True
    +    except OSError:
    +        return False
    +
    +
    +def _elastic_settings() -> tuple[str, str, int]:
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    elastic = config.get("elasticsearch", {}) or {}
    +    url = str(elastic.get("host") or "http://elasticsearch:9200")
    +    index = str(elastic.get("index") or "cosmetics_docs")
    +    port = int(elastic.get("port") or 9200)
    +    return url, index, port
    +
    +
    +def _qdrant_settings() -> tuple[str, int, str]:
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    qdrant = config.get("qdrant", {}) or {}
    +    host = str(qdrant.get("host") or "qdrant")
    +    port = int(qdrant.get("port") or 6333)
    +    collections = qdrant.get("collections", {}) or {}
    +    text_collection = str((collections.get("rag_text_768", {}) or {}).get("name") or "rag_text_768")

    <sub><sub>!P2 Badge</sub></sub> Read the configured dense collection

    When embedding.text.collection is changed from rag_text_768, the production dense search uses that configured value (models/embedding_service.py:206), but this probe still checks the hard-coded default. A healthy configured collection can therefore be reported as unreachable, or a stale default collection can be validated instead of the collection the benchmark would query.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 02, 2026 05:41 UTC
    Code Review
    benchmarks/backends.py:1
    @@ -0,0 +1,256 @@
    +"""Retrieval backends for the benchmark.
    +
    +Every backend is probed before it is used, and a backend that cannot answer a
    +real probe is reported as unavailable. The harness never substitutes a stand-in
    +retriever for a missing one: a benchmark that silently ranks with a fake backend
    +would produce numbers that look like retrieval quality while measuring nothing.
    +
    +Two independent things are required for a meaningful measurement:
    +
    +1. a **live retrieval service** (Elasticsearch / Qdrant) and real model assets;
    +2. a **corpus that actually contains the ground-truth passages**.
    +
    +Requirement 2 is easy to overlook. The golden set stores ground truth as passage
    +*text*; the operator corpus is their own private material. Indexing the golden
    +set passages themselves and then measuring recall would be self-referential —
    +every configuration would trivially reach recall 1.0 — so this module refuses that
    +shortcut and reports the corpus requirement explicitly instead.
    +"""
    +
    +from __future__ import annotations
    +
    +import json
    +import socket
    +import urllib.error
    +import urllib.request
    +from dataclasses import dataclass
    +from typing import Any
    +
    +from benchmarks.models import BackendAvailability
    +
    +PROBE_TIMEOUT_SECONDS = 2.0
    +
    +REASON_OK = "available"
    +REASON_SERVICE_UNREACHABLE = "service_unreachable"
    +REASON_SERVICE_NO_DATA = "service_reachable_but_empty"
    +REASON_MODEL_UNAVAILABLE = "model_assets_unavailable"
    +REASON_CORPUS_UNRESOLVED = "corpus_does_not_contain_ground_truth"
    +REASON_NOT_CONFIGURED = "not_configured"
    +
    +
    +class BenchmarkUnavailable(RuntimeError):
    +    """Raised when a backend is asked to retrieve without being available."""
    +
    +
    +def _http_get(url: str) -> tuple[bool, Any]:
    +    """Return ``(ok, payload)`` for a short-timeout GET."""
    +    try:
    +        with urllib.request.urlopen(url, timeout=PROBE_TIMEOUT_SECONDS) as response:  # noqa: S310 - operator-configured http(s) endpoint
    +            body = response.read()
    +    except (urllib.error.URLError, OSError, ValueError):
    +        return False, None
    +    try:
    +        return True, json.loads(body)
    +    except (json.JSONDecodeError, UnicodeDecodeError):
    +        return True, body.decode("utf-8", errors="replace")
    +
    +
    +def _tcp_reachable(host: str, port: int) -> bool:
    +    try:
    +        with socket.create_connection((host, port), timeout=PROBE_TIMEOUT_SECONDS):
    +            return True
    +    except OSError:
    +        return False
    +
    +
    +def _elastic_settings() -> tuple[str, str, int]:
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    elastic = config.get("elasticsearch", {}) or {}
    +    url = str(elastic.get("host") or "http://elasticsearch:9200")
    +    index = str(elastic.get("index") or "cosmetics_docs")
    +    port = int(elastic.get("port") or 9200)
    +    return url, index, port
    +
    +
    +def _qdrant_settings() -> tuple[str, int, str]:
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    qdrant = config.get("qdrant", {}) or {}
    +    host = str(qdrant.get("host") or "qdrant")
    +    port = int(qdrant.get("port") or 6333)
    +    collections = qdrant.get("collections", {}) or {}
    +    text_collection = str((collections.get("rag_text_768", {}) or {}).get("name") or "rag_text_768")
    +    return host, port, text_collection
    +
    +
    +def _model_weights_available() -> tuple[bool, str | None]:
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    model_path = (config.get("embedding", {}).get("text", {}) or {}).get("model_path")
    +    if not model_path:
    +        return False, None
    +    from pathlib import Path
    +
    +    resolved = Path(str(model_path))
    +    if resolved.exists():
    +        return True, str(model_path)
    +    return False, str(model_path)
    +
    +
    +# ── Probes ────────────────────────────────────────────────────────────────
    +
    +
    +def probe_bm25() -> BackendAvailability:
    +    """BM25 needs a reachable Elasticsearch holding the benchmark corpus."""
    +    url, index, port = _elastic_settings()
    +    if not _tcp_reachable(url.split("//")[-1].split(":")[0], port):

    <sub><sub>!P2 Badge</sub></sub> Derive the Elasticsearch probe port from its URL

    When elasticsearch.host embeds a non-default port, such as http://localhost:19200, or uses HTTPS without a separate port setting, this TCP check still connects to the fallback port 9200. It can reject a reachable Elasticsearch endpoint before attempting the correctly formed HTTP request; parse the hostname and port from the configured URL unless an explicit port override is provided.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 02, 2026 05:41 UTC
    Code Review
    benchmarks/retrieval_benchmark.py:1
    @@ -0,0 +1,210 @@
    +"""Command-line entry point for the retrieval benchmark.
    +
    +Examples
    +--------
    +List what the current environment can actually execute::
    +
    +    python -m benchmarks.retrieval_benchmark --list-configs
    +
    +Attempt a real run (writes an artifact set even when everything is blocked)::
    +
    +    python -m benchmarks.retrieval_benchmark --config bm25 --limit 5
    +
    +The CLI has no flag that installs a fake retriever. A synthetic retriever can
    +only be supplied programmatically by tests, and any run that used one is flagged
    +in its artifacts.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import sys
    +from pathlib import Path
    +
    +from benchmarks import backends, report
    +from benchmarks.dataset import (
    +    DEFAULT_DATASET_PATH,
    +    DatasetError,
    +    bucket_coverage,
    +    load_queries,
    +    load_rows,
    +    sample_ids_hash,
    +    sha256_file,
    +)
    +from benchmarks.models import STATUS_EXECUTED
    +from benchmarks.provenance import (
    +    collect_environment,
    +    git_provenance,
    +    new_run_id,
    +    now_utc,
    +    render_environment,
    +    sha256_json,
    +    write_gitignore_entry,
    +)
    +from benchmarks.runner import DEFAULT_TOP_K, run_configuration, summarize_run, write_per_query_jsonl
    +
    +DEFAULT_OUTPUT_DIR = "artifacts/benchmarks"
    +
    +
    +def build_parser() -> argparse.ArgumentParser:
    +    parser = argparse.ArgumentParser(
    +        prog="python -m benchmarks.retrieval_benchmark",
    +        description="Deterministic retrieval benchmark (no RAGAS evaluator required).",
    +    )
    +    parser.add_argument("--config", help="single configuration to run")
    +    parser.add_argument("--configs", help="comma-separated configurations to run")
    +    parser.add_argument("--dataset", default=DEFAULT_DATASET_PATH, help="golden set JSONL path")
    +    parser.add_argument("--limit", type=int, default=None, help="only use the first N samples")
    +    parser.add_argument("--sample-id", action="append", default=None, help="run only this sample id (repeatable)")
    +    parser.add_argument("--top-k", type=int, default=DEFAULT_TOP_K, help="retrieval depth (default 10)")
    +    parser.add_argument("--output-dir", default=DEFAULT_OUTPUT_DIR, help="artifact root directory")
    +    parser.add_argument(
    +        "--allow-dirty",
    +        action="store_true",
    +        help="allow running with a dirty working tree (recorded as git_dirty=true)",
    +    )
    +    parser.add_argument(
    +        "--require-results",
    +        action="store_true",
    +        help="exit non-zero when no configuration executed (useful to fail CI on blocked runs)",
    +    )
    +    parser.add_argument("--list-configs", action="store_true", help="print configuration availability and exit")
    +    return parser
    +
    +
    +def _resolve_configs(args: argparse.Namespace) -> list[str]:
    +    if args.config and args.configs:
    +        raise SystemExit("use either --config or --configs, not both")
    +    if args.config:
    +        return [args.config]
    +    if args.configs:
    +        return [item.strip() for item in args.configs.split(",") if item.strip()]
    +    return ["bm25", "dense", "hybrid_rrf"]
    +
    +
    +def _print_configs(dataset_queries: int) -> int:
    +    print("configurations (availability probed live):\n")
    +    for name, description in backends.CONFIG_DESCRIPTIONS.items():
    +        availability = backends.evaluate_config(name, dataset_queries)
    +        state = "EXECUTABLE" if availability.available else "BLOCKED"
    +        print(f"  {name:36s} {state:12s} {description}")
    +        if not availability.available:
    +            print(f"  {'':36s} reasons: {availability.describe()}")
    +            if availability.detail:
    +                print(f"  {'':36s} detail:  {availability.detail}")
    +    print("\nNote: a configuration is only reported EXECUTABLE when every required backend")
    +    print("and the benchmark corpus answered a real probe. No stand-in retriever is used.")
    +    return 0
    +
    +
    +def main(argv: list[str] | None = None) -> int:
    +    parser = build_parser()
    +    args = parser.parse_args(argv)
    +
    +    repo_root = Path(__file__).resolve().parents[1]
    +    dataset_path = Path(args.dataset)
    +    if not dataset_path.is_file():
    +        print(f"dataset not found: {dataset_path}", file=sys.stderr)
    +        return 2
    +
    +    try:
    +        rows = load_rows(dataset_path)
    +    except DatasetError as exc:
    +        print(f"dataset error: {exc}", file=sys.stderr)
    +        return 2
    +
    +    if args.list_configs:
    +        return _print_configs(len(rows))
    +
    +    configs = _resolve_configs(args)
    +    unknown = [name for name in configs if name not in backends.CONFIG_DESCRIPTIONS]
    +    if unknown:
    +        print(f"unknown configuration(s): {', '.join(unknown)}", file=sys.stderr)
    +        return 2
    +
    +    git_sha, git_dirty = git_provenance(repo_root)
    +    if git_dirty and not args.allow_dirty:
    +        print(
    +            "refusing to run on a dirty working tree; commit your changes or pass --allow-dirty "
    +            "(the artifact will record git_dirty=true)",
    +            file=sys.stderr,
    +        )
    +        return 3
    +
    +    try:
    +        queries = load_queries(dataset_path, limit=args.limit, sample_ids=args.sample_id)
    +    except DatasetError as exc:
    +        print(f"dataset error: {exc}", file=sys.stderr)
    +        return 2
    +
    +    run_id = new_run_id()
    +    config_payload = {"configs": configs, "top_k": args.top_k, "dataset_sha256": sha256_file(dataset_path)}
    +    metadata = {
    +        "run_id": run_id,
    +        "timestamp_utc": now_utc(),
    +        "git_sha": git_sha,
    +        "git_dirty": git_dirty,
    +        "dataset_path": str(dataset_path),
    +        "dataset_sha256": sha256_file(dataset_path),
    +        "sample_count": len(queries),
    +        "sample_ids_hash": sample_ids_hash(queries),
    +        "config_name": configs[0] if len(configs) == 1 else "multi",
    +        "config_sha256": sha256_json(config_payload),
    +        "requested_configs": configs,
    +        "top_k": args.top_k,
    +        "allow_dirty": bool(args.allow_dirty),
    +        "synthetic_retriever": False,
    +        "results_are_benchmark": True,

    <sub><sub>!P2 Badge</sub></sub> Do not label blocked artifacts as benchmark results

    For the currently expected case where every requested configuration is BLOCKED, the artifact contains no retrieval-quality result but metadata still sets results_are_benchmark to true. Any artifact consumer relying on this explicit field can consequently publish or ingest a blocked run as benchmark evidence; derive it from whether a configuration actually executed instead.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Oct 02, 2026 05:41 UTC
    Reviewer

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: ffca11c4a3

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    </details>

    Xander-Xai Xander-Xai commented on code on Oct 02, 2026 05:51 UTC
    Code Review
    benchmarks/retrieval_benchmark.py:1
    @@ -0,0 +1,210 @@
    +"""Command-line entry point for the retrieval benchmark.
    +
    +Examples
    +--------
    +List what the current environment can actually execute::
    +
    +    python -m benchmarks.retrieval_benchmark --list-configs
    +
    +Attempt a real run (writes an artifact set even when everything is blocked)::
    +
    +    python -m benchmarks.retrieval_benchmark --config bm25 --limit 5
    +
    +The CLI has no flag that installs a fake retriever. A synthetic retriever can
    +only be supplied programmatically by tests, and any run that used one is flagged
    +in its artifacts.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import sys
    +from pathlib import Path
    +
    +from benchmarks import backends, report
    +from benchmarks.dataset import (
    +    DEFAULT_DATASET_PATH,
    +    DatasetError,
    +    bucket_coverage,
    +    load_queries,
    +    load_rows,
    +    sample_ids_hash,
    +    sha256_file,
    +)
    +from benchmarks.models import STATUS_EXECUTED
    +from benchmarks.provenance import (
    +    collect_environment,
    +    git_provenance,
    +    new_run_id,
    +    now_utc,
    +    render_environment,
    +    sha256_json,
    +    write_gitignore_entry,
    +)
    +from benchmarks.runner import DEFAULT_TOP_K, run_configuration, summarize_run, write_per_query_jsonl
    +
    +DEFAULT_OUTPUT_DIR = "artifacts/benchmarks"
    +
    +
    +def build_parser() -> argparse.ArgumentParser:
    +    parser = argparse.ArgumentParser(
    +        prog="python -m benchmarks.retrieval_benchmark",
    +        description="Deterministic retrieval benchmark (no RAGAS evaluator required).",
    +    )
    +    parser.add_argument("--config", help="single configuration to run")
    +    parser.add_argument("--configs", help="comma-separated configurations to run")
    +    parser.add_argument("--dataset", default=DEFAULT_DATASET_PATH, help="golden set JSONL path")
    +    parser.add_argument("--limit", type=int, default=None, help="only use the first N samples")
    +    parser.add_argument("--sample-id", action="append", default=None, help="run only this sample id (repeatable)")
    +    parser.add_argument("--top-k", type=int, default=DEFAULT_TOP_K, help="retrieval depth (default 10)")

    Confirmed P1. Root cause: --top-k was passed straight to the retriever, so a depth below 10 truncated the ranking while metrics were still labelled Recall@10 / MRR@10 / NDCG@10. Fix: added MIN_TOP_K = max(RECALL_KS, HIT_KS, MRR_K, NDCG_K) = 10; the CLI rejects a shallower depth with an explanatory error and run_configuration raises ValueError. Regression tests: test_top_k_below_largest_cutoff_is_rejected, test_min_top_k_covers_the_largest_cutoff, test_cli_rejects_shallow_top_k. Commit 219e0c6.

    Xander-Xai Xander-Xai commented on code on Oct 02, 2026 05:51 UTC
    Code Review
    benchmarks/backends.py:1
    @@ -0,0 +1,256 @@
    +"""Retrieval backends for the benchmark.
    +
    +Every backend is probed before it is used, and a backend that cannot answer a
    +real probe is reported as unavailable. The harness never substitutes a stand-in
    +retriever for a missing one: a benchmark that silently ranks with a fake backend
    +would produce numbers that look like retrieval quality while measuring nothing.
    +
    +Two independent things are required for a meaningful measurement:
    +
    +1. a **live retrieval service** (Elasticsearch / Qdrant) and real model assets;
    +2. a **corpus that actually contains the ground-truth passages**.
    +
    +Requirement 2 is easy to overlook. The golden set stores ground truth as passage
    +*text*; the operator corpus is their own private material. Indexing the golden
    +set passages themselves and then measuring recall would be self-referential —
    +every configuration would trivially reach recall 1.0 — so this module refuses that
    +shortcut and reports the corpus requirement explicitly instead.
    +"""
    +
    +from __future__ import annotations
    +
    +import json
    +import socket
    +import urllib.error
    +import urllib.request
    +from dataclasses import dataclass
    +from typing import Any
    +
    +from benchmarks.models import BackendAvailability
    +
    +PROBE_TIMEOUT_SECONDS = 2.0
    +
    +REASON_OK = "available"
    +REASON_SERVICE_UNREACHABLE = "service_unreachable"
    +REASON_SERVICE_NO_DATA = "service_reachable_but_empty"
    +REASON_MODEL_UNAVAILABLE = "model_assets_unavailable"
    +REASON_CORPUS_UNRESOLVED = "corpus_does_not_contain_ground_truth"
    +REASON_NOT_CONFIGURED = "not_configured"
    +
    +
    +class BenchmarkUnavailable(RuntimeError):
    +    """Raised when a backend is asked to retrieve without being available."""
    +
    +
    +def _http_get(url: str) -> tuple[bool, Any]:
    +    """Return ``(ok, payload)`` for a short-timeout GET."""
    +    try:
    +        with urllib.request.urlopen(url, timeout=PROBE_TIMEOUT_SECONDS) as response:  # noqa: S310 - operator-configured http(s) endpoint
    +            body = response.read()
    +    except (urllib.error.URLError, OSError, ValueError):

    Confirmed. Root cause: the probe used unauthenticated HTTP, so a secured Elasticsearch (Compose sets xpack.security.enabled=true) answers 401 and was reported as service_unreachable. Fix: _http_get now sends basic auth from ELASTICSEARCH_USERNAME/ELASTICSEARCH_PASSWORD, and an HTTP-level error status is treated as reachable (reported as an auth/index problem) rather than unreachable. Regression tests: test_elastic_probe_uses_configured_credentials, test_http_status_is_reachable_not_unreachable. Commit 219e0c6.

    Xander-Xai Xander-Xai commented on code on Oct 02, 2026 05:51 UTC
    Code Review
    benchmarks/retrieval_benchmark.py:1
    @@ -0,0 +1,210 @@
    +"""Command-line entry point for the retrieval benchmark.
    +
    +Examples
    +--------
    +List what the current environment can actually execute::
    +
    +    python -m benchmarks.retrieval_benchmark --list-configs
    +
    +Attempt a real run (writes an artifact set even when everything is blocked)::
    +
    +    python -m benchmarks.retrieval_benchmark --config bm25 --limit 5
    +
    +The CLI has no flag that installs a fake retriever. A synthetic retriever can
    +only be supplied programmatically by tests, and any run that used one is flagged
    +in its artifacts.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import sys
    +from pathlib import Path
    +
    +from benchmarks import backends, report
    +from benchmarks.dataset import (
    +    DEFAULT_DATASET_PATH,
    +    DatasetError,
    +    bucket_coverage,
    +    load_queries,
    +    load_rows,
    +    sample_ids_hash,
    +    sha256_file,
    +)
    +from benchmarks.models import STATUS_EXECUTED
    +from benchmarks.provenance import (
    +    collect_environment,
    +    git_provenance,
    +    new_run_id,
    +    now_utc,
    +    render_environment,
    +    sha256_json,
    +    write_gitignore_entry,
    +)
    +from benchmarks.runner import DEFAULT_TOP_K, run_configuration, summarize_run, write_per_query_jsonl
    +
    +DEFAULT_OUTPUT_DIR = "artifacts/benchmarks"
    +
    +
    +def build_parser() -> argparse.ArgumentParser:
    +    parser = argparse.ArgumentParser(
    +        prog="python -m benchmarks.retrieval_benchmark",
    +        description="Deterministic retrieval benchmark (no RAGAS evaluator required).",
    +    )
    +    parser.add_argument("--config", help="single configuration to run")
    +    parser.add_argument("--configs", help="comma-separated configurations to run")
    +    parser.add_argument("--dataset", default=DEFAULT_DATASET_PATH, help="golden set JSONL path")
    +    parser.add_argument("--limit", type=int, default=None, help="only use the first N samples")
    +    parser.add_argument("--sample-id", action="append", default=None, help="run only this sample id (repeatable)")
    +    parser.add_argument("--top-k", type=int, default=DEFAULT_TOP_K, help="retrieval depth (default 10)")
    +    parser.add_argument("--output-dir", default=DEFAULT_OUTPUT_DIR, help="artifact root directory")
    +    parser.add_argument(
    +        "--allow-dirty",
    +        action="store_true",
    +        help="allow running with a dirty working tree (recorded as git_dirty=true)",
    +    )
    +    parser.add_argument(
    +        "--require-results",
    +        action="store_true",
    +        help="exit non-zero when no configuration executed (useful to fail CI on blocked runs)",
    +    )
    +    parser.add_argument("--list-configs", action="store_true", help="print configuration availability and exit")
    +    return parser
    +
    +
    +def _resolve_configs(args: argparse.Namespace) -> list[str]:
    +    if args.config and args.configs:
    +        raise SystemExit("use either --config or --configs, not both")
    +    if args.config:
    +        return [args.config]
    +    if args.configs:
    +        return [item.strip() for item in args.configs.split(",") if item.strip()]
    +    return ["bm25", "dense", "hybrid_rrf"]
    +
    +
    +def _print_configs(dataset_queries: int) -> int:
    +    print("configurations (availability probed live):\n")
    +    for name, description in backends.CONFIG_DESCRIPTIONS.items():
    +        availability = backends.evaluate_config(name, dataset_queries)
    +        state = "EXECUTABLE" if availability.available else "BLOCKED"
    +        print(f"  {name:36s} {state:12s} {description}")
    +        if not availability.available:
    +            print(f"  {'':36s} reasons: {availability.describe()}")
    +            if availability.detail:
    +                print(f"  {'':36s} detail:  {availability.detail}")
    +    print("\nNote: a configuration is only reported EXECUTABLE when every required backend")
    +    print("and the benchmark corpus answered a real probe. No stand-in retriever is used.")
    +    return 0
    +
    +
    +def main(argv: list[str] | None = None) -> int:
    +    parser = build_parser()
    +    args = parser.parse_args(argv)
    +
    +    repo_root = Path(__file__).resolve().parents[1]
    +    dataset_path = Path(args.dataset)
    +    if not dataset_path.is_file():
    +        print(f"dataset not found: {dataset_path}", file=sys.stderr)
    +        return 2
    +
    +    try:
    +        rows = load_rows(dataset_path)
    +    except DatasetError as exc:
    +        print(f"dataset error: {exc}", file=sys.stderr)
    +        return 2
    +
    +    if args.list_configs:
    +        return _print_configs(len(rows))
    +
    +    configs = _resolve_configs(args)
    +    unknown = [name for name in configs if name not in backends.CONFIG_DESCRIPTIONS]
    +    if unknown:
    +        print(f"unknown configuration(s): {', '.join(unknown)}", file=sys.stderr)
    +        return 2
    +
    +    git_sha, git_dirty = git_provenance(repo_root)
    +    if git_dirty and not args.allow_dirty:
    +        print(
    +            "refusing to run on a dirty working tree; commit your changes or pass --allow-dirty "
    +            "(the artifact will record git_dirty=true)",
    +            file=sys.stderr,
    +        )
    +        return 3
    +
    +    try:
    +        queries = load_queries(dataset_path, limit=args.limit, sample_ids=args.sample_id)
    +    except DatasetError as exc:
    +        print(f"dataset error: {exc}", file=sys.stderr)
    +        return 2
    +
    +    run_id = new_run_id()
    +    config_payload = {"configs": configs, "top_k": args.top_k, "dataset_sha256": sha256_file(dataset_path)}
    +    metadata = {
    +        "run_id": run_id,
    +        "timestamp_utc": now_utc(),
    +        "git_sha": git_sha,
    +        "git_dirty": git_dirty,
    +        "dataset_path": str(dataset_path),
    +        "dataset_sha256": sha256_file(dataset_path),
    +        "sample_count": len(queries),
    +        "sample_ids_hash": sample_ids_hash(queries),
    +        "config_name": configs[0] if len(configs) == 1 else "multi",
    +        "config_sha256": sha256_json(config_payload),
    +        "requested_configs": configs,
    +        "top_k": args.top_k,
    +        "allow_dirty": bool(args.allow_dirty),
    +        "synthetic_retriever": False,
    +        "results_are_benchmark": True,
    +    }
    +    environment = render_environment(collect_environment())
    +    coverage = bucket_coverage(rows)

    Confirmed. Root cause: coverage was computed from the whole dataset file while only the selected queries ran, so a --limit 5 artifact described 301 samples. Fix: coverage is now built from [query.raw for query in queries]. Regression test: test_coverage_reflects_selected_subset, test_coverage_unavailable_buckets_still_reported. Commit 219e0c6.

    Xander-Xai Xander-Xai commented on code on Oct 02, 2026 05:51 UTC
    Code Review
    benchmarks/dataset.py:1
    @@ -0,0 +1,133 @@
    +"""Golden-set loading for the retrieval benchmark.
    +
    +Only fields that actually exist in the dataset are read. Missing metadata is
    +never inferred: ``visual_required`` and a stored complexity label are absent from
    +the current golden set, so the loader does not emit them and the benchmark does
    +not produce those breakdowns.
    +"""
    +
    +from __future__ import annotations
    +
    +import hashlib
    +import json
    +from collections.abc import Sequence
    +from pathlib import Path
    +from typing import Any
    +
    +from benchmarks.models import BenchmarkQuery, RelevantItem
    +from benchmarks.relevance import STABLE_ID_FIELDS, relevant_items_from_texts, stable_id_from
    +
    +DEFAULT_DATASET_PATH = "tests/evaluation/golden_set.jsonl"
    +
    +# Fields that would be required for Level-1 (stable id) relevance matching.
    +_STABLE_ID_KEYS = tuple(field for field in STABLE_ID_FIELDS)
    +
    +# Labels reported by the loader so downstream artifacts can state honestly which
    +# breakdowns exist and which do not.
    +KNOWN_UNAVAILABLE_BUCKETS = ("visual_required", "complexity")
    +
    +
    +class DatasetError(RuntimeError):
    +    """Raised when the dataset cannot support a trustworthy benchmark."""
    +
    +
    +def sha256_file(path: str | Path) -> str:
    +    digest = hashlib.sha256()
    +    with open(path, "rb") as handle:
    +        for chunk in iter(lambda: handle.read(65536), b""):
    +            digest.update(chunk)
    +    return digest.hexdigest()
    +
    +
    +def load_rows(path: str | Path) -> list[dict[str, Any]]:
    +    rows: list[dict[str, Any]] = []
    +    with open(path, encoding="utf-8") as handle:
    +        for line_number, line in enumerate(handle, start=1):
    +            if not line.strip():
    +                continue
    +            try:
    +                rows.append(json.loads(line))
    +            except json.JSONDecodeError as exc:
    +                raise DatasetError(f"{path}:{line_number}: invalid JSON ({exc})") from exc
    +    if not rows:
    +        raise DatasetError(f"{path}: dataset is empty")
    +    return rows
    +
    +
    +def detect_relevance_level(rows: Sequence[dict[str, Any]]) -> str:
    +    """Whether ground truth can be matched by stable id (``level1``) or only by text."""
    +    if not rows:
    +        return "level2_normalized_exact_text"
    +    if any(row.get(_STABLE_ID_KEYS) for row in rows):
    +        return "level1_stable_id"

    Confirmed, real bug. Root cause: row.get(_STABLE_ID_KEYS) passed the whole tuple as a single key, so it always returned None and every dataset was reported as level2 even though load_queries used a stable id when present. Fix: each field is checked individually. Regression tests: test_detect_relevance_level_sees_each_stable_id[doc_id|chunk_id|source_id], test_stable_id_dataset_loads_level1_items. Verified these fail against the old code. Commit 219e0c6.

    Xander-Xai Xander-Xai commented on code on Oct 02, 2026 05:51 UTC
    Code Review
    benchmarks/backends.py:1
    @@ -0,0 +1,256 @@
    +"""Retrieval backends for the benchmark.
    +
    +Every backend is probed before it is used, and a backend that cannot answer a
    +real probe is reported as unavailable. The harness never substitutes a stand-in
    +retriever for a missing one: a benchmark that silently ranks with a fake backend
    +would produce numbers that look like retrieval quality while measuring nothing.
    +
    +Two independent things are required for a meaningful measurement:
    +
    +1. a **live retrieval service** (Elasticsearch / Qdrant) and real model assets;
    +2. a **corpus that actually contains the ground-truth passages**.
    +
    +Requirement 2 is easy to overlook. The golden set stores ground truth as passage
    +*text*; the operator corpus is their own private material. Indexing the golden
    +set passages themselves and then measuring recall would be self-referential —
    +every configuration would trivially reach recall 1.0 — so this module refuses that
    +shortcut and reports the corpus requirement explicitly instead.
    +"""
    +
    +from __future__ import annotations
    +
    +import json
    +import socket
    +import urllib.error
    +import urllib.request
    +from dataclasses import dataclass
    +from typing import Any
    +
    +from benchmarks.models import BackendAvailability
    +
    +PROBE_TIMEOUT_SECONDS = 2.0
    +
    +REASON_OK = "available"
    +REASON_SERVICE_UNREACHABLE = "service_unreachable"
    +REASON_SERVICE_NO_DATA = "service_reachable_but_empty"
    +REASON_MODEL_UNAVAILABLE = "model_assets_unavailable"
    +REASON_CORPUS_UNRESOLVED = "corpus_does_not_contain_ground_truth"
    +REASON_NOT_CONFIGURED = "not_configured"
    +
    +
    +class BenchmarkUnavailable(RuntimeError):
    +    """Raised when a backend is asked to retrieve without being available."""
    +
    +
    +def _http_get(url: str) -> tuple[bool, Any]:
    +    """Return ``(ok, payload)`` for a short-timeout GET."""
    +    try:
    +        with urllib.request.urlopen(url, timeout=PROBE_TIMEOUT_SECONDS) as response:  # noqa: S310 - operator-configured http(s) endpoint
    +            body = response.read()
    +    except (urllib.error.URLError, OSError, ValueError):
    +        return False, None
    +    try:
    +        return True, json.loads(body)
    +    except (json.JSONDecodeError, UnicodeDecodeError):
    +        return True, body.decode("utf-8", errors="replace")
    +
    +
    +def _tcp_reachable(host: str, port: int) -> bool:
    +    try:
    +        with socket.create_connection((host, port), timeout=PROBE_TIMEOUT_SECONDS):
    +            return True
    +    except OSError:
    +        return False
    +
    +
    +def _elastic_settings() -> tuple[str, str, int]:
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    elastic = config.get("elasticsearch", {}) or {}
    +    url = str(elastic.get("host") or "http://elasticsearch:9200")
    +    index = str(elastic.get("index") or "cosmetics_docs")
    +    port = int(elastic.get("port") or 9200)
    +    return url, index, port
    +
    +
    +def _qdrant_settings() -> tuple[str, int, str]:
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    qdrant = config.get("qdrant", {}) or {}
    +    host = str(qdrant.get("host") or "qdrant")
    +    port = int(qdrant.get("port") or 6333)
    +    collections = qdrant.get("collections", {}) or {}
    +    text_collection = str((collections.get("rag_text_768", {}) or {}).get("name") or "rag_text_768")

    Confirmed. Root cause: _qdrant_settings hard-coded rag_text_768 instead of the configured embedding.text.collection used by the production dense search. Fix: the probe now prefers embedding.text.collection, then the Qdrant collections map, then the default. Regression test: test_qdrant_probe_uses_configured_text_collection. Commit 219e0c6.

    Xander-Xai Xander-Xai commented on code on Oct 02, 2026 05:51 UTC
    Code Review
    benchmarks/backends.py:1
    @@ -0,0 +1,256 @@
    +"""Retrieval backends for the benchmark.
    +
    +Every backend is probed before it is used, and a backend that cannot answer a
    +real probe is reported as unavailable. The harness never substitutes a stand-in
    +retriever for a missing one: a benchmark that silently ranks with a fake backend
    +would produce numbers that look like retrieval quality while measuring nothing.
    +
    +Two independent things are required for a meaningful measurement:
    +
    +1. a **live retrieval service** (Elasticsearch / Qdrant) and real model assets;
    +2. a **corpus that actually contains the ground-truth passages**.
    +
    +Requirement 2 is easy to overlook. The golden set stores ground truth as passage
    +*text*; the operator corpus is their own private material. Indexing the golden
    +set passages themselves and then measuring recall would be self-referential —
    +every configuration would trivially reach recall 1.0 — so this module refuses that
    +shortcut and reports the corpus requirement explicitly instead.
    +"""
    +
    +from __future__ import annotations
    +
    +import json
    +import socket
    +import urllib.error
    +import urllib.request
    +from dataclasses import dataclass
    +from typing import Any
    +
    +from benchmarks.models import BackendAvailability
    +
    +PROBE_TIMEOUT_SECONDS = 2.0
    +
    +REASON_OK = "available"
    +REASON_SERVICE_UNREACHABLE = "service_unreachable"
    +REASON_SERVICE_NO_DATA = "service_reachable_but_empty"
    +REASON_MODEL_UNAVAILABLE = "model_assets_unavailable"
    +REASON_CORPUS_UNRESOLVED = "corpus_does_not_contain_ground_truth"
    +REASON_NOT_CONFIGURED = "not_configured"
    +
    +
    +class BenchmarkUnavailable(RuntimeError):
    +    """Raised when a backend is asked to retrieve without being available."""
    +
    +
    +def _http_get(url: str) -> tuple[bool, Any]:
    +    """Return ``(ok, payload)`` for a short-timeout GET."""
    +    try:
    +        with urllib.request.urlopen(url, timeout=PROBE_TIMEOUT_SECONDS) as response:  # noqa: S310 - operator-configured http(s) endpoint
    +            body = response.read()
    +    except (urllib.error.URLError, OSError, ValueError):
    +        return False, None
    +    try:
    +        return True, json.loads(body)
    +    except (json.JSONDecodeError, UnicodeDecodeError):
    +        return True, body.decode("utf-8", errors="replace")
    +
    +
    +def _tcp_reachable(host: str, port: int) -> bool:
    +    try:
    +        with socket.create_connection((host, port), timeout=PROBE_TIMEOUT_SECONDS):
    +            return True
    +    except OSError:
    +        return False
    +
    +
    +def _elastic_settings() -> tuple[str, str, int]:
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    elastic = config.get("elasticsearch", {}) or {}
    +    url = str(elastic.get("host") or "http://elasticsearch:9200")
    +    index = str(elastic.get("index") or "cosmetics_docs")
    +    port = int(elastic.get("port") or 9200)
    +    return url, index, port
    +
    +
    +def _qdrant_settings() -> tuple[str, int, str]:
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    qdrant = config.get("qdrant", {}) or {}
    +    host = str(qdrant.get("host") or "qdrant")
    +    port = int(qdrant.get("port") or 6333)
    +    collections = qdrant.get("collections", {}) or {}
    +    text_collection = str((collections.get("rag_text_768", {}) or {}).get("name") or "rag_text_768")
    +    return host, port, text_collection
    +
    +
    +def _model_weights_available() -> tuple[bool, str | None]:
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    model_path = (config.get("embedding", {}).get("text", {}) or {}).get("model_path")
    +    if not model_path:
    +        return False, None
    +    from pathlib import Path
    +
    +    resolved = Path(str(model_path))
    +    if resolved.exists():
    +        return True, str(model_path)
    +    return False, str(model_path)
    +
    +
    +# ── Probes ────────────────────────────────────────────────────────────────
    +
    +
    +def probe_bm25() -> BackendAvailability:
    +    """BM25 needs a reachable Elasticsearch holding the benchmark corpus."""
    +    url, index, port = _elastic_settings()
    +    if not _tcp_reachable(url.split("//")[-1].split(":")[0], port):

    Confirmed. Root cause: the TCP pre-check connected to the 9200 fallback even when elasticsearch.host embedded another port. Fix: _elastic_settings parses hostname/port/scheme from the configured URL and only falls back when no port is given; an explicit port setting still wins. Regression test: test_elastic_port_is_parsed_from_url. Commit 219e0c6.

    Xander-Xai Xander-Xai commented on code on Oct 02, 2026 05:52 UTC
    Code Review
    benchmarks/retrieval_benchmark.py:1
    @@ -0,0 +1,210 @@
    +"""Command-line entry point for the retrieval benchmark.
    +
    +Examples
    +--------
    +List what the current environment can actually execute::
    +
    +    python -m benchmarks.retrieval_benchmark --list-configs
    +
    +Attempt a real run (writes an artifact set even when everything is blocked)::
    +
    +    python -m benchmarks.retrieval_benchmark --config bm25 --limit 5
    +
    +The CLI has no flag that installs a fake retriever. A synthetic retriever can
    +only be supplied programmatically by tests, and any run that used one is flagged
    +in its artifacts.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import sys
    +from pathlib import Path
    +
    +from benchmarks import backends, report
    +from benchmarks.dataset import (
    +    DEFAULT_DATASET_PATH,
    +    DatasetError,
    +    bucket_coverage,
    +    load_queries,
    +    load_rows,
    +    sample_ids_hash,
    +    sha256_file,
    +)
    +from benchmarks.models import STATUS_EXECUTED
    +from benchmarks.provenance import (
    +    collect_environment,
    +    git_provenance,
    +    new_run_id,
    +    now_utc,
    +    render_environment,
    +    sha256_json,
    +    write_gitignore_entry,
    +)
    +from benchmarks.runner import DEFAULT_TOP_K, run_configuration, summarize_run, write_per_query_jsonl
    +
    +DEFAULT_OUTPUT_DIR = "artifacts/benchmarks"
    +
    +
    +def build_parser() -> argparse.ArgumentParser:
    +    parser = argparse.ArgumentParser(
    +        prog="python -m benchmarks.retrieval_benchmark",
    +        description="Deterministic retrieval benchmark (no RAGAS evaluator required).",
    +    )
    +    parser.add_argument("--config", help="single configuration to run")
    +    parser.add_argument("--configs", help="comma-separated configurations to run")
    +    parser.add_argument("--dataset", default=DEFAULT_DATASET_PATH, help="golden set JSONL path")
    +    parser.add_argument("--limit", type=int, default=None, help="only use the first N samples")
    +    parser.add_argument("--sample-id", action="append", default=None, help="run only this sample id (repeatable)")
    +    parser.add_argument("--top-k", type=int, default=DEFAULT_TOP_K, help="retrieval depth (default 10)")
    +    parser.add_argument("--output-dir", default=DEFAULT_OUTPUT_DIR, help="artifact root directory")
    +    parser.add_argument(
    +        "--allow-dirty",
    +        action="store_true",
    +        help="allow running with a dirty working tree (recorded as git_dirty=true)",
    +    )
    +    parser.add_argument(
    +        "--require-results",
    +        action="store_true",
    +        help="exit non-zero when no configuration executed (useful to fail CI on blocked runs)",
    +    )
    +    parser.add_argument("--list-configs", action="store_true", help="print configuration availability and exit")
    +    return parser
    +
    +
    +def _resolve_configs(args: argparse.Namespace) -> list[str]:
    +    if args.config and args.configs:
    +        raise SystemExit("use either --config or --configs, not both")
    +    if args.config:
    +        return [args.config]
    +    if args.configs:
    +        return [item.strip() for item in args.configs.split(",") if item.strip()]
    +    return ["bm25", "dense", "hybrid_rrf"]
    +
    +
    +def _print_configs(dataset_queries: int) -> int:
    +    print("configurations (availability probed live):\n")
    +    for name, description in backends.CONFIG_DESCRIPTIONS.items():
    +        availability = backends.evaluate_config(name, dataset_queries)
    +        state = "EXECUTABLE" if availability.available else "BLOCKED"
    +        print(f"  {name:36s} {state:12s} {description}")
    +        if not availability.available:
    +            print(f"  {'':36s} reasons: {availability.describe()}")
    +            if availability.detail:
    +                print(f"  {'':36s} detail:  {availability.detail}")
    +    print("\nNote: a configuration is only reported EXECUTABLE when every required backend")
    +    print("and the benchmark corpus answered a real probe. No stand-in retriever is used.")
    +    return 0
    +
    +
    +def main(argv: list[str] | None = None) -> int:
    +    parser = build_parser()
    +    args = parser.parse_args(argv)
    +
    +    repo_root = Path(__file__).resolve().parents[1]
    +    dataset_path = Path(args.dataset)
    +    if not dataset_path.is_file():
    +        print(f"dataset not found: {dataset_path}", file=sys.stderr)
    +        return 2
    +
    +    try:
    +        rows = load_rows(dataset_path)
    +    except DatasetError as exc:
    +        print(f"dataset error: {exc}", file=sys.stderr)
    +        return 2
    +
    +    if args.list_configs:
    +        return _print_configs(len(rows))
    +
    +    configs = _resolve_configs(args)
    +    unknown = [name for name in configs if name not in backends.CONFIG_DESCRIPTIONS]
    +    if unknown:
    +        print(f"unknown configuration(s): {', '.join(unknown)}", file=sys.stderr)
    +        return 2
    +
    +    git_sha, git_dirty = git_provenance(repo_root)
    +    if git_dirty and not args.allow_dirty:
    +        print(
    +            "refusing to run on a dirty working tree; commit your changes or pass --allow-dirty "
    +            "(the artifact will record git_dirty=true)",
    +            file=sys.stderr,
    +        )
    +        return 3
    +
    +    try:
    +        queries = load_queries(dataset_path, limit=args.limit, sample_ids=args.sample_id)
    +    except DatasetError as exc:
    +        print(f"dataset error: {exc}", file=sys.stderr)
    +        return 2
    +
    +    run_id = new_run_id()
    +    config_payload = {"configs": configs, "top_k": args.top_k, "dataset_sha256": sha256_file(dataset_path)}
    +    metadata = {
    +        "run_id": run_id,
    +        "timestamp_utc": now_utc(),
    +        "git_sha": git_sha,
    +        "git_dirty": git_dirty,
    +        "dataset_path": str(dataset_path),
    +        "dataset_sha256": sha256_file(dataset_path),
    +        "sample_count": len(queries),
    +        "sample_ids_hash": sample_ids_hash(queries),
    +        "config_name": configs[0] if len(configs) == 1 else "multi",
    +        "config_sha256": sha256_json(config_payload),
    +        "requested_configs": configs,
    +        "top_k": args.top_k,
    +        "allow_dirty": bool(args.allow_dirty),
    +        "synthetic_retriever": False,
    +        "results_are_benchmark": True,

    Confirmed. Root cause: results_are_benchmark was hard-coded true, so a fully BLOCKED artifact advertised itself as benchmark evidence. Fix: it is derived from summary["any_results"], so a blocked run records false. Regression test: test_blocked_run_metadata_is_not_a_benchmark (verified failing against the old hard-coded value). Commit 219e0c6.

    Xander-Xai Xander-Xai commented on Oct 02, 2026 05:52 UTC
    Author

    @codex review

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 02, 2026 05:56 UTC
    Code Review
    benchmarks/backends.py:1
    @@ -0,0 +1,299 @@
    +"""Retrieval backends for the benchmark.
    +
    +Every backend is probed before it is used, and a backend that cannot answer a
    +real probe is reported as unavailable. The harness never substitutes a stand-in
    +retriever for a missing one: a benchmark that silently ranks with a fake backend
    +would produce numbers that look like retrieval quality while measuring nothing.
    +
    +Two independent things are required for a meaningful measurement:
    +
    +1. a **live retrieval service** (Elasticsearch / Qdrant) and real model assets;
    +2. a **corpus that actually contains the ground-truth passages**.
    +
    +Requirement 2 is easy to overlook. The golden set stores ground truth as passage
    +*text*; the operator corpus is their own private material. Indexing the golden
    +set passages themselves and then measuring recall would be self-referential —
    +every configuration would trivially reach recall 1.0 — so this module refuses that
    +shortcut and reports the corpus requirement explicitly instead.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import os
    +import socket
    +import urllib.error
    +import urllib.request
    +from dataclasses import dataclass
    +from typing import Any
    +
    +from benchmarks.models import BackendAvailability
    +
    +PROBE_TIMEOUT_SECONDS = 2.0
    +
    +REASON_OK = "available"
    +REASON_SERVICE_UNREACHABLE = "service_unreachable"
    +REASON_SERVICE_NO_DATA = "service_reachable_but_empty"
    +REASON_MODEL_UNAVAILABLE = "model_assets_unavailable"
    +REASON_CORPUS_UNRESOLVED = "corpus_does_not_contain_ground_truth"
    +REASON_NOT_CONFIGURED = "not_configured"
    +
    +
    +class BenchmarkUnavailable(RuntimeError):
    +    """Raised when a backend is asked to retrieve without being available."""
    +
    +
    +def _http_get(url: str, auth: tuple[str, str] | None = None) -> tuple[bool, Any]:
    +    """Return ``(ok, payload)`` for a short-timeout GET.
    +
    +    Compose enables ``xpack.security.enabled``, so the probe must authenticate
    +    exactly like the production retriever; otherwise a healthy secured
    +    Elasticsearch answers 401 and would be misreported as unreachable.
    +    """
    +    if not url.lower().startswith(("http://", "https://")):
    +        # Only operator-configured http(s) endpoints are probed; never file:// or
    +        # a custom scheme, so this can never read a local path.
    +        return False, None
    +    request = urllib.request.Request(url)  # noqa: S310 - scheme validated above
    +    if auth and auth[0]:
    +        token = base64.b64encode(f"{auth[0]}:{auth[1]}".encode()).decode("ascii")
    +        request.add_header("Authorization", f"Basic {token}")
    +    try:
    +        with urllib.request.urlopen(request, timeout=PROBE_TIMEOUT_SECONDS) as response:  # noqa: S310
    +            body = response.read()
    +    except urllib.error.HTTPError as exc:
    +        # An HTTP-level answer (401/403/404) proves the service is reachable.
    +        return "http", exc.code
    +    except (urllib.error.URLError, OSError, ValueError):
    +        return False, None
    +    try:
    +        return True, json.loads(body)
    +    except (json.JSONDecodeError, UnicodeDecodeError):
    +        return True, body.decode("utf-8", errors="replace")
    +
    +
    +def _tcp_reachable(host: str, port: int) -> bool:
    +    try:
    +        with socket.create_connection((host, port), timeout=PROBE_TIMEOUT_SECONDS):
    +            return True
    +    except OSError:
    +        return False
    +
    +
    +def _elastic_settings() -> tuple[str, str, int, tuple[str, str] | None]:
    +    """Return ``(url, index, port, auth)`` derived from the live configuration.
    +
    +    The port comes from the URL when it embeds one, unless the configuration
    +    overrides it, so ``http://localhost:19200`` is probed on 19200 rather than on
    +    the 9200 default.
    +    """
    +    from urllib.parse import urlparse
    +
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    elastic = config.get("elasticsearch", {}) or {}
    +    url = str(elastic.get("host") or "http://elasticsearch:9200")
    +    index = str(elastic.get("index") or "cosmetics_docs")
    +    parsed = urlparse(url if "//" in url else f"//{url}")
    +    port = int(elastic.get("port") or parsed.port or (443 if parsed.scheme == "https" else 9200))
    +    auth: tuple[str, str] | None = None
    +    username = elastic.get("username") or os.environ.get("ELASTICSEARCH_USERNAME") or ""
    +    password = elastic.get("password") or os.environ.get("ELASTICSEARCH_PASSWORD") or ""
    +    if username:
    +        auth = (str(username), str(password))
    +    return url, index, port, auth
    +
    +
    +def _qdrant_settings() -> tuple[str, int, str]:
    +    """Return ``(host, port, text_collection)`` using the configured collection."""
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    qdrant = config.get("qdrant", {}) or {}
    +    host = str(qdrant.get("host") or "qdrant")
    +    port = int(qdrant.get("port") or 6333)
    +    configured = (config.get("embedding", {}).get("text", {}) or {}).get("collection")
    +    text_collection = str(
    +        configured or (qdrant.get("collections", {}) or {}).get("rag_text_768", {}).get("name") or "rag_text_768"
    +    )
    +    return host, port, text_collection
    +
    +
    +def _model_weights_available() -> tuple[bool, str | None]:
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    model_path = (config.get("embedding", {}).get("text", {}) or {}).get("model_path")
    +    if not model_path:
    +        return False, None
    +    from pathlib import Path
    +
    +    resolved = Path(str(model_path))
    +    if resolved.exists():
    +        return True, str(model_path)
    +    return False, str(model_path)
    +
    +
    +# ── Probes ────────────────────────────────────────────────────────────────
    +
    +
    +def probe_bm25() -> BackendAvailability:
    +    """BM25 needs a reachable, authenticated Elasticsearch holding the corpus."""
    +    url, index, port, auth = _elastic_settings()
    +    if not _tcp_reachable(url.split("//")[-1].split(":")[0], port):
    +        return BackendAvailability("bm25", False, REASON_SERVICE_UNREACHABLE, f"{url}:{port}")
    +    ok, payload = _http_get(f"{url.rstrip('/')}/{index}/_count", auth=auth)
    +    if ok == "http":
    +        # The service answered; a non-200 status is auth/index, not unreachability.
    +        return BackendAvailability(
    +            "bm25",
    +            False,
    +            REASON_SERVICE_NO_DATA,
    +            f"index {index} answered HTTP {payload} (auth or index problem, service reachable)",
    +        )
    +    if not ok:
    +        return BackendAvailability("bm25", False, REASON_SERVICE_UNREACHABLE, f"{url.rstrip('/')}/{index}")
    +    count = None
    +    if isinstance(payload, dict):
    +        count = payload.get("count")
    +    if count is None:
    +        return BackendAvailability("bm25", False, REASON_SERVICE_UNREACHABLE, "no count response")
    +    if int(count) == 0:
    +        return BackendAvailability("bm25", False, REASON_SERVICE_NO_DATA, f"index {index} is empty")
    +    return BackendAvailability("bm25", True, REASON_OK, f"index {index} has {count} docs")
    +
    +
    +def probe_dense() -> BackendAvailability:
    +    """Dense/BGE needs Qdrant text collection *and* real embedding weights."""
    +    host, port, collection = _qdrant_settings()
    +    if not _tcp_reachable(host, port):
    +        return BackendAvailability("dense", False, REASON_SERVICE_UNREACHABLE, f"{host}:{port}")
    +    ok, payload = _http_get(f"http://{host}:{port}/collections/{collection}")
    +    if not ok:
    +        return BackendAvailability("dense", False, REASON_SERVICE_UNREACHABLE, f"collection {collection}")

    <sub><sub>!P2 Badge</sub></sub> Reject HTTP errors from the Qdrant collection probe

    When Qdrant returns 401, 403, or 404 for this collection endpoint, _http_get returns the truthy sentinel "http"; this condition therefore accepts the error and, if the model directory exists, reports the dense backend as available even when the collection is absent or inaccessible. Handle the HTTP-error sentinel explicitly so availability manifests and --list-configs identify the actual blocker.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 02, 2026 05:56 UTC
    Code Review
    benchmarks/runner.py:1
    @@ -0,0 +1,213 @@
    +"""Benchmark orchestration.
    +
    +The runner is the only place that turns queries into metrics, and it always
    +records a :class:`~benchmarks.models.ConfigOutcome` per configuration. A
    +configuration either produces measured metrics, or it is reported as blocked /
    +skipped with a reason. There is no code path that produces metrics without a
    +retriever that actually returned ranked items.
    +
    +Synthetic retrievers
    +--------------------
    +Tests inject a deterministic fixture retriever through ``retriever_factory``.
    +Any run that used one is marked ``synthetic_retriever: true`` in the artifacts
    +and the report states that the numbers are *not* a retrieval benchmark. The CLI
    +never offers such a mode, so a synthetic run cannot reach a published artifact
    +by accident.
    +"""
    +
    +from __future__ import annotations
    +
    +from collections.abc import Callable, Sequence
    +from dataclasses import dataclass, field
    +from pathlib import Path
    +from typing import Any, Protocol
    +
    +from benchmarks import backends
    +from benchmarks.latency import new_latency_record, record_stage, stage_availability, summarize_latency, timed_stage
    +from benchmarks.metrics import aggregate_results, score_ranking
    +from benchmarks.models import (
    +    HIT_KS,
    +    MRR_K,
    +    NDCG_K,
    +    RECALL_KS,
    +    STATUS_BLOCKED,
    +    STATUS_EXECUTED,
    +    STATUS_SKIPPED,
    +    BackendAvailability,
    +    BenchmarkQuery,
    +    ConfigOutcome,
    +    QueryBenchmarkResult,
    +    RetrievedItem,
    +)
    +from benchmarks.relevance import RelevanceStrategy, dedupe_preserving_rank
    +
    +DEFAULT_TOP_K = 10
    +# Every reported cutoff must be observable. A retrieval depth below this value
    +# would silently understate Recall@10 / MRR@10 / NDCG@10 because results at
    +# ranks 6..10 could never be seen.
    +MIN_TOP_K = max(max(RECALL_KS), max(HIT_KS), MRR_K, NDCG_K)
    +
    +
    +class Retriever(Protocol):
    +    """Minimal retriever contract: question in, ranked items out."""
    +
    +    name: str
    +
    +    def retrieve(self, query: BenchmarkQuery, top_k: int) -> list[RetrievedItem]: ...
    +
    +
    +@dataclass
    +class ConfigRun:
    +    """Everything produced by one configuration."""
    +
    +    outcome: ConfigOutcome
    +    results: list[QueryBenchmarkResult] = field(default_factory=list)
    +
    +    @property
    +    def executed(self) -> bool:
    +        return self.outcome.produced_results
    +
    +
    +def _probe_backends(config_name: str, dataset_queries: int) -> tuple[BackendAvailability, ...]:
    +    manifest = backends.backend_manifest(config_name, dataset_queries)
    +    return tuple(
    +        BackendAvailability(
    +            name=item["backend"],
    +            available=bool(item["available"]),
    +            reason=str(item["reason"]),
    +            detail=item["detail"],
    +        )
    +        for item in manifest
    +    )
    +
    +
    +def run_configuration(
    +    config_name: str,
    +    queries: Sequence[BenchmarkQuery],
    +    top_k: int = DEFAULT_TOP_K,
    +    retriever_factory: Callable[[str], Retriever] | None = None,
    +    force_block_reason: str | None = None,
    +) -> ConfigRun:
    +    """Execute or block one configuration, returning its outcome and metrics."""
    +    if top_k < MIN_TOP_K:
    +        raise ValueError(
    +            f"top_k={top_k} is below the largest reported cutoff ({MIN_TOP_K}); "
    +            "retrieval depth must cover every metric cutoff so Recall@K/MRR/NDCG are not understated"
    +        )
    +    if config_name not in backends.CONFIG_DESCRIPTIONS:
    +        outcome = ConfigOutcome(config_name, STATUS_SKIPPED, f"unknown configuration: {config_name}")
    +        return ConfigRun(outcome)
    +
    +    if force_block_reason:
    +        outcome = ConfigOutcome(config_name, STATUS_SKIPPED, force_block_reason)
    +        return ConfigRun(outcome)
    +
    +    availability = backends.evaluate_config(config_name, len(queries))
    +    probed = _probe_backends(config_name, len(queries))
    +
    +    if retriever_factory is None:
    +        if availability.available:
    +            # Availability without an implemented executor must still not claim
    +            # results; surface the missing executor instead of inventing it.
    +            outcome = ConfigOutcome(
    +                config_name,
    +                STATUS_BLOCKED,
    +                "no real retrieval executor is wired for this configuration yet",
    +                probed,
    +            )
    +            return ConfigRun(outcome)
    +        outcome = ConfigOutcome(
    +            config_name,
    +            STATUS_BLOCKED,
    +            f"unavailable backends: {availability.describe()}",
    +            probed,
    +        )
    +        return ConfigRun(outcome)
    +
    +    retriever = retriever_factory(config_name)
    +    results: list[QueryBenchmarkResult] = []
    +    stages = backends.STAGE_BY_CONFIG[config_name]
    +    for query in queries:
    +        latency = new_latency_record()
    +        with timed_stage(latency, "total_retrieval_ms"):
    +            items = retriever.retrieve(query, top_k)
    +        deduped = dedupe_preserving_rank(items)[:top_k]
    +        scored = score_ranking(
    +            [item.key for item in query.relevant_items],
    +            [item.key for item in deduped],
    +        )
    +        # Only the stages this configuration declares as active are recorded;
    +        # every other stage stays None so it cannot look measured.
    +        for stage in stages:
    +            if stage == "total_retrieval_ms":
    +                continue
    +            record_stage(latency, stage, latency["total_retrieval_ms"])

    <sub><sub>!P2 Badge</sub></sub> Leave unmeasured stage latency unset

    For every configuration executed through retriever_factory, this assigns the same end-to-end retrieval duration to each declared stage; a hybrid run consequently reports BM25, dense, RRF, and reranking as all taking the full request time even though none was timed separately. This corrupts the advertised per-stage percentile data, so these fields should remain None unless the executor supplies actual stage timings.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 02, 2026 05:56 UTC
    Code Review
    benchmarks/backends.py:1
    @@ -0,0 +1,299 @@
    +"""Retrieval backends for the benchmark.
    +
    +Every backend is probed before it is used, and a backend that cannot answer a
    +real probe is reported as unavailable. The harness never substitutes a stand-in
    +retriever for a missing one: a benchmark that silently ranks with a fake backend
    +would produce numbers that look like retrieval quality while measuring nothing.
    +
    +Two independent things are required for a meaningful measurement:
    +
    +1. a **live retrieval service** (Elasticsearch / Qdrant) and real model assets;
    +2. a **corpus that actually contains the ground-truth passages**.
    +
    +Requirement 2 is easy to overlook. The golden set stores ground truth as passage
    +*text*; the operator corpus is their own private material. Indexing the golden
    +set passages themselves and then measuring recall would be self-referential —
    +every configuration would trivially reach recall 1.0 — so this module refuses that
    +shortcut and reports the corpus requirement explicitly instead.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import os
    +import socket
    +import urllib.error
    +import urllib.request
    +from dataclasses import dataclass
    +from typing import Any
    +
    +from benchmarks.models import BackendAvailability
    +
    +PROBE_TIMEOUT_SECONDS = 2.0
    +
    +REASON_OK = "available"
    +REASON_SERVICE_UNREACHABLE = "service_unreachable"
    +REASON_SERVICE_NO_DATA = "service_reachable_but_empty"
    +REASON_MODEL_UNAVAILABLE = "model_assets_unavailable"
    +REASON_CORPUS_UNRESOLVED = "corpus_does_not_contain_ground_truth"
    +REASON_NOT_CONFIGURED = "not_configured"
    +
    +
    +class BenchmarkUnavailable(RuntimeError):
    +    """Raised when a backend is asked to retrieve without being available."""
    +
    +
    +def _http_get(url: str, auth: tuple[str, str] | None = None) -> tuple[bool, Any]:
    +    """Return ``(ok, payload)`` for a short-timeout GET.
    +
    +    Compose enables ``xpack.security.enabled``, so the probe must authenticate
    +    exactly like the production retriever; otherwise a healthy secured
    +    Elasticsearch answers 401 and would be misreported as unreachable.
    +    """
    +    if not url.lower().startswith(("http://", "https://")):
    +        # Only operator-configured http(s) endpoints are probed; never file:// or
    +        # a custom scheme, so this can never read a local path.
    +        return False, None
    +    request = urllib.request.Request(url)  # noqa: S310 - scheme validated above
    +    if auth and auth[0]:
    +        token = base64.b64encode(f"{auth[0]}:{auth[1]}".encode()).decode("ascii")
    +        request.add_header("Authorization", f"Basic {token}")
    +    try:
    +        with urllib.request.urlopen(request, timeout=PROBE_TIMEOUT_SECONDS) as response:  # noqa: S310
    +            body = response.read()
    +    except urllib.error.HTTPError as exc:
    +        # An HTTP-level answer (401/403/404) proves the service is reachable.
    +        return "http", exc.code
    +    except (urllib.error.URLError, OSError, ValueError):
    +        return False, None
    +    try:
    +        return True, json.loads(body)
    +    except (json.JSONDecodeError, UnicodeDecodeError):
    +        return True, body.decode("utf-8", errors="replace")
    +
    +
    +def _tcp_reachable(host: str, port: int) -> bool:
    +    try:
    +        with socket.create_connection((host, port), timeout=PROBE_TIMEOUT_SECONDS):
    +            return True
    +    except OSError:
    +        return False
    +
    +
    +def _elastic_settings() -> tuple[str, str, int, tuple[str, str] | None]:
    +    """Return ``(url, index, port, auth)`` derived from the live configuration.
    +
    +    The port comes from the URL when it embeds one, unless the configuration
    +    overrides it, so ``http://localhost:19200`` is probed on 19200 rather than on
    +    the 9200 default.
    +    """
    +    from urllib.parse import urlparse
    +
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    elastic = config.get("elasticsearch", {}) or {}
    +    url = str(elastic.get("host") or "http://elasticsearch:9200")
    +    index = str(elastic.get("index") or "cosmetics_docs")
    +    parsed = urlparse(url if "//" in url else f"//{url}")
    +    port = int(elastic.get("port") or parsed.port or (443 if parsed.scheme == "https" else 9200))
    +    auth: tuple[str, str] | None = None
    +    username = elastic.get("username") or os.environ.get("ELASTICSEARCH_USERNAME") or ""
    +    password = elastic.get("password") or os.environ.get("ELASTICSEARCH_PASSWORD") or ""

    <sub><sub>!P2 Badge</sub></sub> Prefer environment credentials in the Elasticsearch probe

    When config.json contains credentials but a deployment overrides them with ELASTICSEARCH_USERNAME or ELASTICSEARCH_PASSWORD, the probe uses the config values while the production BM25Retriever uses environment values first. The new auth path now reads the environment, but only as a fallback, so credential rotation or deployment overrides can make real retrieval succeed while the benchmark receives a 401 and reports the backend blocked.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Oct 02, 2026 05:56 UTC
    Reviewer

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: 219e0c6885

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    </details>

    Xander-Xai Xander-Xai commented on code on Oct 02, 2026 06:05 UTC
    Code Review
    benchmarks/backends.py:1
    @@ -0,0 +1,299 @@
    +"""Retrieval backends for the benchmark.
    +
    +Every backend is probed before it is used, and a backend that cannot answer a
    +real probe is reported as unavailable. The harness never substitutes a stand-in
    +retriever for a missing one: a benchmark that silently ranks with a fake backend
    +would produce numbers that look like retrieval quality while measuring nothing.
    +
    +Two independent things are required for a meaningful measurement:
    +
    +1. a **live retrieval service** (Elasticsearch / Qdrant) and real model assets;
    +2. a **corpus that actually contains the ground-truth passages**.
    +
    +Requirement 2 is easy to overlook. The golden set stores ground truth as passage
    +*text*; the operator corpus is their own private material. Indexing the golden
    +set passages themselves and then measuring recall would be self-referential —
    +every configuration would trivially reach recall 1.0 — so this module refuses that
    +shortcut and reports the corpus requirement explicitly instead.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import os
    +import socket
    +import urllib.error
    +import urllib.request
    +from dataclasses import dataclass
    +from typing import Any
    +
    +from benchmarks.models import BackendAvailability
    +
    +PROBE_TIMEOUT_SECONDS = 2.0
    +
    +REASON_OK = "available"
    +REASON_SERVICE_UNREACHABLE = "service_unreachable"
    +REASON_SERVICE_NO_DATA = "service_reachable_but_empty"
    +REASON_MODEL_UNAVAILABLE = "model_assets_unavailable"
    +REASON_CORPUS_UNRESOLVED = "corpus_does_not_contain_ground_truth"
    +REASON_NOT_CONFIGURED = "not_configured"
    +
    +
    +class BenchmarkUnavailable(RuntimeError):
    +    """Raised when a backend is asked to retrieve without being available."""
    +
    +
    +def _http_get(url: str, auth: tuple[str, str] | None = None) -> tuple[bool, Any]:
    +    """Return ``(ok, payload)`` for a short-timeout GET.
    +
    +    Compose enables ``xpack.security.enabled``, so the probe must authenticate
    +    exactly like the production retriever; otherwise a healthy secured
    +    Elasticsearch answers 401 and would be misreported as unreachable.
    +    """
    +    if not url.lower().startswith(("http://", "https://")):
    +        # Only operator-configured http(s) endpoints are probed; never file:// or
    +        # a custom scheme, so this can never read a local path.
    +        return False, None
    +    request = urllib.request.Request(url)  # noqa: S310 - scheme validated above
    +    if auth and auth[0]:
    +        token = base64.b64encode(f"{auth[0]}:{auth[1]}".encode()).decode("ascii")
    +        request.add_header("Authorization", f"Basic {token}")
    +    try:
    +        with urllib.request.urlopen(request, timeout=PROBE_TIMEOUT_SECONDS) as response:  # noqa: S310
    +            body = response.read()
    +    except urllib.error.HTTPError as exc:
    +        # An HTTP-level answer (401/403/404) proves the service is reachable.
    +        return "http", exc.code
    +    except (urllib.error.URLError, OSError, ValueError):
    +        return False, None
    +    try:
    +        return True, json.loads(body)
    +    except (json.JSONDecodeError, UnicodeDecodeError):
    +        return True, body.decode("utf-8", errors="replace")
    +
    +
    +def _tcp_reachable(host: str, port: int) -> bool:
    +    try:
    +        with socket.create_connection((host, port), timeout=PROBE_TIMEOUT_SECONDS):
    +            return True
    +    except OSError:
    +        return False
    +
    +
    +def _elastic_settings() -> tuple[str, str, int, tuple[str, str] | None]:
    +    """Return ``(url, index, port, auth)`` derived from the live configuration.
    +
    +    The port comes from the URL when it embeds one, unless the configuration
    +    overrides it, so ``http://localhost:19200`` is probed on 19200 rather than on
    +    the 9200 default.
    +    """
    +    from urllib.parse import urlparse
    +
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    elastic = config.get("elasticsearch", {}) or {}
    +    url = str(elastic.get("host") or "http://elasticsearch:9200")
    +    index = str(elastic.get("index") or "cosmetics_docs")
    +    parsed = urlparse(url if "//" in url else f"//{url}")
    +    port = int(elastic.get("port") or parsed.port or (443 if parsed.scheme == "https" else 9200))
    +    auth: tuple[str, str] | None = None
    +    username = elastic.get("username") or os.environ.get("ELASTICSEARCH_USERNAME") or ""
    +    password = elastic.get("password") or os.environ.get("ELASTICSEARCH_PASSWORD") or ""
    +    if username:
    +        auth = (str(username), str(password))
    +    return url, index, port, auth
    +
    +
    +def _qdrant_settings() -> tuple[str, int, str]:
    +    """Return ``(host, port, text_collection)`` using the configured collection."""
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    qdrant = config.get("qdrant", {}) or {}
    +    host = str(qdrant.get("host") or "qdrant")
    +    port = int(qdrant.get("port") or 6333)
    +    configured = (config.get("embedding", {}).get("text", {}) or {}).get("collection")
    +    text_collection = str(
    +        configured or (qdrant.get("collections", {}) or {}).get("rag_text_768", {}).get("name") or "rag_text_768"
    +    )
    +    return host, port, text_collection
    +
    +
    +def _model_weights_available() -> tuple[bool, str | None]:
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    model_path = (config.get("embedding", {}).get("text", {}) or {}).get("model_path")
    +    if not model_path:
    +        return False, None
    +    from pathlib import Path
    +
    +    resolved = Path(str(model_path))
    +    if resolved.exists():
    +        return True, str(model_path)
    +    return False, str(model_path)
    +
    +
    +# ── Probes ────────────────────────────────────────────────────────────────
    +
    +
    +def probe_bm25() -> BackendAvailability:
    +    """BM25 needs a reachable, authenticated Elasticsearch holding the corpus."""
    +    url, index, port, auth = _elastic_settings()
    +    if not _tcp_reachable(url.split("//")[-1].split(":")[0], port):
    +        return BackendAvailability("bm25", False, REASON_SERVICE_UNREACHABLE, f"{url}:{port}")
    +    ok, payload = _http_get(f"{url.rstrip('/')}/{index}/_count", auth=auth)
    +    if ok == "http":
    +        # The service answered; a non-200 status is auth/index, not unreachability.
    +        return BackendAvailability(
    +            "bm25",
    +            False,
    +            REASON_SERVICE_NO_DATA,
    +            f"index {index} answered HTTP {payload} (auth or index problem, service reachable)",
    +        )
    +    if not ok:
    +        return BackendAvailability("bm25", False, REASON_SERVICE_UNREACHABLE, f"{url.rstrip('/')}/{index}")
    +    count = None
    +    if isinstance(payload, dict):
    +        count = payload.get("count")
    +    if count is None:
    +        return BackendAvailability("bm25", False, REASON_SERVICE_UNREACHABLE, "no count response")
    +    if int(count) == 0:
    +        return BackendAvailability("bm25", False, REASON_SERVICE_NO_DATA, f"index {index} is empty")
    +    return BackendAvailability("bm25", True, REASON_OK, f"index {index} has {count} docs")
    +
    +
    +def probe_dense() -> BackendAvailability:
    +    """Dense/BGE needs Qdrant text collection *and* real embedding weights."""
    +    host, port, collection = _qdrant_settings()
    +    if not _tcp_reachable(host, port):
    +        return BackendAvailability("dense", False, REASON_SERVICE_UNREACHABLE, f"{host}:{port}")
    +    ok, payload = _http_get(f"http://{host}:{port}/collections/{collection}")
    +    if not ok:
    +        return BackendAvailability("dense", False, REASON_SERVICE_UNREACHABLE, f"collection {collection}")

    Confirmed. Root cause: _http_get returns the truthy sentinel "http" on an HTTP-level error, so if not ok was False and a 401/404 for the Qdrant collection fell through to the model check and could report the dense backend as available. Fix: probe_dense handles the sentinel explicitly and reports service_reachable_but_empty with the status code, naming the collection as the blocker. Regression test: test_qdrant_http_error_is_not_treated_as_available (verified failing against the previous code). Commit 8ee0921.

    Xander-Xai Xander-Xai commented on code on Oct 02, 2026 06:05 UTC
    Code Review
    benchmarks/runner.py:1
    @@ -0,0 +1,213 @@
    +"""Benchmark orchestration.
    +
    +The runner is the only place that turns queries into metrics, and it always
    +records a :class:`~benchmarks.models.ConfigOutcome` per configuration. A
    +configuration either produces measured metrics, or it is reported as blocked /
    +skipped with a reason. There is no code path that produces metrics without a
    +retriever that actually returned ranked items.
    +
    +Synthetic retrievers
    +--------------------
    +Tests inject a deterministic fixture retriever through ``retriever_factory``.
    +Any run that used one is marked ``synthetic_retriever: true`` in the artifacts
    +and the report states that the numbers are *not* a retrieval benchmark. The CLI
    +never offers such a mode, so a synthetic run cannot reach a published artifact
    +by accident.
    +"""
    +
    +from __future__ import annotations
    +
    +from collections.abc import Callable, Sequence
    +from dataclasses import dataclass, field
    +from pathlib import Path
    +from typing import Any, Protocol
    +
    +from benchmarks import backends
    +from benchmarks.latency import new_latency_record, record_stage, stage_availability, summarize_latency, timed_stage
    +from benchmarks.metrics import aggregate_results, score_ranking
    +from benchmarks.models import (
    +    HIT_KS,
    +    MRR_K,
    +    NDCG_K,
    +    RECALL_KS,
    +    STATUS_BLOCKED,
    +    STATUS_EXECUTED,
    +    STATUS_SKIPPED,
    +    BackendAvailability,
    +    BenchmarkQuery,
    +    ConfigOutcome,
    +    QueryBenchmarkResult,
    +    RetrievedItem,
    +)
    +from benchmarks.relevance import RelevanceStrategy, dedupe_preserving_rank
    +
    +DEFAULT_TOP_K = 10
    +# Every reported cutoff must be observable. A retrieval depth below this value
    +# would silently understate Recall@10 / MRR@10 / NDCG@10 because results at
    +# ranks 6..10 could never be seen.
    +MIN_TOP_K = max(max(RECALL_KS), max(HIT_KS), MRR_K, NDCG_K)
    +
    +
    +class Retriever(Protocol):
    +    """Minimal retriever contract: question in, ranked items out."""
    +
    +    name: str
    +
    +    def retrieve(self, query: BenchmarkQuery, top_k: int) -> list[RetrievedItem]: ...
    +
    +
    +@dataclass
    +class ConfigRun:
    +    """Everything produced by one configuration."""
    +
    +    outcome: ConfigOutcome
    +    results: list[QueryBenchmarkResult] = field(default_factory=list)
    +
    +    @property
    +    def executed(self) -> bool:
    +        return self.outcome.produced_results
    +
    +
    +def _probe_backends(config_name: str, dataset_queries: int) -> tuple[BackendAvailability, ...]:
    +    manifest = backends.backend_manifest(config_name, dataset_queries)
    +    return tuple(
    +        BackendAvailability(
    +            name=item["backend"],
    +            available=bool(item["available"]),
    +            reason=str(item["reason"]),
    +            detail=item["detail"],
    +        )
    +        for item in manifest
    +    )
    +
    +
    +def run_configuration(
    +    config_name: str,
    +    queries: Sequence[BenchmarkQuery],
    +    top_k: int = DEFAULT_TOP_K,
    +    retriever_factory: Callable[[str], Retriever] | None = None,
    +    force_block_reason: str | None = None,
    +) -> ConfigRun:
    +    """Execute or block one configuration, returning its outcome and metrics."""
    +    if top_k < MIN_TOP_K:
    +        raise ValueError(
    +            f"top_k={top_k} is below the largest reported cutoff ({MIN_TOP_K}); "
    +            "retrieval depth must cover every metric cutoff so Recall@K/MRR/NDCG are not understated"
    +        )
    +    if config_name not in backends.CONFIG_DESCRIPTIONS:
    +        outcome = ConfigOutcome(config_name, STATUS_SKIPPED, f"unknown configuration: {config_name}")
    +        return ConfigRun(outcome)
    +
    +    if force_block_reason:
    +        outcome = ConfigOutcome(config_name, STATUS_SKIPPED, force_block_reason)
    +        return ConfigRun(outcome)
    +
    +    availability = backends.evaluate_config(config_name, len(queries))
    +    probed = _probe_backends(config_name, len(queries))
    +
    +    if retriever_factory is None:
    +        if availability.available:
    +            # Availability without an implemented executor must still not claim
    +            # results; surface the missing executor instead of inventing it.
    +            outcome = ConfigOutcome(
    +                config_name,
    +                STATUS_BLOCKED,
    +                "no real retrieval executor is wired for this configuration yet",
    +                probed,
    +            )
    +            return ConfigRun(outcome)
    +        outcome = ConfigOutcome(
    +            config_name,
    +            STATUS_BLOCKED,
    +            f"unavailable backends: {availability.describe()}",
    +            probed,
    +        )
    +        return ConfigRun(outcome)
    +
    +    retriever = retriever_factory(config_name)
    +    results: list[QueryBenchmarkResult] = []
    +    stages = backends.STAGE_BY_CONFIG[config_name]
    +    for query in queries:
    +        latency = new_latency_record()
    +        with timed_stage(latency, "total_retrieval_ms"):
    +            items = retriever.retrieve(query, top_k)
    +        deduped = dedupe_preserving_rank(items)[:top_k]
    +        scored = score_ranking(
    +            [item.key for item in query.relevant_items],
    +            [item.key for item in deduped],
    +        )
    +        # Only the stages this configuration declares as active are recorded;
    +        # every other stage stays None so it cannot look measured.
    +        for stage in stages:
    +            if stage == "total_retrieval_ms":
    +                continue
    +            record_stage(latency, stage, latency["total_retrieval_ms"])

    Confirmed; this was a correctness/honesty defect in my own code. Root cause: the runner copied the end-to-end duration into every declared stage, so a hybrid run advertised BM25, dense, RRF and rerank as each taking the full request time although none was timed. Fix: only total_retrieval_ms is measured; every other stage stays None until a real executor supplies a timing. Regression test: test_per_stage_latency_is_not_fabricated asserts all non-total stages stay None and stage_availability reports 0 (verified failing against the previous code). Commit 8ee0921.

    Xander-Xai Xander-Xai commented on code on Oct 02, 2026 06:05 UTC
    Code Review
    benchmarks/backends.py:1
    @@ -0,0 +1,299 @@
    +"""Retrieval backends for the benchmark.
    +
    +Every backend is probed before it is used, and a backend that cannot answer a
    +real probe is reported as unavailable. The harness never substitutes a stand-in
    +retriever for a missing one: a benchmark that silently ranks with a fake backend
    +would produce numbers that look like retrieval quality while measuring nothing.
    +
    +Two independent things are required for a meaningful measurement:
    +
    +1. a **live retrieval service** (Elasticsearch / Qdrant) and real model assets;
    +2. a **corpus that actually contains the ground-truth passages**.
    +
    +Requirement 2 is easy to overlook. The golden set stores ground truth as passage
    +*text*; the operator corpus is their own private material. Indexing the golden
    +set passages themselves and then measuring recall would be self-referential —
    +every configuration would trivially reach recall 1.0 — so this module refuses that
    +shortcut and reports the corpus requirement explicitly instead.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import os
    +import socket
    +import urllib.error
    +import urllib.request
    +from dataclasses import dataclass
    +from typing import Any
    +
    +from benchmarks.models import BackendAvailability
    +
    +PROBE_TIMEOUT_SECONDS = 2.0
    +
    +REASON_OK = "available"
    +REASON_SERVICE_UNREACHABLE = "service_unreachable"
    +REASON_SERVICE_NO_DATA = "service_reachable_but_empty"
    +REASON_MODEL_UNAVAILABLE = "model_assets_unavailable"
    +REASON_CORPUS_UNRESOLVED = "corpus_does_not_contain_ground_truth"
    +REASON_NOT_CONFIGURED = "not_configured"
    +
    +
    +class BenchmarkUnavailable(RuntimeError):
    +    """Raised when a backend is asked to retrieve without being available."""
    +
    +
    +def _http_get(url: str, auth: tuple[str, str] | None = None) -> tuple[bool, Any]:
    +    """Return ``(ok, payload)`` for a short-timeout GET.
    +
    +    Compose enables ``xpack.security.enabled``, so the probe must authenticate
    +    exactly like the production retriever; otherwise a healthy secured
    +    Elasticsearch answers 401 and would be misreported as unreachable.
    +    """
    +    if not url.lower().startswith(("http://", "https://")):
    +        # Only operator-configured http(s) endpoints are probed; never file:// or
    +        # a custom scheme, so this can never read a local path.
    +        return False, None
    +    request = urllib.request.Request(url)  # noqa: S310 - scheme validated above
    +    if auth and auth[0]:
    +        token = base64.b64encode(f"{auth[0]}:{auth[1]}".encode()).decode("ascii")
    +        request.add_header("Authorization", f"Basic {token}")
    +    try:
    +        with urllib.request.urlopen(request, timeout=PROBE_TIMEOUT_SECONDS) as response:  # noqa: S310
    +            body = response.read()
    +    except urllib.error.HTTPError as exc:
    +        # An HTTP-level answer (401/403/404) proves the service is reachable.
    +        return "http", exc.code
    +    except (urllib.error.URLError, OSError, ValueError):
    +        return False, None
    +    try:
    +        return True, json.loads(body)
    +    except (json.JSONDecodeError, UnicodeDecodeError):
    +        return True, body.decode("utf-8", errors="replace")
    +
    +
    +def _tcp_reachable(host: str, port: int) -> bool:
    +    try:
    +        with socket.create_connection((host, port), timeout=PROBE_TIMEOUT_SECONDS):
    +            return True
    +    except OSError:
    +        return False
    +
    +
    +def _elastic_settings() -> tuple[str, str, int, tuple[str, str] | None]:
    +    """Return ``(url, index, port, auth)`` derived from the live configuration.
    +
    +    The port comes from the URL when it embeds one, unless the configuration
    +    overrides it, so ``http://localhost:19200`` is probed on 19200 rather than on
    +    the 9200 default.
    +    """
    +    from urllib.parse import urlparse
    +
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    elastic = config.get("elasticsearch", {}) or {}
    +    url = str(elastic.get("host") or "http://elasticsearch:9200")
    +    index = str(elastic.get("index") or "cosmetics_docs")
    +    parsed = urlparse(url if "//" in url else f"//{url}")
    +    port = int(elastic.get("port") or parsed.port or (443 if parsed.scheme == "https" else 9200))
    +    auth: tuple[str, str] | None = None
    +    username = elastic.get("username") or os.environ.get("ELASTICSEARCH_USERNAME") or ""
    +    password = elastic.get("password") or os.environ.get("ELASTICSEARCH_PASSWORD") or ""

    Confirmed. Root cause: the probe read config.json first and used the environment only as a fallback, which is the reverse of retrieval/bm25_retriever.py:48-50 where the environment wins. Fix: the probe now mirrors production exactly (ELASTICSEARCH_USERNAME/ELASTICSEARCH_PASSWORD first, config.json as fallback) and requires both parts before authenticating. Regression tests: test_environment_credentials_take_precedence_over_config (verified failing before the fix) and test_config_credentials_used_when_env_absent. Commit 8ee0921.

    Xander-Xai Xander-Xai commented on Oct 02, 2026 06:06 UTC
    Author

    @codex review

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 02, 2026 06:09 UTC
    Code Review
    benchmarks/retrieval_benchmark.py:1
    @@ -0,0 +1,221 @@
    +"""Command-line entry point for the retrieval benchmark.
    +
    +Examples
    +--------
    +List what the current environment can actually execute::
    +
    +    python -m benchmarks.retrieval_benchmark --list-configs
    +
    +Attempt a real run (writes an artifact set even when everything is blocked)::
    +
    +    python -m benchmarks.retrieval_benchmark --config bm25 --limit 5
    +
    +The CLI has no flag that installs a fake retriever. A synthetic retriever can
    +only be supplied programmatically by tests, and any run that used one is flagged
    +in its artifacts.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import sys
    +from pathlib import Path
    +
    +from benchmarks import backends, report
    +from benchmarks.dataset import (
    +    DEFAULT_DATASET_PATH,
    +    DatasetError,
    +    bucket_coverage,
    +    load_queries,
    +    load_rows,
    +    sample_ids_hash,
    +    sha256_file,
    +)
    +from benchmarks.models import STATUS_EXECUTED
    +from benchmarks.provenance import (
    +    collect_environment,
    +    git_provenance,
    +    new_run_id,
    +    now_utc,
    +    render_environment,
    +    sha256_json,
    +    write_gitignore_entry,
    +)
    +from benchmarks.runner import DEFAULT_TOP_K, MIN_TOP_K, run_configuration, summarize_run, write_per_query_jsonl
    +
    +DEFAULT_OUTPUT_DIR = "artifacts/benchmarks"
    +
    +
    +def build_parser() -> argparse.ArgumentParser:
    +    parser = argparse.ArgumentParser(
    +        prog="python -m benchmarks.retrieval_benchmark",
    +        description="Deterministic retrieval benchmark (no RAGAS evaluator required).",
    +    )
    +    parser.add_argument("--config", help="single configuration to run")
    +    parser.add_argument("--configs", help="comma-separated configurations to run")
    +    parser.add_argument("--dataset", default=DEFAULT_DATASET_PATH, help="golden set JSONL path")
    +    parser.add_argument("--limit", type=int, default=None, help="only use the first N samples")
    +    parser.add_argument("--sample-id", action="append", default=None, help="run only this sample id (repeatable)")
    +    parser.add_argument("--top-k", type=int, default=DEFAULT_TOP_K, help="retrieval depth (default 10)")
    +    parser.add_argument("--output-dir", default=DEFAULT_OUTPUT_DIR, help="artifact root directory")
    +    parser.add_argument(
    +        "--allow-dirty",
    +        action="store_true",
    +        help="allow running with a dirty working tree (recorded as git_dirty=true)",
    +    )
    +    parser.add_argument(
    +        "--require-results",
    +        action="store_true",
    +        help="exit non-zero when no configuration executed (useful to fail CI on blocked runs)",
    +    )
    +    parser.add_argument("--list-configs", action="store_true", help="print configuration availability and exit")
    +    return parser
    +
    +
    +def _resolve_configs(args: argparse.Namespace) -> list[str]:
    +    if args.config and args.configs:
    +        raise SystemExit("use either --config or --configs, not both")
    +    if args.config:
    +        return [args.config]
    +    if args.configs:
    +        return [item.strip() for item in args.configs.split(",") if item.strip()]
    +    return ["bm25", "dense", "hybrid_rrf"]
    +
    +
    +def _print_configs(dataset_queries: int) -> int:
    +    print("configurations (availability probed live):\n")
    +    for name, description in backends.CONFIG_DESCRIPTIONS.items():
    +        availability = backends.evaluate_config(name, dataset_queries)
    +        state = "EXECUTABLE" if availability.available else "BLOCKED"
    +        print(f"  {name:36s} {state:12s} {description}")
    +        if not availability.available:
    +            print(f"  {'':36s} reasons: {availability.describe()}")
    +            if availability.detail:
    +                print(f"  {'':36s} detail:  {availability.detail}")
    +    print("\nNote: a configuration is only reported EXECUTABLE when every required backend")
    +    print("and the benchmark corpus answered a real probe. No stand-in retriever is used.")
    +    return 0
    +
    +
    +def main(argv: list[str] | None = None) -> int:
    +    parser = build_parser()
    +    args = parser.parse_args(argv)
    +
    +    repo_root = Path(__file__).resolve().parents[1]
    +    dataset_path = Path(args.dataset)
    +    if not dataset_path.is_file():
    +        print(f"dataset not found: {dataset_path}", file=sys.stderr)
    +        return 2
    +
    +    try:
    +        rows = load_rows(dataset_path)
    +    except DatasetError as exc:
    +        print(f"dataset error: {exc}", file=sys.stderr)
    +        return 2
    +
    +    if args.list_configs:
    +        return _print_configs(len(rows))
    +
    +    if args.top_k < MIN_TOP_K:
    +        print(
    +            f"--top-k must be >= {MIN_TOP_K} so every reported metric cutoff (Recall@10, MRR@10, "
    +            f"NDCG@10) is observable; got {args.top_k}. Lowering it would silently understate them.",
    +            file=sys.stderr,
    +        )
    +        return 2
    +
    +    configs = _resolve_configs(args)
    +    unknown = [name for name in configs if name not in backends.CONFIG_DESCRIPTIONS]
    +    if unknown:
    +        print(f"unknown configuration(s): {', '.join(unknown)}", file=sys.stderr)
    +        return 2
    +
    +    git_sha, git_dirty = git_provenance(repo_root)
    +    if git_dirty and not args.allow_dirty:
    +        print(
    +            "refusing to run on a dirty working tree; commit your changes or pass --allow-dirty "
    +            "(the artifact will record git_dirty=true)",
    +            file=sys.stderr,
    +        )
    +        return 3
    +
    +    try:
    +        queries = load_queries(dataset_path, limit=args.limit, sample_ids=args.sample_id)
    +    except DatasetError as exc:
    +        print(f"dataset error: {exc}", file=sys.stderr)
    +        return 2
    +
    +    run_id = new_run_id()
    +    config_payload = {"configs": configs, "top_k": args.top_k, "dataset_sha256": sha256_file(dataset_path)}

    <sub><sub>!P2 Badge</sub></sub> Hash the effective retrieval configuration

    config_sha256 only hashes the selected configuration names, top_k, and dataset hash, so runs using different CONFIG_PATH files or Qdrant environment overrides can receive the same configuration hash despite querying different indexes, collections, model revisions, or retrieval settings. This makes the provenance insufficient to reproduce or safely compare results; hash a sanitized snapshot of the effective runtime configuration, including applied environment overrides.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 02, 2026 06:09 UTC
    Code Review
    benchmarks/runner.py:1
    @@ -0,0 +1,209 @@
    +"""Benchmark orchestration.
    +
    +The runner is the only place that turns queries into metrics, and it always
    +records a :class:`~benchmarks.models.ConfigOutcome` per configuration. A
    +configuration either produces measured metrics, or it is reported as blocked /
    +skipped with a reason. There is no code path that produces metrics without a
    +retriever that actually returned ranked items.
    +
    +Synthetic retrievers
    +--------------------
    +Tests inject a deterministic fixture retriever through ``retriever_factory``.
    +Any run that used one is marked ``synthetic_retriever: true`` in the artifacts
    +and the report states that the numbers are *not* a retrieval benchmark. The CLI
    +never offers such a mode, so a synthetic run cannot reach a published artifact
    +by accident.
    +"""
    +
    +from __future__ import annotations
    +
    +from collections.abc import Callable, Sequence
    +from dataclasses import dataclass, field
    +from pathlib import Path
    +from typing import Any, Protocol
    +
    +from benchmarks import backends
    +from benchmarks.latency import new_latency_record, stage_availability, summarize_latency, timed_stage
    +from benchmarks.metrics import aggregate_results, score_ranking
    +from benchmarks.models import (
    +    HIT_KS,
    +    MRR_K,
    +    NDCG_K,
    +    RECALL_KS,
    +    STATUS_BLOCKED,
    +    STATUS_EXECUTED,
    +    STATUS_SKIPPED,
    +    BackendAvailability,
    +    BenchmarkQuery,
    +    ConfigOutcome,
    +    QueryBenchmarkResult,
    +    RetrievedItem,
    +)
    +from benchmarks.relevance import RelevanceStrategy, dedupe_preserving_rank
    +
    +DEFAULT_TOP_K = 10
    +# Every reported cutoff must be observable. A retrieval depth below this value
    +# would silently understate Recall@10 / MRR@10 / NDCG@10 because results at
    +# ranks 6..10 could never be seen.
    +MIN_TOP_K = max(max(RECALL_KS), max(HIT_KS), MRR_K, NDCG_K)
    +
    +
    +class Retriever(Protocol):
    +    """Minimal retriever contract: question in, ranked items out."""
    +
    +    name: str
    +
    +    def retrieve(self, query: BenchmarkQuery, top_k: int) -> list[RetrievedItem]: ...
    +
    +
    +@dataclass
    +class ConfigRun:
    +    """Everything produced by one configuration."""
    +
    +    outcome: ConfigOutcome
    +    results: list[QueryBenchmarkResult] = field(default_factory=list)
    +
    +    @property
    +    def executed(self) -> bool:
    +        return self.outcome.produced_results
    +
    +
    +def _probe_backends(config_name: str, dataset_queries: int) -> tuple[BackendAvailability, ...]:
    +    manifest = backends.backend_manifest(config_name, dataset_queries)
    +    return tuple(
    +        BackendAvailability(
    +            name=item["backend"],
    +            available=bool(item["available"]),
    +            reason=str(item["reason"]),
    +            detail=item["detail"],
    +        )
    +        for item in manifest
    +    )
    +
    +
    +def run_configuration(
    +    config_name: str,
    +    queries: Sequence[BenchmarkQuery],
    +    top_k: int = DEFAULT_TOP_K,
    +    retriever_factory: Callable[[str], Retriever] | None = None,
    +    force_block_reason: str | None = None,
    +) -> ConfigRun:
    +    """Execute or block one configuration, returning its outcome and metrics."""
    +    if top_k < MIN_TOP_K:
    +        raise ValueError(
    +            f"top_k={top_k} is below the largest reported cutoff ({MIN_TOP_K}); "
    +            "retrieval depth must cover every metric cutoff so Recall@K/MRR/NDCG are not understated"
    +        )
    +    if config_name not in backends.CONFIG_DESCRIPTIONS:
    +        outcome = ConfigOutcome(config_name, STATUS_SKIPPED, f"unknown configuration: {config_name}")
    +        return ConfigRun(outcome)
    +
    +    if force_block_reason:
    +        outcome = ConfigOutcome(config_name, STATUS_SKIPPED, force_block_reason)
    +        return ConfigRun(outcome)
    +
    +    availability = backends.evaluate_config(config_name, len(queries))
    +    probed = _probe_backends(config_name, len(queries))
    +
    +    if retriever_factory is None:
    +        if availability.available:
    +            # Availability without an implemented executor must still not claim
    +            # results; surface the missing executor instead of inventing it.
    +            outcome = ConfigOutcome(
    +                config_name,
    +                STATUS_BLOCKED,
    +                "no real retrieval executor is wired for this configuration yet",
    +                probed,
    +            )
    +            return ConfigRun(outcome)
    +        outcome = ConfigOutcome(
    +            config_name,
    +            STATUS_BLOCKED,
    +            f"unavailable backends: {availability.describe()}",
    +            probed,
    +        )
    +        return ConfigRun(outcome)
    +
    +    retriever = retriever_factory(config_name)
    +    results: list[QueryBenchmarkResult] = []
    +    for query in queries:
    +        latency = new_latency_record()
    +        with timed_stage(latency, "total_retrieval_ms"):
    +            items = retriever.retrieve(query, top_k)
    +        deduped = dedupe_preserving_rank(items)[:top_k]

    <sub><sub>!P2 Badge</sub></sub> Preserve run artifacts when a query retrieval fails

    When a retriever raises for any individual query—for example, due to a transient backend timeout—the exception escapes this loop and the CLI exits before write_artifacts runs. A single failed sample therefore discards all completed measurements and produces neither failure counts nor a configuration outcome, contrary to the artifact contract; catch per-query retrieval failures and record them, or convert the configuration into an explicit failed/blocked outcome before writing the run.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Oct 02, 2026 06:09 UTC
    Code Review
    benchmarks/backends.py:1
    @@ -0,0 +1,310 @@
    +"""Retrieval backends for the benchmark.
    +
    +Every backend is probed before it is used, and a backend that cannot answer a
    +real probe is reported as unavailable. The harness never substitutes a stand-in
    +retriever for a missing one: a benchmark that silently ranks with a fake backend
    +would produce numbers that look like retrieval quality while measuring nothing.
    +
    +Two independent things are required for a meaningful measurement:
    +
    +1. a **live retrieval service** (Elasticsearch / Qdrant) and real model assets;
    +2. a **corpus that actually contains the ground-truth passages**.
    +
    +Requirement 2 is easy to overlook. The golden set stores ground truth as passage
    +*text*; the operator corpus is their own private material. Indexing the golden
    +set passages themselves and then measuring recall would be self-referential —
    +every configuration would trivially reach recall 1.0 — so this module refuses that
    +shortcut and reports the corpus requirement explicitly instead.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import os
    +import socket
    +import urllib.error
    +import urllib.request
    +from dataclasses import dataclass
    +from typing import Any
    +
    +from benchmarks.models import BackendAvailability
    +
    +PROBE_TIMEOUT_SECONDS = 2.0
    +
    +REASON_OK = "available"
    +REASON_SERVICE_UNREACHABLE = "service_unreachable"
    +REASON_SERVICE_NO_DATA = "service_reachable_but_empty"
    +REASON_MODEL_UNAVAILABLE = "model_assets_unavailable"
    +REASON_CORPUS_UNRESOLVED = "corpus_does_not_contain_ground_truth"
    +REASON_NOT_CONFIGURED = "not_configured"
    +
    +
    +class BenchmarkUnavailable(RuntimeError):
    +    """Raised when a backend is asked to retrieve without being available."""
    +
    +
    +def _http_get(url: str, auth: tuple[str, str] | None = None) -> tuple[bool, Any]:
    +    """Return ``(ok, payload)`` for a short-timeout GET.
    +
    +    Compose enables ``xpack.security.enabled``, so the probe must authenticate
    +    exactly like the production retriever; otherwise a healthy secured
    +    Elasticsearch answers 401 and would be misreported as unreachable.
    +    """
    +    if not url.lower().startswith(("http://", "https://")):
    +        # Only operator-configured http(s) endpoints are probed; never file:// or
    +        # a custom scheme, so this can never read a local path.
    +        return False, None
    +    request = urllib.request.Request(url)  # noqa: S310 - scheme validated above
    +    if auth and auth[0]:
    +        token = base64.b64encode(f"{auth[0]}:{auth[1]}".encode()).decode("ascii")
    +        request.add_header("Authorization", f"Basic {token}")
    +    try:
    +        with urllib.request.urlopen(request, timeout=PROBE_TIMEOUT_SECONDS) as response:  # noqa: S310
    +            body = response.read()
    +    except urllib.error.HTTPError as exc:
    +        # An HTTP-level answer (401/403/404) proves the service is reachable.
    +        return "http", exc.code
    +    except (urllib.error.URLError, OSError, ValueError):
    +        return False, None
    +    try:
    +        return True, json.loads(body)
    +    except (json.JSONDecodeError, UnicodeDecodeError):
    +        return True, body.decode("utf-8", errors="replace")
    +
    +
    +def _tcp_reachable(host: str, port: int) -> bool:
    +    try:
    +        with socket.create_connection((host, port), timeout=PROBE_TIMEOUT_SECONDS):
    +            return True
    +    except OSError:
    +        return False
    +
    +
    +def _elastic_settings() -> tuple[str, str, int, tuple[str, str] | None]:
    +    """Return ``(url, index, port, auth)`` derived from the live configuration.
    +
    +    The port comes from the URL when it embeds one, unless the configuration
    +    overrides it, so ``http://localhost:19200`` is probed on 19200 rather than on
    +    the 9200 default.
    +    """
    +    from urllib.parse import urlparse
    +
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    elastic = config.get("elasticsearch", {}) or {}
    +    url = str(elastic.get("host") or "http://elasticsearch:9200")
    +    index = str(elastic.get("index") or "cosmetics_docs")
    +    parsed = urlparse(url if "//" in url else f"//{url}")
    +    port = int(elastic.get("port") or parsed.port or (443 if parsed.scheme == "https" else 9200))
    +    auth: tuple[str, str] | None = None
    +    # Mirror the production BM25Retriever precedence exactly: environment first,
    +    # config.json only as a fallback, otherwise a rotated credential makes real
    +    # retrieval succeed while the probe reports a 401.
    +    username = os.environ.get("ELASTICSEARCH_USERNAME") or elastic.get("username") or ""
    +    password = os.environ.get("ELASTICSEARCH_PASSWORD") or elastic.get("password") or ""
    +    if username and password:
    +        auth = (str(username), str(password))
    +    return url, index, port, auth
    +
    +
    +def _qdrant_settings() -> tuple[str, int, str]:
    +    """Return ``(host, port, text_collection)`` using the configured collection."""
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    qdrant = config.get("qdrant", {}) or {}
    +    host = str(qdrant.get("host") or "qdrant")
    +    port = int(qdrant.get("port") or 6333)
    +    configured = (config.get("embedding", {}).get("text", {}) or {}).get("collection")
    +    text_collection = str(
    +        configured or (qdrant.get("collections", {}) or {}).get("rag_text_768", {}).get("name") or "rag_text_768"
    +    )
    +    return host, port, text_collection
    +
    +
    +def _model_weights_available() -> tuple[bool, str | None]:
    +    from common.config import get_config_dict
    +
    +    config = get_config_dict()
    +    model_path = (config.get("embedding", {}).get("text", {}) or {}).get("model_path")
    +    if not model_path:
    +        return False, None
    +    from pathlib import Path
    +
    +    resolved = Path(str(model_path))
    +    if resolved.exists():
    +        return True, str(model_path)
    +    return False, str(model_path)
    +
    +
    +# ── Probes ────────────────────────────────────────────────────────────────
    +
    +
    +def probe_bm25() -> BackendAvailability:
    +    """BM25 needs a reachable, authenticated Elasticsearch holding the corpus."""
    +    url, index, port, auth = _elastic_settings()
    +    if not _tcp_reachable(url.split("//")[-1].split(":")[0], port):
    +        return BackendAvailability("bm25", False, REASON_SERVICE_UNREACHABLE, f"{url}:{port}")
    +    ok, payload = _http_get(f"{url.rstrip('/')}/{index}/_count", auth=auth)
    +    if ok == "http":
    +        # The service answered; a non-200 status is auth/index, not unreachability.
    +        return BackendAvailability(
    +            "bm25",
    +            False,
    +            REASON_SERVICE_NO_DATA,
    +            f"index {index} answered HTTP {payload} (auth or index problem, service reachable)",
    +        )
    +    if not ok:
    +        return BackendAvailability("bm25", False, REASON_SERVICE_UNREACHABLE, f"{url.rstrip('/')}/{index}")
    +    count = None
    +    if isinstance(payload, dict):
    +        count = payload.get("count")
    +    if count is None:
    +        return BackendAvailability("bm25", False, REASON_SERVICE_UNREACHABLE, "no count response")
    +    if int(count) == 0:
    +        return BackendAvailability("bm25", False, REASON_SERVICE_NO_DATA, f"index {index} is empty")
    +    return BackendAvailability("bm25", True, REASON_OK, f"index {index} has {count} docs")
    +
    +
    +def probe_dense() -> BackendAvailability:
    +    """Dense/BGE needs Qdrant text collection *and* real embedding weights."""
    +    host, port, collection = _qdrant_settings()
    +    if not _tcp_reachable(host, port):
    +        return BackendAvailability("dense", False, REASON_SERVICE_UNREACHABLE, f"{host}:{port}")
    +    ok, payload = _http_get(f"http://{host}:{port}/collections/{collection}")
    +    if ok == "http":
    +        # HTTP-level answer proves reachability; the blocker is the collection.
    +        return BackendAvailability(
    +            "dense",
    +            False,
    +            REASON_SERVICE_NO_DATA,
    +            f"collection {collection} answered HTTP {payload} (absent or inaccessible)",
    +        )
    +    if not ok:
    +        return BackendAvailability("dense", False, REASON_SERVICE_UNREACHABLE, f"collection {collection}")
    +    weights_ok, model_path = _model_weights_available()
    +    if not weights_ok:
    +        return BackendAvailability(
    +            "dense",
    +            False,
    +            REASON_MODEL_UNAVAILABLE,
    +            f"embedding model path not present: {model_path}",
    +        )
    +    return BackendAvailability("dense", True, REASON_OK, f"collection {collection}, model {model_path}")

    <sub><sub>!P2 Badge</sub></sub> Reject empty Qdrant collections

    When the Qdrant collection endpoint returns HTTP 200 but reports zero points, this path checks only that model weights exist and marks the dense backend available. As a result, the backend manifest and --list-configs can describe an empty collection as usable and omit the service_reachable_but_empty blocker; inspect the collection response's point count before returning availability.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Oct 02, 2026 06:09 UTC
    Reviewer

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: 8ee0921dcb

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    </details>

    Reviewers
    Assignees
    Xander-Xai Xander-Xai
    Labels
    risk: low confidence: 61.4% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 85.5% (HIGH) · Higher = larger blast radius
    85.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 61.4% · Lower = rushed or shallow review
    61.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 33.1% · Safe to merge
    33.1%