fix(debugger): address review of the Python Debug Server (#6464)

Follow-up to #6421. A waiting Python Debug Server no longer lends its run configuration to other debug starts: each start's configuration is kept by name and taken by its own started event. Listening again retries the port for up to 5 s while the previous adapter shuts down instead of failing with Address already in use. An IDE host of ::1 listens on ::1 (other IPv6 hosts on ::) and the connect line strips the brackets. A VS Code listen host of 0.0.0.0 imports as localhost.

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-27 19:21:53 +08:00
1 джерело 51ccb68b72
коміт 306c71290c
8 files changed
+92 -21

No files matched your search

+31 -9
Переглянути файл
@@ -13,14 +13,24 @@ pub(crate) fn listens(adapter: &str, request: &str, arguments: &Value) -> bool {
}
/// debugpy's adapter leaves an `attach` whose port is taken unanswered (it only logs the error),
/// which would wait for the program forever: find out before starting it.
pub(crate) fn require_free_port(arguments: &Value) -> Result<(), IdeError> {
/// which would wait for the program forever: find out before starting it. Listening again right
/// after a program ended races the previous adapter, which still listens until its shutdown ends.
pub(crate) async fn require_free_port(arguments: &Value) -> Result<(), IdeError> {
// ponytail: polls; waiting on the previous session's shutdown would report a taken port sooner.
const RELEASE: Duration = Duration::from_secs(5);
let listen = &arguments["listen"];
let host = listen["host"].as_str().unwrap_or("127.0.0.1");
let Some(port) = listen["port"].as_u64().and_then(|p| u16::try_from(p).ok()) else { return Ok(()) };
std::net::TcpListener::bind((host, port))
.map(drop)
.map_err(|e| IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}")))
let deadline = tokio::time::Instant::now() + RELEASE;
loop {
match std::net::TcpListener::bind((host, port)) {
Ok(_) => return Ok(()),
Err(e) if tokio::time::Instant::now() >= deadline => {
return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}")));
}
Err(_) => tokio::time::sleep(Duration::from_millis(100)).await,
}
}
}
/// On the program's first stop: warns in the Debug console when its debugpy is not the adapter's.
@@ -63,15 +73,27 @@ mod tests {
assert!(w.contains("debugpy 1.8.0") && w.ends_with("pip install debugpy==1.8.22\n"), "{w}");
}
#[test]
fn a_taken_port_is_reported_before_the_adapter_starts() {
#[tokio::test(start_paused = true)]
async fn a_taken_port_is_reported_before_the_adapter_starts() {
let taken = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = taken.local_addr().unwrap().port();
let listen = json!({"listen": {"host": "127.0.0.1", "port": port}});
let e = require_free_port(&listen).unwrap_err();
let e = require_free_port(&listen).await.unwrap_err();
assert!(e.to_string().contains(&format!("Cannot listen on 127.0.0.1:{port}")), "{e}");
drop(taken);
assert!(require_free_port(&listen).is_ok());
assert!(require_free_port(&listen).await.is_ok());
}
#[tokio::test]
async fn waits_for_the_previous_adapter_to_release_the_port() {
let previous = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = previous.local_addr().unwrap().port();
let released = tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(300)).await;
drop(previous);
});
require_free_port(&json!({"listen": {"host": "127.0.0.1", "port": port}})).await.unwrap();
released.await.unwrap();
}
#[test]
+1 -1
Переглянути файл
@@ -903,7 +903,7 @@ impl DebugManager {
) -> IdeResult<DebugSessionId> {
let mut arguments = launch_arguments(&config)?;
if debugpy::listens(&config.adapter, &config.request, &arguments) {
debugpy::require_free_port(&arguments)?;
debugpy::require_free_port(&arguments).await?;
}
// An IDE-side marker (never sent to the adapter): the session is a Flutter
// one regardless of what the working directory holds.
+6 -1
Переглянути файл
@@ -319,7 +319,12 @@ impl Cx<'_> {
Some(listen) => ("python-debug-server", listen),
None => ("python-remote", obj.get("connect").and_then(Value::as_object).unwrap_or(obj)),
};
let host = self.string(connect, "host")?.unwrap_or_else(|| "localhost".into());
let mut host = self.string(connect, "host")?.unwrap_or_else(|| "localhost".into());
// VS Code's `listen.host` is where the adapter binds; the configuration names the address the
// program connects to, which a wildcard is not: left at localhost for the user to change.
if kind == "python-debug-server" && matches!(host.as_str(), "0.0.0.0" | "::" | "[::]") {
host = "localhost".into();
}
let Some(port) = self.string(connect, "port")? else {
return Err(SkipReason::UnsupportedAttach);
};
+4
Переглянути файл
@@ -385,6 +385,8 @@ fn attach_requests_become_remote_debug_configurations() {
"restart": { "delay": 500, "maxAttempts": 5 } },
{ "name": "Attach to PID", "type": "debugpy", "request": "attach", "processId": "${command:pickProcess}" },
{ "name": "Debug server", "type": "debugpy", "request": "attach", "listen": { "port": 5679 } },
{ "name": "Debug server (all interfaces)", "type": "debugpy", "request": "attach",
"listen": { "host": "0.0.0.0", "port": 5680 } },
{ "name": "Odd", "type": "node", "request": "test" }
]
}"#);
@@ -394,6 +396,8 @@ fn attach_requests_become_remote_debug_configurations() {
server.extras.params,
BTreeMap::from([("host".into(), "localhost".into()), ("port".into(), "5679".into())])
);
// The bind address is not one a program can connect to.
assert_eq!(get(&r, "Debug server (all interfaces)").extras.params["host"], "localhost");
let py = get(&r, "Attach (container)");
assert_eq!((py.kind.as_str(), py.command.as_str()), ("python-remote", ""));
assert_eq!(py.debug_adapter.as_deref(), Some("debugpy"));
+5 -1
Переглянути файл
@@ -167,7 +167,9 @@ describe("remote attach requests", () => {
redirectOutput: true,
justMyCode: expect.any(Boolean),
});
expect(listen({ host: "::1", port: "5679" }).listen).toEqual({ host: "127.0.0.1", port: 5679 });
expect(listen({ host: "::1", port: "5679" }).listen).toEqual({ host: "::1", port: 5679 });
expect(listen({ host: "127.0.0.2" }).listen.host).toBe("127.0.0.1");
expect(listen({ host: "fd00::5" }).listen.host).toBe("::");
expect(listen({ host: "host.docker.internal", remoteRoot: "/app" })).toMatchObject({
listen: { host: "0.0.0.0", port: 5678 },
pathMappings: [{ localRoot: "/p", remoteRoot: "/app" }],
@@ -181,6 +183,8 @@ describe("remote attach requests", () => {
'import debugpy; debugpy.connect(("host.docker.internal", 5679)); debugpy.wait_for_client()',
);
expect(remote.debugpyConnectLine({ host: 'a"b' })).toContain('connect(("a\\"b", 5678))');
// Python's connect takes an IPv6 address without brackets.
expect(remote.debugpyConnectLine({ host: "[::1]" })).toContain('connect(("::1", 5678))');
});
it("Python Debug Server says it waits for a connection until the program connects, and listens again", () => {
+24
Переглянути файл
@@ -174,6 +174,30 @@ describe("Python Debug Server", () => {
}
});
it("lends its configuration to no other start while it waits", async () => {
const connect = waitForProgram();
void startSession(listen, { runConfig: rc });
await vi.waitFor(() => expect(ipc.debugStart).toHaveBeenCalledOnce());
announce(1);
// Another debug session starts while the server still waits for its program.
const otherStarted = waitForProgram();
const other = startSession(
{ ...launch, name: "tests" },
{ runConfig: { name: "tests", kind: "python" } as RunConfig },
);
await vi.waitFor(() => expect(ipc.debugStart).toHaveBeenCalledTimes(2));
handleDebugEvent(2, { kind: "started", name: "tests", adapter: "debugpy", parent: null });
// Announced before its start returns: nothing of the waiting server's.
expect(useDebug.getState().sessions[2]?.status).toBe("running");
expect(useDebug.getState().console[2] ?? []).toEqual([]);
otherStarted(2);
expect(await other).toBe(2);
const { sessions } = useDebug.getState();
expect(sessions[2]).toMatchObject({ status: "running", runConfig: { kind: "python" } });
expect(sessions[1]).toMatchObject({ status: "starting", runConfig: rc });
connect(1);
});
it("does not listen again when a wait is cancelled", async () => {
const rerun = vi.fn();
const dispose = registerAction({ id: "run.debugConfig", title: "Debug", run: rerun });
+11 -3
Переглянути файл
@@ -199,11 +199,19 @@ export const pythonRemoteType: RunConfigTypeContribution = {
/** The line the program runs to connect, in place of PyCharm's `pydevd_pycharm.settrace(...)`. */
export function debugpyConnectLine(p: Params): string {
const host = hostOf(p).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
const host = hostOf(p)
.replace(/^\[(.*)\]$/, "$1")
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"');
return `import debugpy; debugpy.connect(("${host}", ${portOf(p, 5678)})); debugpy.wait_for_client()`;
}
const isLoopback = (host: string) => /^(localhost|127(\.\d+){3}|::1|\[::1\])$/i.test(host);
/** Where the adapter listens: loopback for a local program, every interface (IPv4 or IPv6) otherwise. */
function listenAddress(host: string): string {
if (/^(::1|\[::1\])$/.test(host)) return "::1";
if (/^(localhost|127(\.\d+){3})$/i.test(host)) return "127.0.0.1";
return host.includes(":") ? "::" : "0.0.0.0";
}
export const pythonDebugServerType: RunConfigTypeContribution = {
id: PYTHON_DEBUG_SERVER,
@@ -450,7 +458,7 @@ export function remoteAttachConfig(rc: RunConfig, root: string): LaunchConfig |
case PYTHON_DEBUG_SERVER:
// debugpy's listen mode has no authentication: other machines only when the program runs on one.
return requestBase(rc, "debugpy", root, "attach", {
listen: { host: isLoopback(host) ? "127.0.0.1" : "0.0.0.0", port: portOf(p, 5678) },
listen: { host: listenAddress(host), port: portOf(p, 5678) },
redirectOutput: true,
justMyCode: skip,
...(map ? { pathMappings: [{ localRoot: map.local, remoteRoot: map.remote }] } : {}),
+10 -6
Переглянути файл
@@ -381,7 +381,9 @@ function ownSession(id: DebugSessionId, event: DebugEvent): DebugSession | null
// The new root session takes the tab it replaces now, not once `debugStart` returns.
const replaced = pendingReplacements[0];
// A Python Debug Server's `debugStart` returns once a program connects: until then it is starting.
const rc = pendingConfigs[0]?.runConfig;
// The start this session belongs to (by name): a server still waiting must not lend its configuration.
const at = event.kind === "started" ? pendingConfigs.findIndex((c) => c.name === event.name) : -1;
const rc = at >= 0 ? pendingConfigs.splice(at, 1)[0]!.runConfig : undefined;
const waiting = listensAgain(rc) ? { runConfig: rc, status: "starting" as const } : {};
const slot = { ...waiting, ...(replaced ? { tabOrder: replaced.tabOrder, pinned: replaced.pinned } : {}) };
const s =
@@ -445,7 +447,7 @@ interface ReplacedTab {
/** Finished tabs whose starting replacements have no session yet, oldest start first. */
const pendingReplacements: ReplacedTab[] = [];
/** The run configurations of starts in flight, oldest first. */
const pendingConfigs: { runConfig?: RunConfig }[] = [];
const pendingConfigs: { name: string; runConfig?: RunConfig }[] = [];
/** The new session is shown: the finished tab it replaces gives way. */
function takeReplacement(r: ReplacedTab | undefined) {
@@ -1004,11 +1006,13 @@ export async function startSession(
await flushBreakpoints();
options.preparation?.signal.throwIfAborted();
const adapterStarted = performance.now();
const pending = { runConfig: options.runConfig };
const pending = { name: launch.name, runConfig: options.runConfig };
pendingConfigs.push(pending);
const id = await call(commands.debugStart(launch)).finally(() =>
pendingConfigs.splice(pendingConfigs.indexOf(pending), 1),
);
const id = await call(commands.debugStart(launch)).finally(() => {
// Its session took the entry when it was announced, unless it never was.
const at = pendingConfigs.indexOf(pending);
if (at >= 0) pendingConfigs.splice(at, 1);
});
console.info("Debug adapter started", { name: launch.name, ms: performance.now() - adapterStarted });
owned.add(id);
if (afterDetach && !options.preparation) replaced = replaceFinished(launch.name, options.runConfig?.id);