Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix(e2e): scope teardown process kill to test ports instead of broad pkill (#10375)

Shahmir Varqha58266fe9f6b5
diff --git a/frontend/e2e-tests/global-teardown.ts b/frontend/e2e-tests/global-teardown.ts
index 17f1e6b982..bd8e1d1a3a 100644
--- a/frontend/e2e-tests/global-teardown.ts
+++ b/frontend/e2e-tests/global-teardown.ts
@@ -3,32 +3,92 @@
import { exec } from "node:child_process";
import { promisify } from "node:util";
+import { getTestPorts } from "../playwright.config";
const execAsync = promisify(exec);
+/**
+ * Kill a process and all of its descendants (e.g. orphaned kernel
+ * workers spawned via multiprocessing).
+ */
+async function killProcessTree(pid: number): Promise<void> {
+ try {
+ const { stdout } = await execAsync(`pgrep -P ${pid}`);
+ const childPids = stdout
+ .split("\n")
+ .map((line) => Number.parseInt(line.trim(), 10))
+ .filter((childPid) => Number.isInteger(childPid));
+ await Promise.all(childPids.map((childPid) => killProcessTree(childPid)));
+ } catch {
+ // No children found; pgrep exits non-zero in that case.
+ }
+
+ try {
+ await execAsync(`kill -9 ${pid}`);
+ } catch {
+ // Process may have already exited.
+ }
+}
+
+async function getCommand(pid: number): Promise<string> {
+ try {
+ const { stdout } = await execAsync(`ps -o command= -p ${pid}`);
+ return stdout.trim();
+ } catch {
+ return "";
+ }
+}
+
+/**
+ * Kill whatever is listening on `port`, plus its parent process (`uv`,
+ * which doesn't forward SIGTERM to the marimo process it spawns) and all
+ * descendants (orphaned kernel workers).
+ */
+async function killServerOnPort(port: number): Promise<void> {
+ let pids: number[] = [];
+ try {
+ const { stdout } = await execAsync(`lsof -ti tcp:${port} -sTCP:LISTEN -nP`);
+ pids = stdout
+ .split("\n")
+ .map((line) => Number.parseInt(line.trim(), 10))
+ .filter((pid) => Number.isInteger(pid));
+ } catch {
+ // Nothing listening on this port.
+ return;
+ }
+
+ for (const pid of pids) {
+ const command = await getCommand(pid);
+ if (!command.includes("marimo")) {
+ continue;
+ }
+
+ let targetPid = pid;
+ try {
+ const { stdout } = await execAsync(`ps -o ppid= -p ${pid}`);
+ const parentPid = Number.parseInt(stdout.trim(), 10);
+ if (Number.isInteger(parentPid) && parentPid > 1) {
+ // Only promote to the parent if it's actually the `uv` wrapper;
+ // otherwise leave it alone and just kill the marimo process itself.
+ const parentCommand = await getCommand(parentPid);
+ if (/(^|\/)uv(\s|$)/.test(parentCommand)) {
+ targetPid = parentPid;
+ }
+ }
+ } catch {
+ // Fall back to killing just the pid bound to the port.
+ }
+ await killProcessTree(targetPid);
+ }
+}
+
async function globalTeardown() {
console.log("🧹 Cleaning up test environment...");
try {
- // Kill marimo processes, kernel workers, and parent uv processes.
- // uv doesn't forward SIGTERM to children, so Playwright's
- // webServer termination hangs waiting for the process to exit.
- // Using SIGKILL (-9) ensures processes die immediately.
- //
- // The character-class trick (e.g. [m]arimo) prevents pkill from
- // matching its own shell wrapper process.
- //
- // We kill broadly — any process with "marimo" in its command line —
- // to catch orphan kernel workers that survive the parent being killed.
- const killCmds = [
- "pkill -9 -f '[m]arimo' || true",
- "pkill -9 -f '[u]v.*run.*[m]arimo' || true",
- ];
- for (const cmd of killCmds) {
- // oxlint-disable-next-line typescript/no-empty-function
- await execAsync(cmd).catch(() => {});
- }
- console.log("✅ Cleaned up marimo/uv processes");
+ const ports = getTestPorts();
+ await Promise.all(ports.map((port) => killServerOnPort(port)));
+ console.log(`✅ Cleaned up marimo servers on ports: ${ports.join(", ")}`);
// Small delay to ensure cleanup completes
await new Promise((resolve) => setTimeout(resolve, 1000));
diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts
index 3e74e22d30..5c99dda2fa 100644
--- a/frontend/playwright.config.ts
+++ b/frontend/playwright.config.ts
@@ -62,7 +62,12 @@ const appToOptions = {
export type ApplicationNames = keyof typeof appToOptions;
-function getUrl(port: number, baseUrl = "", queryParams = ""): string {
+function getUrl(options: {
+ port: number;
+ baseUrl?: string;
+ queryParams?: string;
+}): string {
+ const { port, baseUrl = "", queryParams = "" } = options;
return `http://127.0.0.1:${port}${baseUrl}${queryParams}`;
}
@@ -74,9 +79,9 @@ export function getAppUrl(app: ApplicationNames): string {
}
if (options.command === "edit") {
const pathToApp = path.join(pydir, app);
- return getUrl(EDIT_PORT, "", `?file=${pathToApp}`);
+ return getUrl({ port: EDIT_PORT, queryParams: `?file=${pathToApp}` });
}
- return getUrl(options.port, options.baseUrl);
+ return getUrl({ port: options.port, baseUrl: options.baseUrl });
}
export function getAppMode(app: ApplicationNames): "edit" | "run" {
const options: ServerOptions = appToOptions[app];
@@ -102,6 +107,18 @@ export async function resetFile(app: ApplicationNames): Promise<void> {
return;
}
+// All ports that a marimo test server may be started on
+export function getTestPorts(): number[] {
+ const ports = new Set<number>([EDIT_PORT]);
+ for (const opts of Object.values(appToOptions)) {
+ const options = opts as ServerOptions;
+ if (options.port) {
+ ports.add(options.port);
+ }
+ }
+ return [...ports].toSorted((a, b) => a - b);
+}
+
// Start marimo server for the given app
export function startServer(app: ApplicationNames): void {
const options: ServerOptions = appToOptions[app];
@@ -209,7 +226,7 @@ const config: PlaywrightTestConfig = {
return {
command: marimoCmd,
- url: getUrl(port, baseUrl),
+ url: getUrl({ port, baseUrl }),
reuseExistingServer: true,
timeout: 30 * 1000,
ignoreHTTPSErrors: true,
@@ -222,7 +239,7 @@ const config: PlaywrightTestConfig = {
}),
{
command: `uv run marimo -q edit -p ${EDIT_PORT} --headless --no-token`,
- url: getUrl(EDIT_PORT),
+ url: getUrl({ port: EDIT_PORT }),
reuseExistingServer: true,
timeout: 30 * 1000,
ignoreHTTPSErrors: true,