[GH-ISSUE #5567] [Bug]: {{TRAFFIC_USED}} and {{{TRAFFIC_LEFT}} variable always displays 0.00B for clients created before v3.4.0 update #3886

Closed
opened 2026-10-31 20:35:40 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @tradeahadi-cmyk on GitHub (Jun 25, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/5567

Describe the bug

Description

After updating the panel to version 3.4.0, I noticed a backward compatibility issue with the new {{TRAFFIC_USED}} variable in the subscription template.

When using a template like this:
{{INBOUND}} 📊{{TRAFFIC_USED}} / {{TRAFFIC_LEFT}} 📅 Expiry: {{EXPIRE_DATE}}

The variable {{TRAFFIC_USED}} fails to show the correct usage for any client that was created before the v3.4.0 update, always remaining at 0.00B.

Behavior & Observations

  • Old Clients (Pre-3.4.0): The {{TRAFFIC_USED}} variable always displays 0.00B in the subscription link/remark, regardless of their actual usage.
  • New Clients (Post-3.4.0): The variable works perfectly and displays the exact used traffic.
  • Other Variables: {{TRAFFIC_LEFT}} and {{EXPIRE_DATE}} work perfectly for ALL clients (both old and new).
  • Panel Web UI: The "Clients" page correctly displays the actual traffic usage (up + down) for everyone, meaning the core data exists in the database.

What I've Tried (Troubleshooting)

I tried the following actions on the older clients, but none of them fixed the issue:

  1. Resetting the client's traffic.
  2. Editing and saving the old client again.

Suspected Cause

It seems like a database migration/backward compatibility issue. The migration script likely missed recalculating or mapping the existing up and down sum into the new field/logic that {{TRAFFIC_USED}} relies on for clients created prior to v3.4.0.

How to reproduce the problem

show traffic for old clients

Expected behavior

No response

Actual behavior

No response

Relevant logs


Screenshots

No response

3x-ui version

3.4.0

Xray-core version

No response

How did you install 3x-ui?

install.sh script

Operating system

ubuntu 24

Which parts of the panel are affected?

No response

Browser (only if it is a UI bug)

No response

Is the panel behind a reverse proxy or CDN?

None

Before submitting

  • I searched existing issues and this bug has not been reported.
  • I am running the latest released version of 3x-ui (or have verified the bug still exists on it).
  • This bug report is written in English.
  • I have redacted any sensitive data (tokens, real domains, client UUIDs).
Originally created by @tradeahadi-cmyk on GitHub (Jun 25, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/5567 ### Describe the bug ### Description After updating the panel to version 3.4.0, I noticed a backward compatibility issue with the new `{{TRAFFIC_USED}}` variable in the subscription template. When using a template like this: `{{INBOUND}} 📊{{TRAFFIC_USED}} / {{TRAFFIC_LEFT}} 📅 Expiry: {{EXPIRE_DATE}}` The variable `{{TRAFFIC_USED}}` fails to show the correct usage for any client that was created **before** the v3.4.0 update, always remaining at `0.00B`. ### Behavior & Observations - **Old Clients (Pre-3.4.0):** The `{{TRAFFIC_USED}}` variable always displays `0.00B` in the subscription link/remark, regardless of their actual usage. - **New Clients (Post-3.4.0):** The variable works perfectly and displays the exact used traffic. - **Other Variables:** `{{TRAFFIC_LEFT}}` and `{{EXPIRE_DATE}}` work perfectly for ALL clients (both old and new). - **Panel Web UI:** The "Clients" page correctly displays the actual traffic usage (`up` + `down`) for everyone, meaning the core data exists in the database. ### What I've Tried (Troubleshooting) I tried the following actions on the older clients, but none of them fixed the issue: 1. Resetting the client's traffic. 2. Editing and saving the old client again. ### Suspected Cause It seems like a database migration/backward compatibility issue. The migration script likely missed recalculating or mapping the existing `up` and `down` sum into the new field/logic that `{{TRAFFIC_USED}}` relies on for clients created prior to v3.4.0. ### How to reproduce the problem show traffic for old clients ### Expected behavior _No response_ ### Actual behavior _No response_ ### Relevant logs ```shell ``` ### Screenshots _No response_ ### 3x-ui version 3.4.0 ### Xray-core version _No response_ ### How did you install 3x-ui? install.sh script ### Operating system ubuntu 24 ### Which parts of the panel are affected? _No response_ ### Browser (only if it is a UI bug) _No response_ ### Is the panel behind a reverse proxy or CDN? None ### Before submitting - [x] I searched [existing issues](../issues?q=is%3Aissue) and this bug has not been reported. - [x] I am running the latest released version of 3x-ui (or have verified the bug still exists on it). - [x] This bug report is written in English. - [x] I have redacted any sensitive data (tokens, real domains, client UUIDs).
bsakaguchi 2026-10-31 20:35:40 +07:00
  • closed this issue
  • added the
    bug
    label
Author
Owner

@github-actions[bot] commented on GitHub (Jun 25, 2026):

Root cause of {{TRAFFIC_USED}} always showing 0.00B for pre-v3.4.0 clients

The behavior you're seeing is caused by a lookup discrepancy introduced by v3.4.0's new normalized client tables.


How {{TRAFFIC_USED}} is resolved

{{TRAFFIC_USED}} is expanded in internal/sub/remark_vars.go:189–190:

case "TRAFFIC_USED":
    return common.FormatTraffic(used)  // used = st.Up + st.Down

where st is the xray.ClientTraffic struct returned by statsForClient() (line 432):

func (s *SubService) statsForClient(inbound *model.Inbound, client model.Client) xray.ClientTraffic {
    if stats, ok := s.findClientStats(inbound, client.Email); ok {
        return stats  // path 1: inbound's preloaded ClientStats
    }
    if stats, ok := s.statsByEmail[client.Email]; ok {
        return stats  // path 2: per-request email index
    }
    // FALLBACK: synthesized from client model — Up = 0, Down = 0
    return xray.ClientTraffic{
        Enable:     client.Enable,
        ExpiryTime: client.ExpiryTime,  // → EXPIRE_DATE is still correct
        Total:      client.TotalGB,     // → TRAFFIC_LEFT = ∞ for unlimited clients
    }
}

When both Path 1 and Path 2 fail the fallback runs with Up = 0, Down = 0, which is why {{TRAFFIC_USED}} shows 0.00B while {{EXPIRE_DATE}} and {{TRAFFIC_LEFT}} (∞ for unlimited clients) continue to look correct — those come from the client record in the fallback, not from the traffic row.


Why both lookup paths fail for old clients

getInboundsBySubId() (internal/sub/service.go) loads inbounds using the new client_inbounds/clients join tables introduced in v3.4.0, then preloads traffic rows with Preload("ClientStats"), which translates to:

SELECT * FROM client_traffics WHERE inbound_id IN (<loaded inbound IDs>)

The statsByEmail email index (Path 2) is built from exactly these same preloaded rows.

The constraint: both lookup paths require client_traffics.inbound_id to match the ID of one of the loaded inbounds.

client_traffics.inbound_id is written once when AddClientStat() first creates the row (internal/web/service/inbound_traffic.go:448–458) and never updated again:

return tx.Clauses(clause.OnConflict{
    Columns:   []clause.Column{{Name: "email"}},
    DoNothing: true,  // existing row is never touched
}).Create(&clientTraffic).Error

UpdateClientStat() (line 461) also skips inbound_id:

Updates(map[string]any{
    "enable": ..., "email": ..., "total": ..., "expiry_time": ..., "reset": ...,
    // inbound_id: absent
})

If an inbound was deleted and recreated at any point — a common operation when reconfiguring — the new inbound receives a new auto-increment ID. The old client_traffics.inbound_id is now orphaned. After the v3.4.0 upgrade, getInboundsBySubId loads the new inbound and its Preload("ClientStats") finds no rows for the affected clients, so both paths miss and the fallback returns zeros.

This also explains why the Clients panel shows correct traffic (GetAllClientTraffics / AggregateTrafficByEmails query client_traffics directly by email with no inbound_id filter) while the subscription remark template does not.


Why editing/resetting a client does not help

UpdateClientStat() never updates inbound_id, so a stale value persists through any number of client edits or traffic resets.

x-ui migrate-db is also not a fix here: MigrationRequirements() (internal/web/service/inbound_migration.go:163–176) only calls AddClientStat when a client has no existing row (count == 0). For clients with existing rows — all old clients with any historical traffic — neither inbound_id nor any field is changed.


Diagnostic query

Run against the SQLite DB (stop the panel first; DB is at /etc/x-ui/x-ui.db):

SELECT ct.email,
       ct.inbound_id          AS traffic_row_inbound_id,
       ci.inbound_id          AS linked_inbound_id,
       i.id IS NULL           AS old_inbound_gone,
       ct.up + ct.down        AS bytes_used
FROM client_traffics ct
LEFT JOIN clients      c  ON c.email           = ct.email
LEFT JOIN client_inbounds ci ON ci.client_id   = c.id
LEFT JOIN inbounds      i  ON i.id             = ct.inbound_id
WHERE (ct.up + ct.down) > 0
ORDER BY old_inbound_gone DESC
LIMIT 20;

Rows where old_inbound_gone = 1 confirm the orphaned-inbound_id root cause.


Workaround

Back up your database first:

cp /etc/x-ui/x-ui.db /etc/x-ui/x-ui.db.bak

Then, with the panel stopped, open the DB with sqlite3 /etc/x-ui/x-ui.db and run:

UPDATE client_traffics
SET inbound_id = (
    SELECT ci.inbound_id
    FROM client_inbounds ci
    JOIN clients c ON c.id = ci.client_id
    WHERE c.email = client_traffics.email
    ORDER BY ci.inbound_id
    LIMIT 1
)
WHERE inbound_id NOT IN (SELECT id FROM inbounds)
  AND EXISTS (
    SELECT 1 FROM client_inbounds ci
    JOIN clients c ON c.id = ci.client_id
    WHERE c.email = client_traffics.email
  );

This only updates rows whose referenced inbound no longer exists, pointing them to a currently-valid inbound from client_inbounds. Rows with a still-valid inbound_id are left untouched.


Proper fix

A permanent fix would modify statsForClient() to add a direct email-based DB lookup as a last resort before returning the zero-traffic placeholder — the same strategy the panel's Clients page already uses for GetAllClientTraffics().


Auto-generated by triage bot — all claims are grounded in source read at commit e4b881e.

<!-- gh-comment-id:4801396060 --> @github-actions[bot] commented on GitHub (Jun 25, 2026): ## Root cause of `{{TRAFFIC_USED}}` always showing `0.00B` for pre-v3.4.0 clients The behavior you're seeing is caused by a lookup discrepancy introduced by v3.4.0's new normalized client tables. --- ### How `{{TRAFFIC_USED}}` is resolved `{{TRAFFIC_USED}}` is expanded in `internal/sub/remark_vars.go:189–190`: ```go case "TRAFFIC_USED": return common.FormatTraffic(used) // used = st.Up + st.Down ``` where `st` is the `xray.ClientTraffic` struct returned by `statsForClient()` (line 432): ```go func (s *SubService) statsForClient(inbound *model.Inbound, client model.Client) xray.ClientTraffic { if stats, ok := s.findClientStats(inbound, client.Email); ok { return stats // path 1: inbound's preloaded ClientStats } if stats, ok := s.statsByEmail[client.Email]; ok { return stats // path 2: per-request email index } // FALLBACK: synthesized from client model — Up = 0, Down = 0 return xray.ClientTraffic{ Enable: client.Enable, ExpiryTime: client.ExpiryTime, // → EXPIRE_DATE is still correct Total: client.TotalGB, // → TRAFFIC_LEFT = ∞ for unlimited clients } } ``` When both Path 1 and Path 2 fail the fallback runs with `Up = 0, Down = 0`, which is why `{{TRAFFIC_USED}}` shows `0.00B` while `{{EXPIRE_DATE}}` and `{{TRAFFIC_LEFT}}` (∞ for unlimited clients) continue to look correct — those come from the client record in the fallback, not from the traffic row. --- ### Why both lookup paths fail for old clients `getInboundsBySubId()` (`internal/sub/service.go`) loads inbounds using the **new `client_inbounds`/`clients` join tables introduced in v3.4.0**, then preloads traffic rows with `Preload("ClientStats")`, which translates to: ```sql SELECT * FROM client_traffics WHERE inbound_id IN (<loaded inbound IDs>) ``` The `statsByEmail` email index (Path 2) is built from exactly these same preloaded rows. **The constraint**: both lookup paths require `client_traffics.inbound_id` to match the ID of one of the loaded inbounds. `client_traffics.inbound_id` is written **once** when `AddClientStat()` first creates the row (`internal/web/service/inbound_traffic.go:448–458`) and **never updated again**: ```go return tx.Clauses(clause.OnConflict{ Columns: []clause.Column{{Name: "email"}}, DoNothing: true, // existing row is never touched }).Create(&clientTraffic).Error ``` `UpdateClientStat()` (line 461) also skips `inbound_id`: ```go Updates(map[string]any{ "enable": ..., "email": ..., "total": ..., "expiry_time": ..., "reset": ..., // inbound_id: absent }) ``` If an inbound was **deleted and recreated** at any point — a common operation when reconfiguring — the new inbound receives a new auto-increment ID. The old `client_traffics.inbound_id` is now orphaned. After the v3.4.0 upgrade, `getInboundsBySubId` loads the new inbound and its `Preload("ClientStats")` finds no rows for the affected clients, so both paths miss and the fallback returns zeros. This also explains why the **Clients panel shows correct traffic** (`GetAllClientTraffics` / `AggregateTrafficByEmails` query `client_traffics` directly **by email** with no `inbound_id` filter) while the subscription remark template does not. --- ### Why editing/resetting a client does not help `UpdateClientStat()` never updates `inbound_id`, so a stale value persists through any number of client edits or traffic resets. `x-ui migrate-db` is also not a fix here: `MigrationRequirements()` (`internal/web/service/inbound_migration.go:163–176`) only calls `AddClientStat` when a client has **no existing row** (`count == 0`). For clients with existing rows — all old clients with any historical traffic — neither `inbound_id` nor any field is changed. --- ### Diagnostic query Run against the SQLite DB (stop the panel first; DB is at `/etc/x-ui/x-ui.db`): ```sql SELECT ct.email, ct.inbound_id AS traffic_row_inbound_id, ci.inbound_id AS linked_inbound_id, i.id IS NULL AS old_inbound_gone, ct.up + ct.down AS bytes_used FROM client_traffics ct LEFT JOIN clients c ON c.email = ct.email LEFT JOIN client_inbounds ci ON ci.client_id = c.id LEFT JOIN inbounds i ON i.id = ct.inbound_id WHERE (ct.up + ct.down) > 0 ORDER BY old_inbound_gone DESC LIMIT 20; ``` Rows where `old_inbound_gone = 1` confirm the orphaned-`inbound_id` root cause. --- ### Workaround **Back up your database first:** ```sh cp /etc/x-ui/x-ui.db /etc/x-ui/x-ui.db.bak ``` Then, with the panel stopped, open the DB with `sqlite3 /etc/x-ui/x-ui.db` and run: ```sql UPDATE client_traffics SET inbound_id = ( SELECT ci.inbound_id FROM client_inbounds ci JOIN clients c ON c.id = ci.client_id WHERE c.email = client_traffics.email ORDER BY ci.inbound_id LIMIT 1 ) WHERE inbound_id NOT IN (SELECT id FROM inbounds) AND EXISTS ( SELECT 1 FROM client_inbounds ci JOIN clients c ON c.id = ci.client_id WHERE c.email = client_traffics.email ); ``` This only updates rows whose referenced inbound no longer exists, pointing them to a currently-valid inbound from `client_inbounds`. Rows with a still-valid `inbound_id` are left untouched. --- ### Proper fix A permanent fix would modify `statsForClient()` to add a **direct email-based DB lookup** as a last resort before returning the zero-traffic placeholder — the same strategy the panel's Clients page already uses for `GetAllClientTraffics()`. --- *Auto-generated by triage bot — all claims are grounded in source read at commit `e4b881e`.*
Author
Owner

@MHSanaei commented on GitHub (Jun 25, 2026):

Fixed in commit a4be5a0d.

Root cause: {{TRAFFIC_USED}} resolves through statsForClient, whose two lookup paths (the inbound's preloaded ClientStats and the per-request statsByEmail index) are both keyed by client_traffics.inbound_id. That id is written once by AddClientStat and never updated, so an inbound delete+recreate orphans the row from every loaded inbound — both paths miss and the zero-traffic placeholder makes {{TRAFFIC_USED}} read 0.00B. {{TRAFFIC_LEFT}}/{{EXPIRE_DATE}} looked fine because they came from the client record in that same placeholder, and the sub-info header was correct because it already aggregates by email.

Fix: added a last-resort lookup by the globally-unique email (cached per request), the same strategy the sub-info header already uses. This is a code-side fix — no manual SQL needed; the variable will report correct usage for pre-v3.4.0 clients after updating. A regression test covering the orphaned-row case is included.

<!-- gh-comment-id:4801788068 --> @MHSanaei commented on GitHub (Jun 25, 2026): Fixed in commit a4be5a0d. **Root cause:** `{{TRAFFIC_USED}}` resolves through `statsForClient`, whose two lookup paths (the inbound's preloaded `ClientStats` and the per-request `statsByEmail` index) are both keyed by `client_traffics.inbound_id`. That id is written once by `AddClientStat` and never updated, so an inbound delete+recreate orphans the row from every loaded inbound — both paths miss and the zero-traffic placeholder makes `{{TRAFFIC_USED}}` read `0.00B`. `{{TRAFFIC_LEFT}}`/`{{EXPIRE_DATE}}` looked fine because they came from the client record in that same placeholder, and the sub-info header was correct because it already aggregates by email. **Fix:** added a last-resort lookup by the globally-unique `email` (cached per request), the same strategy the sub-info header already uses. This is a code-side fix — no manual SQL needed; the variable will report correct usage for pre-v3.4.0 clients after updating. A regression test covering the orphaned-row case is included.
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#3886
No description provided.