Skip to content

wgengine/magicsock: keep receive funcs alive across socket read errors - #21396

Closed
nikitistik wants to merge 1 commit into
tailscale:mainfrom
nikitistik:magicsock-receive-rebind
Closed

nikitistik wants to merge 1 commit into
tailscale:mainfrom
nikitistik:magicsock-receive-rebind

Conversation

@nikitistik

Copy link
Copy Markdown

The UDP receive funcs return every read error other than truncation to wireguard-go, whose RoutineReceiveIncoming exits for good on any error that is not a Temporary() net.Error. Nothing recreates that goroutine: Device.Up runs once at engine construction, and Rebind only swaps the socket under a reader that is already gone. The health warnable ("ReceiveIPv4 is not running") has no remedy, and tailscale down/up does not help. On macOS the trigger is another VPN's utun interface coming and going; the same signature is reported on iOS (#19504) and Windows (#10976).

Treat a non-shutdown read error the way the send path treats EPIPE/ENOTCONN in maybeRebindOnError: log it, do a throttled Rebind+ReSTUN, back off from 100ms to 5s, and keep reading. The func now returns only net.ErrClosed, and only when the Conn or the Bind is closed, so the conn.Bind contract and Device.Close's wait on the receive goroutines are unchanged; closing the Bind wakes a func that is waiting out a backoff. Rebinds are bounded per error burst, Rebind/bindSocket install nothing once Close has started, and two clientmetrics count the errors and the rebinds.

Tests: survive a read error and keep delivering from the rebound socket; return net.ErrClosed promptly when the Bind closes during a backoff or mid-read; no rebind after close; bounded rebinds; throttled attempts do not consume the budget. go test ./wgengine/magicsock ./wgengine ./health -race passes.

Two questions carried over from #20616: is retry-in-place in the receive func the layer you want this at, or would you rather see wireguard-go's RoutineReceiveIncoming keep going or a BindUpdate path? And should the persistent-error case raise its own warnable, since inCall stays true during the backoff and the existing "not running" warnable can no longer fire?

Updates #20616
Updates #19504
Updates #10976

The UDP receive funcs handed to wireguard-go returned every read error
other than truncation. wireguard-go's Device.RoutineReceiveIncoming
treats any error that is not a Temporary net.Error as fatal and returns,
and nothing ever calls the receive func again: the address family is
silently dead until the process restarts. tailscaled's only call to
Device.Up (which is what would recreate the receive goroutines) happens
once at engine construction, and Rebind/link-change handling only swaps
the socket underneath a reader that no longer exists. The health tracker
notices ("The MagicSock function ReceiveIPv4 is not running") but has no
remedy; `tailscale down`/`up` does not help either.

On macOS this is reproducible whenever another VPN's utun interface comes
and goes (the bound-interface socket returns a non-temporary error);
similar reports exist for iOS and Windows.

Treat a non-shutdown read error the way the send path already treats
EPIPE/ENOTCONN: log it, perform a throttled Rebind+ReSTUN, back off
(100ms doubling to 5s), and keep reading. Only net.ErrClosed, a closing
Conn, or a closed Bind make the receive func return, which keeps the
conn.Bind contract ("return net.ErrClosed after Close") and Device.Close's
wait on the receive goroutines intact; closing the Bind also wakes a
receive func that is waiting out a backoff. Rebinds are bounded to
receiveErrorMaxRebinds per burst so one persistently broken address
family cannot reset every peer's endpoint state forever; after that the
func only retries its reads and leaves further rebinds to link changes.
Two clientmetrics count the errors and the rebinds they trigger.

Updates tailscale#20616
Updates tailscale#19504
Updates tailscale#10976

Change-Id: If7cb6b53148250f84713d4283b3cbbbcdb57bdb3
Signed-off-by: Nicholas K. Gigliotti <[email protected]>
@elight

elight commented Oct 8, 2026

Copy link
Copy Markdown

Devs, please

@dscottfrey

Copy link
Copy Markdown

Hoping this gets solved soon

@GodKimba

Copy link
Copy Markdown

I validated this PR against current main (3bb8a90), in case it helps review.

Rebase. It no longer applies cleanly. There are four conflicts, all in wgengine/magicsock/magicsock.go:

The minimal resolution:

  • pass receiveIPv4Name/receiveIPv6Name into mkReceiveFunc, and have it look up c.health.ReceiveFuncStats(name);
  • keep the new closedCh/closedAtomic init in connBind.Open inside main's hasUDPTransport structure;
  • keep the closed-bind guard in bindSocket ahead of main's !hasUDPTransport check.

git range-diff shows no other changes.

Tests after the rebase (Go 1.27.2, linux/amd64):

  • go build ./... passes.
  • go test -race ./wgengine/magicsock/ ./wgengine/ ./health/ passes.
  • The 6 new tests passed 120/120 with -race -count=20, and 180/180 with -cpu=1 -count=30.
  • Builds pass for ios/arm64, darwin/arm64, android/arm64, windows/amd64, js/wasm, ts_omit_udptransport and ts_omit_health.
  • With main's receive path swapped back in, TestReceiveFuncSurvivesReadError, TestReceiveFuncCloseDuringRead and TestRebindAfterBindCloseIsNoop fail as expected.

