sing-box icon indicating copy to clipboard operation
sing-box copied to clipboard

fatal error: thread exhaustion after 30-60min uptime (goroutine leak in udpnat2 NewPacket), 1.13.19 Windows

Open double-tu opened this issue 3 months ago • 3 comments

Operating system

Windows

System version

Windows 11 Pro 26200.9168

Installation type

Third-party graphical clients that advertise themselves as using sing-box (Windows)

If you are using a graphical client, please provide the version of the client.

GUI.for.SingBox (latest, version tag not exposed in-app), https://github.com/GUI-for-Cores/GUI.for.SingBox

Version

sing-box version 1.13.19
Environment: go1.26.5 windows/amd64
Tags: with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,with_ocm,with_naive_outbound,with_purego,badlinkname,tfogo_checklinkname0
Revision: b5ebaa1fc0f2b94256180b95468e73ef53caa27d
CGO: disabled

Description

Environment

  • sing-box 1.13.19 stable, Windows 11 Pro (build 26200.9168), managed by third-party GUI GUI.for.SingBox (GUI only starts/stops the core and generates the config; crashes reproduced across GUI restarts)
  • TUN inbound: stack: mixed, auto_route: true, strict_route: true, endpoint_independent_nat: false
  • DNS: fakeip (198.18.0.0/15) for A/AAAA + DoH upstreams (remote DoH via proxy detour, local DoH with UDP bootstrap), hijack-dns action
  • ~153 outbounds (88 trojan, 33 vless, urltest groups...), 27 route rules on rule_sets

Symptom

The core dies every 30-90 minutes under normal desktop traffic with fatal error: thread exhaustion.

Telemetry (process thread count sampled every 10s): starts at ~40 threads, climbs monotonically to 120+ within ~30 min and never drops, until the process aborts. Crash intervals observed: 64, 36, 21 minutes.

At the last crash the log file had grown to 851,886 lines: the tail is a full Go runtime goroutine dump, and the overwhelming majority of goroutines end with:

created by github.com/sagernet/sing/common/udpnat2.(*Service).NewPacket.func1 in goroutine NNN
    github.com/sagernet/[email protected]/common/udpnat2/service.go:67 +0x435

So each UDP NAT session spawned from udpnat2.NewPacket appears to leak a goroutine (and eventually an OS thread), never released.

Possibly related: #4312 (closed, same fatal error, iOS alpha) and #4428 (open). My case is the Windows stable 1.13.19 build.

Reproduction

  1. Run sing-box 1.13.19 on Windows with TUN (stack: mixed, strict_route: true) + fakeip DNS + hijack-dns, behind a desktop workload producing many short-lived UDP flows (QUIC/WebRTC/games; in my case Windows Delivery Optimization flooding UDP port 7680 was one major source, but the leak/crash still reproduces after disabling Delivery Optimization).
  2. Sample the process: Get-Process sing-box | Select-Object @{n='threads';e={$_.Threads.Count}} every 10s - thread count grows monotonically from ~40 and never decreases, even when UDP traffic stops.
  3. After ~30-60 minutes the process aborts with fatal error: thread exhaustion and writes a full runtime goroutine dump (hundreds of thousands of lines) to the log before dying.

The crash is load-dependent: heavier UDP churn => faster exhaustion (21-64 min observed).

Logs

Last lines before death (recovered excerpt; the full log was 851,886 lines of Go runtime dump, truncated on rotation - I can provide the raw dump next time it happens if needed):


FATAL> fatal error: thread exhaustion


Recurring goroutine creator from the runtime dump tail (repeated for the vast majority of goroutines):


runtime.goexit({})
    runtime/asm_amd64.s:1771 +0x1 fp=0x... sp=0x... pc=0x...
created by github.com/sagernet/sing/common/udpnat2.(*Service).NewPacket.func1 in goroutine 348
    github.com/sagernet/[email protected]/common/udpnat2/service.go:67 +0x435


Thread-count telemetry around a typical run (ts, pid, threads, handles, cpu%):


2026-08-25 15:20:50  pid 89976 started with  ~40 threads
2026-08-25 15:48     121 threads (climbing, no release)
2026-08-25 16:01:56,89976,121,1321,53   <- still 121, crash expected before long


