Repository navigation
Fix: model-provider bugs - #15460
Fix: model-provider bugs#15460
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:
📝 WalkthroughWalkthroughAdds async provider API-key verification and endpoint; makes provider instance creation optionally verify keys and removes api_key from returned instances. Standardizes composite model key delimiters to ChangesProvider verification and instance lifecycle
Model key format update
DB index removal and migration updates
Sequence Diagram(s)sequenceDiagram
participant Client
participant ProviderAPI
participant ProviderService
participant ModelFactory
participant ExternalProvider
Client->>ProviderAPI: POST /providers/:name/connection {api_key, base_url?}
ProviderAPI->>ProviderService: await verify_api_key(provider_name, api_key, base_url)
ProviderService->>ModelFactory: build Embedding/Chat/Rerank instances
ModelFactory->>ExternalProvider: call provider endpoints (embed/chat/rerank) with timeout
ExternalProvider-->>ModelFactory: responses / stream chunks
ModelFactory-->>ProviderService: aggregated verification results
ProviderService-->>ProviderAPI: (success, message)
ProviderAPI-->>Client: 200 OK / error payload
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 inconclusive)
✅ Passed checks (3 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
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`:
- Line 346: The code unpacks provider_id, instance_id, model_name from
model_record_key.split("@") which will break if the model name contains '@';
change the parsing to use a max split of 2 (e.g., model_record_key.split("@",
2)) so only the first two '@' separate provider and instance and the remainder
becomes model_name, and add a defensive check that the resulting list has
exactly three parts before unpacking to raise/handle a clear error; locate the
parsing near the variables provider_id, instance_id, model_name in
models_api_service.py (the line using model_record_key.split("@")) and update it
accordingly.
🪄 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: ab9e19ef-b714-4ba4-ac84-82aa22e51fc3
📒 Files selected for processing (1)
api/apps/services/models_api_service.py
| if not model_records: | ||
| continue | ||
| provider_id, instance_id, model_name = model_record_key.split("_") | ||
| provider_id, instance_id, model_name = model_record_key.split("@") |
There was a problem hiding this comment.
Guard composite key parsing against @ inside model names.
Line 346 uses split("@") without a split limit. If a model name contains @, unpacking will fail with ValueError and break the listing path. Use split("@", 2).
💡 Suggested fix
- provider_id, instance_id, model_name = model_record_key.split("@")
+ provider_id, instance_id, model_name = model_record_key.split("@", 2)📝 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.
| provider_id, instance_id, model_name = model_record_key.split("@") | |
| provider_id, instance_id, model_name = model_record_key.split("@", 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 `@api/apps/services/models_api_service.py` at line 346, The code unpacks
provider_id, instance_id, model_name from model_record_key.split("@") which will
break if the model name contains '@'; change the parsing to use a max split of 2
(e.g., model_record_key.split("@", 2)) so only the first two '@' separate
provider and instance and the remainder becomes model_name, and add a defensive
check that the resulting list has exactly three parts before unpacking to
raise/handle a clear error; locate the parsing near the variables provider_id,
instance_id, model_name in models_api_service.py (the line using
model_record_key.split("@")) and update it accordingly.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15460 +/- ##
=======================================
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 Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
api/apps/services/provider_api_service.py (1)
316-316: ⚡ Quick winAvoid using
assertfor runtime validation.
assertstatements are stripped when Python runs with-O(optimize) flag, making these checks no-ops in production. Use explicitifchecks instead.♻️ Proposed refactor
- assert provider_name in EmbeddingModel, f"Embedding model from {provider_name} is not supported yet." + if provider_name not in EmbeddingModel: + continue # Skip unsupported embedding model- assert provider_name in ChatModel, f"Chat model from {provider_name} is not supported yet." + if provider_name not in ChatModel: + continue # Skip unsupported chat model- assert provider_name in RerankModel, f"Rerank model from {provider_name} is not supported yet." + if provider_name not in RerankModel: + continue # Skip unsupported rerank modelAlso applies to: 329-329, 350-350
🤖 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/provider_api_service.py` at line 316, Replace runtime assert checks in provider_api_service.py (e.g., the assert using provider_name in EmbeddingModel and the similar asserts around lines 329 and 350) with explicit conditional checks that raise a proper exception (ValueError or TypeError) and include a clear error message; locate the assertions inside the functions/methods around the provider lookup logic (references: the assert checking "provider_name in EmbeddingModel") and change them to if-not conditions that raise an exception so the validation always runs regardless of Python optimization flags.api/db/db_models.py (1)
1731-1741: 💤 Low valueSuperfluous "already exists" check in DROP INDEX error handling.
The condition
"already exists" in msg.lower()on line 1736 doesn't apply to DROP INDEX operations—this error message is typically returned by CREATE operations. While harmless, it may confuse future maintainers and could inadvertently suppress unrelated errors.Suggested fix
- if "1091" in msg or "can't DROP" in msg.lower() or "does not exist" in msg.lower() or "already exists" in msg.lower(): + if "1091" in msg or "can't DROP" in msg.lower() or "does not exist" in msg.lower():🤖 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/db_models.py` around lines 1731 - 1741, The DROP INDEX error handler around migrate(migrator.drop_index(table_name, index_name)) currently checks for "already exists" in the exception message which is irrelevant for DROP operations; remove the "already exists" check from the conditional while keeping the other guards ("1091", "can't DROP", "does not exist") so that migrate/migrator.drop_index exceptions are only suppressed for genuine non-existent/drop-related errors and all other exceptions are still logged via logging.critical.
🤖 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/provider_api_service.py`:
- Around line 319-327: The coroutine returned by asyncio.wait_for is not awaited
and the except block accesses llm as an object: add await before
asyncio.wait_for(...) when calling asyncio.to_thread(mdl.encode, [...]) so the
coroutine runs and the returned tuple can be unpacked into arr, tc; also change
llm.llm_name to llm["llm_name"] in the exception message to correctly index the
dict (affecting the block using mdl.encode, arr/tc, embd_passed and the except
that builds msg).
- Line 348: The code is using attribute access on llm (llm.fid and llm.llm_name)
but llm is a dict from factory_llms; replace those with safe dict access like
llm.get('fid', '<unknown>') and llm.get('llm_name', llm.get('name',
'<unknown>')) (or the actual keys used in factory_llms, e.g., 'id'/'name') and
include the exception string as before so the line becomes something like:
compose the message using llm.get(...) to avoid AttributeError and provide
sensible defaults when keys are missing.
- Around line 360-362: The exception message builds strings using llm.fid and
llm.llm_name but llm is a dict in this code path, causing attribute access
errors; update the block around logging.debug and the except construction to
access llm safely (e.g., use llm.get('fid') / llm.get('llm_name') or use getattr
with a fallback) so the message and debug log work for both dict and object
shapes and avoid raising a secondary AttributeError when formatting the error
string.
---
Nitpick comments:
In `@api/apps/services/provider_api_service.py`:
- Line 316: Replace runtime assert checks in provider_api_service.py (e.g., the
assert using provider_name in EmbeddingModel and the similar asserts around
lines 329 and 350) with explicit conditional checks that raise a proper
exception (ValueError or TypeError) and include a clear error message; locate
the assertions inside the functions/methods around the provider lookup logic
(references: the assert checking "provider_name in EmbeddingModel") and change
them to if-not conditions that raise an exception so the validation always runs
regardless of Python optimization flags.
In `@api/db/db_models.py`:
- Around line 1731-1741: The DROP INDEX error handler around
migrate(migrator.drop_index(table_name, index_name)) currently checks for
"already exists" in the exception message which is irrelevant for DROP
operations; remove the "already exists" check from the conditional while keeping
the other guards ("1091", "can't DROP", "does not exist") so that
migrate/migrator.drop_index exceptions are only suppressed for genuine
non-existent/drop-related errors and all other exceptions are still logged via
logging.critical.
🪄 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: 0ab6efb2-0bfd-4d7f-8acb-aae45924d62d
📒 Files selected for processing (5)
api/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.pyapi/db/db_models.pyinternal/entity/tenant_model_instance.gotools/scripts/mysql_migration.py
| arr, tc = asyncio.wait_for( | ||
| asyncio.to_thread(mdl.encode, ["Test if the api key is available"]), | ||
| timeout=timeout_seconds, | ||
| ) | ||
| if len(arr[0]) == 0: | ||
| raise Exception("Fail") | ||
| embd_passed = True | ||
| except Exception as e: | ||
| msg += f"\nFail to access embedding model({llm.llm_name}) using this api key." + str(e) |
There was a problem hiding this comment.
Missing await and incorrect dict access will cause runtime errors.
- Line 319: Missing
awaitbeforeasyncio.wait_for()- the coroutine won't execute and tuple unpacking will fail. - Line 327:
llm.llm_nameuses dot notation on a dict - should bellm["llm_name"].
🐛 Proposed fix
try:
- arr, tc = asyncio.wait_for(
+ arr, tc = await asyncio.wait_for(
asyncio.to_thread(mdl.encode, ["Test if the api key is available"]),
timeout=timeout_seconds,
)
if len(arr[0]) == 0:
raise Exception("Fail")
embd_passed = True
except Exception as e:
- msg += f"\nFail to access embedding model({llm.llm_name}) using this api key." + str(e)
+ msg += f"\nFail to access embedding model({llm['llm_name']}) using this api key." + str(e)🤖 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/provider_api_service.py` around lines 319 - 327, The
coroutine returned by asyncio.wait_for is not awaited and the except block
accesses llm as an object: add await before asyncio.wait_for(...) when calling
asyncio.to_thread(mdl.encode, [...]) so the coroutine runs and the returned
tuple can be unpacked into arr, tc; also change llm.llm_name to llm["llm_name"]
in the exception message to correctly index the dict (affecting the block using
mdl.encode, arr/tc, embd_passed and the except that builds msg).
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
tools/scripts/mysql_migration.py (1)
728-742:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winRemove the trailing comma from the
tenant_modelDDL.
create_target_table()now emitsINDEX idx_instance_id (instance_id),immediately before), which is invalid MySQL syntax. Any run that needs to createtenant_modelwill fail before the stage can migrate data.Proposed fix
CREATE TABLE IF NOT EXISTS tenant_model ( id VARCHAR(32) NOT NULL PRIMARY KEY, model_name VARCHAR(128), provider_id VARCHAR(32) NOT NULL, instance_id VARCHAR(32) NOT NULL, model_type VARCHAR(32) NOT NULL, status VARCHAR(32) DEFAULT 'active', extra VARCHAR(1024) DEFAULT '{}', create_time BIGINT, create_date DATETIME, update_time BIGINT, update_date DATETIME, - INDEX idx_instance_id (instance_id), + INDEX idx_instance_id (instance_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4🤖 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 `@tools/scripts/mysql_migration.py` around lines 728 - 742, The CREATE TABLE DDL for tenant_model contains a trailing comma before the closing parenthesis which causes invalid MySQL syntax; in the create_target_table() logic (the create_sql for tenant_model) remove the trailing comma after the INDEX idx_instance_id (instance_id) so the final token before ")" is the index definition, not a comma. Locate the create_sql string for tenant_model in mysql_migration.py (inside create_target_table()/create_sql) and delete the extra comma so the statement ends with "INDEX idx_instance_id (instance_id)" followed by the closing ") ENGINE=InnoDB ..." clause.
🧹 Nitpick comments (1)
tools/scripts/mysql_migration.py (1)
542-556: ⚡ Quick winLog the new empty-factory migration path and fallback behavior.
This branch changes which
tenant_llmrows are eligible for migration, but there is no log showing which factories were loaded or whether the code fell back totl.status = '0'only. Please add logging around config loading and condition selection so this new path is observable during dry runs and real migrations. As per coding guidelines,**/*.py: Add logging for new flows.Possible shape
`@staticmethod` def _get_empty_llm_factories() -> list[str]: """Load factory names whose llm field is an empty list from conf/llm_factories.json""" conf_path = os.path.join(PROJECT_BASE, "conf", "llm_factories.json") - with open(conf_path, "r") as f: - data = json.load(f) + with open(conf_path, "r") as f: + data = json.load(f) factories = [] for key, items in data.items(): if isinstance(items, list): for item in items: if isinstance(item, dict): llm = item.get("llm") if isinstance(llm, list) and len(llm) == 0: factories.append(item["name"]) + logger.info("Loaded %d empty-llm factories from %s", len(factories), conf_path) return factories def _build_status_condition(self) -> str: """Build SQL WHERE condition for status filtering""" empty_factories = self._get_empty_llm_factories() if empty_factories: + logger.info("Including status='1' tenant_llm rows for factories: %s", empty_factories) placeholders = ", ".join(f"'{f}'" for f in empty_factories) return f"(tl.status = '0' OR (tl.status = '1' AND tl.llm_factory IN ({placeholders})))" + logger.info("No empty-llm factories found; using status='0' filter only") return "tl.status = '0'"Also applies to: 609-610, 665-666
🤖 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 `@tools/scripts/mysql_migration.py` around lines 542 - 556, Add logging to make the empty-llm-factory path observable: in _get_empty_llm_factories() log the conf_path and the list of factory names found (include when file read fails or data is unexpected), and in the migration logic that filters tenant_llm rows (references to tenant_llm / tl.status and the conditional that falls back to "tl.status = '0'") log which branch is taken, which factory names triggered the special path, and whether the run is a dry-run or real migration; ensure logs include identifiers (e.g., tenant id or row id) and are emitted at info/debug level so the new flow is visible during dry runs and real migrations.
🤖 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 `@tools/scripts/mysql_migration.py`:
- Around line 558-564: The _build_status_condition method currently injects raw
factory names from _get_empty_llm_factories() into an SQL IN list, which allows
invalid SQL or injection; instead, change the code to return a parameterized
condition and accompanying parameter list (or properly SQL-escape each factory)
so callers can call check()/execute() with bound parameters; locate
_build_status_condition and _get_empty_llm_factories, have
_build_status_condition produce something like "tl.status = '0' OR (tl.status =
'1' AND tl.llm_factory IN (%s))" with placeholders and return both the condition
string and a tuple/list of factory values (or ensure each factory is safely
quoted using the DB API escape function) and update call sites that use the
returned string to pass the parameters to cursor.execute()/check().
---
Outside diff comments:
In `@tools/scripts/mysql_migration.py`:
- Around line 728-742: The CREATE TABLE DDL for tenant_model contains a trailing
comma before the closing parenthesis which causes invalid MySQL syntax; in the
create_target_table() logic (the create_sql for tenant_model) remove the
trailing comma after the INDEX idx_instance_id (instance_id) so the final token
before ")" is the index definition, not a comma. Locate the create_sql string
for tenant_model in mysql_migration.py (inside create_target_table()/create_sql)
and delete the extra comma so the statement ends with "INDEX idx_instance_id
(instance_id)" followed by the closing ") ENGINE=InnoDB ..." clause.
---
Nitpick comments:
In `@tools/scripts/mysql_migration.py`:
- Around line 542-556: Add logging to make the empty-llm-factory path
observable: in _get_empty_llm_factories() log the conf_path and the list of
factory names found (include when file read fails or data is unexpected), and in
the migration logic that filters tenant_llm rows (references to tenant_llm /
tl.status and the conditional that falls back to "tl.status = '0'") log which
branch is taken, which factory names triggered the special path, and whether the
run is a dry-run or real migration; ensure logs include identifiers (e.g.,
tenant id or row id) and are emitted at info/debug level so the new flow is
visible during dry runs and real migrations.
🪄 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: 518302ca-6ed5-40b6-83f5-19372651171f
📒 Files selected for processing (1)
tools/scripts/mysql_migration.py
…#15699) (#15879) ## Summary Fixes #15699. User upgrades to v0.25.6 against an existing MySQL database, tries to add an Ollama provider instance, and gets: ``` MySQL IntegrityError: Duplicate entry 'dbaafbfe608a11f1a5516d6066988224' for key 'tenant_model_instance.tenantmodelinstance_api_key_provider_id' ``` The route at [api/apps/restful_apis/provider_api.py:354](api/apps/restful_apis/provider_api.py#L354) catches it and returns `get_error_data_result(message="Internal server error")` — which by RAGFlow's convention is HTTP 200 with an error `code` on the body — hence the reporter's "200 status code but the database errored" complaint. ### Root cause The provider-instance refactor in [PR #15460](#15460) dropped the unique-compound-index tuple from `TenantModelInstance`: ```python # Removed in #15460 class Meta: db_table = "tenant_model_instance" indexes = ( (("api_key", "provider_id"), True), # unique ) ``` and added a one-shot drop in `migrate_db()` for existing databases. But the drop targets the wrong index name: ```python # Before this PR — wrong name for table_name, index_name in [ ("tenant_model_instance", "idx_api_key_provider_id"), # ← doesn't exist ("tenant_model", "idx_provider_model_instance"), ]: ``` Peewee's auto-derived index name is `<lowercase classname>_<col1>_<col2>` → **`tenantmodelinstance_api_key_provider_id`**, which matches the user's error verbatim. The drop raises `OperationalError: 1091 (HY000): Can't DROP …`, the surrounding `except` clause at [db_models.py:1736](api/db/db_models.py#L1736) swallows it as expected-on-fresh-installs, and the legacy unique index lives on indefinitely. ### Why Ollama hits it specifically Ollama doesn't require an API key. The form posts `api_key: ""`. The app-layer dedupe at [provider_api_service.py:288-292](api/apps/services/provider_api_service.py#L288-L292): ```python api_key_str = "" if api_key: # ← skipped for "" ... same_key_instance = TenantModelInstanceService.get_by_provider_id_and_api_key(...) if same_key_instance: return False, f"Already exist instance: ... with api_key {api_key}" ``` falls through for empty keys. Control reaches `TenantModelInstanceService.create_instance(..., api_key="")` which inserts a row whose `(api_key, provider_id) = ("", <provider_uuid>)` collides with any prior Ollama row that already shipped that same pair → the still-present unique index throws. (`dbaafbfe608a11f1a5516d6066988224` in the user's error is the duplicated `provider_id` UUID, paired with the empty `api_key`.) ### Fix Add the Peewee auto-name alongside the existing `idx_*` entry so the migration finally drops the obsolete index on next restart: ```python legacy_indexes = [ ("tenant_model_instance", "idx_api_key_provider_id"), ("tenant_model_instance", "tenantmodelinstance_api_key_provider_id"), # ← added ("tenant_model", "idx_provider_model_instance"), ] ``` The surrounding `try/except (OperationalError, ProgrammingError)` matches `1091` / `can't DROP` / `does not exist` and treats them as success, so every state is idempotent (see Test plan). ### Idempotency matrix | Database state | First entry (`idx_api_key_provider_id`) | New entry (`tenantmodelinstance_api_key_provider_id`) | | --- | --- | --- | | Fresh install (≥ #15460) — neither index exists | `1091` → swallowed | `1091` → swallowed | | Upgraded from before dc4b825 (the user's case) — auto-name present | `1091` → swallowed | **drops the index** | | Upgraded after a manual rename to `idx_*` | drops the index | `1091` → swallowed | | Re-run of `migrate_db()` after either of the above | `1091` → swallowed | `1091` → swallowed | No rollback hazard: nothing depends on this unique constraint anymore (`create_instance` dedupes by `instance_name` via `duplicate_name`, see [tenant_model_instance_service.py:27](api/db/services/tenant_model_instance_service.py#L27)). ### What this PR does NOT change - **`provider_api_service.create_provider_instance`** — its `if api_key:` gate is correct *for the post-migration world*: multiple Ollama instances with empty keys under one provider are legitimate, so we shouldn't tighten the app-layer check. - **`TenantModelInstance` Peewee model** — the `indexes` tuple was already removed in #15460. New databases never get the constraint in the first place. - **The `except → get_error_data_result` → HTTP 200 pattern at `provider_api.py:354`** — that's a project-wide convention; changing one route to HTTP 500 would be inconsistent and out of scope. ## Test plan - [ ] **Reproducer (pre-fix):** on a database originally created before #15460, configure an Ollama provider with an empty `api_key`, then try to create a *second* instance under the same provider — confirm the `Duplicate entry … 'tenantmodelinstance_api_key_provider_id'` error in the server log. - [ ] **Verify the index is present pre-restart:** `SHOW INDEX FROM tenant_model_instance WHERE Key_name = 'tenantmodelinstance_api_key_provider_id';` — non-empty result. - [ ] **Restart with the fix applied:** server starts cleanly, `migrate_db()` runs, no `Failed to drop index` in critical logs. - [ ] **Verify the index is gone post-restart:** same `SHOW INDEX` query — empty result. - [ ] **Re-run the reproducer:** two Ollama instances under the same provider, both `api_key=""`, both succeed. - [ ] **Restart a second time** — no new errors; the matching `1091` swallow keeps the migration idempotent. - [ ] **Fresh install smoke test:** drop the DB volume, start clean — no `1091` noise (the new index never existed), no functional regression. ## Files changed - [api/db/db_models.py](api/db/db_models.py) — extend the legacy-index drop list with `tenantmodelinstance_api_key_provider_id`; refactor the inline list to a named `legacy_indexes` local with a comment pointing at #15460 and #15699. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [ ] New Feature (non-breaking change which adds functionality) - [ ] Documentation Update - [ ] Refactoring - [ ] Performance Improvement - [ ] Other (please describe): Co-authored-by: Wang Qi <[email protected]>
… (#15699) (#15879) ## Summary Fixes #15699. User upgrades to v0.25.6 against an existing MySQL database, tries to add an Ollama provider instance, and gets: ``` MySQL IntegrityError: Duplicate entry 'dbaafbfe608a11f1a5516d6066988224' for key 'tenant_model_instance.tenantmodelinstance_api_key_provider_id' ``` The route at [api/apps/restful_apis/provider_api.py:354](api/apps/restful_apis/provider_api.py#L354) catches it and returns `get_error_data_result(message="Internal server error")` — which by RAGFlow's convention is HTTP 200 with an error `code` on the body — hence the reporter's "200 status code but the database errored" complaint. ### Root cause The provider-instance refactor in [PR #15460](infiniflow/ragflow#15460) dropped the unique-compound-index tuple from `TenantModelInstance`: ```python # Removed in #15460 class Meta: db_table = "tenant_model_instance" indexes = ( (("api_key", "provider_id"), True), # unique ) ``` and added a one-shot drop in `migrate_db()` for existing databases. But the drop targets the wrong index name: ```python # Before this PR — wrong name for table_name, index_name in [ ("tenant_model_instance", "idx_api_key_provider_id"), # ← doesn't exist ("tenant_model", "idx_provider_model_instance"), ]: ``` Peewee's auto-derived index name is `<lowercase classname>_<col1>_<col2>` → **`tenantmodelinstance_api_key_provider_id`**, which matches the user's error verbatim. The drop raises `OperationalError: 1091 (HY000): Can't DROP …`, the surrounding `except` clause at [db_models.py:1736](api/db/db_models.py#L1736) swallows it as expected-on-fresh-installs, and the legacy unique index lives on indefinitely. ### Why Ollama hits it specifically Ollama doesn't require an API key. The form posts `api_key: ""`. The app-layer dedupe at [provider_api_service.py:288-292](api/apps/services/provider_api_service.py#L288-L292): ```python api_key_str = "" if api_key: # ← skipped for "" ... same_key_instance = TenantModelInstanceService.get_by_provider_id_and_api_key(...) if same_key_instance: return False, f"Already exist instance: ... with api_key {api_key}" ``` falls through for empty keys. Control reaches `TenantModelInstanceService.create_instance(..., api_key="")` which inserts a row whose `(api_key, provider_id) = ("", <provider_uuid>)` collides with any prior Ollama row that already shipped that same pair → the still-present unique index throws. (`dbaafbfe608a11f1a5516d6066988224` in the user's error is the duplicated `provider_id` UUID, paired with the empty `api_key`.) ### Fix Add the Peewee auto-name alongside the existing `idx_*` entry so the migration finally drops the obsolete index on next restart: ```python legacy_indexes = [ ("tenant_model_instance", "idx_api_key_provider_id"), ("tenant_model_instance", "tenantmodelinstance_api_key_provider_id"), # ← added ("tenant_model", "idx_provider_model_instance"), ] ``` The surrounding `try/except (OperationalError, ProgrammingError)` matches `1091` / `can't DROP` / `does not exist` and treats them as success, so every state is idempotent (see Test plan). ### Idempotency matrix | Database state | First entry (`idx_api_key_provider_id`) | New entry (`tenantmodelinstance_api_key_provider_id`) | | --- | --- | --- | | Fresh install (≥ #15460) — neither index exists | `1091` → swallowed | `1091` → swallowed | | Upgraded from before dc4b825 (the user's case) — auto-name present | `1091` → swallowed | **drops the index** | | Upgraded after a manual rename to `idx_*` | drops the index | `1091` → swallowed | | Re-run of `migrate_db()` after either of the above | `1091` → swallowed | `1091` → swallowed | No rollback hazard: nothing depends on this unique constraint anymore (`create_instance` dedupes by `instance_name` via `duplicate_name`, see [tenant_model_instance_service.py:27](api/db/services/tenant_model_instance_service.py#L27)). ### What this PR does NOT change - **`provider_api_service.create_provider_instance`** — its `if api_key:` gate is correct *for the post-migration world*: multiple Ollama instances with empty keys under one provider are legitimate, so we shouldn't tighten the app-layer check. - **`TenantModelInstance` Peewee model** — the `indexes` tuple was already removed in #15460. New databases never get the constraint in the first place. - **The `except → get_error_data_result` → HTTP 200 pattern at `provider_api.py:354`** — that's a project-wide convention; changing one route to HTTP 500 would be inconsistent and out of scope. ## Test plan - [ ] **Reproducer (pre-fix):** on a database originally created before #15460, configure an Ollama provider with an empty `api_key`, then try to create a *second* instance under the same provider — confirm the `Duplicate entry … 'tenantmodelinstance_api_key_provider_id'` error in the server log. - [ ] **Verify the index is present pre-restart:** `SHOW INDEX FROM tenant_model_instance WHERE Key_name = 'tenantmodelinstance_api_key_provider_id';` — non-empty result. - [ ] **Restart with the fix applied:** server starts cleanly, `migrate_db()` runs, no `Failed to drop index` in critical logs. - [ ] **Verify the index is gone post-restart:** same `SHOW INDEX` query — empty result. - [ ] **Re-run the reproducer:** two Ollama instances under the same provider, both `api_key=""`, both succeed. - [ ] **Restart a second time** — no new errors; the matching `1091` swallow keeps the migration idempotent. - [ ] **Fresh install smoke test:** drop the DB volume, start clean — no `1091` noise (the new index never existed), no functional regression. ## Files changed - [api/db/db_models.py](api/db/db_models.py) — extend the legacy-index drop list with `tenantmodelinstance_api_key_provider_id`; refactor the inline list to a named `legacy_indexes` local with a comment pointing at #15460 and #15699. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [ ] New Feature (non-breaking change which adds functionality) - [ ] Documentation Update - [ ] Refactoring - [ ] Performance Improvement - [ ] Other (please describe): Co-authored-by: Wang Qi <[email protected]>
… the legacy unique index before widening Per the maintainer review of infiniflow#22424: - The api_key column is declared varchar(4096) instead of TEXT, so it keeps a bounded maximum while long provider keys (IONOS exceeds 1,700 chars) still fit. The pre-backfill widening spec targets the same shape. - The legacy composite unique index idx_api_key_provider_id (provider_id, api_key) — declared by the entity's uniqueIndex tags in the releases between infiniflow#14423 and infiniflow#15460 and dropped again since — is removed before any widening: MODIFY COLUMN past the legacy varchar(512) makes MySQL rebuild the index, and the widened utf8mb4 key exceeds the 3072-byte InnoDB key length limit, so the ALTER and with it the whole upgrade would fail while the index is in place. The step reuses dropIndexIfExists and runs in RunMigrations ahead of modifyColumnTypes and AutoMigrate. Dao tests pin the bounded varchar(4096) declaration through the real mysql dialector, the widening ALTER and its convergence, the index drop with its missing-index and missing-table guards.
… the legacy unique index before widening Per the maintainer review of infiniflow#22424: - The api_key column is declared varchar(4096) instead of TEXT, so it keeps a bounded maximum while long provider keys (IONOS exceeds 1,700 chars) still fit. The pre-backfill widening spec targets the same shape. - The legacy composite unique index idx_api_key_provider_id (provider_id, api_key) — declared by the entity's uniqueIndex tags in the releases between infiniflow#14423 and infiniflow#15460 and dropped again since — is removed before any widening: MODIFY COLUMN past the legacy varchar(512) makes MySQL rebuild the index, and the widened utf8mb4 key exceeds the 3072-byte InnoDB key length limit, so the ALTER and with it the whole upgrade would fail while the index is in place. The step reuses dropIndexIfExists and runs in RunMigrations ahead of modifyColumnTypes and AutoMigrate. Dao tests pin the bounded varchar(4096) declaration through the real mysql dialector, the widening ALTER and its convergence, the index drop with its missing-index and missing-table guards.
What problem does this PR solve?
Fix:
_in model_name.is_toolsfrom llm_factories.jsonType of change