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
fix(pipeline): own every staging file through an exclusive sidecar lock
Martin Vogel0c4831a3643b
diff --git a/src/foundation/compat_fs.c b/src/foundation/compat_fs.cindex bc1b06ac3..b478002eb 100644--- a/src/foundation/compat_fs.c+++ b/src/foundation/compat_fs.c@@ -23,11 +23,13 @@#include <windows.h>#include <aclapi.h>-#include <direct.h> /* _wmkdir */-#include <errno.h> /* errno for spawn-failure logging */-#include <fcntl.h> /* _O_RDONLY */-#include <io.h> /* _wunlink, _open_osfhandle, _close */-#include <stdint.h> /* intptr_t */+#include <direct.h> /* _wmkdir */+#include <errno.h> /* errno for spawn-failure logging */+#include <fcntl.h> /* _O_RDONLY */+#include <io.h> /* _wunlink, _open_osfhandle, _close */+#include <share.h> /* _SH_DENYRW */+#include <sys/stat.h> /* _S_IREAD */+#include <stdint.h> /* intptr_t */#include "foundation/log.h"#include "foundation/win_utf8.h"@@ -581,6 +583,26 @@ int cbm_rmdir(const char *path) {return ret;}+int cbm_lockfile_open(const char *path, bool create) {+ wchar_t *wpath = cbm_path_to_wide(path);+ if (!wpath) {+ errno = EINVAL;+ return -1;+ }+ int flags = _O_RDWR | _O_BINARY | _O_NOINHERIT | (create ? _O_CREAT : 0);+ /* _SH_DENYRW: every other open of this file, from any process, fails+ * with EACCES until this descriptor closes -- including at death. */+ int fd = _wsopen(wpath, flags, _SH_DENYRW, _S_IREAD | _S_IWRITE);+ free(wpath);+ return fd;+}++void cbm_lockfile_close(int fd) {+ if (fd >= 0) {+ (void)_close(fd);+ }+}+/* Build a properly-quoted Windows command line from an argv array.* Returns a heap-allocated wide string, or NULL on allocation failure.* Quoting follows the MSVC CRT convention: arguments containing spaces,@@ -730,6 +752,7 @@ int cbm_exec_no_shell(const char *const *argv) {#include <dirent.h>#include <errno.h>#include <fcntl.h>+#include <sys/file.h>#include <sys/stat.h>#include <sys/wait.h>#include <unistd.h>@@ -929,6 +952,34 @@ int cbm_rmdir(const char *path) {return rmdir(path);}+int cbm_lockfile_open(const char *path, bool create) {+ int flags = O_RDWR | O_CLOEXEC | O_NOFOLLOW | (create ? O_CREAT : 0);+ int fd;+ do {+ fd = open(path, flags, S_IRUSR | S_IWUSR);+ } while (fd < 0 && errno == EINTR);+ if (fd < 0) {+ return -1;+ }+ int rc;+ do {+ rc = flock(fd, LOCK_EX | LOCK_NB);+ } while (rc != 0 && errno == EINTR);+ if (rc != 0) {+ int saved = errno;+ (void)close(fd);+ errno = saved;+ return -1;+ }+ return fd;+}++void cbm_lockfile_close(int fd) {+ if (fd >= 0) {+ (void)close(fd);+ }+}+int cbm_exec_no_shell(const char *const *argv) {if (!argv || !argv[0]) {return CBM_NOT_FOUND;diff --git a/src/foundation/compat_fs.h b/src/foundation/compat_fs.hindex 8f0d16388..e7dd259a0 100644--- a/src/foundation/compat_fs.h+++ b/src/foundation/compat_fs.h@@ -97,6 +97,18 @@ int cbm_canonical_path(const char *path, char *out, size_t out_sz);/* Delete an empty directory. Returns 0 on success. */int cbm_rmdir(const char *path);+/* Exclusive lock file. Opens `path` and takes an exclusive lock the KERNEL+ * releases on any process death -- POSIX open(O_CLOEXEC|O_NOFOLLOW) ++ * flock(LOCK_EX|LOCK_NB); Windows _wsopen with _SH_DENYRW (deny every other+ * open) and _O_NOINHERIT -- so ownership never outlives its holder and is+ * never inherited by a spawned child. `create` false never creates the file.+ * Returns the descriptor, or -1 with errno: EWOULDBLOCK/EAGAIN (POSIX) or+ * EACCES (Windows sharing violation) when another holder is live, ENOENT+ * when absent, otherwise the open error. Never use this on a SQLite file:+ * on macOS an flock conflicts with SQLite's own fcntl byte locks. */+int cbm_lockfile_open(const char *path, bool create);+void cbm_lockfile_close(int fd);+/* Open a file by UTF-8 path.* On Windows, converts to wide-char and calls _wfopen so paths with* non-ASCII characters (accents, CJK, etc.) are handled correctly.diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.cindex 247f72378..59ff88837 100644--- a/src/pipeline/pipeline.c+++ b/src/pipeline/pipeline.c@@ -1531,12 +1531,148 @@ static bool promote_mode_to_existing_coverage(cbm_pipeline_t *p) {/* Defined below, next to the other publication helpers. */static char *create_staging_path(const char *final_path);+/* ── Stage ownership (#1839) ─────────────────────────────────────+ *+ * A stage used to be recognisable only by its name: the mkstemp descriptor+ * was closed at once and nothing marked who was writing it. A worker killed+ * mid-run (the daemon cancels with SIGTERM then SIGKILL after one second of+ * grace, which a gigabyte backup or clone never finishes inside) left its+ * full-size stage behind forever, and no later run could tell a dead stage+ * from a live one -- so none tried.+ *+ * Ownership is now an exclusive kernel lock on the sidecar "<stage>.lock",+ * held from minting until the stage is discarded or renamed into place. The+ * kernel releases it on any death, so "can I take this lock?" is exactly+ * "is this stage dead?" -- no pid, no mtime, no grace period. The lock lives+ * on a sidecar rather than the stage itself because on macOS an flock on a+ * file conflicts with SQLite's fcntl byte locks on that same file.+ *+ * The stage path is passed around as a plain string through publish and+ * finalize, so the descriptor is kept in this per-process registry keyed by+ * path, and released by the same helpers that remove the file. */+typedef struct stage_owner {+ char *stage_path;+ int lock_fd;+ struct stage_owner *next;+} stage_owner_t;++static stage_owner_t *g_stage_owners = NULL;+static atomic_flag g_stage_owners_spin = ATOMIC_FLAG_INIT;++static void stage_owners_lock(void) {+ while (atomic_flag_test_and_set_explicit(&g_stage_owners_spin, memory_order_acquire)) {}+}++static void stage_owners_unlock(void) {+ atomic_flag_clear_explicit(&g_stage_owners_spin, memory_order_release);+}++static char *stage_lock_sidecar_path(const char *stage_path) {+ static const char suffix[] = ".lock";+ size_t len = strlen(stage_path);+ if (len > SIZE_MAX - sizeof(suffix)) {+ return NULL;+ }+ char *sidecar = (char *)malloc(len + sizeof(suffix));+ if (!sidecar) {+ return NULL;+ }+ memcpy(sidecar, stage_path, len);+ memcpy(sidecar + len, suffix, sizeof(suffix));+ return sidecar;+}++int cbm_pipeline_stage_lock_hold(const char *stage_path) {+ if (!stage_path) {+ return -1;+ }+ char *sidecar = stage_lock_sidecar_path(stage_path);+ if (!sidecar) {+ return -1;+ }+ int fd = cbm_lockfile_open(sidecar, true);+ free(sidecar);+ return fd;+}++void cbm_pipeline_stage_lock_drop(const char *stage_path, int lock_fd) {+ if (!stage_path || lock_fd < 0) {+ return;+ }+ char *sidecar = stage_lock_sidecar_path(stage_path);+ /* Close before unlinking: Windows refuses to delete an open file. The+ * sidecar exists unlocked for that instant, but by every drop the stage+ * itself is already gone (discarded or renamed), so there is nothing a+ * sweeper could take from us. */+ cbm_lockfile_close(lock_fd);+ if (sidecar) {+ (void)cbm_unlink(sidecar);+ free(sidecar);+ }+}++static bool stage_owner_register(const char *stage_path) {+ int fd = cbm_pipeline_stage_lock_hold(stage_path);+ if (fd < 0) {+ char errno_text[16];+ (void)snprintf(errno_text, sizeof(errno_text), "%d", errno);+ cbm_log_warn("pipeline.stage", "action", "lock_failed", "errno", errno_text, "path",+ stage_path);+ return false;+ }+ stage_owner_t *owner = (stage_owner_t *)malloc(sizeof(*owner));+ char *path_copy = strdup(stage_path);+ if (!owner || !path_copy) {+ free(owner);+ free(path_copy);+ cbm_pipeline_stage_lock_drop(stage_path, fd);+ return false;+ }+ owner->stage_path = path_copy;+ owner->lock_fd = fd;+ stage_owners_lock();+ owner->next = g_stage_owners;+ g_stage_owners = owner;+ stage_owners_unlock();+ return true;+}++/* Release ownership of a stage that no longer exists under this name. A path+ * this process never registered is a no-op. */+static void stage_owner_release(const char *stage_path) {+ if (!stage_path) {+ return;+ }+ stage_owner_t *found = NULL;+ stage_owners_lock();+ for (stage_owner_t **link = &g_stage_owners; *link; link = &(*link)->next) {+ if (strcmp((*link)->stage_path, stage_path) == 0) {+ found = *link;+ *link = found->next;+ break;+ }+ }+ stage_owners_unlock();+ if (!found) {+ return;+ }+ cbm_pipeline_stage_lock_drop(found->stage_path, found->lock_fd);+ free(found->stage_path);+ free(found);+}++/* Remove a stage's main file and SQLite sidecars, keeping ownership. */+static void remove_stage_files(const char *stage_path) {+ (void)cbm_unlink(stage_path);+ (void)cbm_remove_db_sidecars(stage_path);+}+static void discard_generation_stage(const char *stage_path) {if (!stage_path) {return;}- cbm_unlink(stage_path);- cbm_remove_db_sidecars(stage_path);+ remove_stage_files(stage_path);+ stage_owner_release(stage_path);}typedef struct {@@ -1930,6 +2066,7 @@ int cbm_pipeline_finalize_staged_generation(char *stage_path, const char *final_discard_generation_stage(stage_path);return CBM_PIPELINE_PERSIST_FAILED;}+ stage_owner_release(stage_path);cbm_log_info("finalize.timing", "block", "rename", "elapsed_ms",itoa_buf((int)elapsed_ms(t_fin)));return 0;@@ -2387,8 +2524,8 @@ static void cleanup_staging_db(const char *path) {if (!path) {return;}- (void)cbm_unlink(path);- (void)cbm_remove_db_sidecars(path);+ remove_stage_files(path);+ stage_owner_release(path);}static bool ensure_db_parent(const char *path) {@@ -2495,6 +2632,11 @@ static char *create_staging_path(const char *final_path) {#elseclose(fd);#endif+ if (!stage_owner_register(path)) {+ (void)cbm_unlink(path);+ free(path);+ return NULL;+ }return path;}@@ -2622,7 +2764,10 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {if (!backup_succeeded) {cbm_log_warn("pipeline.stage", "action", "backup_failed_full_rebuild", "path",final_path);- cleanup_staging_db(staging_path);+ /* The copy is gone but the NAME stays ours: the rebuilt+ * generation is renamed over it by the inner finalize and then+ * published from it below, so its lock is held to the end. */+ remove_stage_files(staging_path);}}@@ -2705,6 +2850,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {return CBM_PIPELINE_PERSIST_FAILED;}+ stage_owner_release(staging_path);rc = export_after_publish(p, final_path);free(staging_path);free(final_path);diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.hindex d749c695a..186b8ee66 100644--- a/src/pipeline/pipeline_internal.h+++ b/src/pipeline/pipeline_internal.h@@ -792,6 +792,17 @@ int cbm_pipeline_publish_staged(char *stage_path, const cbm_pipeline_generation_* executor; the dump path uses it internally). malloc'd, caller frees. */char *cbm_pipeline_create_staging_path(const char *final_path);+/* Stage ownership (#1839). Every stage minted by cbm_pipeline_create_staging_path+ * is owned through an exclusive kernel lock on the sidecar "<stage>.lock" for+ * as long as the stage exists; the lock -- and the sidecar -- go away when the+ * stage is discarded or renamed into place, and the kernel drops the lock+ * when the writer dies. Hold/drop are the same primitive, exposed so a test+ * can stand in for a live writer. hold returns a descriptor >= 0, or -1 when+ * another holder is live or the sidecar cannot be created. drop releases the+ * lock and unlinks the sidecar. */+int cbm_pipeline_stage_lock_hold(const char *stage_path);+void cbm_pipeline_stage_lock_drop(const char *stage_path, int lock_fd);+/* ── Delta-repair staging primitives (pipeline_delta.c) ──────────* Closure-route-only subsystem: clone the live generation, patch exactly* the repaired node/edge set, publish through the shared finalize leg. */diff --git a/tests/test_pipeline.c b/tests/test_pipeline.cindex e724736e2..96857efb8 100644--- a/tests/test_pipeline.c+++ b/tests/test_pipeline.c@@ -2278,7 +2278,7 @@ TEST(pipeline_complexity_props_independent_of_worker_order) {ASSERT_EQ(sequential_rc, 0);ASSERT_NOT_NULL(sequential_sig);ASSERT_GTE(sequential_funcs, copied); /* at least the one function per fixture file */- ASSERT_TRUE(cycles_detected); /* the cycles must reach the pass at all */+ ASSERT_TRUE(cycles_detected); /* the cycles must reach the pass at all */if (mismatch_run >= 0) {printf("\n parallel run %d diverges from sequential: %s\n", mismatch_run, diff);FAIL("complexity props depend on worker id order");@@ -3496,6 +3496,59 @@ TEST(pipeline_stage_names_never_nest) {PASS();}+static bool path_exists(const char *path) {+ cbm_path_info_t info;+ return cbm_path_info_utf8(path, &info) == CBM_PATH_INFO_OK;+}++/* #1839: a minted stage is OWNED through an exclusive kernel lock on its+ * "<stage>.lock" sidecar for exactly as long as the stage exists. A second+ * holder cannot take it while the writer is live; discarding the stage frees+ * the name and removes the sidecar, so nothing stays behind. */+TEST(pipeline_minted_stage_is_owned_until_released) {+ char tmp[256];+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_stage_owner_XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));+ char db_path[512];+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);++ char *stage = cbm_pipeline_create_staging_path(db_path);+ ASSERT_NOT_NULL(stage);+ char lock_path[600];+ snprintf(lock_path, sizeof(lock_path), "%s.lock", stage);+ bool lock_present_while_live = path_exists(lock_path);+ int hold_while_live = cbm_pipeline_stage_lock_hold(stage);+ if (hold_while_live >= 0) {+ cbm_pipeline_stage_lock_drop(stage, hold_while_live);+ }++ cbm_pipeline_discard_stage(stage);+ bool stage_gone = !path_exists(stage);+ bool lock_gone = !path_exists(lock_path);++ int hold_after_discard = cbm_pipeline_stage_lock_hold(stage);+ int second_holder = cbm_pipeline_stage_lock_hold(stage);+ if (second_holder >= 0) {+ cbm_pipeline_stage_lock_drop(stage, second_holder);+ }+ cbm_pipeline_stage_lock_drop(stage, hold_after_discard);+ int hold_after_drop = cbm_pipeline_stage_lock_hold(stage);+ cbm_pipeline_stage_lock_drop(stage, hold_after_drop);+ int leftovers = count_generation_stage_artifacts(tmp, "generation.db");+ free(stage);+ th_rmtree(tmp);++ ASSERT_TRUE(lock_present_while_live);+ ASSERT_EQ(hold_while_live, -1);+ ASSERT_TRUE(stage_gone);+ ASSERT_TRUE(lock_gone);+ ASSERT_TRUE(hold_after_discard >= 0);+ ASSERT_EQ(second_holder, -1);+ ASSERT_TRUE(hold_after_drop >= 0);+ ASSERT_EQ(leftovers, 0);+ PASS();+}+/* Discovery and extraction must describe the same immutable generation. A* source file created after extraction is not present in the original file* list, so merely re-hashing that list cannot detect the race. Publication@@ -7217,19 +7270,18 @@ TEST(pipeline_python_cross_module_call) {* unique_name (candidates==1) is #1572 and is not this claim. */TEST(pipeline_cross_language_same_name_does_not_share_calls_issue725) {const char *files[] = {"store.py", "app.py", "web/src/pages/Editor.js"};- const char *contents[] = {- "class Store:\n"- " def commit(self):\n"- " return True\n",+ const char *contents[] = {"class Store:\n"+ " def commit(self):\n"+ " return True\n",- "from store import Store\n"- "\n"- "def save():\n"- " return Store().commit()\n",+ "from store import Store\n"+ "\n"+ "def save():\n"+ " return Store().commit()\n",- "export function commit() {\n"- " return 1;\n"- "}\n"};+ "export function commit() {\n"+ " return 1;\n"+ "}\n"};if (setup_lang_repo(files, contents, 3) != 0)FAIL("tmpdir");@@ -13644,7 +13696,6 @@ TEST(pipeline_delta_patch_indexes_docstring_into_fts_body) {PASS();}-/* End-to-end for #518/#519: source → docstring → properties JSON → nodes_fts* `body` → findable. Each layer has its own test; this one proves they connect.* It is also the guard on the size budget: build_def_props drops an oversized@@ -14201,6 +14252,7 @@ SUITE(pipeline_semantic_manifest_repro) {RUN_TEST(pipeline_global_extension_config_change_forces_full);RUN_TEST(pipeline_publication_never_uses_a_predictable_staging_path);RUN_TEST(pipeline_stage_names_never_nest);+ RUN_TEST(pipeline_minted_stage_is_owned_until_released);RUN_TEST(pipeline_source_mutation_before_publication_preserves_previous_generation);RUN_TEST(pipeline_source_addition_before_publication_preserves_previous_generation);RUN_TEST(pipeline_tsconfig_mutation_before_publication_preserves_previous_generation);