Repository navigation
Go: implement Rerank in DeepInfra driver - #15185
Conversation
📝 WalkthroughWalkthroughImplements DeepInfraModel.Rerank to call DeepInfra's rerank endpoint: validates inputs, builds a region-aware URL from config, sends an authenticated POST with query and documents, requires 200 OK, parses scores, ensures score count matches documents, applies optional TopN sorting/truncation, and returns indexed RerankResults. Adds unit tests covering happy and edge cases. Also updates CI workflow to compute PORT_OFFSET from GITHUB_RUN_ID and RUNNER_NUM and to perform docker compose down cleanup before starting engine compose projects. ChangesDeepInfra Rerank Implementation
CI test environment and compose cleanup
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/deepinfra_test.go (1)
65-67: ⚡ Quick winAssert the full mapped output in happy-path test.
Only the first rerank item is asserted. Add checks for the second item to catch ordering/mapping regressions.
Suggested test assertion update
- if len(resp.Data) != 2 || resp.Data[0].RelevanceScore != 0.9 || resp.Data[0].Index != 0 { + if len(resp.Data) != 2 || + resp.Data[0].RelevanceScore != 0.9 || resp.Data[0].Index != 0 || + resp.Data[1].RelevanceScore != 0.1 || resp.Data[1].Index != 1 { t.Errorf("resp=%+v", resp.Data) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/deepinfra_test.go` around lines 65 - 67, The test currently only asserts the first rerank item in resp.Data inside deepinfra_test.go; add assertions for the second item to validate its RelevanceScore, Index and any other mapped fields (e.g., ID or Content if present) to ensure ordering/mapping is correct—update the assertion block around resp.Data to check len(resp.Data)==2 and assert resp.Data[0].RelevanceScore, resp.Data[0].Index, resp.Data[1].RelevanceScore, and resp.Data[1].Index (and other mapped fields returned by the rerank mapper) so the happy-path test fully verifies both items.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/entity/models/deepinfra_test.go`:
- Around line 65-67: The test currently only asserts the first rerank item in
resp.Data inside deepinfra_test.go; add assertions for the second item to
validate its RelevanceScore, Index and any other mapped fields (e.g., ID or
Content if present) to ensure ordering/mapping is correct—update the assertion
block around resp.Data to check len(resp.Data)==2 and assert
resp.Data[0].RelevanceScore, resp.Data[0].Index, resp.Data[1].RelevanceScore,
and resp.Data[1].Index (and other mapped fields returned by the rerank mapper)
so the happy-path test fully verifies both items.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 99878c06-cc8d-4444-92f3-94ed4043be9b
📒 Files selected for processing (2)
internal/entity/models/deepinfra.gointernal/entity/models/deepinfra_test.go
Haruko386
left a comment
There was a problem hiding this comment.
Hi @glorydavid03023 , please write suffix in deepinfra.json
example:
"url_suffix": {
"chat": "v1/chat/completions",
"models": "models/list",
"balance": "payment/checklist",
"rerank": "v1/inference",
"embedding": "v1/embeddings",
"tts": "v1/text-to-speech",
"asr": "v1/audio/transcriptions"
},url := fmt.Sprintf("%s/%s/%s", baseURL, d.URLSuffix.Rerank, *modelName)| } | ||
|
|
||
| // Reranker model ids may contain slashes (e.g. Qwen/Qwen3-Reranker-4B). | ||
| url := fmt.Sprintf("%s/v1/inference/%s", strings.TrimSuffix(baseURL, "/"), *modelName) |
There was a problem hiding this comment.
no hard code here
write it in json
Move rerank path into conf/models/deepinfra.json and build the URL from URLSuffix.Rerank. Add godoc on new symbols, assert both rerank results in tests, and document the PR template sections. Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/deepinfra.go`:
- Around line 433-439: The Rerank method (DeepInfraModel.Rerank) currently
ignores rerankConfig.TopN and returns scores for all input documents; update
this method to enforce TopN by (1) when calling DeepInfra, optionally limit the
documents sent based on rerankConfig.TopN (e.g., slice the input documents
before the request) and (2) after receiving the response, sort the returned
candidate scores (use the scores in the DeepInfra RerankResponse) and truncate
the list to the top N specified by rerankConfig.TopN before constructing and
returning the RerankResponse; ensure you handle nil/zero TopN (treat as no
limit) and preserve original document IDs or order metadata when
slicing/sorting.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: af13c22f-ca2f-470c-8797-f026d77312e6
📒 Files selected for processing (3)
conf/models/deepinfra.jsoninternal/entity/models/deepinfra.gointernal/entity/models/deepinfra_test.go
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/deepinfra_test.go (1)
77-103: ⚡ Quick winAdd one TopN test with unsorted scores to lock in sort behavior.
Current TopN coverage can pass even if implementation only truncates. Add a case where the highest score is not first to guarantee client-side sorting is preserved.
💡 Suggested test case
+func TestDeepInfraRerankTopNSortsByScore(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "scores": []float64{0.1, 0.9}, + }) + })) + defer srv.Close() + + apiKey := "test-key" + model := "Qwen/Qwen3-Reranker-4B" + resp, err := newDeepInfraForTest(srv.URL).Rerank( + &model, + "capital of France?", + []string{"Berlin is the capital.", "Paris is the capital."}, + &APIConfig{ApiKey: &apiKey}, + &RerankConfig{TopN: 1}, + ) + if err != nil { + t.Fatalf("Rerank: %v", err) + } + if len(resp.Data) != 1 || resp.Data[0].RelevanceScore != 0.9 || resp.Data[0].Index != 1 { + t.Errorf("resp=%+v", resp.Data) + } +}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/deepinfra_test.go` around lines 77 - 103, Add a new unit test (e.g., TestDeepInfraRerankTopNUnsorted) that exercises Rerank via newDeepInfraForTest with APIConfig.TopN set (e.g., TopN=1) and a mocked response that returns unsorted scores (e.g., scores: [0.1, 0.9]); assert the client sorts and returns the highest-scoring item (RelevanceScore 0.9, Index 1) so the test fails if implementation only truncates without sorting. Locate Rerank, newDeepInfraForTest and APIConfig in the same test file to implement this check.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/entity/models/deepinfra_test.go`:
- Around line 77-103: Add a new unit test (e.g.,
TestDeepInfraRerankTopNUnsorted) that exercises Rerank via newDeepInfraForTest
with APIConfig.TopN set (e.g., TopN=1) and a mocked response that returns
unsorted scores (e.g., scores: [0.1, 0.9]); assert the client sorts and returns
the highest-scoring item (RelevanceScore 0.9, Index 1) so the test fails if
implementation only truncates without sorting. Locate Rerank,
newDeepInfraForTest and APIConfig in the same test file to implement this check.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c9499e65-cb39-40c2-99ff-e4f990b0eb19
📒 Files selected for processing (2)
internal/entity/models/deepinfra.gointernal/entity/models/deepinfra_test.go
- Wire Rerank via url_suffix v1/inference with client-side TopN enforcement - Offset docker compose host ports by GITHUB_RUN_ID to avoid runner clashes - Pre-clean compose project before Infinity/Elasticsearch stack startup Co-authored-by: Cursor <[email protected]>
9645232 to
ca66b3a
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15185 +/- ##
=======================================
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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In @.github/workflows/tests.yml:
- Around line 174-196: The PORT_OFFSET calculation can produce identical offsets
for different RUNNER_NUM values; change the formula to allocate a
non-overlapping block per runner by using a sufficiently large per-runner range.
Replace PORT_OFFSET=$(( (GITHUB_RUN_ID % 400) + RUNNER_NUM * 10 )) with
something like PER_RUNNER_RANGE=1000 and PORT_OFFSET=$(( RUNNER_NUM *
PER_RUNNER_RANGE + (GITHUB_RUN_ID % PER_RUNNER_RANGE) )) so MINIO_PORT,
REDIS_PORT, SVR_HTTP_PORT, etc. (the variables MINIO_PORT, REDIS_PORT,
SVR_HTTP_PORT, SVR_WEB_HTTP_PORT, etc.) will always fall into distinct ranges
per runner.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 24fe5b27-3d34-434e-9be4-fa63a77771e1
📒 Files selected for processing (4)
.github/workflows/tests.ymlconf/models/deepinfra.jsoninternal/entity/models/deepinfra.gointernal/entity/models/deepinfra_test.go
| # Per-runner base plus per-workflow-run offset avoids port clashes when | ||
| # multiple CI jobs share the same self-hosted runner concurrently. | ||
| PORT_OFFSET=$(( (GITHUB_RUN_ID % 400) + RUNNER_NUM * 10 )) | ||
| ES_PORT=$((1200 + PORT_OFFSET)) | ||
| OS_PORT=$((1201 + PORT_OFFSET)) | ||
| INFINITY_THRIFT_PORT=$((23817 + PORT_OFFSET)) | ||
| INFINITY_HTTP_PORT=$((23820 + PORT_OFFSET)) | ||
| INFINITY_PSQL_PORT=$((5432 + PORT_OFFSET)) | ||
| EXPOSE_MYSQL_PORT=$((5455 + PORT_OFFSET)) | ||
| MINIO_PORT=$((9000 + PORT_OFFSET)) | ||
| MINIO_CONSOLE_PORT=$((9001 + PORT_OFFSET)) | ||
| REDIS_PORT=$((6379 + PORT_OFFSET)) | ||
| TEI_PORT=$((6380 + PORT_OFFSET)) | ||
| KIBANA_PORT=$((6601 + PORT_OFFSET)) | ||
| SVR_HTTP_PORT=$((9380 + PORT_OFFSET)) | ||
| ADMIN_SVR_HTTP_PORT=$((9381 + PORT_OFFSET)) | ||
| SVR_MCP_PORT=$((9382 + PORT_OFFSET)) | ||
| GO_HTTP_PORT=$((9384 + PORT_OFFSET)) | ||
| GO_ADMIN_PORT=$((9383 + PORT_OFFSET)) | ||
| SANDBOX_EXECUTOR_MANAGER_PORT=$((9385 + PORT_OFFSET)) | ||
| SVR_WEB_HTTP_PORT=$((80 + PORT_OFFSET)) | ||
| SVR_WEB_HTTPS_PORT=$((443 + PORT_OFFSET)) | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Search recent workflow runs for port binding errors
gh run list --workflow=tests.yml --limit 50 --json databaseId,conclusion,createdAt \
| jq -r '.[] | select(.conclusion == "failure") | .databaseId' \
| head -20 \
| xargs -I {} sh -c 'echo "=== Run {} ===" && gh run view {} --log 2>&1 | grep -i "address already in use\|port.*in use\|bind.*failed" | head -5'Repository: infiniflow/ragflow
Length of output: 2732
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE=".github/workflows/tests.yml"
echo "## Show PORT_OFFSET + derived ports block (around requested lines)"
nl -ba "$FILE" | sed -n '150,240p'
echo
echo "## Find how RUNNER_NUM is computed"
rg -n "RUNNER_NUM" "$FILE" || true
echo
echo "## Show where Docker compose is invoked (to see sudo/docker args + port bindings context)"
rg -n "docker compose|docker-compose|sudo docker" "$FILE" || true
echo
echo "## Pull failing runs and extract computed port-related context from logs"
# Re-run the same query used earlier, but focus on log lines that mention PORT_OFFSET / port env vars.
# (Limits to first 10 failures to keep output small.)
gh run list --workflow=tests.yml --limit 50 --json databaseId,conclusion \
| jq -r '.[] | select(.conclusion == "failure") | .databaseId' \
| head -10 \
| xargs -I {} sh -c '
echo "=== Run {} ==="
gh run view {} --log 2>&1 \
| rg -n "PORT_OFFSET|RUNNER_NUM|MINIO_PORT|MINIO_CONSOLE_PORT|REDIS_PORT|TEI_PORT|ES_PORT|SVR_WEB_HTTP_PORT|SVR_WEB_HTTPS_PORT|address already in use|port is already allocated|Bind for" \
| head -50
'Repository: infiniflow/ragflow
Length of output: 190
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE=".github/workflows/tests.yml"
echo "## Show PORT_OFFSET + derived ports block (around requested lines) with line numbers (via awk)"
awk 'NR>=150 && NR<=240 {printf "%6d %s\n", NR, $0}' "$FILE"
echo
echo "## Find how RUNNER_NUM is computed (context)"
rg -n "RUNNER_NUM" "$FILE" -n || true
rg -n "GITHUB_RUN_ID" "$FILE" -n || true
echo
echo "## Show where Docker compose is invoked (to see sudo/docker args + port bindings context)"
rg -n "docker compose|docker-compose|sudo docker" "$FILE" || true
rg -n "compose up|compose down|docker compose up|docker compose down" "$FILE" || true
echo
echo "## Re-run failing-runs query but extract only relevant port-binding lines"
gh run list --workflow=tests.yml --limit 50 --json databaseId,conclusion \
| jq -r '.[] | select(.conclusion == "failure") | .databaseId' \
| head -10 \
| xargs -I {} sh -c '
echo "=== Run {} ==="
gh run view {} --log 2>&1 \
| rg -n "PORT_OFFSET|RUNNER_NUM|MINIO_PORT|MINIO_CONSOLE_PORT|REDIS_PORT|TEI_PORT|ES_PORT|SVR_WEB_HTTP_PORT|SVR_WEB_HTTPS_PORT|address already in use|port is already allocated|Bind for" \
| head -80
'Repository: infiniflow/ragflow
Length of output: 44075
Major: PORT_OFFSET can collide across runners → fix to guarantee non-overlapping ranges
The current formula PORT_OFFSET=$(( (GITHUB_RUN_ID % 400) + RUNNER_NUM * 10 )) can produce the same PORT_OFFSET for different RUNNER_NUM values, making the derived host ports (e.g., MINIO_PORT=9000+PORT_OFFSET, REDIS_PORT=6379+PORT_OFFSET, etc.) collide. Recent failures show Docker bind errors for 0.0.0.0:9020 and 0.0.0.0:6399, which match the derived port scheme (9020 ↔ MINIO_PORT, 6399 ↔ REDIS_PORT) when PORT_OFFSET=20.
🔧 Suggested fix: use non-overlapping ranges
- # Per-runner base plus per-workflow-run offset avoids port clashes when
- # multiple CI jobs share the same self-hosted runner concurrently.
- PORT_OFFSET=$(( (GITHUB_RUN_ID % 400) + RUNNER_NUM * 10 ))
+ # Per-runner ranges do not overlap: Runner N uses [(N-1)*400, N*400-1]
+ # This avoids port clashes when multiple CI jobs share infrastructure.
+ PORT_OFFSET=$(( (RUNNER_NUM - 1) * 400 + (GITHUB_RUN_ID % 400) ))SVR_WEB_HTTP_PORT/HTTPS won’t hit privileged ports with the workflow’s RUNNER_NUM default of 1 (min 90/453), so that specific concern doesn’t apply.
Cleanup logic (docker compose ... down -v + docker rm -f by project before up -d) looks good.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In @.github/workflows/tests.yml around lines 174 - 196, The PORT_OFFSET
calculation can produce identical offsets for different RUNNER_NUM values;
change the formula to allocate a non-overlapping block per runner by using a
sufficiently large per-runner range. Replace PORT_OFFSET=$(( (GITHUB_RUN_ID %
400) + RUNNER_NUM * 10 )) with something like PER_RUNNER_RANGE=1000 and
PORT_OFFSET=$(( RUNNER_NUM * PER_RUNNER_RANGE + (GITHUB_RUN_ID %
PER_RUNNER_RANGE) )) so MINIO_PORT, REDIS_PORT, SVR_HTTP_PORT, etc. (the
variables MINIO_PORT, REDIS_PORT, SVR_HTTP_PORT, SVR_WEB_HTTP_PORT, etc.) will
always fall into distinct ranges per runner.
What problem does this PR solve?
The Go DeepInfra driver returned a stub error for
Rerank()even though DeepInfra serves reranker models atPOST /v1/inference/{model}withquery,documents, and ascores[]response.Type of change
Changes
conf/models/deepinfra.json: addrerankURL suffix (v1/inference)internal/entity/models/deepinfra.go: implementRerank()usingURLSuffix.Rerank; enforceRerankConfig.TopNclient-side (API returns all scores)internal/entity/models/deepinfra_test.go: httptest coverage for TopN, full results, empty documents, API key, score mismatchCI note
Prior
ragflow_testsfailures were self-hosted runner port collisions (port is already allocatedon MinIO/Redis). This branch offsets compose ports perGITHUB_RUN_IDand runsdocker compose downbefore each stack start.Test plan
go test ./internal/entity/models/ -run TestDeepInfra -count=1