Skip to content

feat(go-api): support setting tenant default models by model_id - #16030

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feature-model-id
Jun 16, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feature-model-id

Conversation

@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

Description

Currently, when setting tenant default models (e.g., chat, embedding, rerank), the API only accepts the composite name (model_name@model_instance@model_provider). However, some integrations and front-end features prefer using the database model_id (UUID) directly.

This PR adds support for model_id in default model configuration:

  1. Request Binding: Added model_id (optional field) to the request body schema in the handler.
  2. Database Lookup: If model_id is supplied, the service queries the database to resolve the respective provider, instance, and model names.
  3. Security Validation: Verified that the provider associated with the resolved model_id belongs to the requesting tenant.
  4. Unit Tests: Added TestSetTenantDefaultModels_WithModelID to verify DB ID resolution and tenant mapping.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 15, 2026
@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a model_id field to the tenant model-setting request payload. When provided, the service layer resolves modelProvider, modelInstance, and modelName from DAO lookups on the model, instance, and provider records, validates tenant ownership, and fills any missing inputs before persisting the default model. A new integration test covers this path using an in-memory SQLite database.

Changes

model_id-based default model resolution

Layer / File(s) Summary
SetModelRequest field and handler call site
internal/handler/tenant.go
SetModelRequest gains a ModelID string \json:"model_id"`field, andsetDefaultModelspassesreq.ModelIDas the new final argument toSetTenantDefaultModels. Minor formatting adjustment to debugFormatstruct fields inInsertChunksFromFile`.
SetTenantDefaultModels signature and modelID resolution
internal/service/tenant.go
Method signature gains modelID string. When non-empty, loads model/instance/provider via DAOs, validates provider tenant ownership, and auto-fills empty provider/instance/name before the existing availability check and persistence step.
Integration test for modelID path
internal/service/tenant_test.go
Adds imports for SQLite/GORM/DAO/entity/models, a //go:linkname binding to dao.modelProviderManager, and TestSetTenantDefaultModels_WithModelID which seeds an in-memory SQLite DB, calls SetTenantDefaultModels with only modelID, and asserts the composite LLMID is set correctly on the tenant.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 A model_id hops into the request,
The DAO sniffs it out, puts providers to test,
It checks the tenant owns what it claims,
Then fills in the blanks and updates the names.
No more guessing — the lookup does best! 🌿

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding support for setting tenant default models by model_id, which is the primary objective of the PR.
Description check ✅ Passed The PR description covers the problem being solved, implementation approach, and testing. However, it does not include the required 'Type of change' section from the template.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

@Harry-Hz-Zhang Harry-Hz-Zhang added the ci Continue Integration label Jun 15, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft June 15, 2026 09:33
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review June 15, 2026 09:33

@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

🧹 Nitpick comments (1)
internal/service/tenant_test.go (1)

159-162: 💤 Low value

Global state mutation may cause test flakiness with parallel execution.

Swapping dao.DB globally affects any other test that runs concurrently in the same process. The defer restores it, but if tests run in parallel (which is the default for go test), race conditions may occur.

Consider adding t.Setenv or using test-specific isolation patterns if parallel test execution is enabled for this package.

🤖 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/service/tenant_test.go` around lines 159 - 162, The test in
tenant_test.go is directly mutating the global dao.DB variable and restoring it
via defer, which creates race conditions during parallel test execution.
Refactor the code to avoid global state mutation by using dependency injection
patterns that pass the test database through function parameters or constructor
arguments instead of swapping the global variable. Alternatively, if the global
mutation pattern must be retained, use proper synchronization mechanisms or
configure the test to run serially rather than in parallel. The key is to
isolate the database dependency at the test level rather than modifying shared
global state that affects other concurrent tests.
🤖 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/service/tenant_test.go`:
- Around line 238-244: The `checkModelAvailable` function has a logic error in
its condition that checks both error and modelEntity status using OR operator,
which causes it to call err.Error() on a nil error when a model is found
successfully. Fix this by restructuring the condition to first check if err !=
nil to handle the error case, then use an else if to check if modelEntity != nil
for the success case where the model already exists. Once this root-cause fix is
applied to `checkModelAvailable`, update the test call to
`SetTenantDefaultModels` to use empty strings for modelProvider and
modelInstance parameters instead of passing "default" as a workaround, removing
the need for the acknowledge comment about bypassing the panic.

---

Nitpick comments:
In `@internal/service/tenant_test.go`:
- Around line 159-162: The test in tenant_test.go is directly mutating the
global dao.DB variable and restoring it via defer, which creates race conditions
during parallel test execution. Refactor the code to avoid global state mutation
by using dependency injection patterns that pass the test database through
function parameters or constructor arguments instead of swapping the global
variable. Alternatively, if the global mutation pattern must be retained, use
proper synchronization mechanisms or configure the test to run serially rather
than in parallel. The key is to isolate the database dependency at the test
level rather than modifying shared global state that affects other concurrent
tests.
🪄 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: 288c9535-d76c-4e15-82b3-353e2f757b72

