Skip to content

Hysteria client: Remove closed instance conn - #7107

Merged
RPRX merged 7 commits into
mainfrom
hy-close
Oct 10, 2026
Merged

RPRX merged 7 commits into
mainfrom
hy-close

Conversation

@Fangliding

Copy link
Copy Markdown
Member

在instance 关闭后正确回收连接
#7102 (comment)

patterniha pushed a commit to patterniha/Xray-core that referenced this pull request Oct 8, 2026
Early merge of XTLS#7107 (PR head d06cf79), squashed, ahead of
it landing upstream: XTLS#7107
@svlavr

svlavr commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Possible race here: Dial grabs the client pointer, the cleaner closes it and removes it from manager.m, then Dial opens a new QUIC connection on that client. The cleaner won’t see it anymore.

Maybe check instance.IsRunning() under the client lock before dialing to block redials after shutdown? Right now only the cleaner checks it.

@RPRX

RPRX commented Oct 8, 2026

Copy link
Copy Markdown
Member

@Fangliding fixes #7100 吗

@LjhAUMEM

LjhAUMEM commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

c.close 应该只在 StatusInactive 状态调用,还有一些小地方我需要改下

@LjhAUMEM

LjhAUMEM commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

。。怎么又有提交,别这样搞,有点打架了

@LjhAUMEM LjhAUMEM left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

好了,就这样不要动了

@svlavr

svlavr commented Oct 8, 2026

Copy link
Copy Markdown
Contributor
  1. Cleaner now deletes any StatusNull client. Dial can already hold its pointer, then open QUIC after deletion. If the instance is still running, the new check passes and the connection ends up outside the pool.
  2. MUX creates its worker context from context.Background(). The instance gets lost, so Hysteria sees instance == nil and skips the shutdown check.
  3. Cleaner holds manager.Lock() while waiting for client locks and closing connections. One slow handshake can now block all pool lookups, even for other ready clients.

@LjhAUMEM

LjhAUMEM commented Oct 8, 2026

Copy link
Copy Markdown
Contributor
  1. Cleaner now deletes any StatusNull client. Dial can already hold its pointer, then open QUIC after deletion. If the instance is still running, the new check passes and the connection ends up outside the pool.
  2. MUX creates its worker context from context.Background(). The instance gets lost, so Hysteria sees instance == nil and skips the shutdown check.
  3. Cleaner holds manager.Lock() while waiting for client locks and closing connections. One slow handshake can now block all pool lookups, even for other ready clients.
  1. 已经修复
  2. @Fangliding 确认下这个
  3. 各个握手间是独立的不会持有锁,至于 cleaner 的 Lock 中调用的是 clean,这个几乎不会阻塞,也只有数量堆起来类似十万个 outbound 才会看到影响

@svlavr

svlavr commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Is 9897b5a a rough draft? Dial and the cleaner can now end up waiting on each other. Also, clean() reads the instance state twice.

@LjhAUMEM

LjhAUMEM commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Is 9897b5a a rough draft? Dial and the cleaner can now end up waiting on each other. Also, clean() reads the instance state twice.

可以是最终版,instance 是会被读两次,不是很想在 status 里去区分这个,因为和 quic 无关

@svlavr

svlavr commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

This is based on reading 9897b5a, without a runtime reproduction.

I mean two specific interleavings.

tcp/udp acquires c.Lock. The cleaner then acquires manager.Lock and waits for c.Lock. Next, isRemoved() tries to acquire manager.RLock — both goroutines are now waiting on each other.

With the double read, the issue isn’t the number of checks itself: status() can return Active, so close() is skipped. The instance then stops, the final check returns true, and the entry gets deleted without closing the connection.

@Fangliding

Fangliding commented Oct 8, 2026 •

Copy link
Copy Markdown
Member Author
  1. @Fangliding 确认下这个

应该没有人在hysteria用mux cool吧 可以不考虑以后再说

@Fangliding

Fangliding commented Oct 8, 2026 •

Copy link
Copy Markdown
Member Author

看了一下上面感觉可能close语义略显混乱(我自己写的时候也发现了)因为以前没考虑要移除
可能需要区分 reset(连接死亡等待重启)和Close(完全终止生命)

@LjhAUMEM

LjhAUMEM commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

主要加入 remove 逻辑后就得确保主 manager remove 后后面的 tcp udp 不会再新建 quicConn,我先修下死锁

@Fangliding

Copy link
Copy Markdown
Member Author

子元素的方法取父元素的锁确实很容易导致死锁
防止新建qui conn 其实我上面推的那个commit就是干这个了 多一个status表示连接不再可用自然屏蔽掉
image

@LjhAUMEM

LjhAUMEM commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

我知道,是因为我后面加的,这部分是可以独立出来的,不用动 status

@LjhAUMEM

LjhAUMEM commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

@svlavr

@svlavr

svlavr commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Awesome!
Checked 2b0d898 on Windows/amd64 with Go 1.27.0. Four targeted tests passed:

  • Forced cleanup closes the active QUIC connection and UDP socket.
  • The old client rejects TCP/UDP dials without waiting for the manager lock.
  • After a normal reset, the client reconnects successfully.
  • Delayed authentication on one client no longer blocks another ready client while the cleaner is running.
    Each test passed 10 times. The last scenario failed on 8f705a1. passes on 2b0d898.
    MUX is deferred.

@svlavr

svlavr commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

For MUX, @Fangliding @LjhAUMEM ?

