Skip to content

Feat: mark mysql migrations as applied - #15504

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
buua436:b058
Jun 2, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
buua436:b058

Conversation

@buua436

@buua436 buua436 commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

mark mysql migrations as applied

Type of change

  • New Feature (non-breaking change which adds functionality)

@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds idempotent database migrations to the backend startup process. The shell script now calls database initialization and migration functions before launching services. The migration framework gains system_settings-backed markers to track version completion per stage, preventing duplicate execution on repeated runs.

Changes

Idempotent database migrations with startup wiring

Layer / File(s) Summary
Backend startup initialization and migration
docker/launch_backend_service.sh
Adds ensure_db_init to initialize schema tables and run_mysql_migrations to run migration stages; both are called during startup before task executors and server launch.
Migration marker persistence in system_settings
tools/scripts/mysql_migration.py
MigrationDatabase gains get_system_setting_value and upsert_system_setting methods to store and retrieve migration version markers in the database.
Migration stage marker contract and infrastructure
tools/scripts/mysql_migration.py
MigrationStage introduces migration_version class field, marker helper methods (migration_marker_name, is_migration_version_applied, mark_migration_version_applied), and a noop-completion flag for stages with no data to migrate.
Idempotent migration stages with version markers
tools/scripts/mysql_migration.py
TenantModelProviderStage, TenantModelInstanceStage, TenantModelStage, and ModelIdConfigStage each declare migration_version = "1" and call mark_noop_completes_migration() when check() finds no work.
Migration runner with marker-based idempotency
tools/scripts/mysql_migration.py
The run_migration() function skips stages whose markers indicate version completion, marks noop stages as applied when check() returns false, and persists completion markers after successful execution.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A rabbit hops through migrations so neat,
With markers to track every version complete.
No doubling or skipping—just once, clean and right,
The database blooms as the services take flight! 🐰✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The PR description follows the template structure but lacks sufficient detail about the problem being solved and implementation specifics. Expand the 'What problem does this PR solve?' section with concrete context: why marking migrations as applied is necessary, what issues this prevents (e.g., idempotency, re-running stages), and how the solution works at a high level.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main change: introducing a mechanism to mark MySQL migrations as applied, which is the core feature across both modified files.
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 added the ci Continue Integration label Jun 2, 2026
@buua436 buua436 changed the title mark mysql migrations as applied Feat: mark mysql migrations as applied Jun 2, 2026
@buua436
buua436 marked this pull request as ready for review June 2, 2026 05:57
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 2, 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: 2

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)

839-855: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Remove the trailing comma from the tenant_model DDL.

The CREATE TABLE statement ends with INDEX idx_instance_id (instance_id), before ), which MySQL rejects. With this PR wiring the tenant_model stage into startup, fresh environments will fail before the backend comes up.

Suggested 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 839 - 855, The CREATE TABLE
DDL for tenant_model contains a trailing comma after "INDEX idx_instance_id
(instance_id)," which makes MySQL reject the statement; edit the create_sql
string in mysql_migration.py (the tenant_model create_sql used by
self.db.execute_sql) to remove the comma after the index definition so the
closing parenthesis is immediately following the last column/index entry and
ensure the SQL string still ends with the ENGINE/CHARSET clause.
🤖 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 `@docker/launch_backend_service.sh`:
- Around line 123-128: The migration startup can silently use defaults when
conf/service_conf.yaml is missing or malformed because
MigrationConfig.from_config_file() swallows file/parse errors; change
MigrationConfig.from_config_file (and any helpers it calls) to raise/propagate
exceptions on missing or invalid YAML instead of returning the localhost/default
fallback, and update the migration entrypoint tools/scripts/mysql_migration.py
(the code path invoked by run_mysql_migrations) to catch failures loading the
config, log a clear error including the file path and parse error, and exit
non-zero so the container startup fails fast rather than running migrations
against the default DB.

In `@tools/scripts/mysql_migration.py`:
- Around line 293-323:
is_migration_version_applied/mark_migration_version_applied are non-atomic
across processes so two instances can both run the same migration; wrap the
entire "already applied? -> check() -> execute() ->
mark_migration_version_applied()" sequence in a DB-backed per-stage lock (e.g.
MySQL GET_LOCK/RELEASE or a helper like
self.db.acquire_advisory_lock(stage_name) if available), and after acquiring the
lock re-read the migration marker (call get_system_setting_value again) before
running check()/execute() to ensure the marker still indicates work is needed;
release the lock after mark_migration_version_applied completes (or on error) so
the check-and-set becomes atomic across startup instances.

