[PR #6912] [MERGED] fix(service): run inbound deletes and depleted-client purges on the serial traffic writer #6515

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

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/6912
Author: @muditagrawal2007
Created: 10/23/2026
Status: ✅ Merged
Merged: 10/24/2026
Merged by: @MHSanaei

Base: main ← Head: fix/serialized-writer-invariant


📝 Commits (5)

  • 1d970aa fix(service): delete inbounds on the serial traffic writer
  • 4c96767 fix(service): purge depleted clients on the serial traffic writer
  • 10501a1 Merge branch 'main' into fix/serialized-writer-invariant
  • df6e7cc Merge remote-tracking branch 'origin/main' into pr/6912
  • 3795227 test(service): keep the serial-writer delete tests with the traffic writer's

📊 Changes

3 files changed (+125 additions, -3 deletions)

View changed files

📝 internal/web/service/inbound.go (+1 -1)
📝 internal/web/service/inbound_traffic.go (+1 -2)
📝 internal/web/service/traffic_writer_test.go (+123 -0)

📄 Description

Summary

Deleting an inbound opened its own database transaction, so it could run outside the panel's single serial traffic writer. It now goes through runSerializedTx, the same helper every other inbound write already uses. A second commit closes the same escape hatch in the depleted-client purge.

before after
delInbound own db.Transaction runSerializedTx → queued on the traffic writer
DelDepletedClients own db.Transaction runSerializedTx → queued on the traffic writer

Why

The panel serialises inbound and traffic writes on one goroutine for a documented reason — internal/web/service/traffic_writer.go:117-123:

the poll locks inbounds then client_traffics; an admin client/inbound mutation does the reverse, which Postgres aborts as a deadlock (SQLSTATE 40P01)

1 · The inbound delete — operator-reachable

internal/web/service/inbound.go:1601 (on current main: :1651)

  • The delete takes client_inbounds first — DetachInbound (internal/web/service/client_link.go:459) — and only then the inbounds row.
  • The poll's lifecycle transaction takes the reverse: autoRenewClients saves the loaded inbounds first (internal/web/service/inbound_traffic.go:537) and rewrites the client links after (:550, SyncInbound); the traffic-sync path does the same (:339 → :353).

Two transactions taking the same two tables in opposite orders is a deadlock cycle on Postgres — one of them is aborted with SQLSTATE 40P01. Putting the delete on the same queue as the poll removes the cycle by construction.

A second, independent failure mode. When the delete commits between a poll's (or an edit's) read and its tx.Save, the UPDATE matches zero rows — and GORM's Save falls back to a CREATE, so the inbound the operator deleted comes back. Verified against the module version this repo pins (gorm.io/gorm v1.31.2, finisher_api.go):

updateTx := tx.callbacks.Update().Execute(tx.Session(&Session{Initialized: true}))
if updateTx.Error == nil && updateTx.RowsAffected == 0 && !updateTx.DryRun && !selectedUpdate {
    return tx.Session(&Session{SkipHooks: true}).Clauses(clause.OnConflict{UpdateAll: true}).Create(value)
}

(The SQLite build cannot show this: it holds a single database write lock, so the delete waits instead of interleaving.)

2 · The depleted-client purge — a latent escape hatch, not an operator-reachable bug

internal/web/service/inbound_traffic.go:902 opened its own transaction over the same two tables. To be precise about its reach: it has no production caller. The panel's "Delete depleted" button goes to ClientService.DelDepleted (internal/web/service/client_bulk.go:1525) → BulkDelete → already on the writer (client_bulk.go:987); only tests call InboundService.DelDepletedClients.

This commit removes the last inbound/traffic writer in that file that bypasses the single writer, so the invariant holds for every path in it — including any future caller. No operator-visible behaviour changes.

Scope

Two other writers touch inbounds outside the writer: SetInboundSubSortIndex (internal/web/service/inbound.go:1739) and SetInboundEnable (:1795). They write inbounds and then nodes — the order the poll uses — so they are not part of the cycle above and are deliberately left untouched.

The PostgreSQL deadlock is inferred from the lock order, not reproduced: the repo has no Postgres-based concurrency reproduction, and the always-on test asserts the invariant (the write reaches the writer) rather than the deadlock itself.

Evidence — red before, green after

before/after: the two mutations bypass the serial traffic writer

--- FAIL: TestDelInboundRunsOnTheSerialWriter (1.16s)
    the inbound delete bypassed the serial traffic writer and opened its own transaction
--- FAIL: TestDelDepletedClientsRunsOnTheSerialWriter (1.12s)
    the depleted-client purge bypassed the serial traffic writer and opened its own transaction

--- PASS: TestDelInboundRunsOnTheSerialWriter (0.09s)
--- PASS: TestDelDepletedClientsRunsOnTheSerialWriter (0.02s)

Type of change

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

Areas affected

  • Backend (API endpoints, login, settings)
  • Frontend (UI / panel pages)
  • 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?

Two new tests in internal/web/service/serialized_writer_invariant_test.go:

  • TestDelInboundRunsOnTheSerialWriter — parks the traffic writer inside an open transaction, starts the delete, and asserts the write was handed to the writer's queue instead of running on a goroutine of its own; then asserts the inbound row is gone.
  • TestDelDepletedClientsRunsOnTheSerialWriter — same shape for the purge; then asserts the depleted inbound and its client_traffics row are gone.

Both fail on the current code with the reason shown above and pass with the fix. The writer queue is the thing under test, so the assertion cannot pass by accident.

Commands run locally:

go test ./internal/web/service/ -run 'TestDelInboundRunsOnTheSerialWriter|TestDelDepletedClientsRunsOnTheSerialWriter' -count=1 -v
go test ./internal/web/service/... -count=1
go test -race ./internal/web/service/ -count=1 -timeout 25m
go test -shuffle=on -count=1 $(go list ./... | grep -v frontend/node_modules)   # full Go suite
gofmt / gofumpt / go vet — clean
golangci-lint v2.15.0 run ./internal/web/service/... — 0 issues

Notes for the reviewer

  • No API route, i18n key, DB schema or OpenAPI change. TestRouteRegistryContract and the locale-key test are unaffected by construction.
  • Bulk delete is covered too. DelInbounds calls delInbound per id, so it is serialised as well; the writer drains one request at a time, so a bulk delete cannot overflow the queue.
  • Nothing inside the moved closures does network I/O or re-enters the writer. DetachInbound and MarkNodeDirtyTx (internal/web/service/node.go:1043) are plain statements; the node push and the runtime cleanup still run after the commit (internal/web/service/inbound.go:1634).
  • One escape hatch was deliberately left alone. submitTrafficWrite still falls back to running inline when the writer was never started (internal/web/service/traffic_writer.go:162). During shutdown the cron is stopped before the writer (internal/web/web.go:776 → :801), so no traffic poll can be running at that point, and an existing test pins that behaviour — changing it would be a contract change, not a fix.

