Skip to content

Fix(Go): make Baidu Encode fail loudly on malformed responses - #14721

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Joseff531:go-nvidia-rerank
May 13, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
Joseff531:go-nvidia-rerank

Conversation

@Joseff531

@Joseff531 Joseff531 commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

The Baidu (Qianfan) Encode method silently swallowed malformed responses. If a data[] item from the API was missing a field (index, embedding, or unexpected shape), the loop did continue instead of returning an error, leaving nil entries in the result slice. Callers got back partial results with no indication anything went wrong, which then crashes downstream consumers when they try to use a nil vector.

Concrete gaps fixed:

  • No count-mismatch check between data length and input texts (only checked for empty)
  • No duplicate-index detection (a duplicate would silently overwrite)
  • No missing-index final scan
  • No empty-embedding rejection
  • No per-call context timeout
  • EmbeddingConfig.Dimension (added in Go CLI: embed and rerank #14735) was not propagated

This PR replaces map[string]interface{} parsing with a typed baiduEmbeddingResponse struct, applies the standard four-layer validation (count → out-of-range → duplicate → empty → final missing-index scan), adds context.WithTimeout(nonStreamCallTimeout), and forwards embeddingConfig.Dimension as the dimensions parameter (Baidu Qianfan v2 uses an OpenAI-compatible API).

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

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

coderabbitai Bot commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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: 2df4773c-88d2-4612-9cc8-1979b023501f

📥 Commits

Reviewing files that changed from the base of the PR and between 262a823 and f6ec95b.

📒 Files selected for processing (1)
  • internal/entity/models/baidu.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/entity/models/baidu.go

📝 Walkthrough

Walkthrough

Refactors Baidu Embed to require a non-empty API key and modelName, optionally include dimensions in requests, decode responses into typed structs with optional indices, and enforce strict per-item validation (count, index presence/bounds/duplicates, non-empty vectors, and completeness).

Changes

Baidu Embedding Robustness

Layer / File(s) Summary
Response Types
internal/entity/models/baidu.go
Added internal baiduEmbeddingResponse/baiduEmbeddingData types; data[].index is optional (*int).
Input Validation
internal/entity/models/baidu.go
Embed now rejects calls when apiConfig.ApiKey is empty or modelName is nil/empty.
Request Building
internal/entity/models/baidu.go
Include dimensions in POST body only when embeddingConfig != nil and embeddingConfig.Dimension > 0; construct HTTP request with context.
Response Parsing & Validation
internal/entity/models/baidu.go
Unmarshal into typed structs; require returned count matches inputs; require non-nil item indices within bounds; reject duplicate indices and empty embeddings; populate outputs by index.
Completeness Check
internal/entity/models/baidu.go
Error if any expected input text index is missing from the response.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant EmbedFunc
  participant BaiduAPI
  participant Unmarshaller
  Caller->>EmbedFunc: call Embed(apiConfig, modelName, texts, embeddingConfig)
  EmbedFunc->>EmbedFunc: validate apiKey and modelName
  EmbedFunc->>BaiduAPI: POST /embeddings (texts, maybe dimensions)
  BaiduAPI-->>EmbedFunc: JSON response
  EmbedFunc->>Unmarshaller: unmarshal into baiduEmbeddingResponse
  Unmarshaller-->>EmbedFunc: parsed items
  EmbedFunc->>EmbedFunc: validate items, populate outputs, check completeness
  EmbedFunc-->>Caller: return embeddings or error
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

🐞 bug

Suggested Reviewers

  • Haruko386

Poem

🐰 I hop through code with careful paws,
I check each name and every clause,
Dimensions join when set just right,
Indices checked from left to right,
Embeddings whole — I clap my paws!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: fixing the Baidu Encode method to fail loudly (error) on malformed responses instead of silently handling them.
Description check ✅ Passed The description follows the template with both required sections completed: it thoroughly explains what problem is being solved with concrete gaps fixed, and indicates the type of change as a bug fix.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

Hi @Joseff531, read the docs before sub your PR

Comment thread conf/models/nvidia.json Resolved
@JinHai-CN

Copy link
Copy Markdown
Member

@Joseff531 Rerank interface is updated, would you please update your implementation accordingly? please refer to #14735

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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/baidu.go`:
- Around line 451-454: Remove the redundant per-request context timeout in the
Encode HTTP call: delete the context.WithTimeout and defer cancel lines and
change http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))
to http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) so the call relies on
the shared httpClient.Timeout (keep in mind the surrounding Encode method does
not accept a context).
🪄 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: d3da9519-e3ab-446b-855a-390e718e3abe

📥 Commits

Reviewing files that changed from the base of the PR and between 30721b2 and da6324b.

📒 Files selected for processing (1)
  • internal/entity/models/baidu.go

Comment thread internal/entity/models/baidu.go Resolved
@Joseff531 Joseff531 changed the title Go: implement Rerank in NVIDIA driver Fix(Go): make Baidu Encode fail loudly on malformed responses May 9, 2026
@Joseff531
Joseff531 force-pushed the go-nvidia-rerank branch from da6324b to ff3554e Compare May 9, 2026 18:49
@Joseff531
Joseff531 requested a review from Haruko386 May 9, 2026 18:50

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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/baidu.go`:
- Around line 422-428: The Encode method dereferences apiConfig and
apiConfig.ApiKey (and similarly elsewhere around the Encode call sites at the
other referenced lines) without nil/empty checks which can cause a panic; add
explicit validation at the start of BaiduModel.Encode to ensure apiConfig is
non-nil and apiConfig.ApiKey is non-nil/non-empty (returning a descriptive error
like "apiConfig.ApiKey is required"), and update any other spots that set
req.Header (the same dereference at the other mentioned lines) to guard against
nil before using *apiConfig.ApiKey or to use a validated local variable for the
API key.
- Around line 415-419: The baiduEmbeddingResponse struct's Index field should be
changed from a non-pointer int to a pointer (e.g., *int) so missing index fields
don't silently decode to 0; update baiduEmbeddingResponse (and the analogous
embedding response struct referenced around lines 484-496) to use *int for
Index, add a nil-check in the parsing/validation logic that consumes these
structs (fail if Index == nil), and update any code that reads Index to
dereference it only after the nil check.
🪄 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: ddc6c1da-f3d8-4fb9-aa28-d579a0df01e1

📥 Commits

Reviewing files that changed from the base of the PR and between da6324b and ff3554e.

📒 Files selected for processing (1)
  • internal/entity/models/baidu.go

Comment thread internal/entity/models/baidu.go Resolved
Comment thread internal/entity/models/baidu.go Resolved
@Joseff531
Joseff531 force-pushed the go-nvidia-rerank branch from ff3554e to 262a823 Compare May 9, 2026 18:55
@JinHai-CN
JinHai-CN marked this pull request as draft May 11, 2026 03:31
@JinHai-CN JinHai-CN added the ci Continue Integration label May 11, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 11, 2026 03:31
@codecov

codecov Bot commented May 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (c55e23e) to head (f6ec95b).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14721   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ 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.

@Joseff531

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN
I'd be happy if you could review the PR again.
Thanks.

@JinHai-CN
JinHai-CN merged commit 733d75d into infiniflow:main May 13, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request May 19, 2026
3 tasks done
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…flow#14721)

### What problem does this PR solve?

The Baidu (Qianfan) `Encode` method silently swallowed malformed
responses. If a `data[]` item from the API was missing a field (`index`,
`embedding`, or unexpected shape), the loop did `continue` instead of
returning an error, leaving `nil` entries in the result slice. Callers
got back partial results with no indication anything went wrong, which
then crashes downstream consumers when they try to use a `nil` vector.

Concrete gaps fixed:

- No count-mismatch check between `data` length and input texts (only
checked for empty)
- No duplicate-index detection (a duplicate would silently overwrite)
- No missing-index final scan
- No empty-embedding rejection
- No per-call context timeout
- `EmbeddingConfig.Dimension` (added in infiniflow#14735) was not propagated

This PR replaces `map[string]interface{}` parsing with a typed
`baiduEmbeddingResponse` struct, applies the standard four-layer
validation (count → out-of-range → duplicate → empty → final
missing-index scan), adds `context.WithTimeout(nonStreamCallTimeout)`,
and forwards `embeddingConfig.Dimension` as the `dimensions` parameter
(Baidu Qianfan v2 uses an OpenAI-compatible API).

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
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.

3 participants