Skip to content

refa: resolve tenant model refs consistently - #16744

Merged
wangq8 merged 15 commits into
infiniflow:mainfrom
buua436:b102
Jul 9, 2026
Merged

wangq8 merged 15 commits into
infiniflow:mainfrom
buua436:b102

Conversation

@buua436

@buua436 buua436 commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fix dataset update flow so embd_id can be resolved consistently whether the request passes a tenant model id or a model name. Also unify tenant model resolution paths to use the existing model lookup utilities instead of re-parsing model refs in multiple places.

Type of change

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

@buua436 buua436 added the ci Continue Integration label Jul 8, 2026
@buua436
buua436 requested a review from Lynn-Inf July 8, 2026 09:11
@coderabbitai

coderabbitai Bot commented Jul 8, 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 resolver-based tenant model lookup helpers and updates callers across agent, API, RAG, and task execution code. It also expands model listing with tenant metadata and allows dataset embedding inputs to pass tenant model ids.

Changes

Model Config Resolver Migration

Layer / File(s) Summary
Core resolver functions
api/db/joint_services/tenant_model_service.py
Adds resolve_model_config, resolve_model_type, get_model_type_by_id, and updates get_model_config_by_id and get_tenant_default_model_by_type to use id-first resolution, type validation, and provider fallback.
Dialog service chat flows
api/db/services/dialog_service.py, test/unit_test/api/db/services/test_dialog_service_final_answer.py, test/unit_test/api/db/services/test_dialog_service_use_sql_source_columns.py
async_chat_solo, get_models, async_chat, async_ask, and gen_mindmap switch to resolver-based model type/config lookup; related tests stub resolve_model_type.
Agent components migration
agent/component/agent_with_tools.py, agent/component/browser.py, agent/component/categorize.py, agent/component/llm.py, agent/tools/retrieval.py
Chat, embedding, rerank, OCR, and model-type resolution in agent components switch to resolve_model_type and resolve_model_config.
REST API endpoints and services
api/apps/restful_apis/bot_api.py, chat_api.py, chunk_api.py, dify_retrieval_api.py, openai_api.py, api/apps/services/provider_api_service.py, api/apps/services/dataset_api_service.py, api/utils/api_utils.py
Retrieval, chat validation, chunking, provider chat, and dataset search/check paths switch to resolve_model_config.
Memory message service
api/db/joint_services/memory_message_service.py
extract_by_llm, embed_and_save, and query_message switch to get_model_config_by_id with resolve_model_config fallback.
RAG parser and benchmark migration
rag/app/naive.py, rag/app/picture.py, rag/benchmark.py, rag/flow/parser/parser.py, rag/flow/parser/utils.py, rag/flow/tokenizer/tokenizer.py
OCR, vision, embedding, audio, and video model config lookups across parsing and tokenization switch to resolve_model_config.
GraphRAG smoke/search scripts
rag/graphrag/general/smoke.py, rag/graphrag/light/smoke.py, rag/graphrag/search.py
Embedding model configuration resolution switches to get_model_config_by_id with resolve_model_config fallback.
Prompt generator migration
rag/prompts/generator.py
full_question and cross_languages switch model type/config resolution to resolver-based helpers.
Task executor migration
rag/svr/task_executor.py, rag/svr/task_executor_refactor/chunk_post_processor.py, dataflow_service.py, dataset_wiki_generator.py, task_handler.py
Chat and embedding model config resolution across chunk processing, dataflow, wiki generation, RAPTOR, GraphRAG, and TOC paths switches to resolve_model_config.

Tenant Model Ownership Features

Layer / File(s) Summary
Owner tenant scoped model listing
api/apps/restful_apis/models_api.py
Adds owner_tenant_id, validates joined-tenant access through TenantService, and lists models for the resolved target tenant.
Model listing tenant metadata
api/apps/services/models_api_service.py
list_tenant_added_models adds tenant_id and tenant_name fields to returned models and the TEI Builtin entry.
Dataset embedding tenant-id passthrough
api/apps/services/dataset_api_service.py, api/utils/validation_utils.py
Dataset update resolves tenant_embd_id via TenantModelService and resolve_model_id; embedding validation accepts a 32-character hex tenant model id.

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

Sequence Diagram(s)

sequenceDiagram
  participant Caller as Caller
  participant Resolver as resolve_model_config
  participant IdLookup as get_model_config_by_id
  participant ProviderLookup as get_model_config_from_provider_instance

  Caller->>Resolver: tenant_id, model_type, model_ref
  Resolver->>IdLookup: try id-based lookup
  IdLookup-->>Resolver: model_config or LookupError
  Resolver->>ProviderLookup: fallback lookup
  ProviderLookup-->>Resolver: model_config
  Resolver-->>Caller: model_config
Loading