common/mux/client.go:

 type DialingWorkerFactory struct {
+    Ctx      context.Context
     Proxy    proxy.Outbound
     Dialer   internet.Dialer
     Strategy ClientStrategy
 }

 func (f *DialingWorkerFactory) Create() (*ClientWorker, error) {
+    baseCtx := f.Ctx
+    if baseCtx == nil {
+        baseCtx = context.Background()
+    }
+
@@
-        ctx := session.ContextWithOutbounds(context.Background(), outbounds)
+        ctx := session.ContextWithOutbounds(baseCtx, outbounds)

app/proxyman/outbound/handler.go, in both MUX and XUDP factories:

 Factory: &mux.DialingWorkerFactory{
+    Ctx:    core.ToBackgroundDetachedContext(ctx),
     Proxy:  proxyHandler,
     Dialer: h,

This keeps the instance without inheriting request cancellation or other request values.

Jolymmiles added a commit to Jolymmiles/Xray-core that referenced this pull request Oct 10, 2026
The port of XTLS#7107 held the pool read lock while the cleaner
called Instance.IsRunning, which now waits for statusLock held by Start and
Close for the whole feature lifecycle, and while it waited for a client lock
held by a dial during its handshake. Either wait blocked every dial to a new
destination, and then, behind that waiting writer, every Hysteria dial in the
process. A feature whose Close waits for an outbound dial (app/geodata waits
for its cron download, which can use a Hysteria outbound) and the cleaner
then waited on each other.

cleanOnce now snapshots the pool under the read lock and checks and cleans
each client without it. A forced client is still closed before it is
removed, and it is removed only if the pool still holds that pointer, so
overlapping passes keep a replacement a dial added under the same key. This
deviates from upstream XTLS#7107 (2b0d898) and is recorded in docs/FORK.md.

Regression tests, each failing on the previous cleanOnce:
- TestCleanerWaitingForInstanceStatusDoesNotBlockDials
- TestCleanerWaitingForOneClientDoesNotBlockOthers/new_client
- TestConcurrentCleanersKeepReplacementClients (also fails with a snapshot
  that deletes without the identity check)
@RPRX RPRX changed the title Hysteria: Remove closed instance conn Hysteria client: Remove closed instance conn Oct 10, 2026
@RPRX
RPRX merged commit c7dbfd5 into main Oct 10, 2026
TaiLerV pushed a commit to TaiLerV/Xray-core-up that referenced this pull request Oct 13, 2026
Port of XTLS#7107 at 2b0d898,
which fixes XTLS#7100. The Hysteria client pool is
process-wide, so an application that restarts Xray in one process kept
one QUIC connection per stopped instance open, sending keepalives, until
the process exited.

A client now keeps the instance from the context of its first dial. The
cleaner closes the clients of an instance that no longer runs, removes
them from the pool and marks them, so that a dial already holding such a
client fails instead of opening a connection no pool owns.
Instance.IsRunning takes the status lock, and AddFeature uses it.

Differences from the upstream head: the switch of
OmitMaxDatagramFrameSize from the 2026-09-01 date check to true is left
out, because it is unrelated and changes the QUIC transport parameters
of a client whose clock is before that date. The cleaner pass is
clientManager.cleanOnce and the pool lookup is clientManager.dial, so
tests drive one pass on a private pool; a nil-by-default cleaning hook
lets a test see the cleaner reach a client.

Not covered: Mux.Cool builds worker contexts from context.Background(),
so its clients have no instance and are never forced. A dial from a
stopped instance after its client was removed creates a new client that
the next pass closes.

svlavr found the races and deadlocks of the intermediate upstream
versions. The later upstream commits are authored "null <null>"; the PR
discussion suggests LjhAUMEM wrote them.

Co-authored-by: Fangliding <[email protected]>
TaiLerV pushed a commit to TaiLerV/Xray-core-up that referenced this pull request Oct 13, 2026
Sync the fork with upstream 7da5dae..v26.10.10 (13 commits).

Conflict resolutions:
- Routing and DNS Lua scripts (XTLS#6823): take them. The dispatcher picks
  routes through the fork's PickRouteTag, which bypassed the script hook
  upstream placed in PickRoute; PickRouteTag now runs the script too, and
  NeedsSniffingAttributes reports true while a script is loaded because a
  script can read attributes. Covered by script_fastpath_test.go and by
  upstream's TestRouterScriptDNSDispatcherReentry, which failed without it.
- Logging: the Lua log module calls the fork's ShouldLog instead of
  upstream's GetSeverity; its tests save and restore the fork's handler
  snapshot and filter through Enabled.
- Dispatcher: keep the ShouldLog guard and add upstream's error log for a
  failed route pick.
- XDNS (XTLS#7095): take upstream's synchronous upload and its fragment
  manager without the per-client size counter. The fork's full-queue test
  becomes a test that every written packet reaches a resolver; the
  fragment-manager test checks entries only.
- Hysteria (XTLS#7107): keep the fork's pool cleaner (docs/FORK.md); take only
  OmitMaxDatagramFrameSize: true, which the old date check already gave.
- TLS client: keep session resumption in copyConfig and add upstream's
  GetClientCertificate bridge for MASQUE WARP.
- go.mod: add gopher-lua (MIT), gopher-luar (MPL-2.0) and
  x509roots/fallback; keep golang.org/x/text v0.43.0.
- Version stamp stays 26.10.6-2241 until the next fork release.
TaiLerV pushed a commit to TaiLerV/Xray-core-up that referenced this pull request Oct 13, 2026
Upstream merged XTLS#7107 in v26.10.10; the Hysteria bullet now
names that commit. Two new bullets cover the routing script on the
dispatcher's PickRouteTag path and the XDNS WriteTo that sends without
the client mutex, each with the tests that guard it.
@RPRX
RPRX deleted the hy-close branch November 19, 2026 12:25
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.

4 participants