Skip to content

feat(ai): rerank RAG hits with the gateway cross-encoder #4972

Open

Description

@dan-petty

Problem or Motivation

After #4971, the final order of a RAG query is the RRF order of the Qdrant hybrid step. On the 62-query project eval set of #4961, a cross-encoder over the hybrid top 50 (B2) gives these results against the fused order (B2f):

  • natural-language queries (42): +0.105 nDCG@10 [+0.027, +0.192], p 0.017;
  • census questions: +0.224 (p 0.002);
  • all queries: +0.053 [-0.007, +0.119], p 0.10, so not larger than the noise;
  • exact identifiers: -0.056 (p 0.071).

Against the current path, the whole plan (B2) gives +0.181 [+0.097, +0.264] (p < 0.001), recall@10 0.714 against 0.565, and MRR@10 0.652 against 0.423. Most of this gain comes from #4965 and #4971, which need no GPU. This issue adds the GPU part, so its acceptance measures the gain over the fused order, not over the current path.

Proposed Solution & Architectural Design

  • In the retriever, send the query and the fused top 50 to the gateway /v1/rerank route of feat(k8s): serve a cross-encoder rerank route on TEI #4970 (Cohere shape: model, query, documents, top_n). Use the gateway HTTP client, key and end-user header that EmbeddingsEngine uses.
  • Cut each candidate to 2,400 characters, or to the truncation length that test(k8s): trial TEI quality and load on a cluster GPU #4968 sets. Return the top k by relevance_score.
  • Add the settings ai.rag.rerank_model (default bge-reranker-v2-m3) and ai.rag.rerank_candidates (default 50).
  • Give the call an inner timeout that is shorter than the query timeout. On an error or a timeout, return the fused order and count a fallback. Never fail the query.
  • Add the stage rerank to devops_cli_rag_query_duration_ms, and a counter of rerank outcomes (ok, fallback).
  • All consumers (devops ai rag query and search, the MCP tool ai_rag_query, the agent tool, review context, the investigator) get the new order with no change. The Retriever keeps its public calls.

Stop rule: if the acceptance test against the fused arm fails, stop and return this issue to New with the evidence.

Target Subsystem

src/devops_cli/ai/rag/retriever.py, the gateway client of EmbeddingsEngine, RAG settings and telemetry.

Existing Tool Considered

The LiteLLM /v1/rerank route (Cohere shape) of #4970, served by Hugging Face Text Embeddings Inference. The existing gateway HTTP client and OpenTelemetry instruments. No new dependency. Estimated cost: about 0.20M tokens and 3 hours.

Acceptance criteria

  • On the eval set of test(ai): a gold set measures retrieval of knowledge base facts #3902, through the live route: the reranked production arm minus the fused arm of feat(ai): search RAG with Qdrant dense and BM25 fusion #4971, nDCG@10 on the natural-language queries, is larger than 0 with p < 0.05 (measured +0.105 [+0.027, +0.192], p 0.017). Exact_identifier nDCG@10 is not lower than the fused arm by more than its bootstrap interval.
  • On the same eval set: nDCG@10 >= 0.54 and recall@10 >= 0.68 (measured B2 0.567 and 0.714).
  • Over 7 days: rerank stage p95 <= 500 ms and total RAG query p95 <= 1.5 s.
  • A test: when the rerank route returns 503 or times out, the query returns the fused order and counts the outcome fallback.
  • The MCP tool ai_rag_query and devops ai rag query return the reranked order.

Dependencies

#4970 (the rerank route) and #4971 (the Qdrant hybrid step). The stop test of #4968 must pass first.

Source: #4961

Alternatives check of 2026-11-27: in-use.
The repository already uses this tool.
Tool: BerriAI/litellm (https://github.com/BerriAI/litellm), NOASSERTION, last activity 2026-11-27, maintained.
Reason: LiteLLM, already the project's gateway, lists a /rerank endpoint in Cohere shape that a cross-encoder can serve, so the reranking capability itself is covered; only project-side fallback, truncation, settings and telemetry remain.

Covers:

  • Cohere-shape rerank route taking model, query, documents and top_n
  • One gateway, key and end-user header for embeddings and rerank
  • Serves cross-encoder models such as bge-reranker-v2-m3 through TEI

Lacks:

  • No fused-order fallback or short inner timeout
  • No rerank stage histogram or ok/fallback counter
  • No candidate truncation, fetch-pool size or ai.rag rerank settings
  • No MCP tool or CLI consumer changes

Proposed design

Problem statement

After #4971, a RAG query returns the RRF order of the Qdrant hybrid step. A cross-encoder over the hybrid top 50 raises nDCG@10 on natural-language queries by 0.105. This issue adds the gateway rerank stage, its two settings, the fused-order fallback and the stage telemetry. The live eval and the 7-day p95 budget move to a separate test issue.

Acceptance criteria

Requirement: Gateway rerank request

The retriever SHALL send the query and at most ai.rag.rerank_candidates fused candidates to the gateway /v1/rerank route when rerank is true and a gateway provider serves the embedder.

Scenario: Rerank request payload

  • WHEN The fused pool holds 100 candidates, ai.rag.rerank_candidates is 50, rerank is true, and a gateway provider serves the embedder.
  • THEN A fake gateway receives model, query, documents and top_n, and documents holds 50 items.

Requirement: Rerank candidate pool

When rerank is true and a gateway provider serves the embedder, the retriever SHALL fetch at least ai.rag.rerank_candidates points per collection.

Scenario: Default candidate pool

  • WHEN ai.rag.top_k is 5, ai.rag.rerank_candidates is 50, rerank is true, and a gateway provider serves the embedder.
  • THEN Each Qdrant search request has a limit of at least 50 points.

Requirement: Gateway client reuse

The rerank call SHALL use the gateway base URL, API key and end-user header that EmbeddingsEngine uses.

Scenario: Shared gateway client

  • WHEN The reranker sends a request through the gateway test double.
  • THEN The test double sees the same base URL, API key and end-user header as an embedding request.

Requirement: Relevance score order

The retriever SHALL order reranked results by descending relevance_score and return the requested top k.

Scenario: Out-of-order relevance scores

  • WHEN The rerank route returns scores in an order that differs from the fused order.
  • THEN The search results follow descending relevance_score and contain at most k items.

Requirement: Rerank settings defaults

The RAG settings SHALL define ai.rag.rerank_model with default bge-reranker-v2-m3 and ai.rag.rerank_candidates with default 50.

Scenario: Default rerank settings

  • WHEN Settings load with no explicit rerank values.
  • THEN ai.rag.rerank_model is bge-reranker-v2-m3 and ai.rag.rerank_candidates is 50.

Requirement: Candidate truncation

The rerank request SHALL cut each candidate text to at most 2,400 characters, or the truncation length that #4968 sets.

Scenario: Long candidate text

  • WHEN A fused candidate is longer than the truncation length.
  • THEN The document sent to /v1/rerank has the truncation length and no more.

Requirement: Rerank timeout and fallback

The rerank call SHALL use a 2 s read timeout and SHALL return the fused order, counted as fallback, on an error or timeout.

Scenario: Rerank route failure

  • WHEN The rerank route returns 503 or exceeds the 2 s read timeout.
  • THEN The query returns the fused order, records outcome fallback, and raises no error.

Requirement: Rerank telemetry

The RAG telemetry SHALL record a rerank stage on devops_cli_rag_query_duration_ms and count each rerank outcome as ok or fallback on devops_cli_rag_rerank_total.

Scenario: Rerank telemetry outcomes

  • WHEN One reranked query succeeds and one falls back.
  • THEN The histogram has one rerank stage observation and the counter has one ok and one fallback.

Requirement: Gateway reranker seam

SemanticRetriever SHALL build a GatewayReranker when a gateway provider serves its embedder, and keep SearchReranker otherwise.

Scenario: Reranker selection

  • WHEN SemanticRetriever is built with a gateway embedder, and again with a local embedder.
  • THEN The first retriever holds a GatewayReranker and the second holds a SearchReranker.

Requirement: Consumer order

The public calls of SemanticRetriever SHALL return the gateway-reranked order and keep their parameter names and defaults.

Scenario: Search order and signature

  • WHEN SemanticRetriever.search runs with a gateway embedder and rerank true.
  • THEN It returns the gateway order and keeps its parameter names and defaults.

Requirement: MCP and CLI consumer order

The MCP tool ai_rag_query and devops ai rag query SHALL return the gateway-reranked order when rerank is enabled.

Scenario: MCP tool and CLI order

  • WHEN The MCP tool ai_rag_query and devops ai rag query run against a fake gateway that returns a different order.
  • THEN Both outputs follow the gateway relevance_score order.

Requirement: Rerank stage in the RAG dashboard

The RAG dashboard SHALL include rerank in each stage matcher of devops_cli_rag_query_duration_ms.

Scenario: Dashboard k8s check

  • WHEN uv run devops ci --check --only k8s runs on the changed dashboard file.
  • THEN The check exits 0 with the changed dashboard JSON.

Existing Tool Considered

The alternatives check in the issue body records verdict in-use for BerriAI/litellm (https://github.com/BerriAI/litellm). The repository already runs this gateway, so the change adds no new dependency. The check lists what the /v1/rerank route covers and lacks. This proposal adds the project-side parts that the check lists as lacking: the GatewayReranker, the fused-order fallback, the two settings, the truncation, the rerank stage, the outcome counter and the dashboard matcher. The retriever-side work is about 0.20M tokens and 3 hours.

Key questions

  • Where should the gateway cross-encoder rerank call live?: Add a GatewayReranker in src/devops_cli/ai/rag/reranker.py with the same rerank(query, results, *, top_k=None) signature as SearchReranker. SemanticRetriever builds it when a gateway provider serves its embedder, else it keeps SearchReranker. The construction sites and public calls need no change. (best practice) [sources: src/devops_cli/ai/rag/reranker.py:149, src/devops_cli/ai/rag/retriever.py:391, src/devops_cli/ai/rag/embeddings.py:483]
    • Chosen: Add a GatewayReranker and select it from the embedder. The gateway route exists only with a gateway provider, and SemanticRetriever already takes a reranker seam.
    • Rejected: Call /v1/rerank inside _rank_results. It mixes HTTP, timeout and fallback logic into the retriever and bypasses the seam.
    • Rejected: Use a local cross-encoder library. It adds a dependency and bypasses the gateway route of feat(k8s): serve a cross-encoder rerank route on TEI #4970.
  • What does the rerank request send as its candidate list?: Send at most ai.rag.rerank_candidates fused candidates, default 50, each cut to at most 2,400 characters or the truncation length that test(k8s): trial TEI quality and load on a cluster GPU #4968 sets. top_n is the requested k. (best practice) [sources: src/devops_cli/ai/rag/retriever.py:433, src/devops_cli/ai/rag/reranker.py:149, src/devops_cli/config/defaults.py]
    • Chosen: Send the fused top 50, cut to the limit. The measured B2 arm is the cross-encoder over the hybrid top 50, and the cut bounds the request size.
    • Rejected: Send every fused candidate. It increases latency and cost with no measured gain.
    • Rejected: Send only the final top k. The cross-encoder needs a larger pool to reorder.
  • How many candidates does the retriever fetch when rerank is on?: Use max(k * 3, rerank_candidates, 10) points per collection when rerank is enabled. The current max(k * 3, 10) gives 15 at the default ai.rag.top_k of 5, so the measured top-50 pool would never exist. (best practice) [sources: src/devops_cli/ai/rag/retriever.py:433, src/devops_cli/config/defaults.py]
    • Chosen: Raise the fetch limit when rerank is on. It fills the 50-candidate pool and leaves the non-rerank path unchanged.
    • Rejected: Keep the current limit and rerank fewer candidates. The measured arm uses the hybrid top 50, so fewer candidates change the experiment.
    • Rejected: Fetch every point of every collection. It adds unbounded latency and memory with no measured gain.
  • What happens when the rerank route fails or times out?: Use a 2 s read timeout, shorter than the query timeout. On an error or timeout the retriever returns the fused order, counts outcome fallback and raises no error. (best practice) [sources: src/devops_cli/ai/rag/retriever.py:433, src/devops_cli/ai/rag/embeddings.py:483, docs/TESTING.md]
    • Chosen: Fall back to the fused order and count fallback. The query survives a rerank outage and the counter shows the fallback rate.
    • Rejected: Fail the query. It turns a rerank outage into a RAG outage.
    • Rejected: Retry the rerank call. It adds latency past the query timeout and can repeat a timeout.
  • How should the rerank stage and its outcomes be measured?: Add the rerank stage to devops_cli_rag_query_duration_ms through _timed_stage, a devops_cli_rag_rerank_total counter labelled ok or fallback, and rerank to the stage matcher of the RAG dashboard. (best practice) [sources: src/devops_cli/ai/rag/retriever.py, src/devops_cli/telemetry/instruments.py, k8s/devops/dashboards/devops-ai-rag.json:121, tests/ai/rag/test_query_stage_telemetry.py]
    • Chosen: Extend the existing histogram and add the counter. The retriever already times each stage on that histogram, and the dashboard matcher lists the stages.
    • Rejected: Add a separate rerank latency histogram. It splits RAG latency across two metrics and breaks the existing panels.
    • Rejected: Log only. Logs give no p95 and no fallback rate.
  • Can the live eval and the 7-day p95 run in this item?: No. The live eval needs the deployed /v1/rerank route of feat(k8s): serve a cross-encoder rerank route on TEI #4970 and a 7-day window, so it cannot be a case that a test checks offline. Defer it to a test issue that keeps the stop rule. (best practice) [sources: docs/ROADMAP_WORKFLOW.md, docs/TESTING.md]
    • Chosen: Defer the live measurement to a test issue. The implementation can land while the deployed route and the 7-day window are not ready.
    • Rejected: Keep the live measurement as an acceptance criterion. It cannot be tested offline in the implementation pull request.
    • Rejected: Drop the live measurement. It is the stop rule for the rerank gain.

Fit

Fits in one pull request.

Suspected block

None.

Dependencies

#4968, #4970, #4971

Activity

  1. added
    source/agent
    on Nov 12, 2026
  2. added
    type/feature
    scope/ai
    status/new
    value/high
    effort/medium
    on Nov 12, 2026
  3. dan-petty commented on Nov 12, 2026

    @dan-petty
    OwnerAuthor
  4. added
    priority/p2-medium
    on Nov 12, 2026
  5. devops-cli-service commented on Nov 15, 2026

    @devops-cli-service
    Contributor

    Alternatives check: in-use

    Reason: The issue already names the tool: the LiteLLM /v1/rerank route (Cohere shape) of #4970, served by Text Embeddings Inference, is the gateway route the project runs, so the rerank stage needs no new library or dependency. The searches turned up only in-process rerank packages (rerankers, FlashRank) that would add a dependency and bypass the gateway, so the existing gateway route is the best fit and the remaining work is wiring in the retriever.

    The repository already uses this tool.

    Tool: BerriAI/litellm (https://github.com/BerriAI/litellm)

    • License: NOASSERTION
    • Last activity: 2026-11-15
    • Maintained: yes

    Covers:

    • A Cohere-shape /v1/rerank API on the existing LiteLLM gateway, taking model, query, documents and top_n
    • Cross-encoder scoring of a candidate list with per-document relevance scores, backed by a Text Embeddings Inference served model such as bge-reranker-v2-m3
    • Reuse of the gateway HTTP client, key, end-user header and the OpenTelemetry instruments that EmbeddingsEngine already uses

    Lacks:

    • The retriever-side stage: cutting candidates to 2,400 characters, taking the top k by relevance_score, and the ai.rag.rerank_model / ai.rag.rerank_candidates settings
    • An inner timeout shorter than the query timeout, the fused-order fallback on error or timeout, and the fallback outcome counter
    • The rerank stage in devops_cli_rag_query_duration_ms and the counter of ok / fallback outcomes
    • The eval-set acceptance measurement and the p95 latency budgets over 7 days

    Tools considered:

    Searches run:

    • LiteLLM /v1/rerank endpoint Cohere rerank support, results: 5
    • open source cross-encoder reranking library for RAG pipeline python, results: 5
    • litellm docs rerank api /v1/rerank cohere shape TEI, results: 5
    • rerankers python library answer.ai flashrank sentence-transformers CrossEncoder rerank documents, results: 5
    • litellm rerank, results: 5
    • rerankers library github, results: 5
    • BerriAI litellm github repository, results: 5
    • huggingface text-embeddings-inference rerank endpoint, results: 5
    • "rerank" litellm proxy documentation cross-encoder, results: 5
    • litellm rerank endpoint, results: 5

    Sources:

    Checked on 2026-11-15. A person decides what this means for the item. The check changes no label and closes no issue.

  6. devops-cli-service commented on Nov 16, 2026

    @devops-cli-service
    Contributor

    Refine cannot set this item to Ready at 181f85e while the items below stay open. The next refine round looks at the item again when they close, or when a person replies in a comment or edits the body.

  7. devops-cli-service commented on Nov 26, 2026

    @devops-cli-service
    Contributor

    Next step: the open items close, or a person replies in a comment or edits the body. See Dependencies and Watched files in the section Proposed design of the body.

  8. devops-cli-service commented on Nov 29, 2026

    @devops-cli-service
    Contributor

    Next step: the open items close, or a person replies in a comment or edits the body. See Dependencies in the section Proposed design of the body.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    effort/mediumpriority/p2-mediumscope/aisource/agentstatus/newtype/featurevalue/high

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions