Skip to content

Fix: model-provider bugs - #15460

Merged
wangq8 merged 14 commits into
infiniflow:mainfrom
Lynn-Inf:fix/model-provider
Jun 2, 2026
Merged

wangq8 merged 14 commits into
infiniflow:mainfrom
Lynn-Inf:fix/model-provider

Conversation

@Lynn-Inf

@Lynn-Inf Lynn-Inf commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fix:

  • Use @ to avoid split by _ in model_name.
  • Verify api_key when add instance.
  • Pop api_key in list intances response.
  • Remove useless index.
  • Sort providers, instances and models by name.
  • Get is_tools from llm_factories.json

Type of change

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

@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. labels Jun 1, 2026
@Lynn-Inf Lynn-Inf added ci Continue Integration and removed 🌈 python Pull requests that update Python code 🐖api The modified files are located under directory 'api/apps/sdk' labels Jun 1, 2026
@Lynn-Inf
Lynn-Inf marked this pull request as draft June 1, 2026 02:18
@coderabbitai

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

Adds 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 @. Removes ORM/db unique indexes and adds migration logic to drop those indexes safely.

Changes

Provider verification and instance lifecycle

Layer / File(s) Summary
REST endpoints and request plumbing
api/apps/restful_apis/provider_api.py
create_provider_instance reads verify and awaits the service; new POST /providers/<provider_name>/connection endpoint calls provider_api_service.verify_api_key with api_key and optional base_url.
Service: async create + verify helper
api/apps/services/provider_api_service.py
create_provider_instance made async and gains verify: bool; adds verify_api_key that exercises Embedding/Chat/Rerank models with timeouts and checks stream/chunk output; instance deletion now uses get_all_by_provider_id; listings omit api_key.

Model key format update

Layer / File(s) Summary
Model key format standardization
api/apps/services/models_api_service.py
Composite model keys now use @ (e.g., provider@instance@model) for record maps, factory-derived keys, and parsing logic.

DB index removal and migration updates

Layer / File(s) Summary
Model Meta and migration logic
api/db/db_models.py
Remove Meta.indexes entry from TenantModelInstance and add migration logic that attempts to drop idx_api_key_provider_id and idx_provider_model_instance, suppressing expected missing/already-exists errors.
GORM tags and migration DDL
internal/entity/tenant_model_instance.go, tools/scripts/mysql_migration.py
Remove uniqueIndex:idx_api_key_provider_id GORM tags from ProviderID/APIKey; change MySQL migration DDL to convert previously-unique indexes into non-unique INDEXes and add helpers to include status='1' for designated empty-LLM factories.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

🐖api

Poem

I’m a rabbit checking keys with care,
I hop through streams, no chunk to spare,
I trade underscores for a tidy @,
and gently flatten indexes that sat. 🐇✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Fix: model-provider bugs' is vague and generic, using non-descriptive terms without conveying specific information about the changes. Make the title more specific by highlighting a primary change, e.g., 'Fix: change model delimiter and verify API keys' or 'Fix: model provider instance management issues'.
Description check ❓ Inconclusive PR description covers main issues but lacks detailed context and explanation for reviewers to understand the rationale behind changes. Expand description to explain why @ delimiter prevents model_name splitting issues, why api_key verification is needed, and the business impact of removing the useless index.
✅ Passed checks (3 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 84.21% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Lynn-Inf
Lynn-Inf marked this pull request as ready for review June 1, 2026 02:18

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/apps/services/models_api_service.py`:
- 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

📥 Commits

Reviewing files that changed from the base of the PR and between cd18cfa and 8487883.

📒 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("@")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
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.

@Lynn-Inf Lynn-Inf changed the title Fix: split by @ Fix: model-provider bugs Jun 1, 2026
@codecov

codecov Bot commented Jun 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (12579db) to head (34b5db5).
⚠️ Report is 24 commits behind head on main.

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

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Jun 1, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

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

316-316: ⚡ Quick win

Avoid using assert for runtime validation.

assert statements are stripped when Python runs with -O (optimize) flag, making these checks no-ops in production. Use explicit if checks 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 model

Also 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 value

Superfluous "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

📥 Commits

Reviewing files that changed from the base of the PR and between 8487883 and 98e1b69.

📒 Files selected for processing (5)
  • api/apps/restful_apis/provider_api.py
  • api/apps/services/provider_api_service.py
  • api/db/db_models.py
  • internal/entity/tenant_model_instance.go
  • tools/scripts/mysql_migration.py

Comment on lines +319 to +327
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Missing await and incorrect dict access will cause runtime errors.

  1. Line 319: Missing await before asyncio.wait_for() - the coroutine won't execute and tuple unpacking will fail.
  2. Line 327: llm.llm_name uses dot notation on a dict - should be llm["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).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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 win

Remove the trailing comma from the tenant_model DDL.

create_target_table() now emits INDEX idx_instance_id (instance_id), immediately before ), which is invalid MySQL syntax. Any run that needs to create tenant_model will 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 win

Log the new empty-factory migration path and fallback behavior.

This branch changes which tenant_llm rows are eligible for migration, but there is no log showing which factories were loaded or whether the code fell back to tl.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

📥 Commits

Reviewing files that changed from the base of the PR and between a25349a and 6488906.

📒 Files selected for processing (1)
  • tools/scripts/mysql_migration.py

Comment thread tools/scripts/mysql_migration.py Resolved
@wangq8
wangq8 merged commit 3bc5ed2 into infiniflow:main Jun 2, 2026
1 check passed
This was referenced Jun 8, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Jun 10, 2026
1 task done
wangq8 added a commit that referenced this pull request Jun 11, 2026
…#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]>
geversite pushed a commit to geversite/ragflow that referenced this pull request Jul 3, 2026
… (#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]>
RerankerGuo added a commit to RerankerGuo/ragflow that referenced this pull request Nov 18, 2026
… 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.
RerankerGuo added a commit to RerankerGuo/ragflow that referenced this pull request Nov 23, 2026
… 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants