Skip to content

Go: implement Rerank in Xinference driver - #15032

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
ai-mountain:feat/14816-xinference-rerank
May 21, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
ai-mountain:feat/14816-xinference-rerank

Conversation

@ai-mountain

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fixes #14816

The Xinference Go driver landed chat in #14938 and Embed is in review in #14932, but Rerank shipped as a stub that returns "xinference, no such method". Tenants who launch a rerank model with --model-type rerank on their Xinference instance cannot route it through the Go API server. This PR fills the gap.

Xinference exposes an OpenAI-compatible REST API. The rerank endpoint is at POST <base>/v1/rerank and accepts the Cohere-shaped body {model, query, documents, top_n}, returning {results: [{index, relevance_score}]} — the same wire shape used by the merged NVIDIA (#14778), Aliyun (#14676), Gitee (#14656), ZhipuAI (#14608), Novita (#15014), and LocalAI (#14813) Rerank implementations. Documented in Xinference rerank docs; the builtin rerank model catalog lists bge-reranker-base, bge-reranker-large, bge-reranker-v2-m3, and others.

Changes

  • internal/entity/models/xinference.go: implement XinferenceModel.Rerank.
    • Validate inputs (model name required) and short-circuit on empty documents.
    • Resolve region via baseURLForRegion(xinferenceRegion(...)), which normalizes both http://host:9997 and http://host:9997/v1 to the same root before appending URLSuffix.Rerank. This matches the chat/ListModels code paths.
    • Send {model, query, documents, top_n} POST body, defaulting top_n to len(documents) and honoring RerankConfig.TopN when set.
    • Optional auth via the existing setXinferenceAuth helper — only sets Authorization: Bearer <api_key> when a non-empty key is configured, since default Xinference deployments run without auth.
    • Bounded non-streaming request with nonStreamCallTimeout, matching the chat / ListModels code paths.
    • Parse {results: [{index, relevance_score}]} and emit one RerankResult per scored document in the API's ranking order, rejecting out-of-range indices and duplicates the same way the merged Novita (Go: implement Rerank in Novita driver #15014) and NVIDIA (Go: implement Rerank in NVIDIA driver #14778) Rerank implementations do.
  • conf/models/xinference.json: add "rerank": "v1/rerank" to url_suffix.
  • internal/entity/models/xinference_test.go: extend newXinferenceForTest with the rerank URL suffix; drop the now-obsolete Rerank → no such method assertion in TestXinferenceUnsupportedMethodsReturnNoSuchMethod; add 9 new Rerank unit tests covering happy-path index reordering, /v1 base-URL normalization, RerankConfig.TopN forwarding, empty-documents short-circuit, missing model name, out-of-range index, duplicate index, HTTP error surfacing, and missing-rerank-suffix safety check.

Type of change

  • New Feature (non-breaking change which adds functionality)

Test plan

  • gofmt -l internal/entity/models/xinference.go internal/entity/models/xinference_test.go — clean
  • python3 -c "import json; json.load(open('conf/models/xinference.json'))" — JSON valid
  • go build ./internal/entity/models/... — succeeds
  • go test -run TestXinference ./internal/entity/models/... — 19/19 PASS (10 existing + 9 new Rerank)
  • Live test against xprobe/xinference:latest-cpu Docker container: Rerank driver call with a not-yet-loaded model correctly surfaces the upstream 404 (Xinference rerank API error: 404 Not Found, body: {"detail":"Model not found...uid: bge-reranker-base..."}); the /v1-in-base-URL variant produces the same 404, proving normalizeXinferenceBaseURL strips and re-appends correctly.

Notes for reviewers

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 20, 2026
@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c9c46865-893e-47a0-be49-66522d6308e5

📥 Commits

Reviewing files that changed from the base of the PR and between 80c72e8 and bd2fea9.

📒 Files selected for processing (3)
  • conf/models/xinference.json
  • internal/entity/models/xinference.go
  • internal/entity/models/xinference_test.go
✅ Files skipped from review due to trivial changes (1)
  • conf/models/xinference.json

📝 Walkthrough

Walkthrough

Adds Xinference /v1/rerank support: updates config, implements XinferenceModel.Rerank to POST model/query/documents/top_n, validate and map response indices/scores, and adds tests for happy path and multiple edge cases.

Changes

Xinference rerank support

Layer / File(s) Summary
Configuration and rerank response schema
conf/models/xinference.json, internal/entity/models/xinference.go
Updated url_suffix to include rerank (v1/rerank). Added internal structs for the Xinference rerank JSON response.
Rerank method implementation
internal/entity/models/xinference.go
Implemented XinferenceModel.Rerank: validates inputs, normalizes base URL, requires rerank suffix, POSTs JSON {model, query, documents, top_n}, applies optional bearer auth, unmarshals response, validates indices (in-range, unique), maps into RerankResponse.Data, and surfaces explicit errors for bad config, HTTP failures, parse errors, and invalid indices. Returns empty response for empty documents.
Test configuration and basic coverage
internal/entity/models/xinference_test.go
Added rerank suffix to test model config, removed stale unsupported-method assertion, introduced newXinferenceRerankServer test helper, and added tests for happy-path reordering, base URL normalization, TopN handling, empty-doc short-circuit, and missing model name.
Edge cases and error handling tests
internal/entity/models/xinference_test.go
Added tests rejecting out-of-range and duplicate indices, surfacing HTTP 500 as a rerank-specific error, and failing when rerank URL suffix is not configured.

Sequence Diagram

sequenceDiagram
  participant Caller
  participant XinferenceModel
  participant HTTPClient
  participant XinferenceAPI
  Caller->>XinferenceModel: Rerank(modelName, query, documents)
  alt empty documents
    XinferenceModel-->>Caller: empty RerankResponse
  else missing model name
    XinferenceModel-->>Caller: error "model name is required"
  else missing rerank suffix
    XinferenceModel-->>Caller: error "no rerank URL suffix configured"
  else valid input
    XinferenceModel->>HTTPClient: POST /v1/rerank (model, query, documents, top_n)
    HTTPClient->>XinferenceAPI: request body
    XinferenceAPI-->>HTTPClient: {results: [{index, relevance_score}]}
    HTTPClient-->>XinferenceModel: response body
    XinferenceModel->>XinferenceModel: validate indices (in-range, unique)
    alt invalid indices
      XinferenceModel-->>Caller: error "invalid index"
    else valid indices
      XinferenceModel-->>Caller: RerankResponse with reordered Data
    end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Possibly related PRs

Suggested labels

size:L

Suggested reviewers

  • Haruko386

Poem

🐰 A tiny rabbit hops and says hooray,
Xinference rerank now finds its way.
Indices checked and scores in line,
Tests confirm the ordering's fine.
A stub no more — the rerank blooms today.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main change: implementing the Rerank method in the Xinference Go driver.
Description check ✅ Passed The PR description comprehensively covers the problem statement (fixes #14816), type of change (New Feature), detailed changes across three files, test validation, and notes for reviewers, following the template structure.
Linked Issues check ✅ Passed The PR fully implements all coding requirements from #14816: Rerank method with input validation, POST to /v1/rerank endpoint, request/response handling, index validation, optional Bearer auth, bounded timeout, rerank URL suffix config, and comprehensive test coverage.
Out of Scope Changes check ✅ Passed All changes are directly aligned with #14816 scope: xinference.go implements the Rerank method, xinference.json adds the rerank URL suffix, and xinference_test.go adds corresponding unit tests with no extraneous modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@RenzoMXD LGTM, thank for your contribution

@Haruko386 Haruko386 added the ci Continue Integration label May 20, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft May 20, 2026 05:27
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 20, 2026 05:27
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels May 20, 2026
@codecov

codecov Bot commented May 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (4a91ca5) to head (bd2fea9).
⚠️ Report is 5 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15032   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN

Copy link
Copy Markdown
Member

@RenzoMXD Since previous PR includes a binary file which is very big. So, I reset the head of main branch. Would you please re-submit the commit from current HEAD of main branch? Thank you very much.

@ai-mountain
ai-mountain force-pushed the feat/14816-xinference-rerank branch from 80c72e8 to bd2fea9 Compare May 20, 2026 12:34
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels May 20, 2026
@ai-mountain

Copy link
Copy Markdown
Contributor Author

@JinHai-CN
Thank you for your review.
My PRs (#15024, #15014, #14932, and this PR) have passed the CI test.
Could you please review them again?

@JinHai-CN
JinHai-CN merged commit 536ed07 into infiniflow:main May 21, 2026
1 check passed
@ai-mountain
ai-mountain deleted the feat/14816-xinference-rerank branch May 21, 2026 03:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Implement rerank in the Xinference Go driver

3 participants