[PR #6491] [MERGED] fix(tgbot): read the admin list and running flag under their mutex #6304

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

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/6491
Author: @BlindMaster24
Created: 9/12/2026
Status: ✅ Merged
Merged: 9/13/2026
Merged by: @MHSanaei

Base: main ← Head: fix/tgbot-admin-list-race


📝 Commits (1)

  • 5b1c3a2 fix(tgbot): read the admin list and running flag under their mutex

📊 Changes

5 files changed (+90 additions, -7 deletions)

View changed files

📝 internal/web/service/tgbot/tgbot.go (+8 -0)
➕ internal/web/service/tgbot/tgbot_admin_list_race_test.go (+73 -0)
📝 internal/web/service/tgbot/tgbot_report.go (+4 -3)
📝 internal/web/service/tgbot/tgbot_router.go (+1 -1)
📝 internal/web/service/tgbot/tgbot_send.go (+4 -3)

📄 Description

Summary

adminIds is replaced under tgBotMutex by Start/Stop, but five readers
took it without the lock. They now read a snapshot under the same mutex, and
SendMsgToTgbot uses the existing IsRunning() accessor instead of reading the
isRunning flag directly.

Why

Writers, both holding tgBotMutex:

  • Start (tgbot.go:290) — assigns the parsed chat IDs
  • Stop (tgbot.go:460) — sets adminIds = nil; reached by the bot settings
    reload, and by panel shutdown through main.go's signal handler

Readers, none of them holding it:

  • checkAdmin (tgbot_router.go:1324) — every callback and command the bot
    receives runs through it, on the 10-goroutine worker pool
  • SendMsgToTgbotAdmins (tgbot_send.go:182) — every event-bus notification
  • SendBackupToAdmins (tgbot_report.go:56) and sendExhaustedToAdmins
    (tgbot_report.go:70) — the Report / backup cron

What the operator meets

An operator opens Settings → Telegram bot, fixes the Chat ID and saves. The
panel reloads the bot (SetReloadTgbotFunc), which calls Stop() → adminIds = nil, while the Report cron scheduled at the same second is inside
SendReport. Two things can then go wrong, and both are visible:

  1. A lost or partial delivery. A slice header is three words. Reading it
    while it is replaced can observe a new pointer with the old length (or the
    reverse), so slices.Contains / range walks a length that does not belong
    to the array it is reading: the report or the DB backup goes to nobody, to
    some admins, or to a stale set. The outcome is non-deterministic and nothing
    logs an error.
  2. The pacing between backup uploads stops. SendBackupToAdmins sleeps one
    second between uploads by comparing against len(adminIds) - 1 inside the
    loop (tgbot_report.go:59). Once the list is nil'd mid-loop, that expression
    is -1, the sleep is skipped for every remaining admin, and the uploads go
    out back-to-back — the exact burst the sleep exists to avoid, hitting the
    same Telegram rate limit as #6340 and #6490.

-race reports the read regardless of which symptom an operator happens to hit;
the race job runs it on every PR.

Scope

isRunning had the same shape — written under the mutex by OnReceive
(tgbot_router.go:68) and StopBot (tgbot.go:473), read unlocked by
SendMsgToTgbot (tgbot_send.go:124) — so that read now uses the accessor the
package already has. The telego client pointer bot has the same problem in
about a dozen places, but it has no accessor yet and every reader would have to
move to it; that is a separate change and is left out of this one.

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 — report and backup delivery only
  • Database / migrations
  • Install / upgrade script
  • Docker image
  • Multi-node (sub-nodes)
  • Telegram bot

How was this tested?

internal/web/service/tgbot/tgbot_admin_list_race_test.go runs one writer that
reassigns adminIds and isRunning under tgBotMutex — the same lock order
Start/Stop use — against four goroutines calling checkAdmin, IsRunning()
and SendMsgToTgbot, the last being the reader this PR changed and which had no
coverage before. The adminIds half trips the detector through checkAdmin; the
isRunning half does so through SendMsgToTgbot, which would stay green under
-race if only this test's IsRunning() calls were left in. A mocked Telegram
API backs SendMsgToTgbot so the live path stays cheap.

go test -race is what CI's race job runs. The test cannot fail without it —
that is inherent to a race, and the race job covers it.

Screenshots / recordings

N/A — no UI.

Breaking changes

None. Same behaviour for every caller, and the backup pacing now uses the
snapshot's length instead of a list that may be replaced mid-loop.

Checklist

  • I tested the change locally and confirmed the described behavior. — no C compiler on this machine, see above; the new test covers it under -race.
  • I added or updated tests for the new behavior (when applicable).
  • go build ./... and the test suite pass locally. — same reason as above.
  • For frontend changes: npm run lint, npm run typecheck, and npm run build pass. — no frontend files touched.
  • I updated the Wiki / README / API docs if user-facing behavior changed. — no endpoint or wire-format change.
  • My commits follow the project's existing message style.
  • I have no unrelated changes mixed into this PR.

🔄 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/6491 **Author:** [@BlindMaster24](https://github.com/BlindMaster24) **Created:** 9/12/2026 **Status:** ✅ Merged **Merged:** 9/13/2026 **Merged by:** [@MHSanaei](https://github.com/MHSanaei) **Base:** `main` ← **Head:** `fix/tgbot-admin-list-race` --- ### 📝 Commits (1) - [`5b1c3a2`](https://github.com/MHSanaei/3x-ui/commit/5b1c3a26dc25176c972b705971b5512a4ef35a35) fix(tgbot): read the admin list and running flag under their mutex ### 📊 Changes **5 files changed** (+90 additions, -7 deletions) <details> <summary>View changed files</summary> 📝 `internal/web/service/tgbot/tgbot.go` (+8 -0) ➕ `internal/web/service/tgbot/tgbot_admin_list_race_test.go` (+73 -0) 📝 `internal/web/service/tgbot/tgbot_report.go` (+4 -3) 📝 `internal/web/service/tgbot/tgbot_router.go` (+1 -1) 📝 `internal/web/service/tgbot/tgbot_send.go` (+4 -3) </details> ### 📄 Description ## Summary `adminIds` is replaced under `tgBotMutex` by `Start`/`Stop`, but five readers took it without the lock. They now read a snapshot under the same mutex, and `SendMsgToTgbot` uses the existing `IsRunning()` accessor instead of reading the `isRunning` flag directly. ## Why Writers, both holding `tgBotMutex`: - `Start` (`tgbot.go:290`) — assigns the parsed chat IDs - `Stop` (`tgbot.go:460`) — sets `adminIds = nil`; reached by the bot settings reload, and by panel shutdown through `main.go`'s signal handler Readers, none of them holding it: - `checkAdmin` (`tgbot_router.go:1324`) — **every** callback and command the bot receives runs through it, on the 10-goroutine worker pool - `SendMsgToTgbotAdmins` (`tgbot_send.go:182`) — every event-bus notification - `SendBackupToAdmins` (`tgbot_report.go:56`) and `sendExhaustedToAdmins` (`tgbot_report.go:70`) — the *Report* / backup cron ### What the operator meets An operator opens **Settings → Telegram bot**, fixes the Chat ID and saves. The panel reloads the bot (`SetReloadTgbotFunc`), which calls `Stop()` → `adminIds = nil`, while the *Report* cron scheduled at the same second is inside `SendReport`. Two things can then go wrong, and both are visible: 1. **A lost or partial delivery.** A slice header is three words. Reading it while it is replaced can observe a new pointer with the old length (or the reverse), so `slices.Contains` / `range` walks a length that does not belong to the array it is reading: the report or the DB backup goes to nobody, to some admins, or to a stale set. The outcome is non-deterministic and nothing logs an error. 2. **The pacing between backup uploads stops.** `SendBackupToAdmins` sleeps one second between uploads by comparing against `len(adminIds) - 1` *inside* the loop (`tgbot_report.go:59`). Once the list is nil'd mid-loop, that expression is `-1`, the sleep is skipped for every remaining admin, and the uploads go out back-to-back — the exact burst the sleep exists to avoid, hitting the same Telegram rate limit as `#6340` and `#6490`. `-race` reports the read regardless of which symptom an operator happens to hit; the `race` job runs it on every PR. ### Scope `isRunning` had the same shape — written under the mutex by `OnReceive` (`tgbot_router.go:68`) and `StopBot` (`tgbot.go:473`), read unlocked by `SendMsgToTgbot` (`tgbot_send.go:124`) — so that read now uses the accessor the package already has. The telego client pointer `bot` has the same problem in about a dozen places, but it has no accessor yet and every reader would have to move to it; that is a separate change and is left out of this one. ## 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) - [x] Statistics / traffic counters — report and backup delivery only - [ ] Database / migrations - [ ] Install / upgrade script - [ ] Docker image - [ ] Multi-node (sub-nodes) - [x] Telegram bot ## How was this tested? `internal/web/service/tgbot/tgbot_admin_list_race_test.go` runs one writer that reassigns `adminIds` **and** `isRunning` under `tgBotMutex` — the same lock order `Start`/`Stop` use — against four goroutines calling `checkAdmin`, `IsRunning()` and `SendMsgToTgbot`, the last being the reader this PR changed and which had no coverage before. The `adminIds` half trips the detector through `checkAdmin`; the `isRunning` half does so through `SendMsgToTgbot`, which would stay green under `-race` if only this test's `IsRunning()` calls were left in. A mocked Telegram API backs `SendMsgToTgbot` so the live path stays cheap. `go test -race` is what CI's `race` job runs. The test cannot fail without it — that is inherent to a race, and the race job covers it. ## Screenshots / recordings N/A — no UI. ## Breaking changes None. Same behaviour for every caller, and the backup pacing now uses the snapshot's length instead of a list that may be replaced mid-loop. ## Checklist - [ ] I tested the change locally and confirmed the described behavior. — no C compiler on this machine, see above; the new test covers it under `-race`. - [x] I added or updated tests for the new behavior (when applicable). - [ ] `go build ./...` and the test suite pass locally. — same reason as above. - [ ] For frontend changes: `npm run lint`, `npm run typecheck`, and `npm run build` pass. — no frontend files touched. - [ ] I updated the Wiki / README / API docs if user-facing behavior changed. — no endpoint or wire-format change. - [x] My commits follow the project's existing message style. - [x] I have no unrelated changes mixed into this PR. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-02 04:07:48 +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#6304
No description provided.