[PR #6887] [MERGED] fix(tgbot): replace costly JSON client lookup with indexed queries #6499

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

📋 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)

  • d24c097 fix(tgbot): optimize Telegram client lookup and notification deduplication
  • a6f0325 chore(tgbot): address benchmark maintenance and PostgreSQL CI review
  • b623f21 fix(deps): update Go and DOMPurify security patches
  • 86f368c Merge remote-tracking branch 'origin/main' into pr/6887
  • d82323d test(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_id index. 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

  • Join normalized clients to client_traffics, filter by clients.tg_id, and use EXISTS over client_inbounds and live inbounds to require a valid attachment without duplicating multi-inbound clients. Return records in client ID order. Stale legacy client_traffics.inbound_id pointers do not prevent a valid normalized attachment from being found.
  • Read Enable, UUID, and SubId from 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.
  • Use a per-pass map[int64]struct{} and mark eligible IDs before lookup. Log lookup errors once per ID. Discover notification recipients through ListClientsForInbound, so stale JSON ownership cannot suppress a current owner's notification. Notification text and threshold calculations remain unchanged.
  • Remove the slice membership helper that became unused.

Compatibility

The existing ClientsTable startup 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_SettingsSerializationStyles still 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
  • Targeted lookup, notification and ownership tests with -race -shuffle=on -count=1
  • golangci-lint run --timeout 10m: 0 issues
  • PostgreSQL lookup and legacy startup migration tests in a disposable local PostgreSQL 16 container
  • Follow-up: full shuffled Go suite rerun successfully, new PostgreSQL CI test command/pass-count check executed with two passes, and actionlint .github/workflows/ci.yml passed.

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: removed inbound_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_IndexedPostgres and TestGetClientTrafficTgBot_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-only InboundService method and requiring reflect.DeepEqual against it would unnecessarily constrain future changes.

To reproduce the historical comparison, use a separate disposable worktree at that commit, then run:

go test ./internal/web/service -run '^$' -bench '^BenchmarkGetClientTrafficTgBot$' -benchmem -benchtime=500ms -count=3

For PostgreSQL, set XUI_DB_TYPE=postgres and XUI_DB_DSN to an isolated disposable test database and add -v to 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:

Backend Total clients Old hit Indexed hit SQL statements per hit
SQLite 100 0.957 ms 0.049 ms 11 → 1
SQLite 1,000 5.292 ms 0.056 ms 11 → 1
SQLite 10,000 48.174 ms 0.055 ms 11 → 1
PostgreSQL 100 8.610 ms 0.749 ms 11 → 1
PostgreSQL 1,000 15.994 ms 0.807 ms 11 → 1
PostgreSQL 10,000 89.083 ms 0.708 ms 11 → 1

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):

Backend Old bytes/op Indexed bytes/op Old allocs/op Indexed allocs/op
SQLite 26,681,825 15,721 46,989 246
PostgreSQL 28,786,513 16,560 46,857 231

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 uses idx_clients_tg_id, idx_client_inbounds_client_id, and uni_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 reports action_required before any jobs start. This fork account has read-only permission on upstream and cannot approve fork runs. The follow-up CI run for a6f03252 also reports action_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.md remain untouched. This branch is based directly on upstream main and 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.

