Repository navigation
Fix(Go): make Baidu Encode fail loudly on malformed responses - #14721
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughRefactors Baidu Embed to require a non-empty API key and modelName, optionally include ChangesBaidu Embedding Robustness
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
Estimated Code Review Effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested Reviewers
Poem
🚥 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 |
Haruko386
left a comment
There was a problem hiding this comment.
Hi @Joseff531, read the docs before sub your PR
|
@Joseff531 Rerank interface is updated, would you please update your implementation accordingly? please refer to #14735 |
30721b2 to
da6324b
Compare
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/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
📒 Files selected for processing (1)
internal/entity/models/baidu.go
da6324b to
ff3554e
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (1)
internal/entity/models/baidu.go
ff3554e to
262a823
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
262a823 to
f6ec95b
Compare
|
Hi, @JinHai-CN |
…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)
What problem does this PR solve?
The Baidu (Qianfan)
Encodemethod silently swallowed malformed responses. If adata[]item from the API was missing a field (index,embedding, or unexpected shape), the loop didcontinueinstead of returning an error, leavingnilentries 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 anilvector.Concrete gaps fixed:
datalength and input texts (only checked for empty)EmbeddingConfig.Dimension(added in Go CLI: embed and rerank #14735) was not propagatedThis PR replaces
map[string]interface{}parsing with a typedbaiduEmbeddingResponsestruct, applies the standard four-layer validation (count → out-of-range → duplicate → empty → final missing-index scan), addscontext.WithTimeout(nonStreamCallTimeout), and forwardsembeddingConfig.Dimensionas thedimensionsparameter (Baidu Qianfan v2 uses an OpenAI-compatible API).Type of change