Two things I noticed while reading it:

  1. The rebind budget only counts consecutive errors. errState is reset on any successful read. So a socket that alternates errors and successes never reaches receiveErrorMaxRebinds, and keeps doing a full Rebind (which resets every peer's endpoint state) plus a ReSTUN every errRebindThrottle. I reproduced this with a throwaway test that alternated error and success reads: 46 rebinds in 500ms, with the throttle shortened to 10ms. I don't know whether real sockets fail this way.

  2. throttledRebind checks the timestamp and stores it in two separate steps. The IPv4 and IPv6 receive funcs and the send path can all pass the check at the same moment. Each one then rebinds, and the budget counts it from the return value. lastErrRebind.CompareAndSwap(old, now) would close that gap.

There's also a minor issue: the comment on closedAtomic says it mirrors closed, but the bind starts with closed: true and closedAtomic false. NewConn's initial rebind depends on that difference.

I'm working on a related iOS wake issue in #21768 (dead DERP connections after sleep, #15776).

@mdbraber

Copy link
Copy Markdown

Possibly this issues is connected to #21773

@chris-reusch

Copy link
Copy Markdown

Rebased this onto current main (e3c3ef1) and verified it, plus two notes on @GodKimba's review points.

Rebase. Same four conflicts in wgengine/magicsock/magicsock.go, and the resolution described above still works on today's main:

  • receiveIPv4/receiveIPv6 pass receiveIPv4Name/receiveIPv6Name; mkReceiveFunc's second parameter becomes name string and it looks up c.health.ReceiveFuncStats(name) itself. That keeps the name available for the error log even when the health item is nil, which main's healthItem.Name() can't do.
  • connBind.Open: keep the closedCh/closedAtomic init, inside main's hasUDPTransport structure, with main's fns = append(fns, c.mkReceiveDERPFunc()).
  • bindSocket: the closed-bind guard goes ahead of main's !hasUDPTransport check.

git range-diff against the PR head shows nothing else.

Verification (go1.27.2 via ./tool/go, darwin/arm64 host):

  • go build ./... clean.
  • go test -race ./wgengine/magicsock ./wgengine ./health passes; the six new tests pass 120/120 at -race -count=20.
  • ./wgengine/magicsock cross-builds clean for ios/arm64, darwin/arm64, windows/amd64, android/arm64, linux/amd64 and js/wasm, and with -tags ts_omit_udptransport, -tags ts_omit_health, and both together.

On the two review points:

  1. Consecutive-only error counting. Confirmed by reading: errState is cleared on any successful read, so a socket that alternates errors and successes never reaches receiveErrorMaxRebinds and keeps doing a full Rebind + ReSTUN every errRebindThrottle (5s), each one resetting every peer's endpoint state. Some reports in iOS 26.4.1 + Tailscale 1.96.5 — MagicSock ReceiveIPv4 goroutine stops, data plane dies while control plane stays up #19504 look like that shape rather than a hard-dead socket — grilledfish's and dscottfrey's stalls clear on their own after 2–3 minutes, and lucasfjk's exit node logged ~15 new contact: … via=derp per minute during the failure against a 0–1/min baseline. As written, those cases trade a permanently dead receive func (clearly worse) for a rebind every 5s while the socket flaps, so decaying errState over time, or requiring a few good reads before clearing it, seems worth doing before this lands.
  2. throttledRebind check-then-store. Worth noting the non-atomicity is pre-existing — main's maybeRebindOnError has the same Load().Before(…) / Store() pair — but this PR adds the two receive funcs as callers, so more goroutines hit the window. c.lastErrRebind is a syncs.AtomicValue[time.Time], which already has CompareAndSwap, so it's a one-line change.

Review ping. #19504 was opened in April, is labeled bug/OS-ios, has 22 comments and no maintainer reply; the same root cause is reported on macOS (#20616), Windows (#10976) and Linux. This PR is the only proposed fix and has been open a month without a review. @jwhited @illotum — the PR's own open question is the one that needs an owner's call: is retry-in-place inside the receive func the right layer, or would you rather see RoutineReceiveIncoming survive the error upstream, or a BindUpdate path? Happy to run a focused test matrix on the iOS side (Mullvad exit node over T-Mobile cellular with 464XLAT, which is where I hit this) if that would help pin the trigger.

@ViRb3

ViRb3 commented Oct 29, 2026

Copy link
Copy Markdown

Started persistently experiencing this after updating to macOS 27.2. I have no other VPN active, so I can't find any other trigger than the OS itself.

@ViRb3

ViRb3 commented Oct 29, 2026 •

Copy link
Copy Markdown

Looks like my issue at least might be related to Little Snitch, which uses a network content-filter extension. What's happening:

  1. Little Snitch's network filter holds each outgoing packet from Tailscale while it decides whether to allow it.
  2. The kernel then sends it on Little Snitch's behalf. If the destination is unreachable, that delayed send fails. Here the destinations were peers' 192.168.1.x LAN addresses that don't exist on my LAN, and IPv6 addresses my Mac can't reach.
  3. macOS leaves that error on the socket. Tailscale's next read gets "no route to host", treats it as fatal, and stops receiving.

@ViRb3

ViRb3 commented Oct 31, 2026 •

Copy link
Copy Markdown

@nikitistik

Copy link
Copy Markdown
Author

Closing this in favour of the fixes that have landed or are in review: #21902 (in 1.104.5), the wireguard-go change that keeps the receive routine alive on any error except shutdown, and #22183 once it lands. One data point in case it helps #22097: on my Mac, with another VPN's utun coming and going, the receive funcs exited with ENOTCONN and ECONNABORTED, not the unreachable errors, so the general retry path is what fixes it there. Thanks for taking this on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants