Skip to content

fix(go-models): fix Moonshot model and balance requests - #15528

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
oktofeesh1:codex/moonshot-driver-requests
Jun 8, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
oktofeesh1:codex/moonshot-driver-requests

Conversation

@oktofeesh1

Copy link
Copy Markdown
Contributor

Summary

  • keep Moonshot chat calls in non-streaming mode and streaming calls in SSE mode
  • make Moonshot model listing and balance checks use bodyless GET requests
  • add focused Moonshot request/response regression tests

What changed

  • return a real Moonshot driver from NewInstance
  • validate API keys, model names, and stream senders before issuing requests
  • remove raw SSE line logging from the chat stream path
  • parse ListModels and Balance responses with typed structs instead of unchecked assertions

Why

Kimi/Moonshot documents both model listing and balance checks as GET endpoints with bearer auth and no request body:

The previous driver sent JSON bodies on those GET requests, let callers flip the expected stream mode, and could panic on malformed model or balance responses.

Validation

  • go test ./internal/entity/models -run TestMoonshot -count=1
  • git diff --check

Notes

  • Also ran go test ./internal/entity/models -count=1; it currently fails in an unrelated upstream Astraflow embedding test before this Moonshot-specific coverage is involved.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 2, 2026
@coderabbitai

coderabbitai Bot commented Jun 2, 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: 5afefe4d-5cf0-49d4-ad49-76ad481fc46c

📥 Commits

Reviewing files that changed from the base of the PR and between ac50490 and f2414d5.

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

📝 Walkthrough

Walkthrough

Refactors Moonshot client to validate API key and model name early, always use Bearer Authorization, force chat/stream modes, use body-less GET with typed parsing for models/balance, improve SSE scanning/error handling, and add comprehensive tests validating these behaviors and error conditions.

Changes

Moonshot Model Hardening

Layer / File(s) Summary
Cleanup and input validators
internal/entity/models/moonshot.go
Removes an unused import and adds validators for required API key and non-empty model name; trims API key before use.
Chat non-streaming request changes
internal/entity/models/moonshot.go
ChatWithMessages stops conditional stream overrides and sets Authorization: Bearer <key> using the trimmed API key.
Chat streaming request and SSE handling
internal/entity/models/moonshot.go
ChatStreamlyWithSender validates inputs (including non-nil sender), enforces streaming, sets Authorization and Accept: text/event-stream, removes per-line SSE logging, and checks scanner.Err() before emitting final [DONE].
ListModels and Balance: bodyless GET + typed parsing
internal/entity/models/moonshot.go
ListModels and Balance use body-less GET requests with Authorization and Accept: application/json, decode into typed structs, and validate presence of required fields (non-empty model IDs and available_balance).
Test helpers and behavior tests
internal/entity/models/moonshot_test.go
Adds newMoonshotServer test helper, newMoonshotForTest factory, and tests for NewInstance, chat (streaming/non-streaming), SSE error behavior, ListModels, Balance, malformed responses, and input validation.

Sequence Diagram

sequenceDiagram
  participant Client
  participant MoonshotAPI
  participant Sender
  Client->>MoonshotAPI: POST /chat/completions (stream=true, Authorization: Bearer <apiKey>, Accept: text/event-stream)
  MoonshotAPI->>Sender: data: <delta chunk>
  MoonshotAPI->>Sender: data: [DONE]
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#14433: Modifies ChatStreamlyWithSender with similar refactoring of request/auth/header handling and streaming/SSE parsing.
  • infiniflow/ragflow#15337: Applies analogous hardening patterns across Go model drivers (input validation, stream overrides, ListModels refactor).
  • infiniflow/ragflow#15224: Hardens model chat/streaming implementations by preventing caller-controlled stream overrides and adjusting SSE handling.

Suggested reviewers

  • Haruko386

Poem

🐰 I hopped through headers, keys held tight,
Streamed small deltas through the quiet night,
Typed responses checked, no empty names in sight,
Tests sing back the fixes, tidy and light,
A moonshot mended — carrots for delight.

🚥 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 'fix(go-models): fix Moonshot model and balance requests' clearly and specifically describes the main changes: fixing Moonshot's model listing, balance checks, and related request handling.
Description check ✅ Passed The PR description provides a clear summary, explains what changed and why, lists validation steps performed, and follows the template's structure with a problem statement and change type indicated.
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.

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/moonshot.go (1)

