Skip to content

remote debug port stucks upon nc -z but nc works #1308

Open

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

  1. EronWright commented on Nov 15, 2023

    @EronWright

    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?

  2. debugmcpdev commented on Nov 28, 2026

    @debugmcpdev

    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 Client constructor 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 calls accept() 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

    • debugpy 1.8.22 from PyPI (tag v1.8.22, e220805).
    • Windows 11 Pro 10.0.26300, CPython 3.13.12 from python.org, debugpy installed into a fresh venv.
    • Debian 13 (trixie) in the official python:3.13-slim image (CPython 3.13.18), kernel 6.6.87.2-microsoft-standard-WSL2. debugpy was installed there with pip, and everything ran on the container's own loopback.

    Reproduction

    There are three scripts. client.py needs Python 3.10 or later. They use only the standard library.

    1. python -m debugpy --listen 127.0.0.1:5900 target.py ready.txt, then wait for ready.txt to appear. The program writes it once debugpy.listen() has returned, so readiness is known without connecting to the port.
    2. python probe.py close 5900. This does the same as nc -z 127.0.0.1 5900.
    3. 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, close failed in 20 of 20 tries.

    target.py:

    """A program that runs until it is killed.
    
    usage: python -m debugpy --listen 127.0.0.1:PORT target.py READY_FILE
    
    Once it runs, it writes its PID to READY_FILE, so that a test can tell that the
    debug port is ready without connecting to it (debugpy.listen() returns, and the
    script starts, only after the adapter is listening).
    """
    
    import os
    import sys
    import time
    
    ready = sys.argv[1]
    with open(ready + ".tmp", "w") as f:
        f.write(str(os.getpid()))
    os.replace(ready + ".tmp", ready)
    
    while True:
        time.sleep(0.1)

    probe.py:

    """One TCP connection to the debug port that sends no DAP request, then closes.
    
    usage: python probe.py KIND PORT [--host HOST]
    
      close    connect, close at once (what `nc -z HOST PORT` does)
      wait     connect, wait 200 ms, close
      newline  connect, send b"\\n", close (what `echo > /dev/tcp/HOST/PORT` does)
      read     connect, read the adapter's first bytes, close
      reset    connect, close with SO_LINGER 0, so that the close sends RST
    """
    
    import argparse
    import json
    import socket
    import struct
    import sys
    import time
    
    
    def main():
        parser = argparse.ArgumentParser()
        parser.add_argument("kind", choices=["close", "wait", "newline", "read", "reset"])
        parser.add_argument("port", type=int)
        parser.add_argument("--host", default="127.0.0.1")
        args = parser.parse_args()
    
        sock = socket.create_connection((args.host, args.port), timeout=5)
        received = None
        if args.kind == "wait":
            time.sleep(0.2)
        elif args.kind == "newline":
            sock.sendall(b"\n")
        elif args.kind == "read":
            received = len(sock.recv(65536))
        elif args.kind == "reset":
            linger = struct.pack("HH" if sys.platform == "win32" else "ii", 1, 0)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, linger)
        sock.close()
        print(json.dumps({"probe": args.kind, "bytes_received": received}), flush=True)
    
    
    if __name__ == "__main__":
        main()

    client.py:

    """A minimal DAP client for a program started with `python -m debugpy --listen`.
    
    usage: python client.py PORT [--host HOST] [--timeout S]
    
    Sends initialize, attach and configurationDone, then disconnect, and reads the
    response to each before closing the socket. Prints one JSON line. "outcome" is
    "ok", "refused" (nothing listens on the port), "timeout" (no response within
    --timeout seconds; "stage" names the request), "eof" (the adapter closed the
    connection) or "failed" (a response with success=false). "received" lists what
    arrived before the initialize response.
    """
    
    import argparse
    import json
    import socket
    import time
    
    
    class Dap:
        def __init__(self, sock):
            self.sock = sock
            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, deadline):
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise TimeoutError
            self.sock.settimeout(remaining)
            chunk = self.sock.recv(65536)
            if not chunk:
                raise EOFError
            self.buf += chunk
    
        def read(self, deadline):
            while b"\r\n\r\n" not in self.buf:
                self._fill(deadline)
            head, rest = 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(rest) < length:
                self._fill(deadline)
                rest = self.buf.split(b"\r\n\r\n", 1)[1]
            self.buf = rest[length:]
            return json.loads(rest[:length])
    
        def wait_for(self, predicate, timeout, seen=None):
            deadline = time.monotonic() + timeout
            while True:
                msg = self.read(deadline)
                if predicate(msg):
                    return msg
                if seen is not None:
                    seen.append(msg.get("event") or msg.get("command"))
    
    
    def response_to(seq):
        return lambda m: m.get("type") == "response" and m.get("request_seq") == seq
    
    
    def run(host, port, timeout):
        result = {"outcome": None, "stage": "connect", "received": []}
        try:
            sock = socket.create_connection((host, port), timeout=5)
        except ConnectionRefusedError:
            result["outcome"] = "refused"
            return result
        dap = Dap(sock)
        try:
            result["stage"] = "initialize"
            started = time.monotonic()
            seq = dap.send("initialize", {
                "clientID": "repro", "adapterID": "debugpy", "pathFormat": "path",
                "linesStartAt1": True, "columnsStartAt1": True,
            })
            msg = dap.wait_for(response_to(seq), timeout, seen=result["received"])
            assert msg["success"], msg
            result["initialize_ms"] = round((time.monotonic() - started) * 1000)
    
            result["stage"] = "attach"
            attach_seq = dap.send("attach", {"justMyCode": True})
            dap.wait_for(lambda m: m.get("event") == "initialized", timeout)
            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,
                    timeout)
                assert msg["success"], msg
                pending.discard(msg["request_seq"])
    
            result["stage"] = "disconnect"
            seq = dap.send("disconnect", {"terminateDebuggee": False})
            dap.wait_for(response_to(seq), timeout)
            result["outcome"] = "ok"
        except TimeoutError:
            result["outcome"] = "timeout"
        except (EOFError, ConnectionError):
            result["outcome"] = "eof"
        except AssertionError as exc:
            result["outcome"] = "failed"
            result["detail"] = str(exc)[:500]
        finally:
            sock.close()
        return result
    
    
    def main():
        parser = argparse.ArgumentParser()
        parser.add_argument("port", type=int)
        parser.add_argument("--host", default="127.0.0.1")
        parser.add_argument("--timeout", type=float, default=15.0)
        args = parser.parse_args()
        print(json.dumps(run(args.host, args.port, args.timeout)), flush=True)
    
    
    if __name__ == "__main__":
        main()

    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, configurationDone and disconnect were all answered, and the client read the disconnect response before it closed. Without a probe, it never failed.

    Probe before the attach Windows Windows, --log-to Linux Linux, --log-to
    none 10 10 10 10
    close: connect, close at once (like nc -z) 5 6 0 0
    wait: connect, wait 200 ms, close 10 10 10 10
    newline: connect, send \n, close (like echo > /dev/tcp/...) 7 9 0 0
    read: connect, read the adapter's first bytes, close 8 9 4 3
    reset: connect, close with SO_LINGER 0 (RST) 5 7 0 0
    • In all 240 runs the adapter process was still alive afterwards and still owned the listening socket. The program was also still running.
      • On Windows I identified the adapter as the owner of the LISTEN socket on the port (GetExtendedTcpTable). It is a grandchild of the program, through the venv's python.exe launcher.
      • On Linux the adapter has PPID 1 after its double fork, and its command line is .../debugpy/adapter --for-server .... I found it through /proc/net/tcp and /proc/<pid>/fd.
    • Whenever the first attach succeeded, a second attach right after it also succeeded. Whenever it failed, the client had received nothing at all.
    • The --log-to columns also had a threading.excepthook installed (see below). With logging on, every message the adapter writes is followed by a log write (messaging.py L325), 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.

    1. adapter/__main__.py L61 calls clients.serve(), which calls sockets.serve("Client", Client, ...). sockets.serve starts one daemon thread, accept_worker. Its loop catches OSError from accept() only. The handler call, handler(sock) at L176, is the Client class itself, and nothing wraps it in a try.
    2. Client.__init__ runs in this order:
    3. Meanwhile the reader thread reads EOF or a reset from the departed peer, and _read_line raises NoMoreMessages (messaging.py L178-L189). _parse_incoming_messages then queues the disconnect and closes the channel, and with it the stream.
    4. The accept thread's next write then raises in one of two ways:
      • The stream is already closed, so write_json raises NoMoreMessages (messaging.py L293-L296). This path is deliberately not logged.
      • The socket write itself fails, so it raises JsonIOError (L315-L323). This path is logged.
    5. The exception leaves Client.__init__ and handler(sock), and accept_worker returns. Several things stay as they were:
      • The listening socket stays open. It is held in clients.listener, and only clients.stop_serving() closes it, which runs at exit (adapter/__main__.py L133).
      • The adapter stays up, because its main thread waits on the debuggee's server connection (adapter/__main__.py L135).
      • A later client gets connected by the kernel but is never accepted, so it receives nothing and its initialize is 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:

    • the constructor returns, and the loop goes back to accept();
    • the reader's disconnect ends that one session normally, and the next client is served.

    That is what the logs show for every wait run: 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 plain nc that read the greeting before it was interrupted did not wedge the port. In the read kind the probe closes as soon as its first recv returns. On Windows, every failed read run 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 connection line, 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, an OSError from accept() itself. The exits seen were:

    How the accept thread ended Windows (9 failures) Linux (37 failures)
    NoMoreMessages: the reader had already closed the stream (write_json L296) close 4 (1st or 2nd write), read 1 (3rd write) close 6 and reset 8 (1st write), read 1 (3rd write)
    JsonIOError: the socket write failed (write_json L323) reset 3 (1st write, WinError 10054), newline 1 (2nd write, WinError 10053) close 4 and newline 10 (2nd write, BrokenPipeError), reset 2 (1st write, ConnectionResetError), read 6 (3rd write, BrokenPipeError or ConnectionResetError)

    Here the 1st write is clients.py L97, 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.py on PYTHONPATH with UPDBG_HOOK_DIR set. That was for the --log-to columns 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:

    # Diagnostic only. Put this directory on PYTHONPATH and set UPDBG_HOOK_DIR: every
    # Python process that starts then records which process it is, and appends the
    # traceback of any thread that dies with an uncaught exception to a file in that
    # directory. (The adapter closes its stdio at start-up, so the default
    # threading.excepthook has nowhere to print.)
    import os
    
    _dir = os.environ.get("UPDBG_HOOK_DIR")
    if _dir:
        import sys
        import threading
        import time
        import traceback
    
        with open(os.path.join(_dir, "hook-loaded-%d.txt" % os.getpid()), "w") as _f:
            _f.write(repr(getattr(sys, "orig_argv", sys.argv)) + "\n")
    
        def _excepthook(args, _dir=_dir):
            with open(os.path.join(_dir, "thread-died-%d.txt" % os.getpid()), "a") as f:
                name = args.thread.name if args.thread is not None else None
                f.write("%.6f pid=%d thread=%r\n" % (time.time(), os.getpid(), name))
                f.write("".join(traceback.format_exception(
                    args.exc_type, args.exc_value, args.exc_traceback)))
                f.write("\n")
    
        threading.excepthook = _excepthook

    This is a close run on Windows. The adapter log is an excerpt, with JSON bodies condensed onto one line:

    I+00000.107: Listening for incoming Client connections on 127.0.0.1:5917...
    I+00000.394: Accepted incoming Client connection from 127.0.0.1:55006.
    D+00000.394: Starting message loop for channel Client[1]
    D+00000.394: Exiting message loop for channel Client[1]: No more messages
    D+00000.394: Client[1] <-- {"seq": 1, "type": "event", "event": "output", "body": {"category": "telemetry", "output": "ptvsd", "data": {"packageVersion": "1.8.22"}}}
    D+00000.395: Closing Client[1] message stream
    I+00000.395: /handling disconnect from Client[1]/
                 Session[1] has ended.
    I+00000.395: /handling disconnect from Client[1]/
                 Client[1] has disconnected; finalizing Session[1].
    I+00000.395: /handling disconnect from Client[1]/
                 Session[1] finalized.
    

    This is where the log ends. It has no further Client[1] <-- line, and no Accepted line 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):

    pid=48468 thread='Thread-1 (accept_worker)'
    Traceback (most recent call last):
      File "...\Lib\threading.py", line 1044, in _bootstrap_inner
      File "...\Lib\threading.py", line 995, in run
      File "...\debugpy\common\sockets.py", line 176, in accept_worker
        handler(sock)
      File "...\debugpy\adapter\clients.py", line 105, in __init__
        self.channel.send_event(
      File "...\debugpy\common\messaging.py", line 1320, in send_event
        with self._send_message(d):
      File "...\Lib\contextlib.py", line 148, in __exit__
      File "...\debugpy\common\messaging.py", line 1282, in _send_message
        self.stream.write_json(message)
      File "...\debugpy\common\messaging.py", line 296, in write_json
        raise NoMoreMessages(stream=self)
    debugpy.common.messaging.NoMoreMessages: No more messages
    

    When the socket write fails instead, the adapter log shows the whole path by itself. Here is a reset run on Windows (trimmed: JSON condensed, paths shortened, some frames and source lines dropped):

    I+00000.324: Accepted incoming Client connection from 127.0.0.1:62768.
    D+00000.325: Starting message loop for channel Client[1]
    D+00000.325: Exiting message loop for channel Client[1]: [WinError 10054] An existing connection was forcibly closed by the remote host
    E+00000.328: Client[1] <-- {"seq": 1, "type": "event", "event": "output", "body": {"category": "telemetry", "output": "ptvsd", "data": {"packageVersion": "1.8.22"}}}
    
                 Traceback (most recent call last):
                   File "...\debugpy\common\messaging.py", line 317, in write_json
                     written = writer.write(data[data_written:])
                   File "...\Lib\socket.py", line 737, in write
                     return self._sock.send(b)
                 ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
    
                 Stack where logged:
                   ...
                   File "...\debugpy\common\sockets.py", line 176, in accept_worker
                     handler(sock)
                   File "...\debugpy\adapter\clients.py", line 97, in __init__
                     self.channel.send_event(
                   ...
                   File "...\debugpy\common\messaging.py", line 322, in write_json
                   ...
    D+00000.328: Closing Client[1] message stream
    

    The newline kind and #2072

    On 1.8.22 the newline kind (echo > /dev/tcp/HOST/PORT) also runs into #2072. What I measured on Linux:

    • The adapter was still using about 1 CPU second per second when I measured after the attach had timed out, about 16 s after the probe. That held in all 20 Linux newline runs.
    • The reader's Exiting message loop line never appears in the 10 logged runs.

    I did not capture a stack of the spinning thread. That it is the _read_line loop comes from the source and #2072: after the \n the 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 newline runs. 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 Linux newline runs, the accept thread died on its own write, with BrokenPipeError raised as JsonIOError from clients.py line 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 with No 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:

    --- a/src/debugpy/common/sockets.py
    +++ b/src/debugpy/common/sockets.py
    @@ -173,7 +173,12 @@
                     other_host,
                     other_port,
                 )
    -            handler(sock)
    +            try:
    +                handler(sock)
    +            except Exception:
    +                log.swallow_exception(
    +                    "Error handling incoming {0} connection:", name, level="warning"
    +                )
     
         thread = threading.Thread(target=accept_worker)
         thread.daemon = True

    The results below are again 10 fresh programs per kind, without --log-to:

    Probe before the attach Windows, with the change Linux, with the change
    none 10 10
    close 10 10
    wait 10 10
    newline 10 10
    read 10 10
    reset 10 10
    • The second attach also succeeded in every run, no thread died, and the adapter stayed alive.
    • The marker files show that every adapter ran from the patched copy.
    • One Windows read run 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.
    • On Linux the newline reader 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.py L92-L93) and skips its remaining writes. Also, the report_sockets() write goes to the client of the lowest-numbered live session (sessions.py L292-L298), which need not be the new one.

    On main

    The same code is on main at 7764458 (2026-11-24). sockets.py, components.py and sessions.py are identical to the tag. clients.py differs only in two lines elsewhere: a capability key in initialize and the type of onTerminate in attach. The constructor and serve() are unchanged. messaging.py differs only in _read_line (#2073). I did not run main.

    The same shape is also in 1.6.7, the version in the original report. There, handler(sock) is unguarded at sockets.py L122, and the constructor makes two telemetry writes after starting the channel (clients.py L95-L112). That fits the report: nc -z wedged the port, while an nc that 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 --listen impossible to attach to until it is restarted. That includes nc -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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions