[PR #6930] [MERGED] perf(ip-sync): avoid redundant client IP reads and writes #6528

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

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/6930
Author: @HamedSanaei
Created: 10/25/2026
Status: ✅ Merged
Merged: 10/25/2026
Merged by: @MHSanaei

Base: main ← Head: perf/client-ip-sync-6927


📝 Commits (6)

  • 9145918 perf(ip-sync): avoid redundant client IP reads and writes
  • 558d444 chore(ci): resolve upstream merge conflict for PR #6930
  • 878bf3b Merge branch 'main' into perf/client-ip-sync-6927
  • 43eebe3 test(ip-sync): fold the client IP sync tests into the merge test file
  • 1f8a062 docs(ip-limit): keep the #6722 marker on the collection-only branch
  • 06e0f0e Merge branch 'main' into perf/client-ip-sync-6927

📊 Changes

22 files changed (+1273 additions, -247 deletions)

View changed files

📝 .github/workflows/ci.yml (+10 -0)
📝 docs/real-client-ip.md (+6 -0)
📝 internal/database/model/node_client_ip.go (+25 -4)
📝 internal/nodee2e/harness_test.go (+27 -0)
📝 internal/nodee2e/node_sync_test.go (+112 -0)
📝 internal/web/job/check_client_ip_ban_commit_test.go (+5 -4)
📝 internal/web/job/check_client_ip_cas_test.go (+21 -9)
📝 internal/web/job/check_client_ip_frozen_ban_test.go (+4 -2)
📝 internal/web/job/check_client_ip_job.go (+50 -73)
📝 internal/web/job/check_client_ip_job_integration_test.go (+18 -19)
📝 internal/web/job/check_client_ip_job_test.go (+14 -14)
📝 internal/web/job/check_client_ip_scale_test.go (+137 -7)
➕ internal/web/job/check_client_ip_sync_postgres_test.go (+188 -0)
📝 internal/web/job/ip_limit_allowlist.go (+4 -2)
📝 internal/web/job/ip_limit_allowlist_test.go (+7 -3)
➕ internal/web/service/client_ip_sync_postgres_test.go (+36 -0)
➕ internal/web/service/client_ip_sync_scale_test.go (+206 -0)
📝 internal/web/service/client_ips_prune_test.go (+3 -3)
📝 internal/web/service/inbound_client_ips.go (+47 -73)
📝 internal/web/service/inbound_client_ips_merge_test.go (+339 -18)

...and 2 more files

📄 Description

Summary

Use one canonical model.ClientIpEntry encoder across client-IP writers and seed remote flat-row CAS merges from the existing preload. Skip identical attribution upserts and merge winning create conflicts instead of losing observations.

Why

Remote sync previously re-read each preloaded flat row before its first CAS. The service and scanner also used different ordering, so equivalent observations could produce different blobs, and attribution upserted every reported email even when its canonical bytes were unchanged.

Canonical storage is timestamp ascending, then IP text ascending, with compact [] for empty input. Encoding does not normalize addresses, filter expiry or stamp timestamps. Writers retain their existing union/filter behavior, differing empty-address treatment, 30-minute retention, GUID buckets and live local-attribution stamping.

The service now compares the original stored snapshot on its first CAS, updates the map-backed snapshot on success, and rereads only after a miss: eight attempts and at most seven intervening rereads, with the existing exhaustion error and transaction rollback. Successful inserts update that same map; insert conflicts load and merge the winning row. Scanner first inserts remain record-only; conflicts enter its existing CAS/enforcement path. Its ban-selection, frozen-ban and commit-before-publication control flow is preserved.

The unchanged attribution path does no mutation and cannot overwrite a newer concurrent row. Changed attribution upserts are not redesigned here. No external cache, service, schema migration, setting or API field change is introduced; modern arrays and legacy JSON-string payloads remain accepted.

Closes #6927.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Documentation
  • Tests only
  • Build / CI / tooling
  • Other: Performance

Areas affected

  • Frontend (UI / panel pages)
  • Backend (API endpoints, login, settings)
  • Xray config generation
  • Subscription (share links / Clash / JSON)
  • Statistics / traffic counters
  • Database / migrations
  • Install / upgrade script
  • Docker image
  • Multi-node (sub-nodes)
  • Telegram bot

How was this tested?

Passed on Windows amd64, Go 1.27.3, CGO/GCC, Node 26.12.1/npm 11.20.0, SQLite 3.53.4, and disposable PostgreSQL 18.6 and 16.15:

# PostgreSQL environment variables unset.
GOFLAGS=-p=1 make verify
GOFLAGS=-p=1 make race
make node-e2e

go test ./internal/web/service ./internal/web/job \
  -run 'ClientIp|ClientIps|NodeClientIp|IpLimit|PartitionLiveIps|SelectIpsToBan' \
  -count=1 -shuffle=on -v

go test ./internal/web/job \
  -run '^(TestProcessObserved_|TestRun_|TestWriteBanLines|TestHasLimitIp_|TestGetInboundByEmail)' \
  -count=1 -shuffle=on -v

# Run with both disposable PostgreSQL 18/16 DSNs: exactly two top-level PASSes, no skips.
XUI_DB_TYPE=postgres XUI_DB_DSN="$TEST_PG_DSN" \
go test -p=1 ./internal/web/service ./internal/web/job \
  -run '^TestClientIpSyncPostgres(Scanner)?$' -count=1 -v

go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 -color -shellcheck=

make verify passed all generation/lint/format/type checks, all Go packages, 214 frontend test files/2,000 tests, full build, Storybook and the docs OpenAPI check. Native package serialization retained every test and race instrumentation; an earlier parallel Windows run hit the unchanged MTProto fake-process test's one-second exit deadline. No MTProto source, assertion or timeout was changed.

Regression-first failures captured the redundant first reads, needless identical attribution upserts, create-conflict/duplicate-new observation loss and extra exhaustion reread. Real-SQL callback injections—not mocked CAS results—prove original-raw-snapshot matching, one reread after a forced miss, exact union/max timestamps and eight-attempt/seven-reread rollback. Alternating the real scanner and service on equal-timestamp, historical, allowlisted and charged-live entries preserves exact bytes with zero repeat flat-row writes; advancing observations still persist. Existing retention, stale-GUID, allowlist, frozen-ban and commit-publication regressions remain exercised.

Actual-process HTTP smoke used a newly built panel and a fresh SQLite database: shuffled modern reports and a legacy JSON-string report retained identical canonical bytes; one timestamp advance persisted; two concurrent additional-address pushes retained their exact union/max timestamps. Real master/node E2E passed under both enrollment scopes, including an additional stable sync cycle, offline recovery and separate GUID-attribution buckets seeded only while panels were stopped. This does not claim firewall enforcement or live-Xray collection coverage.

Repeatable measurements

The same fixtures ran before production edits and afterward: 1k/10k/20k clients, each in four reports (bench-node-0 through bench-node-3), one distinct documentation-range address per node/client. Seed/warmup were excluded. Unchanged reports reused timestamps; advancing reports changed observations; contention submitted independent report slices concurrently and verified the exact four-IP/max-timestamp union. Scanner fixtures covered single/spread inbounds and retained real live-attribution timestamp behavior.

XUI_SCALE_TEST=1 XUI_DB_TYPE=sqlite XUI_SCALE_SIZES=1000,10000,20000 \
go test ./internal/web/service ./internal/web/job \
  -run '^(TestClientIpSyncScale|TestCheckClientIpScale)$' -count=1 -v -timeout=30m

XUI_SCALE_TEST=1 XUI_DB_TYPE=postgres XUI_DB_DSN="$TEST_PG_DSN" \
XUI_SCALE_SIZES=1000,10000,20000 \
go test -p=1 ./internal/web/service ./internal/web/job \
  -run '^(TestClientIpSyncScale|TestCheckClientIpScale)$' -count=1 -v -timeout=30m

Representative PostgreSQL 18 result: 20k clients, four reports. Each cell is before → after; attempted SQL is separate from affected rows.

Phase Flat SELECTs CAS attempts / misses Flat affected rows Attribution attempted / affected Cycle elapsed
Unchanged 80,004 → 4 0/0 → 0/0 0 → 0 80,000/80,000 → 0/0 82.881s → 0.636s
Advancing, uncontended 80,004 → 4 80,000/0 → 80,000/0 80,000 → 80,000 80,000/80,000 → 80,000/80,000 127.330s → 85.020s
Four concurrent changed reports 80,007 → 60,004 80,003/3 → 140,000/60,000 80,000 → 80,000 80,000/80,000 → 80,000/80,000 94.876s → 114.870s

Tradeoff: preloaded snapshots become stale behind another full changed-report transaction. This worst-case contention fixture performs more failed CAS attempts and is slower. The fix targets unchanged/uncontended work; it does not claim a uniform speedup, and it retains exact union correctness and bounded retries rather than adding a new batching/cache subsystem.

pg_stat_statements deltas across both IP-table query shapes, captured inside the live fixtures before teardown:

Phase Statement calls before → after WAL bytes before → after FPI before → after Server execution ms before → after
Unchanged 160,008 → 8 37,568,102 → 68,548 0 → 0 2,965.817 → 69.264
Advancing 240,008 → 160,008 87,812,110 → 88,651,691 2,156 → 1,607 4,630.039 → 4,472.385
Concurrent changed 240,014 → 280,008 83,171,101 → 75,384,740 1,316 → 1 129,508.604 → 132,121.336

Server execution time aggregates concurrent statements and is not wall-clock cycle latency. Changed-workload WAL has different FPI counts, so those values are raw observations, not checkpoint-normalized improvements. The unchanged run has no affected row mutations but still measured residual WAL: zero row updates is not zero database work/WAL. Scanner live-attribution timestamps that genuinely advance remain real writes. Statistics reset stayed unchanged and deallocations were zero; no cluster-wide reset was used. Supplemental complete-counter scanner baselines used an isolated original-source snapshot with the same measurement fixture, not active-worktree source toggles.

Breaking changes

None. IP JSON field names and timestamp units are unchanged; persisted ordering is now shared and deterministic.

Checklist

  • I tested the change locally and confirmed the described behavior.
  • I added or updated tests for the new behavior (when applicable).
  • go build ./... and the test suite pass locally.
  • For frontend changes: npm run lint, npm run typecheck, and npm run build pass. (Exercised by the full gate; backend-only PR.)
  • I updated the Wiki / README / API docs if user-facing behavior changed. (Existing real-client-IP documentation updated.)
  • My commits follow the project's existing message style.
  • I have no unrelated changes mixed into this PR.

🔄 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/6930 **Author:** [@HamedSanaei](https://github.com/HamedSanaei) **Created:** 10/25/2026 **Status:** ✅ Merged **Merged:** 10/25/2026 **Merged by:** [@MHSanaei](https://github.com/MHSanaei) **Base:** `main` ← **Head:** `perf/client-ip-sync-6927` --- ### 📝 Commits (6) - [`9145918`](https://github.com/MHSanaei/3x-ui/commit/91459180f927ea31dd1ba7c418cff8101b3b01d6) perf(ip-sync): avoid redundant client IP reads and writes - [`558d444`](https://github.com/MHSanaei/3x-ui/commit/558d444bbe70e7ee38098bc873a2ef65745d3bb7) chore(ci): resolve upstream merge conflict for PR #6930 - [`878bf3b`](https://github.com/MHSanaei/3x-ui/commit/878bf3bc9419f4651d7a52152a7ceaeb2ad52740) Merge branch 'main' into perf/client-ip-sync-6927 - [`43eebe3`](https://github.com/MHSanaei/3x-ui/commit/43eebe3203e1f8782f921553d383ae127f6e7f49) test(ip-sync): fold the client IP sync tests into the merge test file - [`1f8a062`](https://github.com/MHSanaei/3x-ui/commit/1f8a0623020bb2462d2066aa3b5cc871aa1fbc88) docs(ip-limit): keep the #6722 marker on the collection-only branch - [`06e0f0e`](https://github.com/MHSanaei/3x-ui/commit/06e0f0e9fa173c3bc709d95acd474221cebef77e) Merge branch 'main' into perf/client-ip-sync-6927 ### 📊 Changes **22 files changed** (+1273 additions, -247 deletions) <details> <summary>View changed files</summary> 📝 `.github/workflows/ci.yml` (+10 -0) 📝 `docs/real-client-ip.md` (+6 -0) 📝 `internal/database/model/node_client_ip.go` (+25 -4) 📝 `internal/nodee2e/harness_test.go` (+27 -0) 📝 `internal/nodee2e/node_sync_test.go` (+112 -0) 📝 `internal/web/job/check_client_ip_ban_commit_test.go` (+5 -4) 📝 `internal/web/job/check_client_ip_cas_test.go` (+21 -9) 📝 `internal/web/job/check_client_ip_frozen_ban_test.go` (+4 -2) 📝 `internal/web/job/check_client_ip_job.go` (+50 -73) 📝 `internal/web/job/check_client_ip_job_integration_test.go` (+18 -19) 📝 `internal/web/job/check_client_ip_job_test.go` (+14 -14) 📝 `internal/web/job/check_client_ip_scale_test.go` (+137 -7) ➕ `internal/web/job/check_client_ip_sync_postgres_test.go` (+188 -0) 📝 `internal/web/job/ip_limit_allowlist.go` (+4 -2) 📝 `internal/web/job/ip_limit_allowlist_test.go` (+7 -3) ➕ `internal/web/service/client_ip_sync_postgres_test.go` (+36 -0) ➕ `internal/web/service/client_ip_sync_scale_test.go` (+206 -0) 📝 `internal/web/service/client_ips_prune_test.go` (+3 -3) 📝 `internal/web/service/inbound_client_ips.go` (+47 -73) 📝 `internal/web/service/inbound_client_ips_merge_test.go` (+339 -18) _...and 2 more files_ </details> ### 📄 Description ## Summary Use one canonical `model.ClientIpEntry` encoder across client-IP writers and seed remote flat-row CAS merges from the existing preload. Skip identical attribution upserts and merge winning create conflicts instead of losing observations. ## Why Remote sync previously re-read each preloaded flat row before its first CAS. The service and scanner also used different ordering, so equivalent observations could produce different blobs, and attribution upserted every reported email even when its canonical bytes were unchanged. Canonical storage is timestamp ascending, then IP text ascending, with compact `[]` for empty input. Encoding does not normalize addresses, filter expiry or stamp timestamps. Writers retain their existing union/filter behavior, differing empty-address treatment, 30-minute retention, GUID buckets and live local-attribution stamping. The service now compares the original stored snapshot on its first CAS, updates the map-backed snapshot on success, and rereads only after a miss: eight attempts and at most seven intervening rereads, with the existing exhaustion error and transaction rollback. Successful inserts update that same map; insert conflicts load and merge the winning row. Scanner first inserts remain record-only; conflicts enter its existing CAS/enforcement path. Its ban-selection, frozen-ban and commit-before-publication control flow is preserved. The unchanged attribution path does no mutation and cannot overwrite a newer concurrent row. Changed attribution upserts are not redesigned here. No external cache, service, schema migration, setting or API field change is introduced; modern arrays and legacy JSON-string payloads remain accepted. Closes #6927. ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactoring (no behavior change) - [x] Documentation - [ ] Tests only - [x] Build / CI / tooling - [x] Other: Performance ## Areas affected - [ ] Frontend (UI / panel pages) - [x] Backend (API endpoints, login, settings) - [ ] Xray config generation - [ ] Subscription (share links / Clash / JSON) - [ ] Statistics / traffic counters - [x] Database / migrations - [ ] Install / upgrade script - [ ] Docker image - [x] Multi-node (sub-nodes) - [ ] Telegram bot ## How was this tested? Passed on Windows amd64, Go 1.27.3, CGO/GCC, Node 26.12.1/npm 11.20.0, SQLite 3.53.4, and disposable PostgreSQL 18.6 and 16.15: ```bash # PostgreSQL environment variables unset. GOFLAGS=-p=1 make verify GOFLAGS=-p=1 make race make node-e2e go test ./internal/web/service ./internal/web/job \ -run 'ClientIp|ClientIps|NodeClientIp|IpLimit|PartitionLiveIps|SelectIpsToBan' \ -count=1 -shuffle=on -v go test ./internal/web/job \ -run '^(TestProcessObserved_|TestRun_|TestWriteBanLines|TestHasLimitIp_|TestGetInboundByEmail)' \ -count=1 -shuffle=on -v # Run with both disposable PostgreSQL 18/16 DSNs: exactly two top-level PASSes, no skips. XUI_DB_TYPE=postgres XUI_DB_DSN="$TEST_PG_DSN" \ go test -p=1 ./internal/web/service ./internal/web/job \ -run '^TestClientIpSyncPostgres(Scanner)?$' -count=1 -v go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 -color -shellcheck= ``` `make verify` passed all generation/lint/format/type checks, all Go packages, 214 frontend test files/2,000 tests, full build, Storybook and the docs OpenAPI check. Native package serialization retained every test and race instrumentation; an earlier parallel Windows run hit the unchanged MTProto fake-process test's one-second exit deadline. No MTProto source, assertion or timeout was changed. Regression-first failures captured the redundant first reads, needless identical attribution upserts, create-conflict/duplicate-new observation loss and extra exhaustion reread. Real-SQL callback injections—not mocked CAS results—prove original-raw-snapshot matching, one reread after a forced miss, exact union/max timestamps and eight-attempt/seven-reread rollback. Alternating the real scanner and service on equal-timestamp, historical, allowlisted and charged-live entries preserves exact bytes with zero repeat flat-row writes; advancing observations still persist. Existing retention, stale-GUID, allowlist, frozen-ban and commit-publication regressions remain exercised. Actual-process HTTP smoke used a newly built panel and a fresh SQLite database: shuffled modern reports and a legacy JSON-string report retained identical canonical bytes; one timestamp advance persisted; two concurrent additional-address pushes retained their exact union/max timestamps. Real master/node E2E passed under both enrollment scopes, including an additional stable sync cycle, offline recovery and separate GUID-attribution buckets seeded only while panels were stopped. This does not claim firewall enforcement or live-Xray collection coverage. ### Repeatable measurements The same fixtures ran before production edits and afterward: 1k/10k/20k clients, each in four reports (`bench-node-0` through `bench-node-3`), one distinct documentation-range address per node/client. Seed/warmup were excluded. Unchanged reports reused timestamps; advancing reports changed observations; contention submitted independent report slices concurrently and verified the exact four-IP/max-timestamp union. Scanner fixtures covered single/spread inbounds and retained real live-attribution timestamp behavior. ```bash XUI_SCALE_TEST=1 XUI_DB_TYPE=sqlite XUI_SCALE_SIZES=1000,10000,20000 \ go test ./internal/web/service ./internal/web/job \ -run '^(TestClientIpSyncScale|TestCheckClientIpScale)$' -count=1 -v -timeout=30m XUI_SCALE_TEST=1 XUI_DB_TYPE=postgres XUI_DB_DSN="$TEST_PG_DSN" \ XUI_SCALE_SIZES=1000,10000,20000 \ go test -p=1 ./internal/web/service ./internal/web/job \ -run '^(TestClientIpSyncScale|TestCheckClientIpScale)$' -count=1 -v -timeout=30m ``` Representative PostgreSQL 18 result: 20k clients, four reports. Each cell is **before → after**; attempted SQL is separate from affected rows. | Phase | Flat SELECTs | CAS attempts / misses | Flat affected rows | Attribution attempted / affected | Cycle elapsed | |---|---:|---:|---:|---:|---:| | Unchanged | 80,004 → 4 | 0/0 → 0/0 | 0 → 0 | 80,000/80,000 → 0/0 | 82.881s → 0.636s | | Advancing, uncontended | 80,004 → 4 | 80,000/0 → 80,000/0 | 80,000 → 80,000 | 80,000/80,000 → 80,000/80,000 | 127.330s → 85.020s | | Four concurrent changed reports | 80,007 → 60,004 | 80,003/3 → 140,000/60,000 | 80,000 → 80,000 | 80,000/80,000 → 80,000/80,000 | 94.876s → 114.870s | **Tradeoff:** preloaded snapshots become stale behind another full changed-report transaction. This worst-case contention fixture performs more failed CAS attempts and is slower. The fix targets unchanged/uncontended work; it does not claim a uniform speedup, and it retains exact union correctness and bounded retries rather than adding a new batching/cache subsystem. `pg_stat_statements` deltas across both IP-table query shapes, captured inside the live fixtures before teardown: | Phase | Statement calls before → after | WAL bytes before → after | FPI before → after | Server execution ms before → after | |---|---:|---:|---:|---:| | Unchanged | 160,008 → 8 | 37,568,102 → 68,548 | 0 → 0 | 2,965.817 → 69.264 | | Advancing | 240,008 → 160,008 | 87,812,110 → 88,651,691 | 2,156 → 1,607 | 4,630.039 → 4,472.385 | | Concurrent changed | 240,014 → 280,008 | 83,171,101 → 75,384,740 | 1,316 → 1 | 129,508.604 → 132,121.336 | Server execution time aggregates concurrent statements and is not wall-clock cycle latency. Changed-workload WAL has different FPI counts, so those values are raw observations, not checkpoint-normalized improvements. The unchanged run has no affected row mutations but still measured residual WAL: zero row updates is not zero database work/WAL. Scanner live-attribution timestamps that genuinely advance remain real writes. Statistics reset stayed unchanged and deallocations were zero; no cluster-wide reset was used. Supplemental complete-counter scanner baselines used an isolated original-source snapshot with the same measurement fixture, not active-worktree source toggles. ## Breaking changes None. IP JSON field names and timestamp units are unchanged; persisted ordering is now shared and deterministic. ## Checklist - [x] I tested the change locally and confirmed the described behavior. - [x] I added or updated tests for the new behavior (when applicable). - [x] `go build ./...` and the test suite pass locally. - [x] For frontend changes: `npm run lint`, `npm run typecheck`, and `npm run build` pass. (Exercised by the full gate; backend-only PR.) - [x] I updated the Wiki / README / API docs if user-facing behavior changed. (Existing real-client-IP documentation updated.) - [x] My commits follow the project's existing message style. - [x] I have no unrelated changes mixed into this PR. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-02 04:09:24 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#6528
No description provided.