Skip to content

fix: align model default handling - #16782

Merged
wangq8 merged 9 commits into
infiniflow:mainfrom
buua436:b103
Jul 10, 2026
Merged

wangq8 merged 9 commits into
infiniflow:mainfrom
buua436:b103

Conversation

@buua436

@buua436 buua436 commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

This PR updates model default handling and related compatibility paths across the backend.

It adds support for using model_id where the system previously required model_provider/model_instance/model_name, while keeping the legacy format working. Default model reads now also return model_id, and the default-model write path stores both the legacy composite value and the tenant model id.

It also includes several related fixes:

  • model type resolution now uses the shared resolver consistently
  • chat and dataset code paths were updated to use resolved model ids correctly
  • compilation template and user service logic were aligned with the new default model fields
  • MySQL migration scripts were adjusted for compatibility
  • migration runner script handling was updated

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@coderabbitai

coderabbitai Bot commented Jul 9, 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
📝 Walkthrough

Walkthrough

This PR adds model_id support to model default-setting APIs and service logic, switches several consumers to tenant_*_id fields, updates migration checks for malformed tenant IDs, and changes thread_pool_exec to create a per-call executor.

Changes

Model ID plumbing and tenant field migration

Layer / File(s) Summary
Model-ID mapping and service resolution logic
api/apps/services/models_api_service.py
Adds tenant model-ID field mapping, includes model_id in model info payloads, and updates tenant default model listing and resolution to read and write tenant-specific model ID fields.
Models API endpoint wiring for model_id
api/apps/restful_apis/models_api.py
Extends the model endpoints’ OpenAPI schemas with model_id and forwards it from PATCH /models/default into the service call.
Consumers switch to tenant_*_id fields
api/apps/restful_apis/chat_api.py, api/db/services/compilation_template_service.py, api/db/services/user_service.py
Updates rerank validation, chat default LLM selection, template LLM defaulting, and tenant info field selection to use tenant_llm_id and related tenant-specific columns; preserves the wiki preset formatting-only change.
Migration script backfill for malformed tenant IDs
tools/scripts/mysql_migration.py, tools/scripts/run_migrations.sh
Expands the migration checks and row selection to include non-32-character tenant ID values, and advances the migration database version.
Stub and assertion updates for service tests
test/unit_test/api/apps/services/test_delete_datasets.py, test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py, test/testcases/test_sdk_api/test_dataset_mangement/test_create_dataset.py, test/testcases/test_sdk_api/test_update_dataset.py, test/testcases/restful_api/test_datasets.py
Updates test stubs for the model service dependencies and loosens dataset embedding-model assertions to match the new prefix-based defaults.

Thread pool execution behavior

Layer / File(s) Summary
Per-call thread pool executor
common/misc_utils.py
Replaces the shared executor with a per-call single-worker executor while keeping context propagation.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ModelsAPI
  participant ModelsApiService
  participant TenantModelService
  Client->>ModelsAPI: PATCH /models/default with model_id
  ModelsAPI->>ModelsApiService: set_tenant_default_models(...)
  ModelsApiService->>TenantModelService: resolve_model_id / validate model
  ModelsApiService->>ModelsApiService: update default model fields
  ModelsApiService-->>ModelsAPI: success response
  ModelsAPI-->>Client: updated defaults
Loading

Possibly related PRs

  • infiniflow/ragflow#16131: The main PR adds/threads the new model_id + tenant tenant_llm_id through /models/default and model resolution, while the retrieved PR migrates callers off legacy tenant_llm APIs to the same /models/default provider/instance default-model flow.
  • infiniflow/ragflow#16247: Both PRs modify common/misc_utils.py’s thread_pool_exec implementation.
  • infiniflow/ragflow#16744: Both PRs update api/apps/restful_apis/chat_api.py to resolve tenant model configs via resolve_model_config using a model reference.

Suggested labels: 💞 feature, ☯️ refactor, python

Suggested reviewers: Lynn-Inf

Poem

A rabbit hopped through IDs bright,
Swapping tenant fields by moonlight 🐇
Model IDs now land just so,
And tiny threads still come and go,
Hop, hop—everything feels right.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.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 is concise and accurately summarizes the main change to model default handling.
Description check ✅ Passed The description clearly explains the PR purpose and background, though it uses a different heading than the template.
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.

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.

