Files
tailscale/tstest/membudget/membudget_test.go
Jordan Whited 8fc6dca15e all: use ~128KiB packet buf for batched i/o
This commit bumps the wireguard-go dependency to incorporate changes to
the packet memory model and the tun.Device.Read and conn.ReceiveFunc I/O
interfaces. It updates their implementations accordingly.

These changes improve throughput in all measured benchmarks and reduce
peak RSS in six of eight cases. The two regressions will be addressed in
a follow-up commit that reduces peak RSS below the baseline measured at
1e69418. That work is kept separate to simplify review.

The following throughput and peak RSS benchmarks were performed with
iperf3 between two Intel i5-12400 nodes running Ubuntu 24.04 (Linux 6.8).

The UDP benchmarks did not use UDP GSO on the sender, so they were
roughly equivalent to single packet I/O through wireguard-go.

TCP/1 signifies one TCP stream; TCP/128 signifies 128 parallel TCP
streams.

Throughput (Mb/s)
  Test     1e69418  After  Change
  TCP/1    10,371  11,354   +9.5%
  TCP/128   7,886   8,404   +6.6%
  UDP/1     2,111   2,853  +35.1%
  UDP/128   1,747   2,235  +28.0%

Peak memory (VmHWM, kB)
  Test     Side   1e69418    After   Change
  TCP/1    TX      98,240   52,596   -46.5%
           RX     287,748   73,384   -74.5%
  TCP/128  TX     101,196   52,812   -47.8%
           RX     290,420   63,620   -78.1%
  UDP/1    TX      58,864  160,840  +173.2%
           RX     137,516   49,900   -63.7%
  UDP/128  TX      66,148  116,096   +75.5%
           RX     154,384   56,556   -63.4%

Updates tailscale/corp#46716
Updates tailscale/corp#22467
Updates tailscale/corp#36989
Updates tailscale/corp#37878

Signed-off-by: Jordan Whited <[email protected]>
2026-09-04 09:32:55 -07:00

185 lines
6.2 KiB
Go

// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
// Package membudget contains memory budget regression tests: it brings up an
// in-process backend (via tsnet) against an in-process fake control server
// with a parameterized number of peers, and asserts that the live (post-GC)
// Go heap stays within budget.
//
// Static binary size/dirty-page budgets are enforced elsewhere (see the iOS
// extension size checks); these tests cover what those cannot: runtime heap
// cost at startup and heap cost proportional to netmap size. On iOS the
// Network Extension has a hard 50 MiB phys_footprint limit (jetsam), so
// regressions here that look small on servers can make large tailnets
// unusable on mobile. For example, a table pre-allocation at extension init
// once cost 15.8 MiB of live heap before any netmap arrived: well below the
// noise floor of any existing test, but ~1/3 of the entire iOS budget.
package membudget
import (
"context"
"net/http/httptest"
"runtime"
"testing"
"time"
"tailscale.com/ipn/store/mem"
"tailscale.com/net/netns"
"tailscale.com/tailcfg"
"tailscale.com/tsnet"
"tailscale.com/tstest/integration"
"tailscale.com/tstest/integration/testcontrol"
"tailscale.com/types/logger"
// Match the feature set of shipping clients as closely as possible so
// that feature init cost is measured. (tsnet by default imports only a
// subset of features.)
_ "tailscale.com/feature/condregister"
)
// Budgets, in bytes of live heap (measured after runtime.GC).
//
// These are deliberately generous to avoid flakes from allocator noise and
// unrelated churn; they exist to catch order-of-magnitude regressions of the
// kind that break memory-limited platforms (iOS NetworkExtension: 50 MiB
// phys_footprint for the whole process, of which ~15 MiB is non-heap).
//
// If you trip one of these, either find the regression (see
// http://go/ios-memory or `go tool pprof` the heap) or, if the growth is
// genuinely necessary and accounted for, raise the budget in the same change
// with a justification.
const (
// startupBudget is the live-heap budget for bringing up a backend
// connected to a tailnet with zero peers: feature/extension init,
// engine, netstack, DNS, control client, etc.
//
// As of 2026-09 the measured cost is ~1.73 MiB; the budget leaves ~5x
// headroom for organic growth while still catching multi-MiB
// regressions (the conn25 flow table pre-allocation this test was
// written for measured 17 MiB here).
startupBudget = 8 << 20
// perPeerBudget is the marginal live-heap budget per netmap peer
// (magicsock endpoint state, netmap views, filter, routes, ...).
perPeerBudget = 64 << 10
)
// nPeers is the number of fake peers used to measure marginal per-peer cost.
// Large enough that per-peer cost dominates measurement noise; comparable to
// a large corporate tailnet as seen by one node.
const nPeers = 600
// liveHeap returns the current live heap size, after forcing GC.
func liveHeap() uint64 {
runtime.GC()
runtime.GC() // run finalizers queued by the first cycle, then collect
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
return ms.HeapAlloc
}
func startControl(t *testing.T, peers int) (controlURL string) {
t.Helper()
// Corp#4520: don't use netns for tests.
netns.SetEnabled(false)
t.Cleanup(func() { netns.SetEnabled(true) })
derpMap := integration.RunDERPAndSTUN(t, logger.Discard, "127.0.0.1")
control := &testcontrol.Server{
DERPMap: derpMap,
DNSConfig: &tailcfg.DNSConfig{
Proxied: true,
},
MagicDNSDomain: "tail-scale.ts.net",
}
control.HTTPTestServer = httptest.NewUnstartedServer(control)
control.HTTPTestServer.Start()
t.Cleanup(control.HTTPTestServer.Close)
for range peers {
control.AddFakeNode()
}
return control.HTTPTestServer.URL
}
// startNode starts a tsnet node against controlURL and waits for it to reach
// Running with its full netmap.
func startNode(t *testing.T, ctx context.Context, controlURL string) *tsnet.Server {
t.Helper()
s := &tsnet.Server{
Dir: t.TempDir(),
ControlURL: controlURL,
Hostname: "membudget",
Store: new(mem.Store),
Ephemeral: true,
Logf: logger.Discard,
UserLogf: logger.Discard,
}
t.Cleanup(func() { s.Close() })
if _, err := s.Up(ctx); err != nil {
t.Fatal(err)
}
return s
}
// measureNodeCost returns the live heap delta of running one tsnet node
// connected to a control server with the given number of peers.
//
// The fake control server (and DERP) run in the same process; their live
// state is mostly established before the baseline measurement, but some
// cross-talk is unavoidable and is part of why budgets are generous.
func measureNodeCost(t *testing.T, peers int) uint64 {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
controlURL := startControl(t, peers)
baseline := liveHeap()
s := startNode(t, ctx, controlURL)
// Wait for the netmap to be fully processed and transients to die.
lc, err := s.LocalClient()
if err != nil {
t.Fatal(err)
}
if st, err := lc.Status(ctx); err != nil {
t.Fatal(err)
} else if got := len(st.Peer); got < peers {
t.Fatalf("status shows %v peers; want at least %v", got, peers)
}
after := liveHeap()
if after < baseline {
return 0
}
return after - baseline
}
func TestBackendStartupMemory(t *testing.T) {
if testing.Short() {
t.Skip("skipping in short mode")
}
cost := measureNodeCost(t, 0)
t.Logf("live heap cost of backend with 0 peers: %.2f MiB (budget %.2f MiB)",
float64(cost)/(1<<20), float64(startupBudget)/(1<<20))
if cost > startupBudget {
t.Errorf("backend startup live heap %v exceeds budget %v", cost, int(startupBudget))
}
}
func TestBackendPerPeerMemory(t *testing.T) {
if testing.Short() {
t.Skip("skipping in short mode")
}
base := measureNodeCost(t, 0)
loaded := measureNodeCost(t, nPeers)
if loaded < base {
t.Skipf("measurement noise: %v peers cost (%v) below 0 peers cost (%v)", nPeers, loaded, base)
}
perPeer := (loaded - base) / nPeers
t.Logf("live heap: 0 peers=%.2f MiB, %d peers=%.2f MiB, per peer=%.1f KiB (budget %.1f KiB)",
float64(base)/(1<<20), nPeers, float64(loaded)/(1<<20),
float64(perPeer)/(1<<10), float64(perPeerBudget)/(1<<10))
if perPeer > perPeerBudget {
t.Errorf("per-peer live heap %v exceeds budget %v", perPeer, perPeerBudget)
}
}