[PR #7014] perf(node-sync): avoid redundant full inbound snapshots #6576

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

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/7014
Author: @HamedSanaei
Created: 10/29/2026
Status: 🔄 Open

Base: main ← Head: perf/node-traffic-snapshot-7007


📝 Commits (4)

  • 96e67ae perf(node-sync): reduce redundant full traffic snapshot reads
  • fed8681 docs(perf): format node snapshot measurement report
  • 0c90a62 chore(merge): reconcile node snapshot caching with upstream main
  • a92c5f9 fix(nodes): harden compact snapshot reconciliation

📊 Changes

48 files changed (+5286 additions, -465 deletions)

View changed files

📝 .github/workflows/ci.yml (+22 -2)
📝 docs/content/docs/en/reference/api/inbounds.mdx (+14 -1)
➕ docs/performance/cpu-profiles.csv (+9 -0)
➕ docs/performance/cycles-postgres.csv (+49 -0)
➕ docs/performance/cycles-sqlite.csv (+49 -0)
➕ docs/performance/events-postgres.csv (+73 -0)
➕ docs/performance/events-sqlite.csv (+73 -0)
➕ docs/performance/node-traffic-snapshot-7007.md (+221 -0)
➕ docs/performance/projections-postgres.csv (+13 -0)
➕ docs/performance/projections-sqlite.csv (+13 -0)
📝 docs/public/openapi.json (+299 -0)
📝 frontend/public/openapi.json (+299 -0)
📝 frontend/src/generated/examples.ts (+72 -0)
📝 frontend/src/generated/schemas.ts (+217 -0)
📝 frontend/src/generated/types.ts (+46 -0)
📝 frontend/src/generated/zod.ts (+53 -0)
📝 frontend/src/pages/api-docs/endpoints.ts (+16 -0)
📝 internal/database/db.go (+15 -2)
📝 internal/database/model/model.go (+2 -0)
➕ internal/database/snapshot_revision.go (+91 -0)

...and 28 more files

📄 Description

Summary

Reduce configuration work during the five-second node traffic poll while keeping counters and lifecycle state fresh. A capability-negotiated v1 endpoint sends configuration only after a durable revision change. The master skips reconciliation only when revision, ownership, lifecycle, membership and the complete remote-to-central inbound association validate; deployed aliases remain usable on cached ticks.

Why

The old path was Remote.FetchTrafficSnapshot -> GET /panel/api/inbounds/list -> full settings/preloads/UUID-SubID enrichment/shared-stat backfills -> SetRemoteTraffic settings parsing and SyncInbound. Unchanged polls repeatedly paid those database, JSON and reconciliation costs.

Closes #7007

Related: #7008, #7009

Implementation and compatibility

  • Add authenticated GET /panel/api/inbounds/trafficSnapshot?revision=... for admin, node-admin and node-sync. Reuse existing TLS/mTLS/outbound transport; monitor remains forbidden.
  • Complete counters are always fresh. Omitted structure requires matching validated history and a complete client/inbound roster. Errors cannot become deletions. A present empty catalog retains full semantics and existing safeguards.
  • Persist hidden, GORM-read-only row tokens on inbounds/clients with native SQLite/PostgreSQL triggers, including direct/background edits. Project membership tokens and lifecycle fields; avoid steady-state settings reads/full-JSON hashing. Boot/database-connection epochs handle reopen/restart/migrations.
  • Validate master-side revisions, lifecycle and filtered memberships before skipping structural parsing/sweeps/SyncInbound. Keep the existing common delta, reset, renewal, dirty/justPushed, tombstone, ownership and GUID logic. Prune inactive caches.
  • Preserve validated remote inbound ID → central inbound ID bindings for deployed aliases. Restore them only after cache validation, and fall back to full reconciliation when any association is invalid.
  • Preflight compact collection limits before typed allocation: 65,536 catalog/counter inbounds, 1,048,576 clients/attachments/online emails, and the existing aggregate GUID-map value budgets. Malformed/oversized replies discard history without legacy downgrade.
  • Use unscoped revision-trigger update events with actual-change guards. Remove old trigger definitions before migration DDL, including SQLite bodies that mention retired columns; preserve counter/timestamp/no-op behavior.
  • Old/new pairs retain the legacy APIs. Only 404/405 trigger complete legacy fallback with a retry cooldown; auth/network/server errors surface. Protocol errors discard catalog history and fail closed.

No depletion SQL, global freshness/quota semantics, heartbeat cadence, slim/full/detail response contract or frontend Inbounds behavior changes. #7008 and #7009 remain independently implementable. Existing OpenAPI paths/components were compared byte-for-value; only one route and five supporting schemas were added.

Measurements

Current matched SQLite fetch+merge reruns use 20,000 clients, eight inbounds, one/two peers, two attachments/client, twelve samples after five warmups, Go 1.27.3 and GOMAXPROCS=2:

Peers Idle p50 legacy / v1 Idle p95 legacy / v1 Node/master SQL per cycle, legacy → v1 Idle wire bytes, legacy / v1
1 2538 / 702 ms 2730 / 922 ms 55/448 → 4/45 23,001,295 / 4,789,320
2, shared clients 5556 / 5432 ms 6621 / 5506 ms 110/896 → 8/900 46,002,590 / 9,578,640

One-peer unchanged idle/counter samples kept zero full master structural polls. In the two-peer fixture every client is shared across peers; existing ownership safeguards deliberately retain full master reconciliation. Wire/node-query work decreases there, but a large master CPU reduction is not claimed. Both cases avoided full node catalog fetches on unchanged ticks and refreshed affected peers after add/remove/config events.

Representative eight-counter writes over 4 MB of inbound configuration added about 0.30 ms on SQLite / 0.73 ms on PostgreSQL 16 when switching to generic trigger events. The 20,000-counter bounded decoder allocated 6.56 MB versus 13.82 MB, with validation CPU cost of about 43 ms versus 21 ms. These are measured tradeoffs, not claims that bounded decoding is faster.

The measurement report includes limits, current timings, repeat commands, and the original broader SQLite/PostgreSQL 18 ladders as historical results. The current end-to-end reruns use SQLite only; they isolate fetch+merge rather than the whole cron job or production latency.

Type of change

  • New feature
  • Documentation
  • Build / CI / tooling
  • Other: performance

Areas affected

  • Backend (API)
  • Statistics / traffic counters
  • Database / migrations
  • Multi-node

How was this tested?

  • Test-first reproductions: cached alias counters were dropped, oversized catalogs missed the list-limit error, and PostgreSQL ALTER TYPE failed on a column-scoped trigger. All three now pass.
  • make verify: PASS, including full Go tests, lint, frontend typecheck/format/tests (2,050 tests / 222 files), Go/frontend/Storybook builds, code generation and published OpenAPI comparison.
  • Full make race: PASS (53 packages with tests, shuffled; no reported races).
  • Exact PostgreSQL CI regression step: PASS, expanded from six to twelve required passing tests, including alias/lifecycle/cache fallback and DDL/type/rollback/recreation/reopen cases. Neither PostgreSQL DDL engine cell was skipped.
  • make node-e2e with the pinned c621ba90 baseline: PASS, 404.522 seconds, zero skips; all four old/new version pairs, restart recovery and the three-panel traffic/reset chain.
  • Thirty-second fuzz runs: PASS for list counting (953,472 executions), share links (168,135) and certificate pins (187,897).
  • Default actionlint including ShellCheck: PASS. Existing package-expansion warnings were fixed with quoted Bash arrays; package coverage and flags remain unchanged.
  • Current matched 20,000-client one/two-peer SQLite cycles and SQLite/PostgreSQL trigger microbenchmarks: PASS. Performance evidence and limitations are reported above.
  • The performance note passes the repository formatter. All 12 GitHub checks passed for a92c5f9b905e1757af0e4d7d3e7b252fa354170e: CI and Docs CI.

Existing API contracts, auth/scope/mTLS behavior and legacy fallbacks remain covered by the complete Go suite. No existing tests were removed, CI guards were strengthened, and the optimization remains enabled. No production deployment or live traffic was used.

Breaking changes

None for existing API/config users. Startup migration adds two hidden token columns, initializes legacy tokens and installs triggers with normal migration privileges. Metadata projections remain O(clients + attachments), catalogs consume per-node memory, SQLite structural edits incur an additional trigger update, and changed configurations deliberately retain full reconciliation cost. No new table/index/cache service is required.

Checklist

  • Tested locally and confirmed the behavior.
  • Added regression and integration tests.
  • Build/test/lint/typecheck gates passed locally.
  • Updated API/OpenAPI/reference documentation and performance evidence.
  • Conventional commit; no unrelated changes.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/MHSanaei/3x-ui/pull/7014 **Author:** [@HamedSanaei](https://github.com/HamedSanaei) **Created:** 10/29/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `perf/node-traffic-snapshot-7007` --- ### 📝 Commits (4) - [`96e67ae`](https://github.com/MHSanaei/3x-ui/commit/96e67ae31b1590cf0dd1675e89d171a9e78eba85) perf(node-sync): reduce redundant full traffic snapshot reads - [`fed8681`](https://github.com/MHSanaei/3x-ui/commit/fed8681069d34dcb6d6a64d01a09360d796f4215) docs(perf): format node snapshot measurement report - [`0c90a62`](https://github.com/MHSanaei/3x-ui/commit/0c90a62b16db8b25d1b4a349b2474357a2ddd295) chore(merge): reconcile node snapshot caching with upstream main - [`a92c5f9`](https://github.com/MHSanaei/3x-ui/commit/a92c5f9b905e1757af0e4d7d3e7b252fa354170e) fix(nodes): harden compact snapshot reconciliation ### 📊 Changes **48 files changed** (+5286 additions, -465 deletions) <details> <summary>View changed files</summary> 📝 `.github/workflows/ci.yml` (+22 -2) 📝 `docs/content/docs/en/reference/api/inbounds.mdx` (+14 -1) ➕ `docs/performance/cpu-profiles.csv` (+9 -0) ➕ `docs/performance/cycles-postgres.csv` (+49 -0) ➕ `docs/performance/cycles-sqlite.csv` (+49 -0) ➕ `docs/performance/events-postgres.csv` (+73 -0) ➕ `docs/performance/events-sqlite.csv` (+73 -0) ➕ `docs/performance/node-traffic-snapshot-7007.md` (+221 -0) ➕ `docs/performance/projections-postgres.csv` (+13 -0) ➕ `docs/performance/projections-sqlite.csv` (+13 -0) 📝 `docs/public/openapi.json` (+299 -0) 📝 `frontend/public/openapi.json` (+299 -0) 📝 `frontend/src/generated/examples.ts` (+72 -0) 📝 `frontend/src/generated/schemas.ts` (+217 -0) 📝 `frontend/src/generated/types.ts` (+46 -0) 📝 `frontend/src/generated/zod.ts` (+53 -0) 📝 `frontend/src/pages/api-docs/endpoints.ts` (+16 -0) 📝 `internal/database/db.go` (+15 -2) 📝 `internal/database/model/model.go` (+2 -0) ➕ `internal/database/snapshot_revision.go` (+91 -0) _...and 28 more files_ </details> ### 📄 Description ## Summary Reduce configuration work during the five-second node traffic poll while keeping counters and lifecycle state fresh. A capability-negotiated v1 endpoint sends configuration only after a durable revision change. The master skips reconciliation only when revision, ownership, lifecycle, membership and the complete remote-to-central inbound association validate; deployed aliases remain usable on cached ticks. ## Why The old path was `Remote.FetchTrafficSnapshot` -> `GET /panel/api/inbounds/list` -> full settings/preloads/UUID-SubID enrichment/shared-stat backfills -> `SetRemoteTraffic` settings parsing and `SyncInbound`. Unchanged polls repeatedly paid those database, JSON and reconciliation costs. Closes #7007 Related: #7008, #7009 ## Implementation and compatibility - Add authenticated `GET /panel/api/inbounds/trafficSnapshot?revision=...` for admin, node-admin and node-sync. Reuse existing TLS/mTLS/outbound transport; monitor remains forbidden. - Complete counters are always fresh. Omitted structure requires matching validated history and a complete client/inbound roster. Errors cannot become deletions. A present empty catalog retains full semantics and existing safeguards. - Persist hidden, GORM-read-only row tokens on inbounds/clients with native SQLite/PostgreSQL triggers, including direct/background edits. Project membership tokens and lifecycle fields; avoid steady-state settings reads/full-JSON hashing. Boot/database-connection epochs handle reopen/restart/migrations. - Validate master-side revisions, lifecycle and filtered memberships before skipping structural parsing/sweeps/`SyncInbound`. Keep the existing common delta, reset, renewal, dirty/justPushed, tombstone, ownership and GUID logic. Prune inactive caches. - Preserve validated remote inbound ID → central inbound ID bindings for deployed aliases. Restore them only after cache validation, and fall back to full reconciliation when any association is invalid. - Preflight compact collection limits before typed allocation: 65,536 catalog/counter inbounds, 1,048,576 clients/attachments/online emails, and the existing aggregate GUID-map value budgets. Malformed/oversized replies discard history without legacy downgrade. - Use unscoped revision-trigger update events with actual-change guards. Remove old trigger definitions before migration DDL, including SQLite bodies that mention retired columns; preserve counter/timestamp/no-op behavior. - Old/new pairs retain the legacy APIs. Only 404/405 trigger complete legacy fallback with a retry cooldown; auth/network/server errors surface. Protocol errors discard catalog history and fail closed. No depletion SQL, global freshness/quota semantics, heartbeat cadence, slim/full/detail response contract or frontend Inbounds behavior changes. #7008 and #7009 remain independently implementable. Existing OpenAPI paths/components were compared byte-for-value; only one route and five supporting schemas were added. ## Measurements Current matched SQLite fetch+merge reruns use 20,000 clients, eight inbounds, one/two peers, two attachments/client, twelve samples after five warmups, Go 1.27.3 and GOMAXPROCS=2: | Peers | Idle p50 legacy / v1 | Idle p95 legacy / v1 | Node/master SQL per cycle, legacy → v1 | Idle wire bytes, legacy / v1 | |---|---:|---:|---|---:| | 1 | 2538 / 702 ms | 2730 / 922 ms | 55/448 → 4/45 | 23,001,295 / 4,789,320 | | 2, shared clients | 5556 / 5432 ms | 6621 / 5506 ms | 110/896 → 8/900 | 46,002,590 / 9,578,640 | One-peer unchanged idle/counter samples kept zero full master structural polls. In the two-peer fixture every client is shared across peers; existing ownership safeguards deliberately retain full master reconciliation. Wire/node-query work decreases there, but a large master CPU reduction is **not** claimed. Both cases avoided full node catalog fetches on unchanged ticks and refreshed affected peers after add/remove/config events. Representative eight-counter writes over 4 MB of inbound configuration added about 0.30 ms on SQLite / 0.73 ms on PostgreSQL 16 when switching to generic trigger events. The 20,000-counter bounded decoder allocated 6.56 MB versus 13.82 MB, with validation CPU cost of about 43 ms versus 21 ms. These are measured tradeoffs, not claims that bounded decoding is faster. The [measurement report](https://github.com/HamedSanaei/3x-ui/blob/perf/node-traffic-snapshot-7007/docs/performance/node-traffic-snapshot-7007.md#review-hardening-7014) includes limits, current timings, repeat commands, and the original broader SQLite/PostgreSQL 18 ladders as historical results. The current end-to-end reruns use SQLite only; they isolate fetch+merge rather than the whole cron job or production latency. ## Type of change - [x] New feature - [x] Documentation - [x] Build / CI / tooling - [x] Other: performance ## Areas affected - [x] Backend (API) - [x] Statistics / traffic counters - [x] Database / migrations - [x] Multi-node ## How was this tested? - Test-first reproductions: cached alias counters were dropped, oversized catalogs missed the list-limit error, and PostgreSQL ALTER TYPE failed on a column-scoped trigger. All three now pass. - make verify: PASS, including full Go tests, lint, frontend typecheck/format/tests (2,050 tests / 222 files), Go/frontend/Storybook builds, code generation and published OpenAPI comparison. - Full make race: PASS (53 packages with tests, shuffled; no reported races). - Exact PostgreSQL CI regression step: PASS, expanded from six to twelve required passing tests, including alias/lifecycle/cache fallback and DDL/type/rollback/recreation/reopen cases. Neither PostgreSQL DDL engine cell was skipped. - make node-e2e with the pinned c621ba90 baseline: PASS, 404.522 seconds, zero skips; all four old/new version pairs, restart recovery and the three-panel traffic/reset chain. - Thirty-second fuzz runs: PASS for list counting (953,472 executions), share links (168,135) and certificate pins (187,897). - Default actionlint including ShellCheck: PASS. Existing package-expansion warnings were fixed with quoted Bash arrays; package coverage and flags remain unchanged. - Current matched 20,000-client one/two-peer SQLite cycles and SQLite/PostgreSQL trigger microbenchmarks: PASS. Performance evidence and limitations are reported above. - The performance note passes the repository formatter. All 12 GitHub checks passed for `a92c5f9b905e1757af0e4d7d3e7b252fa354170e`: [CI](https://github.com/MHSanaei/3x-ui/actions/runs/41564099842) and [Docs CI](https://github.com/MHSanaei/3x-ui/actions/runs/41564099841). Existing API contracts, auth/scope/mTLS behavior and legacy fallbacks remain covered by the complete Go suite. No existing tests were removed, CI guards were strengthened, and the optimization remains enabled. No production deployment or live traffic was used. ## Breaking changes None for existing API/config users. Startup migration adds two hidden token columns, initializes legacy tokens and installs triggers with normal migration privileges. Metadata projections remain O(clients + attachments), catalogs consume per-node memory, SQLite structural edits incur an additional trigger update, and changed configurations deliberately retain full reconciliation cost. No new table/index/cache service is required. ## Checklist - [x] Tested locally and confirmed the behavior. - [x] Added regression and integration tests. - [x] Build/test/lint/typecheck gates passed locally. - [x] Updated API/OpenAPI/reference documentation and performance evidence. - [x] Conventional commit; no unrelated changes. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
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#6576
No description provided.