Skip to content

fix(go-models): harden Hunyuan embedding validation - #15249

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
oktofeesh1:codex/hunyuan-embed-validation
May 29, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
oktofeesh1:codex/hunyuan-embed-validation

Conversation

@oktofeesh1

Copy link
Copy Markdown
Contributor

Summary

  • Validate Hunyuan embedding model name and API key before building requests.
  • Reuse region-aware base URL validation for embedding requests.
  • Replace the stale unsupported Embed test with happy-path and validation coverage.

What changed

  • Added early Hunyuan Embed validation for missing model names and API keys.
  • Routed Embed through the same base URL region guard used by the other Hunyuan methods.
  • Updated Hunyuan tests to configure the embedding suffix and cover Embed success plus invalid inputs.

Why

Hunyuan Embed is implemented, but the existing test still expected it to be unsupported and could panic before returning a normal validation error. This keeps the implemented embedding path aligned with the current driver behavior and prevents nil input panics.

Closes #15087
Refs #14736

Validation

  • go test ./internal/entity/models -run TestHunyuan -count=1
  • git diff --check
  • go test ./internal/entity/models -count=1 currently fails on unrelated TestAstraflowEmbedReturnsNoSuchMethod, outside this diff.

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label May 26, 2026
@coderabbitai

coderabbitai Bot commented May 26, 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: 375c93d8-c8a8-412b-a106-da9cc773ac15

📥 Commits

Reviewing files that changed from the base of the PR and between 750af9a and d5cc7cc.

📒 Files selected for processing (2)
  • internal/entity/models/hunyuan.go
  • internal/entity/models/hunyuan_test.go

📝 Walkthrough

Walkthrough

HunyuanModel.Embed adds input validation (modelName, apiConfig.ApiKey), resolves the embeddings endpoint via baseURLForRegion(region), uses a timeout-bound request context, and preallocates the embeddings slice. Tests add routing for embeddings and include happy-path and input-validation tests.

Changes

Hunyuan Embedding Validation and Testing

Layer / File(s) Summary
Embed method validation and endpoint resolution
internal/entity/models/hunyuan.go
Embed adds input guards for non-nil/non-empty modelName and apiConfig.ApiKey, computes region with a default, builds the embeddings URL with baseURLForRegion(region)+URLSuffix.Embedding, uses http.NewRequestWithContext with nonStreamCallTimeout, and preallocates the embeddings result slice capacity from len(parsedResponse.Data).
Embed test setup and coverage
internal/entity/models/hunyuan_test.go
newHunyuanForTest registers the embeddings URL suffix, and tests add TestHunyuanEmbedHappyPath and TestHunyuanEmbedValidatesInputs, replacing the prior placeholder test.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#15207: Both PRs modify the Tencent Hunyuan embedding implementation—HunyuanModel.Embed and related test coverage.

Suggested labels

🐞 bug, ci, size:M

Suggested reviewers

  • Haruko386

Poem

🐰 A rabbit nudges code with care,
Validates the model name there,
Timeouts wrap each HTTP call,
BaseURL set so endpoints fall,
Tests hop in — embeddings fair!

🚥 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 change: hardening validation for Hunyuan embedding by adding input validation checks.
Description check ✅ Passed The description comprehensively covers the problem being solved, changes made, reasons for the changes, and validation steps performed, following the template structure.
Linked Issues check ✅ Passed The PR addresses the embedding validation aspect of #15087 by adding validation for model name and API key, and improving test coverage for the implemented Embed method.
Out of Scope Changes check ✅ Passed All changes are scoped to the Hunyuan embedding implementation: validation logic, test coverage updates, and base URL routing alignment with other methods.

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

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/entity/models/hunyuan.go (1)

455-471: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add a request deadline to Embed HTTP calls.

Line 471 builds the request without context timeout. Since this driver’s httpClient has no client-level Timeout, Embed can hang indefinitely on slow/stalled response bodies.

🔧 Proposed fix
+	ctx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout)
+	defer cancel()
-	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
+	req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))
 	if err != nil {
 		return nil, fmt.Errorf("failed to create request: %w", err)
 	}

Based on learnings: when httpClient.Timeout is intentionally unset and only transport/header timeout is configured, per-request context.WithTimeout for non-stream calls is appropriate.

