Skip to content

Refa: refine mysql migration version workflow - #15549

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
buua436:b059
Jun 3, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
buua436:b059

Conversation

@buua436

@buua436 buua436 commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

refine mysql migration version workflow

Type of change

  • Refactoring

@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors MySQL migration versioning from per-stage markers to a centralized database version system. Four separate migration calls are consolidated into single invocations, and version gating prevents redundant migration runs when the database is already current.

Changes

Database Version Gating Refactor

Layer / File(s) Summary
Version gating infrastructure
tools/scripts/mysql_migration.py
Adds packaging.version imports, defines MIGRATION_DB_VERSION_MARKER key in system_settings, and introduces get_database_version(), set_database_version(), parse_migration_version(), and should_skip_migration() functions in MigrationDatabase to enable centralized version tracking and threshold comparison.
Remove per-stage version markers
tools/scripts/mysql_migration.py
Removes migration_version and migration_marker_prefix class attributes from MigrationStage, deletes is_migration_version_applied() and mark_migration_version_applied() methods, and strips migration_version = "1" from TenantModelProviderStage, TenantModelInstanceStage, TenantModelStage, and ModelIdConfigStage.
Refactored run_migration orchestration
tools/scripts/mysql_migration.py
Updates run_migration() signature with database_version and mark_database_version_on_success parameters. Adds logic to read current DB version, compare against target, and skip all stages when target is already satisfied. Reworks stage execution loop to remove per-stage version checks and conditionally mark the database version after successful completion.
CLI mode and argument handling
tools/scripts/mysql_migration.py
Adds CLI examples for --check-database-version and --mark-database-version modes. Introduces --database-version and --mark-database-version-on-success argument definitions. Removes early stage parsing validation so non-stage commands can run independently. Implements mode validation with mutual exclusivity checks and defers --stages parsing until after mode dispatch.
Docker script consolidation
docker/entrypoint.sh, docker/launch_backend_service.sh
Consolidates four separate mysql_migration.py invocations (one per stage) into single calls with multiple --stages values. Adds --database-version "v0.26.0" and --mark-database-version-on-success flags to both scripts.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#15495: Modifies MySQL migration startup to include the model_id_config stage; this PR consolidates that stage into unified multi-stage calls with database-version gating.
  • infiniflow/ragflow#13976: Adds TenantModelInstanceStage and TenantModelStage to migration stages; this PR refactors their version-marking behavior as part of the move to centralized database versioning.
  • infiniflow/ragflow#15504: Also modifies tools/scripts/mysql_migration.py migration gating for the same four stages by changing how run_migration() gates migrations via version markers.

Suggested labels

size:XL

Suggested reviewers

  • Lynn-Inf

Poem