📥 Commits

Reviewing files that changed from the base of the PR and between f6a2075 and c75ea8c.

📒 Files selected for processing (3)
  • internal/handler/tenant.go
  • internal/service/tenant.go
  • internal/service/tenant_test.go

Comment on lines +238 to +244
// 4. Run SetTenantDefaultModels
s := NewTenantService()
// Set chat model using modelID, explicitly passing "default" as instance name to bypass pre-existing checkModelAvailable panic
err = s.SetTenantDefaultModels(userID, "", "default", "", "chat", modelID)
if err != nil {
t.Fatalf("SetTenantDefaultModels failed: %v", err)
}

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.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify the checkModelAvailable logic and confirm the potential nil-pointer dereference
rg -n -A 10 'func.*checkModelAvailable' internal/service/tenant.go

Repository: infiniflow/ragflow

Length of output: 538


🏁 Script executed:

#!/bin/bash
# Get the complete checkModelAvailable function (from line 579 onwards)
rg -n -A 35 'func.*checkModelAvailable' internal/service/tenant.go

Repository: infiniflow/ragflow

Length of output: 1370


🏁 Script executed:

#!/bin/bash
# Check the test code around lines 238-244
cat -n internal/service/tenant_test.go | sed -n '235,250p'

Repository: infiniflow/ragflow

Length of output: 773


🏁 Script executed:

#!/bin/bash
# Verify the exact line numbers and code around what the review calls "lines 600-608"
sed -n '595,615p' internal/service/tenant.go

Repository: infiniflow/ragflow

Length of output: 726


🏁 Script executed:

#!/bin/bash
# Check how SetTenantDefaultModels calls checkModelAvailable
sed -n '613,700p' internal/service/tenant.go

Repository: infiniflow/ragflow

Length of output: 2440


🏁 Script executed:

#!/bin/bash
# Get more context about what parameters are passed when checkModelAvailable is called
rg -n 'checkModelAvailable' internal/service/tenant.go | head -20

Repository: infiniflow/ragflow

Length of output: 293


Fix the logic error in checkModelAvailable that causes the test to require a workaround.

The bug is at lines 602-603. The condition if err != nil || modelEntity != nil executes when modelEntity is found (not nil) with no error, then immediately calls err.Error() on a nil error, causing a panic. The test comment itself acknowledges this: "to bypass pre-existing checkModelAvailable panic."

The condition should check for error before calling err.Error():

if err != nil {
    // handle error case
} else if modelEntity != nil {
    // model already exists
    // return appropriate response
}

Once fixed, the test at lines 238-244 can be updated to use the pure modelID-only path (passing empty strings for modelProvider and modelInstance) instead of explicitly passing "default" as a workaround.

🤖 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/service/tenant_test.go` around lines 238 - 244, The
`checkModelAvailable` function has a logic error in its condition that checks
both error and modelEntity status using OR operator, which causes it to call
err.Error() on a nil error when a model is found successfully. Fix this by
restructuring the condition to first check if err != nil to handle the error
case, then use an else if to check if modelEntity != nil for the success case
where the model already exists. Once this root-cause fix is applied to
`checkModelAvailable`, update the test call to `SetTenantDefaultModels` to use
empty strings for modelProvider and modelInstance parameters instead of passing
"default" as a workaround, removing the need for the acknowledge comment about
bypassing the panic.

@codecov

codecov Bot commented Jun 15, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16030   +/-   ##
=======================================
  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
JinHai-CN merged commit 3d7b45b into infiniflow:main Jun 16, 2026
1 of 5 checks passed
Harry-Hz-Zhang added a commit to Harry-Hz-Zhang/ragflow that referenced this pull request Jun 17, 2026
…niflow#16030)

### Description
Currently, when setting tenant default models (e.g., chat, embedding,
rerank), the API only accepts the composite name
(`model_name@model_instance@model_provider`). However, some integrations
and front-end features prefer using the database `model_id` (UUID)
directly.

This PR adds support for `model_id` in default model configuration:
1. **Request Binding**: Added `model_id` (optional field) to the request
body schema in the handler.
2. **Database Lookup**: If `model_id` is supplied, the service queries
the database to resolve the respective provider, instance, and model
names.
3. **Security Validation**: Verified that the provider associated with
the resolved `model_id` belongs to the requesting tenant.
4. **Unit Tests**: Added `TestSetTenantDefaultModels_WithModelID` to
verify DB ID resolution and tenant mapping.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants