Repository navigation
refa: resolve tenant model refs consistently - #16744
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis 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. ChangesModel Config Resolver Migration
Tenant Model Ownership Features
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
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
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 winWrong kwarg name breaks rerank validation in
chat_api.py:300-305.
resolve_model_configtakesmodel_ref, notmodel_name. This call raisesTypeErrorinside the broadexcept, so valid non-default rerank models get rejected. Rename the kwarg tomodel_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 winResolve memory embeddings by tenant model ID first.
query_messageresolves only frommemory.embd_id, but the write path usesmemory.tenant_embd_idwhen present. The memory update flow can also leavetenant_embd_idstale, 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 winKeep
embd_idcanonical
req["embd_id"]still gets saved verbatim, so a tenant-model id can end up inKnowledgebase.embd_id.search_datasetsandapi/apps/restful_apis/chunk_api.pyboth callsplit_model_name(kb.embd_id)for cross-dataset embedding checks, so mixing raw ids withmodel@instance@providerstrings will make the same model compare as different.resolve_model_id(...)can raiseLookupErrorhere; 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 winUse
tenant_embd_idwhen binding embeddings here
task_service.pyalready includesKnowledgebase.tenant_embd_idin the task payload, but this legacy executor still binds fromtask["embd_id"]only. Mirror the refactor/dataflow path and prefertask["tenant_embd_id"]first, then fall back toembd_idor 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 valueOptional: log the new owner-scope access decision.
The new
owner_tenant_idcross-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 winSame silent-fallback logging gap on
tenant_embd_idlookup failure.Consider a warning log before falling back to
resolve_model_config(..., embedding_id), so a staletenant_embd_idis 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 winSilent fallback on stale
tenant_embd_id.Same as elsewhere: the
LookupErrorfallback here is silent. Consider logging a warning before falling back toembedding_id, consistent withget_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 winSilent fallback when
tenant_embd_idlookup fails.When
get_model_config_by_idraisesLookupError, the fallback toresolve_model_config(..., kb.embd_id)happens silently.get_tenant_default_model_by_typeintenant_model_service.pylogs a warning in the analogous situation — worth doing the same here so a staletenant_embd_idis 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 winSilent fallback on
tenant_embd_idlookup 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'sdo_handle_taskis missing), but theLookupErrorfallback here is still silent, unlikeget_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 winNew resolver helpers lack logging on fallback/failure paths.
resolve_model_config(andresolve_model_typeat 452-456) silently retries via the fallback path with no log trace, unlikeget_tenant_default_model_by_typewhich 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 valueOptional: avoid duplicate model resolution between
LLM.__init__andAgent.__init__.
Agent.__init__callsLLM.__init__(line 78) which already resolvesmodel_typesandchat_model_configvia the sameresolve_model_type/resolve_model_configcalls. The resolution at lines 85-87 repeats the same work and overwritesself.chat_mdl. Consider extracting the model-type selection into a shared helper or havingAgentaugment the existingself.chat_mdlrather 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
📒 Files selected for processing (36)
agent/component/agent_with_tools.pyagent/component/browser.pyagent/component/categorize.pyagent/component/llm.pyagent/tools/retrieval.pyapi/apps/restful_apis/bot_api.pyapi/apps/restful_apis/chat_api.pyapi/apps/restful_apis/chunk_api.pyapi/apps/restful_apis/dify_retrieval_api.pyapi/apps/restful_apis/models_api.pyapi/apps/restful_apis/openai_api.pyapi/apps/services/dataset_api_service.pyapi/apps/services/models_api_service.pyapi/apps/services/provider_api_service.pyapi/db/joint_services/memory_message_service.pyapi/db/joint_services/tenant_model_service.pyapi/db/services/dialog_service.pyapi/utils/api_utils.pyapi/utils/validation_utils.pyrag/app/naive.pyrag/app/picture.pyrag/benchmark.pyrag/flow/parser/parser.pyrag/flow/parser/utils.pyrag/flow/tokenizer/tokenizer.pyrag/graphrag/general/smoke.pyrag/graphrag/light/smoke.pyrag/graphrag/search.pyrag/prompts/generator.pyrag/svr/task_executor.pyrag/svr/task_executor_refactor/chunk_post_processor.pyrag/svr/task_executor_refactor/dataflow_service.pyrag/svr/task_executor_refactor/dataset_wiki_generator.pyrag/svr/task_executor_refactor/task_handler.pytest/unit_test/api/db/services/test_dialog_service_final_answer.pytest/unit_test/api/db/services/test_dialog_service_use_sql_source_columns.py
| 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) |
There was a problem hiding this comment.
🔒 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.
| 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.
| if isinstance(v, str): | ||
| if re.fullmatch(r"[0-9a-fA-F]{32}", v): | ||
| return v | ||
|
|
There was a problem hiding this comment.
🎯 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.pyRepository: 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`.
| 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 |
There was a problem hiding this comment.
🎯 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.
There was a problem hiding this comment.
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 winAlign
rerank_idprecedence in both search paths
search_datasets()still usesreq.get("rerank_id") or search_config.get("rerank_id"), whilesearch()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
📒 Files selected for processing (8)
api/apps/restful_apis/models_api.pyapi/apps/services/dataset_api_service.pyapi/apps/services/models_api_service.pyapi/apps/services/provider_api_service.pyrag/svr/task_executor.pyrag/svr/task_executor_refactor/chunk_post_processor.pyrag/svr/task_executor_refactor/dataflow_service.pyrag/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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
Fix dataset update flow so
embd_idcan be resolved consistently whether the request passes a tenant modelidor 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