## 📋 Pull Request Information **Original PR:** https://github.com/MHSanaei/3x-ui/pull/6887 **Author:** [@HamedSanaei](https://github.com/HamedSanaei) **Created:** 10/21/2026 **Status:** ✅ Merged **Merged:** 10/24/2026 **Merged by:** [@MHSanaei](https://github.com/MHSanaei) **Base:** `main` ← **Head:** `fix/tgbot-lookup-performance` --- ### 📝 Commits (5) - [`d24c097`](https://github.com/MHSanaei/3x-ui/commit/d24c097e4733068744179a31254ff7274fa9c609) fix(tgbot): optimize Telegram client lookup and notification deduplication - [`a6f0325`](https://github.com/MHSanaei/3x-ui/commit/a6f03252d33b22a32961ef63e6b9e04a7370bc18) chore(tgbot): address benchmark maintenance and PostgreSQL CI review - [`b623f21`](https://github.com/MHSanaei/3x-ui/commit/b623f21c8c1f74aae0ef790993287f871ea11b61) fix(deps): update Go and DOMPurify security patches - [`86f368c`](https://github.com/MHSanaei/3x-ui/commit/86f368c8f17325ae6d1fdd8ff545163e6ef60dbc) Merge remote-tracking branch 'origin/main' into pr/6887 - [`d82323d`](https://github.com/MHSanaei/3x-ui/commit/d82323d78c2c3d10db3f53753b5bce25290abcfd) test(tgbot): keep the indexed lookup tests with the existing lookup and report tests ### 📊 Changes **9 files changed** (+378 additions, -85 deletions) <details> <summary>View changed files</summary> 📝 `.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) </details> ### 📄 Description ## Summary Replace Telegram client traffic lookups that expand every inbound's settings JSON with a single query filtered by the existing `clients.tg_id` index. 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 - Join normalized `clients` to `client_traffics`, filter by `clients.tg_id`, and use `EXISTS` over `client_inbounds` and live inbounds to require a valid attachment without duplicating multi-inbound clients. Return records in client ID order. Stale legacy `client_traffics.inbound_id` pointers do not prevent a valid normalized attachment from being found. - Read `Enable`, `UUID`, and `SubId` from 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. - Use a per-pass `map[int64]struct{}` and mark eligible IDs before lookup. Log lookup errors once per ID. Discover notification recipients through `ListClientsForInbound`, so stale JSON ownership cannot suppress a current owner's notification. Notification text and threshold calculations remain unchanged. - Remove the slice membership helper that became unused. ## Compatibility The existing `ClientsTable` startup 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_SettingsSerializationStyles` still 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` - Targeted lookup, notification and ownership tests with `-race -shuffle=on -count=1` - `golangci-lint run --timeout 10m`: **0 issues** - PostgreSQL lookup and legacy startup migration tests in a disposable local PostgreSQL 16 container - Follow-up: full shuffled Go suite rerun successfully, new PostgreSQL CI test command/pass-count check executed with two passes, and `actionlint .github/workflows/ci.yml` passed. 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](https://github.com/MHSanaei/3x-ui/pull/6887#issuecomment-6314025548): removed `inbound_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_IndexedPostgres` and `TestGetClientTrafficTgBot_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-only `InboundService` method and requiring `reflect.DeepEqual` against it would unnecessarily constrain future changes. To reproduce the historical comparison, use a separate disposable worktree at that commit, then run: ```sh go test ./internal/web/service -run '^$' -bench '^BenchmarkGetClientTrafficTgBot$' -benchmem -benchtime=500ms -count=3 ``` For PostgreSQL, set `XUI_DB_TYPE=postgres` and `XUI_DB_DSN` to an isolated disposable test database and add `-v` to 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: | Backend | Total clients | Old hit | Indexed hit | SQL statements per hit | | --- | ---: | ---: | ---: | ---: | | SQLite | 100 | 0.957 ms | 0.049 ms | 11 → 1 | | SQLite | 1,000 | 5.292 ms | 0.056 ms | 11 → 1 | | SQLite | 10,000 | 48.174 ms | 0.055 ms | 11 → 1 | | PostgreSQL | 100 | 8.610 ms | 0.749 ms | 11 → 1 | | PostgreSQL | 1,000 | 15.994 ms | 0.807 ms | 11 → 1 | | PostgreSQL | 10,000 | 89.083 ms | 0.708 ms | 11 → 1 | 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): | Backend | Old bytes/op | Indexed bytes/op | Old allocs/op | Indexed allocs/op | | --- | ---: | ---: | ---: | ---: | | SQLite | 26,681,825 | 15,721 | 46,989 | 246 | | PostgreSQL | 28,786,513 | 16,560 | 46,857 | 231 | 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 uses `idx_clients_tg_id`, `idx_client_inbounds_client_id`, and `uni_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](https://github.com/MHSanaei/3x-ui/actions/runs/39586175590) reports `action_required` before any jobs start. This fork account has read-only permission on upstream and cannot approve fork runs. The follow-up [CI run for `a6f03252`](https://github.com/MHSanaei/3x-ui/actions/runs/39614503014) also reports `action_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.md` remain untouched. This branch is based directly on upstream `main` and contains only this issue's source and tests. --- <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:13 +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#6499
No description provided.