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(pipeline): fail an over-budget index attempt whole instead of soft-overshooting

Martin Vogel699be6c24688
diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.c
index 9f572b2b7..759c199f6 100644
--- a/src/pipeline/pass_parallel.c
+++ b/src/pipeline/pass_parallel.c
@@ -30,7 +30,9 @@ enum {
/* Extraction memory back-pressure: when the process is over its RSS budget,
* a worker reclaims + naps before pulling another file so peers can finish
* and return pages. Bounded spins avoid deadlock when the resident graph
- * itself is near budget (then proceed with a soft overshoot). */
+ * itself is near budget: then ONE confirmation cycle decides — drained
+ * means continue, still over means the attempt fails whole (decision A,
+ * #1997 #832) instead of the former open-ended soft overshoot. */
PP_BACKPRESSURE_MAX_SPINS = 40,
PP_BACKPRESSURE_NAP_NS = 3000000, /* 3 ms */
};
@@ -667,6 +669,11 @@ typedef struct {
* While set, pulls skip the nap (the designed soft overshoot); the cheap
* over-budget probe re-arms the gate once RSS drains under budget. */
_Atomic int bp_futile;
+ /* Decision A (#1997 #832): set once futility was CONFIRMED by a second
+ * full cycle that still ended over budget. Every pull loop breaks on it
+ * and extract returns CBM_PIPELINE_ABORT_OVER_BUDGET. Deliberately not
+ * the shared cancel token — that one belongs to client cancellation. */
+ _Atomic int over_budget_abort;
const CBMMacroTable *macro_table; /* ObjectScript $$$macros (NULL if none) */
const CBMReturnTypeTable *return_type_table; /* ObjectScript return types (NULL if none) */
@@ -722,6 +729,39 @@ static void log_extract_done(int pos, uint64_t ms, int defs, const char *path) {
}
}
+/* One back-pressure cycle: reclaim this thread's freed pages, then nap in
+ * bounded 3 ms steps while the process stays over budget. Counted for test
+ * observability. Returns true when the FULL cycle elapsed still over budget —
+ * the resident floor, not in-flight transients, holds the memory. */
+static bool pp_backpressure_cycle_still_over(extract_ctx_t *ec) {
+ cbm_mem_collect();
+ atomic_fetch_add_explicit(&g_bp_nap_cycles, SKIP_ONE, memory_order_relaxed);
+ int bp = 0;
+ for (; bp < PP_BACKPRESSURE_MAX_SPINS && cbm_mem_over_budget() &&
+ !atomic_load_explicit(ec->cancelled, memory_order_relaxed) &&
+ !atomic_load_explicit(&ec->over_budget_abort, memory_order_relaxed);
+ bp++) {
+ struct timespec nap = {0, PP_BACKPRESSURE_NAP_NS};
+ cbm_nanosleep(&nap, NULL);
+ }
+ return bp == PP_BACKPRESSURE_MAX_SPINS && cbm_mem_over_budget();
+}
+
+/* Decision A (#1997 #832): back-pressure was futile and the confirmation
+ * cycle still ended over budget. The budget stops being advisory here: flag
+ * the attempt so every worker stops pulling and extract returns
+ * CBM_PIPELINE_ABORT_OVER_BUDGET. Cooperative on purpose — the failure must
+ * travel as a clean-exit worker response, never a kill, or the supervisor
+ * would quarantine innocent files. */
+static void pp_fail_whole_over_budget(extract_ctx_t *ec) {
+ if (atomic_exchange_explicit(&ec->over_budget_abort, 1, memory_order_relaxed) == 0) {
+ cbm_log_error("mem.budget.exceeded", "rss_mb",
+ itoa_log((int)(cbm_mem_rss() / (1024 * 1024))), "budget_mb",
+ itoa_log((int)(cbm_mem_budget() / (1024 * 1024))), "phase",
+ "parallel_extract", "action", "fail_whole");
+ }
+}
+
static void extract_worker(int worker_id, void *ctx_ptr) {
extract_ctx_t *ec = ctx_ptr;
extract_worker_state_t *ws = &ec->workers[worker_id];
@@ -739,7 +779,8 @@ static void extract_worker(int worker_id, void *ctx_ptr) {
break;
}
cbm_scale_tick(&ec->scale, sort_pos);
- if (atomic_load_explicit(ec->cancelled, memory_order_relaxed)) {
+ if (atomic_load_explicit(ec->cancelled, memory_order_relaxed) ||
+ atomic_load_explicit(&ec->over_budget_abort, memory_order_relaxed)) {
break;
}
@@ -750,39 +791,41 @@ static void extract_worker(int worker_id, void *ctx_ptr) {
* near the budget instead of letting all workers parse their biggest
* files at once. Self-disabling when the budget is unset (tests) or RSS
* is under budget; bounded spins avoid deadlock when the resident graph
- * is itself near budget (then proceed with a soft overshoot).
+ * is itself near budget.
*
* Futility latch: when a FULL nap cycle ends still over budget, the
* resident floor — not transients — holds the memory; napping again on
* the next pull cannot reclaim it and only idles workers (linux kernel:
- * one full cycle per pull ≈ 390 s at 79% avg CPU). Latch bp_futile and
- * proceed with the soft overshoot; the over-budget probe below re-arms
- * the gate as soon as RSS drains under budget. */
+ * one full cycle per pull ≈ 390 s at 79% avg CPU). The worker that
+ * latches bp_futile (0→1) runs ONE confirmation cycle while its peers
+ * skip the nap. A confirmation that ends under budget re-arms the gate
+ * (RSS drained after all); one that still ends over budget fails the
+ * attempt whole (decision A, #1997 #832): every worker stops pulling,
+ * extract returns CBM_PIPELINE_ABORT_OVER_BUDGET, nothing is published
+ * and the previously serving index keeps answering. */
if (cbm_mem_budget() > 0) {
bool over = cbm_mem_over_budget();
bool futile = atomic_load_explicit(&ec->bp_futile, memory_order_relaxed) != 0;
if (over && !futile) {
- cbm_mem_collect();
- atomic_fetch_add_explicit(&g_bp_nap_cycles, SKIP_ONE, memory_order_relaxed);
- int bp = 0;
- for (; bp < PP_BACKPRESSURE_MAX_SPINS && cbm_mem_over_budget() &&
- !atomic_load_explicit(ec->cancelled, memory_order_relaxed);
- bp++) {
- struct timespec nap = {0, PP_BACKPRESSURE_NAP_NS};
- cbm_nanosleep(&nap, NULL);
- }
- if (bp == PP_BACKPRESSURE_MAX_SPINS && cbm_mem_over_budget()) {
- /* Log only the 0→1 transition: all workers race into the
- * gate before anyone latches, so a plain store would WARN
- * once per worker (12 lines per latch event). */
- if (atomic_exchange_explicit(&ec->bp_futile, 1, memory_order_relaxed) == 0) {
- cbm_log_warn("mem.backpressure.futile", "action", "soft_overshoot");
+ /* Act only on the 0→1 transition: all workers race into the
+ * gate before anyone latches, so a plain store would confirm
+ * (and WARN) once per worker. */
+ if (pp_backpressure_cycle_still_over(ec) &&
+ atomic_exchange_explicit(&ec->bp_futile, 1, memory_order_relaxed) == 0) {
+ cbm_log_warn("mem.backpressure.futile", "action", "confirm");
+ if (pp_backpressure_cycle_still_over(ec)) {
+ pp_fail_whole_over_budget(ec);
+ } else {
+ atomic_store_explicit(&ec->bp_futile, 0, memory_order_relaxed);
}
}
} else if (!over && futile) {
atomic_store_explicit(&ec->bp_futile, 0, memory_order_relaxed);
}
}
+ if (atomic_load_explicit(&ec->over_budget_abort, memory_order_relaxed)) {
+ break;
+ }
int file_idx = ec->sorted[sort_pos].idx;
const cbm_file_info_t *fi = &ec->files[file_idx];
@@ -1129,6 +1172,7 @@ int cbm_parallel_extract_ex(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
atomic_init(&ec.retain_cap_warned, 0);
atomic_init(&ec.oversized_warned, 0);
atomic_init(&ec.bp_futile, 0);
+ atomic_init(&ec.over_budget_abort, 0);
/* Sub-phase: Dispatch workers (parse + extract per file, PARALLEL) */
CBM_PROF_START(t_dispatch);
@@ -1176,6 +1220,12 @@ int cbm_parallel_extract_ex(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
free(sorted);
cbm_macro_table_free(pp_macro_table); /* ObjectScript macro table (NULL-safe) */
+ /* The over-budget verdict outranks the cancel sentinel: a caller must be
+ * able to name the cause, and the orchestrator discards the staging DB on
+ * every non-zero code alike (the live generation is never touched). */
+ if (atomic_load(&ec.over_budget_abort)) {
+ return CBM_PIPELINE_ABORT_OVER_BUDGET;
+ }
if (atomic_load(ctx->cancelled)) {
return CBM_NOT_FOUND;
}
diff --git a/src/pipeline/pipeline.h b/src/pipeline/pipeline.h
index dfe81f726..954686849 100644
--- a/src/pipeline/pipeline.h
+++ b/src/pipeline/pipeline.h
@@ -63,9 +63,14 @@ void cbm_pipeline_free(cbm_pipeline_t *p);
* need to know whether the PREVIOUS generation survived can distinguish the
* failures by value: the run publishes by renaming a fully validated staging
* database over the destination, so every abort before that rename leaves the
- * existing database in place. Those codes (CBM_PIPELINE_ABORT_PRESERVE_DB and
- * CBM_PIPELINE_PERSIST_FAILED) are defined in pipeline_internal.h alongside the
- * stages that raise them. */
+ * existing database in place. */
+#define CBM_PIPELINE_ABORT_PRESERVE_DB (-2) /* aborted pre-publication; previous DB intact */
+#define CBM_PIPELINE_PERSIST_FAILED (-4) /* staging/rollback failure during publication */
+/* Resident memory stayed above the budget after back-pressure and one
+ * confirmation cycle: the run stops before publication, no partial graph is
+ * written, the previous DB is intact (#1997 #832). Distinct from the cancel
+ * sentinel so callers can name the cause instead of "pipeline failed". */
+#define CBM_PIPELINE_ABORT_OVER_BUDGET (-5)
int cbm_pipeline_run(cbm_pipeline_t *p);
/* Request cancellation of a running pipeline (thread-safe). */
diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.h
index d749c695a..3a6cc1e58 100644
--- a/src/pipeline/pipeline_internal.h
+++ b/src/pipeline/pipeline_internal.h
@@ -29,12 +29,12 @@
/* Route node QN buffer size (must fit __route__METHOD__/full/url/path) */
#define CBM_ROUTE_QN_SIZE 768
-/* Incremental integrity failure: abort the run and preserve the existing DB.
- * Distinct from CBM_NOT_FOUND, which the orchestrator uses as the normal
+/* CBM_PIPELINE_ABORT_PRESERVE_DB / CBM_PIPELINE_PERSIST_FAILED moved to
+ * pipeline.h — callers legitimately distinguish them (the header's contract
+ * always said so). FORCE_FULL_REINDEX never escapes the orchestrator and
+ * stays internal. All three are distinct from CBM_NOT_FOUND, the normal
* "no incremental route; continue with a full index" sentinel. */
-#define CBM_PIPELINE_ABORT_PRESERVE_DB (-2)
#define CBM_PIPELINE_FORCE_FULL_REINDEX (-3)
-#define CBM_PIPELINE_PERSIST_FAILED (-4)
/* Canonicalize route-path parameter placeholders (":id", "{id}", "<id>",
* "${...}") to a single "{}" token so that client call sites and server
diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c
index 0f6332cb2..738445fdf 100644
--- a/tests/test_pipeline.c
+++ b/tests/test_pipeline.c
@@ -12871,23 +12871,82 @@ TEST(pipeline_committed_counts_match_persisted) {
* MIN_FILES_FOR_PARALLEL (50) — else the run routes sequential, the gate never
* fires, and the test would pass vacuously (cycles==0). The engagement assert
* below (cycles >= 1) is a hard guard against that regressing silently. */
-TEST(pipeline_backpressure_futile_nap_disengages) {
- /* 64 tiny files: > MIN_FILES_FOR_PARALLEL (50) so the parallel path (and its
- * back-pressure gate) actually runs; old-code cycles (~64) >> the bound. */
+/* Shared fixture for the back-pressure tests: 64 tiny Go files, above
+ * MIN_FILES_FOR_PARALLEL (50) so the parallel extract path — the only phase
+ * with a memory gate — is the one that runs. */
+static bool write_backpressure_fixture(void) {
snprintf(g_tmpdir, sizeof(g_tmpdir), "/tmp/cbm_test_XXXXXX");
if (!cbm_mkdtemp(g_tmpdir)) {
- FAIL("failed to create temp dir");
+ return false;
}
for (int i = 0; i < 64; i++) {
char path[512];
snprintf(path, sizeof(path), "%s/f%02d.go", g_tmpdir, i);
FILE *f = fopen(path, "w");
if (!f) {
- FAIL("failed to create fixture file");
+ return false;
}
fprintf(f, "package main\n\nfunc F%02d() int {\n\treturn %d\n}\n", i, i);
fclose(f);
}
+ return true;
+}
+
+/* Rewrite every fixture file with a second definition. An unchanged repo
+ * routes incremental_manifest → incremental.noop (nothing is re-extracted, so
+ * no gate can fire); changing all 64 files makes the next run re-extract them
+ * all through the parallel path. */
+static bool mutate_backpressure_fixture(void) {
+ for (int i = 0; i < 64; i++) {
+ char path[512];
+ snprintf(path, sizeof(path), "%s/f%02d.go", g_tmpdir, i);
+ FILE *f = fopen(path, "w");
+ if (!f) {
+ return false;
+ }
+ fprintf(f,
+ "package main\n\nfunc F%02d() int {\n\treturn %d\n}\n\n"
+ "func G%02d() int {\n\treturn F%02d() + 1\n}\n",
+ i, i, i, i);
+ fclose(f);
+ }
+ return true;
+}
+
+/* Whole-file read for byte-identity assertions on a published database. */
+static unsigned char *read_file_bytes(const char *path, size_t *len_out) {
+ *len_out = 0;
+ FILE *f = fopen(path, "rb");
+ if (!f) {
+ return NULL;
+ }
+ long size = fseek(f, 0, SEEK_END) == 0 ? ftell(f) : -1;
+ if (size < 0) {
+ fclose(f);
+ return NULL;
+ }
+ rewind(f);
+ unsigned char *buf = malloc((size_t)size + 1);
+ if (!buf) {
+ fclose(f);
+ return NULL;
+ }
+ size_t got = fread(buf, 1, (size_t)size, f);
+ fclose(f);
+ if (got != (size_t)size) {
+ free(buf);
+ return NULL;
+ }
+ *len_out = got;
+ return buf;
+}
+
+TEST(pipeline_backpressure_futile_nap_disengages) {
+ /* 64 tiny files: > MIN_FILES_FOR_PARALLEL (50) so the parallel path (and its
+ * back-pressure gate) actually runs; old-code cycles (~64) >> the bound. */
+ if (!write_backpressure_fixture()) {
+ FAIL("failed to create fixture");
+ }
/* 1 MB budget: over-budget on every pull, unreclaimable by napping.
* Set via the test hook, NOT setenv + cbm_mem_init: the init-once guard
@@ -12942,7 +13001,10 @@ TEST(pipeline_backpressure_futile_nap_disengages) {
teardown_test_repo();
ASSERT_EQ(restore_workers_rc, 0);
- ASSERT_EQ(rc, 0);
+ /* Decision A (#1997 #832): a budget that never drains is not a soft
+ * overshoot any more — after the latch and ONE confirmation cycle the
+ * attempt fails whole with the named code (rc==0 was the advisory era). */
+ ASSERT_EQ(rc, CBM_PIPELINE_ABORT_OVER_BUDGET);
/* Engagement guard (anti-vacuous): the gate must have actually run — the
* parallel path taken and the 1 MB budget exceeded on every pull. cycles==0
* means the fixture routed sequential (or the gate was compiled out) and
@@ -12951,8 +13013,9 @@ TEST(pipeline_backpressure_futile_nap_disengages) {
FAIL("back-pressure gate never engaged (cycles==0) — fixture routed sequential?");
}
/* Futile napping must disengage: at most one in-flight cycle per worker
- * plus a small margin, never one per file (64). */
- long bound = TEST_WORKERS + 2;
+ * plus the single confirmation cycle and a small margin, never one per
+ * file (64). */
+ long bound = TEST_WORKERS + 3;
if (cycles > bound) {
char msg[128];
snprintf(msg, sizeof(msg), "nap cycles %ld > bound %ld (gate re-paid per pull)", cycles,
@@ -12962,6 +13025,102 @@ TEST(pipeline_backpressure_futile_nap_disengages) {
PASS();
}
+/* Decision A (#1997 #832): once back-pressure is futile AND one confirmation
+ * cycle still ends over budget, the attempt fails WHOLE with a named code —
+ * no partial graph is published, no stage residue remains, and the previously
+ * serving generation is byte-identical. */
+TEST(pipeline_over_budget_after_futility_fails_whole_and_preserves_db) {
+ if (!write_backpressure_fixture()) {
+ FAIL("failed to create fixture");
+ }
+ enum { TEST_WORKERS = 4 };
+ const char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ if ((old_workers && !saved_workers) || cbm_setenv("CBM_WORKERS", "4", 1) != 0) {
+ free(saved_workers);
+ teardown_test_repo();
+ FAIL("failed to pin CBM_WORKERS");
+ }
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/budget.db", g_tmpdir);
+
+ /* Generation 1 at the process budget: publishes normally. */
+ cbm_pipeline_t *p = cbm_pipeline_new(g_tmpdir, db_path, CBM_MODE_FULL);
+ int rc_first = p ? cbm_pipeline_run(p) : -1;
+ char *project = p ? strdup(cbm_pipeline_project_name(p)) : NULL;
+ cbm_pipeline_free(p);
+ int nodes_before = -1;
+ bool valid_before = false;
+ cbm_store_t *live = rc_first == 0 && project ? cbm_store_open_path(db_path) : NULL;
+ if (live) {
+ valid_before = cbm_store_check_integrity(live);
+ nodes_before = cbm_store_count_nodes(live, project);
+ cbm_store_close(live);
+ }
+ size_t before_len = 0;
+ unsigned char *before = read_file_bytes(db_path, &before_len);
+
+ /* Generation 2 at a 1 MiB budget over a CHANGED repo (every file gains a
+ * definition, so the run must re-extract all 64): over budget on every
+ * probe and unreclaimable by napping, so futility latches and the
+ * confirmation cycle still ends over budget. */
+ bool mutated = mutate_backpressure_fixture();
+ size_t saved_budget = cbm_mem_budget();
+ cbm_mem_set_budget_for_tests((size_t)1024 * 1024);
+ bool over_at_start = cbm_mem_over_budget();
+ cbm_pp_bp_nap_cycles_reset();
+ p = cbm_pipeline_new(g_tmpdir, db_path, CBM_MODE_FULL);
+ int rc_second = p ? cbm_pipeline_run(p) : -1;
+ long cycles = cbm_pp_bp_nap_cycles();
+ /* Restore the caller-visible budget BEFORE any assertion. */
+ cbm_mem_set_budget_for_tests(saved_budget);
+ cbm_pipeline_free(p);
+
+ size_t after_len = 0;
+ unsigned char *after = read_file_bytes(db_path, &after_len);
+ int stage_count = count_generation_stage_artifacts(g_tmpdir, "budget.db");
+ int nodes_after = -1;
+ bool valid_after = false;
+ live = cbm_store_open_path(db_path);
+ if (live) {
+ valid_after = cbm_store_check_integrity(live);
+ nodes_after = project ? cbm_store_count_nodes(live, project) : -1;
+ cbm_store_close(live);
+ }
+ bool bytes_identical =
+ before && after && before_len == after_len && memcmp(before, after, before_len) == 0;
+ free(before);
+ free(after);
+ free(project);
+ int restore_workers_rc =
+ saved_workers ? cbm_setenv("CBM_WORKERS", saved_workers, 1) : cbm_unsetenv("CBM_WORKERS");
+ free(saved_workers);
+ teardown_test_repo();
+
+ ASSERT_EQ(restore_workers_rc, 0);
+ ASSERT_EQ(rc_first, 0);
+ ASSERT_TRUE(valid_before);
+ ASSERT_GT(nodes_before, 0);
+ ASSERT_TRUE(before_len > 0);
+ ASSERT_TRUE(mutated);
+ ASSERT_TRUE(over_at_start);
+ /* The named failure — not the cancel sentinel, not success. */
+ ASSERT_EQ(rc_second, CBM_PIPELINE_ABORT_OVER_BUDGET);
+ /* Engagement guard (anti-vacuous): fail-whole needs the latching cycle AND
+ * the confirmation cycle; fewer means the gate never decided anything. */
+ if (cycles < 2) {
+ FAIL("back-pressure gate never confirmed futility (cycles<2) — fixture routed sequential?");
+ }
+ /* The serving generation is untouched: same bytes, still valid, same
+ * graph; and the failed attempt left no stage residue behind. */
+ ASSERT_TRUE(bytes_identical);
+ ASSERT_TRUE(valid_after);
+ ASSERT_EQ(nodes_after, nodes_before);
+ ASSERT_EQ(stage_count, 0);
+ PASS();
+}
+
/* TS cross-registry test hooks (ts_lsp.c) — extern to avoid pulling the
* tree-sitter-typed ts_lsp.h into this store-level test. */
extern long cbm_ts_full_registry_builds(void);
@@ -13774,6 +13933,7 @@ SUITE(pipeline) {
RUN_TEST(pipeline_run_null);
/* Extraction back-pressure */
RUN_TEST(pipeline_backpressure_futile_nap_disengages);
+ RUN_TEST(pipeline_over_budget_after_futility_fails_whole_and_preserves_db);
/* Sequential cross-LSP shared registry (ms-typescript quadratic) */
RUN_TEST(pipeline_seq_ts_cross_uses_shared_registry);
/* File persistence */