Skip to content

Fix: model list - #15860

Merged
wangq8 merged 15 commits into
infiniflow:mainfrom
Lynn-Inf:fix/model-list
Jun 10, 2026
Merged

wangq8 merged 15 commits into
infiniflow:mainfrom
Lynn-Inf:fix/model-list

Conversation

@Lynn-Inf

@Lynn-Inf Lynn-Inf commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Remove tenant_llm call in rag.

Type of change

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

@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 9, 2026
@Lynn-Inf Lynn-Inf added the ci Continue Integration label Jun 9, 2026
@Lynn-Inf
Lynn-Inf marked this pull request as draft June 9, 2026 12:21
@Lynn-Inf
Lynn-Inf marked this pull request as ready for review June 9, 2026 12:21
@coderabbitai

coderabbitai Bot commented Jun 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

Disables automatic tenant-scoped TenantLLM init/persistence and related deletions; adds env-driven OpenDataLoader helpers and tenant-model query APIs; migrates OCR and embedding model-name resolution to the new helpers; adds a deprecation TODO for the legacy LLM factory.

Changes

OCR and Embedding Model Management Refactor

Layer / File(s) Summary
New OCR model provisioning and query helpers
api/db/joint_services/tenant_model_service.py, api/db/services/tenant_model_service.py, api/apps/services/models_api_service.py
Adds ensure_opendataloader_from_env and get_models_by_tenant_and_provider_and_model_type, imports OCR/provider default constants and IntegrityError, adds TenantModelService.get_by_provider_id_and_instance_id_and_model_type, and invokes the env helper in model listing.
Disable tenant LLM initialization during user and admin flows
admin/server/auth.py, api/apps/restful_apis/user_api.py, api/db/joint_services/user_account_service.py, test/testcases/restful_api/test_user_tenant_routes_unit.py
Comments out/removes calls that generated, persisted, or deleted tenant-scoped TenantLLM records during admin tenant setup, user registration/rollback, user creation/rollback, and user deletion; tests updated to stop expecting tenant_llm deletes.
Migrate OCR model resolution to new provisioning helpers
rag/app/naive.py, rag/flow/parser/parser.py
Replaces TenantLLMService-based env resolution and queries in OpenDataLoader branches with ensure_opendataloader_from_env + get_models_by_tenant_and_provider_and_model_type.
Switch embedding model name derivation to simplified split function
api/apps/restful_apis/chunk_api.py, api/apps/services/dataset_api_service.py
Replaces TenantLLMService.split_model_name_and_factory(...) with split_model_name(...) for embedding name extraction and updates imports accordingly; removes unused top-level TenantLLMService import.
Mark legacy LLM factory initialization as deprecated
api/db/init_data.py
Adds a # todo deprecated comment to init_llm_factory() without changing behavior.

Sequence Diagram(s)

sequenceDiagram
  participant EnvCollector
  participant TenantModelJointService
  participant TenantModelService
  EnvCollector->>TenantModelJointService: _ensure_ocr_provider_from_env(OPENDATALOADER_ENV_KEYS, OPENDATALOADER_DEFAULT_CONFIG)
  TenantModelJointService->>TenantModelService: aggregate TenantModel rows by provider instances and model_type
  TenantModelService->>TenantModelService: return model list (tenant-scoped)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • wangq8
  • euvre

Poem

