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.

feat(index): skip the crashing file and index the rest (supervisor recovery)

Martin Vogelfb334f789fd4
diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.c
index aefcca4d9..11a23df0d 100644
--- a/internal/cbm/cbm.c
+++ b/internal/cbm/cbm.c
@@ -14,6 +14,8 @@
#include "lsp/rust_lsp.h"
#include "preprocessor.h"
#include "foundation/compat.h"
+#include "foundation/compat_fs.h" // cbm_fopen — crash-supervisor per-file marker write
+#include "foundation/hash_table.h" // CBMHashTable — crash-supervisor quarantine set
#include "tree_sitter/api.h" // TSParser, TSNode, TSTree, TSInput, TSLanguage, TSPoint, TSParseOptions, TSParseState
#include "foundation/constants.h"
#include "mimalloc.h" // mi_malloc/mi_calloc/mi_realloc/mi_free/mi_usable_size — bind 3rd-party allocators (#424)
@@ -500,6 +502,97 @@ static int count_params_from_signature(const char *sig) {
* or spins forever (an external-scanner infinite loop the quiet-timeout kills).
* This gives an honest guard — green iff the supervisor actually contains a real
* fault — instead of a fixture that may stop faulting once a root cause is fixed. */
+/* Crash-supervisor per-file marker (Stage 3c skip-and-continue). In the
+ * supervisor's single-threaded recovery re-run, cbm_extract_file records the
+ * file it is ABOUT to process here (CBM_INDEX_MARKER_FILE) before touching it,
+ * so that if this file hard-crashes the worker the parent can read the marker
+ * back and learn the EXACT crasher to quarantine. Only meaningful single-
+ * threaded (parallel would race the marker); the env var is set solely by the
+ * supervisor during recovery, so it is a no-op on every normal run. */
+static void cbm_index_write_marker(const char *rel_path) {
+ const char *mf = getenv("CBM_INDEX_MARKER_FILE");
+ if (!mf || !mf[0] || !rel_path || !rel_path[0]) {
+ return;
+ }
+ FILE *f = cbm_fopen(mf, "wb");
+ if (f) {
+ (void)fputs(rel_path, f);
+ (void)fclose(f);
+ }
+}
+
+/* ── Crash-quarantine set (Stage 3c skip-and-continue) ──────────────────────
+ * After a crash the supervisor re-runs the worker single-threaded, passing
+ * CBM_INDEX_QUARANTINE_FILE — a newline-delimited list of repo-relative paths
+ * that already crashed the indexer and MUST NOT be extracted again. Owned here,
+ * next to the other env-driven extract hooks (marker + fault injector), so the
+ * single hard guard lives at the one choke point every pass funnels through
+ * (cbm_extract_file): whether a pass re-extracts from disk on a cache miss
+ * (sequential pass_calls/usages/semantic) or extracts fresh, a quarantined file
+ * short-circuits to an empty result and never reaches the parser/crash. The
+ * pipeline extract loops separately REPORT the skip as phase="crash" via
+ * cbm_index_is_quarantined() so the crasher surfaces in the response skipped[].
+ * Loaded once, lazily; read-only after load (safe for the parallel workers,
+ * though recovery runs single-threaded). Unset env ⇒ empty set ⇒ cheap no-op. */
+static CBMHashTable *g_quarantine_set = NULL;
+enum { CBM_QSET_UNINIT = 0, CBM_QSET_INITING = 1, CBM_QSET_INITED = 2 };
+static atomic_int g_quarantine_state = CBM_QSET_UNINIT;
+
+static void cbm_quarantine_load(void) {
+ const char *qf = getenv("CBM_INDEX_QUARANTINE_FILE");
+ if (!qf || !qf[0]) {
+ return; /* normal path: empty set */
+ }
+ FILE *f = cbm_fopen(qf, "rb");
+ if (!f) {
+ return;
+ }
+ CBMHashTable *set = cbm_ht_create(16);
+ if (!set) {
+ (void)fclose(f);
+ return;
+ }
+ char line[2048];
+ while (fgets(line, sizeof(line), f)) {
+ size_t len = strlen(line);
+ while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) {
+ line[--len] = '\0';
+ }
+ 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. */
+ char *key = cbm_strdup(line);
+ if (key) {
+ cbm_ht_set(set, key, (void *)(intptr_t)1);
+ }
+ }
+ (void)fclose(f);
+ g_quarantine_set = set;
+}
+
+bool cbm_index_is_quarantined(const char *rel_path) {
+ if (!rel_path || !rel_path[0]) {
+ return false;
+ }
+ int state = atomic_load(&g_quarantine_state);
+ if (state != CBM_QSET_INITED) {
+ /* First caller wins the CAS and loads; racers spin until INITED.
+ * Same once-init pattern as cbm_ui_log_init (http_server.c). */
+ state = CBM_QSET_UNINIT;
+ if (atomic_compare_exchange_strong(&g_quarantine_state, &state, CBM_QSET_INITING)) {
+ cbm_quarantine_load();
+ atomic_store(&g_quarantine_state, CBM_QSET_INITED);
+ } else {
+ while (atomic_load(&g_quarantine_state) != CBM_QSET_INITED) {
+ cbm_usleep(1000); /* 1ms */
+ }
+ }
+ }
+ return g_quarantine_set && cbm_ht_has(g_quarantine_set, rel_path);
+}
+
static void cbm_test_fault_inject(const char *rel_path) {
if (!rel_path || !rel_path[0]) {
return;
@@ -519,8 +612,6 @@ static void cbm_test_fault_inject(const char *rel_path) {
CBMFileResult *cbm_extract_file(const char *source, int source_len, CBMLanguage language,
const char *project, const char *rel_path, int64_t timeout_micros,
const char **extra_defines, const char **include_paths) {
- cbm_test_fault_inject(rel_path);
-
// Allocate result on heap (arena inside for all string data)
enum { SINGLE = 1 };
CBMFileResult *result = (CBMFileResult *)calloc(SINGLE, sizeof(CBMFileResult));
@@ -531,6 +622,20 @@ CBMFileResult *cbm_extract_file(const char *source, int source_len, CBMLanguage
cbm_arena_init(&result->arena);
CBMArena *a = &result->arena;
+ /* Crash-quarantine hard guard (Stage 3c): a file the supervisor pinned as a
+ * crasher must NEVER be parsed again. Return a clean empty result BEFORE the
+ * marker write and fault injector so no pass (including sequential re-extract
+ * passes that miss the result cache) can crash on it. The pipeline extract
+ * loops separately record it as a phase="crash" skip. Checked before the
+ * marker so quarantined files never overwrite it — the marker keeps pointing
+ * at the real (non-quarantined) file being processed when a crash hits. */
+ if (cbm_index_is_quarantined(rel_path)) {
+ return result;
+ }
+
+ cbm_index_write_marker(rel_path);
+ cbm_test_fault_inject(rel_path);
+
// Get language spec
const CBMLangSpec *spec = cbm_lang_spec(language);
if (!spec) {
diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h
index b40305af9..22fda446a 100644
--- a/internal/cbm/cbm.h
+++ b/internal/cbm/cbm.h
@@ -516,6 +516,14 @@ void cbm_alloc_init(void);
// Initialize the library. Call once at startup. Returns 0 on success.
int cbm_init(void);
+// True when rel_path is in the crash-quarantine set — the newline-delimited list
+// of files (CBM_INDEX_QUARANTINE_FILE) the crash supervisor pinned as crashers
+// during its single-threaded recovery re-run. Loaded once, lazily; read-only
+// after load. cbm_extract_file short-circuits such files to an empty result so no
+// pass can crash on them; the pipeline extract loops call this to also REPORT the
+// skip as phase="crash". Always false (cheap no-op) when the env var is unset.
+bool cbm_index_is_quarantined(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.sh
index 8e14c5b66..0e2f57862 100755
--- a/scripts/smoke-invariants.sh
+++ b/scripts/smoke-invariants.sh
@@ -707,14 +707,17 @@ inv_garbage_files_cli() {
fi
}
-# ── Invariant: a hard crash on one file is CONTAINED by the supervisor ──────
-# A file that hard-crashes the native indexer (SIGSEGV/abort/stack-overflow) must
-# not take down the whole process. Uses the test-only fault injector
+# ── Invariant: a hard crash on one file is SKIPPED and the rest is indexed ──
+# Stage 3c skip-and-continue: a file that hard-crashes the native indexer
+# (SIGSEGV/abort/stack-overflow) must be QUARANTINED — the supervisor re-runs the
+# worker single-threaded, pins the exact crasher via a per-file marker, adds it to
+# a quarantine list, and re-spawns until a clean run indexes the GOOD files while
+# reporting the crasher as a phase="crash" skip. Uses the test-only fault injector
# (CBM_TEST_CRASH_ON) so the guard is honest: with the supervisor OFF the crash
-# must genuinely escape as a signal (rc>=128), and with it ON (default) the crash
-# must be contained (rc<128) and reported (outcome=crash). If the baseline does
-# not crash, the injector is inactive and the guard would be vacuous → fail.
-inv_crasher_contained_cli() {
+# must genuinely escape as a signal (rc>=128, vacuity guard); with it ON (default)
+# the run must be contained (rc<128), report status="indexed" + the crasher as
+# phase="crash", index the good file (nodes>0), and NOT skip the good file.
+inv_crasher_skipped_cli() {
local crepo="$SCRATCH/crasher_repo"
mkdir -p "$crepo"
printf 'def good():\n return 1\n' > "$crepo/good.py"
@@ -729,22 +732,40 @@ inv_crasher_contained_cli() {
local base_rc="$CLI_RC"
unset CBM_INDEX_SUPERVISOR
- # Supervisor ON (default) → the crash must be contained and reported.
- cli_call 60 index_repository "{\"repo_path\":\"$cn\"}"
+ # Supervisor ON (default) → the crash must be contained AND skipped-and-continued.
+ cli_call 90 index_repository "{\"repo_path\":\"$cn\"}"
local sup_rc="$CLI_RC"
local sup_out="$CLI_OUT"
unset CBM_TEST_CRASH_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" -le 128 ]; then
- fail "crasher-contained-cli" "baseline did not crash (rc=$base_rc) — injector inactive, guard would be vacuous"
+ fail "crasher-skipped-cli" "baseline did not crash (rc=$base_rc) — injector inactive, guard would be vacuous"
elif [ "$sup_rc" -eq 124 ]; then
- fail "crasher-contained-cli" "supervised run hung (rc=124)"
+ fail "crasher-skipped-cli" "supervised run hung (rc=124)"
elif [ "$sup_rc" -gt 128 ]; then
- fail "crasher-contained-cli" "crash escaped the supervisor (signal $((sup_rc-128)))"
- elif ! printf '%s' "$sup_out" | grep -q '"outcome":"crash"'; then
- fail "crasher-contained-cli" "crash not reported (no outcome=crash): $sup_out"
+ fail "crasher-skipped-cli" "crash escaped the supervisor (signal $((sup_rc-128)))"
+ elif ! printf '%s' "$flat" | grep -q 'status:indexed'; then
+ fail "crasher-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:crash'; then
+ fail "crasher-skipped-cli" "crasher not reported as phase=crash: $(printf '%s' "$sup_out" | tr '\n' ' ' | cut -c1-300)"
+ elif ! printf '%s' "$flat" | grep -q 'crash_me.py'; then
+ fail "crasher-skipped-cli" "crash_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 "crasher-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 "crasher-skipped-cli" "good file not indexed (nodes=${nodes:-0}): $(printf '%s' "$sup_out" | tr '\n' ' ' | cut -c1-300)"
else
- pass "crasher-contained-cli (baseline rc=$base_rc escaped; supervised rc=$sup_rc contained + reported)"
+ pass "crasher-skipped-cli (baseline rc=$base_rc escaped; supervised rc=$sup_rc: status=indexed, crash_me.py phase=crash, good.py indexed nodes=$nodes)"
fi
}
@@ -882,7 +903,7 @@ inv_index_status_cli
inv_nonexistent_repo_cli
inv_empty_repo_cli
inv_garbage_files_cli
-inv_crasher_contained_cli
+inv_crasher_skipped_cli
# MCP server-lifecycle invariants (one shared server instance).
inv_mcp_initialize
diff --git a/src/mcp/index_supervisor.c b/src/mcp/index_supervisor.c
index 48b24e1ce..d8448f27f 100644
--- a/src/mcp/index_supervisor.c
+++ b/src/mcp/index_supervisor.c
@@ -3,6 +3,7 @@
*/
#include "index_supervisor.h"
+#include "foundation/compat.h" /* cbm_setenv, cbm_unsetenv */
#include "foundation/compat_fs.h" /* cbm_mkdir_p, cbm_fopen */
#include "foundation/log.h"
#include "foundation/platform.h" /* cbm_resolve_cache_dir */
@@ -108,8 +109,8 @@ 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, const char *exclude_file,
- cbm_index_worker_result_t *result) {
+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) {
result->outcome = CBM_PROC_SPAWN_FAILED;
result->exit_code = -1;
result->term_signal = 0;
@@ -128,7 +129,7 @@ int cbm_index_spawn_worker(const char *args_json, const char *exclude_file,
worker_tmp_path(log_path, sizeof(log_path), pid, ".log");
(void)remove(resp_path); /* clear any stale file */
- const char *argv[12];
+ const char *argv[8];
int n = 0;
argv[n++] = self;
argv[n++] = "cli";
@@ -137,12 +138,22 @@ int cbm_index_spawn_worker(const char *args_json, const char *exclude_file,
argv[n++] = args_json;
argv[n++] = "--response-out";
argv[n++] = resp_path;
- if (exclude_file && exclude_file[0]) {
- argv[n++] = "--exclude-file";
- argv[n++] = exclude_file;
- }
argv[n] = NULL;
+ /* Recovery-run probe knobs → inherited env for the child. Spawns are
+ * sequential, so mutating the parent's environment around a single spawn is
+ * safe. Set only the requested knobs; unset them all again after reaping so
+ * a later attempt (or the caller) starts from a clean environment. */
+ if (single_thread) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ }
+ if (marker_file && marker_file[0]) {
+ cbm_setenv("CBM_INDEX_MARKER_FILE", marker_file, 1);
+ }
+ if (quarantine_file && quarantine_file[0]) {
+ cbm_setenv("CBM_INDEX_QUARANTINE_FILE", quarantine_file, 1);
+ }
+
cbm_proc_opts_t opts = {0};
opts.bin = self;
opts.argv = argv;
@@ -151,7 +162,19 @@ int cbm_index_spawn_worker(const char *args_json, const char *exclude_file,
opts.delete_log_on_exit = true;
cbm_proc_result_t r;
- if (cbm_subprocess_run(&opts, &r) != 0) {
+ int run_rc = cbm_subprocess_run(&opts, &r);
+
+ if (single_thread) {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ if (marker_file && marker_file[0]) {
+ cbm_unsetenv("CBM_INDEX_MARKER_FILE");
+ }
+ if (quarantine_file && quarantine_file[0]) {
+ cbm_unsetenv("CBM_INDEX_QUARANTINE_FILE");
+ }
+
+ if (run_rc != 0) {
(void)remove(resp_path);
cbm_log_warn("index.supervisor.spawn_failed", "action", "degrade_in_process");
return -1;
diff --git a/src/mcp/index_supervisor.h b/src/mcp/index_supervisor.h
index 3c05bc914..d585b48e8 100644
--- a/src/mcp/index_supervisor.h
+++ b/src/mcp/index_supervisor.h
@@ -44,14 +44,25 @@ typedef struct {
char *response; /* worker's result string on CLEAN exit (caller frees); else NULL */
} cbm_index_worker_result_t;
-/* Spawn `<self> cli --index-worker index_repository <args_json> --response-out <tmp>
- * [--exclude-file <exclude_file>]`, supervise it (quiet-timeout for hangs), reap,
- * and classify. On a clean exit, result->response holds the worker's response
- * string (read from the temp file). Returns 0 if a worker was spawned and reaped
- * (result filled), or -1 if the child could not be spawned (caller degrades to
- * in-process). exclude_file may be NULL. */
-int cbm_index_spawn_worker(const char *args_json, const char *exclude_file,
- cbm_index_worker_result_t *result);
+/* Spawn `<self> cli --index-worker index_repository <args_json> --response-out <tmp>`,
+ * supervise it (quiet-timeout for hangs), reap, and classify. On a clean exit,
+ * result->response holds the worker's response string (read from the temp file).
+ * Returns 0 if a worker was spawned and reaped (result filled), or -1 if the
+ * child could not be spawned (caller degrades to in-process).
+ *
+ * Probe knobs for the skip-and-continue recovery re-run (Stage 3c) are passed to
+ * the child as inherited env vars around the spawn (set before, unset after —
+ * safe because spawns are sequential):
+ * - single_thread → CBM_INDEX_SINGLE_THREAD=1: the pipeline uses exactly one
+ * worker, so a per-file marker pins the EXACT crasher.
+ * - marker_file → CBM_INDEX_MARKER_FILE: the worker writes the rel_path of
+ * the file it is about to process here before touching it.
+ * - quarantine_file → CBM_INDEX_QUARANTINE_FILE: newline-delimited rel_paths to
+ * skip and report as phase="crash".
+ * Any of the three may be false/NULL to leave that knob unset (the normal first
+ * attempt passes single_thread=false, marker_file=NULL, quarantine_file=NULL). */
+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);
void cbm_index_worker_result_free(cbm_index_worker_result_t *result);
diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c
index 1b14dd0db..b15c60b5e 100644
--- a/src/mcp/mcp.c
+++ b/src/mcp/mcp.c
@@ -3341,47 +3341,180 @@ static char *build_worker_failure_response(const char *args, cbm_proc_outcome_t
return result;
}
-/* Run index_repository in a supervised worker subprocess. Returns the response
- * string (caller frees) — the worker's own response on a clean exit, or a
- * contained-failure response on a crash/hang. Returns NULL only when the worker
- * could not be spawned, so the caller degrades to the in-process path. */
-static char *index_run_supervised(cbm_mcp_server_t *srv, const char *args) {
- /* Drop the cached store: the worker (a fresh process) deletes + recreates the
- * .db, and the parent must reopen fresh afterwards. */
+/* Drop the cached store so the next query reopens whatever the worker wrote (each
+ * worker is a fresh process that deletes + recreates the .db). */
+static void supervisor_invalidate_store(cbm_mcp_server_t *srv) {
if (srv->owns_store && srv->store) {
cbm_store_close(srv->store);
srv->store = NULL;
}
free(srv->current_project);
srv->current_project = NULL;
+}
- cbm_index_worker_result_t wr;
- int rc = cbm_index_spawn_worker(args, NULL, &wr);
+/* Resolve a per-supervisor-run temp path <cache_dir>/logs/.supervisor-<pid><suffix>
+ * (falls back to the CWD if the cache dir is unresolvable). Used for the crash-
+ * attribution marker and the quarantine list during the recovery re-run. */
+static void supervisor_tmp_path(char *out, size_t out_sz, const char *suffix) {
+ const char *cdir = cbm_resolve_cache_dir();
+ if (cdir && cdir[0]) {
+ char logdir[CBM_SZ_1K];
+ snprintf(logdir, sizeof(logdir), "%s/logs", cdir);
+ cbm_mkdir_p(logdir, 0755);
+ snprintf(out, out_sz, "%s/.supervisor-%d%s", logdir, (int)getpid(), suffix);
+ } else {
+ snprintf(out, out_sz, ".supervisor-%d%s", (int)getpid(), suffix);
+ }
+}
- /* Invalidate the cached store again so the next query reopens whatever the
- * worker wrote (or the prior DB, if it crashed before its final dump). */
- if (srv->owns_store && srv->store) {
- cbm_store_close(srv->store);
- srv->store = NULL;
+/* Read the single-line crash marker (the rel_path the worker was processing when
+ * it died). Returns a trimmed heap string (caller frees), or NULL when the marker
+ * is empty/unreadable (i.e. the crash could not be attributed to a file). */
+static char *supervisor_read_marker(const char *path) {
+ FILE *f = cbm_fopen(path, "rb");
+ if (!f) {
+ return NULL;
}
- free(srv->current_project);
- srv->current_project = NULL;
+ char buf[CBM_SZ_1K];
+ size_t n = fread(buf, 1, sizeof(buf) - 1, f);
+ (void)fclose(f);
+ buf[n] = '\0';
+ size_t len = strlen(buf);
+ while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r' || buf[len - 1] == ' ')) {
+ buf[--len] = '\0';
+ }
+ 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) {
+ FILE *f = cbm_fopen(path, "ab");
+ if (!f) {
+ return false;
+ }
+ (void)fprintf(f, "%s\n", rel);
+ (void)fclose(f);
+ return true;
+}
+
+/* Run index_repository in a supervised worker subprocess with skip-and-continue
+ * (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).
+ * 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) {
+ supervisor_invalidate_store(srv);
+
+ /* First attempt: normal parallel run. */
+ cbm_index_worker_result_t wr;
+ int rc = cbm_index_spawn_worker(args, false, NULL, NULL, &wr);
if (rc != 0 || wr.outcome == CBM_PROC_SPAWN_FAILED) {
cbm_index_worker_result_free(&wr);
+ supervisor_invalidate_store(srv);
return NULL; /* degrade to in-process */
}
-
- if (wr.outcome == CBM_PROC_CLEAN && wr.response) {
- char *resp = wr.response; /* transfer ownership to caller */
+ if (wr.outcome == CBM_PROC_CLEAN) {
+ /* Clean exit → transfer the worker's response (the common path). If the
+ * worker exited clean but wrote no response (a degenerate case, e.g. a
+ * self binary that does not act as an index worker), resp is NULL and the
+ * caller degrades to the in-process path — a clean run never needs the
+ * crash-recovery loop. */
+ char *resp = wr.response; /* transfer ownership to caller (may be NULL) */
wr.response = NULL;
cbm_index_worker_result_free(&wr);
+ supervisor_invalidate_store(srv);
return resp;
}
- char *resp = build_worker_failure_response(args, wr.outcome);
+ /* Crash / hang / nonzero exit → skip-and-continue recovery. Re-run the worker
+ * single-threaded with a per-file marker; each time it crashes/hangs the
+ * marker names the exact crasher, which we append to the quarantine file
+ * before re-spawning. A clean single-threaded run then indexes the good files
+ * and reports the quarantined ones as phase="crash" skips (via the ordinary
+ * Stage-2 skip plumbing — no JSON merge needed). */
+ cbm_proc_outcome_t last_outcome = wr.outcome;
cbm_index_worker_result_free(&wr);
- return resp;
+
+ char marker_path[CBM_SZ_1K];
+ char quarantine_path[CBM_SZ_1K];
+ supervisor_tmp_path(marker_path, sizeof(marker_path), ".marker");
+ supervisor_tmp_path(quarantine_path, sizeof(quarantine_path), ".quarantine");
+ (void)remove(marker_path);
+ /* Start the quarantine list empty (truncate any stale file). */
+ FILE *qinit = cbm_fopen(quarantine_path, "wb");
+ if (qinit) {
+ (void)fclose(qinit);
+ }
+
+ int cap = 100;
+ const char *cap_env = getenv("CBM_INDEX_MAX_RESTARTS");
+ if (cap_env && cap_env[0]) {
+ int v = atoi(cap_env);
+ if (v > 0) {
+ cap = v;
+ }
+ }
+
+ char *resp = NULL;
+ 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);
+ if (rc2 != 0) {
+ last_outcome = wr2.outcome;
+ cbm_index_worker_result_free(&wr2);
+ break; /* spawn failed mid-recovery — give up */
+ }
+ if (wr2.outcome == CBM_PROC_CLEAN && wr2.response) {
+ 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 */
+ }
+ 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. */
+ 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)) {
+ cbm_log_warn("index.supervisor.quarantine_write_fail", "path", crasher);
+ free(crasher);
+ break;
+ }
+ 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",
+ attempt_buf);
+ free(crasher);
+ (void)remove(marker_path); /* fresh marker for the next re-run */
+ continue;
+ }
+ /* SPAWN_FAILED / nonzero exit / non-fault kill → not a crash we can
+ * attribute; stop and report a contained failure. */
+ last_outcome = wr2.outcome;
+ cbm_index_worker_result_free(&wr2);
+ break;
+ }
+
+ (void)remove(marker_path);
+ (void)remove(quarantine_path);
+ supervisor_invalidate_store(srv);
+
+ if (resp) {
+ return resp;
+ }
+ return build_worker_failure_response(args, last_outcome);
}
static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {
diff --git a/src/pipeline/pass_definitions.c b/src/pipeline/pass_definitions.c
index e7deefd72..2339ebbeb 100644
--- a/src/pipeline/pass_definitions.c
+++ b/src/pipeline/pass_definitions.c
@@ -514,6 +514,20 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
const char *rel = files[i].rel_path;
CBMLanguage lang = files[i].language;
+ /* Crash-quarantine skip (Stage 3c): the supervisor's single-threaded
+ * recovery re-run always lands on THIS sequential path (worker_count
+ * forced to 1). This first sequential pass REPORTS a crasher as a
+ * phase="crash" skip (surfacing it in skipped[]) and continues; later
+ * sequential passes (calls/usages/semantic) re-extract on a cache miss
+ * but hit the hard guard inside cbm_extract_file, so they no-op without
+ * 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");
+ errors++;
+ continue;
+ }
+
/* Read source file */
int source_len = 0;
long file_size = 0;
diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.c
index 49c287ac0..30ac13119 100644
--- a/src/pipeline/pass_parallel.c
+++ b/src/pipeline/pass_parallel.c
@@ -666,6 +666,20 @@ static void extract_worker(int worker_id, void *ctx_ptr) {
const cbm_file_info_t *fi = &ec->files[file_idx];
pp_err_list_t *errs = ec->err_lists ? &ec->err_lists[worker_id] : NULL;
+ /* Crash-quarantine skip (Stage 3c): a file the supervisor pinned as a
+ * crasher must never be extracted again. Record it as a phase="crash"
+ * skip in this worker's list (merged into the pipeline's file-error list
+ * later, surfacing in skipped[]) and move on — the good files still
+ * index and status stays "indexed". No-op unless the supervisor set
+ * CBM_INDEX_QUARANTINE_FILE. Covers the parallel path; the supervisor's
+ * 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");
+ ws->errors++;
+ continue;
+ }
+
/* Read + extract */
int source_len = 0;
long file_size = 0;
diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.c
index 3a9282036..0d567e372 100644
--- a/src/pipeline/pipeline.c
+++ b/src/pipeline/pipeline.c
@@ -331,6 +331,19 @@ void cbm_pipeline_set_committed_counts(cbm_pipeline_t *p, int nodes, int edges)
}
}
+/* Effective worker count. The crash supervisor re-runs its worker single-
+ * threaded (CBM_INDEX_SINGLE_THREAD=1) so a per-file marker can pin the EXACT
+ * crasher; a parallel re-run would race the marker. Honour that override
+ * everywhere the worker count drives the parallel/sequential decision, so the
+ * whole extraction phase collapses to the deterministic sequential path. */
+static int effective_worker_count(bool initial) {
+ const char *st = getenv("CBM_INDEX_SINGLE_THREAD");
+ if (st && st[0] == '1') {
+ return 1;
+ }
+ return cbm_default_worker_count(initial);
+}
+
/* Resolve the DB path for this pipeline. Caller must free(). */
static char *resolve_db_path(const cbm_pipeline_t *p) {
char *path = malloc(CBM_SZ_1K);
@@ -1097,7 +1110,7 @@ static int run_githistory(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx) {
gh_compute_arg_t gh_arg = {.repo_path = ctx->repo_path, .result = &gh_result};
if (p->mode != CBM_MODE_FAST) {
- if (cbm_default_worker_count(true) > SKIP_ONE) {
+ if (effective_worker_count(true) > SKIP_ONE) {
if (cbm_thread_create(&gh_thread, 0, gh_compute_thread_fn, &gh_arg) == 0) {
gh_threaded = true;
}
@@ -1186,7 +1199,7 @@ static int run_extraction_phase(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
return CBM_NOT_FOUND;
}
- int worker_count = cbm_default_worker_count(true);
+ int worker_count = effective_worker_count(true);
CBM_PROF_START(t_extract_total);
int rc = (worker_count > SKIP_ONE && file_count > MIN_FILES_FOR_PARALLEL)
? run_parallel_pipeline(p, ctx, files, file_count, worker_count, &t)