Possibly related PRs

  • infiniflow/ragflow#16482: Both PRs touch api/db/joint_services/tenant_model_service.py model-config resolution logic used by the new resolver helpers.
  • infiniflow/ragflow#16604: Both PRs modify tenant_model_service.py id-based resolvers and update dialog_service.py call sites to use them.
  • infiniflow/ragflow#16742: Both PRs modify dataset search and embedding-related resolution paths in dataset_api_service.py.

Suggested labels: size:XXL

Suggested reviewers: yingfeng, xugangqiang

Poem

A rabbit hopped through code so deep,
Swapping old lookups while others sleep,
resolve_model_config, hop by hop,
From provider chains straight to the top,
Tenant scopes now click just right —
🐇 crisp carrots in the light!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.04% 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 clearly reflects the main change: consistent tenant model reference resolution.
Description check ✅ Passed The description covers the problem, context, and change type, and is sufficiently complete despite using custom headings.
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 marked this pull request as ready for review July 9, 2026 03:12
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. labels Jul 9, 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: 7

Caution

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

⚠️ Outside diff range comments (4)
api/apps/restful_apis/chat_api.py (1)

300-305: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Wrong kwarg name breaks rerank validation in chat_api.py:300-305.
resolve_model_config takes model_ref, not model_name. This call raises TypeError inside the broad except, so valid non-default rerank models get rejected. Rename the kwarg to model_ref.

🤖 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/chat_api.py` around lines 300 - 305, The rerank model
validation call in resolve_model_config is using the wrong keyword argument,
which causes a TypeError that gets swallowed by the broad exception handling in
chat_api. Update the thread_pool_exec invocation in the rerank validation path
to pass model_ref instead of model_name, keeping the existing tenant_id and
model_type="rerank" arguments unchanged so non-default rerank models validate
correctly.
api/db/joint_services/memory_message_service.py (1)

247-274: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Resolve memory embeddings by tenant model ID first.

query_message resolves only from memory.embd_id, but the write path uses memory.tenant_embd_id when present. The memory update flow can also leave tenant_embd_id stale, so read-time queries can be embedded with a different model than the stored vectors.

🤖 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/memory_message_service.py` around lines 247 - 274,
query_message is resolving embeddings with memory.embd_id only, which can
diverge from the write path and stale tenant-specific model mapping. Update the
embedding model selection in query_message to prefer memory.tenant_embd_id when
present, with memory.embd_id as fallback, and use that same identifier when
calling resolve_model_config and LLMBundle so read-time queries match the stored
vector model.
api/apps/services/dataset_api_service.py (1)

326-336: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Keep embd_id canonical

  • req["embd_id"] still gets saved verbatim, so a tenant-model id can end up in Knowledgebase.embd_id. search_datasets and api/apps/restful_apis/chunk_api.py both call split_model_name(kb.embd_id) for cross-dataset embedding checks, so mixing raw ids with model@instance@provider strings will make the same model compare as different.
  • resolve_model_id(...) can raise LookupError here; wrap it and return a (False, err) response instead of letting the update fail unexpectedly.
🤖 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/dataset_api_service.py` around lines 326 - 336, Keep
`embd_id` in canonical model-name form instead of persisting a tenant-model id
in `Knowledgebase.embd_id`; in `dataset_api_service.py`, update the `embd_id`
handling so `req["embd_id"]` is normalized via `resolve_model_id(...)` before
save, while still setting `req["tenant_embd_id"]` for tenant lookup. Also wrap
the `resolve_model_id` call in the `embd_id` branch to catch `LookupError` and
return `(False, err)` instead of allowing the update to fail unexpectedly. Use
the existing `verify_embedding_availability`, `TenantModelService.get_by_id`,
and `resolve_model_id` flow to keep `search_datasets` and `chunk_api.py`
comparisons consistent.

Source: Path instructions

rag/svr/task_executor.py (1)

1391-1425: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use tenant_embd_id when binding embeddings here

task_service.py already includes Knowledgebase.tenant_embd_id in the task payload, but this legacy executor still binds from task["embd_id"] only. Mirror the refactor/dataflow path and prefer task["tenant_embd_id"] first, then fall back to embd_id or the tenant default.

🤖 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/svr/task_executor.py` around lines 1391 - 1425, The embedding binding
logic in task_executor.py still reads only task["embd_id"], so update the task
setup in the executor to prefer task["tenant_embd_id"] first, then fall back to
task["embd_id"], and finally the tenant default. Use the existing
task_embedding_id/resolve_model_config/get_tenant_default_model_by_type flow so
the LLMBundle initialization picks up the new tenant-level embedding ID without
changing the rest of the execution path.
🧹 Nitpick comments (7)
api/apps/restful_apis/models_api.py (1)

84-93: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low value

Optional: log the new owner-scope access decision.

The new owner_tenant_id cross-tenant path has no log entry on the permission-denied branch, which weakens auditability of access-control decisions.

