Skip to content

fix(ext/net): cancel in-flight reads when closing TCP/Unix/Vsock streams - #35294

Merged
bartlomieju merged 3 commits into
denoland:mainfrom
mlyngvo:fix/net-close-cancel-read-35292
Jun 18, 2026
Merged

bartlomieju merged 3 commits into
denoland:mainfrom
mlyngvo:fix/net-close-cancel-read-35292

Conversation

@mlyngvo

@mlyngvo mlyngvo commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #35292.

Problem

Closing a Deno.Conn (TCP/Unix/Vsock) while a read is in flight does not cancel the read and does not send a FIN — the OS socket stays ESTABLISHED until the process exits. conn.closeWrite() works, so only close() is affected.

Minimal repro (peer never observes EOF after close()):

const listener = Deno.listen({ hostname: "127.0.0.1", port: 0 });
const port = (listener.addr as Deno.NetAddr).port;
(async () => {
  const c = await listener.accept();
  const n = await c.read(new Uint8Array(64));
  console.log("server saw EOF:", n === null); // false with close(), true with closeWrite()
})();
const conn = await Deno.connect({ hostname: "127.0.0.1", port });
conn.readable.getReader().read().catch(() => {}); // read in flight
await new Promise((r) => setTimeout(r, 100));
conn.close();

Root cause

The Resource trait has a default no-op fn cancel_read_ops(self: Rc<Self>) {}. The net stream resources (TcpStreamResource/UnixStreamResource/VsockStreamResource, all FullDuplexResource) define an inherent cancel_read_ops(&self) that performs the real cancellation, but they never override the trait method.

When close() calls self.cancel_read_ops() (and when op_cancel_read dispatches dynamically), self is Rc<Self>, so method resolution picks the trait method — its by-value Rc<Self> receiver is an exact match, while the inherent &self method would require an autoref. The empty default runs, the in-flight read is never cancelled, the read op keeps the resource alive, the socket is never dropped, and no FIN is sent.

FileResource in ext/io does not hit this because it correctly overrides the trait method (delegating to its inherent method). The net resources were missing that override.

Fix

Override cancel_read_ops(self: Rc<Self>) on each affected resource to delegate to the inherent &self cancellation, mirroring FileResource:

  • ext/net/io.rs — TcpStreamResource, UnixStreamResource, VsockStreamResource. The override delegates via the type-alias name (e.g. UnixStreamResource::cancel_read_ops(&self)), which resolves to the inherent method on every platform, so no #[cfg] gating is needed despite the shared impl Resource blocks.
  • ext/io/lib.rs — ChildStdoutResource and ChildStderrResource (ReadOnlyResource) have the identical shape and the same latent bug (closing/cancelling a child's stdout/stderr with a read in flight hit the no-op default). Added the override to both.

TlsStreamResource and FileResource are already correct (TLS cancels its handle directly in close(); FileResource got its override in #34986).

Tests

Adds two regression tests to tests/unit/net_test.ts — netTcpCloseCancelsPendingReadAndSendsFin (TCP) and netUnixCloseCancelsPendingReadAndSendsEof (Unix, skipped on Windows). Each starts a read, calls close(), and asserts the peer observes EOF within a short timeout (cleared via AbortController so the sanitizer sees no leaked timer). Both fail before the fix, pass after.

No vsock test: there is no vsock loopback peer available in the unit-test environment. ChildStdout/ChildStderr are covered by the shared ReadOnlyResource path and the same override.

Verified locally on macOS aarch64: ./x build, cargo clippy -p deno_net -p deno_io, ./x fmt, and ./x test-unit net all pass with no leaks.


Disclosure: this change was investigated and authored with AI assistance (Claude).

@deno-cla-assistant

deno-cla-assistant Bot commented Jun 17, 2026 •

Copy link
Copy Markdown

Deno Individual Contributor License Agreement

All contributors have signed the CLA. Thank you!

Re-run CLA check


This is an automated message from CLA Assistant

The `Resource` trait's default `cancel_read_ops(self: Rc<Self>)` is a no-op.
The net stream resources have an inherent `cancel_read_ops(&self)` that does
the real cancellation, but they never override the trait method. Because the
trait method's by-value `Rc<Self>` receiver is an exact match (no autoref)
while the inherent `&self` method needs an autoref, calls like
`self.cancel_read_ops()` in `close()` — and the dynamic dispatch in
`op_cancel_read` — resolve to the empty trait default instead of the inherent
method.

As a result, closing a TCP/Unix/Vsock stream while a read is in flight never
cancels the read: the read op keeps the resource alive, the socket is never
dropped, and no FIN is sent until the process exits. A single-client peer that
is idle between messages then refuses all further connections.

Override the trait method on each net resource (mirroring `FileResource` in
ext/io) to delegate to the inherent cancellation.

Fixes #35292

@bartlomieju bartlomieju left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for jumping on this so quickly — really nice debugging, and the root-cause writeup is spot on: the trait default cancel_read_ops(self: Rc<Self>) shadows the inherent &self method at the self.cancel_read_ops() call site because the by-value Rc<Self> receiver is an exact match. The fix mirrors the FileResource precedent correctly, and the #[cfg] gating on Unix/Vsock is the right call since those impl Resource blocks are shared with the non-platform stub structs.

I left two inline comments (one must-fix, one optional). One more thing that can't be inlined since the file isn't in this diff:

Same bug also lives in ext/io/lib.rs: ChildStdoutResource and ChildStderrResource are ReadOnlyResources with the identical shape — inherent cancel_read_ops(&self), close() calling self.cancel_read_ops(), and no trait override — so closing/cancelling a child's stdout/stderr with a read in flight hits the same no-op default (the FIFO/pipe-blocking class of bug that #34544 fixed for files). Worth adding the same override to both there, either in this PR or a quick follow-up. (TlsStreamResource and FileResource are already fine — TLS cancels its handle directly, File got its override in #34986.)

Thanks again for the fast turnaround!

Comment thread tests/unit/net_test.ts Outdated
Comment on lines +1773 to +1775
const sawEof = await Promise.race([
serverSawEof,
delay(5000).then(() => false),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This will fail CI as written: the delay(5000) timer is never cleared, so when serverSawEof wins the race the timer is still pending and Deno's test sanitizer reports a leak. I ran this exact test under ./x test-unit net and it fails with:

error: Leaks detected:
  - A timer was started in this test, but never completed.

Abort the timeout once the race settles, e.g.:

const ac = new AbortController();
const sawEof = await Promise.race([
  serverSawEof,
  delay(5000, { signal: ac.signal }).then(() => false, () => false),
]);
ac.abort();

(5s is also more than needed — the FIN arrives within a few ms.)

Comment thread ext/net/io.rs Outdated
Comment on lines +220 to +224
fn cancel_read_ops(self: Rc<Self>) {
#[cfg(unix)]
FullDuplexResource::cancel_read_ops(&self);
#[cfg(not(unix))]
let _ = self;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Optional nit (non-blocking): you can drop the #[cfg] gating on the Unix/Vsock overrides by delegating through the type-alias name instead of FullDuplexResource:: — it resolves to the inherent method on every platform (the FullDuplexResource alias on supported targets, the stub struct otherwise):

fn cancel_read_ops(self: Rc<Self>) {
  UnixStreamResource::cancel_read_ops(&self);
}

Fine to leave as-is though.

Address review feedback on #35294:

- ext/io: ChildStdoutResource and ChildStderrResource have the same shadowing
  bug (inherent cancel_read_ops(&self), close() calling self.cancel_read_ops(),
  no trait override) — closing them with a read in flight hit the no-op trait
  default. Add the override to both.
- ext/net: simplify the Unix/Vsock overrides to delegate through the type-alias
  name instead of FullDuplexResource::, which resolves to the inherent method on
  every platform and drops the #[cfg] gating.
- test: clear the timeout via AbortController so the test sanitizer no longer
  reports a leaked timer (and shorten it — the FIN arrives within a few ms).
@mlyngvo

mlyngvo commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review! All three are addressed in 99b8991:

  1. Test timer leak (must-fix): switched the timeout to an AbortController and abort it once the race settles, so no pending timer is left for the sanitizer to flag. Also dropped it to 2s. Confirmed clean under ./x test-unit net.
  2. #[cfg] gating (nit): took your suggestion — the Unix/Vsock overrides now delegate through the type-alias name (UnixStreamResource::cancel_read_ops(&self) / VsockStreamResource::…), which resolves to the inherent method on every platform. Dropped the #[cfg] blocks; all three net overrides are now uniform.
  3. ext/io (ChildStdoutResource / ChildStderrResource): good catch — identical shape, identical bug. Added the override to both in this PR so it's covered here rather than as a follow-up.

Verified locally on macOS aarch64: ./x build, cargo clippy -p deno_net -p deno_io, ./x fmt, and ./x test-unit net all pass with no leaks.

@mlyngvo
mlyngvo requested a review from bartlomieju June 18, 2026 07:00

@bartlomieju bartlomieju left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, thanks!

@bartlomieju
bartlomieju merged commit c72a8a9 into denoland:main Jun 18, 2026
137 checks passed
@mlyngvo
mlyngvo deleted the fix/net-close-cancel-read-35292 branch June 23, 2026 10:23
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.

Deno.Conn.close() doesn't cancel an in-flight read or send FIN; socket leaks until process exit

2 participants