382-388: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't emit [DONE] after a scanner failure.

If scanner.Scan() stops because of a read error, timeout, or oversized SSE frame, this path still sends the completion sentinel before returning the error. That can make callers treat a failed stream as successfully finished and commit partial output.

Suggested fix
+	if err := scanner.Err(); err != nil {
+		return err
+	}
+
 	// Send [DONE] marker for OpenAI compatibility
 	endOfStream := "[DONE]"
 	if err = sender(&endOfStream, nil); err != nil {
 		return err
 	}
 
-	return scanner.Err()
+	return nil
🤖 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/moonshot.go` around lines 382 - 388, The code
currently always sends the "[DONE]" sentinel via sender(&endOfStream, nil) even
when scanner.Scan() failed; change the logic to check scanner.Err() first and
only call sender for the endOfStream if scanner.Err() returns nil (no
read/timeout/oversize error). Concretely, query err2 := scanner.Err() (or reuse
err) after the scan loop, return that error immediately if non-nil, and only
then call sender(&endOfStream, nil) before returning nil; reference the scanner
variable and the sender(...) call to locate where to adjust the flow.
🤖 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/moonshot.go`:
- Around line 382-388: The code currently always sends the "[DONE]" sentinel via
sender(&endOfStream, nil) even when scanner.Scan() failed; change the logic to
check scanner.Err() first and only call sender for the endOfStream if
scanner.Err() returns nil (no read/timeout/oversize error). Concretely, query
err2 := scanner.Err() (or reuse err) after the scan loop, return that error
immediately if non-nil, and only then call sender(&endOfStream, nil) before
returning nil; reference the scanner variable and the sender(...) call to locate
where to adjust the flow.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 120f4214-1ae5-4a5d-8068-fc5000d7bb28

📥 Commits

Reviewing files that changed from the base of the PR and between 9799f33 and ac67208.

📒 Files selected for processing (2)
  • internal/entity/models/moonshot.go
  • internal/entity/models/moonshot_test.go

@oktofeesh1

Copy link
Copy Markdown
Contributor Author

Hi @Haruko386 @JinHai-CN - please review when you have a little time. 🤝

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

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jun 3, 2026
@Haruko386 Haruko386 added the ci Continue Integration label Jun 3, 2026
@Haruko386
Haruko386 marked this pull request as draft June 3, 2026 02:13
@Haruko386
Haruko386 marked this pull request as ready for review June 3, 2026 02:14
@codecov

codecov Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (220ee9d) to head (f2414d5).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15528   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 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

Copy link
Copy Markdown
Member

@oktofeesh1 Would you please resolve the conflicts?

@oktofeesh1
oktofeesh1 force-pushed the codex/moonshot-driver-requests branch from d7653ec to fbfa05b Compare June 7, 2026 16:19
@oktofeesh1

Copy link
Copy Markdown
Contributor Author

@oktofeesh1 Would you please resolve the conflicts?

Fixed, thank you and sorry for delay

@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 Just use this func

Comment thread internal/entity/models/moonshot.go Resolved
@dosubot dosubot Bot removed the lgtm This PR has been approved by a maintainer label Jun 8, 2026
@oktofeesh1

Copy link
Copy Markdown
Contributor Author

@oktofeesh1 Just use this func

This is now resolved :)

@oktofeesh1
oktofeesh1 requested a review from Haruko386 June 8, 2026 06:08
@oktofeesh1

Copy link
Copy Markdown
Contributor Author

Thanks, I fetched/rebased onto the latest upstream code and rechecked the requested pattern. ChatWithMessages, ChatStreamlyWithSender, ListModels, and Balance all call m.baseModel.APIConfigCheck(apiConfig) and then use strings.TrimSpace(*apiConfig.ApiKey) for Authorization. The stream scanner-error fix is still in place as well. Validation passed with go test ./internal/entity/models -run 'TestMoonshot' -count=1, go test ./internal/entity/models -run '^$' -count=1, go vet ./internal/entity/models, and git diff --check.

@oktofeesh1
oktofeesh1 force-pushed the codex/moonshot-driver-requests branch from ac50490 to f2414d5 Compare June 8, 2026 06:32

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

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jun 8, 2026
@JinHai-CN
JinHai-CN merged commit d63bd81 into infiniflow:main Jun 8, 2026
1 check 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 lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants