#42125·grpc

[Python] aio: channel.close() leaks C-core TCP subchannel connections when a reader task is cancelled concurrently (bidi streaming)

Author: andyblackheel-acclaimCreated Apr 15, 2026Updated Sep 23, 2026
Labelskind/buglang/Pythonpriority/P2

Environment

  • grpcio: 1.80.0 (latest released at time of filing)
  • Also reproduced on: commit eaf8bdf2c6ebec5843e13fd62932b8584c78e933 (Apr 8) from PR https://github.com/grpc/grpc/pull/41893, which was merged to fix the related asyncio-task leak in issue https://github.com/grpc/grpc/issues/41875. That fix resolves the Python-level task leak but does not fix the TCP socket leak described below.
  • Python: 3.13.11
  • OS: Ubuntu 25.10 (kernel 6.17.5)

Problem Statement

On an grpc.aio bidirectional streaming RPC, when the client's reader task (blocked on await stream.read()) is cancelled synchronously (fire-and-forget task.cancel()) and channel.close() is invoked before that task has actually stopped, the underlying TCP connection is orphaned in ESTABLISHED state. It is not closed by C-core and is not reclaimable from Python — the grpc.aio.Channel object is gone from the user's perspective, but the socket lives on.

In production we observed ~150 ESTABLISHED connections persist for 30+ minutes (and indefinitely, because keepalive_time_ms was unset) after all 75 logical sessions had torn down. Python-side profiling shows no leaked asyncio tasks (with PR #41893 applied) and no grpc.aio.Channel references — the leak lives entirely below Python.

This is distinct from https://github.com/grpc/grpc/issues/41875: that issue is about Python tasks that never resolve; this issue is about TCP sockets that never close. The asyncio-task fix in PR #41893 is a real fix for #41875, but it does not address this one.

Reproducer

Attached: reproduce_bug.sh, client.py, server.py. (GitHub does not accept .proto attachments — echo.proto is inlined as a heredoc inside reproduce_bug.sh.)

The script runs four scenarios (leaky vs fixed teardown × global vs local subchannel pool), starting a fresh server for each. After each client run, it counts ESTABLISHED connections to the server port via ss. Exit code 1 means the scenario leaked at least one TCP connection.

chmod +x reproduce_bug.sh
./reproduce_bug.sh

Leaky teardown pattern (reproduces the bug)

This is the exact pattern used in production (via contextlib.AsyncExitStack LIFO ordering, where stack.callback(task.cancel) fires before the channel's __aexit__):

python
# client.py — run_session_leaky
reader_task = asyncio.create_task(reader())  # blocked on stream.read()
# ... send some messages ...

# === LEAKY TEARDOWN ===
reader_task.cancel()                 # sync, fire-and-forget — task still alive
await channel.close(grace=0)         # closed while reader still has pending read()

Fixed teardown pattern (no leak)

python
# client.py — run_session_fixed
reader_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
    await reader_task                # await the task so C-core call is released

if not stream.done():
    stream.cancel()
    try:
        await asyncio.wait_for(stream.code(), timeout=1.0)
    except (TimeoutError, asyncio.CancelledError, grpc.RpcError):
        pass

await channel.close(grace=0)

Expected output

The leaky_* scenarios leak ESTABLISHED TCP sockets that persist after channel.close() returns; the fixed_* scenarios close cleanly. Example summary from the script:

  Scenario                  Result
  --------                  ------
  leaky_global              LEAKED
  leaky_local               LEAKED
  fixed_global              clean
  fixed_local               clean

The leak is most severe with grpc.use_local_subchannel_pool=True, where each channel owns its own subchannel pool and there is no shared-pool cleanup path to rescue the orphaned connection.

Why this matters

The channel.close() docstring says it "immediately stops the channel from executing new RPCs and begins the process of releasing resources associated with the channel." A user reasonably expects that once await channel.close(grace=...) returns, the TCP socket is either closed or in TIME_WAIT/CLOSE_WAIT. Instead the connection remains ESTABLISHED and there is no way to reach it from Python to close it.

For applications that open a fresh per-session channel (the recommended pattern for use_local_subchannel_pool=True), this causes unbounded FD and connection growth on long-running services.

What we think is happening (C-core)

The bidi stream's C-core call object still holds a reference to the subchannel at the moment channel.close(grace=0) runs, because Python's reader task has not yet been stepped through its CancelledError — task.cancel() only schedules the exception. When the Python channel wrapper is marked closed, the subchannel pool shutdown path sees an outstanding call reference and skips closing the TCP connection. Later, when the reader task finally dies and the call object is released, the channel is already "closed" and there is no longer a cleanup path that will close the socket.

Under use_local_subchannel_pool=True, the pool is per-channel, so there is no other channel that could later reclaim this subchannel — the connection is genuinely orphaned.

Workaround

Until this is fixed in C-core, user code must guarantee that no RPC call object holds a subchannel reference at the moment channel.close() runs. The two teardown steps below must both be applied, in order:

  1. await the reader task to completion after cancelling it (so the call's Python-side references are dropped).
  2. Explicitly stream.cancel() and await stream.code() before calling channel.close().

See run_session_fixed in client.py for the full pattern. Both the fixed_global and fixed_local scenarios in the reproducer confirm that this combination fully prevents the leak.

Ideally, however, channel.close() should itself be robust against pending reader tasks — user code shouldn't have to hand-orchestrate call-object release before closing the channel.

client.py reproduce_bug.sh server.py