🔄 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/6912 **Author:** [@muditagrawal2007](https://github.com/muditagrawal2007) **Created:** 10/23/2026 **Status:** ✅ Merged **Merged:** 10/24/2026 **Merged by:** [@MHSanaei](https://github.com/MHSanaei) **Base:** `main` ← **Head:** `fix/serialized-writer-invariant` --- ### 📝 Commits (5) - [`1d970aa`](https://github.com/MHSanaei/3x-ui/commit/1d970aa1341b20cc34d11c1d8a91dfff19ecfbb3) fix(service): delete inbounds on the serial traffic writer - [`4c96767`](https://github.com/MHSanaei/3x-ui/commit/4c967676c60bf0ff0def34c45eec42c71b4eec09) fix(service): purge depleted clients on the serial traffic writer - [`10501a1`](https://github.com/MHSanaei/3x-ui/commit/10501a1236b70b3782d3bce108f42be9e4f82ffe) Merge branch 'main' into fix/serialized-writer-invariant - [`df6e7cc`](https://github.com/MHSanaei/3x-ui/commit/df6e7cc08f5243e477e8218ca5b8db2436ab1bb9) Merge remote-tracking branch 'origin/main' into pr/6912 - [`3795227`](https://github.com/MHSanaei/3x-ui/commit/379522761e9dae50b890765d7058972c38acda64) test(service): keep the serial-writer delete tests with the traffic writer's ### 📊 Changes **3 files changed** (+125 additions, -3 deletions) <details> <summary>View changed files</summary> 📝 `internal/web/service/inbound.go` (+1 -1) 📝 `internal/web/service/inbound_traffic.go` (+1 -2) 📝 `internal/web/service/traffic_writer_test.go` (+123 -0) </details> ### 📄 Description ## Summary Deleting an inbound opened **its own** database transaction, so it could run outside the panel's single serial traffic writer. It now goes through `runSerializedTx`, the same helper every other inbound write already uses. A second commit closes the same escape hatch in the depleted-client purge. | | before | after | |---|---|---| | `delInbound` | own `db.Transaction` | `runSerializedTx` → queued on the traffic writer | | `DelDepletedClients` | own `db.Transaction` | `runSerializedTx` → queued on the traffic writer | --- ## Why The panel serialises inbound and traffic writes on one goroutine for a documented reason — `internal/web/service/traffic_writer.go:117-123`: > the poll locks `inbounds` then `client_traffics`; an admin client/inbound mutation does the reverse, which Postgres aborts as a deadlock (SQLSTATE 40P01) ### 1 · The inbound delete — operator-reachable `internal/web/service/inbound.go:1601` (on current `main`: `:1651`) - The delete takes **`client_inbounds` first** — `DetachInbound` (`internal/web/service/client_link.go:459`) — and only then the `inbounds` row. - The poll's lifecycle transaction takes the **reverse**: `autoRenewClients` saves the loaded inbounds first (`internal/web/service/inbound_traffic.go:537`) and rewrites the client links after (`:550`, `SyncInbound`); the traffic-sync path does the same (`:339` → `:353`). Two transactions taking the same two tables in opposite orders is a deadlock cycle on Postgres — one of them is aborted with `SQLSTATE 40P01`. Putting the delete on the same queue as the poll removes the cycle by construction. **A second, independent failure mode.** When the delete commits between a poll's (or an edit's) read and its `tx.Save`, the `UPDATE` matches zero rows — and GORM's `Save` falls back to a `CREATE`, so the inbound the operator deleted comes back. Verified against the module version this repo pins (`gorm.io/gorm v1.31.2`, `finisher_api.go`): ```go updateTx := tx.callbacks.Update().Execute(tx.Session(&Session{Initialized: true})) if updateTx.Error == nil && updateTx.RowsAffected == 0 && !updateTx.DryRun && !selectedUpdate { return tx.Session(&Session{SkipHooks: true}).Clauses(clause.OnConflict{UpdateAll: true}).Create(value) } ``` (The SQLite build cannot show this: it holds a single database write lock, so the delete waits instead of interleaving.) ### 2 · The depleted-client purge — a latent escape hatch, not an operator-reachable bug `internal/web/service/inbound_traffic.go:902` opened its own transaction over the same two tables. To be precise about its reach: **it has no production caller.** The panel's *"Delete depleted"* button goes to `ClientService.DelDepleted` (`internal/web/service/client_bulk.go:1525`) → `BulkDelete` → already on the writer (`client_bulk.go:987`); only tests call `InboundService.DelDepletedClients`. This commit removes the last inbound/traffic writer in that file that bypasses the single writer, so the invariant holds for every path in it — including any future caller. **No operator-visible behaviour changes.** ### Scope Two other writers touch `inbounds` outside the writer: `SetInboundSubSortIndex` (`internal/web/service/inbound.go:1739`) and `SetInboundEnable` (`:1795`). They write `inbounds` and then `nodes` — the order the poll uses — so they are not part of the cycle above and are deliberately left untouched. The PostgreSQL deadlock is **inferred from the lock order, not reproduced**: the repo has no Postgres-based concurrency reproduction, and the always-on test asserts the invariant (the write reaches the writer) rather than the deadlock itself. ### Evidence — red before, green after ![before/after: the two mutations bypass the serial traffic writer](https://raw.githubusercontent.com/muditagrawal2007/3x-ui/pr-evidence/serialized-writer/.github/pr-evidence/serialized-writer-red-green.png) ``` --- FAIL: TestDelInboundRunsOnTheSerialWriter (1.16s) the inbound delete bypassed the serial traffic writer and opened its own transaction --- FAIL: TestDelDepletedClientsRunsOnTheSerialWriter (1.12s) the depleted-client purge bypassed the serial traffic writer and opened its own transaction --- PASS: TestDelInboundRunsOnTheSerialWriter (0.09s) --- PASS: TestDelDepletedClientsRunsOnTheSerialWriter (0.02s) ``` --- ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactoring (no behavior change) - [ ] Documentation - [ ] Tests only - [ ] Build / CI / tooling - [ ] Other ## Areas affected - [x] Backend (API endpoints, login, settings) - [ ] Frontend (UI / panel pages) - [ ] 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? Two new tests in `internal/web/service/serialized_writer_invariant_test.go`: - **`TestDelInboundRunsOnTheSerialWriter`** — parks the traffic writer inside an open transaction, starts the delete, and asserts the write was handed to the writer's queue instead of running on a goroutine of its own; then asserts the inbound row is gone. - **`TestDelDepletedClientsRunsOnTheSerialWriter`** — same shape for the purge; then asserts the depleted inbound and its `client_traffics` row are gone. Both fail on the current code with the reason shown above and pass with the fix. The writer queue is the thing under test, so the assertion cannot pass by accident. Commands run locally: ``` go test ./internal/web/service/ -run 'TestDelInboundRunsOnTheSerialWriter|TestDelDepletedClientsRunsOnTheSerialWriter' -count=1 -v go test ./internal/web/service/... -count=1 go test -race ./internal/web/service/ -count=1 -timeout 25m go test -shuffle=on -count=1 $(go list ./... | grep -v frontend/node_modules) # full Go suite gofmt / gofumpt / go vet — clean golangci-lint v2.15.0 run ./internal/web/service/... — 0 issues ``` ## Notes for the reviewer - **No API route, i18n key, DB schema or OpenAPI change.** `TestRouteRegistryContract` and the locale-key test are unaffected by construction. - **Bulk delete is covered too.** `DelInbounds` calls `delInbound` per id, so it is serialised as well; the writer drains one request at a time, so a bulk delete cannot overflow the queue. - **Nothing inside the moved closures does network I/O or re-enters the writer.** `DetachInbound` and `MarkNodeDirtyTx` (`internal/web/service/node.go:1043`) are plain statements; the node push and the runtime cleanup still run after the commit (`internal/web/service/inbound.go:1634`). - **One escape hatch was deliberately left alone.** `submitTrafficWrite` still falls back to running inline when the writer was never started (`internal/web/service/traffic_writer.go:162`). During shutdown the cron is stopped *before* the writer (`internal/web/web.go:776` → `:801`), so no traffic poll can be running at that point, and an existing test pins that behaviour — changing it would be a contract change, not a fix. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-02 04:09:19 +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#6515
No description provided.