[GH-ISSUE #6116] [Bug]: pickClientsSummary's snapshot-coverage guard is a count check, not identity — an orphan+gap pair cancels out and slips through #4225

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

Originally created by @mrnickson-hue on GitHub (Jul 27, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6116

Describe the bug

Follow-up from #6110's review — a bot-reviewer finding that was agreed as real but deliberately deferred there as out of scope, tracked here per that PR's own discussion instead of being silently forgotten.

pickClientsSummary (frontend/src/hooks/useClients.ts:120, introduced in #6110) guards the live client-summary recompute with a coverage check at line 128:

if (serverSummary.total > allClientStats.length) return serverSummary;

This is a count comparison, not an identity/coverage check. serverSummary.total counts rows in the clients table; allClientStats is the client_traffics WebSocket snapshot, which can contain orphaned rows (traffic rows with no matching clients row — the exact class #6110 is about) and can be missing rows for clients that exist in clients but have no client_traffics row yet.

If there's simultaneously one orphaned row (inflating allClientStats.length by one) and one client missing its row (deflating it by one), the two cancel out numerically. The guard sees serverSummary.total === allClientStats.length, concludes coverage is complete, and proceeds with the live recompute — which still drops the real, uncovered client from every summary bucket while additionally bucketing the orphan under some other category. The check that exists specifically to catch an incomplete snapshot doesn't catch this shape of incompleteness.

How to reproduce the problem

  1. Get the panel into a state with one orphaned client_traffics row (no matching clients row) and, simultaneously, one clients row with no matching client_traffics row. (clients/client_traffics can drift apart via the seeder-skip and migration paths discussed in #6110's review.)
  2. Trigger a client_stats WebSocket broadcast (any XrayTrafficJob tick with websocket.HasClients() true).
  3. Compare the live-recomputed summary buckets against the true state: the real client that's missing its traffic row won't appear in any bucket (Active/Ended/Disabled/etc.), while the orphaned row will be bucketed as if it were a real client — with no warning surfaced, because the guard's count check happened to balance.

Expected behavior

An incomplete or inconsistent snapshot should be detected regardless of whether the imbalance happens to net out to zero, and the guard should fall back to serverSummary in that case too — not just when the counts visibly disagree.

Actual behavior

The guard is fooled by a shortfall and a surplus of matching magnitude occurring at the same time, and the frontend proceeds to recompute a subtly wrong live summary.

Relevant logs

N/A — code-review finding (from #6110's automated review, confirmed by reading the source), not caught from a live incident.

3x-ui version

Not yet released — applies to the fix/6102-orphaned-traffics-and-summary branch (#6110), which introduces pickClientsSummary.

How did you install 3x-ui?

Other (please describe in the bug body)

N/A — source-level finding, not install-specific.

Operating system

N/A

Which parts of the panel are affected?

Frontend (UI / panel pages), Statistics / traffic counters

Is the panel behind a reverse proxy or CDN?

No — direct access

Possible fix direction

As the reviewer on #6110 put it: the robust fix is for the server to ship the summary buckets alongside the client_stats payload instead of the frontend re-deriving them from a snapshot whose coverage it can only approximate. There's already a precedent for this in the same job: XrayTrafficJob.Run() computes GetInboundsTrafficSummary() server-side and ships it in the same WebSocket payload (internal/web/job/xray_traffic_job.go) rather than asking the frontend to derive inbound totals from raw traffic rows. Doing the same for the client-status buckets (Active/Ended/Disabled/Expiring/Online — whatever computeClientsSummary currently derives client-side) would remove the need for a coverage heuristic entirely, since the server always has full, authoritative clients/client_traffics state.

If a maintainer's fine with that direction, happy to open a PR.

Before submitting

  • I searched existing issues and this bug has not been reported.
  • I am running the latest released version of 3x-ui (not applicable — this is a source-level finding on the unmerged fix/6102-orphaned-traffics-and-summary branch, #6110; the affected code doesn't exist in any released version yet).
  • This bug report is written in English.
  • I have redacted any sensitive data (tokens, real domains, IPs, client UUIDs).
Originally created by @mrnickson-hue on GitHub (Jul 27, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6116 ### Describe the bug Follow-up from #6110's review — a bot-reviewer finding that was agreed as real but deliberately deferred there as out of scope, tracked here per that PR's own discussion instead of being silently forgotten. `pickClientsSummary` (`frontend/src/hooks/useClients.ts:120`, introduced in #6110) guards the live client-summary recompute with a coverage check at line 128: ```ts if (serverSummary.total > allClientStats.length) return serverSummary; ``` This is a **count comparison, not an identity/coverage check**. `serverSummary.total` counts rows in the `clients` table; `allClientStats` is the `client_traffics` WebSocket snapshot, which can contain orphaned rows (traffic rows with no matching `clients` row — the exact class #6110 is about) and can be missing rows for clients that exist in `clients` but have no `client_traffics` row yet. If there's simultaneously one orphaned row (inflating `allClientStats.length` by one) and one client missing its row (deflating it by one), the two cancel out numerically. The guard sees `serverSummary.total === allClientStats.length`, concludes coverage is complete, and proceeds with the live recompute — which still drops the real, uncovered client from every summary bucket while additionally bucketing the orphan under some other category. The check that exists specifically to catch an incomplete snapshot doesn't catch this shape of incompleteness. ### How to reproduce the problem 1. Get the panel into a state with one orphaned `client_traffics` row (no matching `clients` row) and, simultaneously, one `clients` row with no matching `client_traffics` row. (`clients`/`client_traffics` can drift apart via the seeder-skip and migration paths discussed in #6110's review.) 2. Trigger a `client_stats` WebSocket broadcast (any `XrayTrafficJob` tick with `websocket.HasClients()` true). 3. Compare the live-recomputed summary buckets against the true state: the real client that's missing its traffic row won't appear in any bucket (Active/Ended/Disabled/etc.), while the orphaned row will be bucketed as if it were a real client — with no warning surfaced, because the guard's count check happened to balance. ### Expected behavior An incomplete or inconsistent snapshot should be detected regardless of whether the imbalance happens to net out to zero, and the guard should fall back to `serverSummary` in that case too — not just when the counts visibly disagree. ### Actual behavior The guard is fooled by a shortfall and a surplus of matching magnitude occurring at the same time, and the frontend proceeds to recompute a subtly wrong live summary. ### Relevant logs N/A — code-review finding (from #6110's automated review, confirmed by reading the source), not caught from a live incident. ### 3x-ui version Not yet released — applies to the `fix/6102-orphaned-traffics-and-summary` branch (#6110), which introduces `pickClientsSummary`. ### How did you install 3x-ui? Other (please describe in the bug body) N/A — source-level finding, not install-specific. ### Operating system N/A ### Which parts of the panel are affected? Frontend (UI / panel pages), Statistics / traffic counters ### Is the panel behind a reverse proxy or CDN? No — direct access ### Possible fix direction As the reviewer on #6110 put it: the robust fix is for the server to ship the summary buckets alongside the `client_stats` payload instead of the frontend re-deriving them from a snapshot whose coverage it can only approximate. There's already a precedent for this in the same job: `XrayTrafficJob.Run()` computes `GetInboundsTrafficSummary()` server-side and ships it in the same WebSocket payload (`internal/web/job/xray_traffic_job.go`) rather than asking the frontend to derive inbound totals from raw traffic rows. Doing the same for the client-status buckets (Active/Ended/Disabled/Expiring/Online — whatever `computeClientsSummary` currently derives client-side) would remove the need for a coverage heuristic entirely, since the server always has full, authoritative `clients`/`client_traffics` state. If a maintainer's fine with that direction, happy to open a PR. ### Before submitting - [x] I searched existing issues and this bug has not been reported. - [ ] I am running the latest released version of 3x-ui (not applicable — this is a source-level finding on the unmerged `fix/6102-orphaned-traffics-and-summary` branch, #6110; the affected code doesn't exist in any released version yet). - [x] This bug report is written in English. - [x] I have redacted any sensitive data (tokens, real domains, IPs, client UUIDs).
bsakaguchi 2026-10-31 20:38:07 +07:00
  • closed this issue
  • added the
    bug
    label
Author
Owner

@github-actions[bot] commented on GitHub (Jul 27, 2026):

Confirmed, and the guard is weaker than described here: it is asymmetric, so a surplus of orphaned rows on its own — with no compensating gap — also slips through. The simultaneous orphan+gap pair is not required.

I could not read the unmerged fix/6102-orphaned-traffics-and-summary branch directly in this environment, so the confirmation rests on the predicate as quoted in this report and in #6110's review thread (both quote it identically, and #6110's author confirmed it was left unchanged), plus the base-branch source for both of its operands, which #6110 does not modify.

Title: pickClientsSummary's coverage guard compares row counts across two different tables, so it only fires on a net shortfall

Severity: Medium

Category: Correctness

Why this matters:

The two operands are counts of different tables, and neither is a subset of the other.

  • serverSummary.total is len(all) over every row of clients (internal/web/service/client_paging.go:226-228). It is fed by ClientService.List() (internal/web/service/client_lookup.go:126-181), which starts from an unfiltered Find over clients and attaches Traffic from a map lookup — trafficByEmail[rows[i].Email] at line 177 is simply nil when the client has no client_traffics row. It is also computed at client_paging.go:149, before the filter loop at line 153, so it is the unfiltered clients total.
  • allClientStats is the entire client_traffics table: GetAllClientTraffics() (internal/web/service/inbound_traffic.go:995-1003) is an unfiltered Find with no join to clients, broadcast from internal/web/job/xray_traffic_job.go:141-142 and 179-190. The frontend only replaces the array when snapshot !== false (frontend/src/hooks/useClients.ts:577 on main), so it is always a full table dump.

The difference between them is therefore orphans − gaps, and total > length can only detect a net gap surplus. Two cases pass it:

  1. The netting case in this report (orphans == gaps).
  2. Orphans with no gaps at all (orphans > 0, gaps == 0), which gives total < length. This is the more reachable one, because orphaned client_traffics rows are precisely the state #6102 and #6110 are about, and it needs drift in only one direction rather than two at once.

In both cases the recompute proceeds, and an orphan is indistinguishable from a real client to computeClientsSummary: xray.ClientTraffic (internal/xray/client_traffic.go:5-18) carries Enable, Email, Up, Down, ExpiryTime and Total, which is every field the bucketing loop at frontend/src/hooks/useClients.ts:102-116 reads. The orphan lands in a bucket while the headline count still comes from the server's clients total, so buckets and headline can disagree — the original #6102 symptom.

Recommendation:

The direction proposed here checks out against the source. XrayTrafficJob.Run() already computes GetInboundsTrafficSummary() server-side and ships it in the same client_stats payload under the inbounds key (internal/web/job/xray_traffic_job.go:183-187), so a summary key computed by buildClientsSummary would follow an existing shape in the same function and remove the heuristic entirely. Two practical notes for whoever picks this up:

  • buildClientsSummary is unexported and needs onlineSet plus expireDiffMs/trafficDiffBytes. The job already holds settingService (GetExpireDiff/GetTrafficDiff) and already calls j.inboundService.GetOnlineClients() at xray_traffic_job.go:166, so only a ClientService and a small exported wrapper are missing.
  • Cost is the open question, not correctness. ClientService.List() is a full clients scan plus the client_inbounds and client_traffics lookups, and it would run on every traffic tick. clientStatsSnapshotMaxClients = 5000 (xray_traffic_job.go:29) exists for exactly this kind of per-tick weight, so the server-side summary may need a comparable bound or a cheaper aggregate query rather than reusing List().

Example:

frontend/src/hooks/useClients.ts — pickClientsSummary (#6110)

  if (serverSummary.total > allClientStats.length) return serverSummary;

  serverSummary.total  -> COUNT(clients)          (client_paging.go:228)
  allClientStats.length-> COUNT(client_traffics)  (inbound_traffic.go:995)

  orphans=0, gaps=1  -> total > length  -> guard fires   (caught today)
  orphans=1, gaps=1  -> total = length  -> guard passes  (this report)
  orphans=1, gaps=0  -> total < length  -> guard passes  (also uncaught)

Confidence is high on the base-branch facts above, which I read directly, and on the reasoning about the quoted predicate. It is lower only on the exact line numbers on the branch, which shifted after the comment removal in #6110's follow-up commit.

Related, not duplicate: #6102 is the reported symptom and #6110 the migration fix; this is the residual frontend gap that #6110's discussion agreed to defer. Labelled bug and left open for a maintainer's decision on the server-side-summary direction.

@MHSanaei

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:5086361498 --> @github-actions[bot] commented on GitHub (Jul 27, 2026): Confirmed, and the guard is weaker than described here: it is asymmetric, so a surplus of orphaned rows on its own — with no compensating gap — also slips through. The simultaneous orphan+gap pair is not required. I could not read the unmerged `fix/6102-orphaned-traffics-and-summary` branch directly in this environment, so the confirmation rests on the predicate as quoted in this report and in #6110's review thread (both quote it identically, and #6110's author confirmed it was left unchanged), plus the base-branch source for both of its operands, which #6110 does not modify. Title: `pickClientsSummary`'s coverage guard compares row counts across two different tables, so it only fires on a net shortfall Severity: Medium Category: Correctness Why this matters: The two operands are counts of different tables, and neither is a subset of the other. - `serverSummary.total` is `len(all)` over every row of `clients` (`internal/web/service/client_paging.go:226-228`). It is fed by `ClientService.List()` (`internal/web/service/client_lookup.go:126-181`), which starts from an unfiltered `Find` over `clients` and attaches `Traffic` from a map lookup — `trafficByEmail[rows[i].Email]` at line 177 is simply `nil` when the client has no `client_traffics` row. It is also computed at `client_paging.go:149`, before the filter loop at line 153, so it is the unfiltered clients total. - `allClientStats` is the entire `client_traffics` table: `GetAllClientTraffics()` (`internal/web/service/inbound_traffic.go:995-1003`) is an unfiltered `Find` with no join to `clients`, broadcast from `internal/web/job/xray_traffic_job.go:141-142` and `179-190`. The frontend only replaces the array when `snapshot !== false` (`frontend/src/hooks/useClients.ts:577` on `main`), so it is always a full table dump. The difference between them is therefore `orphans − gaps`, and `total > length` can only detect a net gap surplus. Two cases pass it: 1. The netting case in this report (`orphans == gaps`). 2. Orphans with no gaps at all (`orphans > 0`, `gaps == 0`), which gives `total < length`. This is the more reachable one, because orphaned `client_traffics` rows are precisely the state #6102 and #6110 are about, and it needs drift in only one direction rather than two at once. In both cases the recompute proceeds, and an orphan is indistinguishable from a real client to `computeClientsSummary`: `xray.ClientTraffic` (`internal/xray/client_traffic.go:5-18`) carries `Enable`, `Email`, `Up`, `Down`, `ExpiryTime` and `Total`, which is every field the bucketing loop at `frontend/src/hooks/useClients.ts:102-116` reads. The orphan lands in a bucket while the headline count still comes from the server's `clients` total, so buckets and headline can disagree — the original #6102 symptom. Recommendation: The direction proposed here checks out against the source. `XrayTrafficJob.Run()` already computes `GetInboundsTrafficSummary()` server-side and ships it in the same `client_stats` payload under the `inbounds` key (`internal/web/job/xray_traffic_job.go:183-187`), so a `summary` key computed by `buildClientsSummary` would follow an existing shape in the same function and remove the heuristic entirely. Two practical notes for whoever picks this up: - `buildClientsSummary` is unexported and needs `onlineSet` plus `expireDiffMs`/`trafficDiffBytes`. The job already holds `settingService` (`GetExpireDiff`/`GetTrafficDiff`) and already calls `j.inboundService.GetOnlineClients()` at `xray_traffic_job.go:166`, so only a `ClientService` and a small exported wrapper are missing. - Cost is the open question, not correctness. `ClientService.List()` is a full `clients` scan plus the `client_inbounds` and `client_traffics` lookups, and it would run on every traffic tick. `clientStatsSnapshotMaxClients = 5000` (`xray_traffic_job.go:29`) exists for exactly this kind of per-tick weight, so the server-side summary may need a comparable bound or a cheaper aggregate query rather than reusing `List()`. Example: ``` frontend/src/hooks/useClients.ts — pickClientsSummary (#6110) if (serverSummary.total > allClientStats.length) return serverSummary; serverSummary.total -> COUNT(clients) (client_paging.go:228) allClientStats.length-> COUNT(client_traffics) (inbound_traffic.go:995) orphans=0, gaps=1 -> total > length -> guard fires (caught today) orphans=1, gaps=1 -> total = length -> guard passes (this report) orphans=1, gaps=0 -> total < length -> guard passes (also uncaught) ``` Confidence is high on the base-branch facts above, which I read directly, and on the reasoning about the quoted predicate. It is lower only on the exact line numbers on the branch, which shifted after the comment removal in #6110's follow-up commit. Related, not duplicate: #6102 is the reported symptom and #6110 the migration fix; this is the residual frontend gap that #6110's discussion agreed to defer. Labelled `bug` and left open for a maintainer's decision on the server-side-summary direction. @MHSanaei *This reply was generated automatically; a maintainer may follow up.*
Author
Owner

@mrnickson-hue commented on GitHub (Jul 27, 2026):

Agreed this is worth doing as its own PR rather than folding into #6110 — the performance question you raised (ClientService.List() on every 5s tick needs a bound or a cheaper aggregate, not a straight reuse) deserves its own design pass rather than being rushed as an addendum to an already-reviewed PR.

Once #6110 is merged and out in a release, I'm happy to pick this up: server-side client-status summary shipped alongside client_stats (mirroring how GetInboundsTrafficSummary already rides along in the same payload), with the ClientService/exported-wrapper wiring you outlined, and a cost-bound appropriate for the per-tick cadence. Will post here before starting in case anything's shifted in the meantime.

<!-- gh-comment-id:5086412746 --> @mrnickson-hue commented on GitHub (Jul 27, 2026): Agreed this is worth doing as its own PR rather than folding into #6110 — the performance question you raised (`ClientService.List()` on every 5s tick needs a bound or a cheaper aggregate, not a straight reuse) deserves its own design pass rather than being rushed as an addendum to an already-reviewed PR. Once #6110 is merged and out in a release, I'm happy to pick this up: server-side client-status summary shipped alongside `client_stats` (mirroring how `GetInboundsTrafficSummary` already rides along in the same payload), with the `ClientService`/exported-wrapper wiring you outlined, and a cost-bound appropriate for the per-tick cadence. Will post here before starting in case anything's shifted in the meantime.
Author
Owner

@MHSanaei commented on GitHub (Jul 27, 2026):

Leaving this open and unchanged by the current triage sweep, for one reason worth stating explicitly: pickClientsSummary does not exist on main. It is introduced by #6110, so there is nothing to fix at HEAD and no released version is affected — the "3x-ui version: not yet released" in the report is accurate.

The finding itself holds, and the sequencing you and the reviewer agreed on is the right one: land #6110 first, then do the server-side summary as its own change. The performance question raised there is the real design work — ClientService.List() is a full clients scan plus the client_inbounds and client_traffics lookups, and running it on every 5s tick needs a bound or a cheaper aggregate query rather than a straight reuse. clientStatsSnapshotMaxClients = 5000 exists for exactly that kind of per-tick weight and is the precedent to follow.

Thanks for opening it separately rather than letting it disappear into a review thread — that is the right call, and the offer to pick it up after #6110 ships is appreciated.

<!-- gh-comment-id:5091442705 --> @MHSanaei commented on GitHub (Jul 27, 2026): Leaving this open and unchanged by the current triage sweep, for one reason worth stating explicitly: `pickClientsSummary` does not exist on `main`. It is introduced by #6110, so there is nothing to fix at HEAD and no released version is affected — the "3x-ui version: not yet released" in the report is accurate. The finding itself holds, and the sequencing you and the reviewer agreed on is the right one: land #6110 first, then do the server-side summary as its own change. The performance question raised there is the real design work — `ClientService.List()` is a full `clients` scan plus the `client_inbounds` and `client_traffics` lookups, and running it on every 5s tick needs a bound or a cheaper aggregate query rather than a straight reuse. `clientStatsSnapshotMaxClients = 5000` exists for exactly that kind of per-tick weight and is the precedent to follow. Thanks for opening it separately rather than letting it disappear into a review thread — that is the right call, and the offer to pick it up after #6110 ships is appreciated.
Author
Owner

@mrnickson-hue commented on GitHub (Jul 27, 2026):

Sounds good — will wait for #6110 to land and then follow up here with a PR for the server-side summary, bounded per the clientStatsSnapshotMaxClients precedent. Thanks for the quick, thorough look at all three of these threads today.

<!-- gh-comment-id:5092236082 --> @mrnickson-hue commented on GitHub (Jul 27, 2026): Sounds good — will wait for #6110 to land and then follow up here with a PR for the server-side summary, bounded per the `clientStatsSnapshotMaxClients` precedent. Thanks for the quick, thorough look at all three of these threads today.
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#4225
No description provided.