[GH-ISSUE #6927] [Performance]: Reduce PostgreSQL round trips and write amplification in multi-node client IP synchronization #4584

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

Originally created by @HamedSanaei on GitHub (Oct 25, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6927

Summary

At scale, collection and cross-node synchronization of client IPs generates a very large number of small PostgreSQL reads and writes. The current code correctly includes compare-and-set (CAS) protection against lost updates (see #6587), but the per-client/row SQL cost of the cluster IP synchronization path merits optimization.

This is a performance-only proposal. IP-limit correctness and security must take precedence over query-count reduction. No Redis or external cache is requested.

Affected paths

  • internal/web/service/inbound_client_ips.go: MergeInboundClientIps loads current rows, iterates incoming clients, and mergeExistingClientIps executes per-row reads and CAS retries (SELECT ... WHERE id / UPDATE ... WHERE id AND ips = old).
  • internal/web/job/check_client_ip_job.go: processObserved already batches initial lookups but processes each client's IP row with guarded updates; keep that protection.
  • internal/web/service/inbound_node_ips.go: upsertNodeClientIps loads existing rows per GUID and issues INSERT ... ON CONFLICT DO UPDATE individually for each email, even when merged content is identical.

Already implemented: updateInboundClientIps and mergeExistingClientIps skip unchanged merged IP strings. This issue is NOT proposing to redo that fix; it targets the remaining round trips, per-row attribution upserts and duplicate processing.

Production evidence (PostgreSQL 18)

Cumulative pg_stat_statements and table statistics collected since 2026-10-21:

Query shape Approximate executions
SELECT * FROM inbound_client_ips WHERE id = $1 ... 13.90 million
UPDATE inbound_client_ips SET ips = ... WHERE id = ? AND ips = ? 5.06 million
UPDATE inbound_client_ips SET client_email = ..., ips = ... WHERE id = ? 3.41 million
INSERT INTO node_client_ips ... ON CONFLICT ... DO UPDATE 3.40 million

In a separate 20-second sample: 542 per-ID IP reads, 153 CAS IP updates, and 118 node_client_ips upserts. The IP-read calls themselves are fast, but their volume creates avoidable overhead.

These counts characterize one workload and are not expected on all installations.

Suggested direction for discussion

  1. Instrument each stage of IP sync (incoming records, genuinely changed IP/timestamp sets, CAS retries, rows written, and SQL calls). Locate duplicate merge/upsert work before changing semantics.
  2. In upsertNodeClientIps, omit truly unchanged merged rows, including the ON CONFLICT write; evaluate batched upsert with a deterministic lock/order strategy and PostgreSQL IS DISTINCT FROM where appropriate (plus portable SQLite behavior).
  3. Investigate whether existing preloaded rows can reduce additional per-ID round trips in MergeInboundClientIps without weakening optimistic concurrency. A stale snapshot must never overwrite more recent IPs: preserve CAS, retry/re-merge and deterministic ordering.
  4. If two nodes report identical observations repeatedly, deduplicate within each sync batch. Do not suppress updated timestamps just because the literal IP address is unchanged: timestamps govern liveness/expiry.
  5. Compare PostgreSQL calls, WAL bytes, per-cycle latency and retained IP semantics before/after.

Acceptance criteria

  • Material reduction in redundant SQL calls and/or WAL on a repeatable multi-node IP-sync workload.
  • No lost updates under concurrent local scans + remote merges (regression for #6587).
  • IP-limit enforcement, allowlist, bans, and live-versus-historical IP distinctions remain correct.
  • 30-minute IP retention/cleanup, timestamps, node GUID attribution, and stale-node handling remain correct.
  • PostgreSQL and SQLite tests, race/concurrency tests and multi-node regression tests pass.
  • No Redis, external cache, or new mandatory service.

Related but separate: #6587 (lost-update correctness), #6286 (expiry), #6285 (orphaned GUID attribution). This issue targets database write amplification without altering their invariants.

Originally created by @HamedSanaei on GitHub (Oct 25, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6927 ## Summary At scale, collection and cross-node synchronization of client IPs generates a very large number of small PostgreSQL reads and writes. The current code correctly includes compare-and-set (CAS) protection against lost updates (see #6587), but the per-client/row SQL cost of the **cluster IP synchronization** path merits optimization. This is a performance-only proposal. **IP-limit correctness and security must take precedence over query-count reduction.** No Redis or external cache is requested. ## Affected paths - [`internal/web/service/inbound_client_ips.go`](https://github.com/MHSanaei/3x-ui/blob/main/internal/web/service/inbound_client_ips.go): `MergeInboundClientIps` loads current rows, iterates incoming clients, and `mergeExistingClientIps` executes per-row reads and CAS retries (`SELECT ... WHERE id` / `UPDATE ... WHERE id AND ips = old`). - [`internal/web/job/check_client_ip_job.go`](https://github.com/MHSanaei/3x-ui/blob/main/internal/web/job/check_client_ip_job.go): `processObserved` already batches initial lookups but processes each client's IP row with guarded updates; keep that protection. - [`internal/web/service/inbound_node_ips.go`](https://github.com/MHSanaei/3x-ui/blob/main/internal/web/service/inbound_node_ips.go): `upsertNodeClientIps` loads existing rows per GUID and issues `INSERT ... ON CONFLICT DO UPDATE` individually for each email, even when merged content is identical. **Already implemented:** `updateInboundClientIps` and `mergeExistingClientIps` skip unchanged merged IP strings. This issue is NOT proposing to redo that fix; it targets the remaining round trips, per-row attribution upserts and duplicate processing. ## Production evidence (PostgreSQL 18) Cumulative `pg_stat_statements` and table statistics collected since 2026-10-21: | Query shape | Approximate executions | | --- | ---: | | `SELECT * FROM inbound_client_ips WHERE id = $1 ...` | 13.90 million | | `UPDATE inbound_client_ips SET ips = ... WHERE id = ? AND ips = ?` | 5.06 million | | `UPDATE inbound_client_ips SET client_email = ..., ips = ... WHERE id = ?` | 3.41 million | | `INSERT INTO node_client_ips ... ON CONFLICT ... DO UPDATE` | 3.40 million | In a separate 20-second sample: 542 per-ID IP reads, 153 CAS IP updates, and 118 `node_client_ips` upserts. The IP-read calls themselves are fast, but their volume creates avoidable overhead. These counts characterize one workload and are not expected on all installations. ## Suggested direction for discussion 1. Instrument each stage of IP sync (incoming records, genuinely changed IP/timestamp sets, CAS retries, rows written, and SQL calls). Locate duplicate merge/upsert work before changing semantics. 2. In `upsertNodeClientIps`, omit **truly unchanged** merged rows, including the `ON CONFLICT` write; evaluate batched upsert with a deterministic lock/order strategy and PostgreSQL `IS DISTINCT FROM` where appropriate (plus portable SQLite behavior). 3. Investigate whether existing preloaded rows can reduce additional per-ID round trips in `MergeInboundClientIps` without weakening optimistic concurrency. A stale snapshot must never overwrite more recent IPs: preserve CAS, retry/re-merge and deterministic ordering. 4. If two nodes report identical observations repeatedly, deduplicate within each sync batch. Do not suppress updated timestamps just because the literal IP address is unchanged: **timestamps govern liveness/expiry**. 5. Compare PostgreSQL calls, WAL bytes, per-cycle latency and retained IP semantics before/after. ## Acceptance criteria - [ ] Material reduction in redundant SQL calls and/or WAL on a repeatable multi-node IP-sync workload. - [ ] No lost updates under concurrent local scans + remote merges (regression for #6587). - [ ] IP-limit enforcement, allowlist, bans, and live-versus-historical IP distinctions remain correct. - [ ] 30-minute IP retention/cleanup, timestamps, node GUID attribution, and stale-node handling remain correct. - [ ] PostgreSQL and SQLite tests, race/concurrency tests and multi-node regression tests pass. - [ ] No Redis, external cache, or new mandatory service. Related but separate: #6587 (lost-update correctness), #6286 (expiry), #6285 (orphaned GUID attribution). This issue targets **database write amplification** without altering their invariants.
bsakaguchi 2026-10-31 20:40:41 +07:00
  • closed this issue
  • added the
    bug
    label
Author
Owner

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

The redundancy you measured is real, and part of it is a defect rather than just tuning. The two writers of inbound_client_ips.ips serialize the same IP set in opposite orders. So each one's "skip if unchanged" string compare fails after the other has written, and a row both of them touch gets rewritten on every cycle even when its IP set has not changed. Separately, mergeExistingClientIps re-SELECTs every row it already holds in memory, and upsertNodeClientIps upserts every email without comparing it to the stored row.

1. The two writers sort the blob in opposite orders, so the unchanged-skip never fires on shared rows

The scan job writes oldest-first, with the IP as a tie-breaker (internal/web/job/check_client_ip_job.go:588-593, sortedIpsFromMap):

if out[i].Timestamp != out[j].Timestamp {
    return out[i].Timestamp < out[j].Timestamp
}
return out[i].IP < out[j].IP

When the limit is enforced it writes kept + allowedIps + historicalIps, concatenated in that order (check_client_ip_job.go:550-551). The cross-node merge writes newest-first, with no tie-breaker (internal/web/service/inbound_client_ips.go:86):

sort.Slice(out, func(i, j int) bool { return out[i].Timestamp > out[j].Timestamp })

Both writers then skip the write only on an exact string match: if newIps == inboundClientIps.Ips (check_client_ip_job.go:559) and if row.Ips == mergedStr (inbound_client_ips.go:201). With two or more IPs the strings never match after the other writer has run, so each side issues a CAS UPDATE. Because there is no tie-breaker, IPs that share a timestamp also come out of the merge in a random order (Go map iteration + sort.Slice). So the merge alone can produce a "changed" blob from identical input.

Where this happens: on a node, the master's push (node_traffic_sync_job.go:466 → server.go:550 MergeInboundClientIps) competes with the node's own scan for every client it hosts. On the master, it happens for any client the master also serves locally. Comments in the code say the skip is meant to work: "sorted so unchanged scans skip the write" (check_client_ip_job.go:554-555). No test checks that the blob stays stable across both writers.

2. A per-row SELECT the snapshot already covers

MergeInboundClientIps loads every row up front (inbound_client_ips.go:98). Then for every incoming email that already has a row, mergeExistingClientIps reads it again before its first attempt (inbound_client_ips.go:191):

if err := tx.Where("id = ?", id).First(&row).Error; err != nil {

That is one SELECT ... WHERE id per reported email, per node, per cycle, whether or not anything changed. This matches your 13.9M reads against 5.06M CAS updates. The CAS in CasUpdateInboundClientIps (WHERE id = ? AND ips = ?, line 178) already protects a stale snapshot. The first attempt can therefore use the preloaded current.Ips as the expected value and re-read only after RowsAffected == 0, without weakening #6587.

3. upsertNodeClientIps writes every email unconditionally

internal/web/service/inbound_node_ips.go:102-110 marshals the merged entries and always runs INSERT ... ON CONFLICT (node_guid, email) DO UPDATE SET ips. It never compares the result with existingByEmail[email].Ips, which it has already loaded (line 59). It runs from two places: every local scan (check_client_ip_job.go:408, RecordLocalClientIps) and every node attribution pull (node_traffic_sync_job.go:486, MergeClientIpsByGuid). Two caveats for a fix:

  • mergeModelClientIpEntries (line 44) has the same tie-breaker gap, so the order must be made deterministic before an equality skip can work.
  • With the live API, every attribution entry is stamped now on each scan (check_client_ip_job.go:345-346). Local-scan rows therefore really change every scan. As you said, timestamps drive expiry and must not be suppressed. Skipping unchanged rows mainly saves writes on the MergeClientIpsByGuid path.

About point 4 of your proposal: within one MergeInboundClientIps batch, emails are already unique, because the batch is one node's inbound_client_ips rows, keyed by client_email. The duplicate work is across nodes and across writers (items 1–3), not inside a batch.

About the UPDATE inbound_client_ips SET client_email = ..., ips = ... WHERE id = ? shape (3.41M): that matches the blind tx.Save(inboundClientIps) that 8f120155 (fix(ip-limit): CAS-retry inbound_client_ips merges under Postgres (#6612)) removed. That commit first shipped in v3.10.0. I found no code on the current default branch that emits that statement. Those counts most likely come from a panel or node running a version older than v3.10.0, or from before an upgrade (inference).

Verdict:        Confirmed bug
Severity:       Medium
Confidence:     High
Root cause:     internal/web/job/check_client_ip_job.go:588 (sortedIpsFromMap, oldest-first + IP tie-break)
                and internal/web/service/inbound_client_ips.go:86 (mergeClientIpEntries, newest-first, no
                tie-break) serialize the same set differently, so the string-equality skips at
                check_client_ip_job.go:559 and inbound_client_ips.go:201 miss on every row both write.
                Also: inbound_client_ips.go:191 re-SELECTs a row already in the line-98 snapshot;
                inbound_node_ips.go:104 upserts without comparing to the loaded row.
Same class:     inbound_node_ips.go:44 mergeModelClientIpEntries (same unstable newest-first sort);
                callers of upsertNodeClientIps: check_client_ip_job.go:408, node_traffic_sync_job.go:486;
                callers of MergeInboundClientIps: node_traffic_sync_job.go:453, controller/server.go:550
Already fixed:  Still present on the default branch (73fad424). The skip-unchanged guards came with
                8f120155 (v3.10.0) and 49c0600f (unreleased); neither aligns the sort orders.
Duplicate of:   Related: #6587, #6286, #6285
Evidence:       quoted lines above; no test asserts blob stability across the scan and merge writers
Not determined: Which 3x-ui version each panel/node in your cluster runs. Running `x-ui` → version on
                each one would confirm where the 3.41M Save-shaped UPDATEs come from.

Suggested fix: Give both writers one shared canonical serializer, with one fixed sort order and the IP as tie-breaker, so a byte-equal compare means set-equal on every path. Use it in sortedIpsFromMap/the enforce path, mergeClientIpEntries and mergeModelClientIpEntries. Then let mergeExistingClientIps try its first CAS against the preloaded current.Ips and re-read only on a miss, and let upsertNodeClientIps skip emails whose canonical blob equals the stored one. A batched ON CONFLICT is a separate, optional step on top of that.

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

<!-- gh-comment-id:6391946970 --> @github-actions[bot] commented on GitHub (Oct 25, 2026): The redundancy you measured is real, and part of it is a defect rather than just tuning. The two writers of `inbound_client_ips.ips` serialize the same IP set in **opposite orders**. So each one's "skip if unchanged" string compare fails after the other has written, and a row both of them touch gets rewritten on every cycle even when its IP set has not changed. Separately, `mergeExistingClientIps` re-SELECTs every row it already holds in memory, and `upsertNodeClientIps` upserts every email without comparing it to the stored row. **1. The two writers sort the blob in opposite orders, so the unchanged-skip never fires on shared rows** The scan job writes **oldest-first**, with the IP as a tie-breaker (`internal/web/job/check_client_ip_job.go:588-593`, `sortedIpsFromMap`): ```go if out[i].Timestamp != out[j].Timestamp { return out[i].Timestamp < out[j].Timestamp } return out[i].IP < out[j].IP ``` When the limit is enforced it writes `kept` + `allowedIps` + `historicalIps`, concatenated in that order (`check_client_ip_job.go:550-551`). The cross-node merge writes **newest-first**, with no tie-breaker (`internal/web/service/inbound_client_ips.go:86`): ```go sort.Slice(out, func(i, j int) bool { return out[i].Timestamp > out[j].Timestamp }) ``` Both writers then skip the write only on an exact string match: `if newIps == inboundClientIps.Ips` (`check_client_ip_job.go:559`) and `if row.Ips == mergedStr` (`inbound_client_ips.go:201`). With two or more IPs the strings never match after the other writer has run, so each side issues a CAS `UPDATE`. Because there is no tie-breaker, IPs that share a timestamp also come out of the merge in a random order (Go map iteration + `sort.Slice`). So the merge alone can produce a "changed" blob from identical input. Where this happens: on a **node**, the master's push (`node_traffic_sync_job.go:466` → `server.go:550` `MergeInboundClientIps`) competes with the node's own scan for every client it hosts. On the **master**, it happens for any client the master also serves locally. Comments in the code say the skip is meant to work: "sorted so unchanged scans skip the write" (`check_client_ip_job.go:554-555`). No test checks that the blob stays stable across both writers. **2. A per-row SELECT the snapshot already covers** `MergeInboundClientIps` loads every row up front (`inbound_client_ips.go:98`). Then for every incoming email that already has a row, `mergeExistingClientIps` reads it again before its first attempt (`inbound_client_ips.go:191`): ```go if err := tx.Where("id = ?", id).First(&row).Error; err != nil { ``` That is one `SELECT ... WHERE id` per reported email, per node, per cycle, whether or not anything changed. This matches your 13.9M reads against 5.06M CAS updates. The CAS in `CasUpdateInboundClientIps` (`WHERE id = ? AND ips = ?`, line 178) already protects a stale snapshot. The first attempt can therefore use the preloaded `current.Ips` as the expected value and re-read only after `RowsAffected == 0`, without weakening #6587. **3. `upsertNodeClientIps` writes every email unconditionally** `internal/web/service/inbound_node_ips.go:102-110` marshals the merged entries and always runs `INSERT ... ON CONFLICT (node_guid, email) DO UPDATE SET ips`. It never compares the result with `existingByEmail[email].Ips`, which it has already loaded (line 59). It runs from two places: every local scan (`check_client_ip_job.go:408`, `RecordLocalClientIps`) and every node attribution pull (`node_traffic_sync_job.go:486`, `MergeClientIpsByGuid`). Two caveats for a fix: - `mergeModelClientIpEntries` (line 44) has the same tie-breaker gap, so the order must be made deterministic before an equality skip can work. - With the live API, every attribution entry is stamped `now` on each scan (`check_client_ip_job.go:345-346`). Local-scan rows therefore really change every scan. As you said, timestamps drive expiry and must not be suppressed. Skipping unchanged rows mainly saves writes on the `MergeClientIpsByGuid` path. **About point 4 of your proposal:** within one `MergeInboundClientIps` batch, emails are already unique, because the batch is one node's `inbound_client_ips` rows, keyed by `client_email`. The duplicate work is across nodes and across writers (items 1–3), not inside a batch. **About the `UPDATE inbound_client_ips SET client_email = ..., ips = ... WHERE id = ?` shape (3.41M):** that matches the blind `tx.Save(inboundClientIps)` that 8f120155 (`fix(ip-limit): CAS-retry inbound_client_ips merges under Postgres (#6612)`) removed. That commit first shipped in v3.10.0. I found no code on the current default branch that emits that statement. Those counts most likely come from a panel or node running a version older than v3.10.0, or from before an upgrade (inference). ``` Verdict: Confirmed bug Severity: Medium Confidence: High Root cause: internal/web/job/check_client_ip_job.go:588 (sortedIpsFromMap, oldest-first + IP tie-break) and internal/web/service/inbound_client_ips.go:86 (mergeClientIpEntries, newest-first, no tie-break) serialize the same set differently, so the string-equality skips at check_client_ip_job.go:559 and inbound_client_ips.go:201 miss on every row both write. Also: inbound_client_ips.go:191 re-SELECTs a row already in the line-98 snapshot; inbound_node_ips.go:104 upserts without comparing to the loaded row. Same class: inbound_node_ips.go:44 mergeModelClientIpEntries (same unstable newest-first sort); callers of upsertNodeClientIps: check_client_ip_job.go:408, node_traffic_sync_job.go:486; callers of MergeInboundClientIps: node_traffic_sync_job.go:453, controller/server.go:550 Already fixed: Still present on the default branch (73fad424). The skip-unchanged guards came with 8f120155 (v3.10.0) and 49c0600f (unreleased); neither aligns the sort orders. Duplicate of: Related: #6587, #6286, #6285 Evidence: quoted lines above; no test asserts blob stability across the scan and merge writers Not determined: Which 3x-ui version each panel/node in your cluster runs. Running `x-ui` → version on each one would confirm where the 3.41M Save-shaped UPDATEs come from. ``` Suggested fix: Give both writers one shared canonical serializer, with one fixed sort order and the IP as tie-breaker, so a byte-equal compare means set-equal on every path. Use it in `sortedIpsFromMap`/the enforce path, `mergeClientIpEntries` and `mergeModelClientIpEntries`. Then let `mergeExistingClientIps` try its first CAS against the preloaded `current.Ips` and re-read only on a miss, and let `upsertNodeClientIps` skip emails whose canonical blob equals the stored one. A batched `ON CONFLICT` is a separate, optional step on top of that. *This reply was generated automatically; a maintainer may follow up.* <!-- claude-issue:analyst -->
Author
Owner

@HamedSanaei commented on GitHub (Oct 25, 2026):

Implemented in https://github.com/MHSanaei/3x-ui/pull/6930 and pushed as 91459180f927ea31dd1ba7c418cff8101b3b01d6 (perf/client-ip-sync-6927).

All IP writers now use model.ClientIpEntry with canonical timestamp/IP ordering and compact JSON. Remote merges use their preload for the first CAS, compare against the original stored bytes, reread only after contention, and preserve the eight-attempt/seven-reread bound, exact exhaustion error and rollback. Winning insert conflicts and duplicate payload emails retain their union instead of losing observations. Identical attribution blobs skip upserts; timestamp advances remain real writes.

The 30-minute retention window, maximum timestamp per address, legacy JSON-string input, GUID separation, differing empty-address rules, live local-attribution stamping, scanner first-scan behavior, allowlist/frozen-ban semantics and commit-before-ban publication are preserved. Changed attribution upserts are not redesigned; this is not a claim to fix every pre-existing changed-attribution race.

Checks passed on SQLite 3.53.4 and real PostgreSQL 18.6/16.15:

  • GOFLAGS=-p=1 make verify and GOFLAGS=-p=1 make race, with every package/test and race instrumentation retained. The full gate included 214 frontend test files/2,000 tests, build/Storybook and generated/OpenAPI checks.
  • The requested shuffled service/job IP regression pattern and additional scanner enforcement/transactional flows.
  • Exact CI entry go test -p=1 ./internal/web/service ./internal/web/job -run '^TestClientIpSyncPostgres(Scanner)?$' -count=1 -v: exactly two top-level PASSes on each PG version, no skips; actionlint passed.
  • Real master/node E2E under both enrollment scopes: exact union/max timestamps, stable additional sync cycle, offline recovery and separate GUID buckets seeded only while panels were stopped. No live-Xray/firewall claim.
  • Newly built disposable-panel HTTP smoke: shuffled modern and legacy-string reports kept identical bytes; an advancing timestamp and two concurrent extra addresses persisted correctly.

Regression-first tests failed before the production edit for redundant reads/writes, create-conflict/duplicate-new observation loss and the extra exhaustion reread. Real SQL injections, not mocked CAS outcomes, exercise contention and rollback.

Measured on the same 1k/10k/20k fixtures before/after, four overlapping node reports, warm union seeded outside timing. Representative PostgreSQL 18 result at 20k clients; each cell is before → after:

Phase Flat SELECTs CAS attempts / misses Attribution attempted / affected Cycle elapsed
Unchanged 80,004 → 4 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 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 94.876s → 114.870s

Flat affected rows were zero in the unchanged phase and 80,000 in each changed phase, on both revisions; the exact four-IP/max-timestamp union passed in every phase.

Phase PG statement calls before → after WAL bytes before → after FPI before → after
Unchanged 160,008 → 8 37,568,102 → 68,548 0 → 0
Advancing 240,008 → 160,008 87,812,110 → 88,651,691 2,156 → 1,607
Concurrent changed 240,014 → 280,008 83,171,101 → 75,384,740 1,316 → 1

Tradeoff: synchronized all-changed reports make preloaded snapshots stale and increase failed CAS work; this worst-case phase is slower. The measured benefit is unchanged/uncontended sync, not a uniform speedup. Changed-phase WAL has differing FPI conditions and is reported raw, not as a normalized reduction. Zero affected row mutations is not zero WAL. Scanner live attribution still writes genuinely advancing timestamps. Statistics were captured before fixture teardown with unchanged stats_reset, dealloc=0, and no cluster-wide reset. No external cache/service or schema/API change is introduced.

<!-- gh-comment-id:6394130121 --> @HamedSanaei commented on GitHub (Oct 25, 2026): Implemented in https://github.com/MHSanaei/3x-ui/pull/6930 and pushed as `91459180f927ea31dd1ba7c418cff8101b3b01d6` (`perf/client-ip-sync-6927`). All IP writers now use `model.ClientIpEntry` with canonical timestamp/IP ordering and compact JSON. Remote merges use their preload for the first CAS, compare against the original stored bytes, reread only after contention, and preserve the eight-attempt/seven-reread bound, exact exhaustion error and rollback. Winning insert conflicts and duplicate payload emails retain their union instead of losing observations. Identical attribution blobs skip upserts; timestamp advances remain real writes. The 30-minute retention window, maximum timestamp per address, legacy JSON-string input, GUID separation, differing empty-address rules, live local-attribution stamping, scanner first-scan behavior, allowlist/frozen-ban semantics and commit-before-ban publication are preserved. Changed attribution upserts are not redesigned; this is not a claim to fix every pre-existing changed-attribution race. Checks passed on SQLite 3.53.4 and real PostgreSQL 18.6/16.15: - `GOFLAGS=-p=1 make verify` and `GOFLAGS=-p=1 make race`, with every package/test and race instrumentation retained. The full gate included 214 frontend test files/2,000 tests, build/Storybook and generated/OpenAPI checks. - The requested shuffled service/job IP regression pattern and additional scanner enforcement/transactional flows. - Exact CI entry `go test -p=1 ./internal/web/service ./internal/web/job -run '^TestClientIpSyncPostgres(Scanner)?$' -count=1 -v`: exactly two top-level PASSes on each PG version, no skips; actionlint passed. - Real master/node E2E under both enrollment scopes: exact union/max timestamps, stable additional sync cycle, offline recovery and separate GUID buckets seeded only while panels were stopped. No live-Xray/firewall claim. - Newly built disposable-panel HTTP smoke: shuffled modern and legacy-string reports kept identical bytes; an advancing timestamp and two concurrent extra addresses persisted correctly. Regression-first tests failed before the production edit for redundant reads/writes, create-conflict/duplicate-new observation loss and the extra exhaustion reread. Real SQL injections, not mocked CAS outcomes, exercise contention and rollback. Measured on the same 1k/10k/20k fixtures before/after, four overlapping node reports, warm union seeded outside timing. Representative PostgreSQL 18 result at 20k clients; each cell is **before → after**: | Phase | Flat SELECTs | CAS attempts / misses | Attribution attempted / affected | Cycle elapsed | |---|---:|---:|---:|---:| | Unchanged | 80,004 → 4 | 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 | 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 | 94.876s → 114.870s | Flat affected rows were zero in the unchanged phase and 80,000 in each changed phase, on both revisions; the exact four-IP/max-timestamp union passed in every phase. | Phase | PG statement calls before → after | WAL bytes before → after | FPI before → after | |---|---:|---:|---:| | Unchanged | 160,008 → 8 | 37,568,102 → 68,548 | 0 → 0 | | Advancing | 240,008 → 160,008 | 87,812,110 → 88,651,691 | 2,156 → 1,607 | | Concurrent changed | 240,014 → 280,008 | 83,171,101 → 75,384,740 | 1,316 → 1 | **Tradeoff:** synchronized all-changed reports make preloaded snapshots stale and increase failed CAS work; this worst-case phase is slower. The measured benefit is unchanged/uncontended sync, not a uniform speedup. Changed-phase WAL has differing FPI conditions and is reported raw, not as a normalized reduction. Zero affected row mutations is not zero WAL. Scanner live attribution still writes genuinely advancing timestamps. Statistics were captured before fixture teardown with unchanged `stats_reset`, `dealloc=0`, and no cluster-wide reset. No external cache/service or schema/API change is introduced.
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#4584
No description provided.