@buua436 buua436 added the ci Continue Integration label Jul 9, 2026
@buua436
buua436 marked this pull request as ready for review July 9, 2026 09:18
@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 Jul 9, 2026
@buua436
buua436 marked this pull request as draft July 9, 2026 09:26
@buua436
buua436 marked this pull request as ready for review July 9, 2026 09:26

@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: 5

🧹 Nitpick comments (1)
api/apps/services/models_api_service.py (1)

249-287: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logging around the new default-model flows.

The new model_id, legacy resolution, and clear branches update tenant defaults without branch-level logs. Add low-cardinality logs such as path and model_type, avoiding secrets or API keys. As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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 `@api/apps/services/models_api_service.py` around lines 249 - 287, The new
default-model handling in the tenant update path lacks branch-level logging for
the `model_id`, legacy `model_provider/model_instance/model_name`, and
clear-default flows. Add low-cardinality logs inside the `models_api_service`
default-model logic around `_check_model_available`, `resolve_model_id`, and the
`TenantService.update_by_id` update, including the path taken and `model_type`
while avoiding any secrets or API keys.

Source: Coding guidelines

🤖 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 `@api/apps/restful_apis/chat_api.py`:
- Around line 401-404: The chat request defaulting logic in the request handler
should fall back to the tenant’s non-null LLM identifier when the tenant default
is unavailable. Update the `req.setdefault("llm_id", ...)` and subsequent `if
req["llm_id"] is None` handling in the chat request flow to use `tenant.llm_id`
as the fallback when `tenant.tenant_llm_id` is missing, so
`DialogService.save()` never receives a null `llm_id`.

In `@api/apps/restful_apis/models_api.py`:
- Around line 78-79: The default-model response schema is missing the new
model_id field even though list_tenant_default_models now returns it. Update the
response documentation in get_default_models so the models[] item schema
includes model_id, matching the added-model schema used elsewhere in
models_api.py.

In `@api/apps/services/models_api_service.py`:
- Line 244: The tenant lookup in TenantService.get_by_id is only being used for
existence checking, so the unused tenant binding should be renamed to satisfy
Ruff RUF059. Update the assignment in the models_api_service flow to keep the
error value binding while discarding the tenant result with an ignored
placeholder, and make sure the surrounding existence check logic remains
unchanged.
- Around line 274-280: The model lookup flow in the availability check is using
the raw API model type and then treating a missing tenant model ID as a hard
failure, which breaks legacy and builtin paths. In the same block that calls
_check_model_available and resolve_model_id, normalize the model type to the
canonical value used by _check_model_available before building the default model
key, and update the fallback so TEI builtin embeddings can proceed when
resolve_model_id returns None instead of immediately returning “not found”. Keep
the behavior aligned with the existing legacy mapping logic in
_check_model_available and the builtin handling in resolve_model_id.

In `@api/db/services/compilation_template_service.py`:
- Around line 40-42: The guard in fill_config_default_llm and _to_saved_dict is
checking the legacy tenant.llm_id field but writing tenant.tenant_llm_id into
config["llm_id"], which can leave a None value behind. Update both checks to
validate tenant.tenant_llm_id before assigning, and only populate
config["llm_id"] when that new field is present so the fallback behavior stays
consistent.

---

Nitpick comments:
In `@api/apps/services/models_api_service.py`:
- Around line 249-287: The new default-model handling in the tenant update path
lacks branch-level logging for the `model_id`, legacy
`model_provider/model_instance/model_name`, and clear-default flows. Add
low-cardinality logs inside the `models_api_service` default-model logic around
`_check_model_available`, `resolve_model_id`, and the
`TenantService.update_by_id` update, including the path taken and `model_type`
while avoiding any secrets or API keys.
🪄 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: e93e7a7c-57b1-4602-bdda-d063b15a9fc4

📥 Commits

Reviewing files that changed from the base of the PR and between b29a4a6 and e6a2bb3.

