Skip to content

Commit de1d58a

Browse files
author
Martin Vogel
committed
Distill PR #407 (#406) and PR #414 (#413): parent-death watchdog + CBM_LOG_LEVEL
Two reviewed external-fork contributions, re-implemented as clean maintainer code. #406 / PR #407 (thanks @nvt-pankajsharma): a POSIX parent-death watchdog so the stdio MCP server exits when its launching parent dies instead of lingering on stdin. Refactors signal_handler into an idempotent request_shutdown(); a watchdog thread polls getppid() (500ms) and shuts down + exit(0) once the initial ppid (>1) changes; Windows unaffected (#ifndef _WIN32). The fork's getppid()<=1 startup early-exit was dropped (it could wrongly kill a legitimately-launched server during reparent races / in container launchers; the initial_ppid>1 guard already no-ops safely), and thread-create failure is now non-fatal (matches the watcher/HTTP background-thread policy). Adds tests/test_parent_watchdog.sh + scripts/test.sh wiring. #413 / PR #414 (thanks @santanusinha): runtime log-level control via CBM_LOG_LEVEL (case-insensitive debug|info|warn|error|none, or numeric 0..4; unset/unknown leaves the level unchanged). getenv() before threads start (no race). Adds tests/test_log.c cases + README env-var row.
1 parent 7bce843 commit de1d58a

7 files changed

Lines changed: 308 additions & 4 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,7 @@ codebase-memory-mcp config reset auto_index # reset to default
443443
| `CBM_CACHE_DIR` | `~/.cache/codebase-memory-mcp` | Override the database storage directory. All project indexes and config are stored here. |
444444
| `CBM_DIAGNOSTICS` | `false` | Set to `1` or `true` to enable periodic diagnostics output to `/tmp/cbm-diagnostics-<pid>.json`. |
445445
| `CBM_DOWNLOAD_URL` | *(GitHub releases)* | Override the download URL for updates. Used for testing or self-hosted deployments. |
446+
| `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. |
446447
| `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. |
447448