🐰 I hopped through configs, env, and names,
I swapped old init for cleaner claims,
OCR finds tenants, models in line,
Embeds trimmed fine, no extra sign,
A nibble of code — carrot-time!

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (1 warning, 2 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.71% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Fix: model list' is vague and generic, using non-descriptive terms that don't clearly convey the main change being made in the changeset. Provide a more specific title that clearly indicates the primary change, such as 'Remove tenant_llm initialization from user registration and other flows' or similar.
Description check ❓ Inconclusive The PR description is incomplete. While it follows the template structure with a 'What problem does this PR solve?' section and 'Type of change', the explanation lacks sufficient detail and context about the changes. Expand the description to explain why tenant_llm calls are being removed, what issues this addresses, and how the migration to the new tenant_model_service functions impacts the system.
✅ Passed checks (2 passed)
Check name Status Explanation
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.

Actionable comments posted: 4

Caution

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

⚠️ Outside diff range comments (3)
rag/app/naive.py (3)

287-291: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Same attribute bug: llm_name should be model_name.

Same issue as the other OCR parsers.

🐛 Proposed fix
                 candidates = get_models_by_tenant_and_provider_and_model_type(tenant_id=tenant_id, provider_name="PaddleOCR", model_type=LLMType.OCR)
                 if candidates:
-                    paddleocr_llm_name = candidates[0].llm_name
+                    paddleocr_llm_name = candidates[0].model_name
                 elif env_name:
                     paddleocr_llm_name = env_name
🤖 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 `@rag/app/naive.py` around lines 287 - 291, The code uses the wrong attribute
name for the returned candidate model; in the
get_models_by_tenant_and_provider_and_model_type result you should access
model_name instead of llm_name—update the assignment to set paddleocr_llm_name =
candidates[0].model_name (and keep the existing fallback to env_name unchanged)
so the OCR parser uses the correct model attribute; locate this in the block
that calls get_models_by_tenant_and_provider_and_model_type and updates
paddleocr_llm_name.

226-230: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Same attribute bug: llm_name should be model_name.

Same issue as in by_mineru - accessing non-existent llm_name attribute.

🐛 Proposed fix
                 candidates = get_models_by_tenant_and_provider_and_model_type(tenant_id=tenant_id, provider_name="OpenDataLoader", model_type=LLMType.OCR)
                 if candidates:
-                    opendataloader_llm_name = candidates[0].llm_name
+                    opendataloader_llm_name = candidates[0].model_name
                 elif env_name:
                     opendataloader_llm_name = env_name
🤖 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 `@rag/app/naive.py` around lines 226 - 230, The code in the branch that sets
opendataloader_llm_name uses a non-existent attribute llm_name on the returned
candidate objects; update the assignment to use the correct attribute model_name
(i.e., when handling the first candidate from
get_models_by_tenant_and_provider_and_model_type(tenant_id=tenant_id,
provider_name="OpenDataLoader", model_type=LLMType.OCR), set
opendataloader_llm_name = candidates[0].model_name) and keep the existing
fallback to env_name unchanged.

143-147: ⚠️ Potential issue | 🔴 Critical

Fix runtime AttributeError when selecting MinerU OCR model

In rag/app/naive.py (by_mineru), candidates[0] is a TenantModel instance, which exposes model_name (not llm_name). The current candidates[0].llm_name access can raise AttributeError at runtime.

🐛 Proposed fix
                 candidates = get_models_by_tenant_and_provider_and_model_type(tenant_id=tenant_id, provider_name="MinerU", model_type=LLMType.OCR)
                 if candidates:
-                    mineru_llm_name = candidates[0].llm_name
+                    mineru_llm_name = candidates[0].model_name
                 elif env_name:
                     mineru_llm_name = env_name
🤖 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 `@rag/app/naive.py` around lines 143 - 147, In by_mineru, the code reads
candidates[0].llm_name but TenantModel exposes model_name, causing an
AttributeError; update the selection logic in by_mineru (the block that calls
get_models_by_tenant_and_provider_and_model_type) to use
candidates[0].model_name instead of llm_name and keep the existing fallback to
env_name so mineru_llm_name is set to the TenantModel.model_name when candidates
exist, otherwise to env_name.
🧹 Nitpick comments (4)
api/db/joint_services/tenant_model_service.py (2)

266-266: 💤 Low value

Inconsistent logger usage.

Line 266 uses logging.warning directly, but the module defines logger = logging.getLogger(__name__) at line 28. For consistent, named logging, use logger.warning(...) instead.

The same issue applies to lines 338-339 and 410-411.

♻️ Suggested fix
-            logging.warning("MinerU env model %s already exists for tenant %s, retry with next name", candidate, tenant_id)
+            logger.warning("MinerU env model %s already exists for tenant %s, retry with next name", candidate, tenant_id)
🤖 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/db/joint_services/tenant_model_service.py` at line 266, Replace direct
calls to the root logging module with the module-level logger instance to ensure
consistent named logging: change any usage of logging.warning(...) to
logger.warning(...) in tenant_model_service.py (notably the occurrence in the
candidate-name retry message inside the function that generates MinerU env model
names and the two occurrences around lines 338-339 and 410-411). Locate the
functions/methods that perform tenant model creation/retry and update those
logging calls to use the existing logger = logging.getLogger(__name__) defined
at the top of the module so all warnings are emitted via logger.warning(...).

200-413: ⚖️ Poor tradeoff

Consider extracting shared logic into a generic helper.

The three ensure_*_from_env functions share ~90% identical code. A single parameterized helper would reduce duplication and maintenance burden:

def _ensure_ocr_model_from_env(
    tenant_id: str,
    provider_name: str,
    collect_env_config_fn,
    default_config: dict,
    env_keys: list,
    base_name: str,
) -> str | None:
    # shared implementation

This is optional given the current scope but would improve maintainability if more OCR providers are added.

🤖 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/db/joint_services/tenant_model_service.py` around lines 200 - 413, The
three functions ensure_mineru_from_env, ensure_paddleocr_from_env, and
ensure_opendataloader_from_env duplicate almost identical logic; extract a
single parameterized helper (e.g. _ensure_ocr_model_from_env with params
tenant_id, provider_name, collect_env_config_fn, default_config, env_keys,
base_name) that implements: collect cfg, parse api_key, find provider and
matching instance/models, compute used_names, iterate candidate names, create
provider/instance and insert model, and handle IntegrityError retry; then
simplify each ensure_*_from_env to call this helper with the appropriate
provider name, env collector (TenantLLMService._collect_*_env_config),
DEFAULT_CONFIG constant, ENV_KEYS list, and base_name to remove duplication and
centralize behavior.
api/apps/restful_apis/user_api.py (1)

30-33: 💤 Low value

Remove unused imports.

These imports are no longer used after commenting out the LLM initialization:

  • TenantLLM (line 30)
  • get_init_tenant_llm (line 32)
  • TenantLLMService (line 33)
🤖 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/restful_apis/user_api.py` around lines 30 - 33, Remove the three
unused imports from the top of the module: TenantLLM, get_init_tenant_llm, and
TenantLLMService; locate them in the import block that also imports FileService
and simply delete those three identifiers so only used imports remain (you can
run the linter/flake8 or mypy after to verify no references remain).
admin/server/auth.py (1)

136-139: 💤 Low value

Remove commented-out code instead of leaving it.

Commented-out code can confuse future maintainers. If the LLM initialization is being permanently removed, delete these lines. If this is a temporary change, consider adding a TODO comment explaining when/why it should be restored.

🤖 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 `@admin/server/auth.py` around lines 136 - 139, Remove the two commented-out
LLM-related lines (the call to get_init_tenant_llm and the
TenantLLMService.insert_many) instead of leaving them in place; if this LLM
initialization is intended to be temporary, replace the commented lines with a
single TODO that references get_init_tenant_llm and TenantLLMService.insert_many
explaining when/why to restore them, otherwise delete them so only
TenantService.insert(**tenant) and UserTenantService.insert(**usr_tenant)
remain.
🤖 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/db/services/tenant_model_service.py`:
- Around line 38-45: The method
TenantModelService.get_by_provider_id_and_instance_id_and_model_type currently
uses cls.model.get_or_none (returns a single TenantModel or None) but callers
expect an iterable and call extend(); change the method to return a list: fetch
the single object with cls.model.get_or_none (or use a select/filter) and then
return [obj] if obj is not None else [] so callers can safely call
results.extend(models); update the method body to wrap the get_or_none result
into a list rather than returning the raw object.

In `@rag/flow/parser/parser.py`:
- Around line 453-456: In parser.py, the code that selects a fallback model uses
candidates[0].llm_name but the model objects expose model_name; update the
selection to read candidates[0].model_name (within the
get_models_by_tenant_and_provider_and_model_type result handling) so the
function get_models_by_tenant_and_provider_and_model_type and the surrounding
branch that returns a model name use the correct attribute (replace llm_name
with model_name).
- Around line 374-377: The code calls
get_models_by_tenant_and_provider_and_model_type and then returns
candidates[0].llm_name, but the TenantModel defines model_name (same bug as in
naive.py); update the attribute access to return candidates[0].model_name
(preserving the same fallback to env_name) so
get_models_by_tenant_and_provider_and_model_type, the candidates handling, and
the LLMType.OCR branch use model_name correctly.
- Around line 558-561: The code accesses a non-existent attribute llm_name on
candidate objects; in the block using
get_models_by_tenant_and_provider_and_model_type(tenant_id=tenant_id,
provider_name="PaddleOCR", model_type=LLMType.OCR) replace
candidates[0].llm_name with candidates[0].model_name so the correct property is
used (keep the existing fallback to env_name).

---

Outside diff comments:
In `@rag/app/naive.py`:
- Around line 287-291: The code uses the wrong attribute name for the returned
candidate model; in the get_models_by_tenant_and_provider_and_model_type result
you should access model_name instead of llm_name—update the assignment to set
paddleocr_llm_name = candidates[0].model_name (and keep the existing fallback to
env_name unchanged) so the OCR parser uses the correct model attribute; locate
this in the block that calls get_models_by_tenant_and_provider_and_model_type
and updates paddleocr_llm_name.
- Around line 226-230: The code in the branch that sets opendataloader_llm_name
uses a non-existent attribute llm_name on the returned candidate objects; update
the assignment to use the correct attribute model_name (i.e., when handling the
first candidate from
get_models_by_tenant_and_provider_and_model_type(tenant_id=tenant_id,
provider_name="OpenDataLoader", model_type=LLMType.OCR), set
opendataloader_llm_name = candidates[0].model_name) and keep the existing
fallback to env_name unchanged.
- Around line 143-147: In by_mineru, the code reads candidates[0].llm_name but
TenantModel exposes model_name, causing an AttributeError; update the selection
logic in by_mineru (the block that calls
get_models_by_tenant_and_provider_and_model_type) to use
candidates[0].model_name instead of llm_name and keep the existing fallback to
env_name so mineru_llm_name is set to the TenantModel.model_name when candidates
exist, otherwise to env_name.

---

Nitpick comments:
In `@admin/server/auth.py`:
- Around line 136-139: Remove the two commented-out LLM-related lines (the call
to get_init_tenant_llm and the TenantLLMService.insert_many) instead of leaving
them in place; if this LLM initialization is intended to be temporary, replace
the commented lines with a single TODO that references get_init_tenant_llm and
TenantLLMService.insert_many explaining when/why to restore them, otherwise
delete them so only TenantService.insert(**tenant) and
UserTenantService.insert(**usr_tenant) remain.

In `@api/apps/restful_apis/user_api.py`:
- Around line 30-33: Remove the three unused imports from the top of the module:
TenantLLM, get_init_tenant_llm, and TenantLLMService; locate them in the import
block that also imports FileService and simply delete those three identifiers so
only used imports remain (you can run the linter/flake8 or mypy after to verify
no references remain).

In `@api/db/joint_services/tenant_model_service.py`:
- Line 266: Replace direct calls to the root logging module with the
module-level logger instance to ensure consistent named logging: change any
usage of logging.warning(...) to logger.warning(...) in tenant_model_service.py
(notably the occurrence in the candidate-name retry message inside the function
that generates MinerU env model names and the two occurrences around lines
338-339 and 410-411). Locate the functions/methods that perform tenant model
creation/retry and update those logging calls to use the existing logger =
logging.getLogger(__name__) defined at the top of the module so all warnings are
emitted via logger.warning(...).
- Around line 200-413: The three functions ensure_mineru_from_env,
ensure_paddleocr_from_env, and ensure_opendataloader_from_env duplicate almost
identical logic; extract a single parameterized helper (e.g.
_ensure_ocr_model_from_env with params tenant_id, provider_name,
collect_env_config_fn, default_config, env_keys, base_name) that implements:
collect cfg, parse api_key, find provider and matching instance/models, compute
used_names, iterate candidate names, create provider/instance and insert model,
and handle IntegrityError retry; then simplify each ensure_*_from_env to call
this helper with the appropriate provider name, env collector
(TenantLLMService._collect_*_env_config), DEFAULT_CONFIG constant, ENV_KEYS
list, and base_name to remove duplication and centralize behavior.
🪄 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: acc275a9-8839-403d-95c6-1e3223652a4f

📥 Commits

Reviewing files that changed from the base of the PR and between 64b860f and 93afd5a.

📒 Files selected for processing (10)
  • admin/server/auth.py
  • api/apps/restful_apis/chunk_api.py
  • api/apps/restful_apis/user_api.py
  • api/apps/services/dataset_api_service.py
  • api/db/init_data.py
  • api/db/joint_services/tenant_model_service.py
  • api/db/joint_services/user_account_service.py
  • api/db/services/tenant_model_service.py
  • rag/app/naive.py
  • rag/flow/parser/parser.py

Comment on lines +38 to +45
@classmethod
@DB.connection_context()
def get_by_provider_id_and_instance_id_and_model_type(cls, provider_id, instance_id, model_type):
return cls.model.get_or_none(
cls.model.provider_id == provider_id,
cls.model.instance_id == instance_id,
cls.model.model_type == model_type
)

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 | 🟠 Major | ⚡ Quick win

Method returns single object but caller expects a list.

get_or_none() returns a single TenantModel or None, but the caller at api/db/joint_services/tenant_model_service.py:429-431 does:

models = TenantModelService.get_by_provider_id_and_instance_id_and_model_type(...)
if models:
    results.extend(models)

Calling extend() on a non-list object will fail or produce incorrect results. Either return a list like the similar method at lines 25-26, or have the caller use append().

🐛 Recommended fix: return a list
     `@classmethod`
     `@DB.connection_context`()
     def get_by_provider_id_and_instance_id_and_model_type(cls, provider_id, instance_id, model_type):
-        return cls.model.get_or_none(
+        return list(cls.model.select().where(
             cls.model.provider_id == provider_id,
             cls.model.instance_id == instance_id,
             cls.model.model_type == model_type
-        )
+        ))
🤖 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/db/services/tenant_model_service.py` around lines 38 - 45, The method
TenantModelService.get_by_provider_id_and_instance_id_and_model_type currently
uses cls.model.get_or_none (returns a single TenantModel or None) but callers
expect an iterable and call extend(); change the method to return a list: fetch
the single object with cls.model.get_or_none (or use a select/filter) and then
return [obj] if obj is not None else [] so callers can safely call
results.extend(models); update the method body to wrap the get_or_none result
into a list rather than returning the raw object.

Comment thread rag/flow/parser/parser.py Resolved
Comment thread rag/flow/parser/parser.py Resolved
Comment thread rag/flow/parser/parser.py Resolved
@codecov

codecov Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Codecov Report

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

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

@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)
test/testcases/restful_api/test_user_tenant_routes_unit.py (1)

1052-1055: ⚡ Quick win

Remove unused _RaisingDeleteQuery class.

The _RaisingDeleteQuery class appears to be dead code left over from the removal of tenant_llm deletion logic. Since rollback_user_registration no longer deletes tenant_llm records, this mock is no longer needed.

🧹 Proposed cleanup
     monkeypatch.setattr(module.TenantService, "delete_by_id", lambda _tenant_id: (_ for _ in ()).throw(RuntimeError("t boom")))
     monkeypatch.setattr(module.UserTenantService, "query", lambda **_kwargs: (_ for _ in ()).throw(RuntimeError("ut boom")))
 
-    class _RaisingDeleteQuery:
-        def where(self, *_args, **_kwargs):
-            raise RuntimeError("llm boom")
-
     module.rollback_user_registration("user-2")
🤖 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 `@test/testcases/restful_api/test_user_tenant_routes_unit.py` around lines 1052
- 1055, Remove the dead mock class _RaisingDeleteQuery from the test file since
rollback_user_registration no longer deletes tenant_llm records; locate the
class definition "class _RaisingDeleteQuery" in test_user_tenant_routes_unit.py
and delete it (and any imports or references only used by that class) so the
test contains only relevant mocks for current rollback_user_registration
behavior.
🤖 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 `@test/testcases/restful_api/test_user_tenant_routes_unit.py`:
- Around line 1052-1055: Remove the dead mock class _RaisingDeleteQuery from the
test file since rollback_user_registration no longer deletes tenant_llm records;
locate the class definition "class _RaisingDeleteQuery" in
test_user_tenant_routes_unit.py and delete it (and any imports or references
only used by that class) so the test contains only relevant mocks for current
rollback_user_registration behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 759c8cc7-1855-4606-8ecb-0e6ecba0a64b

📥 Commits

Reviewing files that changed from the base of the PR and between eb445ff and b0123c9.

📒 Files selected for processing (1)
  • test/testcases/restful_api/test_user_tenant_routes_unit.py

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 10, 2026

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

Caution

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

⚠️ Outside diff range comments (1)
rag/app/naive.py (1)

222-229: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Incomplete OpenDataLoader refactoring spans two files.

Both rag/app/naive.py (lines 222–229) and rag/flow/parser/parser.py (lines 450–456) suffer from:

  1. Runtime crash: accessing .llm_name on TenantModel (which defines model_name, not llm_name)
  2. Inconsistent pattern: manually selecting the first candidate instead of using get_first_provider_model_name(...) like MinerU/PaddleOCR

The shared root cause is incomplete migration to the unified helper. Adopt the same pattern across all three OCR providers.

🤖 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 `@rag/app/naive.py` around lines 222 - 229, The code in the OpenDataLoader
selection block incorrectly accesses TenantModel.llm_name and manually picks
candidates[0], causing crashes and inconsistency; replace this manual logic with
a call to the unified helper get_first_provider_model_name(tenant_id,
provider_name="OpenDataLoader", model_type=LLMType.OCR) and fall back to
ensure_opendataloader_from_env(tenant_id) only if that helper returns None, and
ensure you read the model name via the helper (or TenantModel.model_name) rather
than .llm_name; update the selection in the opendataloader logic in the naive
flow to match the MinerU/PaddleOCR pattern.
🧹 Nitpick comments (1)
api/db/joint_services/tenant_model_service.py (1)

309-325: ⚡ Quick win

Add logging for model aggregation query.

This new helper lacks logging. Debugging tenant-specific model lookups requires visibility into what was found.

📝 Suggested logging
 def get_models_by_tenant_and_provider_and_model_type(tenant_id: str, provider_name: str, model_type: str):
     """
     Query TenantModel records by tenant_id, provider_name and model_name.
     Returns all matching model records under all instances of the specified provider.
     """
     provider_obj = TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id, provider_name)
     if not provider_obj:
+        logger.debug(f"Provider {provider_name} not found for tenant {tenant_id}")
         return []
     instances = TenantModelInstanceService.get_all_by_provider_id(provider_obj.id)
     if not instances:
+        logger.debug(f"No instances found for provider {provider_name}, tenant {tenant_id}")
         return []
     results = []
     for inst in instances:
         models = TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id, inst.id, model_type)
         if models:
             results.extend(models)
+    logger.debug(f"Found {len(results)} {model_type} models for {provider_name}, tenant {tenant_id}")
     return results

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/db/joint_services/tenant_model_service.py` around lines 309 - 325, The
function get_models_by_tenant_and_provider_and_model_type lacks any logging; add
logs inside that function (using the module logger) to record key events and
counts: log when provider_obj is not found (include tenant_id and
provider_name), log the number of instances returned from
TenantModelInstanceService.get_all_by_provider_id(provider_obj.id), for each
inst log the instance id and number of models returned by
TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id,
inst.id, model_type), and finally log the total number of aggregated results
before returning; place logs at appropriate levels (info/debug) to aid debugging
of tenant-specific model lookups.

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/db/joint_services/tenant_model_service.py`:
- Around line 76-110: The _ensure_ocr_provider_from_env function performs DB
inserts and lookups without any logs; add structured logging at key steps in
_ensure_ocr_provider_from_env: log when config is missing, when a
TenantModelProviderService lookup misses and you insert a provider (include
tenant_id and provider_name), when creating a TenantModelInstance via
TenantModelInstanceService.create_instance (include provider_id, model_name and
a masked/partial api_key), when inserting a TenantModelService model (include
provider_id, instance_id, model_name and model_type), and log any unexpected
failures or exceptions around these calls; use the module logger (or
logging.getLogger(__name__)) and avoid logging full secrets (mask api_key) to
meet guidelines.
- Around line 50-62: Add structured logging to the get_first_provider_model_name
flow: import and use the module logger and add logs in
TenantModelProviderService/TenantModelInstanceService/TenantModelService
interaction points — log when no provider found for tenant_id/provider_name, log
when skipping an instance because instance_obj.status !=
ActiveStatusEnum.ACTIVE.value (include instance id/name and
tenant_id/provider_name), log when skipping a model because model_obj.status !=
ActiveStatusEnum.ACTIVE.value or model_obj.model_type mismatch (include model
id/name/type), and log the resolved model string right before the return in
get_first_provider_model_name. Ensure logs include tenant_id, provider_name,
instance_obj.id/instance_name and model_obj.model_name to aid tenant-specific
debugging.
- Line 20: The file currently imports IntegrityError but never uses it; remove
the unused import by deleting IntegrityError from the import statement at the
top (the "from peewee import IntegrityError" reference) so the module no longer
contains a dead import and lints cleanly.

---

Outside diff comments:
In `@rag/app/naive.py`:
- Around line 222-229: The code in the OpenDataLoader selection block
incorrectly accesses TenantModel.llm_name and manually picks candidates[0],
causing crashes and inconsistency; replace this manual logic with a call to the
unified helper get_first_provider_model_name(tenant_id,
provider_name="OpenDataLoader", model_type=LLMType.OCR) and fall back to
ensure_opendataloader_from_env(tenant_id) only if that helper returns None, and
ensure you read the model name via the helper (or TenantModel.model_name) rather
than .llm_name; update the selection in the opendataloader logic in the naive
flow to match the MinerU/PaddleOCR pattern.

---

Nitpick comments:
In `@api/db/joint_services/tenant_model_service.py`:
- Around line 309-325: The function
get_models_by_tenant_and_provider_and_model_type lacks any logging; add logs
inside that function (using the module logger) to record key events and counts:
log when provider_obj is not found (include tenant_id and provider_name), log
the number of instances returned from
TenantModelInstanceService.get_all_by_provider_id(provider_obj.id), for each
inst log the instance id and number of models returned by
TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id,
inst.id, model_type), and finally log the total number of aggregated results
before returning; place logs at appropriate levels (info/debug) to aid debugging
of tenant-specific model lookups.
🪄 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: 7465d05d-e9b5-4069-b76c-4c28c2793de0

📥 Commits

Reviewing files that changed from the base of the PR and between b0123c9 and a808afe.

📒 Files selected for processing (3)
  • api/db/joint_services/tenant_model_service.py
  • rag/app/naive.py
  • rag/flow/parser/parser.py

@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

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 3

Caution

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

⚠️ Outside diff range comments (1)
rag/app/naive.py (1)

222-229: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Incomplete OpenDataLoader refactoring spans two files.

Both rag/app/naive.py (lines 222–229) and rag/flow/parser/parser.py (lines 450–456) suffer from:

  1. Runtime crash: accessing .llm_name on TenantModel (which defines model_name, not llm_name)
  2. Inconsistent pattern: manually selecting the first candidate instead of using get_first_provider_model_name(...) like MinerU/PaddleOCR

The shared root cause is incomplete migration to the unified helper. Adopt the same pattern across all three OCR providers.

🤖 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 `@rag/app/naive.py` around lines 222 - 229, The code in the OpenDataLoader
selection block incorrectly accesses TenantModel.llm_name and manually picks
candidates[0], causing crashes and inconsistency; replace this manual logic with
a call to the unified helper get_first_provider_model_name(tenant_id,
provider_name="OpenDataLoader", model_type=LLMType.OCR) and fall back to
ensure_opendataloader_from_env(tenant_id) only if that helper returns None, and
ensure you read the model name via the helper (or TenantModel.model_name) rather
than .llm_name; update the selection in the opendataloader logic in the naive
flow to match the MinerU/PaddleOCR pattern.
🧹 Nitpick comments (1)
api/db/joint_services/tenant_model_service.py (1)

309-325: ⚡ Quick win

Add logging for model aggregation query.

This new helper lacks logging. Debugging tenant-specific model lookups requires visibility into what was found.

📝 Suggested logging
 def get_models_by_tenant_and_provider_and_model_type(tenant_id: str, provider_name: str, model_type: str):
     """
     Query TenantModel records by tenant_id, provider_name and model_name.
     Returns all matching model records under all instances of the specified provider.
     """
     provider_obj = TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id, provider_name)
     if not provider_obj:
+        logger.debug(f"Provider {provider_name} not found for tenant {tenant_id}")
         return []
     instances = TenantModelInstanceService.get_all_by_provider_id(provider_obj.id)
     if not instances:
+        logger.debug(f"No instances found for provider {provider_name}, tenant {tenant_id}")
         return []
     results = []
     for inst in instances:
         models = TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id, inst.id, model_type)
         if models:
             results.extend(models)
+    logger.debug(f"Found {len(results)} {model_type} models for {provider_name}, tenant {tenant_id}")
     return results

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/db/joint_services/tenant_model_service.py` around lines 309 - 325, The
function get_models_by_tenant_and_provider_and_model_type lacks any logging; add
logs inside that function (using the module logger) to record key events and
counts: log when provider_obj is not found (include tenant_id and
provider_name), log the number of instances returned from
TenantModelInstanceService.get_all_by_provider_id(provider_obj.id), for each
inst log the instance id and number of models returned by
TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id,
inst.id, model_type), and finally log the total number of aggregated results
before returning; place logs at appropriate levels (info/debug) to aid debugging
of tenant-specific model lookups.

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/db/joint_services/tenant_model_service.py`:
- Around line 76-110: The _ensure_ocr_provider_from_env function performs DB
inserts and lookups without any logs; add structured logging at key steps in
_ensure_ocr_provider_from_env: log when config is missing, when a
TenantModelProviderService lookup misses and you insert a provider (include
tenant_id and provider_name), when creating a TenantModelInstance via
TenantModelInstanceService.create_instance (include provider_id, model_name and
a masked/partial api_key), when inserting a TenantModelService model (include
provider_id, instance_id, model_name and model_type), and log any unexpected
failures or exceptions around these calls; use the module logger (or
logging.getLogger(__name__)) and avoid logging full secrets (mask api_key) to
meet guidelines.
- Around line 50-62: Add structured logging to the get_first_provider_model_name
flow: import and use the module logger and add logs in
TenantModelProviderService/TenantModelInstanceService/TenantModelService
interaction points — log when no provider found for tenant_id/provider_name, log
when skipping an instance because instance_obj.status !=
ActiveStatusEnum.ACTIVE.value (include instance id/name and
tenant_id/provider_name), log when skipping a model because model_obj.status !=
ActiveStatusEnum.ACTIVE.value or model_obj.model_type mismatch (include model
id/name/type), and log the resolved model string right before the return in
get_first_provider_model_name. Ensure logs include tenant_id, provider_name,
instance_obj.id/instance_name and model_obj.model_name to aid tenant-specific
debugging.
- Line 20: The file currently imports IntegrityError but never uses it; remove
the unused import by deleting IntegrityError from the import statement at the
top (the "from peewee import IntegrityError" reference) so the module no longer
contains a dead import and lints cleanly.

---

Outside diff comments:
In `@rag/app/naive.py`:
- Around line 222-229: The code in the OpenDataLoader selection block
incorrectly accesses TenantModel.llm_name and manually picks candidates[0],
causing crashes and inconsistency; replace this manual logic with a call to the
unified helper get_first_provider_model_name(tenant_id,
provider_name="OpenDataLoader", model_type=LLMType.OCR) and fall back to
ensure_opendataloader_from_env(tenant_id) only if that helper returns None, and
ensure you read the model name via the helper (or TenantModel.model_name) rather
than .llm_name; update the selection in the opendataloader logic in the naive
flow to match the MinerU/PaddleOCR pattern.

---

Nitpick comments:
In `@api/db/joint_services/tenant_model_service.py`:
- Around line 309-325: The function
get_models_by_tenant_and_provider_and_model_type lacks any logging; add logs
inside that function (using the module logger) to record key events and counts:
log when provider_obj is not found (include tenant_id and provider_name), log
the number of instances returned from
TenantModelInstanceService.get_all_by_provider_id(provider_obj.id), for each
inst log the instance id and number of models returned by
TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id,
inst.id, model_type), and finally log the total number of aggregated results
before returning; place logs at appropriate levels (info/debug) to aid debugging
of tenant-specific model lookups.
🪄 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: 7465d05d-e9b5-4069-b76c-4c28c2793de0

📥 Commits

Reviewing files that changed from the base of the PR and between b0123c9 and a808afe.

📒 Files selected for processing (3)
  • api/db/joint_services/tenant_model_service.py
  • rag/app/naive.py
  • rag/flow/parser/parser.py
🛑 Comments failed to post (3)
api/db/joint_services/tenant_model_service.py (3)

20-20: ⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check if IntegrityError is used in this file

rg -n 'IntegrityError' api/db/joint_services/tenant_model_service.py -A 3 -B 3

Repository: infiniflow/ragflow

Length of output: 437


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="api/db/joint_services/tenant_model_service.py"

echo "== File line count =="
wc -l "$FILE"

echo
echo "== IntegrityError occurrences =="
rg -n --hidden --no-ignore-vcs 'IntegrityError' "$FILE" || true
echo
echo "Count:"
rg -n 'IntegrityError' "$FILE" | wc -l || true

echo
echo "== Look for exception handling patterns =="
rg -n --hidden --no-ignore-vcs 'except\s+.*:' "$FILE" -S || true
rg -n --hidden --no-ignore-vcs 'except\s+.*IntegrityError' "$FILE" -S || true

echo
echo "== Search for provider/instance creation call sites =="
rg -n --hidden --no-ignore-vcs 'provider|instance|create|upsert|insert|get_or_create|on_conflict' "$FILE" -S || true

Repository: infiniflow/ragflow

Length of output: 7184


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="api/db/joint_services/tenant_model_service.py"

# Print top + likely relevant middle sections without dumping entire file
echo "== Top 80 lines =="
sed -n '1,120p' "$FILE" | cat -n

echo
echo "== Lines 120-240 =="
sed -n '120,240p' "$FILE" | cat -n

Repository: infiniflow/ragflow

Length of output: 11619


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="api/db/joint_services/tenant_model_service.py"

echo "== File line count =="
wc -l "$FILE"

echo
echo "== IntegrityError occurrences =="
rg -n --hidden --no-ignore-vcs 'IntegrityError' "$FILE" || true
echo
echo "Count:"
rg -n 'IntegrityError' "$FILE" | wc -l || true

echo
echo "== Look for exception handling patterns =="
rg -n --hidden --no-ignore-vcs 'except\s+.*IntegrityError' "$FILE" -S || true
echo
echo "All except clauses:"
rg -n --hidden --no-ignore-vcs 'except\s+.*:' "$FILE" -S || true

echo
echo "== Search for provider/instance creation call sites =="
rg -n --hidden --no-ignore-vcs 'provider|instance|create|upsert|insert|get_or_create|on_conflict' "$FILE" -S || true

Repository: infiniflow/ragflow

Length of output: 7205


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="api/db/joint_services/tenant_model_service.py"

echo "== Top 120 lines =="
sed -n '1,120p' "$FILE" | cat -n

echo
echo "== Lines 120-260 =="
sed -n '120,260p' "$FILE" | cat -n

Repository: infiniflow/ragflow

Length of output: 12659


Remove unused IntegrityError import.

api/db/joint_services/tenant_model_service.py imports IntegrityError but the file contains no other references to it (no except IntegrityError or other usage), so it’s likely a dead import unless needed elsewhere.

🤖 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/db/joint_services/tenant_model_service.py` at line 20, The file currently
imports IntegrityError but never uses it; remove the unused import by deleting
IntegrityError from the import statement at the top (the "from peewee import
IntegrityError" reference) so the module no longer contains a dead import and
lints cleanly.

50-62: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add logging for new OCR model resolution flow.

This new helper lacks logging. Per coding guidelines, new flows should include logging to aid debugging tenant-specific model selection.

📝 Suggested logging additions
 def get_first_provider_model_name(tenant_id: str, provider_name: str, model_type: str | enum.Enum) -> str | None:
     model_type_val = model_type if isinstance(model_type, str) else model_type.value
     provider_obj = TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id, provider_name)
     if not provider_obj:
