mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 21:18:19 +07:00
[PR #6887] [MERGED] fix(tgbot): replace costly JSON client lookup with indexed queries #6499
Labels
No labels
backlog
bug
clarification needed
documentation
duplicate
enhancement
github_actions
good first issue
invalid
javascript
New Feature
PR welcomed
pull-request
question
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
MHSanaei/3x-ui#6499
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 Pull Request Information
Original PR: https://github.com/MHSanaei/3x-ui/pull/6887
Author: @HamedSanaei
Created: 10/21/2026
Status: ✅ Merged
Merged: 10/24/2026
Merged by: @MHSanaei
Base:
main← Head:fix/tgbot-lookup-performance📝 Commits (5)
d24c097fix(tgbot): optimize Telegram client lookup and notification deduplicationa6f0325chore(tgbot): address benchmark maintenance and PostgreSQL CI reviewb623f21fix(deps): update Go and DOMPurify security patches86f368cMerge remote-tracking branch 'origin/main' into pr/6887d82323dtest(tgbot): keep the indexed lookup tests with the existing lookup and report tests📊 Changes
9 files changed (+378 additions, -85 deletions)
View changed files
📝
.github/workflows/ci.yml(+10 -0)📝
internal/web/service/inbound_tgbot_lookup_test.go(+206 -7)📝
internal/web/service/inbound_traffic.go(+27 -63)📝
internal/web/service/tgbot/tgbot.go(+0 -5)📝
internal/web/service/tgbot/tgbot_client_links_authz_test.go(+29 -2)📝
internal/web/service/tgbot/tgbot_invite_test.go(+4 -1)📝
internal/web/service/tgbot/tgbot_level_test.go(+0 -1)📝
internal/web/service/tgbot/tgbot_report.go(+7 -4)📝
internal/web/service/tgbot/tgbot_report_batching_test.go(+95 -2)📄 Description
Summary
Replace Telegram client traffic lookups that expand every inbound's settings JSON with a single query filtered by the existing
clients.tg_idindex. Populate client metadata in that query, and deduplicate exhaustion notification lookups even when they return no traffic or fail.Fixes #6886. Retains and extends the #5805 serialization regression coverage.
Root cause
Each Telegram ID previously triggered JSON array expansion across all inbounds, followed by inbound loading and JSON parsing. Every matching traffic row then called
GetClientByEmail, adding database reads and further JSON parsing. The notification pass only marked an ID processed after a nonempty successful lookup, so empty results and errors repeated that work for each associated client.Implementation
clientstoclient_traffics, filter byclients.tg_id, and useEXISTSoverclient_inboundsand live inbounds to require a valid attachment without duplicating multi-inbound clients. Return records in client ID order. Stale legacyclient_traffics.inbound_idpointers do not prevent a valid normalized attachment from being found.Enable,UUID, andSubIdfrom the same normalized rows. Preserve traffic counters, expiry, reset fields and the existing traffic record. Remove all per-row metadata queries and JSON parsing from this lookup. Nonpositive IDs return no records without querying the database.map[int64]struct{}and mark eligible IDs before lookup. Log lookup errors once per ID. Discover notification recipients throughListClientsForInbound, so stale JSON ownership cannot suppress a current owner's notification. Notification text and threshold calculations remain unchanged.Compatibility
The existing
ClientsTablestartup seeder (seedClientsFromInboundJSON) converts legacy JSON-only clients and their attachments before services run. Normal inbound creation/update/import and client synchronization keep normalized data populated. No new schema or data migration is introduced.TestGetClientTrafficTgBot_SettingsSerializationStylesstill starts with legacy settings and traffic. It now executes the actual startup migration, checks that normalized records exist, and retains its lookup assertions. It covers compact, spaced and indented JSON, including an existing client whose attachment is missing before migration. The migration/lookup combination has been exercised on SQLite and PostgreSQL 16.Normalized records are authoritative after migration, as they already are for running clients. Direct SQL writes that insert JSON-only clients after a completed migration must synchronize those records; a request-time JSON fallback would reintroduce the hotspot and could restore stale Telegram ownership. Unknown IDs never trigger a JSON scan.
Tests
Passed locally on Windows/amd64 with Go 1.27.2 and GCC:
go fmt ./...go vet ./...go build -p 2 ./...go test -p 2 -shuffle=on -count=1 ./...go test -p 2 ./internal/web/service/tgbot/... -count=1-race -shuffle=on -count=1golangci-lint run --timeout 10m: 0 issuesactionlint .github/workflows/ci.ymlpassed.New regressions cover shared Telegram IDs, multi-inbound attachments, absent traffic, unknown/zero/negative IDs, disabled metadata, UUID/subscription fields, counters, stale traffic pointers, orphan attachments, changed ownership, expiration/traffic notifications, and empty/failed notification lookup deduplication. Query assertions require one SQL statement for positive IDs and no settings/JSON access; 1,200 matching clients still require one query. Existing callback/invite tests retain their assertions with synchronized fixtures.
Review follow-up
In follow-up commit
a6f03252, addressed the LOW finding in the review: removedinbound_tgbot_benchmark_test.go, including the old implementation and the equality guard. All behavioral, ownership, notification, and query-count regression tests remain.The PostgreSQL CI job now explicitly selects
TestGetClientTrafficTgBot_IndexedPostgresandTestGetClientTrafficTgBot_SettingsSerializationStyles, requiring exactly two top-level passes. Previously the job's durable-first/schema filters did not select these new tests. This prevents a skipped or renamed PostgreSQL regression from silently leaving the job green.Performance
The measurements below were collected at commit
d24c097e4733068744179a31254ff7274fa9c609. In response to review, the comparison harness has been removed from the current tree: keeping the deleted implementation as a permanent test-onlyInboundServicemethod and requiringreflect.DeepEqualagainst it would unnecessarily constrain future changes.To reproduce the historical comparison, use a separate disposable worktree at that commit, then run:
For PostgreSQL, set
XUI_DB_TYPE=postgresandXUI_DB_DSNto an isolated disposable test database and add-vto print execution plans. The historical harness refreshes statistics on its synthetic PostgreSQL tables. It compares both implementations against identical data: eight inbounds, four matching clients, and 100/1,000/10,000 total clients. Measurements remain in this PR rather than in a permanent copy of the removed code. Query-count and behavioral regressions remain in the normal test suite.Median of three 500 ms benchmark runs on a local Windows/amd64 i5-13450HX, with PostgreSQL 16 in a local Docker container:
For 10,000-client misses: SQLite 16.417 ms → 0.031 ms, PostgreSQL 25.946 ms → 0.584 ms. Both paths issue one SQL statement on a miss; the new path avoids expanding JSON.
Go allocation measurements for 10,000-client hits (sample at the median runtime):
Misses have a higher fixed Go allocation overhead in the indexed implementation: SQLite approximately 12.8 KB / 100 allocations versus 3.3 KB / 48 before; PostgreSQL approximately 13.3 KB / 83 versus 7.6 KB / 49 before. These figures exclude database server memory.
With fresh statistics on the 10,000-client PostgreSQL dataset,
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF)measured the old JSON discovery query at 23.861 ms, versus 0.093 ms for the complete indexed lookup. The new plan usesidx_clients_tg_id,idx_client_inbounds_client_id, anduni_client_traffics_email; it does not scan the full attachment table. These are local synthetic measurements, not production guarantees or the production measurements quoted in the issue. Generated benchmark output is excluded from the commit.GitHub Actions
The initial automated review completed successfully and reported one LOW maintenance finding, addressed by
a6f03252. The initial CI run reportsaction_requiredbefore any jobs start. This fork account has read-only permission on upstream and cannot approve fork runs. The follow-up CI run fora6f03252also reportsaction_required; remote CI success is not claimed. The new PostgreSQL test step is wired into the existing PostgreSQL job and has passed locally with both tests executed.Safety
No production database, schema, deployment, or running service was modified. All database tests and benchmarks used local synthetic data. The original IPv6 branch and its untracked
PR.mdremain untouched. This branch is based directly on upstreammainand contains only this issue's source and tests.🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.