As per coding guidelines ("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/restful_apis/models_api.py` around lines 84 - 93, Add logging for
the new owner_tenant_id cross-tenant access flow in the models_api permission
check. In the branch that returns “Permission denied” after checking
TenantService.get_joined_tenants_by_user_id and allowed_tenant_ids, emit a log
entry with enough context to audit the denied owner-scope access decision. Keep
the log close to the owner_tenant_id handling so it’s easy to trace alongside
target_tenant_id selection and the permission check.

Source: Coding guidelines

rag/svr/task_executor_refactor/dataflow_service.py (1)

238-248: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Same silent-fallback logging gap on tenant_embd_id lookup failure.

Consider a warning log before falling back to resolve_model_config(..., embedding_id), so a stale tenant_embd_id is discoverable in production without needing to reproduce the failure.

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 `@rag/svr/task_executor_refactor/dataflow_service.py` around lines 238 - 248,
The fallback path in dataflow_service.py for the embedding model lookup is
silently swallowing a LookupError when get_model_config_by_id(ctx.tenant_id,
LLMType.EMBEDDING, kb.tenant_embd_id) fails. Add a warning log in the except
LookupError branch inside the embedding config resolution logic so a stale
kb.tenant_embd_id is visible before calling resolve_model_config(...,
embedding_id), and keep the same fallback behavior in the embd_model_config
assignment flow.

Source: Coding guidelines

rag/svr/task_executor.py (1)

816-820: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Silent fallback on stale tenant_embd_id.

Same as elsewhere: the LookupError fallback here is silent. Consider logging a warning before falling back to embedding_id, consistent with get_tenant_default_model_by_type's pattern.

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 `@rag/svr/task_executor.py` around lines 816 - 820, The fallback in
task_executor.py is silent when get_model_config_by_id raises LookupError for
kb.tenant_embd_id, so add a warning log before switching to resolve_model_config
with embedding_id. Update the logic around the embd_model_config assignment in
the task executor flow to match the warning pattern used by
get_tenant_default_model_by_type, so stale tenant_embd_id values are visible
when the fallback path is taken.

Source: Coding guidelines

rag/graphrag/general/smoke.py (1)

79-83: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Silent fallback when tenant_embd_id lookup fails.

When get_model_config_by_id raises LookupError, the fallback to resolve_model_config(..., kb.embd_id) happens silently. get_tenant_default_model_by_type in tenant_model_service.py logs a warning in the analogous situation — worth doing the same here so a stale tenant_embd_id is observable.

♻️ Suggested logging addition
     if kb.tenant_embd_id:
         try:
             embd_model_config = get_model_config_by_id(args.tenant_id, LLMType.EMBEDDING, kb.tenant_embd_id)
         except LookupError:
+            logging.warning("tenant_model id=%s not found, falling back to model_name lookup for %s", kb.tenant_embd_id, kb.embd_id)
             embd_model_config = resolve_model_config(args.tenant_id, LLMType.EMBEDDING, kb.embd_id)

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 `@rag/graphrag/general/smoke.py` around lines 79 - 83, Add a warning log in the
`smoke.py` embedding model selection flow when `get_model_config_by_id` fails
with `LookupError` and the code falls back to `resolve_model_config` using
`kb.embd_id`. Mirror the behavior of `get_tenant_default_model_by_type` in
`tenant_model_service.py` by logging the stale `tenant_embd_id` context before
the fallback so the silent recovery is observable, and keep the fallback logic
in the existing `embd_model_config` assignment path.

Source: Coding guidelines

rag/svr/task_executor_refactor/task_handler.py (1)

321-336: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Silent fallback on tenant_embd_id lookup failure.

This is the most complete version of the embedding-resolution pattern in the PR (it correctly adds the tenant-id branch that task_executor.py's do_handle_task is missing), but the LookupError fallback here is still silent, unlike get_tenant_default_model_by_type's warning-log pattern.

♻️ Suggested logging addition
             if ctx.tenant_embd_id:
                 try:
                     embd_model_config = get_model_config_by_id(
                         task_tenant_id, LLMType.EMBEDDING, ctx.tenant_embd_id
                     )
                 except LookupError:
+                    logging.warning("tenant_model id=%s not found, falling back to model_name lookup for %s", ctx.tenant_embd_id, task_embedding_id)
                     embd_model_config = resolve_model_config(
                         task_tenant_id, LLMType.EMBEDDING, task_embedding_id
                     )

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 `@rag/svr/task_executor_refactor/task_handler.py` around lines 321 - 336, The
`tenant_embd_id` fallback in the embedding resolution flow is silent when
`get_model_config_by_id` raises `LookupError`. Update the `task_handler.py`
branch around `get_model_config_by_id`, `resolve_model_config`, and
`get_tenant_default_model_by_type` to emit a warning log inside the `except
LookupError` path before falling back, matching the existing logging style used
by the tenant-default model resolution flow. Keep the fallback behavior the
same, but make the failure visible with enough context to identify the
tenant/model lookup that failed.

Source: Coding guidelines

api/db/joint_services/tenant_model_service.py (1)

252-256: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

New resolver helpers lack logging on fallback/failure paths.

resolve_model_config (and resolve_model_type at 452-456) silently retries via the fallback path with no log trace, unlike get_tenant_default_model_by_type which logs a warning on ID-lookup failure (line 200). Consider adding a debug/warning log when the ID-based lookup fails and falls back to name/provider-instance resolution, to aid tracing model-resolution issues in production.

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 252 - 256,
`resolve_model_config` currently falls back from `get_model_config_by_id` to
`get_model_config_from_provider_instance` with no trace, so add a debug or
warning log in the `LookupError` path before retrying, matching the logging
style used by `get_tenant_default_model_by_type`; also update the similar
fallback in `resolve_model_type` so both resolver helpers emit a log when
ID-based lookup fails and the name/provider-instance path is used.

Source: Coding guidelines

agent/component/agent_with_tools.py (1)

85-87: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Optional: avoid duplicate model resolution between LLM.__init__ and Agent.__init__.

Agent.__init__ calls LLM.__init__ (line 78) which already resolves model_types and chat_model_config via the same resolve_model_type / resolve_model_config calls. The resolution at lines 85-87 repeats the same work and overwrites self.chat_mdl. Consider extracting the model-type selection into a shared helper or having Agent augment the existing self.chat_mdl rather than re-resolving from scratch.

🤖 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 `@agent/component/agent_with_tools.py` around lines 85 - 87, `Agent.__init__`
is duplicating the model resolution already done by `LLM.__init__`, which
re-calls `resolve_model_type` and `resolve_model_config` and overwrites
`self.chat_mdl`. Refactor the `Agent`/`LLM` initialization flow so the shared
model selection logic lives in one place, and have `Agent` reuse or augment the
existing `self.chat_mdl` instead of resolving it again. Use the `LLM.__init__`
and `Agent.__init__` paths to locate the duplicated setup and keep
`self.chat_mdl` consistent without redundant lookups.
🤖 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/models_api.py`:
- Around line 85-93: The authorization check in the tenant selection logic is
using the wrong tenant context, so it may validate access against the owner’s
memberships instead of the current user’s. In the models_api flow around the
owner_tenant_id handling, change the call to
TenantService.get_joined_tenants_by_user_id() to use the current tenant_id, then
compare owner_tenant_id against that allowed set before setting
target_tenant_id. Keep the Permission denied path for cases where the owner
tenant is not in the current user’s joined tenants.

In `@api/apps/services/dataset_api_service.py`:
- Around line 1054-1062: Align the `rerank_id` fallback order between `search()`
and `search_datasets()` in `dataset_api_service.py`: the two paths should use
the same precedence when choosing between `search_config` and `req`. Update the
`rerank_id` resolution in `search()` to match the intended behavior used by
`search_datasets()` (or vice versa, if the newer order is the desired one), and
keep the downstream `resolve_model_config(..., LLMType.RERANK.value, rerank_id)`
flow unchanged.

In `@api/db/joint_services/tenant_model_service.py`:
- Around line 446-456: `get_model_type_by_id` currently resolves a model type by
`model_id` only, bypassing the tenant ownership/join validation used elsewhere
in this module. Update `get_model_type_by_id` to accept `tenant_id` and enforce
the same access-control check as `get_model_config_by_id`, then change
`resolve_model_type` to pass its `tenant_id` through before falling back to
`get_model_type_by_name`; use the existing `TenantModelService`/ownership
validation path so arbitrary tenant_model ids cannot be queried across tenants.

In `@api/db/services/dialog_service.py`:
- Around line 586-602: The CHAT/IMAGE2TEXT selection in dialog_service’s LLM
config resolution is swapped in the same branch as async_chat_solo, so the path
handling resolve_model_type() for chat models should request LLMType.CHAT
instead of LLMType.IMAGE2TEXT when calling
get_model_config_by_id/resolve_model_config. Update the conditional in the
dialog flow to match the fallback logic below it, and consider extracting the
repeated model-resolution logic into a shared helper like _resolve_llm_config to
prevent this mismatch from recurring.
- Around line 298-314: The tenant-id fast path in dialog_service’s model
resolution is requesting the wrong LLMType for chat models. Update the branch in
the dialog model lookup logic so the call to get_model_config_by_id uses
LLMType.CHAT when "chat" is in llm_types, matching the fallback path and the
get_models pattern in this file; keep IMAGE2TEXT only for non-chat models.
Ensure the fast path can succeed without falling into the LookupError retry
loop.

In `@api/utils/validation_utils.py`:
- Around line 642-645: The 32-hex string branch in the validation helper
currently returns the input unchanged, which can make exact ID lookups miss
lowercase stored IDs and fall through to later rejection. Update the matching
logic in the relevant validation function that handles `v` as a string so that
when the regex matches a 32-hex tenant model ID, it returns the normalized
lowercase value instead of the original input, consistent with
`validate_pipeline_id`.

In `@rag/benchmark.py`:
- Line 28: The embedding config lookup in benchmark handling should match the
other call sites by trying kb.tenant_embd_id first and only falling back to
resolve_model_config(kb.embd_id) on LookupError. Update the benchmark flow that
currently uses resolve_model_config directly, and import get_model_config_by_id
alongside resolve_model_config so the same tenant-model-id path is used
consistently in the benchmark class/methods that resolve embeddings.

---

Outside diff comments:
In `@api/apps/restful_apis/chat_api.py`:
- Around line 300-305: The rerank model validation call in resolve_model_config
is using the wrong keyword argument, which causes a TypeError that gets
swallowed by the broad exception handling in chat_api. Update the
thread_pool_exec invocation in the rerank validation path to pass model_ref
instead of model_name, keeping the existing tenant_id and model_type="rerank"
arguments unchanged so non-default rerank models validate correctly.

In `@api/apps/services/dataset_api_service.py`:
- Around line 326-336: Keep `embd_id` in canonical model-name form instead of
persisting a tenant-model id in `Knowledgebase.embd_id`; in
`dataset_api_service.py`, update the `embd_id` handling so `req["embd_id"]` is
normalized via `resolve_model_id(...)` before save, while still setting
`req["tenant_embd_id"]` for tenant lookup. Also wrap the `resolve_model_id` call
in the `embd_id` branch to catch `LookupError` and return `(False, err)` instead
of allowing the update to fail unexpectedly. Use the existing
`verify_embedding_availability`, `TenantModelService.get_by_id`, and
`resolve_model_id` flow to keep `search_datasets` and `chunk_api.py` comparisons
consistent.

In `@api/db/joint_services/memory_message_service.py`:
- Around line 247-274: query_message is resolving embeddings with memory.embd_id
only, which can diverge from the write path and stale tenant-specific model
mapping. Update the embedding model selection in query_message to prefer
memory.tenant_embd_id when present, with memory.embd_id as fallback, and use
that same identifier when calling resolve_model_config and LLMBundle so
read-time queries match the stored vector model.

In `@rag/svr/task_executor.py`:
- Around line 1391-1425: The embedding binding logic in task_executor.py still
reads only task["embd_id"], so update the task setup in the executor to prefer
task["tenant_embd_id"] first, then fall back to task["embd_id"], and finally the
tenant default. Use the existing
task_embedding_id/resolve_model_config/get_tenant_default_model_by_type flow so
the LLMBundle initialization picks up the new tenant-level embedding ID without
changing the rest of the execution path.

---

Nitpick comments:
In `@agent/component/agent_with_tools.py`:
- Around line 85-87: `Agent.__init__` is duplicating the model resolution
already done by `LLM.__init__`, which re-calls `resolve_model_type` and
`resolve_model_config` and overwrites `self.chat_mdl`. Refactor the
`Agent`/`LLM` initialization flow so the shared model selection logic lives in
one place, and have `Agent` reuse or augment the existing `self.chat_mdl`
instead of resolving it again. Use the `LLM.__init__` and `Agent.__init__` paths
to locate the duplicated setup and keep `self.chat_mdl` consistent without
redundant lookups.

In `@api/apps/restful_apis/models_api.py`:
- Around line 84-93: Add logging for the new owner_tenant_id cross-tenant access
flow in the models_api permission check. In the branch that returns “Permission
denied” after checking TenantService.get_joined_tenants_by_user_id and
allowed_tenant_ids, emit a log entry with enough context to audit the denied
owner-scope access decision. Keep the log close to the owner_tenant_id handling
so it’s easy to trace alongside target_tenant_id selection and the permission
check.

In `@api/db/joint_services/tenant_model_service.py`:
- Around line 252-256: `resolve_model_config` currently falls back from
`get_model_config_by_id` to `get_model_config_from_provider_instance` with no
trace, so add a debug or warning log in the `LookupError` path before retrying,
matching the logging style used by `get_tenant_default_model_by_type`; also
update the similar fallback in `resolve_model_type` so both resolver helpers
emit a log when ID-based lookup fails and the name/provider-instance path is
used.

In `@rag/graphrag/general/smoke.py`:
- Around line 79-83: Add a warning log in the `smoke.py` embedding model
selection flow when `get_model_config_by_id` fails with `LookupError` and the
code falls back to `resolve_model_config` using `kb.embd_id`. Mirror the
behavior of `get_tenant_default_model_by_type` in `tenant_model_service.py` by
logging the stale `tenant_embd_id` context before the fallback so the silent
recovery is observable, and keep the fallback logic in the existing
`embd_model_config` assignment path.

In `@rag/svr/task_executor_refactor/dataflow_service.py`:
- Around line 238-248: The fallback path in dataflow_service.py for the
embedding model lookup is silently swallowing a LookupError when
get_model_config_by_id(ctx.tenant_id, LLMType.EMBEDDING, kb.tenant_embd_id)
fails. Add a warning log in the except LookupError branch inside the embedding
config resolution logic so a stale kb.tenant_embd_id is visible before calling
resolve_model_config(..., embedding_id), and keep the same fallback behavior in
the embd_model_config assignment flow.

In `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 321-336: The `tenant_embd_id` fallback in the embedding resolution
flow is silent when `get_model_config_by_id` raises `LookupError`. Update the
`task_handler.py` branch around `get_model_config_by_id`,
`resolve_model_config`, and `get_tenant_default_model_by_type` to emit a warning
log inside the `except LookupError` path before falling back, matching the
existing logging style used by the tenant-default model resolution flow. Keep
the fallback behavior the same, but make the failure visible with enough context
to identify the tenant/model lookup that failed.

In `@rag/svr/task_executor.py`:
- Around line 816-820: The fallback in task_executor.py is silent when
get_model_config_by_id raises LookupError for kb.tenant_embd_id, so add a
warning log before switching to resolve_model_config with embedding_id. Update
the logic around the embd_model_config assignment in the task executor flow to
match the warning pattern used by get_tenant_default_model_by_type, so stale
tenant_embd_id values are visible when the fallback path is taken.
🪄 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: 19adc881-887d-4e51-a044-3344b27f6807

📥 Commits

Reviewing files that changed from the base of the PR and between 3d16720 and a394647.

📒 Files selected for processing (36)
  • agent/component/agent_with_tools.py
  • agent/component/browser.py
  • agent/component/categorize.py
  • agent/component/llm.py
  • agent/tools/retrieval.py
  • api/apps/restful_apis/bot_api.py
  • api/apps/restful_apis/chat_api.py
  • api/apps/restful_apis/chunk_api.py
  • api/apps/restful_apis/dify_retrieval_api.py
  • api/apps/restful_apis/models_api.py
  • api/apps/restful_apis/openai_api.py
  • api/apps/services/dataset_api_service.py
  • api/apps/services/models_api_service.py
  • api/apps/services/provider_api_service.py
  • api/db/joint_services/memory_message_service.py
  • api/db/joint_services/tenant_model_service.py
  • api/db/services/dialog_service.py
  • api/utils/api_utils.py
  • api/utils/validation_utils.py
  • rag/app/naive.py
  • rag/app/picture.py
  • rag/benchmark.py
  • rag/flow/parser/parser.py
  • rag/flow/parser/utils.py
  • rag/flow/tokenizer/tokenizer.py
  • rag/graphrag/general/smoke.py
  • rag/graphrag/light/smoke.py
  • rag/graphrag/search.py
  • rag/prompts/generator.py
  • rag/svr/task_executor.py
  • rag/svr/task_executor_refactor/chunk_post_processor.py
  • rag/svr/task_executor_refactor/dataflow_service.py
  • rag/svr/task_executor_refactor/dataset_wiki_generator.py
  • rag/svr/task_executor_refactor/task_handler.py
  • test/unit_test/api/db/services/test_dialog_service_final_answer.py
  • test/unit_test/api/db/services/test_dialog_service_use_sql_source_columns.py

Comment thread api/apps/restful_apis/models_api.py Resolved
Comment on lines +446 to +456
def get_model_type_by_id(model_id: str):
exist, model_obj = TenantModelService.get_by_id(model_id)
if not exist:
raise LookupError(f"TenantModel id={model_id} not found.")
return get_model_type_human(model_obj.model_type)

def resolve_model_type(tenant_id: str, model_ref: str):
try:
return get_model_type_by_id(model_ref)
except LookupError:
return get_model_type_by_name(tenant_id, model_ref)

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

get_model_type_by_id skips tenant-ownership validation that get_model_config_by_id enforces.

get_model_type_by_id fetches the tenant_model row purely by model_id, with no check that tenant_id owns (or is a joined tenant of) the provider — unlike get_model_config_by_id, which explicitly validates ownership (lines 338-343). resolve_model_type(tenant_id, model_ref) receives tenant_id but never forwards it to get_model_type_by_id, so any tenant can pass an arbitrary tenant_model id (e.g. via dialog.llm_id) belonging to another tenant and learn its model type. Actual model configs remain protected downstream (get_model_config_by_id/resolve_model_config still enforce ownership), but this breaks the access-control pattern established elsewhere in this file.

🔒️ Proposed fix
-def get_model_type_by_id(model_id: str):
+def get_model_type_by_id(tenant_id: str, model_id: str):
     exist, model_obj = TenantModelService.get_by_id(model_id)
     if not exist:
         raise LookupError(f"TenantModel id={model_id} not found.")
+    ok, provider_obj = TenantModelProviderService.get_by_id(model_obj.provider_id)
+    if not ok:
+        raise LookupError(f"Provider id={model_obj.provider_id} not found for model id={model_id}.")
+    if tenant_id != provider_obj.tenant_id:
+        joined_tenants = TenantService.get_joined_tenants_by_user_id(tenant_id)
+        joined_tenant_ids = [t["tenant_id"] for t in joined_tenants]
+        if provider_obj.tenant_id not in joined_tenant_ids:
+            raise LookupError(f"Tenant {tenant_id} has no access to provider owned by tenant {provider_obj.tenant_id}.")
     return get_model_type_human(model_obj.model_type)
 
 def resolve_model_type(tenant_id: str, model_ref: str):
     try:
-        return get_model_type_by_id(model_ref)
+        return get_model_type_by_id(tenant_id, model_ref)
     except LookupError:
         return get_model_type_by_name(tenant_id, model_ref)
📝 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
def get_model_type_by_id(model_id: str):
exist, model_obj = TenantModelService.get_by_id(model_id)
if not exist:
raise LookupError(f"TenantModel id={model_id} not found.")
return get_model_type_human(model_obj.model_type)
def resolve_model_type(tenant_id: str, model_ref: str):
try:
return get_model_type_by_id(model_ref)
except LookupError:
return get_model_type_by_name(tenant_id, model_ref)
def get_model_type_by_id(tenant_id: str, model_id: str):
exist, model_obj = TenantModelService.get_by_id(model_id)
if not exist:
raise LookupError(f"TenantModel id={model_id} not found.")
ok, provider_obj = TenantModelProviderService.get_by_id(model_obj.provider_id)
if not ok:
raise LookupError(f"Provider id={model_obj.provider_id} not found for model id={model_id}.")
if tenant_id != provider_obj.tenant_id:
joined_tenants = TenantService.get_joined_tenants_by_user_id(tenant_id)
joined_tenant_ids = [t["tenant_id"] for t in joined_tenants]
if provider_obj.tenant_id not in joined_tenant_ids:
raise LookupError(f"Tenant {tenant_id} has no access to provider owned by tenant {provider_obj.tenant_id}.")
return get_model_type_human(model_obj.model_type)
def resolve_model_type(tenant_id: str, model_ref: str):
try:
return get_model_type_by_id(tenant_id, model_ref)
except LookupError:
return get_model_type_by_name(tenant_id, model_ref)
🤖 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 446 - 456,
`get_model_type_by_id` currently resolves a model type by `model_id` only,
bypassing the tenant ownership/join validation used elsewhere in this module.
Update `get_model_type_by_id` to accept `tenant_id` and enforce the same
access-control check as `get_model_config_by_id`, then change
`resolve_model_type` to pass its `tenant_id` through before falling back to
`get_model_type_by_name`; use the existing `TenantModelService`/ownership
validation path so arbitrary tenant_model ids cannot be queried across tenants.

Comment thread api/db/services/dialog_service.py Resolved
Comment thread api/db/services/dialog_service.py Resolved
Comment on lines 642 to +645
if isinstance(v, str):
if re.fullmatch(r"[0-9a-fA-F]{32}", v):
return v

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -nP '^\s*import re\b|^\s*from re\b' api/utils/validation_utils.py
# Confirm tenant_model id casing at generation
rg -nP -C2 'get_uuid|uuid4|\.hex' api/db/joint_services/tenant_model_service.py

Repository: infiniflow/ragflow

Length of output: 169


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== validation_utils.py around the hex passthrough =="
sed -n '620,660p' api/utils/validation_utils.py

echo
echo "== tenant_model_service.py relevant ID lookup/generation =="
sed -n '1,260p' api/db/joint_services/tenant_model_service.py

echo
echo "== dataset_api_service.py embd_id lookup path =="
rg -n -C 3 'embd_id|TenantModelService\.get_by_id|resolve_model_id' api -g '*.py'

echo
echo "== any lowercasing normalization for pipeline IDs or model IDs =="
rg -n -C 2 'lower\(\).*hex|\.lower\(\).*id|validate_pipeline_id|pipeline_id' api -g '*.py'

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== tenant_model_service.py: ID generation / insert paths =="
rg -n -C 4 'uuid4|hex|gen.*id|create.*id|insert\(' api/db/joint_services/tenant_model_service.py api/db/services/tenant_model_service.py api/db/db_models.py

echo
echo "== validation_utils.py: pipeline_id normalization and embedding_model validator context =="
sed -n '520,680p' api/utils/validation_utils.py

echo
echo "== any other lowercase normalization for 32-hex ids =="
rg -n -C 2 'return .*lower\(\)|\.lower\(\).*fullmatch\(r"\[0-9a-fA-F\]\{32\}"|re\.fullmatch\(r"\[0-9a-fA-F\]\{32\}"' api -g '*.py'

Repository: infiniflow/ragflow

Length of output: 13906


Normalize 32-hex tenant model IDs to lowercase. TenantModelService.get_by_id(req["embd_id"]) is an exact lookup, so mixed/upper-case input can miss a stored lowercase tenant_model.id and fall through to resolve_model_id, which rejects bare 32-hex values. This should match validate_pipeline_id and return v.lower() here.

🤖 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/utils/validation_utils.py` around lines 642 - 645, The 32-hex string
branch in the validation helper currently returns the input unchanged, which can
make exact ID lookups miss lowercase stored IDs and fall through to later
rejection. Update the matching logic in the relevant validation function that
handles `v` as a string so that when the regex matches a 32-hex tenant model ID,
it returns the normalized lowercase value instead of the original input,
consistent with `validate_pipeline_id`.

Comment thread rag/benchmark.py
from api.db.services.llm_service import LLMBundle
from api.db.services.knowledgebase_service import KnowledgebaseService
from api.db.joint_services.tenant_model_service import get_model_config_from_provider_instance
from api.db.joint_services.tenant_model_service import resolve_model_config

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Missing tenant_embd_id fallback, unlike sibling call sites.

Every other embedding-resolution call site touched in this PR (rag/flow/tokenizer/tokenizer.py lines 66-70, rag/graphrag/light/smoke.py lines 80-84, rag/graphrag/search.py lines 319-323) prefers kb.tenant_embd_id via get_model_config_by_id, falling back to resolve_model_config(kb.embd_id) only on LookupError. This file goes straight to resolve_model_config(self.kb.tenant_id, LLMType.EMBEDDING, self.kb.embd_id), skipping the tenant-model-id path entirely.

🔧 Proposed fix to align with sibling call sites
-        embd_model_config = resolve_model_config(self.kb.tenant_id, LLMType.EMBEDDING, self.kb.embd_id)
+        if self.kb.tenant_embd_id:
+            try:
+                embd_model_config = get_model_config_by_id(self.kb.tenant_id, LLMType.EMBEDDING, self.kb.tenant_embd_id)
+            except LookupError:
+                embd_model_config = resolve_model_config(self.kb.tenant_id, LLMType.EMBEDDING, self.kb.embd_id)
+        else:
+            embd_model_config = resolve_model_config(self.kb.tenant_id, LLMType.EMBEDDING, self.kb.embd_id)

Requires importing get_model_config_by_id alongside resolve_model_config at line 28.

Also applies to: 46-47

🤖 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/benchmark.py` at line 28, The embedding config lookup in benchmark
handling should match the other call sites by trying kb.tenant_embd_id first and
only falling back to resolve_model_config(kb.embd_id) on LookupError. Update the
benchmark flow that currently uses resolve_model_config directly, and import
get_model_config_by_id alongside resolve_model_config so the same
tenant-model-id path is used consistently in the benchmark class/methods that
resolve embeddings.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

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

⚠️ Outside diff range comments (1)
api/apps/services/dataset_api_service.py (1)

1054-1062: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Align rerank_id precedence in both search paths
search_datasets() still uses req.get("rerank_id") or search_config.get("rerank_id"), while search() uses the reverse order. Pick one precedence and apply it in both places to avoid selecting a different rerank model for the same saved search config.

🤖 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/dataset_api_service.py` around lines 1054 - 1062, The
rerank model selection order is inconsistent between the two search paths,
causing different models to be picked for the same saved search configuration.
Update the rerank resolution logic in both `search()` and `search_datasets()` to
use the same precedence for `rerank_id`, and keep the existing
`resolve_model_config` flow and `LLMBundle` setup unchanged. Use the `rerank_id`
handling near `search_config`, `req.get("rerank_id")`, and `rerank_model_config`
as the place to align the 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.

Outside diff comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 1054-1062: The rerank model selection order is inconsistent
between the two search paths, causing different models to be picked for the same
saved search configuration. Update the rerank resolution logic in both
`search()` and `search_datasets()` to use the same precedence for `rerank_id`,
and keep the existing `resolve_model_config` flow and `LLMBundle` setup
unchanged. Use the `rerank_id` handling near `search_config`,
`req.get("rerank_id")`, and `rerank_model_config` as the place to align the
behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c21e4fe1-584c-4fd0-9488-6714f68fb40d

📥 Commits

Reviewing files that changed from the base of the PR and between a394647 and af00ec7.

📒 Files selected for processing (8)
  • api/apps/restful_apis/models_api.py
  • api/apps/services/dataset_api_service.py
  • api/apps/services/models_api_service.py
  • api/apps/services/provider_api_service.py
  • rag/svr/task_executor.py
  • rag/svr/task_executor_refactor/chunk_post_processor.py
  • rag/svr/task_executor_refactor/dataflow_service.py
  • rag/svr/task_executor_refactor/dataset_wiki_generator.py
🚧 Files skipped from review as they are similar to previous changes (5)
  • api/apps/restful_apis/models_api.py
  • rag/svr/task_executor_refactor/dataflow_service.py
  • rag/svr/task_executor_refactor/chunk_post_processor.py
  • api/apps/services/models_api_service.py
  • rag/svr/task_executor.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 (1430d0e) to head (eacccd0).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16744   +/-   ##
=======================================
  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 6a77523 into infiniflow:main Jul 9, 2026
3 checks 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 🌈 python Pull requests that update Python code ☯️ refactor Pull request that refactor/refine code 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