🤖 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/hunyuan.go` around lines 455 - 471, The Embed HTTP
call builds a request without a per-request deadline and can hang; update the
Embed implementation to create the request with a context timeout by using
context.WithTimeout and http.NewRequestWithContext (e.g., derive ctx from the
existing ctx param, call ctx, cancel := context.WithTimeout(ctx, <reasonable
duration or configurable field>), defer cancel()), then pass that ctx into
http.NewRequestWithContext before calling a.httpClient.Do so the call cannot
block indefinitely; reference the Embed function and
a.httpClient/http.NewRequestWithContext when making this change.
🧹 Nitpick comments (1)
internal/entity/models/hunyuan_test.go (1)

462-481: ⚡ Quick win

Add explicit empty-string API key coverage in Embed validation tests.

You verify missing ApiKey (nil pointer), but not the separate *ApiKey == "" branch. Adding it will lock the new validation path against regressions.

🧪 Suggested test addition
 func TestHunyuanEmbedValidatesInputs(t *testing.T) {
 	apiKey := "test-key"
 	model := "hunyuan-embedding"
@@
 	if _, err := newHunyuanForTest("http://unused").Embed(&model, []string{"x"}, &APIConfig{}, nil); err == nil || !strings.Contains(err.Error(), "api key is required") {
 		t.Errorf("missing api key: %v", err)
 	}
+	emptyAPIKey := ""
+	if _, err := newHunyuanForTest("http://unused").Embed(&model, []string{"x"}, &APIConfig{ApiKey: &emptyAPIKey}, nil); err == nil || !strings.Contains(err.Error(), "api key is required") {
+		t.Errorf("empty api key: %v", err)
+	}
 }
🤖 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/hunyuan_test.go` around lines 462 - 481,
TestHunyuanEmbedValidatesInputs doesn't cover the case where APIConfig.ApiKey is
a non-nil pointer to an empty string; add an assertion that
newHunyuanForTest(...).Embed(&model, []string{"x"}, &APIConfig{ApiKey:
&emptyKey}, nil) returns an error and that err.Error() contains "api key is
required". Update TestHunyuanEmbedValidatesInputs to declare emptyKey := "" and
call Embed with &APIConfig{ApiKey: &emptyKey}, referencing newHunyuanForTest and
Embed to ensure the empty-string branch of validation is exercised.
🤖 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.

Outside diff comments:
In `@internal/entity/models/hunyuan.go`:
- Around line 455-471: The Embed HTTP call builds a request without a
per-request deadline and can hang; update the Embed implementation to create the
request with a context timeout by using context.WithTimeout and
http.NewRequestWithContext (e.g., derive ctx from the existing ctx param, call
ctx, cancel := context.WithTimeout(ctx, <reasonable duration or configurable
field>), defer cancel()), then pass that ctx into http.NewRequestWithContext
before calling a.httpClient.Do so the call cannot block indefinitely; reference
the Embed function and a.httpClient/http.NewRequestWithContext when making this
change.

---

Nitpick comments:
In `@internal/entity/models/hunyuan_test.go`:
- Around line 462-481: TestHunyuanEmbedValidatesInputs doesn't cover the case
where APIConfig.ApiKey is a non-nil pointer to an empty string; add an assertion
that newHunyuanForTest(...).Embed(&model, []string{"x"}, &APIConfig{ApiKey:
&emptyKey}, nil) returns an error and that err.Error() contains "api key is
required". Update TestHunyuanEmbedValidatesInputs to declare emptyKey := "" and
call Embed with &APIConfig{ApiKey: &emptyKey}, referencing newHunyuanForTest and
Embed to ensure the empty-string branch of validation is exercised.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 03f5dd74-3e58-45bc-8373-d6d777348220

📥 Commits

Reviewing files that changed from the base of the PR and between 3619cec and 750af9a.

📒 Files selected for processing (2)
  • internal/entity/models/hunyuan.go
  • internal/entity/models/hunyuan_test.go

Use a request-scoped timeout for Hunyuan embedding calls and cover empty API key pointers in embedding validation tests.
@oktofeesh1

Copy link
Copy Markdown
Contributor Author

Another improvement, if you don't mind reviewing - thanks @Haruko386 @JinHai-CN

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

@oktofeesh1

Copy link
Copy Markdown
Contributor Author

Thanks for merging my other PRs!

I believe this one is ready for merge as well, @JinHai-CN @Haruko386 🤝

@Haruko386
Haruko386 marked this pull request as draft May 29, 2026 01:59
@Haruko386
Haruko386 marked this pull request as ready for review May 29, 2026 01:59
@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label May 29, 2026
@Haruko386 Haruko386 added the ci Continue Integration label May 29, 2026
@Haruko386
Haruko386 marked this pull request as draft May 29, 2026 02:00
@Haruko386
Haruko386 marked this pull request as ready for review May 29, 2026 02:00
@codecov

codecov Bot commented May 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (7fc909a) to head (5583ea7).
⚠️ Report is 5 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #15249      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +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 be28177 into infiniflow:main May 29, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Implement provider: Tencent Hunyuan in Go driver

3 participants