📒 Files selected for processing (7)
  • api/apps/restful_apis/chat_api.py
  • api/apps/restful_apis/models_api.py
  • api/apps/services/models_api_service.py
  • api/db/services/compilation_template_service.py
  • api/db/services/user_service.py
  • tools/scripts/mysql_migration.py
  • tools/scripts/run_migrations.sh

Comment thread api/apps/restful_apis/chat_api.py Resolved
Comment thread api/apps/restful_apis/models_api.py Resolved
return False, f"model type '{model_type}' is invalid"
tenant_field_name = MODEL_TYPE_TO_TENANT_ID_FIELD.get(model_type)

e, tenant = TenantService.get_by_id(tenant_id)

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove the unused tenant binding.

Line 244 only checks existence; rename the unused binding to satisfy Ruff RUF059.

Proposed fix
-    e, tenant = TenantService.get_by_id(tenant_id)
+    e, _tenant = TenantService.get_by_id(tenant_id)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
e, tenant = TenantService.get_by_id(tenant_id)
e, _tenant = TenantService.get_by_id(tenant_id)
🧰 Tools
🪛 Ruff (0.15.20)

[warning] 244-244: Unpacked variable tenant is never used

Prefix it with an underscore or any other dummy variable pattern

(RUF059)

🤖 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 `@api/apps/services/models_api_service.py` at line 244, The tenant lookup in
TenantService.get_by_id is only being used for existence checking, so the unused
tenant binding should be renamed to satisfy Ruff RUF059. Update the assignment
in the models_api_service flow to keep the error value binding while discarding
the tenant result with an ignored placeholder, and make sure the surrounding
existence check logic remains unchanged.

Source: Linters/SAST tools

Comment thread api/apps/services/models_api_service.py Resolved

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

🧹 Nitpick comments (1)
common/misc_utils.py (1)

255-259: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoff

Per-call executor adds thread create/teardown overhead on hot paths.

Creating a fresh ThreadPoolExecutor per invocation spawns and tears down a worker thread on every call. This is a reasonable workaround for the cited Python 3.13 executor-reuse deadlock, but if thread_pool_exec sits on a high-frequency path the churn may become measurable. If profiling later shows this matters, consider a bounded pool of long-lived executors keyed to avoid the reuse-deadlock condition, rather than spawning per call.

Also worth confirming the deadlock is inherent to shared-executor reuse and not a symptom of a specific await pattern, so the workaround targets the true root cause.

🤖 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 `@common/misc_utils.py` around lines 255 - 259, The hot-path overhead comes
from creating a new ThreadPoolExecutor inside thread_pool_exec on every call, so
reuse a bounded long-lived executor strategy instead of per-invocation
spawn/teardown. Keep the Python 3.13 deadlock workaround in place by ensuring
the executor used by loop.run_in_executor is not shared in the problematic way,
and verify the deadlock is tied to executor reuse rather than the ctx.run/await
pattern.
🤖 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.

Nitpick comments:
In `@common/misc_utils.py`:
- Around line 255-259: The hot-path overhead comes from creating a new
ThreadPoolExecutor inside thread_pool_exec on every call, so reuse a bounded
long-lived executor strategy instead of per-invocation spawn/teardown. Keep the
Python 3.13 deadlock workaround in place by ensuring the executor used by
loop.run_in_executor is not shared in the problematic way, and verify the
deadlock is tied to executor reuse rather than the ctx.run/await pattern.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1792af6e-05ed-4fac-8eac-cdc94e5d193f

📥 Commits

Reviewing files that changed from the base of the PR and between e6a2bb3 and 0d7d8c1.

📒 Files selected for processing (3)
  • common/misc_utils.py
  • test/unit_test/api/apps/services/test_delete_datasets.py
  • test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py

@codecov

codecov Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16782   +/-   ##
=======================================
  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.

@wangq8
wangq8 merged commit 74bbbba into infiniflow:main Jul 10, 2026
4 checks passed
huang-aoqin added a commit to tecpie/ragflow that referenced this pull request Jul 14, 2026
Bring in main fixes (infiniflow#16765, infiniflow#16782). Resolve conflicts using resolve_model_config from main with dev user_id on LLMBundle. Fix get_model_type_by_name single-record handling.

Co-authored-by: Cursor <[email protected]>
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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants