Skip to content

Fix(Go): make OpenRouter Encode fail loudly on malformed responses - #14717

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Joseff531:go-minimax-encode
May 11, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
Joseff531:go-minimax-encode

Conversation

@Joseff531

@Joseff531 Joseff531 commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

The OpenRouter 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. There were three concrete gaps:

  • No count-mismatch check between data length and input texts (only checked for empty)
  • No duplicate-index detection (a duplicate would silently overwrite)
  • Parse failures on individual items returned partial slices instead of erroring

This PR replaces map[string]interface{} parsing with a typed openrouterEmbeddingResponse struct and applies the same 3-layer validation used in the other drivers (count mismatch → out-of-range index → duplicate index), so any malformed response produces a clear error instead of corrupted data.

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 8, 2026
@coderabbitai

coderabbitai Bot commented May 8, 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: a8849632-d1d8-4b2b-adaf-9d9d78818204

📥 Commits

Reviewing files that changed from the base of the PR and between cd9dbf5 and a9999ad.

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

📝 Walkthrough

Walkthrough

This PR refactors OpenRouterModel.Encode to use a typed openrouterEmbeddingResponse, requires non-nil/non-empty modelName, conditionally includes a dimensions field when provided, and enforces strict response validation: matching counts, in-range non-duplicate indexes, and direct embedding extraction.

Changes

OpenRouter Embeddings Validation

Layer / File(s) Summary
Response Type & Input Validation
internal/entity/models/openrouter.go
Introduces openrouterEmbeddingResponse struct and enforces non-nil, non-empty modelName validation before API calls.
Request Body Options
internal/entity/models/openrouter.go
Conditionally adds dimensions to the embedding request when embeddingConfig.Dimension > 0.
Response Parsing & Validation
internal/entity/models/openrouter.go
Replaces dynamic map parsing with typed json.Unmarshal, validates embedding count matches input, ensures each embedding index is in-range and unique, and extracts embeddings from the typed struct.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

  • infiniflow/ragflow#14657: Earlier PR modifying OpenRouter’s embedding Encode implementation; strongly related to typed parsing and validation changes.

Suggested labels

🐞 bug

Suggested reviewers

  • Haruko386

Poem

🐰 Types hop in, tidy and neat,
No more maps with loose-footed feet,
Indexes checked, counts align,
Embeddings ordered, clean, and fine —
A rabbit cheers for code so sweet.

🚥 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 concisely describes the main fix: making OpenRouter Encode fail loudly on malformed responses instead of silently swallowing them.
Description check ✅ Passed The description comprehensively covers the problem, root causes, and solution. It includes the required template sections: problem statement and type of change (Bug Fix).
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.

@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/minimax.go`:
- Around line 353-355: The code currently accepts vectors on HTTP 200 without
verifying MiniMax's application-level success; update the Embed response parsing
(type minimaxEmbedResponse handling used by the Encode method) to inspect the
nested base_resp.status_code field first and only proceed to use Vectors when
status_code indicates success; if status_code indicates an error, return or
propagate an error containing the base_resp message/details instead of trusting
vectors. Ensure the same check is added for the other Embed parsing site
referenced around lines 430-437 so both code paths validate
base_resp.status_code before accepting the vectors slice.
- Around line 407-416: Create a per-call context with a deadline using
context.WithTimeout and use http.NewRequestWithContext instead of
http.NewRequest so the HTTP call is request-scoped; specifically, wrap the call
that builds the request (currently using http.NewRequest with variables endpoint
and jsonData) in a ctx, cancel := context.WithTimeout(parentCtx, timeout) (defer
cancel()), call http.NewRequestWithContext(ctx, "POST", endpoint,
bytes.NewBuffer(jsonData)), preserve setting headers (req.Header.Set...) and
pass that request to z.httpClient.Do(req); add necessary imports (context, time)
and use an incoming context parameter if available or a sensible timeout
constant.
🪄 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: 93194ebb-e604-4201-93b5-6510d45d44cb

📥 Commits

Reviewing files that changed from the base of the PR and between 5e96c5c and 71954c5.

📒 Files selected for processing (2)
  • conf/models/minimax.json
  • internal/entity/models/minimax.go

Comment thread internal/entity/models/minimax.go Resolved
Comment thread internal/entity/models/minimax.go Resolved
@Joseff531
Joseff531 force-pushed the go-minimax-encode branch from 71954c5 to 2c31f43 Compare May 9, 2026 00:43
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels May 9, 2026
@Joseff531

Copy link
Copy Markdown
Contributor Author

Hi, @Haruko386
I'd be happy if you could review the PR and share any feedback, Thanks

@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, please let me know where you find embo-01
MiniMax Model List

Comment thread conf/models/minimax.json Resolved
@Joseff531
Joseff531 force-pushed the go-minimax-encode branch from 2c31f43 to cd9dbf5 Compare May 9, 2026 03:42
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 9, 2026
@Joseff531 Joseff531 changed the title Go: implement Encode (embeddings) in MiniMax driver Fix(Go): make OpenRouter Encode fail loudly on malformed responses May 9, 2026
@Joseff531
Joseff531 requested a review from Haruko386 May 9, 2026 03:58

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

@Joseff531 LGTM

@JinHai-CN

Copy link
Copy Markdown
Member

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

@Joseff531
Joseff531 force-pushed the go-minimax-encode branch from cd9dbf5 to a9999ad Compare May 9, 2026 18:17
@Joseff531
Joseff531 requested a review from Haruko386 May 9, 2026 18:18
@Joseff531

Copy link
Copy Markdown
Contributor Author

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

Thanks for the heads-up. Rebased this branch onto current main and updated the OpenRouter Encode to honor the new EmbeddingConfig.Dimension field — when set, it's now passed as the dimensions parameter to OpenRouter's embeddings API (officially documented at https://openrouter.ai/docs/api/reference/embeddings).

@JinHai-CN JinHai-CN added the ci Continue Integration label May 11, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft May 11, 2026 03:00
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 11, 2026 03:00
@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 (048ec2f) to head (a9999ad).
⚠️ Report is 18 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14717      +/-   ##
==========================================
- Coverage   95.59%   94.16%   -1.43%     
==========================================
  Files          10       10              
  Lines         703      703              
  Branches      112      112              
==========================================
- Hits          672      662      -10     
- Misses         21       25       +4     
- Partials       10       16       +6     

☔ 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
JinHai-CN merged commit 13e6554 into infiniflow:main May 11, 2026
2 checks passed
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…nfiniflow#14717)

### What problem does this PR solve?

The OpenRouter `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.
There were three concrete gaps:

- No count-mismatch check between `data` length and input texts (only
checked for empty)
- No duplicate-index detection (a duplicate would silently overwrite)
- Parse failures on individual items returned partial slices instead of
erroring

This PR replaces `map[string]interface{}` parsing with a typed
`openrouterEmbeddingResponse` struct and applies the same 3-layer
validation used in the other drivers (count mismatch → out-of-range
index → duplicate index), so any malformed response produces a clear
error instead of corrupted data.

### 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