Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

fix(supervisor): wrap only marked host binaries; watchdog in worker mode

Martin Vogelfbd7287f4cb7
diff --git a/scripts/test.sh b/scripts/test.sh
index 1f5c6d9ed..1254419a6 100755
--- a/scripts/test.sh
+++ b/scripts/test.sh
@@ -75,6 +75,12 @@ echo "=== Step 5: parent-death watchdog regression (#406/#407) ==="
make -j"$NPROC" -f Makefile.cbm cbm $MAKE_ARGS
bash "$ROOT/tests/test_parent_watchdog.sh"
+# Step 5b: worker-mode parent-death watchdog (#845). A supervised index worker
+# (`cli --index-worker …`) whose supervisor dies must self-exit instead of
+# indexing on as an orphan. Reuses the prod binary built in Step 5.
+echo "=== Step 5b: worker-mode watchdog regression (#845) ==="
+bash "$ROOT/tests/test_worker_watchdog.sh"
+
# Step 6: security-strings URL allow-list regression. The MSYS2 CLANG64 toolchain
# bakes its package-tracker URL into the static Windows .exe; the binary string
# audit must allow-list it (Windows-only — Linux smoke never saw it).
diff --git a/src/main.c b/src/main.c
index 05a5da1db..5bbaa65c9 100644
--- a/src/main.c
+++ b/src/main.c
@@ -328,6 +328,29 @@ static int run_cli(int argc, char **argv) {
const char *response_out = cli_strip_flag_value(&argc, argv, "--response-out");
cbm_index_set_worker_role(index_worker, response_out);
+#ifndef _WIN32
+ /* #845: a supervised worker must not outlive its supervisor. If the parent
+ * dies without reaping us (agent killed, supervisor crashed), an orphaned
+ * worker would index on unsupervised — observed contributing to memory
+ * pressure during the 2026-07-04 host panics. Reuse the parent-death
+ * watchdog (safe outside server mode: on ppid change it only writes to
+ * stderr and _exit(0)s — no cleanup dependencies). Detached: the worker
+ * exits by returning from run_cli; exit() tears the thread down. Failure
+ * to start is non-fatal, same policy as the MCP-server watchdog. */
+ if (index_worker) {
+ static pid_t worker_initial_ppid; /* static: outlives run_cli for the thread */
+ worker_initial_ppid = getppid();
+ cbm_thread_t worker_watchdog_tid;
+ if (cbm_thread_create(&worker_watchdog_tid, PARENT_WATCHDOG_STACK_SIZE,
+ parent_watchdog_thread, &worker_initial_ppid) == 0) {
+ (void)cbm_thread_detach(&worker_watchdog_tid);
+ cbm_log_info("worker.watchdog.start");
+ } else {
+ cbm_log_warn("worker.watchdog.unavailable", "reason", "thread_create_failed");
+ }
+ }
+#endif
+
if (argc < MAIN_MIN_ARGC) {
(void)fprintf(stderr, CLI_USAGE);
return SKIP_ONE;
@@ -563,6 +586,13 @@ int main(int argc, char **argv) {
* below opens sqlite early), else sqlite3_config returns SQLITE_MISUSE and
* the bind is silently ignored. No-op in the test build. */
cbm_alloc_init();
+ /* #845: mark this process as the REAL binary so the index supervisor may
+ * wrap index_repository in a worker subprocess. Must run before any
+ * subcommand dispatch so MCP-server, CLI, and HTTP paths are all covered.
+ * Embedders of cbm_mcp_handle_tool (test binaries) never mark themselves,
+ * so they index in-process instead of re-invoking themselves as
+ * `<self> cli --index-worker …` (recursive suite re-runs / spawn chains). */
+ cbm_index_supervisor_mark_host();
cbm_cli_set_version(CBM_VERSION);
cbm_profile_init(); /* reads CBM_PROFILE env var, gates all prof macros */
/* CBM_LOG_LEVEL support — distilled from #414 (closes #413). Apply before
diff --git a/src/mcp/index_supervisor.c b/src/mcp/index_supervisor.c
index 74c393186..45a56b8f3 100644
--- a/src/mcp/index_supervisor.c
+++ b/src/mcp/index_supervisor.c
@@ -43,7 +43,27 @@ const char *cbm_index_worker_response_out(void) {
return g_worker_response_out[0] ? g_worker_response_out : NULL;
}
+/* Test hook (#845): counts spawn ATTEMPTS (entry to cbm_index_spawn_worker),
+ * including ones that fail to resolve the self binary — an embedder must never
+ * even try to spawn. */
+static int g_spawn_count = 0;
+
+int cbm_index_supervisor_spawn_count(void) {
+ return g_spawn_count;
+}
+
+/* #845: opt-in host mark — see the header. Set once from the real binary's
+ * main(); embedders never set it, so should_wrap() stays false for them. */
+static bool g_host_marked = false;
+
+void cbm_index_supervisor_mark_host(void) {
+ g_host_marked = true;
+}
+
bool cbm_index_supervisor_should_wrap(void) {
+ if (!g_host_marked) {
+ return false; /* embedder (#845): never spawn `<self> cli --index-worker` */
+ }
if (g_worker_active) {
return false; /* I am the worker — run in-process, never re-supervise */
}
@@ -115,6 +135,7 @@ static void worker_tmp_path(char *out, size_t out_sz, int pid, const char *suffi
int cbm_index_spawn_worker(const char *args_json, bool single_thread, const char *marker_file,
const char *quarantine_file, cbm_index_worker_result_t *result) {
+ g_spawn_count++; /* test hook (#845) — see cbm_index_supervisor_spawn_count */
result->outcome = CBM_PROC_SPAWN_FAILED;
result->exit_code = -1;
result->term_signal = 0;
diff --git a/src/mcp/index_supervisor.h b/src/mcp/index_supervisor.h
index d585b48e8..95fcf7fb1 100644
--- a/src/mcp/index_supervisor.h
+++ b/src/mcp/index_supervisor.h
@@ -32,11 +32,28 @@ void cbm_index_set_worker_role(bool is_worker, const char *response_out);
bool cbm_index_worker_active(void);
const char *cbm_index_worker_response_out(void);
+/* Host marking (#845): the supervisor gate is OPT-IN per process. Only the real
+ * codebase-memory-mcp binary calls this (first thing in main(), before any
+ * subcommand dispatch, so MCP server + CLI + HTTP paths are all covered).
+ * EMBEDDERS of cbm_mcp_handle_tool (test binaries, future library users) never
+ * call it, so they index in-process by default. Without this gate the supervisor
+ * resolved the CURRENT executable and re-invoked it as
+ * `<self> cli --index-worker …` — a test binary ignores those args and re-runs
+ * its suites instead, producing recursive spawn chains (11-min hangs; kernel
+ * VM-map pressure during the 2026-07-04 host panics). */
+void cbm_index_supervisor_mark_host(void);
+
/* True when handle_index_repository should wrap the run in a supervised child:
- * this process is not itself a worker AND the kill switch (CBM_INDEX_SUPERVISOR=0)
- * is not set. */
+ * this process called cbm_index_supervisor_mark_host() (i.e. it IS the real
+ * binary, not an embedder), is not itself a worker, AND the kill switch
+ * (CBM_INDEX_SUPERVISOR=0) is not set. */
bool cbm_index_supervisor_should_wrap(void);
+/* TEST HOOK (#845): process-wide count of worker-spawn attempts, incremented on
+ * entry to cbm_index_spawn_worker. Embedder tests assert the count is unchanged
+ * across an index_repository call to prove indexing ran IN-PROCESS. */
+int cbm_index_supervisor_spawn_count(void);
+
typedef struct {
cbm_proc_outcome_t outcome; /* how the worker ended */
int exit_code; /* worker exit code (-1 if signalled) */
diff --git a/tests/repro/repro_main.c b/tests/repro/repro_main.c
index 6c516be32..24277ea7b 100644
--- a/tests/repro/repro_main.c
+++ b/tests/repro/repro_main.c
@@ -26,6 +26,7 @@ int tf_fail_count = 0;
int tf_skip_count = 0;
#include "test_framework.h"
+#include "foundation/compat.h" /* cbm_setenv — #845 supervisor kill switch */
/* Per-suite summary + filter. RUN_SUITE prints a one-line
* "[SUITE] <name> P passed, F failed" report (greppable for which suites still
@@ -109,6 +110,13 @@ extern void suite_repro_lsp_java_cs(void);
extern void suite_repro_lsp_kt_php_rust(void);
int main(void) {
+ /* #845 belt-and-suspenders: this binary EMBEDS cbm_mcp_handle_tool and its
+ * main() IGNORES argv — spawned as `<self> cli --index-worker …` it would
+ * re-run EVERY repro suite recursively (the observed 11-min hangs). The
+ * supervisor gate already ignores unmarked hosts; pin the kill switch too.
+ * A test that exercises the supervisor must explicitly re-enable it. */
+ cbm_setenv("CBM_INDEX_SUPERVISOR", "0", 1);
+
/* Unbuffered: a reproduction may crash/_exit (or a sanitizer may _exit on a
* leak) before stdio flushes — keep every printed line so the summary and the
* RED rows always reach the board even on an abnormal exit. */
diff --git a/tests/test_main.c b/tests/test_main.c
index df86c18b0..da7c21c50 100644
--- a/tests/test_main.c
+++ b/tests/test_main.c
@@ -9,6 +9,7 @@ int tf_fail_count = 0;
int tf_skip_count = 0;
#include "test_framework.h"
+#include "foundation/compat.h" /* cbm_setenv — #845 supervisor kill switch */
#include <sqlite3.h>
#include <stdbool.h>
#include <string.h>
@@ -134,6 +135,13 @@ extern void suite_dump_verify_io(void);
extern void cbm_kind_in_set_free_cache(void);
int main(int argc, char **argv) {
+ /* #845 belt-and-suspenders: this binary EMBEDS cbm_mcp_handle_tool. The
+ * supervisor gate already ignores unmarked hosts, but pin the kill switch
+ * too so even a future supervisor-marked test host can never resolve THIS
+ * binary as `<self> cli --index-worker …` and recursively re-run suites.
+ * A test that exercises the supervisor must explicitly re-enable it. */
+ cbm_setenv("CBM_INDEX_SUPERVISOR", "0", 1);
+
g_suite_argc = argc;
g_suite_argv = argv;
printf("\n codebase-memory-mcp C test suite\n");
diff --git a/tests/test_mcp.c b/tests/test_mcp.c
index 81613a6dd..e8cc2abcb 100644
--- a/tests/test_mcp.c
+++ b/tests/test_mcp.c
@@ -9,6 +9,7 @@
#include "../src/foundation/log.h"
#include "test_framework.h"
#include <cli/cli.h>
+#include <mcp/index_supervisor.h> /* spawn-count hook — #845 in-process guard */
#include <mcp/mcp.h>
#include <pipeline/pipeline.h>
#include <store/store.h>
@@ -23,6 +24,7 @@
#define cbm_chdir _chdir
#define cbm_getcwd _getcwd
#else
+#include <sys/wait.h> /* waitpid — #845 fork+alarm harness */
#include <unistd.h>
#define cbm_chdir chdir
#define cbm_getcwd getcwd
@@ -4032,6 +4034,138 @@ TEST(readonly_query_succeeds_on_readonly_fs) {
#undef ROQ_PROJECT
+/* ══════════════════════════════════════════════════════════════════
+ * #845 — supervisor gate must not wrap embedders of cbm_mcp_handle_tool
+ * ══════════════════════════════════════════════════════════════════ */
+
+/* Child-side check: index a tiny fixture and verify it ran IN-PROCESS.
+ * Distinct exit codes so the parent can report the exact failure mode. */
+enum {
+ IDX845_OK = 0,
+ IDX845_SPAWNED = 41, /* a worker subprocess was spawned — the #845 bug */
+ IDX845_NO_RESULT = 42, /* handle_tool returned NULL */
+ IDX845_NOT_INDEXED = 43, /* response lacks status=indexed */
+};
+
+static int idx845_index_inprocess_check(const char *repo_dir) {
+ int spawns_before = cbm_index_supervisor_spawn_count();
+
+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
+ if (!srv) {
+ return IDX845_NO_RESULT;
+ }
+ char args[1024];
+ snprintf(args, sizeof(args), "{\"repo_path\":\"%s\",\"mode\":\"fast\"}", repo_dir);
+ char *resp = cbm_mcp_handle_tool(srv, "index_repository", args);
+
+ int code = IDX845_OK;
+ if (cbm_index_supervisor_spawn_count() != spawns_before) {
+ code = IDX845_SPAWNED;
+ } else if (!resp) {
+ code = IDX845_NO_RESULT;
+ } else if (!response_contains_json_fragment(resp, "\"status\":\"indexed\"")) {
+ code = IDX845_NOT_INDEXED;
+ }
+ free(resp);
+ cbm_mcp_server_free(srv);
+ return code;
+}
+
+TEST(index_supervisor_gate_requires_marked_host_issue845) {
+ /* #845: index_repository via cbm_mcp_handle_tool from an EMBEDDER (this test
+ * binary) must index IN-PROCESS even with CBM_INDEX_SUPERVISOR unset. The
+ * supervisor gate may only wrap a process that called
+ * cbm_index_supervisor_mark_host() — i.e. the real binary's main(). Before
+ * the fix, should_wrap() was true for ANY embedder: the gate resolved the
+ * CURRENT binary (this test runner!) and spawned
+ * '<test-runner> cli --index-worker index_repository …', which a test binary
+ * interprets as suite-filter args → it re-runs test suites in the child →
+ * recursive spawn chains (observed 11-min hangs; kernel VM-map load during
+ * the 2026-07-04 host panics).
+ *
+ * POSIX: run the call in a forked child under alarm(20) so the pre-fix
+ * recursive behaviour cannot hang the runner; the child reports via exit
+ * code. Windows: no fork — run in-process (safe once the gate is fixed; the
+ * pre-fix redness is demonstrated on POSIX). */
+ char tmp_dir[256];
+ snprintf(tmp_dir, sizeof(tmp_dir), "/tmp/cbm-idx845-repo-XXXXXX");
+ if (!cbm_mkdtemp(tmp_dir)) {
+ PASS();
+ }
+ char cache[256];
+ snprintf(cache, sizeof(cache), "/tmp/cbm-idx845-cache-XXXXXX");
+ if (!cbm_mkdtemp(cache)) {
+ cbm_rmdir(tmp_dir);
+ PASS();
+ }
+
+ const char *saved_cache = getenv("CBM_CACHE_DIR");
+ char *saved_cache_copy = saved_cache ? strdup(saved_cache) : NULL;
+ cbm_setenv("CBM_CACHE_DIR", cache, 1);
+
+ /* The point of the guard: NO kill switch. The gate itself must keep an
+ * unmarked host in-process. Save + restore the ambient value. */
+ const char *saved_sv = getenv("CBM_INDEX_SUPERVISOR");
+ char *saved_sv_copy = saved_sv ? strdup(saved_sv) : NULL;
+ cbm_unsetenv("CBM_INDEX_SUPERVISOR");
+
+ char src_path[512];
+ snprintf(src_path, sizeof(src_path), "%s/main.py", tmp_dir);
+ FILE *fp = fopen(src_path, "w");
+ ASSERT_NOT_NULL(fp);
+ fputs("def main():\n return 'ok'\n", fp);
+ fclose(fp);
+
+ int code = -1;
+ bool signalled = false;
+ int sig = 0;
+#ifdef _WIN32
+ code = idx845_index_inprocess_check(tmp_dir);
+#else
+ fflush(NULL);
+ pid_t pid = fork();
+ if (pid == 0) {
+ alarm(20); /* pre-fix spawn chain must die here, not hang the runner */
+ _exit(idx845_index_inprocess_check(tmp_dir));
+ }
+ ASSERT_TRUE(pid > 0);
+ int status = 0;
+ (void)waitpid(pid, &status, 0);
+ if (WIFEXITED(status)) {
+ code = WEXITSTATUS(status);
+ } else if (WIFSIGNALED(status)) {
+ signalled = true;
+ sig = WTERMSIG(status);
+ }
+#endif
+
+ /* Restore env BEFORE asserting so a red run doesn't leak state. */
+ if (saved_sv_copy) {
+ cbm_setenv("CBM_INDEX_SUPERVISOR", saved_sv_copy, 1);
+ free(saved_sv_copy);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SUPERVISOR");
+ }
+ char *project = cbm_project_name_from_path(tmp_dir);
+ cleanup_project_db(cache, project);
+ free(project);
+ restore_cache_dir(saved_cache_copy);
+ free(saved_cache_copy);
+ remove(src_path);
+ cbm_rmdir(cache);
+ cbm_rmdir(tmp_dir);
+
+ if (signalled) {
+ printf(" child killed by signal %d (alarm => recursive spawn chain hang)\n", sig);
+ } else if (code != IDX845_OK) {
+ printf(" child exit code %d (41=worker spawned, 42=no result, 43=not indexed)\n",
+ code);
+ }
+ ASSERT_FALSE(signalled);
+ ASSERT_EQ(code, IDX845_OK);
+ PASS();
+}
+
/* ══════════════════════════════════════════════════════════════════
* SUITE
* ══════════════════════════════════════════════════════════════════ */
@@ -4153,6 +4287,7 @@ SUITE(mcp) {
RUN_TEST(tool_manage_adr_unified_backend_issue256);
RUN_TEST(tool_index_repository_reports_store_backed_adr);
RUN_TEST(tool_index_repository_dot_uses_absolute_project_key_and_preserves_adr);
+ RUN_TEST(index_supervisor_gate_requires_marked_host_issue845);
RUN_TEST(tool_manage_adr_not_found_rich_error);
RUN_TEST(tool_manage_adr_get_accepts_abs_path);
RUN_TEST(tool_manage_adr_get_accepts_symlink_path);
diff --git a/tests/test_worker_watchdog.sh b/tests/test_worker_watchdog.sh
new file mode 100755
index 000000000..c0e5317af
--- /dev/null
+++ b/tests/test_worker_watchdog.sh
@@ -0,0 +1,130 @@
+#!/usr/bin/env bash
+# test_worker_watchdog.sh — regression guard for the WORKER-mode parent-death
+# watchdog (#845). A supervised index worker (`cli --index-worker
+# index_repository …`) whose supervisor dies must exit on its own instead of
+# indexing on as an orphan (orphaned workers contributed to memory pressure
+# during the 2026-07-04 host panics). The MCP-server watchdog (#406/#407,
+# tests/test_parent_watchdog.sh) did not cover CLI worker mode.
+#
+# Strategy: launch the worker under a wrapper "parent" on a fixture where the
+# test-only injector (CBM_TEST_HANG_ON) busy-spins on one file, so the worker
+# is guaranteed to still be mid-index when the wrapper is killed — the guard
+# cannot pass vacuously via the worker simply finishing. CBM_INDEX_SINGLE_THREAD
+# + CBM_INDEX_MARKER_FILE (the supervisor's own recovery knobs) give a
+# deterministic "worker is AT the hang file" sync point: the worker writes the
+# rel_path it is about to process before touching it. After kill -9 of the
+# wrapper, the worker-mode watchdog must notice the changed ppid and _exit
+# within a few seconds; without it the busy-spin keeps the orphan alive
+# forever (RED). Skipped on Windows-like shells (the watchdog is POSIX-only).
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+BINARY="${ROOT}/build/c/codebase-memory-mcp"
+
+case "$(uname -s)" in
+ MINGW*|MSYS*|CYGWIN*)
+ echo "skipping worker watchdog test on Windows"
+ exit 0
+ ;;
+esac
+
+if [[ ! -x "${BINARY}" ]]; then
+ echo "missing binary: ${BINARY}" >&2
+ exit 2
+fi
+
+tmpdir="$(mktemp -d)"
+wrapper_pid=""
+cleanup() {
+ if [[ -s "${tmpdir}/child.pid" ]]; then
+ local child_pid
+ child_pid="$(cat "${tmpdir}/child.pid" 2>/dev/null || true)"
+ [[ -n "${child_pid}" ]] && kill -9 "${child_pid}" 2>/dev/null || true
+ fi
+ [[ -n "${wrapper_pid}" ]] && kill -9 "${wrapper_pid}" 2>/dev/null || true
+ rm -rf "${tmpdir}"
+}
+trap cleanup EXIT
+
+# Fixture: one good file + one the injector busy-spins on.
+mkdir -p "${tmpdir}/repo"
+printf 'def good():\n return 1\n' > "${tmpdir}/repo/good.py"
+printf 'def slow():\n return 2\n' > "${tmpdir}/repo/hang_me.py"
+
+# Wrapper "parent": launches the worker exactly as the supervisor would
+# (cli --index-worker … --response-out), records the child PID, then waits.
+cat >"${tmpdir}/wrapper.sh" <<'SH'
+#!/usr/bin/env bash
+set -euo pipefail
+"${CBM_BINARY}" cli --index-worker index_repository "${ARGS_JSON}" \
+ --response-out "${TMPDIR_PATH}/resp" \
+ >/dev/null 2>"${TMPDIR_PATH}/child.err" &
+echo "$!" >"${TMPDIR_PATH}/child.pid"
+wait
+SH
+chmod +x "${tmpdir}/wrapper.sh"
+
+CBM_BINARY="${BINARY}" TMPDIR_PATH="${tmpdir}" \
+ ARGS_JSON="{\"repo_path\":\"${tmpdir}/repo\"}" \
+ CBM_TEST_HANG_ON=hang_me CBM_INDEX_SINGLE_THREAD=1 \
+ CBM_INDEX_MARKER_FILE="${tmpdir}/marker" \
+ "${tmpdir}/wrapper.sh" &
+wrapper_pid=$!
+
+# Wait for the worker PID file to appear.
+for _ in {1..50}; do
+ [[ -s "${tmpdir}/child.pid" ]] && break
+ sleep 0.1
+done
+if [[ ! -s "${tmpdir}/child.pid" ]]; then
+ echo "worker pid file was not written" >&2
+ [[ -s "${tmpdir}/child.err" ]] && cat "${tmpdir}/child.err" >&2
+ exit 3
+fi
+child_pid="$(cat "${tmpdir}/child.pid")"
+
+# Sync point: once the marker names the hang file, the worker is provably
+# mid-index (busy-spinning in extraction) and long past watchdog installation.
+for _ in {1..100}; do
+ if [[ -s "${tmpdir}/marker" ]] && grep -q "hang_me" "${tmpdir}/marker"; then
+ break
+ fi
+ sleep 0.1
+done
+if ! grep -q "hang_me" "${tmpdir}/marker" 2>/dev/null; then
+ echo "worker never reached the hang file (marker: $(cat "${tmpdir}/marker" 2>/dev/null || echo '<empty>'))" >&2
+ [[ -s "${tmpdir}/child.err" ]] && cat "${tmpdir}/child.err" >&2
+ exit 3
+fi
+
+# Vacuity guard: the worker must still be ALIVE (busy-spinning) right now —
+# it cannot "pass" by having finished before the parent dies.
+if ! kill -0 "${child_pid}" 2>/dev/null; then
+ echo "worker exited before the supervisor was killed — guard would be vacuous" >&2
+ [[ -s "${tmpdir}/child.err" ]] && cat "${tmpdir}/child.err" >&2
+ exit 3
+fi
+
+# Kill the wrapper parent: the orphaned worker must now self-exit.
+kill -9 "${wrapper_pid}"
+wait "${wrapper_pid}" 2>/dev/null || true
+
+deadline=$((SECONDS + 15))
+while (( SECONDS < deadline )); do
+ if ! kill -0 "${child_pid}" 2>/dev/null; then
+ echo "ok: worker ${child_pid} exited after supervisor death"
+ exit 0
+ fi
+ # A zombie no longer indexes; kill -0 still reports it until it is reaped,
+ # so treat that as a successful exit (same as test_parent_watchdog.sh).
+ child_state="$(ps -p "${child_pid}" -o stat= 2>/dev/null | tr -d '[:space:]' || true)"
+ if [[ "${child_state}" == Z* ]]; then
+ echo "ok: worker ${child_pid} exited after supervisor death (zombie awaiting reap)"
+ exit 0
+ fi
+ sleep 0.2
+done
+
+echo "index worker ${child_pid} survived supervisor death (#845)" >&2
+[[ -s "${tmpdir}/child.err" ]] && cat "${tmpdir}/child.err" >&2
+exit 1