Repository navigation
Feat: mark mysql migrations as applied - #15504
Conversation
📝 WalkthroughWalkthroughThe 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. ChangesIdempotent database migrations with startup wiring
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 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: 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 winRemove the trailing comma from the
tenant_modelDDL.The
CREATE TABLEstatement ends withINDEX idx_instance_id (instance_id),before), which MySQL rejects. With this PR wiring thetenant_modelstage 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
📒 Files selected for processing (2)
docker/launch_backend_service.shtools/scripts/mysql_migration.py
| 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 |
There was a problem hiding this comment.
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.
| 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, | ||
| ) |
There was a problem hiding this comment.
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
mark mysql migrations as applied
Type of change