<details><summary>Sanitized config (DNS/TUN section, structure identical to the one in use)</summary>


{
 "log": {
  "level": "warn",
  "timestamp": true
 },
 "dns": {
  "servers": {
   "Remote-DNS": {
    "type": "https",
    "server": "***.example.com",
    "domain_resolver": "Local-DNS"
   },
   "Local-DNS": {
    "type": "udp",
    "server": "***"
   },
   "dnsfallback": {
    "type": "https",
    "server": "***.example.com",
    "domain_resolver": "Local-DNS"
   }
  },
  "rules": [
   {
    "query_type": [
     "A",
     "AAAA"
    ],
    "rewrite_dns": true
   },
   {
    "clash_mode": "Global",
    "server": "Remote-DNS"
   },
   {
    "clash_mode": "Direct",
    "server": "Local-DNS"
   },
   {
    "rule_set": "GeoSite-CN",
    "server": "Local-DNS"
   },
   {
    "rule_set": "GeoLocation-!CN",
    "server": "Remote-DNS"
   },
   {
    "outbound": "any",
    "server": "dnsfallback"
   }
  ],
  "final": "Remote-DNS",
  "strategy": "ipv4_only"
 },
 "inbounds": [
  {
   "type": "tun",
   "tag": "tun-in",
   "address": [
    "172.18.0.1/30"
   ],
   "mtu": 0,
   "auto_route": true,
   "strict_route": true,
   "stack": "mixed"
  },
  {
   "type": "mixed",
   "tag": "mixed-in",
   "listen": "127.0.0.1",
   "listen_port": 20122
  }
 ],
 "outbounds": [
  {
   "type": "selector",
   "tag": "proxy",
   "outbounds": [
    "trojan-1",
    "trojan-2",
    "direct"
   ],
   "interrupt_exist_connections": false
  },
  {
   "type": "trojan",
   "tag": "trojan-1",
   "server": "***.example.com",
   "server_port": 443,
   "password": "***"
  },
  {
   "type": "trojan",
   "tag": "trojan-2",
   "server": "***.example.com",
   "server_port": 443,
   "type_new": true,
   "password": "***"
  },
  {
   "type": "direct",
   "tag": "direct"
  }
 ],
 "route": {
  "rules": [
   {
    "action": "sniff"
   },
   {
    "protocol": "dns",
    "action": "hijack-dns"
   },
   {
    "ip_is_private": true,
    "outbound": "direct"
   },
   {
    "rule_set": [
     "GeoSite-CN",
     "GeoLocation-!CN"
    ],
    "action": "resolve"
   },
   {
    "rule_set": "GeoSite-CN",
    "outbound": "direct"
   },
   {
    "rule_set": "GeoLocation-!CN",
    "outbound": "proxy"
   }
  ],
  "auto_detect_interface": true,
  "final": "proxy"
 }
}

</details>

Supporter

Integrity requirements

  • [x] I confirm that I have read the documentation, understand the meaning of all the configuration items I wrote, and did not pile up seemingly useful options or default values.
  • [x] I confirm that I have provided the server and client configuration files and process that can be reproduced locally, instead of a complicated client configuration file that has been stripped of sensitive data.
  • [x] I confirm that I have provided the simplest configuration that can be used to reproduce the error I reported, instead of depending on remote servers, TUN, graphical interface clients, or other closed-source software.
  • [x] I confirm that I have provided the complete configuration files and logs, rather than just providing parts I think are useful out of confidence in my own intelligence.

double-tu avatar Aug 25 '26 08:08 double-tu

Reproduced again today, with Delivery Optimization confirmed fully disabled at crash time (registry DODownloadMode = 0, Get-DeliveryOptimizationStatus shows no active jobs). So DO is not the (only) trigger.

New data point: this crash happened after ~3.5h of stable operation (kernel thread count steady at ~121), then the count jumped 121 -> 10002 within 62 seconds (10s-interval sampling) and the process died with the same fatal error: thread exhaustion.