448449
```bash

‎scripts/test.sh‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,10 @@ if [ "${CBM_RUN_HANG_TEST:-0}" = "1" ]; then
6969
bash "$ROOT/tests/test_cpp_index_hang.sh"
7070
fi
7171

72+
# Step 5: Parent-death watchdog regression (#406/#407). Builds the prod stdio
73+
# binary and verifies it self-exits when its launching parent is killed.
74+
echo "=== Step 5: parent-death watchdog regression (#406/#407) ==="
75+
$ARCH_PREFIX make -j"$NPROC" -f Makefile.cbm cbm $MAKE_ARGS
76+
bash "$ROOT/tests/test_parent_watchdog.sh"
77+
7278
echo "=== All tests passed ==="

‎src/foundation/log.c‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,54 @@
33
*/
44
#include "log.h"
55
#include "foundation/constants.h"
6+
#include <ctype.h>
67
#include <inttypes.h>
78
#include <stdarg.h>
89
#include <stdint.h>
910
#include <stdio.h>
11+
#include <stdlib.h>
12+
#include <string.h>
1013

1114
static CBMLogLevel g_log_level = CBM_LOG_INFO;
1215
static cbm_log_sink_fn g_log_sink = NULL;
1316

17+
/* CBM_LOG_LEVEL support — distilled from #414 (closes #413, thanks @santanusinha). */
18+
void cbm_log_init_from_env(void) {
19+
/* getenv() is safe here: this runs at startup before any thread is created,
20+
* so there is no concurrent setenv() to race against. */
21+
const char *raw = getenv("CBM_LOG_LEVEL");
22+
if (!raw || raw[0] == '\0') {
23+
return; /* unset/empty: keep the current (default) level — fail-open */
24+
}
25+
26+
/* Textual form, case-insensitive. Index of each name == its enum value. */
27+
static const char *const names[] = {"debug", "info", "warn", "error", "none"};
28+
char lower[8];
29+
size_t i = 0;
30+
for (; raw[i] != '\0' && i < sizeof(lower) - 1; i++) {
31+
lower[i] = (char)tolower((unsigned char)raw[i]);
32+
}
33+
lower[i] = '\0';
34+
if (raw[i] == '\0') { /* fully consumed — candidate textual match */
35+
for (size_t lvl = 0; lvl < sizeof(names) / sizeof(names[0]); lvl++) {
36+
if (strcmp(lower, names[lvl]) == 0) {
37+
cbm_log_set_level((CBMLogLevel)lvl);
38+
return;
39+
}
40+
}
41+
}
42+
43+
/* Numeric form: 0=debug .. 4=none, matching CBMLogLevel. */
44+
char *end = NULL;
45+
long n = strtol(raw, &end, CBM_DECIMAL_BASE);
46+
if (end != raw && *end == '\0' && n >= CBM_LOG_DEBUG && n <= CBM_LOG_NONE) {
47+
cbm_log_set_level((CBMLogLevel)n);
48+
return;
49+
}
50+
51+
/* Unrecognised value: leave the level unchanged (fail-open). */
52+
}
53+
1454
void cbm_log_set_sink(cbm_log_sink_fn fn) {
1555
g_log_sink = fn;
1656
}

‎src/foundation/log.h‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
* - All output goes to stderr (stdout is reserved for MCP JSON-RPC)
66
* - Structured format: "level=info msg=pass.timing pass=defs elapsed_ms=42"
77
* - Levels: DEBUG, INFO, WARN, ERROR
8-
* - Level filtering at compile time (CBM_LOG_MIN_LEVEL) and runtime
8+
* - Level filtering at runtime via cbm_log_set_level() or the
9+
* CBM_LOG_LEVEL env var (see cbm_log_init_from_env)
910
* - Thread-safe (each fprintf is atomic on POSIX for lines < PIPE_BUF)
1011
*/
1112
#ifndef CBM_LOG_H
@@ -21,6 +22,13 @@ typedef enum {
2122
CBM_LOG_NONE = 4 /* disable all logging */
2223
} CBMLogLevel;
2324

25+
/* Apply the CBM_LOG_LEVEL environment variable to the runtime log level.
26+
* Accepts (case-insensitive) "debug", "info", "warn", "error", "none", or
27+
* the numeric equivalents 0..4 matching CBMLogLevel. Unknown, empty, or
28+
* unset values leave the level unchanged (fail-open). Call once at startup,
29+
* before any threads or log statements. Distilled from #414 (closes #413). */
30+
void cbm_log_init_from_env(void);
31+
2432
/* Set minimum log level (default: INFO). */
2533
void cbm_log_set_level(CBMLogLevel level);
2634

‎src/main.c‎

Lines changed: 86 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,15 @@ enum {
2727
MAIN_FLAG_OFF = 5, /* strlen("--ui=") */
2828
MAIN_PORT_OFF = 7, /* strlen("--port=") */
2929
MAIN_MAX_PORT = 65536,
30+
PARENT_WATCHDOG_STACK_SIZE = 64 * CBM_SZ_1K, /* watchdog only polls — tiny stack suffices */
3031
};
3132
#define MAIN_RAM_FRACTION 0.5
3233

3334
#define SLEN(s) (sizeof(s) - 1)
3435
#include "foundation/log.h"
3536
#include "foundation/diagnostics.h"
3637
#include "foundation/platform.h"
38+
#include "foundation/compat.h"
3739
#include "foundation/compat_thread.h"
3840
#include "foundation/mem.h"
3941
#include "foundation/profile.h"
@@ -59,9 +61,15 @@ static cbm_mcp_server_t *g_server = NULL;
5961
static cbm_http_server_t *g_http_server = NULL;
6062
static atomic_int g_shutdown = 0;
6163

62-
static void signal_handler(int sig) {
63-
(void)sig;
64-
atomic_store(&g_shutdown, 1);
64+
/* Idempotent shutdown: cancels the active pipeline, stops background servers,
65+
* and closes stdin to unblock the MCP read loop. Invoked from the signal
66+
* handler and from the parent-death watchdog, hence the atomic_exchange guard
67+
* so the body runs at most once. Body is async-signal-safe (only atomic stores
68+
* and stop calls that themselves only set atomics). */
69+
static void request_shutdown(void) {
70+
if (atomic_exchange(&g_shutdown, 1)) {
71+
return; /* already shutting down */
72+
}
6573

6674
/* Cancel any in-progress pipeline (async-signal-safe: only does atomic_store) */
6775
if (g_server) {
@@ -83,6 +91,43 @@ static void signal_handler(int sig) {
8391
(void)fclose(stdin);
8492
}
8593

94+
static void signal_handler(int sig) {
95+
(void)sig;
96+
request_shutdown();
97+
}
98+
99+
/* ── Parent-process watchdog ────────────────────────────────────── */
100+
/* parent-death watchdog — distilled from #407 (fixes #406, thanks @nvt-pankajsharma).
101+
*
102+
* When this stdio MCP server is launched by an agent that later dies without a
103+
* clean SIGTERM (e.g. the editor is force-killed), the orphaned server would
104+
* otherwise linger forever blocked on stdin. POSIX has no portable "notify on
105+
* parent death" primitive (PR_SET_PDEATHSIG is Linux-only), so we poll getppid:
106+
* once the parent dies the process is reparented (ppid changes, typically to 1)
107+
* and we shut down. Windows is unaffected (job objects handle this) — #ifndef. */
108+
109+
#ifndef _WIN32
110+
static void *parent_watchdog_thread(void *arg) {
111+
pid_t initial_ppid = *(pid_t *)arg;
112+
const unsigned int poll_interval_us = 500000; /* 500ms */
113+
114+
while (!atomic_load(&g_shutdown)) {
115+
cbm_usleep(poll_interval_us);
116+
if (atomic_load(&g_shutdown)) {
117+
break;
118+
}
119+
/* initial_ppid > 1 guards against an already-orphaned start (ppid==1),
120+
* where a changing ppid carries no signal. */
121+
if (initial_ppid > 1 && getppid() != initial_ppid) {
122+
cbm_log_warn("parent.exited", "reason", "ppid_changed");
123+
request_shutdown();
124+
exit(0);
125+
}
126+
}
127+
return NULL;
128+
}
129+
#endif
130+
86131
/* ── Watcher background thread ──────────────────────────────────── */
87132

88133
static void *watcher_thread(void *arg) {
@@ -340,11 +385,36 @@ static void setup_signal_handlers(void) {
340385

341386
int main(int argc, char **argv) {
342387
cbm_profile_init(); /* reads CBM_PROFILE env var, gates all prof macros */
388+
/* CBM_LOG_LEVEL support — distilled from #414 (closes #413). Apply before
389+
* the first log statement so the configured level governs all output. */
390+
cbm_log_init_from_env();
343391
int subcmd = handle_subcommand(argc, argv);
344392
if (subcmd >= 0) {
345393
return subcmd;
346394
}
347395

396+
/* parent-death watchdog — distilled from #407 (fixes #406). Start it early so
397+
* an orphaned server exits even if it dies before reaching the MCP loop. A
398+
* thread-create failure (or ppid<=1) is non-fatal: the server still runs, it
399+
* just won't auto-exit on parent death — same policy as the watcher/HTTP
400+
* threads below. We deliberately do NOT exit at startup when ppid<=1 (the PR's
401+
* original behaviour): a legitimately-launched server can transiently show
402+
* ppid==1 (early reparent races, double-fork/container launchers), and the
403+
* watchdog already no-ops safely in that case via its initial_ppid>1 guard. */
404+
#ifndef _WIN32
405+
/* main() outlives the watchdog (it joins before returning), so a stack
406+
* local is a valid lifetime for the thread's argument. */
407+
pid_t initial_ppid = getppid();
408+
cbm_thread_t parent_watchdog_tid;
409+
bool parent_watchdog_started = false;
410+
if (cbm_thread_create(&parent_watchdog_tid, PARENT_WATCHDOG_STACK_SIZE,
411+
parent_watchdog_thread, &initial_ppid) == 0) {
412+
parent_watchdog_started = true;
413+
} else {
414+
cbm_log_warn("parent.watchdog.unavailable", "reason", "thread_create_failed");
415+
}
416+
#endif
417+
348418
/* Default: MCP server on stdio */
349419
cbm_mem_init(MAIN_RAM_FRACTION); /* 50% of RAM — safe now because mimalloc tracks ALL
350420
* memory (C + C++ allocations) via global override.
@@ -391,6 +461,12 @@ int main(int argc, char **argv) {
391461
if (!g_server) {
392462
cbm_log_error("server.err", "msg", "failed to create server");
393463
cbm_config_close(runtime_config);
464+
#ifndef _WIN32
465+
if (parent_watchdog_started) {
466+
atomic_store(&g_shutdown, 1);
467+
cbm_thread_join(&parent_watchdog_tid);
468+
}
469+
#endif
394470
return SKIP_ONE;
395471
}
396472

@@ -430,10 +506,17 @@ int main(int argc, char **argv) {
430506

431507
/* Run MCP event loop (blocks until EOF or signal) */
432508
int rc = cbm_mcp_server_run(g_server, stdin, stdout);
509+
atomic_store(&g_shutdown, 1); /* unblock the watchdog poll loop */
433510

434511
/* Shutdown */
435512
cbm_log_info("server.shutdown");
436513

514+
#ifndef _WIN32
515+
if (parent_watchdog_started) {
516+
cbm_thread_join(&parent_watchdog_tid);
517+
}
518+
#endif
519+
437520
if (http_started) {
438521
cbm_http_server_stop(g_http_server);
439522
cbm_thread_join(&http_tid);

‎tests/test_log.c‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,11 +112,86 @@ TEST(log_int_helper) {
112112
PASS();
113113
}
114114

115+
/* CBM_LOG_LEVEL parsing — distilled from #414 (closes #413). */
116+
TEST(log_level_from_env_textual) {
117+
cbm_setenv("CBM_LOG_LEVEL", "error", 1);
118+
cbm_log_init_from_env();
119+
ASSERT_EQ(cbm_log_get_level(), CBM_LOG_ERROR);
120+
121+
cbm_setenv("CBM_LOG_LEVEL", "debug", 1);
122+
cbm_log_init_from_env();
123+
ASSERT_EQ(cbm_log_get_level(), CBM_LOG_DEBUG);
124+
125+
cbm_setenv("CBM_LOG_LEVEL", "none", 1);
126+
cbm_log_init_from_env();
127+
ASSERT_EQ(cbm_log_get_level(), CBM_LOG_NONE);
128+
129+
/* Matching is case-insensitive */
130+
cbm_setenv("CBM_LOG_LEVEL", "WARN", 1);
131+
cbm_log_init_from_env();
132+
ASSERT_EQ(cbm_log_get_level(), CBM_LOG_WARN);
133+
134+
cbm_setenv("CBM_LOG_LEVEL", "Info", 1);
135+
cbm_log_init_from_env();
136+
ASSERT_EQ(cbm_log_get_level(), CBM_LOG_INFO);
137+
138+
cbm_unsetenv("CBM_LOG_LEVEL");
139+
cbm_log_set_level(CBM_LOG_INFO); /* restore */
140+
PASS();
141+
}
142+
143+
TEST(log_level_from_env_numeric) {
144+
/* 0=debug 1=info 2=warn 3=error 4=none — mirrors CBMLogLevel */
145+
cbm_setenv("CBM_LOG_LEVEL", "0", 1);
146+
cbm_log_init_from_env();
147+
ASSERT_EQ(cbm_log_get_level(), CBM_LOG_DEBUG);
148+
149+
cbm_setenv("CBM_LOG_LEVEL", "3", 1);
150+
cbm_log_init_from_env();
151+
ASSERT_EQ(cbm_log_get_level(), CBM_LOG_ERROR);
152+
153+
cbm_setenv("CBM_LOG_LEVEL", "4", 1);
154+
cbm_log_init_from_env();
155+
ASSERT_EQ(cbm_log_get_level(), CBM_LOG_NONE);
156+
157+
/* Out-of-range numeric is ignored — level unchanged */
158+
cbm_log_set_level(CBM_LOG_INFO);
159+
cbm_setenv("CBM_LOG_LEVEL", "5", 1);
160+
cbm_log_init_from_env();
161+
ASSERT_EQ(cbm_log_get_level(), CBM_LOG_INFO);
162+
163+
cbm_unsetenv("CBM_LOG_LEVEL");
164+
cbm_log_set_level(CBM_LOG_INFO); /* restore */
165+
PASS();
166+
}
167+
168+
TEST(log_level_from_env_invalid_ignored) {
169+
/* Unknown string and empty/unset both leave the level unchanged (fail-open) */
170+
cbm_log_set_level(CBM_LOG_WARN);
171+
cbm_setenv("CBM_LOG_LEVEL", "verbose", 1);
172+
cbm_log_init_from_env();
173+
ASSERT_EQ(cbm_log_get_level(), CBM_LOG_WARN);
174+
175+
cbm_setenv("CBM_LOG_LEVEL", "", 1);
176+
cbm_log_init_from_env();
177+
ASSERT_EQ(cbm_log_get_level(), CBM_LOG_WARN);
178+
179+
cbm_unsetenv("CBM_LOG_LEVEL");
180+
cbm_log_init_from_env();
181+
ASSERT_EQ(cbm_log_get_level(), CBM_LOG_WARN);
182+
183+
cbm_log_set_level(CBM_LOG_INFO); /* restore */
184+
PASS();
185+
}
186+
115187
SUITE(log) {
116188
RUN_TEST(log_level_default);
117189
RUN_TEST(log_level_set);
118190
RUN_TEST(log_info_output);
119191
RUN_TEST(log_filtered_by_level);
120192
RUN_TEST(log_error_output);
121193
RUN_TEST(log_int_helper);
194+
RUN_TEST(log_level_from_env_textual);
195+
RUN_TEST(log_level_from_env_numeric);
196+
RUN_TEST(log_level_from_env_invalid_ignored);
122197
}

0 commit comments

Comments
 (0)