+        logger.info(f"Provider {provider_name} not found for tenant {tenant_id}")
         return None
 
     for instance_obj in TenantModelInstanceService.get_all_by_provider_id(provider_obj.id):
         if instance_obj.status != ActiveStatusEnum.ACTIVE.value:
             continue
         for model_obj in TenantModelService.get_models_by_instance_id(instance_obj.id):
             if model_obj.model_type == model_type_val and model_obj.status == ActiveStatusEnum.ACTIVE.value:
+                logger.debug(f"Selected {model_type_val} model {model_obj.model_name} for tenant {tenant_id}")
                 return f"{model_obj.model_name}@{instance_obj.instance_name}@{provider_name}"
+    logger.warning(f"No active {model_type_val} model found for provider {provider_name}, tenant {tenant_id}")
     return None

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/db/joint_services/tenant_model_service.py` around lines 50 - 62, Add
structured logging to the get_first_provider_model_name flow: import and use the
module logger and add logs in
TenantModelProviderService/TenantModelInstanceService/TenantModelService
interaction points — log when no provider found for tenant_id/provider_name, log
when skipping an instance because instance_obj.status !=
ActiveStatusEnum.ACTIVE.value (include instance id/name and
tenant_id/provider_name), log when skipping a model because model_obj.status !=
ActiveStatusEnum.ACTIVE.value or model_obj.model_type mismatch (include model
id/name/type), and log the resolved model string right before the return in
get_first_provider_model_name. Ensure logs include tenant_id, provider_name,
instance_obj.id/instance_name and model_obj.model_name to aid tenant-specific
debugging.

Source: Coding guidelines


76-110: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add logging for OCR provider provisioning.

_ensure_ocr_provider_from_env creates database records but lacks logging. This makes tenant-specific OCR setup difficult to troubleshoot.

📝 Suggested logging additions
 def _ensure_ocr_provider_from_env(tenant_id: str, provider_name: str, model_name: str, config: dict | None) -> str | None:
     if not config:
         return None
 
     provider_obj = TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id, provider_name)
     if not provider_obj:
+        logger.info(f"Creating {provider_name} provider for tenant {tenant_id}")
         TenantModelProviderService.insert(tenant_id=tenant_id, provider_name=provider_name)
         provider_obj = TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id, provider_name)
 
     api_key = json.dumps(config)
     instance_obj = TenantModelInstanceService.get_by_provider_id_and_api_key(provider_obj.id, api_key)
     if not instance_obj:
+        logger.info(f"Creating {provider_name} instance '{model_name}' for tenant {tenant_id}")
         instance_obj = TenantModelInstanceService.create_instance(
             provider_id=provider_obj.id,
             instance_name=model_name,
             api_key=api_key,
             extra="{}",
         )
 
     model_obj = TenantModelService.get_by_provider_id_and_instance_id_and_model_type_and_model_name(
         provider_obj.id,
         instance_obj.id,
         LLMType.OCR.value,
         model_name,
     )
     if not model_obj:
+        logger.info(f"Creating OCR model '{model_name}' for tenant {tenant_id}")
         TenantModelService.insert(
             model_name=model_name,
             provider_id=provider_obj.id,
             instance_id=instance_obj.id,
             model_type=LLMType.OCR.value,
             extra=json.dumps({"max_tokens": 0}),
         )
 
     return f"{model_name}@{instance_obj.instance_name}@{provider_name}"

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/db/joint_services/tenant_model_service.py` around lines 76 - 110, The
_ensure_ocr_provider_from_env function performs DB inserts and lookups without
any logs; add structured logging at key steps in _ensure_ocr_provider_from_env:
log when config is missing, when a TenantModelProviderService lookup misses and
you insert a provider (include tenant_id and provider_name), when creating a
TenantModelInstance via TenantModelInstanceService.create_instance (include
provider_id, model_name and a masked/partial api_key), when inserting a
TenantModelService model (include provider_id, instance_id, model_name and
model_type), and log any unexpected failures or exceptions around these calls;
use the module logger (or logging.getLogger(__name__)) and avoid logging full
secrets (mask api_key) to meet guidelines.

