Files
James Tucker 23c4f85942 util/execqueue, ipn/ipnlocal: avoid heap allocations on steady-state enqueue
Discovered during review of #22868, ExecQueue allocated on every
0 -> 1 -> 0 transition and forced callers to allocate closures on the
hot path:

- go q.run(f) synthesized a heap-allocated gowrap closure capturing
  (q, f) on every idle-to-busy transition.
- q.queue = nil on drain discarded the backing slice after every burst,
  reallocating on subsequent 1 -> 2 overlaps.
- q.initCtxLocked() eagerly allocated a context.WithCancel on the first
  Add even when Wait or RunSync were never called.
- ExecQueue.Add only accepts func(), forcing single-handler callers like
  LocalBackend.onPeerWireGuardState (called while wireguard-go holds
  peer locks) to allocate a closure per call.

Add a generic Queue[T] backed by a single handler function (initialized
with NewQueue or in-place Init) and eliminate steady-state allocations:

- Store the 0 -> 1 item inline in an unexported first slot (zeroed
  before invoking the handler) and cache the q.run method value in
  runFunc so idle-to-busy launches go runFunc() with 0 allocations.
- Drain the overflow slice with a head index, resetting to q.queue[:0]
  when empty while retaining capacities up to 16 (and compacting on
  sustained non-draining overlap, releasing on shutdown or after larger
  bursts).
- Replace context.WithCancel with a lazily allocated closedCh channel
  created only when Wait or RunSync blocks before shutdown.

Keep ExecQueue as a thin zero-value-ready wrapper around Queue[func()]
rather than replacing it with a generic type. Go has no default type
parameters, so parameterizing ExecQueue would break existing callers;
heterogeneous queues still enqueue arbitrary closures without an Init
step; and RunSync(ctx, func()) is specific to func() items.

Switch LocalBackend.peerWGStateQueue to execqueue.Queue[peerWGStateEvent]
so onPeerWireGuardState performs 0 heap allocations under wireguard-go's
lock.

Updates #22868

Change-Id: I048d0549781caa7dec9f2a44313f32d13a377d4b
Signed-off-by: James Tucker <james@tailscale.com>
2026-12-03 23:13:03 +00:00
..
2026-07-10 17:39:16 -07:00