🐰 Four migrations walked into a bar,
Said "let's sync as one, less goes far!"
Version gates now bloom,
No duplicate doom—
One marker to rule them all, by far! ⭐

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (1 warning, 2 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.53% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Refa: refine mysql migration version workflow' is partially related to the changeset but contains a typo ('Refa' instead of a meaningful prefix) and is somewhat vague about the specific refactoring. Consider clarifying the title by removing the unclear 'Refa' prefix and being more specific about the refactoring, e.g., 'Centralize MySQL migration version tracking with database-level markers'.
Description check ❓ Inconclusive The PR description includes the required 'What problem does this PR solve?' section and 'Type of change' with Refactoring selected, but the problem statement is merely a restatement of the title without substantive context or explanation. Expand the problem statement to explain why the migration version workflow needs refinement and what benefits this refactoring provides to the codebase.
✅ Passed checks (2 passed)
Check name Status Explanation
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.

@buua436 buua436 assigned buua436 and unassigned buua436 Jun 3, 2026
@buua436 buua436 added the ci Continue Integration label Jun 3, 2026
@buua436
buua436 marked this pull request as ready for review June 3, 2026 02:29
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code labels Jun 3, 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.

Caution

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

⚠️ Outside diff range comments (4)
tools/scripts/mysql_migration.py (4)

582-604: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

SQL injection risk: use parameterized queries instead of string interpolation.

This stage uses manual quote escaping (replace("'", "''")), while TenantModelProviderStage correctly uses parameterized queries with placeholders. Manual escaping is fragile and doesn't handle all edge cases (e.g., backslash escapes in certain MySQL modes).

Refactor to use parameterized queries consistent with TenantModelProviderStage (lines 414-437).

🔒 Proposed fix using parameterized queries
         # Insert records in batches
         batch_size = 100
         for i in range(0, len(records), batch_size):
             batch = records[i:i + batch_size]
-            values = []
+            placeholders = []
+            params = []
             for tenant_id, llm_factory, api_key, status, provider_id in batch:
                 record_id = self.generate_uuid()
                 instance_name = "default"
-                api_key_escaped = api_key.replace("'", "''") if api_key else ""
                 status_val = "active" if status in ["1", "active", "enable"] else "inactive"
-                values.append(f"('{record_id}', '{instance_name}', '{provider_id}', "
-                            f"'{api_key_escaped}', '{status_val}', "
-                            f"{current_ts * 1000}, FROM_UNIXTIME({current_ts}), "
-                            f"{current_ts * 1000}, FROM_UNIXTIME({current_ts}))")
-
-            insert_sql = f"""
+                placeholders.append("(%s, %s, %s, %s, %s, %s, FROM_UNIXTIME(%s), %s, FROM_UNIXTIME(%s))")
+                params.extend([
+                    record_id,
+                    instance_name,
+                    provider_id,
+                    api_key or "",
+                    status_val,
+                    current_ts * 1000,
+                    current_ts,
+                    current_ts * 1000,
+                    current_ts,
+                ])
+            insert_sql = """
                 INSERT INTO tenant_model_instance 
                 (id, instance_name, provider_id, api_key, status, create_time, create_date, update_time, update_date)
-                VALUES {', '.join(values)}
-            """
-            self.db.execute_sql(insert_sql)
+                VALUES """ + ', '.join(placeholders)
+            self.db.execute_sql(insert_sql, params)
             rows_inserted += len(batch)
             logger.info(f"Inserted batch {i // batch_size + 1}: {len(batch)} records")
🤖 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 582 - 604, The batch INSERT
builds SQL via string interpolation (in the for loop that calls
self.generate_uuid() and constructs values) which risks SQL injection; refactor
the insertion in the loop that populates values for tenant_model_instance to use
parameterized queries like TenantModelProviderStage does: build a single INSERT
statement with parameter placeholders for each row, accumulate a flat params
list (id, instance_name, provider_id, api_key, status, create_time, create_date,
update_time, update_date) for every record in the batch, and call
self.db.execute_sql(insert_sql, params) (or the equivalent paramized execute
method) instead of formatting values into the SQL string and manually escaping
quotes.

795-818: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

SQL injection risk: same issue as TenantModelInstanceStage.

Apply parameterized queries here as well.

🔒 Proposed fix using parameterized queries
         # Insert records in batches
         batch_size = 100
         for i in range(0, len(records), batch_size):
             batch = records[i:i + batch_size]
-            values = []
+            placeholders = []
+            params = []
             for source_id, llm_name, provider_id, instance_id, model_type, status in batch:
                 record_id = self.generate_uuid()
-                model_name_escaped = llm_name.replace("'", "''") if llm_name else ""
-                model_type_escaped = model_type.replace("'", "''") if model_type else ""
                 status_val = "active" if status in ["1", "active", "enable"] else "inactive"
-                values.append(f"('{record_id}', '{model_name_escaped}', '{provider_id}', "
-                            f"'{instance_id}', '{model_type_escaped}', '{status_val}', "
-                            f"{current_ts * 1000}, FROM_UNIXTIME({current_ts}), "
-                            f"{current_ts * 1000}, FROM_UNIXTIME({current_ts}))")
-
-            insert_sql = f"""
+                placeholders.append("(%s, %s, %s, %s, %s, %s, %s, FROM_UNIXTIME(%s), %s, FROM_UNIXTIME(%s))")
+                params.extend([
+                    record_id,
+                    llm_name or "",
+                    provider_id,
+                    instance_id,
+                    model_type or "",
+                    status_val,
+                    current_ts * 1000,
+                    current_ts,
+                    current_ts * 1000,
+                    current_ts,
+                ])
+            insert_sql = """
                 INSERT INTO tenant_model 
                 (id, model_name, provider_id, instance_id, model_type, status, 
                  create_time, create_date, update_time, update_date)
-                VALUES {', '.join(values)}
-            """
-            self.db.execute_sql(insert_sql)
+                VALUES """ + ', '.join(placeholders)
+            self.db.execute_sql(insert_sql, params)
             rows_inserted += len(batch)
             logger.info(f"Inserted batch {i // batch_size + 1}: {len(batch)} records")
🤖 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 795 - 818, The batch INSERT
currently builds SQL via string interpolation (in the block that generates
values using self.generate_uuid(), model_name_escaped, model_type_escaped and
then calls self.db.execute_sql(insert_sql)), which is vulnerable to SQL
injection; change this to use parameterized queries: build the INSERT with
placeholders for each column (id, model_name, provider_id, instance_id,
model_type, status, create_time, create_date, update_time, update_date) and pass
a list of parameter tuples for the batch to a safe execute_many/execute method
on self.db instead of concatenating values into the SQL string, and remove
manual quote-escaping (model_name_escaped/model_type_escaped) so values are
bound as parameters.

822-841: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

SQL syntax error: trailing comma before closing parenthesis.

Line 838 has a trailing comma after the last index definition, which will cause a MySQL syntax error when creating the table.

🐛 Proposed fix
             INDEX idx_instance_id (instance_id),
-        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
+            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 822 - 841, The CREATE TABLE in
create_target_table defines tenant_model with a trailing comma after the last
index definition which causes a MySQL syntax error; open the create_sql string
in create_target_table and remove the extra comma after "INDEX idx_instance_id
(instance_id)," so the closing parenthesis follows the last definition directly,
then keep the rest of the SQL intact and rerun the migration.

1144-1189: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Version marker may be set even when stages fail due to missing dependencies.

all_stages_completed is only set to False for unknown stage names (line 1154). However, stages like TenantModelInstanceStage and TenantModelStage return (0, []) when dependency tables are missing (e.g., lines 532-536), which doesn't mark the run as incomplete.

This could result in the database version being marked as migrated even though no actual migration occurred due to missing prerequisites.

Consider tracking whether each stage's execute() returned successfully with expected results, or whether it returned early due to a precondition failure.

🤖 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 1144 - 1189, The code only
flips all_stages_completed for unknown stages but not when a stage ran but
effectively did nothing due to missing dependencies; update the migration loop
that calls stage.check() / stage.execute() (and the MIGRATION_STAGES entries
like TenantModelInstanceStage and TenantModelStage) so you can detect and mark
failed/skipped executions: either (preferred) change execute() to return a third
success flag (rows, tables, success) and set all_stages_completed = False when
success is False, or (if you cannot change signatures) treat a post-check
execute() result of rows == 0 and tables == [] (when stage.check() was True and
not create_table_only) as an incomplete stage and set all_stages_completed =
False before accumulating stats; ensure this logic is applied before calling
db.set_database_version and references stage.check(), stage.execute(),
all_stages_completed, mark_database_version_on_success, and
db.set_database_version.
🤖 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 `@tools/scripts/mysql_migration.py`:
- Around line 582-604: The batch INSERT builds SQL via string interpolation (in
the for loop that calls self.generate_uuid() and constructs values) which risks
SQL injection; refactor the insertion in the loop that populates values for
tenant_model_instance to use parameterized queries like TenantModelProviderStage
does: build a single INSERT statement with parameter placeholders for each row,
accumulate a flat params list (id, instance_name, provider_id, api_key, status,
create_time, create_date, update_time, update_date) for every record in the
batch, and call self.db.execute_sql(insert_sql, params) (or the equivalent
paramized execute method) instead of formatting values into the SQL string and
manually escaping quotes.
- Around line 795-818: The batch INSERT currently builds SQL via string
interpolation (in the block that generates values using self.generate_uuid(),
model_name_escaped, model_type_escaped and then calls
self.db.execute_sql(insert_sql)), which is vulnerable to SQL injection; change
this to use parameterized queries: build the INSERT with placeholders for each
column (id, model_name, provider_id, instance_id, model_type, status,
create_time, create_date, update_time, update_date) and pass a list of parameter
tuples for the batch to a safe execute_many/execute method on self.db instead of
concatenating values into the SQL string, and remove manual quote-escaping
(model_name_escaped/model_type_escaped) so values are bound as parameters.
- Around line 822-841: The CREATE TABLE in create_target_table defines
tenant_model with a trailing comma after the last index definition which causes
a MySQL syntax error; open the create_sql string in create_target_table and
remove the extra comma after "INDEX idx_instance_id (instance_id)," so the
closing parenthesis follows the last definition directly, then keep the rest of
the SQL intact and rerun the migration.
- Around line 1144-1189: The code only flips all_stages_completed for unknown
stages but not when a stage ran but effectively did nothing due to missing
dependencies; update the migration loop that calls stage.check() /
stage.execute() (and the MIGRATION_STAGES entries like TenantModelInstanceStage
and TenantModelStage) so you can detect and mark failed/skipped executions:
either (preferred) change execute() to return a third success flag (rows,
tables, success) and set all_stages_completed = False when success is False, or
(if you cannot change signatures) treat a post-check execute() result of rows ==
0 and tables == [] (when stage.check() was True and not create_table_only) as an
incomplete stage and set all_stages_completed = False before accumulating stats;
ensure this logic is applied before calling db.set_database_version and
references stage.check(), stage.execute(), all_stages_completed,
mark_database_version_on_success, and db.set_database_version.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8659c93f-c50f-40af-aa3c-9719a5005944

📥 Commits

Reviewing files that changed from the base of the PR and between 583daf4 and 346606b.

📒 Files selected for processing (3)
  • docker/entrypoint.sh
  • docker/launch_backend_service.sh
  • tools/scripts/mysql_migration.py

@codecov

codecov Bot commented Jun 3, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15549   +/-   ##
=======================================
  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.

@wangq8
wangq8 requested a review from Lynn-Inf June 3, 2026 03:34

@Lynn-Inf Lynn-Inf 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.

LGTM

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

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants