Repository navigation
Description
For remote debugging (the debug server method), I was trying to set my pre-launch task as follows:
"command": "rsync -avlP ../test-debug-server $server:./projects/ && (ssh $server 'cd projects/test-debug-server/; ~/anaconda3/bin/python -m debugpy --listen $server:20001 --wait-for-client test.py' & while ! nc -z $server 20001; do sleep 0.1; done)"
so that remote debugging can appear exactly the same as local debugging.
The last command while ! nc -z $server 20001; do sleep 0.1; done is basically waiting for remote server to be ready so that the debug port can be attached. Unfortunately, although this command can wait until the debug port is ready, VSCode can no longer attach to such a debug port, remote attach takes forever, causing VSCode to stuck forever while waiting for remote debugger to attach.
I have investigated and can confirm that the bug lies in debugpy rather than vscode so I posted the issue here. When I run nc to connect to debug port, it receives some messages from the debug server as follows:
~/projects/python-remote-debug$ nc $server 20001
Content-Length: 137
{"seq": 1, "type": "event", "event": "output", "body": {"category": "telemetry", "output": "ptvsd", "data": {"packageVersion": "1.6.7"}}}Content-Length: 139
{"seq": 2, "type": "event", "event": "output", "body": {"category": "telemetry", "output": "debugpy", "data": {"packageVersion": "1.6.7"}}}
At this time, if I press Ctrl+C to abort the nc command, the debug server is still functioning, VSCode can still attach to this port, and if I run nc $server 20001 again, I will still receive the same message.
However, if I run nc -z as show below:
~/projects/python-remote-debug$ nc -z $server 20001
Connection to 10.8.0.6 port 20001 [tcp/microsan] succeeded!
After this point, although running nc -z again will still return the same succeeded message, the debug port has stucked, VSCode can no longer attach to this debug port, and if I run nc again, I will no longer receive any message from the debug server. I suspect since nc -z closes the TCP port immediately after successful connection without reading the initial message, debugpy did not finished sending the initial message. The expected behaviour should be that debugpy treats the debugger connection as broken and reset to initial state (similar to the first case where I run nc without -z and press Ctrl+C). However, the bug in debugpy causes it to hang in a stucked state, not be able to be attached anymore.
Activity
EronWright commentedon Nov 15, 2023
I too have observed this issue, in the context of trying to wait for the DAP server to be up before attempting to attach to it. I tried to simply make a TCP connection and then disconnect, and observed that the DAP server is then unable to accept new connections.
Does anyone have an idea as to the root cause?
fix(server): the instructions say what a call asks for and where the …
debugmcpdev commentedon Nov 28, 2026
I looked into this with the current release, 1.8.22, and I think I found the cause. It is still there today and is not specific to
nc.In short: the adapter accepts client connections on a single thread, and it runs the whole
Clientconstructor on that thread. The constructor writes three messages to the new connection. If the peer has already gone, one of those writes can raise. Nothing catches the exception, so the accept thread ends. The listening socket stays open and the adapter process stays up. Later connections are still completed by the OS and queued, but nothing ever callsaccept()again. Whether the writes fail is a race, so it does not happen every time. This is a different failure from #2104, where the adapter process exits. Here the adapter stays up and stops accepting.Versions
v1.8.22, e220805).python:3.13-slimimage (CPython 3.13.18), kernel 6.6.87.2-microsoft-standard-WSL2. debugpy was installed there withpip, and everything ran on the container's own loopback.Reproduction
There are three scripts.
client.pyneeds Python 3.10 or later. They use only the standard library.python -m debugpy --listen 127.0.0.1:5900 target.py ready.txt, then wait forready.txtto appear. The program writes it oncedebugpy.listen()has returned, so readiness is known without connecting to the port.python probe.py close 5900. This does the same asnc -z 127.0.0.1 5900.python client.py 5900. When the bug hits, this prints{"outcome": "timeout", "stage": "initialize", "received": []}: the connection succeeds, but nothing arrives within the 15 s timeout, not even the telemetry events. The program keeps running. Otherwise it prints{"outcome": "ok", ...}.Because it is a race, use a fresh program for each try. On Linux,
closefailed in 20 of 20 tries.target.py:probe.py:client.py:What I measured
Each cell counts runs where the attach in step 3 succeeded, out of 10, each with a fresh program. The probe kinds were interleaved. "Succeeded" means
initialize,attach,configurationDoneanddisconnectwere all answered, and the client read thedisconnectresponse before it closed. Without a probe, it never failed.--log-to--log-toclose: connect, close at once (likenc -z)wait: connect, wait 200 ms, closenewline: connect, send\n, close (likeecho > /dev/tcp/...)read: connect, read the adapter's first bytes, closereset: connect, close withSO_LINGER0 (RST)GetExtendedTcpTable). It is a grandchild of the program, through the venv'spython.exelauncher..../debugpy/adapter --for-server .... I found it through/proc/net/tcpand/proc/<pid>/fd.--log-tocolumns also had athreading.excepthookinstalled (see below). With logging on, every message the adapter writes is followed by a log write (messaging.pyL325), so I counted both ways. On Windows fewer runs failed with logging (9 of 50 against 15 of 50). On Linux about the same number did (37 against 36).What happens
All links point to the v1.8.22 tag. The run evidence is below the list.
adapter/__main__.pyL61 callsclients.serve(), which callssockets.serve("Client", Client, ...).sockets.servestarts one daemon thread,accept_worker. Its loop catchesOSErrorfromaccept()only. The handler call,handler(sock)at L176, is theClientclass itself, and nothing wraps it in atry.Client.__init__runs in this order:Component.__init__, which creates the channel and starts it (components.pyL52-L55). That starts the channel's reader thread (messaging.pyL1197-L1214).outputevents (L97-L112).sessions.report_sockets()(L113), which writesdebugpySockets(sessions.pyL292-L298,clients.pyL732-L748)._read_lineraisesNoMoreMessages(messaging.pyL178-L189)._parse_incoming_messagesthen queues the disconnect and closes the channel, and with it the stream.write_jsonraisesNoMoreMessages(messaging.pyL293-L296). This path is deliberately not logged.JsonIOError(L315-L323). This path is logged.Client.__init__andhandler(sock), andaccept_workerreturns. Several things stay as they were:clients.listener, and onlyclients.stop_serving()closes it, which runs at exit (adapter/__main__.pyL133).adapter/__main__.pyL135).initializeis never read.What decides the race is whether the accept thread finishes its three writes before the reader thread has seen the peer leave and closed the stream, and before the peer's RST makes a socket write fail. If all three writes go out first:
accept();That is what the logs show for every
waitrun: all three writes went out within 2 ms of the accept, and the reader ended 200 to 225 ms after it. It also fits the original report, where a plainncthat read the greeting before it was interrupted did not wedge the port. In thereadkind the probe closes as soon as its firstrecvreturns. On Windows, every failedreadrun had received 161 bytes (the first event only) and every successful one 536 bytes (all three). On Linux, every failure had 161 bytes and every success 324 bytes (two events).Run evidence
In the logged runs, every failure shows exactly one
Accepted incoming Client connectionline, the probe's. Every success after a probe shows three: the probe's and the two attaches'. In every failure the accept thread died with a traceback. In no success did any thread die. I never saw the other way out of the loop, anOSErrorfromaccept()itself. The exits seen were:NoMoreMessages: the reader had already closed the stream (write_jsonL296)close4 (1st or 2nd write),read1 (3rd write)close6 andreset8 (1st write),read1 (3rd write)JsonIOError: the socket write failed (write_jsonL323)reset3 (1st write, WinError 10054),newline1 (2nd write, WinError 10053)close4 andnewline10 (2nd write,BrokenPipeError),reset2 (1st write,ConnectionResetError),read6 (3rd write,BrokenPipeErrororConnectionResetError)Here the 1st write is
clients.pyL97, the 2nd is L105, and the 3rd is L113 (report_sockets).The adapter closes its stdio at start-up, so a dying thread's traceback normally goes nowhere. To capture it I put this
sitecustomize.pyonPYTHONPATHwithUPDBG_HOOK_DIRset. That was for the--log-tocolumns and for the runs with the change below, not for the plain columns. Apart from a marker file it writes at start-up, it changes nothing:This is a
closerun on Windows. The adapter log is an excerpt, with JSON bodies condensed onto one line:This is where the log ends. It has no further
Client[1] <--line, and noAcceptedline for the attach that came 0.5 s later and waited 15 s. The hook recorded the following (trimmed: timestamp and paths shortened, caret lines and some source lines dropped):When the socket write fails instead, the adapter log shows the whole path by itself. Here is a
resetrun on Windows (trimmed: JSON condensed, paths shortened, some frames and source lines dropped):The
newlinekind and #2072On 1.8.22 the
newlinekind (echo > /dev/tcp/HOST/PORT) also runs into #2072. What I measured on Linux:newlineruns.Exiting message loopline never appears in the 10 logged runs.I did not capture a stack of the spinning thread. That it is the
_read_lineloop comes from the source and #2072: after the\nthe stream is at EOF in the middle of a header line, and that loop retries without bound.On Windows the adapter spun in none of the 20
newlineruns. In the 10 logged ones the reader ended with WinError 10054 or 10053.The spin is a separate defect, and #2073 fixes it on
main. It is not what stops the accept loop. In the Linuxnewlineruns, the accept thread died on its own write, withBrokenPipeErrorraised asJsonIOErrorfromclients.pyline 105. That is the same path as the other kinds.#2072 says that a peer which closes without sending anything is handled correctly today. That holds for
read_json: in these logs the reader thread ends cleanly withNo more messages. The failure is on the other thread, in the writes the constructor makes.A check of the cause
To check that this one uncaught exception accounts for the hang, I ran a copy of the installed 1.8.22 package, put first on
PYTHONPATH, with this one change and no other:The results below are again 10 fresh programs per kind, without
--log-to:closewaitnewlinereadresetreadrun was lost to an error in my harness: it read the ready file while the program was replacing it, before any connection was made. I repeated that run.newlinereader thread still spun (Adapter spins at 100% CPU when a peer disconnects in the middle of a message header #2072) in all 10 runs, but both attaches were served.I don't propose this as the fix. It only shows where the loop is lost. A constructor that raises has already registered its session (
clients.pyL92-L93) and skips its remaining writes. Also, thereport_sockets()write goes to the client of the lowest-numbered live session (sessions.pyL292-L298), which need not be the new one.On
mainThe same code is on
mainat 7764458 (2026-11-24).sockets.py,components.pyandsessions.pyare identical to the tag.clients.pydiffers only in two lines elsewhere: a capability key ininitializeand the type ofonTerminateinattach. The constructor andserve()are unchanged.messaging.pydiffers only in_read_line(#2073). I did not runmain.The same shape is also in 1.6.7, the version in the original report. There,
handler(sock)is unguarded atsockets.pyL122, and the constructor makes two telemetry writes after starting the channel (clients.pyL95-L112). That fits the report:nc -zwedged the port, while anncthat read the greeting and was then interrupted did not.Expected
A client that connects and leaves should cost the adapter one failed session, not its ability to serve the next client. Today a port check before attaching can make a program started with
--listenimpossible to attach to until it is restarted. That includesnc -z,echo > /dev/tcp/..., or a script waiting for the port to open.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.