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.

Distill PR #407 (#406) and PR #414 (#413): parent-death watchdog + CBM_LOG_LEVEL

Martin Vogelde1d58ab9ed6
diff --git a/README.md b/README.md
index 01d6bd300..8b625b1c1 100644
--- a/README.md
+++ b/README.md
@@ -443,6 +443,7 @@ codebase-memory-mcp config reset auto_index # reset to default
| `CBM_CACHE_DIR` | `~/.cache/codebase-memory-mcp` | Override the database storage directory. All project indexes and config are stored here. |
| `CBM_DIAGNOSTICS` | `false` | Set to `1` or `true` to enable periodic diagnostics output to `/tmp/cbm-diagnostics-<pid>.json`. |
| `CBM_DOWNLOAD_URL` | *(GitHub releases)* | Override the download URL for updates. Used for testing or self-hosted deployments. |
+| `CBM_LOG_LEVEL` | `info` | Set the minimum log level. Accepted values (case-insensitive): `debug`, `info`, `warn`, `error`, `none` — or their numeric equivalents `0`–`4` matching the internal enum. Logs go to stderr; stdout is reserved for MCP JSON-RPC. |
| `CBM_WORKERS` | *(detected)* | Override the parallel-indexing worker count returned by `cbm_default_worker_count`. Useful inside containers where `sysconf(_SC_NPROCESSORS_ONLN)` reports host CPUs rather than the cgroup's effective quota. Range 1–256; invalid values are ignored with a warning. |
```bash
diff --git a/scripts/test.sh b/scripts/test.sh
index cfe3cc265..6b03f8618 100755
--- a/scripts/test.sh
+++ b/scripts/test.sh
@@ -69,4 +69,10 @@ if [ "${CBM_RUN_HANG_TEST:-0}" = "1" ]; then
bash "$ROOT/tests/test_cpp_index_hang.sh"
fi
+# Step 5: Parent-death watchdog regression (#406/#407). Builds the prod stdio
+# binary and verifies it self-exits when its launching parent is killed.
+echo "=== Step 5: parent-death watchdog regression (#406/#407) ==="
+$ARCH_PREFIX make -j"$NPROC" -f Makefile.cbm cbm $MAKE_ARGS
+bash "$ROOT/tests/test_parent_watchdog.sh"
+
echo "=== All tests passed ==="
diff --git a/src/foundation/log.c b/src/foundation/log.c
index b4daa229e..eda658dba 100644
--- a/src/foundation/log.c
+++ b/src/foundation/log.c
@@ -3,14 +3,54 @@
*/
#include "log.h"
#include "foundation/constants.h"
+#include <ctype.h>
#include <inttypes.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
static CBMLogLevel g_log_level = CBM_LOG_INFO;
static cbm_log_sink_fn g_log_sink = NULL;
+/* CBM_LOG_LEVEL support — distilled from #414 (closes #413, thanks @santanusinha). */
+void cbm_log_init_from_env(void) {
+ /* getenv() is safe here: this runs at startup before any thread is created,
+ * so there is no concurrent setenv() to race against. */
+ const char *raw = getenv("CBM_LOG_LEVEL");
+ if (!raw || raw[0] == '\0') {
+ return; /* unset/empty: keep the current (default) level — fail-open */
+ }
+
+ /* Textual form, case-insensitive. Index of each name == its enum value. */
+ static const char *const names[] = {"debug", "info", "warn", "error", "none"};
+ char lower[8];
+ size_t i = 0;
+ for (; raw[i] != '\0' && i < sizeof(lower) - 1; i++) {
+ lower[i] = (char)tolower((unsigned char)raw[i]);
+ }
+ lower[i] = '\0';
+ if (raw[i] == '\0') { /* fully consumed — candidate textual match */
+ for (size_t lvl = 0; lvl < sizeof(names) / sizeof(names[0]); lvl++) {
+ if (strcmp(lower, names[lvl]) == 0) {
+ cbm_log_set_level((CBMLogLevel)lvl);
+ return;
+ }
+ }
+ }
+
+ /* Numeric form: 0=debug .. 4=none, matching CBMLogLevel. */
+ char *end = NULL;
+ long n = strtol(raw, &end, CBM_DECIMAL_BASE);
+ if (end != raw && *end == '\0' && n >= CBM_LOG_DEBUG && n <= CBM_LOG_NONE) {
+ cbm_log_set_level((CBMLogLevel)n);
+ return;
+ }
+
+ /* Unrecognised value: leave the level unchanged (fail-open). */
+}
+
void cbm_log_set_sink(cbm_log_sink_fn fn) {
g_log_sink = fn;
}
diff --git a/src/foundation/log.h b/src/foundation/log.h
index e61eb013f..beb60d5be 100644
--- a/src/foundation/log.h
+++ b/src/foundation/log.h
@@ -5,7 +5,8 @@
* - All output goes to stderr (stdout is reserved for MCP JSON-RPC)
* - Structured format: "level=info msg=pass.timing pass=defs elapsed_ms=42"
* - Levels: DEBUG, INFO, WARN, ERROR
- * - Level filtering at compile time (CBM_LOG_MIN_LEVEL) and runtime
+ * - Level filtering at runtime via cbm_log_set_level() or the
+ * CBM_LOG_LEVEL env var (see cbm_log_init_from_env)
* - Thread-safe (each fprintf is atomic on POSIX for lines < PIPE_BUF)
*/
#ifndef CBM_LOG_H
@@ -21,6 +22,13 @@ typedef enum {
CBM_LOG_NONE = 4 /* disable all logging */
} CBMLogLevel;
+/* Apply the CBM_LOG_LEVEL environment variable to the runtime log level.
+ * Accepts (case-insensitive) "debug", "info", "warn", "error", "none", or
+ * the numeric equivalents 0..4 matching CBMLogLevel. Unknown, empty, or
+ * unset values leave the level unchanged (fail-open). Call once at startup,
+ * before any threads or log statements. Distilled from #414 (closes #413). */
+void cbm_log_init_from_env(void);
+
/* Set minimum log level (default: INFO). */
void cbm_log_set_level(CBMLogLevel level);
diff --git a/src/main.c b/src/main.c
index d413d9dd7..3ecc1e832 100644
--- a/src/main.c
+++ b/src/main.c
@@ -27,6 +27,7 @@ enum {
MAIN_FLAG_OFF = 5, /* strlen("--ui=") */
MAIN_PORT_OFF = 7, /* strlen("--port=") */
MAIN_MAX_PORT = 65536,
+ PARENT_WATCHDOG_STACK_SIZE = 64 * CBM_SZ_1K, /* watchdog only polls — tiny stack suffices */
};
#define MAIN_RAM_FRACTION 0.5
@@ -34,6 +35,7 @@ enum {
#include "foundation/log.h"
#include "foundation/diagnostics.h"
#include "foundation/platform.h"
+#include "foundation/compat.h"
#include "foundation/compat_thread.h"
#include "foundation/mem.h"
#include "foundation/profile.h"
@@ -59,9 +61,15 @@ static cbm_mcp_server_t *g_server = NULL;
static cbm_http_server_t *g_http_server = NULL;
static atomic_int g_shutdown = 0;
-static void signal_handler(int sig) {
- (void)sig;
- atomic_store(&g_shutdown, 1);
+/* Idempotent shutdown: cancels the active pipeline, stops background servers,
+ * and closes stdin to unblock the MCP read loop. Invoked from the signal
+ * handler and from the parent-death watchdog, hence the atomic_exchange guard
+ * so the body runs at most once. Body is async-signal-safe (only atomic stores
+ * and stop calls that themselves only set atomics). */
+static void request_shutdown(void) {
+ if (atomic_exchange(&g_shutdown, 1)) {
+ return; /* already shutting down */
+ }
/* Cancel any in-progress pipeline (async-signal-safe: only does atomic_store) */
if (g_server) {
@@ -83,6 +91,43 @@ static void signal_handler(int sig) {
(void)fclose(stdin);
}
+static void signal_handler(int sig) {
+ (void)sig;
+ request_shutdown();
+}
+
+/* ── Parent-process watchdog ────────────────────────────────────── */
+/* parent-death watchdog — distilled from #407 (fixes #406, thanks @nvt-pankajsharma).
+ *
+ * When this stdio MCP server is launched by an agent that later dies without a
+ * clean SIGTERM (e.g. the editor is force-killed), the orphaned server would
+ * otherwise linger forever blocked on stdin. POSIX has no portable "notify on
+ * parent death" primitive (PR_SET_PDEATHSIG is Linux-only), so we poll getppid:
+ * once the parent dies the process is reparented (ppid changes, typically to 1)
+ * and we shut down. Windows is unaffected (job objects handle this) — #ifndef. */
+
+#ifndef _WIN32
+static void *parent_watchdog_thread(void *arg) {
+ pid_t initial_ppid = *(pid_t *)arg;
+ const unsigned int poll_interval_us = 500000; /* 500ms */
+
+ while (!atomic_load(&g_shutdown)) {
+ cbm_usleep(poll_interval_us);
+ if (atomic_load(&g_shutdown)) {
+ break;
+ }
+ /* initial_ppid > 1 guards against an already-orphaned start (ppid==1),
+ * where a changing ppid carries no signal. */
+ if (initial_ppid > 1 && getppid() != initial_ppid) {
+ cbm_log_warn("parent.exited", "reason", "ppid_changed");
+ request_shutdown();
+ exit(0);
+ }
+ }
+ return NULL;
+}
+#endif
+
/* ── Watcher background thread ──────────────────────────────────── */
static void *watcher_thread(void *arg) {
@@ -340,11 +385,36 @@ static void setup_signal_handlers(void) {
int main(int argc, char **argv) {
cbm_profile_init(); /* reads CBM_PROFILE env var, gates all prof macros */
+ /* CBM_LOG_LEVEL support — distilled from #414 (closes #413). Apply before
+ * the first log statement so the configured level governs all output. */
+ cbm_log_init_from_env();
int subcmd = handle_subcommand(argc, argv);
if (subcmd >= 0) {
return subcmd;
}
+ /* parent-death watchdog — distilled from #407 (fixes #406). Start it early so
+ * an orphaned server exits even if it dies before reaching the MCP loop. A
+ * thread-create failure (or ppid<=1) is non-fatal: the server still runs, it
+ * just won't auto-exit on parent death — same policy as the watcher/HTTP
+ * threads below. We deliberately do NOT exit at startup when ppid<=1 (the PR's
+ * original behaviour): a legitimately-launched server can transiently show
+ * ppid==1 (early reparent races, double-fork/container launchers), and the
+ * watchdog already no-ops safely in that case via its initial_ppid>1 guard. */
+#ifndef _WIN32
+ /* main() outlives the watchdog (it joins before returning), so a stack
+ * local is a valid lifetime for the thread's argument. */
+ pid_t initial_ppid = getppid();
+ cbm_thread_t parent_watchdog_tid;
+ bool parent_watchdog_started = false;
+ if (cbm_thread_create(&parent_watchdog_tid, PARENT_WATCHDOG_STACK_SIZE,
+ parent_watchdog_thread, &initial_ppid) == 0) {
+ parent_watchdog_started = true;
+ } else {
+ cbm_log_warn("parent.watchdog.unavailable", "reason", "thread_create_failed");
+ }
+#endif
+
/* Default: MCP server on stdio */
cbm_mem_init(MAIN_RAM_FRACTION); /* 50% of RAM — safe now because mimalloc tracks ALL
* memory (C + C++ allocations) via global override.
@@ -391,6 +461,12 @@ int main(int argc, char **argv) {
if (!g_server) {
cbm_log_error("server.err", "msg", "failed to create server");
cbm_config_close(runtime_config);
+#ifndef _WIN32
+ if (parent_watchdog_started) {
+ atomic_store(&g_shutdown, 1);
+ cbm_thread_join(&parent_watchdog_tid);
+ }
+#endif
return SKIP_ONE;
}
@@ -430,10 +506,17 @@ int main(int argc, char **argv) {
/* Run MCP event loop (blocks until EOF or signal) */
int rc = cbm_mcp_server_run(g_server, stdin, stdout);
+ atomic_store(&g_shutdown, 1); /* unblock the watchdog poll loop */
/* Shutdown */
cbm_log_info("server.shutdown");
+#ifndef _WIN32
+ if (parent_watchdog_started) {
+ cbm_thread_join(&parent_watchdog_tid);
+ }
+#endif
+
if (http_started) {
cbm_http_server_stop(g_http_server);
cbm_thread_join(&http_tid);
diff --git a/tests/test_log.c b/tests/test_log.c
index 4d55a3b61..9b87efcc8 100644
--- a/tests/test_log.c
+++ b/tests/test_log.c
@@ -112,6 +112,78 @@ TEST(log_int_helper) {
PASS();
}
+/* CBM_LOG_LEVEL parsing — distilled from #414 (closes #413). */
+TEST(log_level_from_env_textual) {
+ cbm_setenv("CBM_LOG_LEVEL", "error", 1);
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_ERROR);
+
+ cbm_setenv("CBM_LOG_LEVEL", "debug", 1);
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_DEBUG);
+
+ cbm_setenv("CBM_LOG_LEVEL", "none", 1);
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_NONE);
+
+ /* Matching is case-insensitive */
+ cbm_setenv("CBM_LOG_LEVEL", "WARN", 1);
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_WARN);
+
+ cbm_setenv("CBM_LOG_LEVEL", "Info", 1);
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_INFO);
+
+ cbm_unsetenv("CBM_LOG_LEVEL");
+ cbm_log_set_level(CBM_LOG_INFO); /* restore */
+ PASS();
+}
+
+TEST(log_level_from_env_numeric) {
+ /* 0=debug 1=info 2=warn 3=error 4=none — mirrors CBMLogLevel */
+ cbm_setenv("CBM_LOG_LEVEL", "0", 1);
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_DEBUG);
+
+ cbm_setenv("CBM_LOG_LEVEL", "3", 1);
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_ERROR);
+
+ cbm_setenv("CBM_LOG_LEVEL", "4", 1);
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_NONE);
+
+ /* Out-of-range numeric is ignored — level unchanged */
+ cbm_log_set_level(CBM_LOG_INFO);
+ cbm_setenv("CBM_LOG_LEVEL", "5", 1);
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_INFO);
+
+ cbm_unsetenv("CBM_LOG_LEVEL");
+ cbm_log_set_level(CBM_LOG_INFO); /* restore */
+ PASS();
+}
+
+TEST(log_level_from_env_invalid_ignored) {
+ /* Unknown string and empty/unset both leave the level unchanged (fail-open) */
+ cbm_log_set_level(CBM_LOG_WARN);
+ cbm_setenv("CBM_LOG_LEVEL", "verbose", 1);
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_WARN);
+
+ cbm_setenv("CBM_LOG_LEVEL", "", 1);
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_WARN);
+
+ cbm_unsetenv("CBM_LOG_LEVEL");
+ cbm_log_init_from_env();
+ ASSERT_EQ(cbm_log_get_level(), CBM_LOG_WARN);
+
+ cbm_log_set_level(CBM_LOG_INFO); /* restore */
+ PASS();
+}
+
SUITE(log) {
RUN_TEST(log_level_default);
RUN_TEST(log_level_set);
@@ -119,4 +191,7 @@ SUITE(log) {
RUN_TEST(log_filtered_by_level);
RUN_TEST(log_error_output);
RUN_TEST(log_int_helper);
+ RUN_TEST(log_level_from_env_textual);
+ RUN_TEST(log_level_from_env_numeric);
+ RUN_TEST(log_level_from_env_invalid_ignored);
}
diff --git a/tests/test_parent_watchdog.sh b/tests/test_parent_watchdog.sh
new file mode 100755
index 000000000..aa1eb0070
--- /dev/null
+++ b/tests/test_parent_watchdog.sh
@@ -0,0 +1,91 @@
+#!/usr/bin/env bash
+# test_parent_watchdog.sh — regression guard for the parent-death watchdog.
+# Distilled from #407 (fixes #406): when the process that launched the stdio
+# MCP server dies, the orphaned server must exit on its own rather than linger
+# forever blocked on stdin.
+#
+# Strategy: launch the binary under a wrapper "parent" process (stdin kept open
+# via a FIFO so the server doesn't see EOF), record the child's PID, then kill
+# the wrapper. The watchdog should notice the changed ppid and exit within a
+# few seconds. 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 parent 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 "${child_pid}" 2>/dev/null || true
+ fi
+ [[ -n "${wrapper_pid}" ]] && kill "${wrapper_pid}" 2>/dev/null || true
+ rm -rf "${tmpdir}"
+}
+trap cleanup EXIT
+
+# Wrapper "parent": opens the FIFO read-write so it stays open, launches the
+# MCP server with that FIFO as stdin, records the child PID, then waits.
+cat >"${tmpdir}/wrapper.sh" <<'SH'
+#!/usr/bin/env bash
+set -euo pipefail
+exec 3<>"${FIFO}"
+"${CBM_BINARY}" <&3 >/dev/null 2>"${TMPDIR_PATH}/child.err" &
+echo "$!" >"${TMPDIR_PATH}/child.pid"
+wait
+SH
+chmod +x "${tmpdir}/wrapper.sh"
+mkfifo "${tmpdir}/stdin"
+
+CBM_BINARY="${BINARY}" FIFO="${tmpdir}/stdin" TMPDIR_PATH="${tmpdir}" \
+ "${tmpdir}/wrapper.sh" &
+wrapper_pid=$!
+
+# Wait for the child 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 "child pid file was not written" >&2
+ [[ -s "${tmpdir}/child.err" ]] && cat "${tmpdir}/child.err" >&2
+ exit 3
+fi
+
+child_pid="$(cat "${tmpdir}/child.pid")"
+if ! kill -0 "${child_pid}" 2>/dev/null; then
+ echo "child did not start" >&2
+ exit 3
+fi
+
+# Kill the wrapper parent: the orphaned child must now self-exit.
+kill -9 "${wrapper_pid}"
+wait "${wrapper_pid}" 2>/dev/null || true
+
+deadline=$((SECONDS + 6))
+while (( SECONDS < deadline )); do
+ if ! kill -0 "${child_pid}" 2>/dev/null; then
+ echo "ok: child ${child_pid} exited after parent death"
+ exit 0
+ fi
+ sleep 0.2
+done
+
+echo "codebase-memory-mcp child ${child_pid} survived parent death" >&2
+[[ -s "${tmpdir}/child.err" ]] && cat "${tmpdir}/child.err" >&2
+exit 1