LocalAI icon indicating copy to clipboard operation
LocalAI copied to clipboard

federated load balancing: SelectLeastUsedServer does not pick the least used node

Open ptimizeroracle opened this issue 1 month ago • 1 comments

LocalAI version: master at 9386a3a (the code in question last changed in fa25493)

Environment, CPU architecture, OS, and Version: darwin arm64, go 1.26.0. the numbers below come from a go test on the real functions, not from a running federated cluster, see "to reproduce"

Describe the bug local-ai federated load balances by default (loadBalanced is !RandomWorker), but SelectLeastUsedServer in core/p2p/federated.go often doesn't return the least used node. three things combine:

  1. zero is both "unset" and a real count. the loop is if min == 0 || v < min, so once a node at 0 is seen, the next node in map order replaces it, whatever its count. map order is random, so the node with the highest count can win
  2. RecordRequest runs after proxyP2PConnection returns, so the count only moves once the connection has ended. every connection that overlaps reads the same table and picks the same node
  3. the counter is lifetime and never decremented, so it measures requests served, not current load. a node that joins a running cluster takes all the traffic until it catches up

the third one is the case i'd expect people to hit in practice, adding a node to a busy cluster and watching it take everything.

To Reproduce i added a test file to core/p2p on master. it registers nodes with AddNode, sets requestTable, and calls the real SelectLeastUsedServer and RecordRequest in the same order as federated_server.go. the proxied connection is simulated by holding each goroutine until all of them have selected. the test file is below, run it with go test ./core/p2p/ -run TestSelectLeastUsed -v after make protogen-go.

case result
{a:5, b:0, c:100}, 10000 runs c 5911, b 2070, a 2019
{a:0, b:50}, 10000 runs b 7854, a 2146
{a:3, b:9}, 10000 runs (no zero, control) a 10000
32 overlapping connections, {a:10, b:10, c:9, d:10} 32 of 32 go to c
3000 sequential requests, a, b, c at 1000, d joins at 1 d takes 999 to 1000 in a row (5 runs)

so with a node at 0, the node at 100 wins most often. the percentages depend on go's map iteration, the wrong pick doesn't.

zz_scratch_least_used_test.go
package p2p

import (
	"fmt"
	"sync"
	"testing"
	"time"

	"github.com/mudler/LocalAI/core/schema"
)

func setup(service string, table map[string]int) *FederatedServer {
	fs := NewFederatedServer(":0", service, "", true, "")
	for id, c := range table {
		AddNode(service, schema.NodeData{Name: id, ID: id, TunnelAddress: "127.0.0.1:1", LastSeen: time.Now()})
		fs.requestTable[id] = c
	}
	return fs
}

func freq(t *testing.T, name string, table map[string]int, n int) {
	got := map[string]int{}
	for i := 0; i < n; i++ {
		fs := setup(name, table)
		got[fs.SelectLeastUsedServer()]++
	}
	fmt.Printf("%s table=%v n=%d picks=%v\n", name, table, n, got)
}

func TestSelectLeastUsedSentinel(t *testing.T) {
	freq(t, "s1", map[string]int{"a": 5, "b": 0, "c": 100}, 10000)
	freq(t, "s2", map[string]int{"a": 0, "b": 50}, 10000)
	freq(t, "s3", map[string]int{"a": 0, "b": 50, "c": 100}, 10000)
	freq(t, "s4", map[string]int{"a": 3, "b": 9}, 10000)
}

// same order as federated_server.go: select, hold the connection, then record
func TestSelectLeastUsedBurst(t *testing.T) {
	for _, k := range []int{8, 32} {
		fs := setup(fmt.Sprintf("b%d", k), map[string]int{"a": 10, "b": 10, "c": 9, "d": 10})
		before := fmt.Sprint(fs.requestTable)
		var wg sync.WaitGroup
		var m sync.Mutex
		got := map[string]int{}
		release := make(chan struct{})
		var selected sync.WaitGroup
		selected.Add(k)
		for i := 0; i < k; i++ {
			wg.Add(1)
			go func() {
				defer wg.Done()
				id := fs.SelectLeastUsedServer()
				m.Lock()
				got[id]++
				m.Unlock()
				selected.Done()
				<-release
				fs.RecordRequest(id)
			}()
		}
		selected.Wait()
		close(release)
		wg.Wait()
		fmt.Printf("burst k=%d before=%s assignments=%v after=%v\n", k, before, got, fs.requestTable)
	}
}

func TestSelectLeastUsedLateJoin(t *testing.T) {
	for _, start := range []int{1, 0} {
		for trial := 0; trial < 5; trial++ {
			fs := setup(fmt.Sprintf("j%d%d", start, trial), map[string]int{"a": 1000, "b": 1000, "c": 1000, "d": start})
			got := map[string]int{}
			first := ""
			run, longest := 0, 0
			for i := 0; i < 3000; i++ {
				id := fs.SelectLeastUsedServer()
				if i == 0 {
					first = id
				}
				got[id]++
				if id == "d" {
					run++
					if run > longest {
						longest = run
					}
				} else {
					run = 0
				}
				fs.RecordRequest(id)
			}
			fmt.Printf("join d=%d trial=%d first=%s longest_d_run=%d picks_of_3000=%v\n", start, trial, first, longest, got)
		}
	}
}

i haven't run this on a live cluster. 3 workers and one federated instance with --debug should show it in the Selected tunnel log lines, with slow streaming requests running in parallel.

Expected behavior the node with the lowest current load, random among ties (the comment above the loop says "if there are multiple entries with the same number, select one randomly").

Logs n/a, see the table

Additional context pkg/clusterrouting says it is shared by the NATS mode and the federation server, but core/p2p doesn't import it, so the federated path looks like it never moved to that policy. there is also no test covering SelectLeastUsedServer.

a small fix would init min from the first entry and count in flight, incrementing at selection and decrementing when the proxy returns. using pkg/clusterrouting may be the better direction, but that depends on what the p2p side can gossip. which one would you prefer? happy to send the pr.

(i used an ai assistant to help run the checks and write this up)

ptimizeroracle avatar Oct 31 '26 08:10 ptimizeroracle