[PR #4120] [CLOSED] fix(database): prevent "database is locked" with WAL mode and single connection pool #5604

Closed
opened 2026-10-31 20:48:07 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/4120
Author: @kanghouchao
Created: 4/28/2026
Status: ❌ Closed

Base: main ← Head: fix/sqlite-database-is-locked


📝 Commits (7)

  • 545f5a3 fix(database): prevent "database is locked" with WAL mode and single connection pool
  • de4d40a style(database): fix gofmt comment indentation in concurrent_test.go
  • 314f877 fix(database): address Copilot review comments
  • ca49f56 docs(database): fix proof claim — SetMaxOpenConns(1) is sufficient, not necessary
  • b0cfc49 docs(database): scope the lock-prevention guarantee to intra-process access
  • 0499e91 docs(database): clarify test coverage scope and experimental variable
  • ee27768 update too "// primary DB configuration variable under test."

📊 Changes

2 files changed (+208 additions, -1 deletions)

View changed files

➕ database/concurrent_test.go (+201 -0)
📝 database/db.go (+7 -1)

📄 Description

Problem

Multiple goroutines — `XrayTrafficJob` (every 10 s), `PeriodicResetJob` (hourly/daily), WebSocket tickers — each obtain their own GORM connection and race for the SQLite write lock. When a long-running transaction (many clients, auto-renew logic) holds the lock longer than go-sqlite3's busy timeout, the competing writer fails with `database is locked`. This is the root cause of #3739.

The default DELETE journal mode means any concurrent write blocks all other writes. The unbounded GORM connection pool (`MaxOpenConns = 0`) means every goroutine can get its own connection and race.

Historical note: A correct fix was submitted in PR #2645 (`_journal_mode=WAL` + pragmas + `SkipDefaultTransaction`) but was accidentally reverted in commit `d18a1a37` ("revert group management") along with an unrelated feature rollback. This PR restores and extends that fix.

Fix

Two minimal changes to `InitDB` in `database/db.go`:

1. WAL journal mode
```go
sqlite.Open(dbPath + "?_journal_mode=WAL")
```
Readers no longer block writers and vice-versa, reducing the write-lock window.

2. Single connection pool
```go
sqlDB.SetMaxOpenConns(1)
```
Serialises all GORM database access through one connection at the Go `database/sql` pool level. A second writer waits for the pool connection to be free rather than racing at the SQLite level — eliminating write-lock contention entirely regardless of transaction duration.

Tests

`database/concurrent_test.go` adds two test functions:

  • `TestConcurrentWrites` — behavioural proof with two sub-tests:
    • `without_fix_*`: opens two explicit connections with `_busy_timeout=10ms`, holds a write transaction on one, then immediately writes on the other. Confirms `database is locked` is reproduced deterministically.
    • `with_fix_*`: same scenario with `MaxOpenConns=1`. The second connection blocks in the Go pool queue instead of racing at the SQLite level — no error.
  • `TestInitDBConcurrencyConfig` — verifies `InitDB` actually applies both settings (`journal_mode=wal`, `MaxOpenConnections=1`), completing the proof that the production code path is fixed.

Test run

```
$ go test -race -shuffle=on ./...
ok github.com/mhsanaei/3x-ui/v2/database 3.019s
ok github.com/mhsanaei/3x-ui/v2/database/model 1.478s
ok github.com/mhsanaei/3x-ui/v2/web/job 3.696s
ok github.com/mhsanaei/3x-ui/v2/web/service 3.148s
```

Closes #3739


🔄 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/4120 **Author:** [@kanghouchao](https://github.com/kanghouchao) **Created:** 4/28/2026 **Status:** ❌ Closed **Base:** `main` ← **Head:** `fix/sqlite-database-is-locked` --- ### 📝 Commits (7) - [`545f5a3`](https://github.com/MHSanaei/3x-ui/commit/545f5a36725ad249dca98e4876f6eb7ad7a705d7) fix(database): prevent "database is locked" with WAL mode and single connection pool - [`de4d40a`](https://github.com/MHSanaei/3x-ui/commit/de4d40a25c97ba4b6542976be5b45c8ce9ab2b9b) style(database): fix gofmt comment indentation in concurrent_test.go - [`314f877`](https://github.com/MHSanaei/3x-ui/commit/314f877d784e4bd5c1333c50c800715441308d7f) fix(database): address Copilot review comments - [`ca49f56`](https://github.com/MHSanaei/3x-ui/commit/ca49f5672a7a23af9731a4025ed74ec2b35de150) docs(database): fix proof claim — SetMaxOpenConns(1) is sufficient, not necessary - [`b0cfc49`](https://github.com/MHSanaei/3x-ui/commit/b0cfc49c0dd71ae1c2df19e9ee06f7e1e9c68519) docs(database): scope the lock-prevention guarantee to intra-process access - [`0499e91`](https://github.com/MHSanaei/3x-ui/commit/0499e91ebeedb650c522c25be0a81903dd529b23) docs(database): clarify test coverage scope and experimental variable - [`ee27768`](https://github.com/MHSanaei/3x-ui/commit/ee277688073ee23cb93a4ffe9693925bb31241aa) update too "// primary DB configuration variable under test." ### 📊 Changes **2 files changed** (+208 additions, -1 deletions) <details> <summary>View changed files</summary> ➕ `database/concurrent_test.go` (+201 -0) 📝 `database/db.go` (+7 -1) </details> ### 📄 Description ## Problem Multiple goroutines — \`XrayTrafficJob\` (every 10 s), \`PeriodicResetJob\` (hourly/daily), WebSocket tickers — each obtain their own GORM connection and race for the SQLite write lock. When a long-running transaction (many clients, auto-renew logic) holds the lock longer than go-sqlite3's busy timeout, the competing writer fails with \`database is locked\`. This is the root cause of #3739. The default DELETE journal mode means any concurrent write blocks all other writes. The unbounded GORM connection pool (\`MaxOpenConns = 0\`) means every goroutine can get its own connection and race. **Historical note:** A correct fix was submitted in PR #2645 (\`_journal_mode=WAL\` + pragmas + \`SkipDefaultTransaction\`) but was accidentally reverted in commit \`d18a1a37\` ("revert group management") along with an unrelated feature rollback. This PR restores and extends that fix. ## Fix Two minimal changes to \`InitDB\` in \`database/db.go\`: **1. WAL journal mode** \`\`\`go sqlite.Open(dbPath + "?_journal_mode=WAL") \`\`\` Readers no longer block writers and vice-versa, reducing the write-lock window. **2. Single connection pool** \`\`\`go sqlDB.SetMaxOpenConns(1) \`\`\` Serialises all GORM database access through one connection at the Go \`database/sql\` pool level. A second writer waits for the pool connection to be free rather than racing at the SQLite level — eliminating write-lock contention entirely regardless of transaction duration. ## Tests \`database/concurrent_test.go\` adds two test functions: - **\`TestConcurrentWrites\`** — behavioural proof with two sub-tests: - \`without_fix_*\`: opens two explicit connections with \`_busy_timeout=10ms\`, holds a write transaction on one, then immediately writes on the other. Confirms \`database is locked\` is reproduced deterministically. - \`with_fix_*\`: same scenario with \`MaxOpenConns=1\`. The second connection blocks in the Go pool queue instead of racing at the SQLite level — no error. - **\`TestInitDBConcurrencyConfig\`** — verifies \`InitDB\` actually applies both settings (\`journal_mode=wal\`, \`MaxOpenConnections=1\`), completing the proof that the production code path is fixed. ## Test run \`\`\` $ go test -race -shuffle=on ./... ok github.com/mhsanaei/3x-ui/v2/database 3.019s ok github.com/mhsanaei/3x-ui/v2/database/model 1.478s ok github.com/mhsanaei/3x-ui/v2/web/job 3.696s ok github.com/mhsanaei/3x-ui/v2/web/service 3.148s \`\`\` Closes #3739 --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-31 20:48:07 +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#5604
No description provided.