---

Outside diff comments:
In `@tools/scripts/mysql_migration.py`:
- Around line 839-855: The CREATE TABLE DDL for tenant_model contains a trailing
comma after "INDEX idx_instance_id (instance_id)," which makes MySQL reject the
statement; edit the create_sql string in mysql_migration.py (the tenant_model
create_sql used by self.db.execute_sql) to remove the comma after the index
definition so the closing parenthesis is immediately following the last
column/index entry and ensure the SQL string still ends with the ENGINE/CHARSET
clause.
🪄 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: 76356c4f-e2e9-4c6b-b510-dee7cec58138

📥 Commits

Reviewing files that changed from the base of the PR and between 5733e06 and 43da54b.

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

Comment on lines +123 to +128
run_mysql_migrations() {
echo "Running model provider table migrations..."
"$PY" tools/scripts/mysql_migration.py --stages tenant_model_provider --config conf/service_conf.yaml --execute
"$PY" tools/scripts/mysql_migration.py --stages tenant_model_instance --config conf/service_conf.yaml --execute
"$PY" tools/scripts/mysql_migration.py --stages tenant_model --config conf/service_conf.yaml --execute
"$PY" tools/scripts/mysql_migration.py --stages model_id_config --config conf/service_conf.yaml --execute

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 | 🟠 Major | ⚡ Quick win

Fail fast when conf/service_conf.yaml cannot be loaded.

These startup calls rely on --config conf/service_conf.yaml, but MigrationConfig.from_config_file() currently swallows file/parse errors and falls back to localhost/root/rag_flow. A missing or malformed config here would run boot-time migrations against the default database instead of aborting startup.

🤖 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 `@docker/launch_backend_service.sh` around lines 123 - 128, The migration
startup can silently use defaults when conf/service_conf.yaml is missing or
malformed because MigrationConfig.from_config_file() swallows file/parse errors;
change MigrationConfig.from_config_file (and any helpers it calls) to
raise/propagate exceptions on missing or invalid YAML instead of returning the
localhost/default fallback, and update the migration entrypoint
tools/scripts/mysql_migration.py (the code path invoked by run_mysql_migrations)
to catch failures loading the config, log a clear error including the file path
and parse error, and exit non-zero so the container startup fails fast rather
than running migrations against the default DB.

Comment on lines +293 to +323
def is_migration_version_applied(self) -> bool:
if not self.migration_version:
return False

marker_name = self.migration_marker_name()
current_version = self.db.get_system_setting_value(marker_name)
if current_version == self.migration_version:
logger.info(
"Stage '%s' already applied at version %s, skipping",
self.name,
self.migration_version,
)
return True

if current_version:
logger.info(
"Stage '%s' marker version is %s, target version is %s",
self.name,
current_version,
self.migration_version,
)
return False

def mark_migration_version_applied(self):
if not self.migration_version:
return

self.db.upsert_system_setting(
self.migration_marker_name(),
self.migration_version,
)

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 | 🟠 Major | 🏗️ Heavy lift

Make the marker check/update atomic across startup instances.

is_migration_version_applied() and mark_migration_version_applied() are separated by check()/execute(), with no cross-process lock. Since launch_backend_service.sh now runs these stages on every boot, two backend instances can both observe the marker as missing, run the same backfill, and one will hit duplicate-key or partial-write failures before the marker is written.

Suggested direction

Use a per-stage MySQL advisory lock (or another DB-backed lock) around the entire already applied? -> check -> execute -> mark applied sequence, and re-read the marker after the lock is acquired.

Also applies to: 1148-1168

🤖 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 293 - 323,
is_migration_version_applied/mark_migration_version_applied are non-atomic
across processes so two instances can both run the same migration; wrap the
entire "already applied? -> check() -> execute() ->
mark_migration_version_applied()" sequence in a DB-backed per-stage lock (e.g.
MySQL GET_LOCK/RELEASE or a helper like
self.db.acquire_advisory_lock(stage_name) if available), and after acquiring the
lock re-read the migration marker (call get_system_setting_value again) before
running check()/execute() to ensure the marker still indicates work is needed;
release the lock after mark_migration_version_applied completes (or on error) so
the check-and-set becomes atomic across startup instances.

@codecov

codecov Bot commented Jun 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (33ef724) to head (43da54b).
⚠️ Report is 9 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15504   +/-   ##
=======================================
  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 merged commit 4018f02 into infiniflow:main Jun 2, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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