Skip to content

Use all your internet connections at once on Windows, macOS, Linux and Android: per-connection load balancing over Wi-Fi, Ethernet, mobile data and phone tethers

fix(engine): prevent adaptive balancing from starving healthy links (#48)

vwidmera646c009e47a
diff --git a/docs/DEVELOPING.md b/docs/DEVELOPING.md
index 7ca7d4f..19b57ac 100644
--- a/docs/DEVELOPING.md
+++ b/docs/DEVELOPING.md
@@ -37,9 +37,14 @@ Flags for `tray`/`run`/`socks`: `-include "WiFi,Ethernet"` (only these adapters)
(`net-merge list` shows why).
- Each adapter and each address family is probed for real internet access. A tether with no data or a
captive-portal Wi-Fi gets no flows; a recovered link rejoins within seconds.
-- Flows go to the adapter with the lowest (active flows + 1) / weight. Weights follow measured
- throughput, separately for IPv4 and IPv6 (a link can be fast over native IPv6 and slow over translated
- IPv4).
+- Automatic balancing sends flows to the adapter with the lowest (busy flows + 1) / weight,
+ discounting TCP sockets with no data for two seconds. Connecting sockets still count as busy.
+ Weights update every second from smoothed throughput estimates, separately for IPv4 and IPv6
+ (a link can be fast over native IPv6 and slow over translated IPv4). Idle low estimates
+ recover up to half the best link's capacity, never to equal preference. Address changes
+ reset the affected family's estimate. Static weights retain least-open-flows scheduling;
+ scheduling respects health filtering, cooldowns and retry exclusions. Existing flows
+ stay pinned to their original adapter; no background speed tests are used.
- IPv6 (`-ipv6 auto|on|off`, tray checkbox): IPv6 flows can only leave through adapters that have IPv6, and
apps that prefer IPv6 (browsers, OBS, curl) would funnel everything onto them. In `auto` mode IPv6 is
balanced only when every adapter has working IPv6; otherwise new IPv6 connections are refused at the SYN
diff --git a/internal/engine/balancer.go b/internal/engine/balancer.go
index d6406ad..83cdfee 100644
--- a/internal/engine/balancer.go
+++ b/internal/engine/balancer.go
@@ -185,29 +185,36 @@ var bufPool = sync.Pool{New: func() any { b := make([]byte, 128<<10); return &b
// closes both conns and releases the slot. Half-close is honoured so request/response
// protocols that shut down their write side still receive the reply.
func Relay(client, upstream net.Conn, sl *Slot, f Family, s *Scheduler) {
+ activity := s.track(sl, f)
var wg sync.WaitGroup
var once sync.Once
- release := func() { once.Do(func() { s.ReleaseFor(sl, f) }) } // at the first half-close, see slotConn
+ release := func() {
+ once.Do(func() {
+ s.untrack(sl, f, activity)
+ s.ReleaseFor(sl, f)
+ })
+ } // at the first half-close, see slotConn
wg.Add(1)
go func() {
defer wg.Done()
- pump(upstream, client, &sl.bytesOut[f])
+ pump(upstream, client, &sl.bytesOut[f], activity)
release()
}()
- pump(client, upstream, &sl.bytesIn[f])
+ pump(client, upstream, &sl.bytesIn[f], activity)
release()
wg.Wait()
client.Close()
upstream.Close()
}
-func pump(dst, src net.Conn, counter interface{ Add(int64) int64 }) {
+func pump(dst, src net.Conn, counter interface{ Add(int64) int64 }, activity *flowActivity) {
bp := bufPool.Get().(*[]byte)
defer bufPool.Put(bp)
buf := *bp
for {
n, err := src.Read(buf)
if n > 0 {
+ activity.bytes.Add(int64(n))
counter.Add(int64(n))
if _, werr := dst.Write(buf[:n]); werr != nil {
dst.Close()
diff --git a/internal/engine/flowconn.go b/internal/engine/flowconn.go
index 030fc20..450630f 100644
--- a/internal/engine/flowconn.go
+++ b/internal/engine/flowconn.go
@@ -13,28 +13,40 @@ import (
// CloseRead/CloseWrite because the TUN relay half-closes each direction separately.
type slotConn struct {
*net.TCPConn
- sl *Slot
- fam Family
- s *Scheduler
- once sync.Once
+ sl *Slot
+ fam Family
+ s *Scheduler
+ once sync.Once
+ activity *flowActivity
}
func (c *slotConn) Read(p []byte) (int, error) {
n, err := c.TCPConn.Read(p)
c.sl.bytesIn[c.fam].Add(int64(n))
+ if c.activity != nil {
+ c.activity.bytes.Add(int64(n))
+ }
return n, err
}
func (c *slotConn) Write(p []byte) (int, error) {
n, err := c.TCPConn.Write(p)
c.sl.bytesOut[c.fam].Add(int64(n))
+ if c.activity != nil {
+ c.activity.bytes.Add(int64(n))
+ }
return n, err
}
// release frees the slot's balancing count. It happens at the first half-close, not at the final
// Close: the relay can keep a finished flow open for up to a minute waiting for the peer's FIN,
// and counting those as active would steer new flows away from the NIC that just finished.
-func (c *slotConn) release() { c.once.Do(func() { c.s.ReleaseFor(c.sl, c.fam) }) }
+func (c *slotConn) release() {
+ c.once.Do(func() {
+ c.s.untrack(c.sl, c.fam, c.activity)
+ c.s.ReleaseFor(c.sl, c.fam)
+ })
+}
func (c *slotConn) CloseRead() error { c.release(); return c.TCPConn.CloseRead() }
func (c *slotConn) CloseWrite() error { c.release(); return c.TCPConn.CloseWrite() }
@@ -46,7 +58,7 @@ func (b *Balancer) DialPinned(ctx context.Context, host string, port int) (net.C
if err != nil {
return nil, err
}
- return &slotConn{TCPConn: c.(*net.TCPConn), sl: sl, fam: f, s: b.S}, nil
+ return &slotConn{TCPConn: c.(*net.TCPConn), sl: sl, fam: f, s: b.S, activity: b.S.track(sl, f)}, nil
}
type slotPacketConn struct {
diff --git a/internal/engine/sched.go b/internal/engine/sched.go
index bd6c446..5b927ff 100644
--- a/internal/engine/sched.go
+++ b/internal/engine/sched.go
@@ -58,6 +58,7 @@ type Slot struct {
lastIn, lastOut [2]int64
rateIn, rateOut [2]float64 // bytes/s over the last tick
peak [2]float64 // observed capacity: max recent rateIn+rateOut
+ flows [2]map[*flowActivity]struct{}
// The adapter's total traffic from the OS's counters (all apps, not only net-merge's flows).
linkIn, linkOut uint64
@@ -65,6 +66,44 @@ type Slot struct {
linkPrimed bool
}
+// flowActivity separates recent data transfer from long-lived idle sockets. Byte
+// accounting is lock-free; membership and sampled activity are guarded by mu.
+type flowActivity struct {
+ bytes atomic.Int64
+ last int64
+ idle time.Duration
+}
+
+const flowIdleAfter = 2 * time.Second
+
+func (s *Scheduler) track(sl *Slot, f Family) *flowActivity {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ a := &flowActivity{}
+ if sl.flows[f] == nil {
+ sl.flows[f] = make(map[*flowActivity]struct{})
+ }
+ sl.flows[f][a] = struct{}{}
+ return a
+}
+
+func (s *Scheduler) untrack(sl *Slot, f Family, a *flowActivity) {
+ s.mu.Lock()
+ delete(sl.flows[f], a)
+ s.mu.Unlock()
+}
+
+func (sl *Slot) busy(f Family) int64 {
+ // Acquired but not yet tracked flows are connecting, and must count too.
+ n := max(int64(0), sl.actF[f].Load()-int64(len(sl.flows[f])))
+ for a := range sl.flows[f] {
+ if a.idle < flowIdleAfter {
+ n++
+ }
+ }
+ return n
+}
+
func (sl *Slot) ip(f Family) net.IP {
a := sl.addr.Load()
if f == Fam6 {
@@ -89,9 +128,9 @@ type SlotStats struct {
Peak, Peak6 float64
}
-// Scheduler is weighted least-active-flows, per address family: each new flow goes to the NIC
-// with the lowest (active + 1) / weight among those that have an address of that family. Only
-// new flows take the lock.
+// Scheduler uses weighted least-busy-flows per address family. Automatic mode
+// discounts idle TCP sockets; static mode
+// retains weighted least-open-flows. Data transfer accounting stays lock-free.
type Scheduler struct {
mu sync.Mutex
slots []*Slot
@@ -152,11 +191,19 @@ func (s *Scheduler) Update(nics []nics.Nic) {
found.weight = [2]float64{n.Weight, n.Weight}
}
old := found.addr.Load()
- if !old.ip4.Equal(na.ip4) {
- found.state[Fam4] = stateUnknown // new address: re-verify
- }
- if !old.ip6.Equal(na.ip6) {
- found.state[Fam6] = stateUnknown
+ for _, f := range []Family{Fam4, Fam6} {
+ changed := !old.ip4.Equal(na.ip4)
+ if f == Fam6 {
+ changed = !old.ip6.Equal(na.ip6)
+ }
+ if changed {
+ found.state[f] = stateUnknown
+ found.lastProbe[f], found.downUntil[f] = time.Time{}, time.Time{}
+ found.peak[f] = 0
+ if s.auto {
+ found.weight[f] = 1
+ }
+ }
}
if !old.ip4.Equal(na.ip4) || !old.ip6.Equal(na.ip6) {
found.addr.Store(na)
@@ -174,12 +221,14 @@ func (s *Scheduler) Update(nics []nics.Nic) {
// A NIC counts as measured once it has carried this much (bytes/s, about 0.4 Mbit/s).
const minMeasuredPeak = 50_000
-// Tick samples throughput per family. With auto on, a family's weights follow each NIC's
-// observed peak for that family (floored at 0.05, so a slow path still sees an occasional flow
-// and is re-measured). Until every NIC with that family has been measured the weights stay
-// equal, which spreads load so each one gets measured. The peak holds while a NIC is idle and
-// only decays when it is in use but underperforming, so capacity is remembered across pauses.
+// Tick samples flow activity and throughput per family. Automatic weights follow
+// smoothed capacity estimates (floored at 0.05). Until all links are measured,
+// weights stay equal. Quiet links retain capacity, while stale low estimates
+// recover up to half the best link's capacity so they can be measured again.
func (s *Scheduler) Tick(dt time.Duration) {
+ if dt <= 0 {
+ return
+ }
// nics.Octets calls into the OS, so read the counters on a snapshot of the slots without s.mu
// (it would stall AcquireFor and Update) and take the lock only to store the results.
s.mu.Lock()
@@ -217,13 +266,32 @@ func (s *Scheduler) Tick(dt time.Duration) {
live, measured := 0, true
idle := map[*Slot]bool{}
for _, sl := range s.slots {
+ for a := range sl.flows[f] {
+ n := a.bytes.Load()
+ if n != a.last {
+ a.idle = 0
+ } else {
+ a.idle += dt
+ }
+ a.last = n
+ }
in, out := sl.bytesIn[f].Load(), sl.bytesOut[f].Load()
sl.rateIn[f] = float64(in-sl.lastIn[f]) / sec
sl.rateOut[f] = float64(out-sl.lastOut[f]) / sec
sl.lastIn[f], sl.lastOut[f] = in, out
r := sl.rateIn[f] + sl.rateOut[f]
- if r >= 0.05*sl.peak[f] {
- sl.peak[f] = math.Max(r, sl.peak[f]*0.97)
+ if r >= minMeasuredPeak && r >= 0.05*sl.peak[f] {
+ if sl.peak[f] == 0 {
+ sl.peak[f] = r
+ } else {
+ // Fast but smoothed growth, slower decay. Neither a single burst
+ // nor a quiet tick should abruptly invert link preference.
+ tau := 2.0
+ if r < sl.peak[f] {
+ tau = 30
+ }
+ sl.peak[f] += (r - sl.peak[f]) * (1 - math.Exp(-sec/tau))
+ }
} else {
idle[sl] = true
}
@@ -233,9 +301,8 @@ func (s *Scheduler) Tick(dt time.Duration) {
live++
maxPeak = math.Max(maxPeak, sl.peak[f])
}
- // An idle NIC's old estimate may be stale or pessimistic (it was measured during a bad
- // moment and then starved of flows, so it could never correct itself). Let it drift back
- // up, capped at half of the best NIC, so it keeps getting a fair chance to be re-measured.
+ // An idle link may have a pessimistic estimate. Let it recover, but never
+ // raise it above half the best link just because no traffic is flowing.
for sl := range idle {
if sl.present && sl.ip(f) != nil && sl.peak[f] > 0 {
sl.peak[f] = math.Min(sl.peak[f]*1.03, math.Max(sl.peak[f], 0.5*maxPeak))
@@ -308,7 +375,11 @@ func (s *Scheduler) AcquireFor(f Family, skip map[string]struct{}) *Slot {
bestScore := math.Inf(1)
for i := range pool {
sl := pool[(start+i)%len(pool)]
- if score := float64(sl.actF[f].Load()+1) / sl.weight[f]; score < bestScore {
+ load := sl.actF[f].Load()
+ if s.auto {
+ load = sl.busy(f)
+ }
+ if score := float64(load+1) / sl.weight[f]; score < bestScore {
best, bestScore = sl, score
}
}
diff --git a/internal/engine/sched_test.go b/internal/engine/sched_test.go
index 91a9535..26876fa 100644
--- a/internal/engine/sched_test.go
+++ b/internal/engine/sched_test.go
@@ -1,6 +1,7 @@
package engine
import (
+ "math"
"net"
"testing"
"time"
@@ -38,6 +39,143 @@ func TestEqualWeightsSpreadEvenly(t *testing.T) {
}
}
+func TestAutoIgnoresIdleSockets(t *testing.T) {
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
+ s.SetAuto(true)
+ a, b := s.slots[0], s.slots[1]
+ for range 20 {
+ a.actF[Fam4].Add(1)
+ s.track(a, Fam4)
+ }
+ s.Tick(time.Second)
+ if got := a.busy(Fam4); got != 20 {
+ t.Fatalf("sockets became idle before two seconds: busy=%d", got)
+ }
+ s.Tick(time.Second)
+ if got := a.busy(Fam4); got != 0 {
+ t.Fatalf("idle sockets counted as busy: %d", got)
+ }
+ // A connecting socket still counts; an idle socket becomes busy on data.
+ b.actF[Fam4].Add(1)
+ if got := s.Acquire(nil); got != a {
+ t.Fatal("idle sockets steered new flow away from available link")
+ }
+ s.Release(a)
+ for activity := range a.flows[Fam4] {
+ activity.bytes.Add(1000)
+ break
+ }
+ s.Tick(time.Second)
+ if a.busy(Fam4) != 1 || b.busy(Fam4) != 1 {
+ t.Fatal("recent data and connecting sockets must count")
+ }
+}
+
+func TestAutoDoesNotForceSlowLinkAfterIdle(t *testing.T) {
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
+ s.SetAuto(true)
+ clock := time.Unix(1000, 0)
+ s.now = func() time.Time { return clock }
+ a, b := s.slots[0], s.slots[1]
+ b.weight[Fam4] = 0.05
+ for range 24 {
+ clock = clock.Add(5 * time.Second)
+ if got := s.Acquire(nil); got != a {
+ t.Fatal("elapsed time overrode weighted scheduling")
+ }
+ s.Release(a)
+ }
+}
+
+func TestStaticSchedulingCountsIdleSockets(t *testing.T) {
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 0.05)})
+ a, b := s.slots[0], s.slots[1]
+ for range 20 {
+ a.actF[Fam4].Add(1)
+ s.track(a, Fam4)
+ }
+ s.Tick(flowIdleAfter)
+ if got := s.Acquire(nil); got != b {
+ t.Fatal("static scheduling discounted idle sockets")
+ }
+}
+
+func TestAddressChangeResetsLearnedFamily(t *testing.T) {
+ for _, f := range []Family{Fam4, Fam6} {
+ t.Run(map[Family]string{Fam4: "IPv4", Fam6: "IPv6"}[f], func(t *testing.T) {
+ a := nic("A", "10.0.0.1", 1)
+ a.IP6 = net.ParseIP("2001:db8::1")
+ s := NewScheduler([]nics.Nic{a})
+ s.SetAuto(true)
+ sl := s.slots[0]
+ sl.peak = [2]float64{1e6, 2e6}
+ sl.weight = [2]float64{0.1, 0.2}
+ now := time.Now()
+ sl.state = [2]linkState{stateDown, stateDown}
+ sl.lastProbe = [2]time.Time{now, now}
+ sl.downUntil = [2]time.Time{now.Add(time.Hour), now.Add(time.Hour)}
+ if f == Fam4 {
+ a.IP = net.ParseIP("10.1.0.1")
+ } else {
+ a.IP6 = net.ParseIP("2001:db8:1::1")
+ }
+ other := Fam6 - f
+ peak, weight, cooldown := sl.peak[other], sl.weight[other], sl.downUntil[other]
+ s.Update([]nics.Nic{a})
+ if sl.peak[f] != 0 || sl.weight[f] != 1 || !sl.downUntil[f].IsZero() || !sl.lastProbe[f].IsZero() || sl.state[f] != stateUnknown {
+ t.Fatal("new address retained stale estimate or probe state")
+ }
+ if sl.peak[other] != peak || sl.weight[other] != weight || sl.downUntil[other] != cooldown || sl.lastProbe[other] != now || sl.state[other] != stateDown {
+ t.Fatal("unchanged address family's estimate or probe state reset")
+ }
+ })
+ }
+}
+
+func TestThroughputEstimateSmoothsBursts(t *testing.T) {
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1)})
+ s.SetAuto(true)
+ a := s.slots[0]
+ a.bytesIn[Fam4].Add(1e6)
+ s.Tick(time.Second)
+ a.bytesIn[Fam4].Add(10e6)
+ s.Tick(time.Second)
+ want := 1e6 + (10e6-1e6)*(1-math.Exp(-1.0/2))
+ if math.Abs(a.peak[Fam4]-want) > 1e-6 {
+ t.Fatalf("rising estimate = %g, want %g", a.peak[Fam4], want)
+ }
+ peak := a.peak[Fam4]
+ a.bytesIn[Fam4].Add(1e6)
+ s.Tick(time.Second)
+ want = peak + (1e6-peak)*(1-math.Exp(-1.0/30))
+ if math.Abs(a.peak[Fam4]-want) > 1e-6 {
+ t.Fatalf("falling estimate = %g, want %g", a.peak[Fam4], want)
+ }
+}
+
+func TestTickIgnoresNonPositiveDuration(t *testing.T) {
+ for _, dt := range []time.Duration{0, -time.Second} {
+ t.Run(dt.String(), func(t *testing.T) {
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1)})
+ s.SetAuto(true)
+ a := s.slots[0]
+ a.actF[Fam4].Add(1)
+ activity := s.track(a, Fam4)
+ a.bytesIn[Fam4].Add(1e6)
+ activity.bytes.Add(1e6)
+ before := s.Snapshot()[0]
+ s.Tick(dt)
+ if got := s.Snapshot()[0]; got != before || a.lastIn[Fam4] != 0 || activity.last != 0 || activity.idle != 0 {
+ t.Fatal("non-positive duration changed sampled state")
+ }
+ s.Tick(time.Second)
+ if a.peak[Fam4] != 1e6 {
+ t.Fatal("invalid tick consumed pending traffic sample")
+ }
+ })
+ }
+}
+
func TestWeightsSkew(t *testing.T) {
s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 3), nic("B", "10.0.0.2", 1)})
p := acquireN(s, 8)
@@ -250,6 +388,47 @@ func TestPessimisticEstimateRecoversWhileIdle(t *testing.T) {
}
}
+func TestIdleRecoveryCappedAtHalfBestLink(t *testing.T) {
+ for _, fastActive := range []bool{false, true} {
+ name := "both idle"
+ if fastActive {
+ name = "fast link active"
+ }
+ t.Run(name, func(t *testing.T) {
+ a := nic("A", "10.0.0.1", 1)
+ a.IP6 = net.ParseIP("2001:db8::1")
+ b := nic("B", "10.0.0.2", 1)
+ b.IP6 = net.ParseIP("2001:db8::2")
+ s := NewScheduler([]nics.Nic{a, b})
+ s.SetAuto(true)
+ fast, slow := s.slots[0], s.slots[1]
+ for _, f := range []Family{Fam4, Fam6} {
+ fast.bytesIn[f].Add(10e6)
+ slow.bytesIn[f].Add(500_000)
+ }
+ s.Tick(time.Second)
+ for range 600 {
+ if fastActive {
+ for _, f := range []Family{Fam4, Fam6} {
+ fast.bytesIn[f].Add(10e6)
+ }
+ }
+ s.Tick(time.Second)
+ for _, f := range []Family{Fam4, Fam6} {
+ if ratio := slow.weight[f] / fast.weight[f]; ratio > 0.5 {
+ t.Fatalf("family %d: idle recovery exceeded half weight: %g", f, ratio)
+ }
+ }
+ }
+ for _, f := range []Family{Fam4, Fam6} {
+ if ratio := slow.weight[f] / fast.weight[f]; math.Abs(ratio-0.5) > 1e-6 {
+ t.Fatalf("family %d: idle estimate did not recover to half weight: %g", f, ratio)
+ }
+ }
+ })
+ }
+}
+
func TestV6CoverageDecidesWhetherIPv6IsBalanced(t *testing.T) {
a := nic("A", "10.0.0.1", 1)
a.IP6 = net.ParseIP("2001:db8::1")