From b1cec64b18fe2da6408bdd4665d517790522bbce Mon Sep 17 00:00:00 2001 From: Hamed Date: Sun, 29 Nov 2026 17:55:47 +0330 Subject: [PATCH] perf(nodes): target orphan recovery during client reconciliation (#7240) 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 --- .github/workflows/ci.yml | 10 ++ internal/web/service/client_link.go | 32 +++-- internal/web/service/client_sync_orphan.go | 30 ++-- .../web/service/client_sync_orphan_test.go | 135 ++++++++++++++++++ internal/web/service/inbound_node.go | 4 - 5 files changed, 184 insertions(+), 27 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b48c8f061..799b02296 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -94,6 +94,16 @@ jobs: exit 1 fi + - name: PostgreSQL sync orphan recovery + run: | + set -o pipefail + go test ./internal/web/service -run '^Test(SyncOrphanRecoveryScope|LegacySyncOrphanMarksAcrossLinkChanges)Postgres$' -count=1 -v | tee /tmp/postgres-sync-orphans.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-sync-orphans.log || true) + if [ "$passed" -ne 2 ]; then + echo "expected both PostgreSQL sync orphan recovery tests to pass, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL client traffic lifecycle edits run: | set -o pipefail diff --git a/internal/web/service/client_link.go b/internal/web/service/client_link.go index cd6f198c2..e457d830f 100644 --- a/internal/web/service/client_link.go +++ b/internal/web/service/client_link.go @@ -342,6 +342,16 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ } } + var marked []int + for _, row := range existing { + if row.SyncOrphanedAt > 0 { + marked = append(marked, row.Id) + } + } + if err := clearSyncOrphanMarks(tx, marked); err != nil { + return err + } + // A failed validation can roll back the row while the outer transaction commits. liftTombstonesOnCommit(tx, toCreate) return nil @@ -409,6 +419,10 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wanted }) } + // A restored, still-attached client must lose its legacy mark before it loses its link. + if err := clearSyncOrphanMarks(tx, toDelete); err != nil { + return nil, err + } for _, batch := range chunkInts(toDelete, sqlInChunk) { if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch). Delete(&model.ClientInbound{}).Error; err != nil { @@ -433,18 +447,6 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wanted }).CreateInBatches(toInsert, 200).Error; err != nil { return nil, err } - // Not left to the next node merge: there may never be one, and a mark that outlives the - // attach hands the client to the reaper on its next detach. - linked := make([]int, 0, len(toInsert)) - for _, link := range toInsert { - linked = append(linked, link.ClientId) - } - for _, batch := range chunkInts(linked, sqlInChunk) { - if err := tx.Model(&model.ClientRecord{}).Where("id IN ? AND sync_orphaned_at > 0", batch). - Updates(map[string]any{"sync_orphaned_at": 0, "sync_orphaned_by": 0}).Error; err != nil { - return nil, err - } - } } relinked := append([]int(nil), toDelete...) @@ -539,7 +541,11 @@ func settleRecordFlows(tx *gorm.DB, clientIds []int) error { func (s *ClientService) DetachInbound(tx *gorm.DB, inboundId int) error { if tx == nil { - tx = database.GetDB() + return runSerializedTx(func(tx *gorm.DB) error { return s.DetachInbound(tx, inboundId) }) + } + linked := tx.Model(&model.ClientInbound{}).Select("client_id").Where("inbound_id = ?", inboundId) + if err := clearAttachedSyncOrphanMarks(tx.Model(&model.ClientRecord{}).Where("id IN (?)", linked)); err != nil { + return err } return tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error } diff --git a/internal/web/service/client_sync_orphan.go b/internal/web/service/client_sync_orphan.go index b1a9a17aa..5e73d8b42 100644 --- a/internal/web/service/client_sync_orphan.go +++ b/internal/web/service/client_sync_orphan.go @@ -36,9 +36,18 @@ func markSyncOrphan(tx *gorm.DB, email string, nodeID int, nowMs int64) error { // A client that is attached again is not orphaned, whatever an earlier merge // concluded — this is what makes a bad merge recoverable instead of fatal. -func clearSyncOrphanMarks(tx *gorm.DB) error { - return tx.Model(&model.ClientRecord{}). - Where("sync_orphaned_at > 0 AND EXISTS (SELECT 1 FROM client_inbounds WHERE client_inbounds.client_id = clients.id)"). +func clearSyncOrphanMarks(tx *gorm.DB, ids []int) error { + for _, batch := range chunkInts(ids, sqlInChunk) { + scope := tx.Model(&model.ClientRecord{}).Where("id IN ?", batch) + if err := clearAttachedSyncOrphanMarks(scope); err != nil { + return err + } + } + return nil +} + +func clearAttachedSyncOrphanMarks(scope *gorm.DB) error { + return scope.Where("sync_orphaned_at > 0 AND EXISTS (SELECT 1 FROM client_inbounds WHERE client_inbounds.client_id = clients.id)"). Updates(map[string]any{"sync_orphaned_at": 0, "sync_orphaned_by": 0}).Error } @@ -54,20 +63,21 @@ func (s *ClientService) ReapSyncOrphans() (int, error) { db := database.GetDB() cutoff := time.Now().Add(-syncOrphanReapGrace).UnixMilli() - var emails []string - if err := reapableSyncOrphans(db, cutoff).Pluck("email", &emails).Error; err != nil { + // The maintenance pass also repairs attached marks from legacy databases and imports. + var ids []int + if err := db.Model(&model.ClientRecord{}).Where("sync_orphaned_at > 0").Pluck("id", &ids).Error; err != nil { return 0, err } - if len(emails) == 0 { - return 0, nil - } reaped := 0 - for _, listed := range chunkStrings(emails, sqlInChunk) { + for _, listed := range chunkInts(ids, sqlInChunk) { var batch []string if err := runSerializedTx(func(tx *gorm.DB) error { // The list was read outside the writer; an attach may have committed since. - if err := reapableSyncOrphans(tx, cutoff).Where("email IN ?", listed).Pluck("email", &batch).Error; err != nil { + if err := clearSyncOrphanMarks(tx, listed); err != nil { + return err + } + if err := reapableSyncOrphans(tx, cutoff).Where("id IN ?", listed).Pluck("email", &batch).Error; err != nil { return err } if len(batch) == 0 { diff --git a/internal/web/service/client_sync_orphan_test.go b/internal/web/service/client_sync_orphan_test.go index 4d1eb3488..795835a83 100644 --- a/internal/web/service/client_sync_orphan_test.go +++ b/internal/web/service/client_sync_orphan_test.go @@ -2,10 +2,12 @@ package service import ( "fmt" + "strings" "testing" "time" "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" "github.com/mhsanaei/3x-ui/v3/internal/xray" "gorm.io/gorm" @@ -201,3 +203,136 @@ func TestAdminAttachClearsSyncOrphanMark(t *testing.T) { t.Fatalf("admin-detached client was reaped: reaped=%d clients=%d, want 0/1", reaped, rec) } } + +func TestSyncOrphanRecoveryScope(t *testing.T) { + testSyncOrphanRecoveryScope(t, initTrafficTestDB(t)) +} + +func TestSyncOrphanRecoveryScopePostgres(t *testing.T) { + testSyncOrphanRecoveryScope(t, durablePostgresDB(t)) +} + +func TestLegacySyncOrphanMarksAcrossLinkChanges(t *testing.T) { + testLegacySyncOrphanMarksAcrossLinkChanges(t, initTrafficTestDB(t)) +} + +func TestLegacySyncOrphanMarksAcrossLinkChangesPostgres(t *testing.T) { + cleanup, err := testpg.IsolatePackage("legacy_sync_orphan_marks") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + testLegacySyncOrphanMarksAcrossLinkChanges(t, durablePostgresDB(t)) +} + +func testLegacySyncOrphanMarksAcrossLinkChanges(t *testing.T, db *gorm.DB) { + t.Helper() + clientSvc, inboundSvc := &ClientService{}, &InboundService{} + for _, action := range []string{"detach client", "delete inbound", "reattach client"} { + t.Run(action, func(t *testing.T) { + client := model.Client{Email: fmt.Sprintf("legacy-mark-%d@x", time.Now().UnixNano())} + ib := durableTestInbound(nil, client.Email, 42534) + ib.Enable = false + if action != "reattach client" { + ib.Settings = clientsSettings(t, []model.Client{client}) + } + if err := db.Create(ib).Error; err != nil { + t.Fatal(err) + } + if action == "reattach client" { + record := model.ClientRecord{Email: client.Email} + if err := db.Create(&record).Error; err != nil { + t.Fatal(err) + } + } else if err := clientSvc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil { + t.Fatal(err) + } + backdateOrphanMark(t, db, client.Email) + + switch action { + case "detach client": + if _, err := clientSvc.DetachByEmail(inboundSvc, ib.Id, client.Email); err != nil { + t.Fatal(err) + } + case "delete inbound": + if _, err := inboundSvc.DelInbound(ib.Id); err != nil { + t.Fatal(err) + } + case "reattach client": + writes := 0 + const callback = "test:reattach-mark-writes" + if err := db.Callback().Update().After("gorm:update").Register(callback, func(tx *gorm.DB) { + sql := strings.NewReplacer("`", "", "\"", "").Replace(tx.Statement.SQL.String()) + if strings.Contains(sql, "SET sync_orphaned_at=") { + writes++ + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) }) + if err := clientSvc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil { + t.Fatal(err) + } + if writes != 1 { + t.Errorf("reattachment issued %d mark clears, want 1", writes) + } + } + + if reaped, err := clientSvc.ReapSyncOrphans(); err != nil || reaped != 0 { + t.Fatalf("legacy mark after %s: reaped=%d err=%v", action, reaped, err) + } + if got := readOrphanMark(t, db, client.Email); got != 0 { + t.Fatalf("legacy mark after %s was %d, want zero", action, got) + } + }) + } +} + +func testSyncOrphanRecoveryScope(t *testing.T, db *gorm.DB) { + t.Helper() + suffix := time.Now().UnixNano() + tag, unrelatedTag := fmt.Sprintf("scope-node-%d", suffix), fmt.Sprintf("scope-local-%d", suffix) + email, otherEmail := tag+"@x", unrelatedTag+"@x" + node := &model.Node{Name: tag, Address: "127.0.0.1", Port: 2096, Enable: true} + if err := db.Create(node).Error; err != nil { + t.Fatal(err) + } + createNodeInboundWithClient(t, db, node.Id, tag, 42531, email) + createNodeInboundWithClient(t, db, node.Id+10000, unrelatedTag, 42532, otherEmail) + backdateOrphanMark(t, db, email) + backdateOrphanMark(t, db, otherEmail) + writes := 0 + const callback = "test:orphan-scope" + if err := db.Callback().Update().After("gorm:update").Register(callback, func(tx *gorm.DB) { + if strings.Contains(tx.Statement.SQL.String(), "sync_orphaned_by") && strings.Contains(tx.Statement.SQL.String(), "EXISTS") { + writes++ + if !strings.Contains(tx.Statement.SQL.String(), "id IN") { + t.Error("unbounded orphan recovery update") + } + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) }) + + service := &InboundService{} + settings := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true}]}`, email) + syncNodeWithSettings(t, service, node.Id, tag, settings, xray.ClientTraffic{Email: email, Enable: true}) + if readOrphanMark(t, db, email) != 0 { + t.Fatal("touched client still marked") + } + if readOrphanMark(t, db, otherEmail) <= 0 { + t.Fatal("merge repaired an unrelated mark") + } + writes = 0 + syncNodeWithSettings(t, service, node.Id, tag, settings, xray.ClientTraffic{Email: email, Up: 1, Enable: true}) + if writes != 0 { + t.Fatalf("unchanged snapshot issued %d orphan updates", writes) + } + if _, err := (&ClientService{}).ReapSyncOrphans(); err != nil { + t.Fatal(err) + } + if readOrphanMark(t, db, otherEmail) != 0 { + t.Fatal("maintenance failed to repair attached legacy mark") + } +} diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 16757f266..6a33e5429 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -1500,10 +1500,6 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } - if err := clearSyncOrphanMarks(tx); err != nil { - logger.Warning("setRemoteTraffic: clear orphan marks failed:", err) - } - if err := liftActivatedClientRecordExpiries(tx); err != nil { logger.Warning("setRemoteTraffic: lift activated expiries failed:", err) }