Skip to content

fix(db): drop Peewee-auto-named unique index on tenant_model_instance (#15699) - #15879

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
Rene0422:fix/drop-legacy-tenant-model-instance-unique-index-15699
Jun 11, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
Rene0422:fix/drop-legacy-tenant-model-instance-unique-index-15699

Conversation

@Rene0422

@Rene0422 Rene0422 commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

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 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 dropped the unique-compound-index tuple from TenantModelInstance:

# 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:

# 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 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_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:

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

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 Fix: model-provider bugs #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 Fix: model-provider bugs #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

Type of change

  • 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):

@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 9, 2026
@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 02058525-eea1-4768-8da4-64fcfb080747

📥 Commits

Reviewing files that changed from the base of the PR and between 87b8062 and b2d7101.

📒 Files selected for processing (1)
  • api/db/db_models.py

📝 Walkthrough

Walkthrough

This PR updates the database migration to remove an additional legacy compound unique index that causes duplicate key constraint violations when creating new provider instances. The migration now drops the auto-named tenantmodelinstance_api_key_provider_id index alongside previously handled index variants.

Changes

Database Migration Cleanup

Layer / File(s) Summary
Legacy index removal in migrate_db
api/db/db_models.py
migrate_db() extends legacy index cleanup to drop the tenantmodelinstance_api_key_provider_id compound unique index alongside previously handled index names, catching and ignoring drop errors before continuing to subsequent migration steps.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

🐰 A legacy index caused duplicate woes,
So we extend the cleanup—off it goes!
Drop and catch, then migrate with grace,
Fresh constraints find their rightful place. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed Title clearly and specifically identifies the fix: dropping a Peewee-auto-named unique index on tenant_model_instance to resolve issue #15699.
Description check ✅ Passed Description is comprehensive, well-structured, includes bug analysis, fix explanation, idempotency matrix, test plan, and properly fills the template's Type of change section.
Linked Issues check ✅ Passed PR fully addresses issue #15699: modifies api/db/db_models.py to add the Peewee auto-named index to the legacy drop list, ensuring the migration removes the obsolete constraint that blocked Ollama instance creation.
Out of Scope Changes check ✅ Passed All changes are in-scope: only api/db/db_models.py is modified to extend the legacy-index drop list and refactor into a named local, directly addressing the linked issue without unrelated alterations.

✏️ 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.

@wangq8 wangq8 added the ci Continue Integration label Jun 11, 2026
@codecov

codecov Bot commented Jun 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (a1dc2da) to head (0533479).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15879   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@wangq8
wangq8 merged commit b978e26 into infiniflow:main Jun 11, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: he ragfow-v0.25.6 version encounters errors when configuring the local LLM and embedding models pulled by ollama

2 participants