Source: Coding guidelines

@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 `@api/apps/services/models_api_service.py`:
- Around line 305-307: The new OpenDataLoader provisioning call
ensure_opendataloader_from_env(tenant_id) lacks an informational log entry; add
a descriptive logger.info or logger.debug call before (or immediately after)
invoking ensure_opendataloader_from_env to mirror the existing provisioning logs
for ensure_mineru_from_env and ensure_paddleocr_from_env, including the
tenant_id and action name (e.g., "Provisioning OpenDataLoader for tenant:
{tenant_id}") so operators can trace this flow in production; ensure you use the
module/class logger used elsewhere in models_api_service.py for consistency.
🪄 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: a0c32cbe-e04c-4046-87ab-424bbf49153b

📥 Commits

Reviewing files that changed from the base of the PR and between a808afe and 3c26967.

📒 Files selected for processing (1)
  • api/apps/services/models_api_service.py

Comment on lines 305 to +307
ensure_mineru_from_env(tenant_id)
ensure_paddleocr_from_env(tenant_id)
ensure_opendataloader_from_env(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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add logging for the new OpenDataLoader provisioning flow.

Line 307 introduces a new flow path (ensure_opendataloader_from_env) but does not emit a log, which makes provisioning/debugging harder in production triage.

Suggested patch
     ensure_mineru_from_env(tenant_id)
     ensure_paddleocr_from_env(tenant_id)
+    logging.debug("Ensuring OpenDataLoader OCR model from env for tenant_id=%s", tenant_id)
     ensure_opendataloader_from_env(tenant_id)

As per coding guidelines, **/*.py: Add logging for new flows.

📝 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
ensure_mineru_from_env(tenant_id)
ensure_paddleocr_from_env(tenant_id)
ensure_opendataloader_from_env(tenant_id)
ensure_mineru_from_env(tenant_id)
ensure_paddleocr_from_env(tenant_id)
logging.debug("Ensuring OpenDataLoader OCR model from env for tenant_id=%s", tenant_id)
ensure_opendataloader_from_env(tenant_id)
🤖 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 305 - 307, The new
OpenDataLoader provisioning call ensure_opendataloader_from_env(tenant_id) lacks
an informational log entry; add a descriptive logger.info or logger.debug call
before (or immediately after) invoking ensure_opendataloader_from_env to mirror
the existing provisioning logs for ensure_mineru_from_env and
ensure_paddleocr_from_env, including the tenant_id and action name (e.g.,
"Provisioning OpenDataLoader for tenant: {tenant_id}") so operators can trace
this flow in production; ensure you use the module/class logger used elsewhere
in models_api_service.py for consistency.

Source: Coding guidelines

@wangq8
wangq8 merged commit 478c984 into infiniflow:main Jun 10, 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 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