This time the leaked goroutines in the dump were created via a different entry point than the one in the original report (udpnat2.NewPacket): all 326 leaked goroutines are created by route.(*ConnectionManager).NewPacketConnection:

  • 153x [select] blocked in udpnat2.(*natConn).WaitReadPacket
  • 93x [IO wait] blocked in route.(*trackedPacketConn).ReadFrom (route/conn.go:357)
  • 43x [semacquire], 36x [syscall]

Representative stacks (trimmed):

goroutine 467509 [select]:
github.com/sagernet/sing/common/udpnat2.(*natConn).WaitReadPacket(...)
github.com/sagernet/sing-box/route.(*ConnectionManager).packetConnectionCopy(...)
github.com/sagernet/sing-box/route.(*ConnectionManager).NewPacketConnection.gowrap1()
created by github.com/sagernet/sing-box/route.(*ConnectionManager).NewPacketConnection in goroutine 467539

goroutine 467555 [IO wait]:
net.(*UDPConn).readFromUDP(...)
github.com/sagernet/sing-box/route.(*trackedPacketConn).ReadFrom(...)            // route/conn.go:357
github.com/sagernet/sing-box/route.(*ConnectionManager).packetConnectionCopy(...) // route/conn.go:258
github.com/sagernet/sing-box/route.(*ConnectionManager).NewPacketConnection.gowrap2()
created by github.com/sagernet/sing-box/route.(*ConnectionManager).NewPacketConnection in goroutine 467547

Both copy goroutines (in/out) of UDP NAT sessions appear to never exit, so a UDP burst multiplies goroutines faster than they are reaped, and the ones parked in syscall each pin an OS thread until thread exhaustion.

I have the full 1.25 MB dump excerpt saved - happy to attach it if useful.

double-tu avatar Aug 25 '26 12:08 double-tu

Follow-up: trigger identified (ablation), steady-state math, and direct evidence that expired UDP NAT sessions never release their goroutines

1) The UDP storm's seeder was found by ablation — Syncthing's NAT port-mapping discovery. It periodically sends UDP packets to port 5351 (NAT-PMP) addressed to the TUN subnet gateway 172.18.0.2. With auto_route these packets get routed back into the TUN inbound, and each loop iteration spawns a brand-new UDP NAT session (source port increments every round). The sender uses transient sockets (send-then-close), so it never appears in netstat / UDP-endpoint snapshots — I could only pin it down by killing it: I stopped Syncthing at ~01:00, the storm died at 02:01:06 and did not reignite for the following 9+ hours (new-UDP-session rate = 0, OS UDP endpoints back to the ~60 baseline). Before that, the storm had been re-igniting every 30–60 min, matching the NAT-discovery retry interval.

2) Steady-state numbers during the storm (sampled every 10 s): ~1024 concurrent UDP NAT sessions (apparent internal cap), ~205 new sessions/sec — exactly 1024 sessions / 5 s timeout; ~6.2 threads per session → thread count plateaued at ~6350 across two generations of the process. Collateral damage visible in the log while saturated: repeated bind: An operation on a socket ... lacked sufficient buffer failures.

3) The leak, isolated in slow motion. After the storm ended, the session table dropped back to 1 session, but the process thread count stayed frozen at 6349 for 9+ hours (zero variation, 10 s sampling), memory flat at ~149 MB. So sessions that expire normally do not release their copy goroutines / OS threads either — they just stay parked in WaitReadPacket / trackedPacketConn.ReadFrom forever. The Aug 25 fatal case (121 → 10002 threads in 62 s) is simply what happens when a burst outruns this plateau instead of sitting on it.

Practical implication: on Windows, once enough short-lived UDP flows have passed, restarting the core is the only way to reclaim threads. If I may suggest a fix direction: make session expiry also cancel the per-session copy goroutines.

double-tu avatar Aug 27 '26 03:08 double-tu

I did a source-level pass over this against the exact revisions in the report (sing-box v1.13.19 / sing v0.8.13 / sing-tun @ 7c73233). The created by line in the dump matches a specific code path, and the session-reclamation logic there has gaps that plausibly explain the unbounded growth. Details below in case it helps triage.

1. Where the leaked goroutines are born

udpnat2.(*Service).NewPacket.func1 ... service.go:67 is exactly:

go s.handler.NewPacketConnectionEx(ctx, newConn, source, destination, onClose)

— one goroutine per UDP 5-tuple session. With stack: mixed, TUN UDP is always handed to the gvisor forwarder and this NAT, so the config in the report guarantees every new UDP session passes through this line:

sing-tun stack_mixed.go:50      SetTransportProtocolHandler(udp, NewUDPForwarder(...).HandlePacket)
sing-tun stack_gvisor_udp.go:35   udpnat.New(handler, ..., udpTimeout, false)   // sing common/udpnat2
sing common/udpnat2 service.go:53 Service.NewPacket → cache.GetAndRefreshOrAdd(source, alloc)
sing common/udpnat2 service.go:67 go handler.NewPacketConnectionEx(...)          ← the dump creator

2. Why LRU eviction can't reap these goroutines

The NAT table is a freelru LRU: capacity 1024, lifetime = udp_timeout (default C.UDPTimeout = 5 min when unset), expiry purely lazy (no timer; purge happens only on cache activity). OnEvict → conn.Close() closes doneChan once. But doneChan is only honored in the read direction:

  • ReadPacket / WaitReadPacket: select { packetChan, doneChan, readDeadline } — interruptible ✅
  • WritePacket: bare writer.WritePacket(...), no doneChan, no deadline ❌
  • the ctx handed to the session goroutine at service.go:67 is the forwarder/inbound lifetime ctx (f.ctx, stack_gvisor_udp.go:81) — never cancelled while the inbound runs ❌

So a session goroutine blocked in an outbound dial / TLS handshake read / write with no deadline cannot be terminated by evicting its LRU entry. And while a goroutine is blocked in a syscall it pins one OS thread, which matches the observed monotonic thread climb to the 10,000 limit.

3. The arithmetic says the exit paths are failing

The LRU caps live session entries at 1024, yet the dump (851,886 lines ≈ 20k+ goroutines, "vast majority" from service.go:67) is ~20x that. If retirement worked, live :67 goroutines would be bounded by the table size; the overshoot means most of them outlive their entries, stuck on blocking points with no timeout. QUIC makes it worse: every short-lived re-created 5-tuple spawns a fresh :67 goroutine while the old ones never exit — consistent with "heavier UDP churn ⇒ faster crash" (21–64 min).

4. No fixed version to upgrade to

git diff v0.8.13..master -- common/udpnat2 is empty — conn.go/service.go are byte-identical in master and in the v0.9.0-beta.4 that sing-box 1.14 alphas depend on. The only commit in that area (87773cc, "Fix socks client handshake timeout") is the repo's squashed root commit, not a targeted fix, and this config has no socks outbounds anyway.

5. What would settle the exact blocking point

The excerpt only shows created by tails. From the full dump, the head of a few stuck goroutine blocks — the goroutine N [state, N minutes] line plus the top frames above runtime.goexit — would identify the blocking call directly. Reading the source, the candidates I'd rank:

  1. trojan/vless outbound TLS handshake read (no deadline; likely when a urltest group rotates onto a black-holed node among ~150 outbounds)
  2. TCP connect (Windows itself aborts ~21 s, so it contributes pulses, not permanent leaks)
  3. WritePacket into the gvisor stack (possible, less likely)

Possible fixes (udpnat2 / forwarder)

  • derive the session ctx from doneChan + udpTimeout (or enforce an explicit dial/handshake deadline) so evicted sessions actually die
  • put WritePacket under the same doneChan/deadline select
  • add a periodic PurgeExpired to the freelru (currently lazy-only, so entries linger through idle periods)

Workarounds meanwhile

  • "stack": "system" — different UDP NAT code path, bypasses udpnat2
  • a smaller udp_timeout (e.g. "30s") — lowers steady-state session count (won't free goroutines already stuck)
  • trim dead nodes from urltest groups / disable QUIC for offending apps

Related but distinct roots: #4428 (hijacked-DNS entries pinned to udp_timeout in the same NAT — entry retention, not goroutine retention) and #4312 (sing-tun's own NAT on iOS alpha).

double-tu avatar Aug 27 '26 04:08 double-tu