Skip to content

Commit 5e5405c

Browse files
authored
Merge pull request #1874 from LazyXuan/fix/windows-parent-watchdog
fix(main): exit Windows stdio servers when the spawning client dies (#914)
2 parents 8ec859b + 4ef5672 commit 5e5405c

2 files changed

Lines changed: 238 additions & 23 deletions

File tree

‎src/main.c‎

Lines changed: 122 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ enum {
7878
#ifdef _WIN32
7979
#include <shellapi.h> /* CommandLineToArgvW — not pulled in by windows.h under WIN32_LEAN_AND_MEAN */
8080
#include <io.h>
81+
#include <tlhelp32.h> /* CreateToolhelp32Snapshot — parent PID discovery for the parent-death watchdog */
8182
#endif
8283
#include "ui/http_server.h"
8384
#include "ui/embedded_assets.h"
@@ -390,7 +391,15 @@ static void signal_handler(int sig) {
390391
* otherwise linger forever blocked on stdin. POSIX has no portable "notify on
391392
* parent death" primitive (PR_SET_PDEATHSIG is Linux-only), so we poll getppid:
392393
* once the parent dies the process is reparented (ppid changes, typically to 1)
393-
* and we shut down. Windows is unaffected (job objects handle this) — #ifndef. */
394+
* and we shut down.
395+
*
396+
* Windows used to be excluded here on the assumption that job objects cover it
397+
* (#914 proved they do not): the KILL_ON_JOB_CLOSE job in subprocess.c only
398+
* wraps processes CBM itself spawns. An MCP stdio server is spawned BY the
399+
* client as its child, and Windows does not propagate parent termination to
400+
* children, so the orphan lingers holding SQLite WAL read locks. The Windows
401+
* branch below waits on a handle to the parent process instead — a signaled
402+
* handle is exact (no PID-reuse window), so no polling of the PID is needed. */
394403

395404
#ifndef _WIN32
396405
typedef struct {
@@ -537,6 +546,110 @@ static bool client_start_parent_watchdog(pid_t initial_ppid) {
537546
}
538547
return true;
539548
}
549+
#else /* _WIN32 */
550+
/* Windows parent-death watchdog — the #914 half of the story.
551+
*
552+
* The KILL_ON_JOB_CLOSE job in subprocess.c only contains processes CBM
553+
* spawns itself; a stdio MCP server is the CLIENT's child, and Windows never
554+
* propagates a parent's termination to its children, so a force-killed client
555+
* leaves the server lingering on stdin while pinning SQLite WAL read locks.
556+
* There is no reparenting to poll for either — instead we open a handle to
557+
* the parent at startup and wait on it: the kernel signals a process handle
558+
* exactly once, when the process terminates, and the held handle pins the
559+
* process object, so PID reuse cannot fool the wait the way re-reading a ppid
560+
* could. The 500 ms timeout exists only to re-check g_shutdown, mirroring the
561+
* POSIX poll cadence.
562+
*
563+
* The worker path keeps its POSIX-only guard: workers are spawned by CBM's own
564+
* subprocess layer inside a kill-on-close job, so containment there is already
565+
* the job object's job. */
566+
typedef struct {
567+
HANDLE parent_process;
568+
bool exit_on_parent_death;
569+
} parent_watchdog_config_t;
570+
571+
static void *parent_watchdog_thread(void *arg) {
572+
parent_watchdog_config_t config = *(parent_watchdog_config_t *)arg;
573+
574+
while (!atomic_load(&g_shutdown)) {
575+
DWORD wait_status = WaitForSingleObject(config.parent_process, 500);
576+
if (wait_status == WAIT_OBJECT_0) {
577+
static const char msg[] = "level=warn msg=parent.exited reason=handle_signaled\n";
578+
(void)_write(_fileno(stderr), msg, sizeof(msg) - 1);
579+
if (config.exit_on_parent_death) {
580+
/* Same deliberate hard stop as the POSIX branch: a lingering
581+
* orphan must release its daemon connection, file locks and
582+
* WAL read lock through kernel handle reclamation, and no
583+
* atexit cleanup is trustworthy after the owning client is
584+
* gone. */
585+
_exit(0);
586+
}
587+
request_shutdown();
588+
break;
589+
}
590+
if (wait_status != WAIT_TIMEOUT) {
591+
break; /* handle became unwaitable — stop watching, never spin */
592+
}
593+
}
594+
return NULL;
595+
}
596+
597+
/* Toolhelp is the documented way to learn one's own parent PID on Windows;
598+
* the PEB value is not exposed through any public API. Returns 0 when the
599+
* lookup itself fails; callers treat that as "no parent signal available". */
600+
static DWORD win_parent_pid_from_snapshot(void) {
601+
DWORD parent_pid = 0;
602+
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
603+
if (snapshot == INVALID_HANDLE_VALUE) {
604+
return 0;
605+
}
606+
PROCESSENTRY32W entry;
607+
ZeroMemory(&entry, sizeof(entry));
608+
entry.dwSize = sizeof(entry);
609+
DWORD self_pid = GetCurrentProcessId();
610+
if (Process32FirstW(snapshot, &entry)) {
611+
do {
612+
if (entry.th32ProcessID == self_pid) {
613+
parent_pid = entry.th32ParentProcessID;
614+
break;
615+
}
616+
} while (Process32NextW(snapshot, &entry));
617+
}
618+
CloseHandle(snapshot);
619+
return parent_pid;
620+
}
621+
622+
static bool client_start_parent_watchdog(DWORD initial_ppid) {
623+
/* Mirrors the POSIX initial_ppid <= 1 bail-out: when no trustworthy parent
624+
* signal exists at startup — snapshot failed, reserved PID, or the parent
625+
* already exited so the handle cannot be opened — keep running and rely on
626+
* the stdin EOF path instead of watching nothing or dying on a false
627+
* alarm. A watchdog thread creation failure, by contrast, is fatal: the
628+
* same fail-closed choice as POSIX. */
629+
if (initial_ppid == 0) {
630+
return true;
631+
}
632+
HANDLE parent_process = OpenProcess(SYNCHRONIZE, FALSE, initial_ppid);
633+
if (!parent_process) {
634+
return true;
635+
}
636+
static parent_watchdog_config_t client_config;
637+
client_config.parent_process = parent_process;
638+
client_config.exit_on_parent_death = true;
639+
cbm_thread_t watchdog;
640+
if (cbm_thread_create(&watchdog, PARENT_WATCHDOG_STACK_SIZE, parent_watchdog_thread,
641+
&client_config) != 0) {
642+
CloseHandle(parent_process);
643+
return false;
644+
}
645+
if (cbm_thread_detach(&watchdog) != 0) {
646+
atomic_store(&g_shutdown, 1);
647+
(void)cbm_thread_join(&watchdog);
648+
CloseHandle(parent_process);
649+
return false;
650+
}
651+
return true;
652+
}
540653
#endif
541654

542655
/* ── CLI mode ───────────────────────────────────────────────────── */
@@ -2527,6 +2640,11 @@ int main(int argc, char **argv) {
25272640
cbm_alloc_init();
25282641
#ifndef _WIN32
25292642
pid_t process_initial_ppid = getppid();
2643+
#else
2644+
/* Captured at the same instant as POSIX: the later OpenProcess in
2645+
* client_start_parent_watchdog must target the process that spawned us,
2646+
* not whatever may have recycled the PID meanwhile. */
2647+
DWORD process_initial_ppid = win_parent_pid_from_snapshot();
25302648
#endif
25312649
#ifdef _WIN32
25322650
{
@@ -3114,15 +3232,16 @@ int main(int argc, char **argv) {
31143232
"cbm-with-ui`.\n");
31153233
}
31163234
}
3117-
#ifndef _WIN32
3235+
/* The Windows branch of this call is the #914 fix: identical placement and
3236+
* failure handling as POSIX (fail-closed — a client that cannot arm its
3237+
* parent watchdog would linger as an orphan after the editor dies). */
31183238
if (!client_start_parent_watchdog(process_initial_ppid)) {
31193239
(void)fprintf(stderr, "codebase-memory-mcp: parent-death watchdog could not start\n");
31203240
(void)cbm_daemon_runtime_client_close(g_daemon_client, MAIN_CLOSE_TIMEOUT_MS);
31213241
g_daemon_client = NULL;
31223242
(void)main_version_cohort_close(&client_cohort_lease, &client_cohort_manager);
31233243
return EXIT_FAILURE;
31243244
}
3125-
#endif
31263245

31273246
setup_signal_handlers();
31283247
int result = cbm_daemon_frontend_mcp_run(g_daemon_client, client_cohort_manager, stdin, stdout);

‎tests/test_parent_watchdog.sh‎

Lines changed: 116 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,18 @@
77
# Strategy: launch the binary under a wrapper "parent" process (stdin kept open
88
# via a FIFO so the server doesn't see EOF), record the child's PID, then kill
99
# the wrapper. The watchdog should notice the changed ppid and exit within a
10-
# few seconds. Skipped on Windows-like shells (the watchdog is POSIX-only).
10+
# few seconds. On Windows (MSYS2 shells) the same tree applies: the wrapper is
11+
# an MSYS bash process, the child a native binary whose parent handle the
12+
# watchdog waits on; killing the wrapper terminates that parent process (#914).
1113
set -euo pipefail
1214

1315
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
1416
BINARY="${CBM_TEST_BINARY:-${ROOT}/build/c/codebase-memory-mcp}"
1517

18+
windows_mode=0
1619
case "$(uname -s)" in
1720
MINGW*|MSYS*|CYGWIN*)
18-
echo "skipping parent watchdog test on Windows"
19-
exit 0
21+
windows_mode=1
2022
;;
2123
esac
2224

@@ -30,33 +32,91 @@ source "${ROOT}/scripts/test-runtime.sh"
3032
cbm_test_runtime_init
3133
tmpdir="${CBM_TEST_RUNTIME_ROOT}"
3234
wrapper_pid=""
35+
writer_pid=""
36+
37+
kill_hard() {
38+
# MSYS signal delivery does not reliably terminate the Windows process
39+
# behind an MSYS pid (observed: a wrapper bash kept running after kill -9,
40+
# so a child's real parent never actually died). Force-kill through
41+
# TerminateProcess on the Windows pid as well. The winpid must be resolved
42+
# BEFORE the msys kill: kill -9 removes the pid from the MSYS process table
43+
# immediately, and the mapping would be lost. `ps -W` exists only on MSYS —
44+
# under `set -o pipefail` a failing ps would abort this helper on POSIX —
45+
# so the pipeline is guarded and simply yields an empty winpid elsewhere.
46+
local pid="$1" winpid
47+
winpid="$(ps -W 2>/dev/null | awk -v m="${pid}" '$1==m {print $4; exit}' || true)"
48+
kill -9 "${pid}" 2>/dev/null || true
49+
[[ -n "${winpid}" ]] && taskkill //F //PID "${winpid}" >/dev/null 2>&1 || true
50+
}
51+
3352
cleanup() {
3453
if [[ -s "${tmpdir}/child.pid" ]]; then
3554
local child_pid
3655
child_pid="$(cat "${tmpdir}/child.pid" 2>/dev/null || true)"
37-
[[ -n "${child_pid}" ]] && kill "${child_pid}" 2>/dev/null || true
56+
[[ -n "${child_pid}" ]] && kill_hard "${child_pid}" || true
57+
fi
58+
# On Windows the pipe writer is an orphaned helper that outlives the wrapper
59+
# by design (it holds stdin open); only the test knows its PID.
60+
if [[ -n "${writer_pid}" ]]; then
61+
kill_hard "${writer_pid}" || true
3862
fi
39-
[[ -n "${wrapper_pid}" ]] && kill "${wrapper_pid}" 2>/dev/null || true
63+
[[ -n "${wrapper_pid}" ]] && kill_hard "${wrapper_pid}" || true
4064
cbm_test_runtime_cleanup "${BINARY}"
4165
}
4266
trap cleanup EXIT
4367

44-
# Wrapper "parent": opens the FIFO read-write so it stays open, launches the
45-
# MCP server with that FIFO as stdin, records the child PID, then waits.
46-
cat >"${tmpdir}/wrapper.sh" <<'SH'
68+
if (( windows_mode )); then
69+
# MSYS FIFOs are not readable by native Windows binaries (the server blocks
70+
# forever), so the stdin-holder is an anonymous PIPE instead: a writer helper
71+
# forwards the initialize request once the test drops it into a file, then
72+
# holds the pipe's write end open forever. Killing the wrapper orphans the
73+
# writer too, so stdin never sees EOF — the child's exit can only come from
74+
# the parent-death watchdog.
75+
cat >"${tmpdir}/wrapper.sh" <<'SH'
76+
#!/usr/bin/env bash
77+
set -euo pipefail
78+
echo $$ >"${TMPDIR_PATH}/writer.pid"
79+
(
80+
for _ in {1..300}; do
81+
if [[ -s "${REQ_FILE}" ]]; then
82+
cat "${REQ_FILE}"
83+
exec sleep 3600
84+
fi
85+
sleep 0.1
86+
done
87+
) | "${CBM_BINARY}" >"${TMPDIR_PATH}/child.out" 2>"${TMPDIR_PATH}/child.err" &
88+
echo "$!" >"${TMPDIR_PATH}/child.pid"
89+
wait
90+
SH
91+
chmod +x "${tmpdir}/wrapper.sh"
92+
: >"${tmpdir}/request.json"
93+
94+
CBM_BINARY="${BINARY}" REQ_FILE="${tmpdir}/request.json" TMPDIR_PATH="${tmpdir}" \
95+
"${tmpdir}/wrapper.sh" &
96+
wrapper_pid=$!
97+
for _ in {1..50}; do
98+
[[ -s "${tmpdir}/writer.pid" ]] && break
99+
sleep 0.1
100+
done
101+
[[ -s "${tmpdir}/writer.pid" ]] && writer_pid="$(cat "${tmpdir}/writer.pid")"
102+
else
103+
# Wrapper "parent": opens the FIFO read-write so it stays open, launches the
104+
# MCP server with that FIFO as stdin, records the child PID, then waits.
105+
cat >"${tmpdir}/wrapper.sh" <<'SH'
47106
#!/usr/bin/env bash
48107
set -euo pipefail
49108
exec 3<>"${FIFO}"
50109
"${CBM_BINARY}" <&3 >"${TMPDIR_PATH}/child.out" 2>"${TMPDIR_PATH}/child.err" &
51110
echo "$!" >"${TMPDIR_PATH}/child.pid"
52111
wait
53112
SH
54-
chmod +x "${tmpdir}/wrapper.sh"
55-
mkfifo "${tmpdir}/stdin"
113+
chmod +x "${tmpdir}/wrapper.sh"
114+
mkfifo "${tmpdir}/stdin"
56115

57-
CBM_BINARY="${BINARY}" FIFO="${tmpdir}/stdin" TMPDIR_PATH="${tmpdir}" \
58-
"${tmpdir}/wrapper.sh" &
59-
wrapper_pid=$!
116+
CBM_BINARY="${BINARY}" FIFO="${tmpdir}/stdin" TMPDIR_PATH="${tmpdir}" \
117+
"${tmpdir}/wrapper.sh" &
118+
wrapper_pid=$!
119+
fi
60120

61121
# Wait for the child PID file to appear.
62122
for _ in {1..50}; do
@@ -80,9 +140,14 @@ fi
80140
# the frontend reached its stdio loop after installing the parent watchdog.
81141
# The old mem.init log sync point belonged to the pre-daemon architecture: the
82142
# shared daemon now owns memory initialization, so a frontend need not emit it.
143+
if (( windows_mode )); then
144+
request_target="${tmpdir}/request.json"
145+
else
146+
request_target="${tmpdir}/stdin"
147+
fi
83148
printf '%s\n' \
84149
'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"parent-watchdog-test","version":"1.0"}}}' \
85-
>"${tmpdir}/stdin"
150+
>"${request_target}"
86151
for _ in {1..150}; do
87152
if [[ -s "${tmpdir}/child.out" ]] &&
88153
grep -Eq '"id"[[:space:]]*:[[:space:]]*1' "${tmpdir}/child.out"; then
@@ -98,8 +163,35 @@ if ! grep -Eq '"id"[[:space:]]*:[[:space:]]*1' "${tmpdir}/child.out" 2>/dev/null
98163
fi
99164

100165
# Kill the wrapper parent: the orphaned child must now self-exit.
101-
kill -9 "${wrapper_pid}"
102-
wait "${wrapper_pid}" 2>/dev/null || true
166+
if (( windows_mode )); then
167+
# Two Windows-specific traps make "kill -9 $wrapper_pid" wrong here:
168+
# 1. MSYS kill -9 does not reliably terminate the Windows process behind
169+
# an MSYS pid (a wrapper bash keeps running), and
170+
# 2. the wrapper's background PIPELINE puts an intermediate subshell bash
171+
# between wrapper and server, and the watchdog watches the
172+
# Windows-physical parent (Toolhelp ParentProcessId) — that subshell.
173+
# Resolve the child's actual Windows parent and TerminateProcess exactly
174+
# that one, mirroring a force-killed MCP client. The wrapper is NOT waited
175+
# on yet: its wait covers the whole pipeline job, and the stdin-holding
176+
# writer must survive until the child's exit is observed, or stdin would
177+
# EOF and the test could pass without the watchdog doing anything.
178+
child_winpid="$(ps -W 2>/dev/null | awk -v m="${child_pid}" '$1==m {print $4; exit}')"
179+
if [[ -z "${child_winpid}" ]]; then
180+
echo "child windows pid not found for msys pid ${child_pid}" >&2
181+
exit 3
182+
fi
183+
parent_winpid="$(powershell.exe -NoProfile -Command \
184+
"(Get-CimInstance Win32_Process -Filter \"ProcessId=${child_winpid}\").ParentProcessId" \
185+
2>/dev/null | tr -d '[:space:]')"
186+
if [[ -z "${parent_winpid}" || ! "${parent_winpid}" =~ ^[0-9]+$ ]]; then
187+
echo "could not resolve the child's windows parent pid" >&2
188+
exit 3
189+
fi
190+
taskkill //F //PID "${parent_winpid}" >/dev/null 2>&1 || true
191+
else
192+
kill -9 "${wrapper_pid}"
193+
wait "${wrapper_pid}" 2>/dev/null || true
194+
fi
103195

104196
deadline=$((SECONDS + 15))
105197
while (( SECONDS < deadline )); do
@@ -109,10 +201,14 @@ while (( SECONDS < deadline )); do
109201
fi
110202
# A zombie no longer holds stdin or runs the MCP loop; kill -0 still reports
111203
# it until launchd/test parent reaps it, so treat that as a successful exit.
112-
child_state="$(ps -p "${child_pid}" -o stat= 2>/dev/null | tr -d '[:space:]' || true)"
113-
if [[ "${child_state}" == Z* ]]; then
114-
echo "ok: child ${child_pid} exited after parent death (zombie awaiting reap)"
115-
exit 0
204+
# Windows has no zombie state — an exited process simply disappears from
205+
# kill -0 — so this probe is POSIX-only.
206+
if [[ "${windows_mode}" -eq 0 ]]; then
207+
child_state="$(ps -p "${child_pid}" -o stat= 2>/dev/null | tr -d '[:space:]' || true)"
208+
if [[ "${child_state}" == Z* ]]; then
209+
echo "ok: child ${child_pid} exited after parent death (zombie awaiting reap)"
210+
exit 0
211+
fi
116212
fi
117213
sleep 0.2
118214
done

0 commit comments

Comments
 (0)