Repository navigation
Description
Environment data
- debugpy version: 1.8.22 (from PyPI, into a fresh venv)
- OS and version: Windows 11 Pro (10.0.26300), and Debian 13 (trixie) in the official
python:3.13-slimDocker image (kernel 6.6.87.2-microsoft-standard-WSL2) - Python version (& distribution if applicable, e.g. Anaconda): CPython 3.13.12 from python.org on Windows; CPython 3.13.18 from the image on Linux
- Using VS Code or Visual Studio: neither. The client below is plain Python (standard library only).
Actual behavior
A program started with python -m debugpy --listen 127.0.0.1:PORT script.py gets one adapter process, which owns the listening port. If a client sends disconnect and closes its socket before the adapter has sent the disconnect response, the adapter process exits. Nothing listens on the port after that, so no client can attach again, while the program itself keeps running.
The adapter answers disconnect only after it has passed the request on to pydevd in the debuggee and pydevd has answered. On an idle program that took 1 to 3 ms in my runs. While the debuggee holds the GIL (below, a regular expression with catastrophic backtracking), pydevd cannot answer, and the response waits until the GIL is released. So a client that gives up on the response after about a second, and closes, ends the adapter as soon as the debuggee lets go.
What happens in the adapter (links are to the v1.8.22 tag, e220805):
clients.pyL700-L710:disconnect_requestcallsself.session.finalize(...)(L709) and only thenrequest.respond({})(L710).finalizeforwardsdisconnectto pydevd and waits for its response (sessions.pyL186-L193).- Meanwhile the client channel's reader thread has read EOF and closed the channel (
messaging.pyL1359-L1384), sorespondfails:write_jsonraisesNoMoreMessages(messaging.pyL293-L296). lock_and_handlecatches theJsonIOErrorand callsmessage.cant_handle(...)(components.pyL105-L108).cant_handle→error()sends the error response right away (messaging.pyL556-L557), and that write fails the same way, so aNoMoreMessagesleavescant_handleinstead of aMessageHandlingError.Request._handle(messaging.pyL745-L797) does not catch it: itsexcept MessageHandlingError(L751) does not match, and theexcept NoMoreMessagesat L785 covers only a body returned by a handler, not a handler that callsresponditself. It is re-raised at L792-L797.messaging.pyL1517-L1522,_run_handlers:self.close(); os._exit(1). On Windows the adapter's exit code was 1 in every such run.
Why the port stays closed: the listening socket belongs to the adapter process. It is opened once at adapter start-up (adapter/__main__.py L61 → clients.py L803-L807 → sockets.py L143-L183). In the installed package, vendored pydevd included, the adapter is spawned only by listen() in the debuggee (server/api.py L190-L239), _adapter_process is referenced nowhere else, and listen() runs once per process (L142-L144, L302; nothing resets listen.called).
The same code is on main at 7764458 (2026-11-24). messaging.py there differs only in _read_line (the fix for #2072), which moves the later lines down by 5; components.py, sessions.py, adapter/__main__.py, server/api.py and sockets.py are identical, and disconnect_request in clients.py is unchanged.
Adapter log of one close-early run on Windows (--log-to; excerpt, trimmed: JSON bodies condensed onto one line, source-line echoes and contextlib frames dropped, paths shortened). The Linux log shows the same frames.
D+00001.583: Exiting message loop for channel Client[1]: No more messages
D+00001.583: Closing Client[1] message stream
I+00001.583: /handling #4 request "disconnect" from Client[1]/
client requested "disconnect"; finalizing Session[1].
D+00001.584: /handling #4 request "disconnect" from Client[1]/
Server[1] <-- {"seq": 7, "type": "request", "command": "disconnect", "arguments": {"terminateDebuggee": false}}
D+00001.585: Server[1] --> {"pydevd_cmd_id": 502, "seq": 20, "type": "response", "request_seq": 7, "success": true, "command": "disconnect"}
I+00001.585: /handling #4 request "disconnect" from Client[1]/
Session[1] finalized.
E+00001.594: /handling #4 request "disconnect" from Client[1]/
Handler 'Client.disconnect_request' (file '.../debugpy/adapter/components.py', line 700)
couldn't handle #4 request "disconnect" from Client[1]:
Traceback (most recent call last):
File ".../debugpy/adapter/components.py", line 97, in lock_and_handle
File ".../debugpy/adapter/clients.py", line 710, in disconnect_request
File ".../debugpy/common/messaging.py", line 728, in respond
File ".../debugpy/common/messaging.py", line 1282, in _send_message
File ".../debugpy/common/messaging.py", line 296, in write_json
debugpy.common.messaging.NoMoreMessages: No more messages
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File ".../debugpy/common/messaging.py", line 750, in _handle
File ".../debugpy/adapter/components.py", line 106, in lock_and_handle
File ".../debugpy/common/messaging.py", line 566, in cant_handle
File ".../debugpy/common/messaging.py", line 557, in error
File ".../debugpy/common/messaging.py", line 728, in respond
File ".../debugpy/common/messaging.py", line 1282, in _send_message
File ".../debugpy/common/messaging.py", line 296, in write_json
debugpy.common.messaging.NoMoreMessages: No more messages
Stack where logged:
...
File ".../debugpy/common/messaging.py", line 1518, in _run_handlers
File ".../debugpy/common/messaging.py", line 793, in _handle
In a logged run with the busy program below and a 1 s client timeout, the same log shows the order: disconnect received and forwarded to pydevd at +3.026, the client's EOF at +4.040, pydevd's response at +7.755 (the end of the hold), then the same two failed writes at +7.758.
Expected behavior
A failed write to a client that has gone should end that client's session, not the adapter process that holds the listener. After a client sends disconnect and closes without waiting, the next client should be able to attach, as it can today when the client reads the response first, closes without sending disconnect, or is killed.
Impact: because the response waits on the debuggee, a client with an ordinary timeout of a second or so, detaching from a busy long-running service, removes the ability to debug that service until it is restarted.
Steps to reproduce:
- Create a venv, install
debugpy==1.8.22, and savetarget.pyandclient.py(below) in one folder. The client needs Python 3.10 or later. - Start the program:
python -m debugpy --listen 127.0.0.1:5900 target.py - Attach, send
disconnect, close at once:python client.py close-early 5900 - Try to attach again:
python client.py read-first 5900. It fails withConnectionRefusedError. Nothing listens on 5900 any more and the adapter process is gone, whiletarget.pyis still running. - With a fresh program from step 2, run
python client.py read-first 5900in step 3 instead. The response arrives after about 1 ms, and the second attach in step 4 succeeds.
To see the timing, start target_busy.py (below) instead of target.py and run python client.py read-first 5900 --delay 1.5. The program holds the GIL for a few seconds starting 1 s after a client attaches, and the disconnect response arrives when the hold ends. With --timeout 1 added, the client gives up and closes. The adapter is still alive at that point and exits when the hold ends.
target.py:
import time
while True:
time.sleep(0.1)client.py:
"""Minimal DAP client for a debuggee started with `python -m debugpy --listen HOST:PORT`.
usage: python client.py MODE PORT [--host HOST] [--delay S] [--timeout S]
close-early attach, send "disconnect", close the socket at once
read-first attach, send "disconnect", read until its response (or until
--timeout seconds have passed), then close the socket
no-disconnect attach, close the socket without sending "disconnect"
hang attach, then wait forever (for a test that kills the client)
"""
import argparse
import json
import socket
import time
class Dap:
def __init__(self, host, port):
self.sock = socket.create_connection((host, port), timeout=30)
self.buf = b""
self.seq = 0
def send(self, command, arguments=None):
self.seq += 1
msg = {"seq": self.seq, "type": "request", "command": command}
if arguments is not None:
msg["arguments"] = arguments
body = json.dumps(msg).encode("utf-8")
self.sock.sendall(b"Content-Length: %d\r\n\r\n" % len(body) + body)
return self.seq
def _fill(self):
chunk = self.sock.recv(65536)
if not chunk:
raise EOFError("adapter closed the connection")
self.buf += chunk
def read(self):
while b"\r\n\r\n" not in self.buf:
self._fill()
head, self.buf = self.buf.split(b"\r\n\r\n", 1)
length = None
for line in head.split(b"\r\n"):
name, _, value = line.partition(b":")
if name.strip().lower() == b"content-length":
length = int(value)
while len(self.buf) < length:
self._fill()
body, self.buf = self.buf[:length], self.buf[length:]
return json.loads(body)
def wait_for(self, predicate):
while True:
msg = self.read()
if predicate(msg):
return msg
def is_response(seq):
return lambda m: m.get("type") == "response" and m.get("request_seq") == seq
def attach(dap):
init = dap.wait_for(is_response(dap.send("initialize", {
"clientID": "repro", "adapterID": "debugpy", "pathFormat": "path",
"linesStartAt1": True, "columnsStartAt1": True,
})))
assert init["success"], init
attach_seq = dap.send("attach", {"justMyCode": True})
dap.wait_for(lambda m: m.get("type") == "event" and m.get("event") == "initialized")
done_seq = dap.send("configurationDone")
pending = {attach_seq, done_seq}
while pending:
msg = dap.wait_for(lambda m: m.get("type") == "response" and m.get("request_seq") in pending)
assert msg["success"], msg
pending.discard(msg["request_seq"])
# Read the events that follow the handshake ("process", "thread", ...), as any
# client does, so that nothing unread is left when the socket is closed.
dap.sock.settimeout(0.5)
try:
while True:
dap.read()
except TimeoutError:
pass
dap.sock.settimeout(None)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("mode", choices=["close-early", "read-first", "no-disconnect", "hang"])
parser.add_argument("port", type=int)
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--delay", type=float, default=0.0, help="seconds to wait after attaching")
parser.add_argument("--timeout", type=float, default=None, help="read-first: give up after this many seconds")
args = parser.parse_args()
dap = Dap(args.host, args.port)
attach(dap)
print("attached", flush=True)
time.sleep(args.delay)
if args.mode == "hang":
while True:
time.sleep(60)
if args.mode == "no-disconnect":
dap.sock.close()
print("closed without sending disconnect", flush=True)
return
sent_at = time.time()
seq = dap.send("disconnect", {"terminateDebuggee": False})
if args.mode == "close-early":
dap.sock.close()
print(f"sent disconnect at {sent_at:.3f}, closed at once", flush=True)
return
dap.sock.settimeout(args.timeout)
try:
resp = dap.wait_for(is_response(seq))
except TimeoutError:
print(f"sent disconnect at {sent_at:.3f}, no response within {args.timeout} s, closed", flush=True)
else:
got_at = time.time()
print(f"sent disconnect at {sent_at:.3f}, response at {got_at:.3f} "
f"after {(got_at - sent_at) * 1000:.0f} ms, success={resp['success']}", flush=True)
dap.sock.close()
if __name__ == "__main__":
main()target_busy.py (only for the timing):
# Like target.py, but once a client is attached it holds the interpreter for a
# few seconds: a regular expression with catastrophic backtracking runs in C
# without releasing the GIL, so the debugger's own threads in this process
# cannot run until it returns. Prints wall-clock times of the hold to stderr.
import re
import sys
import time
import debugpy
while not debugpy.is_client_connected():
time.sleep(0.05)
time.sleep(1.0)
start = time.time()
re.match(r"(a+)+$", "a" * 28 + "b")
end = time.time()
print(f"HOLD start={start:.3f} end={end:.3f} seconds={end - start:.3f}", file=sys.stderr, flush=True)
while True:
time.sleep(0.1)What I get
Each row is 5 runs, each on a freshly started program on its own loopback port. About 2 s after the client exited (8 s for the busy rows), I checked whether the adapter process was alive, whether anything still listened on the port, and whether a new read-first attach succeeded. On Windows the adapter is the process that owns the listening socket, a grandchild of the debuggee interpreter through the venv's python.exe launcher. On Linux it double-forks at start-up (adapter/__main__.py L31-L41), so it is not a child: it had PPID 1 and its own session, and I found it as the owner of the listening socket through /proc/net/tcp and /proc/<pid>/fd.
| Client | Windows: adapter gone | Linux: adapter gone |
|---|---|---|
close-early |
5 of 5 | 5 of 5 |
read-first |
0 of 5 | 0 of 5 |
no-disconnect (closes without sending disconnect) |
0 of 5 | 0 of 5 |
hang, then the client process is killed (TerminateProcess / SIGKILL) |
0 of 5 | 0 of 5 |
target_busy.py, read-first --delay 1.5 |
0 of 5 | 0 of 5 |
target_busy.py, read-first --delay 1.5 --timeout 1 |
5 of 5 | 5 of 5 |
"Adapter gone" means all three at once: the adapter process had ended, nothing listened on the port, and the new attach was refused. In every other run the adapter was alive, the port listened, and the new attach succeeded. The debuggee was still running after every run.
Timing:
- Idle program (
read-first): the response came 1 ms afterdisconnectin all 5 Windows runs, and after 1, 1, 3, 3 and 1 ms on Linux. target_busy.py: the holds lasted 5.4 to 5.6 s on Windows and 6.7 to 8.0 s on Linux.disconnectwent out about 1 s into the hold. The response came 4.4 to 4.6 s later on Windows and 5.6 to 6.9 s later on Linux, each time within 1 ms of the end of the hold as printed by the program.target_busy.pywith--timeout 1: when the client exited, the adapter was still alive. It ended 7 to 52 ms after the end of the hold (I polled every 50 ms; 5 Linux runs and 3 further Windows runs).
Possibly related: #1582 reports the same symptom (a re-attach refused with ECONNREFUSED after restarting a remote attach session) without logs, so I can't tell whether this is its cause. #1859 changed the same handler (the channel close after the disconnect response) for a different problem. #1308 is a different failure on the same port: there the adapter stays up but stops accepting after a bare connect-and-close.
this report was prepared by an AI coding agent working for the mcp-debugger project. The reproduction above was run and the linked source lines were read as stated; nothing in it is inferred without a run or a source read.
Activity
fix(session): close_debug_session releases an attached target the way…