[PR #6729] [MERGED] fix(update): run the database migration before starting the service #6432

Closed
opened 2026-11-02 04:08:43 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/6729
Author: @mrnickson-hue
Created: 10/4/2026
Status: ✅ Merged
Merged: 10/5/2026
Merged by: @MHSanaei

Base: main ← Head: fix/6728-migration-race


📝 Commits (2)

  • 2ccf1f6 fix(update): run the database migration before starting the service
  • d5d0883 Merge branch 'main' into fix/6728-migration-race

📊 Changes

1 file changed (+5 additions, -0 deletions)

View changed files

📝 update.sh (+5 -0)

📄 Description

Summary

update.sh now runs x-ui migrate to completion before starting the service. The freshly started service and config_after_update's CLI calls therefore no longer run the schema migrations on the same database at the same time, which is the race reported in #6728.

Why

Closes #6728.

update_x-ui() ran systemctl start x-ui and then immediately config_after_update, which calls x-ui setting -show true and x-ui migrate. All three processes call InitDB(), and with it every migration, concurrently. On an upgrade that adds schema, the loser exits with an error. 3.8.5 → 3.9.0 failed with duplicate column name: exclude_from_sub, and the panel only came back because the unit has Restart=on-failure.

The fix suggested in the issue triage is not sufficient. I implemented it first: routing the three column helpers' AddColumn error through isIgnorableDuplicateColumnErr, with a red→green unit test. Then I ran it against a real 3.8.5 database. With the column race tolerated, the two processes get further and collide on the tables that are new in 3.9.0:

Database initialization failed: table `node_pending_resets` already exists
Database initialization failed: table `tuic_traffic_receipts` already exists

Failures went up, from 11/30 to 20/30 (table below). Concurrent InitDB() is unsafe in general (columns, tables, the inbounds rebuild), so tolerating one error class only moves the race. This PR removes the concurrency on the update path instead, and the Go change is not included.

This also brings update.sh in line with install.sh, where config_after_install already runs x-ui migrate before the first systemctl start.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Documentation
  • Tests only
  • Build / CI / tooling
  • Other

Areas affected

  • Frontend (UI / panel pages)
  • Backend (API endpoints, login, settings)
  • Xray config generation
  • Subscription (share links / Clash / JSON)
  • Statistics / traffic counters
  • Database / migrations
  • Install / upgrade script
  • Docker image
  • Multi-node (sub-nodes)
  • Telegram bot

How was this tested?

No unit test can reach a shell script's step ordering (per CLAUDE.md, the command that demonstrates it is named instead). I reproduced the update sequence against a real 3.8.5 production database copy, taken with sqlite3 .backup, with binaries built from this branch's base (815c9c57):

  • each run starts from a fresh copy of the DB;
  • XUI_DB_FOLDER and XUI_LOG_FOLDER point to a temp dir;
  • two x-ui setting -show true processes start at once, the same overlap update.sh creates;
  • a run counts as a failure when either process logs Database initialization failed, Error initializing database or Error auto migrating.
Scenario (30 runs each) Init failures Column present integrity_check
A. current update.sh order: two concurrent InitDB (control) 11 / 30 30 / 30 ok 30 / 30
B. column-helper tolerance only (the triage suggestion, not in this PR) 20 / 30 30 / 30 ok 30 / 30
C. this PR: x-ui migrate first, then the two concurrent calls 0 / 30 30 / 30 ok 30 / 30
D. this PR + the column-helper tolerance 0 / 30 30 / 30 ok 30 / 30

C and D are identical, so the Go change adds nothing once the update path is serialised.

The core of each run:

cp x-ui-3.8.5.db "$W/x-ui.db"; export XUI_DB_FOLDER="$W" XUI_LOG_FOLDER="$W/log"
"$BIN" migrate                                   # scenario C/D only
( "$BIN" setting -show true >a.out 2>&1 ) & ( "$BIN" setting -show true >b.out 2>&1 ) & wait
grep -hE "Database initialization failed|Error initializing database|Error auto migrating" a.out b.out

Also checked:

  • bash -n update.sh passes.
  • shellcheck update.sh reports 129 findings before and after, so none is new. The new path is quoted to avoid adding an SC2086.
  • The new step runs before the alpine / systemd branch, so both the OpenRC and the systemd start are covered. ${xui_folder}/x-ui is already installed at that point, since the line just above chmods its bin/config.json.
  • x-ui migrate is InitDB() + InboundService.MigrateDB(). Both are idempotent and touch only the database, not Xray, so running them while the service is stopped is safe. config_after_update still runs it again afterwards as a no-op.
  • The web updater fetches update.sh from main (panelUpdaterURL), so after merge the fix also applies to panels updating from older versions.
  • Go code is unchanged relative to main. On the branch with the Go experiment: make verify gen-check, golangci-lint (0 issues), lint, format:check and typecheck passed; go test ./... (48 packages) and go test -race ./internal/database/... passed; make build build-storybook passed.

Two things I hit locally that are pre-existing on main and unrelated to this PR:

  • make msw-worker-check fails because frontend/public/mockServiceWorker.js is still the 2.15.0 worker while 99bc68fa bumped msw to 3.0.1. CI does not run this target.
  • On a 2-vCPU host, 3 component tests time out at 5000 ms (client-bulk-calendar-renewal, client-calendar-renewal, inbound-form-modal). They time out identically on clean main.

Screenshots / recordings

N/A, no UI change.

Breaking changes

None. Updates print one extra step, Migrating database..., followed by the existing x-ui migrate output.

Checklist

  • I tested the change locally and confirmed the described behavior.
  • I added or updated tests for the new behavior (when applicable). Not applicable: shell-script ordering. The reproducing commands are above.
  • go build ./... and the test suite pass locally.
  • For frontend changes: npm run lint, npm run typecheck, and npm run build pass. No frontend changes.
  • I updated the Wiki / README / API docs if user-facing behavior changed. No user-facing change.
  • My commits follow the project's existing message style.
  • I have no unrelated changes mixed into this PR.

Open question for the maintainer. This PR closes the update path, but any other overlap of two InitDB() callers is still unsafe, for example running an x-ui setting command while the service is (re)starting. A complete fix would be a cross-process migration lock in InitDB(): an advisory file lock next to the SQLite DB and pg_advisory_lock on PostgreSQL. That is a larger, platform-specific change, so I did not include it unasked. Happy to send it as a follow-up if you want it.


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/MHSanaei/3x-ui/pull/6729 **Author:** [@mrnickson-hue](https://github.com/mrnickson-hue) **Created:** 10/4/2026 **Status:** ✅ Merged **Merged:** 10/5/2026 **Merged by:** [@MHSanaei](https://github.com/MHSanaei) **Base:** `main` ← **Head:** `fix/6728-migration-race` --- ### 📝 Commits (2) - [`2ccf1f6`](https://github.com/MHSanaei/3x-ui/commit/2ccf1f6d1188c1836ad456ba41a539db1c2363ec) fix(update): run the database migration before starting the service - [`d5d0883`](https://github.com/MHSanaei/3x-ui/commit/d5d088300d8671b13a60d4f344227b8c20c1efaa) Merge branch 'main' into fix/6728-migration-race ### 📊 Changes **1 file changed** (+5 additions, -0 deletions) <details> <summary>View changed files</summary> 📝 `update.sh` (+5 -0) </details> ### 📄 Description ## Summary `update.sh` now runs `x-ui migrate` to completion **before** starting the service. The freshly started service and `config_after_update`'s CLI calls therefore no longer run the schema migrations on the same database at the same time, which is the race reported in #6728. ## Why Closes #6728. `update_x-ui()` ran `systemctl start x-ui` and then immediately `config_after_update`, which calls `x-ui setting -show true` and `x-ui migrate`. All three processes call `InitDB()`, and with it every migration, concurrently. On an upgrade that adds schema, the loser exits with an error. 3.8.5 → 3.9.0 failed with `duplicate column name: exclude_from_sub`, and the panel only came back because the unit has `Restart=on-failure`. **The fix suggested in the issue triage is not sufficient.** I implemented it first: routing the three column helpers' `AddColumn` error through `isIgnorableDuplicateColumnErr`, with a red→green unit test. Then I ran it against a real 3.8.5 database. With the column race tolerated, the two processes get further and collide on the **tables** that are new in 3.9.0: ``` Database initialization failed: table `node_pending_resets` already exists Database initialization failed: table `tuic_traffic_receipts` already exists ``` Failures went *up*, from 11/30 to 20/30 (table below). Concurrent `InitDB()` is unsafe in general (columns, tables, the inbounds rebuild), so tolerating one error class only moves the race. This PR removes the concurrency on the update path instead, and the Go change is not included. This also brings `update.sh` in line with `install.sh`, where `config_after_install` already runs `x-ui migrate` before the first `systemctl start`. ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactoring (no behavior change) - [ ] Documentation - [ ] Tests only - [ ] Build / CI / tooling - [ ] Other ## Areas affected - [ ] Frontend (UI / panel pages) - [ ] Backend (API endpoints, login, settings) - [ ] Xray config generation - [ ] Subscription (share links / Clash / JSON) - [ ] Statistics / traffic counters - [ ] Database / migrations - [x] Install / upgrade script - [ ] Docker image - [ ] Multi-node (sub-nodes) - [ ] Telegram bot ## How was this tested? No unit test can reach a shell script's step ordering (per CLAUDE.md, the command that demonstrates it is named instead). I reproduced the update sequence against a **real 3.8.5 production database copy**, taken with `sqlite3 .backup`, with binaries built from this branch's base (`815c9c57`): - each run starts from a fresh copy of the DB; - `XUI_DB_FOLDER` and `XUI_LOG_FOLDER` point to a temp dir; - two `x-ui setting -show true` processes start at once, the same overlap `update.sh` creates; - a run counts as a failure when either process logs `Database initialization failed`, `Error initializing database` or `Error auto migrating`. | Scenario (30 runs each) | Init failures | Column present | `integrity_check` | |---|---|---|---| | A. current `update.sh` order: two concurrent `InitDB` (control) | **11 / 30** | 30 / 30 | ok 30 / 30 | | B. column-helper tolerance only (the triage suggestion, not in this PR) | **20 / 30** | 30 / 30 | ok 30 / 30 | | C. **this PR**: `x-ui migrate` first, then the two concurrent calls | **0 / 30** | 30 / 30 | ok 30 / 30 | | D. this PR + the column-helper tolerance | 0 / 30 | 30 / 30 | ok 30 / 30 | C and D are identical, so the Go change adds nothing once the update path is serialised. The core of each run: ```shell cp x-ui-3.8.5.db "$W/x-ui.db"; export XUI_DB_FOLDER="$W" XUI_LOG_FOLDER="$W/log" "$BIN" migrate # scenario C/D only ( "$BIN" setting -show true >a.out 2>&1 ) & ( "$BIN" setting -show true >b.out 2>&1 ) & wait grep -hE "Database initialization failed|Error initializing database|Error auto migrating" a.out b.out ``` Also checked: - `bash -n update.sh` passes. - `shellcheck update.sh` reports 129 findings before and after, so none is new. The new path is quoted to avoid adding an SC2086. - The new step runs before the `alpine` / systemd branch, so both the OpenRC and the systemd start are covered. `${xui_folder}/x-ui` is already installed at that point, since the line just above chmods its `bin/config.json`. - `x-ui migrate` is `InitDB()` + `InboundService.MigrateDB()`. Both are idempotent and touch only the database, not Xray, so running them while the service is stopped is safe. `config_after_update` still runs it again afterwards as a no-op. - The web updater fetches `update.sh` from `main` (`panelUpdaterURL`), so after merge the fix also applies to panels updating *from* older versions. - Go code is unchanged relative to `main`. On the branch with the Go experiment: `make verify` gen-check, `golangci-lint` (0 issues), `lint`, `format:check` and `typecheck` passed; `go test ./...` (48 packages) and `go test -race ./internal/database/...` passed; `make build build-storybook` passed. Two things I hit locally that are **pre-existing on `main` and unrelated** to this PR: - `make msw-worker-check` fails because `frontend/public/mockServiceWorker.js` is still the 2.15.0 worker while 99bc68fa bumped `msw` to 3.0.1. CI does not run this target. - On a 2-vCPU host, 3 component tests time out at 5000 ms (`client-bulk-calendar-renewal`, `client-calendar-renewal`, `inbound-form-modal`). They time out identically on clean `main`. ## Screenshots / recordings N/A, no UI change. ## Breaking changes None. Updates print one extra step, `Migrating database...`, followed by the existing `x-ui migrate` output. ## Checklist - [x] I tested the change locally and confirmed the described behavior. - [ ] I added or updated tests for the new behavior (when applicable). Not applicable: shell-script ordering. The reproducing commands are above. - [x] `go build ./...` and the test suite pass locally. - [ ] For frontend changes: `npm run lint`, `npm run typecheck`, and `npm run build` pass. No frontend changes. - [ ] I updated the Wiki / README / API docs if user-facing behavior changed. No user-facing change. - [x] My commits follow the project's existing message style. - [x] I have no unrelated changes mixed into this PR. --- **Open question for the maintainer.** This PR closes the update path, but any other overlap of two `InitDB()` callers is still unsafe, for example running an `x-ui setting` command while the service is (re)starting. A complete fix would be a cross-process migration lock in `InitDB()`: an advisory file lock next to the SQLite DB and `pg_advisory_lock` on PostgreSQL. That is a larger, platform-specific change, so I did not include it unasked. Happy to send it as a follow-up if you want it. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-02 04:08:43 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#6432
No description provided.