Skip to content

fix(go-models): harden JieKouAI driver requests - #15337

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
oktofeesh1:codex/jiekouai-driver-hardening
May 29, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
oktofeesh1:codex/jiekouai-driver-hardening

Conversation

@oktofeesh1

Copy link
Copy Markdown
Contributor

Summary

  • Harden JieKouAI request validation before outbound provider calls
  • Force non-streaming and streaming chat methods to use their expected stream modes
  • Make model listing use a bodyless GET and parse model responses without panics

What changed

  • Added API key and model-name validation for JieKouAI request paths
  • Removed caller-controlled stream mode overrides from chat and streaming chat
  • Removed raw SSE line logging from the streaming response loop
  • Replaced panic-prone ListModels response assertions with typed parsing and validation
  • Added focused JieKouAI tests for chat, streaming, embeddings, rerank, and model listing behavior

Why

JieKouAI follows the same OpenAI-compatible request shape as the related 302.AI provider, but its Go driver still accepted invalid local inputs, allowed callers to flip stream mode on the wrong method, sent a body with GET /models, logged raw SSE payloads, and could panic on malformed model-list responses.

Closes #14736

Validation

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

Notes

  • go test ./internal/entity/models -count=1 is currently blocked by an unrelated upstream Astraflow test panic in TestAstraflowEmbedReturnsNoSuchMethod.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 28, 2026
@coderabbitai

coderabbitai Bot commented May 28, 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: 7756d09d-713d-42d7-932d-e689d1a07a5b

📥 Commits

Reviewing files that changed from the base of the PR and between 06e3faa and 679960a.

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

📝 Walkthrough

Walkthrough

Centralized API-key and model-name validation across JieKouAI methods; updated chat (streaming and non-streaming), embed, rerank, and ListModels to use validated values in headers and bodies, removed per-line SSE logging and config-level stream overrides, and added comprehensive integration and validation tests.

Changes

JieKouAI Provider Input Validation and Request Hardening

Layer / File(s) Summary
Input validation helpers and dependency cleanup
internal/entity/models/jiekouai.go
Added unexported validateApiKey() and validateModelName() helpers to centralize validation with trimming and error reporting; removed unused ragflow/internal/common logging dependency.
Chat and streaming chat API improvements
internal/entity/models/jiekouai.go
Updated ChatWithMessages and ChatStreamlyWithSender to validate apiKey and modelName before building requests; removed config-level stream flag overrides; set Authorization to validated apiKey and appropriate Accept headers; removed per-line SSE logs and require non-nil stream sender.
Embed API validation and request improvements
internal/entity/models/jiekouai.go
Updated Embed to validate model name and apiKey via helpers, use the trimmed model value in the request body, and set Authorization with the validated apiKey.
Rerank API validation and request construction
internal/entity/models/jiekouai.go
Updated Rerank to validate non-blank query, model name, and apiKey; trim query in request body; include top_n only when non-zero; use validated apiKey in headers.
ListModels API refactor to GET with typed response parsing
internal/entity/models/jiekouai.go
Refactored ListModels to use GET without a request body, validate apiKey, set Authorization/Accept headers, and parse responses into a typed struct that errors on missing data or empty model IDs.
Integration and validation test suite
internal/entity/models/jiekouai_test.go
Added httptest server helper, JieKouAIModel constructor helper, integration tests for chat (streaming and non-streaming), models listing (happy and malformed responses), embeddings, rerank (nil config case), and table-driven client-side input validation tests.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

size:M

Suggested reviewers

  • Haruko386

Poem

🐰 I trimmed the keys, I trimmed the name,
Headers set tidy, no loose flag to blame,
Streams now behave, SSE sings then ends,
Typed lists return clean model friends,
The rabbit hops in tests and mends.

🚥 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): harden JieKouAI driver requests' clearly and concisely summarizes the main objective of the PR: hardening validation and request handling in the JieKouAI Go driver.
Description check ✅ Passed The PR description is well-structured and comprehensive, covering the summary, what changed, why it matters, validation steps, and notes. It aligns with the template requirements by clearly explaining the problem and the type of change.
Linked Issues check ✅ Passed The PR successfully implements hardening of the JieKouAI driver as part of the broader model provider implementation effort (#14736), including request validation, stream mode enforcement, and model listing improvements with comprehensive tests.
Out of Scope Changes check ✅ Passed All changes are directly scoped to hardening the JieKouAI driver implementation: validation, stream handling, model listing, and comprehensive testing. No unrelated or extraneous changes are present.

✏️ 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: 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/jiekouai.go`:
- Around line 468-478: The current code always serializes "top_n": topN even
when rerankConfig is nil or TopN==0, sending an unintended 0; change
construction of reqBody so you only add the "top_n" key when rerankConfig != nil
&& rerankConfig.TopN != 0 (i.e., compute topN as you do, build reqBody with
model/query/documents first, then conditionally set reqBody["top_n"] = topN) so
the key is omitted unless explicitly provided.
🪄 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: 33092582-29f0-4146-be7d-08137eb36a88

📥 Commits

Reviewing files that changed from the base of the PR and between 8468227 and 06e3faa.

📒 Files selected for processing (2)
  • internal/entity/models/jiekouai.go
  • internal/entity/models/jiekouai_test.go

Comment thread internal/entity/models/jiekouai.go Resolved
@oktofeesh1

Copy link
Copy Markdown
Contributor Author

@Haruko386 @JinHai-CN ready for review when you have a moment - thank you

@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 May 28, 2026
@Haruko386 Haruko386 added the ci Continue Integration label May 28, 2026
@Haruko386
Haruko386 marked this pull request as draft May 28, 2026 06:53
@Haruko386
Haruko386 marked this pull request as ready for review May 28, 2026 06:53
@oktofeesh1

Copy link
Copy Markdown
Contributor Author

@oktofeesh1 LGTM

Thank you @Haruko386 - I think my other PR was marked approved but never merged from 2 days ago as well, very similar focus (driver improvements) - mind taking a look? #15249

@codecov

codecov Bot commented May 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (98bc9ca) to head (f37aa80).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15337   +/-   ##
=======================================
  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 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 58eb957 into infiniflow:main May 29, 2026
1 check passed
JinHai-CN pushed a commit that referenced this pull request May 29, 2026
…ot dropped (#15382)

### Summary

Closes #15381 

Every provider in `internal/entity/models/` reads its streaming response
with `bufio.NewScanner(resp.Body)` and iterates over `scanner.Scan()`.
The default `bufio.Scanner` maximum token size is 64KB, so when an
upstream sends a single SSE `data:` line larger than 64KB (long content
deltas, large tool or function call argument blobs, bundled
`reasoning_content`, or providers that emit a whole message in one
event) `scanner.Scan()` returns `false` and `scanner.Err()` returns
`bufio.ErrTooLong`. Streaming chat then ends with an error partway
through the response.

This change adds `scanner.Buffer(make([]byte, 64*1024), 1024*1024)`
immediately after every SSE scanner that was still bare, raising the cap
to 1MB. 1MB is the value already used for streaming chat in `openai.go`,
`modelscope.go`, `groq.go`, `mistral.go`, `xai.go` and the other already
patched providers (the 8MB cap in the repo is reserved for TTS and
embedding paths), so this simply converges the remaining providers onto
the established pattern. Nothing else changes: line parsing, `data:`
prefix handling, `[DONE]` detection, JSON unmarshalling, error handling,
and the existing `scanner.Err()` checks all stay the same.

Providers covered (23 scanners across 22 files): 302ai, aliyun,
baichuan, baidu, cohere, deepinfra, deepseek, gitee, huggingface,
lmstudio, minimax (the chat scanner, whose TTS scanner was already
bumped), moonshot, nvidia, ollama, openrouter, orcarouter, paddleocr,
siliconflow, tokenhub, vllm, volcengine, xunfei, zhipu-ai. `jiekouai.go`
is excluded because it is covered by the in flight #15337.

A table driven regression test (`sse_scanner_buffer_test.go`) streams a
single 128KB `data:` content delta followed by `data: [DONE]` through an
`httptest` server and asserts that `ChatStreamlyWithSender` delivers the
full content with no error across a representative subset of providers.
Without the buffer fix the test fails with `bufio.Scanner: token too
long`.

This PR also removes three duplicate declarations of the package level
`roundTripperFunc` test helper that several recently merged provider PRs
each added independently, which had left the `internal/entity/models`
test package unable to compile. The helper now lives in a single place
and is shared.

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

[Feature] Implement model providers of RAGFlow API server in Go

3 participants