diff --git a/scripts/e2e-ui.sh b/scripts/e2e-ui.sh index 1beb60474..ca5e2b8ff 100755 --- a/scripts/e2e-ui.sh +++ b/scripts/e2e-ui.sh @@ -119,19 +119,40 @@ reap() { kill -9 "$pid" 2>/dev/null || true } +read_pidfile() { + [ -s "$PIDFILE" ] || return 0 + tr -dc '0-9' <"$PIDFILE" 2>/dev/null || true +} + cleanup() { - # If we were signalled mid-boot, e2e-local.sh itself is still running (backgrounded, see below). - # Stop it first so it can't keep waiting on a server we are about to kill. + # ORDER MATTERS. Read the pidfile BEFORE touching the launcher: killing e2e-local.sh first could + # land in the window between its fork and its pidfile write, losing the only handle on a server + # that is already running. + local pid="$SERVER_PID" + [ -n "$pid" ] || pid="$(read_pidfile)" + + # Now stop the backgrounded launcher so it can't keep booting/waiting on a server we're killing. + # Best-effort only — it is never the primary handle on the server (see the grace re-read below). if [ -n "${BOOT_PID:-}" ]; then kill "$BOOT_PID" 2>/dev/null || true BOOT_PID="" fi rm -f "${BOOT_OUT:-}" 2>/dev/null || true - local pid="$SERVER_PID" - if [ -z "$pid" ] && [ -s "$PIDFILE" ]; then - pid="$(tr -dc '0-9' <"$PIDFILE" 2>/dev/null || true)" + # Grace re-read: a signal can land in the sliver between e2e-local.sh forking the server and + # publishing its PID (or between `... &` and this script's `BOOT_PID=$!`). In those cases the + # pidfile is empty at first read but populated microseconds later. Without this, that server is + # orphaned. Bounded at ~1s so a genuinely server-less abort still exits promptly. + if [ -z "$pid" ]; then + local i=0 + while [ "$i" -lt 20 ]; do + pid="$(read_pidfile)" + [ -n "$pid" ] && break + sleep 0.05 + i=$((i + 1)) + done fi + SERVER_PID="" rm -f "$PIDFILE" [ -n "$pid" ] || return 0 @@ -166,6 +187,11 @@ set +e wait "$BOOT_PID" boot_status=$? set -e +# Clear it the moment `wait` reaps the launcher. A stale PID here is not merely useless — the number +# can be RECYCLED by the OS during a long spec run, and cleanup would then SIGTERM an unrelated +# process. (Same "never kill something you didn't prove is yours" rule that removed the earlier +# port-based reap.) +BOOT_PID="" OUT="$(cat "$BOOT_OUT")" rm -f "$BOOT_OUT"