Keep the existing node API token unless an operator explicitly requests a replacement.
Initialize edit sessions with an empty replacement draft and keep the credential field unmounted by default. Omit apiToken from Test Connection, Save, fingerprint, and inbound-loading requests in keep mode, while preserving explicit replacement, token clearing, and tokenless mTLS behavior.
Accept historyUndo/historyRedo input events so undoing and redoing an explicit replacement remains synchronized with form state. Add regression coverage for the default keep path, replacement flow, and Undo/Redo.
The first edit after a page refresh could otherwise submit an unintended non-empty password value as a replacement token, causing Test Connection and Save to fail. The exact browser/password-manager trigger was not independently reproduced; this change fixes the unsafe form/payload behavior at its source.
Addresses #7349.
Replace full inbound hydration in Show Info with owner-scoped, no-store reads of one display client or up to 50 WireGuard/AmneziaWG peers. Preserve absolute peer numbering, Host/node endpoint projection, selected tab and IP logs across live traffic updates; keep edit and clone on full detail.
Stream ordered NDJSON pages from a single stored inbound snapshot for explicit Export All Peers. Generate an ordered ZIP64 archive with existing client config/link generators; validate page offsets, protocol and total, and reject incomplete or cancelled exports. Renew the per-page HTTP write deadline through the original response writer before gzip wrapping, keeping ordinary endpoint timeouts unchanged.
Validated on head 0f853351: all 12 CI jobs and Docs CI passed, including 2,350 frontend tests, bounded-info Chromium stories, live-traffic and archive regressions, Go/race, PostgreSQL, and node/Xray E2E. The final review also verified a conflict-free test merge with main 38452eac, matching regenerated API contracts and passing focused controller tests, including the real HTTP deadline regression for identity and gzip.
The author's synthetic 50,000-peer fixture reduces the uncompressed Show Info response from 2,650,526 to 3,184 bytes. Stored JSON still requires a linear scan per page; explicit ZIP export retains archive data in browser memory. Slow individual writes and reverse-proxy timeouts remain operational limits. No production latency or memory guarantee is implied.
Fixes#7330.
Prevent inbound data migration from waiting behind concurrent PostgreSQL node/client writes: acquire the complete write-table set with EXCLUSIVE NOWAIT before any DML, use ACCESS EXCLUSIVE only for tables requiring legacy DDL, and surface SQLSTATE 55P03 as retryable contention. Plain SELECT remains compatible with the normal lock set.
Commit inbound normalization, orphan traffic cleanup and Vision flow repair together; propagate failures to CLI and restore callers and record transaction duration. Keep the reopened database pool private during host-settings restoration and inbound migration, with bounded retries of lock acquisition.
Remove duplicate post-start migration and fail installation/update before service startup when migration fails. Preserve the stopped/disabled service unit so systemd and OpenRC updates can be retried; replace the unit only after successful migration.
Verified reviewed head 56e0372a09: all 12 CI jobs passed, including PostgreSQL contention/reader/private-pool regressions and Go/race. Detached test merge against main d6afe0ef3c was conflict-free and git diff --check passed. Integrated local targeted tests passed for private pool, telemetry migration, SQLite rollback, and shared descendant selection (all eight subcases); PostgreSQL-specific tests skipped locally and verified in PR CI. Full integrated CI and live service-manager testing were not rerun.
This is a scoped fix, not an atomic whole-database restore or proof of resolution of the historical 41-second SQL tail. Persistent external writers or post-import migration errors can still leave an already committed import requiring recovery; broader schema/restore maintenance coordination and writer occupancy investigation remain open.
Review: https://github.com/MHSanaei/3x-ui/pull/7321#issuecomment-7364094359
Refs #7305 (keep open).
Replace the eager unpaged client catalog request in the routing rule editor with an admin-only, email-only suggestions endpoint. Project the email column in SQL, enforce a fixed 50-result limit, and use parameterized literal substring matching with request cancellation.
Fetch only while the User picker is open, debounce nonempty searches by 250 ms, and cancel superseded queries. Preserve saved and manual tags, comma-separated entry, the routing rule user array, and Save when suggestions fail.
Add HTTP regression coverage for 50,002 records, token scopes, response shape and literal wildcards, component coverage for stale requests and tag preservation, and browser stories for 1k/10k/50k synthetic catalogs. Update OpenAPI and API reference.
Reviewed head: c01ec35f99. All 13 CI/Docs jobs on the PR head passed. A detached local test merge against main ef99e67507 completed without conflicts; regenerated Go schemas and OpenAPI matched the staged merge, with identical frontend/docs OpenAPI copies (101 schemas, 214 paths, 227 operations). Full CI on the latest integrated tree and independent PostgreSQL-specific execution were not performed. See https://github.com/MHSanaei/3x-ui/pull/7338#issuecomment-7363795973.
Closes#7329
Expose sampled CPU topology, absolute RAM, TCP/UDP counts, load averages and network throughput through the existing heartbeat and descendant contracts, preserving measured zero versus unavailable values. Add an explicit nullable telemetry migration and freshness/availability checks.
Provide read-only All nodes and Master rows with deduplicated host/client totals, grouped SQL aggregation and reporting coverage. Preserve known descendants during parent outages and prefer the freshest valid observation of shared GUIDs. Keep the ordinary heartbeat broadcast free of fleet-wide totals.
Implement the approved compact Penpot-inspired Nodes layout, responsive stacked details, status diagnostics and existing remote actions. Preserve cached rows, search and controls on overview refresh failures. By maintainer decision, hide both system rows when no remote nodes are registered.
Final review of 44ed457985: no outstanding HIGH or MEDIUM findings. CI and Docs CI passed (13 jobs; 2342 frontend tests in 269 files), including Go/race and mixed-version node E2E. Feature-specific PostgreSQL regression execution was not independently verified in the selected CI logs. See https://github.com/MHSanaei/3x-ui/pull/7342#issuecomment-7363599190.
Closes#7335Closes#7336Closes#7337
Replace full inbound/client-list downloads on cold remote ID lookups with an owner-scoped six-field catalog projected directly from the database. Coalesce concurrent catalog refreshes per remote while preserving independent caller cancellation and rejecting stale ID mappings after topology mutations.
Seed reconciliation from the catalog, create missing inbounds directly, preserve prefixed/adopted aliases and invalidate pushed state when remote IDs change. Avoid invalidating catalog generations on unchanged-ID settings pushes. Retain client-membership-aware reconciliation state and legacy full-list fallback only on HTTP 404/405.
Cover permissions, query projection, concurrent refresh/cancellation, deletion/recreation, reconciliation request counts and mixed-version node compatibility. Integrated CI and Docs CI passed, including race, node E2E and PostgreSQL catalog projection. Synthetic response-size comparison is not a production latency benchmark.
Fixes#7303.
Cache online-independent client rollups by inbound row identity, reuse unchanged per-GUID online sets, and update only affected online overlays. Defer email popover rendering until opened and cooperatively schedule large-list rollups.
Keep the table mounted during structural refresh and detail hydration, withholding mismatched-generation counts and guarding delete-all confirmations. Preserve search, node filters and selection, and use the current cache for subscribed WebSocket updates. Retain #7289's unavailable, pending, idle, legacy and partial-report attribution semantics.
Validated on the reviewed head: all 12 CI jobs passed, including 2,338 frontend tests, ten identity regressions, the synthetic 120,000-membership Chromium story, PostgreSQL online attribution regressions, race checks, and Xray/node E2E. Includes test-only stabilization of existing relay and Telegram assertions. Production latency improvement has not been independently measured against main.
Fixes#7281.
Distinguish unavailable, pending, explicitly idle and legacy inbound online reports across REST, WebSocket and node snapshots. Require hosting-node emails and matching inbound activity; use a labeled node-wide fallback only for confirmed unsupported endpoints (HTTP 404/405).
Track Xray freshness separately from sidecar observations and prevent accounting retries from publishing online state across core replacement. Preserve partial sidecar reports through mixed-version relays using the reserved nonempty NUL marker. Retain GUID/tag remapping and attached-client filtering.
Validated on the reviewed head: all 12 CI jobs and Docs CI passed, including 2,332 frontend tests, mandatory PostgreSQL attribution regressions, race checks, Xray/node E2E and all four master/node version combinations. Exact client attribution across simultaneously active shared-client inbounds remains an estimate; older nodes may omit idle GUIDs during rollout.
Fixes#7283.
Avoid repeatedly loading and decoding full inbound settings on the slim UI list path. Read scoped inbound metadata without Settings, reuse immutable projections keyed by database handle, inbound ID and structural revision, and fetch cold or changed rows in bounded batches. Preserve row-version consistency on misses, exclude deleted rows, and bound the LRU to 2,048 entries and 32 MiB of settings content. Existing SQLite/PostgreSQL revision triggers cover structural/direct SQL edits; counter-only changes retain cache reuse. Keep shared-client stats, fallback annotations, global traffic overlays and full-list/detail contracts intact.
Add an exact-PASS PostgreSQL regression gate and a production-shaped benchmark with 30 inbounds, 7,100 clients and 115,000 actual membership rows.
Validation: [final review](https://github.com/MHSanaei/3x-ui/pull/7287#issuecomment-7360333998), [CI 12/12](https://github.com/MHSanaei/3x-ui/actions/runs/46976935406), PostgreSQL 16 regression PASS, race, frontend 2,311 tests and four node-version pairings. Independent Lenovo SQLite/PG18 tests and [benchmark](https://github.com/MHSanaei/3x-ui/pull/7287#issuecomment-7359646826): stable JSON identical (39,246,921 bytes); warm p95 2670 -> 1031 ms, settings 46,122,401 -> 0 bytes, allocations -36.2%; concurrent structural edits p95 2673 -> 1148 ms, settings bytes -97.1%. Cold full reads remain and allocations increase 1.8%. Eight samples, same-binary baseline, synthetic topology, no production latency guarantee.
The reviewed head is one commit behind main solely due to nonoverlapping #7277 dashboard/docs changes; both trees passed their own CI, but combined-tree CI remains to be verified after merge. No schema or wire-format change.
Refs #7009
Reduce repeated inbound settings materialization with a protocol-aware preparation projection that retains node_id. Reuse the locked validation/mutation snapshot while preserving the transaction-time settings reread and three-way rebase. Gate effective Create/Attach Flow before grouped payload construction; retain public Add and bulk/copy semantics.
Preserve #7367 grouped Create, intended-payload fingerprint CAS, ordered turns, cancellation, metadata ordering, durable delete/reattachment safeguards, node outcomes and PostgreSQL lock ordering. Add a mandatory PostgreSQL gate for nine read/protocol regressions without weakening the existing 21 ordering/grouped-create cases.
Validation: all 12 CI jobs passed on 9062e5cf94 (run 46971334865), including PostgreSQL 9/9 and 21/21 focused gates, race, and all four version pairings. Author-reported paired PostgreSQL 16 fixture: 44 -> 22 full reads, 64.82 -> 32.41 MiB materialized per local Create, p95 497.0 -> 400.9 ms; contended Create p95 994.2 -> 633.5 ms and Update 1118.4 -> 937.5 ms. Single-node grouped Create stays one RPC. Necessary protocol/Flow reads and Attach preparation remain; no WAL redesign or production latency claim.
Refs #7300
Group compatible client creates by destination and effective payload via the existing clients/add API. Resolve node-local inbound IDs, preserve distinct flow/address/credential payloads, bound delivery concurrency and use a shared four-second remote delivery budget after local commits.
Advance reconciliation fingerprints only for acknowledged intended settings, retaining previous-fingerprint CAS rather than stamping unrelated rebased changes. Preserve FIFO turns, node-wide barriers, dirty generations, durable delete supersession, partial and uncertain delivery recovery and downstream outcomes. Protect later reattachments in final Delete cleanup and complete Create metadata before remote delivery.
Validation: all 12 CI jobs passed on 63e70cda38 (run 46935177853). PostgreSQL logs confirm 21 ordering/grouped-create tests and prior reporter-lock, reconciliation and traffic contention gates; node E2E confirms all four version pairings. Author reports SQLite/PostgreSQL race tests, make verify and isolated full make race.
Author-reported paired PostgreSQL 18 benchmark: 11 -> 1 RPC, fixed 200 ms peer delay 11-target p95 1552.0 -> 731.9 ms, timeout probe 12.41–12.42 -> 4.41–4.50 s. Size-dependent peer cost can instead cause pending delivery (1.74 -> 4.51 s with 0.74 s recovery); four stalled nodes can defer a fifth. Monitor production convergence and pending rate. No general production latency or allocation improvement claimed.
Refs #7299
Batch changed node_client_ips rows in bounded deterministic 190-row statements with snapshot CAS, affected-row/replacement-ID checks, whole-GUID rollback and retry, insert-only RETURNING id and guarded pruning. Preserve exact timestamps, canonical no-op skipping, GUID scoping and flat IP-limit behavior.
Integrate independent node polling with transactional reporter eligibility and identity fences. Avoid the reproduced PostgreSQL flat-IP/node ABBA cycle by ordering flat IP DML before reporter validation at commit; retain node-before-attribution ordering for GUID writes and node deletion. Prelock rename and bulk cleanup targets in byte order and reject stale email CAS attempts. Preserve SQLite immediate write transactions, ordered dispatch, durable deletion and existing traffic reconciliation. No network I/O under the new DB locks or global IP-sync serialization.
Validation: all 12 CI jobs passed on c2831ca52f (run 46915194728). PostgreSQL logs confirm delete/rename/bulk lock order, independent reporter progress, lifecycle rollback on disable/delete/endpoint/GUID changes, guarded prune, scanner enforcement and existing durable-delete/reconciliation regressions. Author reports RED SQLSTATE 40P01 on af77a55d, focused SQLite/PostgreSQL race tests, make verify and all four node E2E version pairings.
Author-reported PostgreSQL 16 fixture: 552 -> 4 UPSERTs/round, unchanged 70,656 affected rows, merge p95 387.8–391.1 -> 72.3–81.4 ms, handler p95 16.9–19.5 -> 8.9–11.7 ms. Contention: 2 -> 0 observed deadlocks; corrected 192/192 reports succeeded. Loaded-host tails increased; idle-host repeats did not show a consistent material regression. WAL reduction and production latency improvement are not established. Monitor lock waits and CRUD tail latency separately.
Fixes#7298
Reuse client records and successful link diffs during full node snapshot reconciliation. Preserve master-owned comments on existing records while importing new comments; omit comment writes so concurrent operator updates survive. Deduplicate detached IDs across successful inbound savepoints and mark only globally unattached clients in bounded 400-ID batches inside the existing transaction; roll back on orphan-mark write failure.
Integrate against current main while preserving #7314 target-node pending-delete cancellation and cross-node recreation guarantees, #7315 staged traffic and batched baseline writes, and #7308 serialized eligibility checks. Preserve orphan recovery, degraded-inbound safeguards and idempotent snapshot replay.
Validation: all 12 CI jobs passed on 51e627739e (run 46895213148). PostgreSQL logs confirm four new reconciliation tests, both contention/baseline regressions and eight ordering/durable-delete regressions. Author reports focused SQLite/PostgreSQL 18 race tests, make verify and all four mixed-version node E2E pairings.
Author-reported controlled 4096-client PostgreSQL 18 fixture: idle SQL statements 350 -> 270, changing-counter statements 552 -> 472, rows read 151832 -> 102680. Idle writer p50/p95 490/597 -> 430/466 ms; counter writer 489/521 -> 449/519 ms. Idle cycle p50/p95 1118/1277 -> 1015/1050 ms; counter cycle 1121/1172 -> 1046/1135 ms. Worst counter cycle effectively unchanged. These fixture results are not independent production measurements. Production tail latency, shared-client compact-cache reuse and migration coordination remain separate follow-ups.
Refs #7305
Isolate traffic synchronization with bounded round-robin per-node workers, independent maintenance and publication, cancellation and ordered shutdown drain. Recheck online eligibility inside the serialized writer before merging snapshots and retain the latest valid speed sample per node, with expiry and explicit empty publication.
Report direct per-node applied/pending/failed outcomes without changing local-save success semantics. Propagate downstream pending separately from direct ACKs so acknowledged batch items do not abort subsequent work. Integrate live admission into the existing #7314 ordered dispatcher with separate four-second queue and batch budgets, retaining monotonic dirty generations, exclusive full-delete/reconcile turns, durable deletion outbox, generation-matched settlement, cross-node recreation safeguards and targeted fingerprint invalidation. Preserve legacy peer compatibility and update generated API documentation.
Validation: all 12 CI jobs and Docs CI passed on reviewed head d13850474f (runs 46871519847 and 46871519831). PostgreSQL logs confirm eight ordering regressions, including saturation, lost ACK, cross-node recreation and bulk recovery. Author reports make verify, focused SQLite/PostgreSQL race tests, four mixed-version node E2E pairings and Xray E2E. No independent production-scale latency measurement or universal HTTP timeout guarantee.
Residual follow-ups: possible conservative false-pending result when a final full delete settles an intermediate superseded intent on the same node; add per-logical-operation settlement regression. Verify shutdown drain under a blocked writer/maintenance worker. These static-review concerns remain open for follow-up, not demonstrated data loss or a new deadlock.
Refs #7293
Release inbound mutation locks after durable local commit and reserve conflicting remote dispatch turns in writer commit order. Allow independent inbounds to progress concurrently while reconciliation and full client deletes retain node-wide ordering. Bound queue waits and live batches separately, advance dirty revisions strictly, and invalidate only affected remote fingerprints.
Persist permanent-delete intents transactionally per node/email and replay bounded pages during reconciliation. Match acknowledgements to the queued generation and retain failed/ambiguous deliveries. Supersede pending deletes only when the client is desired on the target node, so recreation on another node does not leave an old orphan record. Preserve pending rows during database migration and accept legacy backups without the outbox table.
Validation: reproduced the cross-node orphan on the previous head; fixed regression passed locally on Lenovo with focused SQLite (9/9) and PostgreSQL 16 (7/7). All 12 CI jobs passed on 5459316fbd (run 46862646487), including race, PostgreSQL migration and durable-first, and node/Xray E2E. PostgreSQL logs confirm all seven ordering tests including cross-node recreation, lost acknowledgement and bulk recovery after database reopen. Branch is up to date with main. No measured production latency claim; requests still wait for their own bounded ordered remote apply. Coordinate overlapping #7308 before its integration.
Fixes#7304.
Stage existing client traffic updates in snapshot order and flush them after client reconciliation to shorten PostgreSQL row-lock lifetime. Keep configuration, traffic counters, renewals and baselines atomic in the same serialized transaction, preserve concurrent last_sub_fetch updates, and retain rollback and idempotent replay semantics.
Batch baseline upserts by (node_id, email) within SQLite parameter limits. Decode snapshot claims before opening the transaction while retaining transactional ownership checks. Add debug metrics for queue wait, writer execution and transaction duration.
Validation: all 12 GitHub CI jobs passed on reviewed head 6dc504b675, including race, PostgreSQL, node and Xray E2E. PostgreSQL CI logs explicitly confirm both contention and baseline batching regressions. The author reports PostgreSQL 16/18 validation, rollback/replay coverage and a reduction from 4,187 baseline upserts to 28 in a local fixture.
Scope: this resolves the reproduced subscription row-lock window, not the full serialized writer hold, shared-client cache restriction, historical 41-second SQL tail or cross-process migration/restore deadlock. These require follow-up. No independent production measurements or successful CI run on the exact latest combined revision were verified before merge.
Refs #7305
Avoid materializing full inbound settings and client statistics only to discard the snapshot above the existing 5,000-row WebSocket cutoff. Probe user-scoped direct and sibling-backed traffic rows with bounded SQL before loading the snapshot; skip work without subscribers, fall back to invalidation on probe failure, and retain the post-read guard for concurrent growth.
Coalesce WebSocket invalidations by resource in a 200 ms window so paired Inbounds and Clients events refresh both query roots without duplicate same-resource refetches.
Regression coverage exercises the real inbound mutation route and WebSocket hub at and above the cutoff, shared traffic, user scoping, no subscribers, and frontend paired invalidations. All 12 CI jobs passed on the reviewed PR head. The author also reports SQLite/PostgreSQL 16 validation and make verify. Static review of the current merge candidate found no overlapping file changes with main; CI on that exact combined revision was not independently run before merge.
The reported synthetic SQLite notification benchmark (30 inbounds, 7,101 clients, 115,041 associations) improved from 323.87 ms to 0.24 ms and from 324,751,126 to 5,393 allocated bytes per operation. These figures do not establish production HTTP or browser latency improvements.
Fixes#7297
Fix the production-confirmed ABBA lock inversion introduced in v3.12.0: Xray restart held the lifecycle mutex while synchronously waiting for the serialized traffic writer, which needed the same mutex to amend the committed live configuration snapshot. This blocked API writes and node synchronization, and made panel reload wait indefinitely for cron shutdown.
Run traffic maintenance before acquiring the Xray lifecycle mutex, keep config generation free of writer submissions, and retain the live-snapshot generation guard. Bound panel-only reload with one 75-second deadline across shutdown and startup; fence replacement workers until the old generation drains, and exit nonzero for supervised recovery on failure. Preserve Xray on healthy reloads, gracefully handle termination signals, log phase timings and bounded function-only stack diagnostics, and distinguish accepted restart requests from successful completion.
Validation: all 13 GitHub checks passed on the reviewed head, including Go tests, race, PostgreSQL durable-first/migration, node and Xray E2E, frontend, lint, codegen, vulnerability check and docs. PR validation reports isolated SQLite/PostgreSQL 18 reload tests with 15,844 clients and 30,270 memberships, stable real Xray PIDs, and legacy/current node interoperability.
Addresses the primary deadlock and bounded panel reload; writer cancellation and per-source listener admission diagnostics remain follow-ups. Supervised failure recovery may interrupt Xray sessions.
Fixes#7345
The shared zstd encoder for master-to-node request bodies was built with
library defaults: one workspace per CPU, each holding a 16 MiB history for
the default 8 MiB window. The pool hands its workspaces out in rotation and
never frees them, so a 4-vCPU master kept about 70 MiB alive after its
first few pushes and a 16-core one about 280 MiB.
Build it with a 1 MiB window, at most four workers and zstd's low-memory
mode, which retains about 10 MiB whatever the CPU count. Callers queue for
a worker on a slot channel, so a cancelled push stops waiting instead of
blocking inside EncodeAll. Frames stay standard zstd: capability
negotiation, the SHA-256 of the uncompressed body and the node's decode
bounds are unchanged.
Closes#7274
The guard that keeps a working core from being replaced by a config it cannot
bind only knew one reason: another process holds the port. An inbound whose
listen address the host does not have, or whose port the panel is not allowed
to bind, went the same way as that one did: the new core exited at start and
the watchdog restarted it every two seconds with every inbound down.
The probe now names those two failures as well. A tproxy inbound is excused
from the address check: IP_TRANSPARENT lets the core bind an address the host
does not hold, which the probe cannot do. The permission check assumes what
the shipped units give: the core is the panel's child with the same
privileges. A core granted file capabilities the panel lacks would be refused
a port it could bind.
Checked against the pinned core on its own: it exits 255 on a missing address
and on a denied port, and starts on the missing address with tproxy. On a
running panel an inbound on 192.0.2.1 was refused with the core's PID and the
other inbound untouched, and came up by hot apply once its listen was fixed.
The case that left a missing address to the core is replaced: that was the
previous commit's scope, not a rule.
A config the core cannot bind must never replace one that works: the new core
exits at start and the watchdog then restarts it every two seconds with every
inbound down. The guard only looked for two inbounds of the same config sharing
a socket, so an inbound saved on a port some other process holds went through:
the hot apply failed, the restart followed, and the panel looped on
"address already in use" until the inbound was removed.
Before replacing a running core, bind each socket the new config adds the way
the core will (it sets SO_REUSEPORT on every listener) and refuse the config
when the address is in use. Sockets the running config already serves are the
core's own and are not probed. The refusal is reported like the existing bind
conflict, on the status page and in the log, and the next tick applies the
config once the port is free.
Run on a panel with the real core: with the port held, the core kept its PID
and the other inbound kept serving with no failed probe in 60 s; the inbound
came up by hot apply on the first tick after the port was released.
A listen address the host does not have, or a port the panel may not bind, is
still left to the core's own error.
With restart-on-client-disable on, a client the API removes from a running
inbound must be followed by a core restart: the removal drops the credential
only. The apply layer asked for that restart by setting the generic
need-restart flag, and the tick then restarted only when the generated config
differed from the running-config snapshot. A client added over the API is not
in that snapshot, so disabling or deleting it before any reconcile diffed as
"no change" and its live session kept passing traffic.
The removal now queues the session-drop restart itself, through the request
the depletion path already uses, so the tick replaces the core whatever the
snapshot holds. Detaching a client and bulk delete removed clients the same
way without asking for anything; they queue it too. WireGuard is left out: its
session ends with the peer.
The pending flag and the protocol predicate lose "depletion" from their names
now that manual removals share them.
Run on a panel with the real core: a client added after the core started,
holding a stream open, was cut and the core replaced within one tick of its
disable; before the change the stream ran on and the core kept its PID.
The test counted every hot_apply_failed restart in the package's shared log
buffer and required exactly one. Any other test that makes a core restart for
that reason, or the same test run twice with -count, made it fail for a line
it did not write. It now compares the buffer before and after its own restart
and checks the newest entry.
The three regressions for a node counter that restarts below its baseline, and the migration test for the column that fix added, shared fixed node ids and inbound tags. Run as a group against PostgreSQL, the database in the report, the second one failed on a duplicate key before reaching the code under test.
Give each case its own PostgreSQL schema and run all four in the PostgreSQL CI job, requiring four passes. No panel code changes; the fix itself is already on main in 408fd682.
Refs #7271
Every five seconds the master fetched each node's complete inbound list, settings JSON and enrichment included, parsed it and reconciled every client, whether anything had changed or not.
A node that advertises traffic-snapshot-v1 now answers a revisioned endpoint: counters and lifecycle state on every poll, inbound configuration and attachments only when its revision changed. The master skips structural parsing and client reconciliation while the node's revision, its own rows for that node, the lifecycle state and the full remote-to-central inbound mapping are all unchanged; anything else falls back to the full merge. Old and new panels keep talking through the previous endpoints.
Revisions come from a hidden per-row token on inbounds and clients, maintained by database triggers on SQLite and PostgreSQL so that direct and background writes count too. Counter and timestamp updates leave it alone. The triggers are dropped before migrations and recreated after them, and the previous build runs unchanged on a database that carries them.
Measured here at 20,000 clients on one node, per idle poll: master SQL statements 551 -> 44, node statements 55 -> 4, transfer 23.0 MB -> 4.8 MB. When every client is shared between nodes the ownership checks keep the full master merge, so only the node and the transfer get cheaper. The node still reads every membership and counter on each poll.
Closes#7007
One switch decided two things: whether Xray restarts when a client is disabled or deleted by hand, and whether it restarts when a client runs out of quota or expires. A panel that takes many API deletes had to choose between a restart on each of them and leaving depleted clients' open connections alive.
Add a switch for the quota and expiry case. It inherits the old switch until it is saved, and older settings clients may omit it. A depletion asks for one restart per affected running core per committed batch: the local core when a local inbound served the client, and each affected node through the node API. A master whose nodes alone served the client is not restarted. With the new switch off, a depleted client is still removed from the running core and from its config snapshot, so a later reconcile does not restart for it either.
Also add a node traffic fetch timeout setting (1 to 30 seconds, default 4).
Run on a panel with real cores: with the old switch off and the new one on, a stream through a client that crossed its quota was cut within one poll and the lifecycle log names client_depletion; with them swapped, the stream and the core survived. A depletion a node detects itself follows that node's own switches.
Refs #7145
Every node snapshot merge ran a table-wide UPDATE that copies a node-activated deadline onto client records still holding the start-after-first-use duration, whether or not that snapshot activated anyone.
A merge now repairs only the clients it activated or renewed in that tick, and a snapshot with no such transition issues no UPDATE. Older drift (legacy imports, a tick whose client reconciliation was skipped) is repaired by the five-minute maintenance job in windows of 4,000 client ids, which also covers standalone panels. A failed repair now fails the merge on SQLite as it always did on PostgreSQL, where the transaction was already aborted.
Verified on SQLite and PostgreSQL 18: the previous code rewrites an unrelated client's expiry on every merge, and without the scoped lift a record on a tick that cannot rebuild client records keeps its negative duration.
Fixes#7233
Every node snapshot merge ran a clear-orphan-marks UPDATE over the whole clients table, marked rows or not. On a PostgreSQL master with thousands of clients that was a full scan every five seconds per node, inside the single serialized writer.
A merge now clears marks only for the clients it reconciled, and an unchanged snapshot issues no orphan statement at all. Marks left on still-attached clients by older builds, restores or imports are repaired by the existing five-minute reaper, in the same transaction that decides what to delete, and a client that loses its last link has its stale mark cleared first so the reaper cannot delete it without a grace period.
Verified on SQLite and PostgreSQL 18: the previous code repairs an unrelated mark on every merge and reaps a legacy-marked client right after it is detached.
Fixes#7231
Comparing current traffic across nodes meant opening each node's history chart. The heartbeat already carries every node's upload and download rate.
Show both rates in a stacked column of the Nodes table, between Memory and Xray Version, and in the mobile detail dialog, which now follows heartbeat updates. A measured idle link reads 0 B/s; a disabled, offline or transitive node, a peer too old to report throughput, and a sample older than 30 seconds read as a dash. The sample's age is computed on the master and anchored to when the browser received it, so a skewed browser clock does not blank the column.
The probe now records a missing or invalid direction as unavailable where it used to store zero, so such peers also stop adding zero points to the history chart.
Fixes#7238
The external traffic webhook was sent from inside the 5-second accounting job: its cadence could not be changed, and a slow receiver held up accounting.
Add an interval setting (5 to 3600 seconds, default 5). The accounting poll only sums each tick's deltas per client email and per inbound or outbound tag; once the interval has passed, the batch is posted from its own goroutine. Accounting, quota enforcement and online updates keep their 5-second cadence.
Delivery semantics are unchanged: each batch is posted once. A failure drops it, warns once with the reason (never the URI) and reports when deliveries resume. Destinations are checked at dial time and redirects are refused. A settings client that omits the interval keeps the stored value.
Fixes#7028
Reconciling a client record whose fields changed wrote it twice: Save stamped updated_at with the current time, then a second UPDATE put the agreed timestamp back. A PostgreSQL master with about 7,000 clients counted roughly 179,000 of each in 50 minutes.
Run the Save through a session whose clock returns the agreed timestamp, so GORM's hooks and serializers still run and one UPDATE carries the right value. An unchanged row still writes nothing. Verified on SQLite and PostgreSQL 18: one UPDATE per changed row, where the previous code issues two.
Fixes#7234
At the default log level an operator could see the Xray child PID change many times a day without learning which of those changes the panel caused, or why.
Write one xray_lifecycle line for every real start, stop, restart, hot apply, rejected config and unexpected child exit. It carries the old and new PID, the path that asked (manual, watchdog, client depletion, pending restart and its first trigger, ...), a fixed reason, the force flag, the duration, the hot-apply outcome and the previous child's exit code or signal. An unchanged config still emits nothing and restart policy is unchanged.
A hot apply the core refuses also logs the core's own error once, with the inbound tag or client it concerned, so a restart labelled hot_apply_failed can be traced to its cause.
Fixes#7260
splitMovedClientTraffics reserved room for every registered client before filtering down to the ones that moved bytes. On a large panel where almost everyone is idle, that was megabytes of unused slices and map buckets on every five-second poll.
Count the moved rows first and size the slices and the email set from that count. Order, set membership, zero-delta filtering and the non-nil empty results are unchanged. Measured here at 50,000 rows with 1% active: 2.95 MB -> 39.6 KB and 109 -> 60 us per call; with every row active it costs about 4% more time for the same allocations.
Fixes#7262
External Traffic Inform could be saved enabled with a blank URI. Every traffic tick then built the full payload and POSTed it nowhere, logging one "missing port in address" warning per tick (about 17,000 a day in the report).
Refuse the save when the switch is on and the URI is empty. A database that already holds that state skips the notification before the payload is built and warns once per episode, naming why the destination was refused without echoing a malformed URI. Local traffic counters and last-online times are still committed on the skip path.
Fixes#7261
1Password for Safari does not show its Universal Sign-In banner on the
Russian login form, because the label 'Код 2FA' is not recognised as a
one-time-code field. Use 'Одноразовый код' instead; the field already
has autocomplete=one-time-code. The key's only other use is an aria-label
in the 2FA setup dialog.
Fixes#7258
x-ui setting -reset puts the panel back on its default ports, 2053 and
2096 for the subscription server. An inbound already listening on one of
them then shares a socket with the panel, and Xray cannot start. The
other writers of those ports refuse such a change, but a reset is the
way back into a panel whose port was forgotten, so it must not be
refused.
After the reset the command now lists every enabled local inbound that
collides with a panel socket and says that Xray will not start until one
of the two moves. Disabled inbounds are left out: they bind nothing, and
enabling one is refused by the port check.
Printing the lines from main.go is wiring no test reaches; running
x-ui setting -reset on a database with inbounds on 2053 and 2096 prints
one warning for each.
The panel binds its web and subscription sockets before Xray starts, so
a local inbound on either leaves Xray unable to listen at all. Nothing
compared an inbound with those two sockets. Restoring a backup with this
machine's settings kept could therefore import a tunnel on the panel's
own port: the database was swapped first, and the failure only showed
when Xray would not start.
The rule is now stated once and every writer goes through it:
- A restore reads the backup's inbounds and the settings that will be in
force afterwards (this machine's for kept keys, the backup's for the
rest, XUI_PORT over both) and is refused before Xray is stopped or the
database touched. All three paths do this: a SQLite file, a SQLite
file imported into PostgreSQL, and a pg_dump archive, whose two tables
pg_restore prints as a data script without a connection. Only enabled
rows refuse a restore, so a backup holding a disabled leftover stays
usable; enabling that row later is refused by the port check.
- Adding, editing and enabling an inbound run the same check.
- Saving panel settings, and x-ui setting -port / -listenIP, refuse to
move a panel socket onto an inbound. A collision that already exists
does not block later saves. The x-ui menu no longer reports a refused
port or listen address as set.
One existing test put its inbound on 2053, the default panel port, for
no reason of its own; it now uses 2083.
Not covered: x-ui setting -reset and a changed XUI_PORT can still put
the panel on an inbound's port.
The PostgreSQL paths were run against PostgreSQL 18 with its pg_dump and
pg_restore; CI skips those tests. make node-e2e passes.
Closes#7115
Since a69f2dee a node's online report is cut to the clients linked to
its inbounds on this panel, so a node that also serves inbounds the
panel does not import (inboundSyncMode=selected, or inbounds created on
the node) shows only part of its load, and an operator cannot tell a
busy node from an idle one.
The panel now counts the distinct clients in the node's own entry of
that report before the cut and keeps the number only: the emails of
clients it does not manage are still dropped, so they cannot mark
another client online or reach the IP limit. The count needs no new
node endpoint, so nodes on older builds report it too, and it is
dropped together with the node's online clients when the node is no
longer synced.
The Nodes page shows it as "synced / total" in the online tag when the
node reports more than the synced count. Transitive sub-nodes carry no
total: the panel takes no counts from an intermediate node.
The Public IPv4/IPv6 hint told operators to leave the field blank so mtg
would detect the address itself. mtg-multi has no such detection for the
middle proxy: with the field empty it feeds its socket's local address
into the middle-proxy key schedule, which only matches what Telegram
sees when the public IP sits on the server's own interface.
Behind NAT or a Docker bridge the handshake is refused, so every
connection of an ad-tagged client spends 5-7 seconds on the middle proxy
before falling back to a direct connection, and the sponsored channel
never appears. Measured against real Telegram with a tagged and three
untagged clients; the untagged ones were unaffected.
The hint in all 14 locales now says when blank is correct and when the
address must be entered. The two code comments repeating the claim are
corrected with it.
Every client the panel serves has its connected addresses recorded and its
IP limit applied, whichever process carries it. MTProto clients are served
by mtg, never by Xray, so the core's online list could not see them: their
IP log stayed empty and a configured limitIp never fired, although the form
offers both for every protocol.
mtg-multi 1.17.0 reports users.<name>.active_ips in /stats. The manager
keeps them from each scrape together with the time an address was first
seen connected, so the scan can keep the newest addresses and ban the
oldest, and the IP scan merges them the way it already merges kernel-mode
AmneziaWG peers. A failed scrape drops the addresses instead of leaving
them live, and loopback addresses (a relay in front of mtg) are skipped as
the core skips them.
Enforcement is the existing fail2ban path. The temporary credential drop
is Xray-only, so on Windows, where it is the only mechanism, an MTProto
limit is recorded but not enforced.
An MTProto inbound must not relay a stranger's connection to a public host
picked by an SNI the panel never configured, and every byte it moves must
show up in the inbound's traffic.
mtg relays whatever it cannot serve as a proxy to the fronting target, byte
for byte, and the target answers by the SNI of that connection. With the
default FakeTLS domain on a CDN, anybody could reach any site of that CDN
through the inbound ("clean IP"). mtg dials the target itself, past the
Xray bridge and outside every secret, so neither the clients nor the
inbound showed that traffic.
- The generated config sets [domain-fronting] require-sni-match (mtg-multi
1.17.0) unless the fronting IP is a loopback, private or link-local
address, i.e. the operator's own web server. mtg then relays only a
ClientHello naming the FakeTLS domain and closes the rest. An older mtg
ignores the key.
- The /stats "fronting" counters are scraped per process and added to the
inbound's total, for routed inbounds too.
TestRenderConfig pinned the old rule (a bare config has no
[domain-fronting] section) and now expects the section without a host.
The config scale benchmark used the b.N loop that gopls flags for modernization; it now uses b.Loop, which also makes its ResetTimer and StopTimer calls redundant. assertInboundClientGroup and seedUsageHistoryClient each took a parameter they never read, so the parameters and the arguments passed for them are gone.
While a client's lifecycle was frozen (node config_dirty, a push that just landed, a reset the node still owes, or a client the node only reports usage for), a node counter that fell below the stored baseline left that baseline untouched. The other field's growth was still added to the client, and because the baseline never moved the same amount was added again on every sync tick: an idle client gained gigabytes per minute and was cut off. A client whose counters stayed below the old baseline had the opposite problem, and none of its usage was counted.
The baseline was held back on purpose (#6228): the dip is the evidence that the node renewed the client, and it had to survive until an unfrozen tick could judge it. The baseline was doing two jobs. It now always follows the node, so a delta is added once, and the unjudged dip is kept in a new node_client_traffics.dipped_while_frozen column that the first unfrozen tick consumes.
A renewal seen while frozen is now also adopted when the client's usage has since outgrown the pre-renewal baseline; before, that evidence was lost.
Usage already over-counted cannot be recovered and needs a manual reset. A baseline that is stuck at upgrade time adds its delta one last time on the first sync and is correct from then on.
With around 10,000 clients both attach dialogs loaded every client, pre-selected all of them and rendered every row, which locked the browser for minutes.
Both dialogs now ask the server for 100 rows at a time and render only the visible ones. Select All freezes the eligible client IDs that match the current search and group into a small server-issued token; the browser keeps that token plus the clients the operator unticked instead of thousands of emails, and the listing marks each row against the frozen filter so rows outside it stay unselected. On submit the server re-derives the same set and rejects the job before any write when its membership changed; clients created after the freeze stay outside it. The attach runs as a background job the dialog polls for counts.
Requests that post an email list keep their synchronous response. The Postgres job now runs the selection tests, which build their predicates by hand for both dialects.
Fixes#7236
The traffic poller treated the first stats reply of every core as a baseline and credited none of it, so whatever clients moved between an Xray start and the first poll never reached their committed usage. A restart on the same API port also kept the previous core's last values, which under-credited the new core by that amount, and by all of it when the new counter had not yet passed the old one.
Track the baseline by process identity instead: a core the panel has just started counts from zero, and the poller keeps its own API client so a restart issued by any other service value cannot leave stale values behind. A panel-only reload keeps the same process and is not counted again. A generic API connection to a core with unknown counter history still takes a baseline first.
Fixes#7211
A master pushing an inbound delete or update to a node treated every failed lookup of the node's inbound list as "the inbound is not there". An auth error, a 503, an application error or a malformed list made a delete count as done while nothing was deleted, and made an update fall back to adding the inbound a second time.
Only a list that loaded and lacks the tag now counts as absent: deleting an inbound that is really gone still succeeds and an edit still re-creates it. Every other failure is returned and no add, update or delete is sent to the node.
Refs #7237
A subscription balancer whose inbounds were deleted, disabled, changed to a protocol with no JSON outbound, left without clients or closed by their hosts simply vanished from the JSON subscription, and nothing in the panel or the log said why.
GET /panel/api/sub-balancers now returns a problems[] array per balancer with stable codes: unknown_inbound, disabled_inbound, json_incapable_protocol, inbound_without_clients, hosts_excluded_from_json and no_members. Settings -> Sub Balancers shows a warning tag whose tooltip names each cause and the affected inbounds, and the log records a balancer's problems when they change instead of on every listing.
The advisories are read from the stored rows and never change what a subscription emits: a balancer with no usable member is still omitted. The list of JSON-incapable protocols is pinned to the renderer, the subscription allowlist and the form by tests.
Node sync could commit a rejected inbound's client changes. The cross-inbound TUIC UUID check runs after the shared client record, the inbound links and the flow overrides are written, and the merge used to log the error and commit anyway: a shared client could keep another client's UUID, half-updated links and the node's settings for that inbound.
Each inbound's adopted configuration and client sync now run in a savepoint. A refusal rolls that inbound back and the merge goes on, so traffic and the inbounds that synced still commit; the refused inbound stays out of the orphan sweep and a later valid snapshot reconciles it.
A node inbound the master sees for the first time is stored with the settings the node reported and stamped as already delivered. Without the row the next reconcile deletes the inbound on the node; with other settings it overwrites the node's clients; and pushing the node's own inconsistent blob back is refused there on every tick, which keeps the node dirty and suspends adoption for all of its inbounds.
Run on a real master and node with clients connected: the refused inbound kept serving through a reconcile, the node stayed clean, and the master adopted it once the node's report was consistent.
Closes#7219
The node traffic sync and heartbeat jobs run every 5 seconds and listed nodes through GetAll, which also built the Nodes page statistics: a distinct-client count and a join over every client on a node-hosted inbound with its traffic row. Neither job reads those numbers, and neither do the Xray config build or the reset-all fan-out. With sub-nodes present the Nodes tree ran the same classification twice.
Those callers now take ListOperational, a plain ordered node list with decrypted tokens. GetNodeTree adds the statistics once, and only the client count when a transitive tree recounts the rest itself. GetAll is gone, since nothing reads it any more.
The Nodes page shows the same counts. On a master with 20,000 clients across eight node inbounds (SQLite), idle master CPU went from about 13.1 s to 12.3 s per minute.
Closes#7232