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.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
feat(index): contain hangs too — quiet-timeout + phase=hang + partial fallback
Martin Vogele242ce1e8be8
diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.cindex 11a23df0d..67b6b28e4 100644--- a/internal/cbm/cbm.c+++ b/internal/cbm/cbm.c@@ -561,11 +561,28 @@ static void cbm_quarantine_load(void) {if (len == 0) {continue;}- /* The table borrows key pointers, so dup each path. Intentionally never- * freed: the set lives for the whole (short-lived worker) process. */+ /* Line format: "path\tphase" where phase is "crash" or "hang". A bare+ * "path" line (no tab) is tolerated and defaults to phase "crash" for+ * backward compatibility with older quarantine files. */+ char *tab = strchr(line, '\t');+ const char *phase = "crash";+ if (tab) {+ *tab = '\0';+ if (tab[1]) {+ phase = tab + 1;+ }+ }+ if (line[0] == '\0') {+ continue; /* empty path (line began with a tab) — skip */+ }+ /* The table borrows the key + value pointers, so dup both. Intentionally+ * never freed: the set lives for the whole (short-lived worker) process.+ * The value stores the phase so cbm_index_quarantine_phase() can report+ * "crash" vs "hang"; membership (cbm_index_is_quarantined) is value != NULL. */char *key = cbm_strdup(line);- if (key) {- cbm_ht_set(set, key, (void *)(intptr_t)1);+ char *pval = cbm_strdup(phase);+ if (key && pval) {+ cbm_ht_set(set, key, (void *)pval);}}(void)fclose(f);@@ -593,6 +610,16 @@ bool cbm_index_is_quarantined(const char *rel_path) {return g_quarantine_set && cbm_ht_has(g_quarantine_set, rel_path);}+const char *cbm_index_quarantine_phase(const char *rel_path) {+ /* cbm_index_is_quarantined drives the lazy once-load and returns true only+ * when the set is loaded and holds rel_path — so on true, g_quarantine_set is+ * non-NULL and the stored value is the phase string ("crash"/"hang"). */+ if (!cbm_index_is_quarantined(rel_path)) {+ return NULL;+ }+ return (const char *)cbm_ht_get(g_quarantine_set, rel_path);+}+static void cbm_test_fault_inject(const char *rel_path) {if (!rel_path || !rel_path[0]) {return;diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.hindex 22fda446a..b68f2f36a 100644--- a/internal/cbm/cbm.h+++ b/internal/cbm/cbm.h@@ -524,6 +524,12 @@ int cbm_init(void);// skip as phase="crash". Always false (cheap no-op) when the env var is unset.bool cbm_index_is_quarantined(const char *rel_path);+// Phase a quarantined file was pinned under: "crash" (a fault signal) or "hang"+// (killed for making no progress). Returns NULL when rel_path is not quarantined.+// Drives the same lazy once-load as cbm_index_is_quarantined. Used by the pipeline+// extract loops to report the skip's phase in skipped[] (falls back to "crash").+const char *cbm_index_quarantine_phase(const char *rel_path);+// Extract all data from one file. Caller must call cbm_free_result().// source must remain valid for the duration of the call.// timeout_micros: per-file parse timeout in microseconds (0 = no timeout).diff --git a/scripts/smoke-invariants.sh b/scripts/smoke-invariants.shindex 0e2f57862..0beb0344e 100755--- a/scripts/smoke-invariants.sh+++ b/scripts/smoke-invariants.sh@@ -95,19 +95,31 @@ run_bounded() {filocal of; of="$SCRATCH/rb_out.$$"if [ -n "$tobin" ]; then- "$tobin" "$secs" "$@" >"$of" 2>&1+ # -s KILL: force-kill at the deadline. The binary catches SIGTERM for a+ # graceful shutdown, so a busy-spin (e.g. a stuck external scanner) would+ # survive plain `timeout`'s TERM and hang the runner forever. timeout still+ # exits 124 on the deadline regardless of the signal used.+ "$tobin" -s KILL "$secs" "$@" >"$of" 2>&1RB_RC=$?else- # Fallback: background the command, bound the wait via a done-fifo.+ # Fallback (no timeout/gtimeout): background the command, bound the wait via+ # a done-fifo. Open the fifo read-WRITE (exec 9<>) so the open never blocks+ # waiting for a writer — a truly-hanging command never opens the write end,+ # and a blocking open would defeat `read -t`. On the deadline, force-kill+ # the whole command subtree with SIGKILL (children first so no orphan spins+ # on): SIGTERM is caught by the binary and cannot stop a busy-spin.local done; done="$SCRATCH/rb_done.$$"rm -f "$done"; mkfifo "$done" 2>/dev/null || done=""( "$@" >"$of" 2>&1; echo $? > "$SCRATCH/rb_rc.$$"; [ -n "$done" ] && echo done > "$done" ) &local bgpid=$!if [ -n "$done" ]; then+ exec 9<>"$done"local sig=""- read -t "$secs" sig < "$done"+ read -t "$secs" sig <&9+ exec 9<&-if [ -z "$sig" ]; then- kill "$bgpid" 2>/dev/null || true+ pkill -9 -P "$bgpid" 2>/dev/null || true+ kill -9 "$bgpid" 2>/dev/null || trueRB_RC=124 # mimic timeout's exit codeelseRB_RC="$(cat "$SCRATCH/rb_rc.$$" 2>/dev/null || echo 1)"@@ -769,6 +781,76 @@ print(max((int(x) for x in m), default=0))' 2>/dev/null)"fi}+# ── Invariant: a HANG on one file is SKIPPED and the rest is indexed ─────────+# The hang twin of inv_crasher_skipped_cli. A file that makes the indexer make NO+# progress (external-scanner infinite loop, modelled by CBM_TEST_HANG_ON's busy-+# spin) must be QUARANTINED: the supervisor's quiet-timeout kills the worker,+# classifies it as a HANG, pins the exact file via the marker, quarantines it as+# phase="hang", and re-spawns until a clean run indexes the GOOD files while+# reporting the hanger as a phase="hang" skip. Honest guard: with the supervisor+# OFF the injected hang must genuinely NOT complete within a bound (rc=124, the+# vacuity guard — proving the injector really hangs); with it ON + a SHORT+# CBM_INDEX_WORKER_TIMEOUT_S the run must COMPLETE (rc<128, not 124), report+# status="indexed" + the hanger as phase="hang", index the good file (nodes>0),+# and NOT skip the good file.+inv_hanger_skipped_cli() {+ local hrepo="$SCRATCH/hanger_repo"+ mkdir -p "$hrepo"+ printf 'def good():\n return 1\n' > "$hrepo/good.py"+ printf 'def slow():\n return 2\n' > "$hrepo/hang_me.py"+ git -C "$hrepo" init -q 2>/dev/null || true+ local hn; hn="$(native_path "$hrepo")"++ # Honesty baseline: supervisor OFF → the injected hang must NOT complete within+ # the bound. The bounded runner fires (rc=124), proving the injector hangs.+ export CBM_TEST_HANG_ON=hang_me+ export CBM_INDEX_SUPERVISOR=0+ cli_call 12 index_repository "{\"repo_path\":\"$hn\"}"+ local base_rc="$CLI_RC"+ unset CBM_INDEX_SUPERVISOR++ # Supervisor ON (default) + a SHORT no-progress timeout → the hang must be+ # detected fast, contained, and skipped-and-continued. Recovery spends two+ # ~5s timeouts (first parallel run, then the single-threaded recovery run) so+ # this invariant legitimately takes ~10-15s; it MUST still complete.+ export CBM_INDEX_WORKER_TIMEOUT_S=5+ cli_call 90 index_repository "{\"repo_path\":\"$hn\"}"+ local sup_rc="$CLI_RC"+ local sup_out="$CLI_OUT"+ unset CBM_INDEX_WORKER_TIMEOUT_S+ unset CBM_TEST_HANG_ON++ # Strip JSON escaping so the assertions are robust to the text-result wrapping.+ local flat+ flat="$(printf '%s' "$sup_out" | tr -d '\\' | tr -d '"')"+ local nodes+ nodes="$(printf '%s' "$sup_out" | "$PY" -c '+import sys,re+t=sys.stdin.read().replace("\\","").replace("\"","")+m=re.findall(r"nodes\s*[:=]\s*(\d+)", t)+print(max((int(x) for x in m), default=0))' 2>/dev/null)"++ if [ "$base_rc" -ne 124 ]; then+ fail "hanger-skipped-cli" "baseline did not hang (rc=$base_rc, want 124) — injector inactive, guard would be vacuous"+ elif [ "$sup_rc" -eq 124 ]; then+ fail "hanger-skipped-cli" "supervised run hung (rc=124) — hang not contained"+ elif [ "$sup_rc" -gt 128 ]; then+ fail "hanger-skipped-cli" "supervised run died via signal $((sup_rc-128))"+ elif ! printf '%s' "$flat" | grep -q 'status:indexed'; then+ fail "hanger-skipped-cli" "status not indexed after skip-and-continue: $(printf '%s' "$sup_out" | tr '\n' ' ' | cut -c1-300)"+ elif ! printf '%s' "$flat" | grep -q 'phase:hang'; then+ fail "hanger-skipped-cli" "hanger not reported as phase=hang: $(printf '%s' "$sup_out" | tr '\n' ' ' | cut -c1-300)"+ elif ! printf '%s' "$flat" | grep -q 'hang_me.py'; then+ fail "hanger-skipped-cli" "hang_me.py not listed as skipped: $(printf '%s' "$sup_out" | tr '\n' ' ' | cut -c1-300)"+ elif printf '%s' "$flat" | grep -q 'good.py'; then+ fail "hanger-skipped-cli" "good.py was skipped (should have been indexed): $(printf '%s' "$sup_out" | tr '\n' ' ' | cut -c1-300)"+ elif [ "${nodes:-0}" -le 0 ] 2>/dev/null; then+ fail "hanger-skipped-cli" "good file not indexed (nodes=${nodes:-0}): $(printf '%s' "$sup_out" | tr '\n' ' ' | cut -c1-300)"+ else+ pass "hanger-skipped-cli (baseline rc=$base_rc hung; supervised rc=$sup_rc: status=indexed, hang_me.py phase=hang, good.py indexed nodes=$nodes)"+ fi+}+# ── Invariant 8: clean exit on stdin EOF within a bounded wait (no hang) ────# Close the server's stdin (fd3). The server must reach EOF, break its loop, and# exit cleanly. We bound the wait WITHOUT sleep: closing stdin makes the server@@ -904,6 +986,7 @@ inv_nonexistent_repo_cliinv_empty_repo_cliinv_garbage_files_cliinv_crasher_skipped_cli+inv_hanger_skipped_cli# MCP server-lifecycle invariants (one shared server instance).inv_mcp_initializediff --git a/src/mcp/index_supervisor.c b/src/mcp/index_supervisor.cindex d8448f27f..56c218f0d 100644--- a/src/mcp/index_supervisor.c+++ b/src/mcp/index_supervisor.c@@ -55,10 +55,14 @@ bool cbm_index_supervisor_should_wrap(void) {}/* Quiet-timeout (ms) for a supervised worker: killed + reported as a hang if it- * emits no progress within the window. 0 => disabled. Full hang coverage (a- * generous default + attribution) is wired in a later stage; for now honour the- * env override and default to disabled so crash containment ships independently. */+ * emits no NEW log line within the window. This is a NO-PROGRESS timeout — every+ * completed log line the worker tails (per-batch parallel.extract.progress every+ * 10 files, plus each pass boundary) resets it — NOT a total-time cap, so a large+ * repo that keeps making progress is never falsely killed. Default: 15 min (a+ * genuinely stuck file emits nothing, so this fires only on a real hang). The+ * CBM_INDEX_WORKER_TIMEOUT_S override (seconds → ms) tightens it for tests. */static int worker_quiet_timeout_ms(void) {+ enum { DEFAULT_QUIET_TIMEOUT_MS = 900000 }; /* 15 min with no progress */const char *e = getenv("CBM_INDEX_WORKER_TIMEOUT_S");if (e && e[0]) {long s = atol(e);@@ -66,7 +70,7 @@ static int worker_quiet_timeout_ms(void) {return (int)(s * 1000);}}- return 0;+ return DEFAULT_QUIET_TIMEOUT_MS;}/* Read an entire file into a heap string (NUL-terminated). NULL on error. */@@ -129,6 +133,14 @@ int cbm_index_spawn_worker(const char *args_json, bool single_thread, const charworker_tmp_path(log_path, sizeof(log_path), pid, ".log");(void)remove(resp_path); /* clear any stale file */+ /* No --progress: the worker's DEFAULT structured logging already provides the+ * no-progress heartbeat (INFO parallel.extract.progress every 10 files + each+ * pass boundary — all newline-terminated → tailed → reset the quiet-timeout).+ * --progress would be strictly worse here: it installs a REPLACE-mode sink that+ * suppresses those default lines and emits per-file extraction as a carriage-+ * return in-place update (no trailing '\n'), which cbm_tail_log does not count+ * as progress. (It would not corrupt the response either — that goes to the+ * separate --response-out file, not stdout.) */const char *argv[8];int n = 0;argv[n++] = self;diff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex b15c60b5e..8b98bf26f 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -3386,13 +3386,15 @@ static char *supervisor_read_marker(const char *path) {return len > 0 ? cbm_strdup(buf) : NULL;}-/* Append one repo-relative path (newline-terminated) to the quarantine list. */-static bool supervisor_append_quarantine(const char *path, const char *rel) {+/* Append one quarantine entry "rel\tphase\n" (phase = "crash"|"hang") to the+ * quarantine list. The worker's loader parses this back and reports the skip's+ * phase in skipped[]; a bare "rel" line is still tolerated there (defaults crash). */+static bool supervisor_append_quarantine(const char *path, const char *rel, const char *phase) {FILE *f = cbm_fopen(path, "ab");if (!f) {return false;}- (void)fprintf(f, "%s\n", rel);+ (void)fprintf(f, "%s\t%s\n", rel, phase);(void)fclose(f);return true;}@@ -3401,10 +3403,11 @@ static bool supervisor_append_quarantine(const char *path, const char *rel) {* (Stage 3c). Returns the response string (caller frees):* - the worker's own response on a clean first run (the common path);* - after a crash/hang, the response from a clean single-threaded RECOVERY run- * that quarantines the crashing file(s) — status="indexed" with the crashers- * listed in skipped[] as phase="crash", and the good files indexed;- * - a contained-failure response if recovery cannot converge (cap exhausted or- * an unattributable crash).+ * that quarantines the culprit file(s) — status="indexed" with them listed in+ * skipped[] as phase="crash"/"hang", and the good files indexed;+ * - a best-effort PARTIAL index (one final quarantine-only run) if the recovery+ * loop cannot converge but at least one file was quarantined;+ * - a contained-failure response only if even that cannot produce a clean run.* Returns NULL only when the worker could not be spawned at all, so the caller* degrades to the in-process path. */static char *index_run_supervised(cbm_mcp_server_t *srv, const char *args) {@@ -3462,6 +3465,7 @@ static char *index_run_supervised(cbm_mcp_server_t *srv, const char *args) {}char *resp = NULL;+ int quarantined = 0; /* files pinned + added to the quarantine list so far */for (int i = 0; i < cap; i++) {cbm_index_worker_result_t wr2;int rc2 = cbm_index_spawn_worker(args, true, marker_path, quarantine_path, &wr2);@@ -3474,27 +3478,32 @@ static char *index_run_supervised(cbm_mcp_server_t *srv, const char *args) {resp = wr2.response; /* transfer ownership to caller */wr2.response = NULL;cbm_index_worker_result_free(&wr2);- break; /* good files indexed; quarantined files reported as phase=crash */+ break; /* good files indexed; quarantined files reported as crash/hang */}if (wr2.outcome == CBM_PROC_CRASH || wr2.outcome == CBM_PROC_HANG) {last_outcome = wr2.outcome;cbm_index_worker_result_free(&wr2);- /* Attribute the crash to the file the marker pinned and quarantine it.- * If the marker is empty/unreadable we cannot attribute the crash to a- * single file → stop and report a contained failure. */+ /* crash vs hang: the phase this file is quarantined under and reported+ * as in skipped[]. A fault signal → "crash"; a no-progress kill →+ * "hang". */+ const char *phase = (last_outcome == CBM_PROC_HANG) ? "hang" : "crash";+ /* Attribute the failure to the file the marker pinned and quarantine it.+ * If the marker is empty/unreadable we cannot attribute it to a single+ * file → stop and report a contained failure. */char *crasher = supervisor_read_marker(marker_path);if (!crasher) {cbm_log_warn("index.supervisor.unattributable", "action", "give_up");break;}- if (!supervisor_append_quarantine(quarantine_path, crasher)) {+ if (!supervisor_append_quarantine(quarantine_path, crasher, phase)) {cbm_log_warn("index.supervisor.quarantine_write_fail", "path", crasher);free(crasher);break;}+ quarantined++;char attempt_buf[MCP_FIELD_SIZE];snprintf(attempt_buf, sizeof(attempt_buf), "%d", i + 1);- cbm_log_warn("index.file_quarantined", "path", crasher, "phase", "crash", "attempt",+ cbm_log_warn("index.file_quarantined", "path", crasher, "outcome", phase, "attempt",attempt_buf);free(crasher);(void)remove(marker_path); /* fresh marker for the next re-run */@@ -3507,7 +3516,29 @@ static char *index_run_supervised(cbm_mcp_server_t *srv, const char *args) {break;}- (void)remove(marker_path);+ (void)remove(marker_path); /* marker no longer needed */++ /* Terminal best-effort-partial: the loop exited WITHOUT a clean run (cap+ * exhausted, or an unattributable failure) but at least one file was already+ * quarantined. Try ONE final single-threaded spawn with the accumulated+ * quarantine and NO marker — every known-bad file short-circuits, so a clean+ * run yields a PARTIAL index (all good files indexed, all known crashers/hangs+ * reported as skips) rather than a hard failure. Bounded by the same quiet-+ * timeout, so it cannot itself hang. Rare given monotonic progress. */+ if (!resp && quarantined > 0) {+ cbm_index_worker_result_t wrp;+ int rcp = cbm_index_spawn_worker(args, true, NULL, quarantine_path, &wrp);+ if (rcp == 0 && wrp.outcome == CBM_PROC_CLEAN && wrp.response) {+ resp = wrp.response; /* transfer ownership to caller */+ wrp.response = NULL;+ char qn[MCP_FIELD_SIZE];+ snprintf(qn, sizeof(qn), "%d", quarantined);+ cbm_log_error("index.supervisor.partial", "quarantined", qn, "outcome",+ cbm_proc_outcome_str(last_outcome));+ }+ cbm_index_worker_result_free(&wrp);+ }+(void)remove(quarantine_path);supervisor_invalidate_store(srv);diff --git a/src/pipeline/pass_definitions.c b/src/pipeline/pass_definitions.cindex 2339ebbeb..acda8b226 100644--- a/src/pipeline/pass_definitions.c+++ b/src/pipeline/pass_definitions.c@@ -523,7 +523,13 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t* re-crashing and without duplicating the skip. No-op unless* CBM_INDEX_QUARANTINE_FILE is set. */if (cbm_index_is_quarantined(rel)) {- cbm_pipeline_add_file_error(ctx->pipeline, rel, "quarantined after crash", "crash");+ const char *phase = cbm_index_quarantine_phase(rel);+ if (!phase) {+ phase = "crash";+ }+ const char *reason =+ (strcmp(phase, "hang") == 0) ? "quarantined after hang" : "quarantined after crash";+ cbm_pipeline_add_file_error(ctx->pipeline, rel, reason, phase);errors++;continue;}diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.cindex 30ac13119..0e739c789 100644--- a/src/pipeline/pass_parallel.c+++ b/src/pipeline/pass_parallel.c@@ -675,7 +675,13 @@ static void extract_worker(int worker_id, void *ctx_ptr) {* single-threaded recovery run instead takes the sequential path* (pass_definitions.c), and cbm_extract_file's hard guard backstops both. */if (cbm_index_is_quarantined(fi->rel_path)) {- pp_err_add(errs, fi->rel_path, "quarantined after crash", "crash");+ const char *phase = cbm_index_quarantine_phase(fi->rel_path);+ if (!phase) {+ phase = "crash";+ }+ const char *reason =+ (strcmp(phase, "hang") == 0) ? "quarantined after hang" : "quarantined after crash";+ pp_err_add(errs, fi->rel_path, reason, phase);ws->errors++;continue;}