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(store): bind pagination to published generations

Martin Vogel4cbc0536ac8d
diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.c
index 938437549..0ffb46c0b 100644
--- a/src/pipeline/pipeline.c
+++ b/src/pipeline/pipeline.c
@@ -1815,6 +1815,16 @@ int cbm_pipeline_publish_staged(char *stage_path, const cbm_pipeline_generation_
}
cbm_log_info("publish.timing", "block", "fts", "elapsed_ms", itoa_buf((int)elapsed_ms(t_pub)));
cbm_clock_gettime(CLOCK_MONOTONIC, &t_pub);
+ /* This is the shared commit tail for complete rebuilds and isolated
+ * deltas. Stamp only after every graph/metadata/FTS mutation: a fresh
+ * staging file receives a new uid, while a cloned delta keeps its uid and
+ * advances the mutation counter. A failure discards the private stage. */
+ if (ok && cbm_store_generation_advance(store) != CBM_STORE_OK) {
+ ok = false;
+ }
+ cbm_log_info("publish.timing", "block", "generation", "elapsed_ms",
+ itoa_buf((int)elapsed_ms(t_pub)));
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t_pub);
if (ok && !cbm_store_check_integrity(store)) {
ok = false;
}
diff --git a/src/store/store.c b/src/store/store.c
index 0709631c3..cbac03d70 100644
--- a/src/store/store.c
+++ b/src/store/store.c
@@ -2175,13 +2175,214 @@ int cbm_store_dump_to_file(cbm_store_t *s, const char *dest_path) {
/* ── Project CRUD ───────────────────────────────────────────────── */
+static int rollback_savepoint_preserving_error(cbm_store_t *s, const char *rollback_sql,
+ const char *release_sql) {
+ char saved_error[sizeof(s->errbuf)];
+ snprintf(saved_error, sizeof(saved_error), "%s", s->errbuf);
+ (void)sqlite3_exec(s->db, rollback_sql, NULL, NULL, NULL);
+ (void)sqlite3_exec(s->db, release_sql, NULL, NULL, NULL);
+ snprintf(s->errbuf, sizeof(s->errbuf), "%s", saved_error);
+ return CBM_STORE_ERR;
+}
+
+static bool generation_uid_is_canonical(const char *uid) {
+ if (!uid || strlen(uid) != 16) {
+ return false;
+ }
+ for (size_t i = 0; i < 16; i++) {
+ if (!((uid[i] >= '0' && uid[i] <= '9') || (uid[i] >= 'a' && uid[i] <= 'f'))) {
+ return false;
+ }
+ }
+ return true;
+}
+
+static bool generation_counter_parse(const char *text, uint64_t *out) {
+ if (!text || !text[0] || (text[0] == '0' && text[1] != '\0')) {
+ return false;
+ }
+ uint64_t value = 0;
+ for (const unsigned char *p = (const unsigned char *)text; *p; p++) {
+ if (*p < '0' || *p > '9') {
+ return false;
+ }
+ uint64_t digit = (uint64_t)(*p - '0');
+ if (value > (UINT64_MAX - digit) / 10) {
+ return false;
+ }
+ value = value * 10 + digit;
+ }
+ *out = value;
+ return true;
+}
+
+/* Read and validate the two generation keys. Extra store_meta keys belong to
+ * other store features and are deliberately ignored. */
+static int generation_metadata_read(cbm_store_t *s, bool *absent, char uid[17], char counter[21],
+ uint64_t *counter_value) {
+ *absent = false;
+ sqlite3_stmt *object = NULL;
+ int rc = sqlite3_prepare_v2(s->db,
+ "SELECT type FROM sqlite_schema WHERE name='store_meta' "
+ "AND type IN ('table','view') LIMIT 1;",
+ CBM_NOT_FOUND, &object, NULL);
+ if (rc != SQLITE_OK) {
+ store_set_error_sqlite(s, "store generation schema probe prepare");
+ return CBM_STORE_ERR;
+ }
+ rc = sqlite3_step(object);
+ if (rc == SQLITE_DONE) {
+ sqlite3_finalize(object);
+ *absent = true;
+ return CBM_STORE_OK;
+ }
+ if (rc != SQLITE_ROW) {
+ store_set_error_sqlite(s, "store generation schema probe");
+ sqlite3_finalize(object);
+ return CBM_STORE_ERR;
+ }
+ const char *object_type = (const char *)sqlite3_column_text(object, 0);
+ bool is_table = object_type && strcmp(object_type, "table") == 0;
+ sqlite3_finalize(object);
+ if (!is_table) {
+ store_set_error(s, "store generation metadata is not a table");
+ return CBM_STORE_ERR;
+ }
+
+ sqlite3_stmt *stmt = NULL;
+ rc = sqlite3_prepare_v2(s->db,
+ "SELECT k, v, typeof(v) FROM store_meta "
+ "WHERE k IN ('db_uid','mutation_gen') ORDER BY k;",
+ CBM_NOT_FOUND, &stmt, NULL);
+ if (rc != SQLITE_OK) {
+ store_set_error_sqlite(s, "store generation metadata prepare");
+ return CBM_STORE_ERR;
+ }
+ bool have_uid = false;
+ bool have_counter = false;
+ while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
+ const char *key = (const char *)sqlite3_column_text(stmt, 0);
+ const char *value = (const char *)sqlite3_column_text(stmt, 1);
+ const char *value_type = (const char *)sqlite3_column_text(stmt, 2);
+ if (!key || !value || !value_type || strcmp(value_type, "text") != 0) {
+ store_set_error(s, "store generation metadata has a non-text value");
+ sqlite3_finalize(stmt);
+ return CBM_STORE_ERR;
+ }
+ if ((size_t)sqlite3_column_bytes(stmt, 0) != strlen(key) ||
+ (size_t)sqlite3_column_bytes(stmt, 1) != strlen(value) ||
+ (size_t)sqlite3_column_bytes(stmt, 2) != strlen(value_type)) {
+ store_set_error(s, "store generation metadata contains an embedded NUL");
+ sqlite3_finalize(stmt);
+ return CBM_STORE_ERR;
+ }
+ if (strcmp(key, "db_uid") == 0 && !have_uid && generation_uid_is_canonical(value)) {
+ snprintf(uid, 17, "%s", value);
+ have_uid = true;
+ } else if (strcmp(key, "mutation_gen") == 0 && !have_counter &&
+ generation_counter_parse(value, counter_value)) {
+ snprintf(counter, 21, "%s", value);
+ have_counter = true;
+ } else {
+ store_set_error(s, "store generation metadata is malformed");
+ sqlite3_finalize(stmt);
+ return CBM_STORE_ERR;
+ }
+ }
+ if (rc != SQLITE_DONE) {
+ store_set_error_sqlite(s, "store generation metadata scan");
+ sqlite3_finalize(stmt);
+ return CBM_STORE_ERR;
+ }
+ sqlite3_finalize(stmt);
+ if (!have_uid || !have_counter) {
+ store_set_error(s, "store generation metadata is incomplete");
+ return CBM_STORE_ERR;
+ }
+ return CBM_STORE_OK;
+}
+
+int cbm_store_generation_advance(cbm_store_t *s) {
+ static const char savepoint[] = "SAVEPOINT cbm_generation_advance;";
+ static const char rollback[] = "ROLLBACK TO cbm_generation_advance;";
+ static const char release[] = "RELEASE cbm_generation_advance;";
+ if (!s || !s->db) {
+ return CBM_STORE_ERR;
+ }
+ int rc = SQLITE_OK;
+ if (exec_sql(s, savepoint) != CBM_STORE_OK) {
+ return CBM_STORE_ERR;
+ }
+
+ bool absent = false;
+ char uid[17] = {0};
+ char counter[21] = {0};
+ uint64_t counter_value = 0;
+ if (generation_metadata_read(s, &absent, uid, counter, &counter_value) != CBM_STORE_OK) {
+ return rollback_savepoint_preserving_error(s, rollback, release);
+ }
+ if (absent) {
+ if (sqlite3_exec(s->db,
+ "CREATE TABLE store_meta (k TEXT PRIMARY KEY, v TEXT NOT NULL);"
+ "INSERT INTO store_meta VALUES"
+ "('db_uid', lower(hex(randomblob(8))));"
+ "INSERT INTO store_meta VALUES('mutation_gen','0');",
+ NULL, NULL, NULL) != SQLITE_OK) {
+ store_set_error_sqlite(s, "store generation metadata create");
+ return rollback_savepoint_preserving_error(s, rollback, release);
+ }
+ if (generation_metadata_read(s, &absent, uid, counter, &counter_value) != CBM_STORE_OK ||
+ absent) {
+ if (absent) {
+ store_set_error(s, "store generation metadata create did not persist");
+ }
+ return rollback_savepoint_preserving_error(s, rollback, release);
+ }
+ }
+ if (counter_value == UINT64_MAX) {
+ store_set_error(s, "store generation mutation counter overflow");
+ return rollback_savepoint_preserving_error(s, rollback, release);
+ }
+
+ char next_counter[21];
+ snprintf(next_counter, sizeof(next_counter), "%llu", (unsigned long long)(counter_value + 1));
+ sqlite3_stmt *update = NULL;
+ if (sqlite3_prepare_v2(s->db, "UPDATE store_meta SET v=?1 WHERE k='mutation_gen' AND v=?2;",
+ CBM_NOT_FOUND, &update, NULL) != SQLITE_OK) {
+ store_set_error_sqlite(s, "store generation advance prepare");
+ return rollback_savepoint_preserving_error(s, rollback, release);
+ }
+ bind_text(update, SKIP_ONE, next_counter);
+ bind_text(update, ST_COL_2, counter);
+ rc = sqlite3_step(update);
+ sqlite3_finalize(update);
+ if (rc != SQLITE_DONE || sqlite3_changes(s->db) != 1) {
+ if (rc != SQLITE_DONE) {
+ store_set_error_sqlite(s, "store generation advance");
+ } else {
+ store_set_error(s, "store generation advance changed an unexpected row count");
+ }
+ return rollback_savepoint_preserving_error(s, rollback, release);
+ }
+ if (exec_sql(s, release) != CBM_STORE_OK) {
+ return rollback_savepoint_preserving_error(s, rollback, release);
+ }
+ return CBM_STORE_OK;
+}
+
int cbm_store_upsert_project(cbm_store_t *s, const char *name, const char *root_path) {
+ static const char savepoint[] = "SAVEPOINT cbm_upsert_project;";
+ static const char rollback[] = "ROLLBACK TO cbm_upsert_project;";
+ static const char release[] = "RELEASE cbm_upsert_project;";
+ if (!s || !s->db || exec_sql(s, savepoint) != CBM_STORE_OK) {
+ return CBM_STORE_ERR;
+ }
sqlite3_stmt *stmt =
prepare_cached(s, &s->stmt_upsert_project,
"INSERT INTO projects (name, indexed_at, root_path) VALUES (?1, ?2, ?3) "
"ON CONFLICT(name) DO UPDATE SET indexed_at=?2, root_path=?3;");
if (!stmt) {
- return CBM_STORE_ERR;
+ return rollback_savepoint_preserving_error(s, rollback, release);
}
char ts[CBM_SZ_64];
@@ -2194,53 +2395,42 @@ int cbm_store_upsert_project(cbm_store_t *s, const char *name, const char *root_
int rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE) {
store_set_error_sqlite(s, "upsert_project");
- return CBM_STORE_ERR;
+ sqlite3_reset(stmt);
+ return rollback_savepoint_preserving_error(s, rollback, release);
}
+ sqlite3_reset(stmt);
- /* Store generation for cursor staleness (pagination): db_uid is a random
- * identity minted once per DB FILE (a full reindex publishes a fresh file
- * via the writer, which carries no store_meta — the first upsert_project
- * on the opened store seeds a NEW uid, so cursors minted against the old
- * file can never validate against the rebuilt one, whose node ids all
- * differ). mutation_gen increments on every project upsert — the choke
- * point every index run (full, incremental, watcher) passes through.
- * Created here rather than in the byte-level writer: adding a table to
- * its hand-built sqlite_master is rootpage surgery for zero benefit. */
- (void)sqlite3_exec(s->db,
- "CREATE TABLE IF NOT EXISTS store_meta (k TEXT PRIMARY KEY, v TEXT);"
- "INSERT OR IGNORE INTO store_meta VALUES"
- "('db_uid', lower(hex(randomblob(8))));"
- "INSERT OR IGNORE INTO store_meta VALUES('mutation_gen','0');"
- "UPDATE store_meta SET v = CAST(CAST(v AS INTEGER)+1 AS TEXT) "
- "WHERE k='mutation_gen';",
- NULL, NULL, NULL);
+ if (cbm_store_generation_advance(s) != CBM_STORE_OK) {
+ return rollback_savepoint_preserving_error(s, rollback, release);
+ }
+ if (exec_sql(s, release) != CBM_STORE_OK) {
+ return rollback_savepoint_preserving_error(s, rollback, release);
+ }
return CBM_STORE_OK;
}
/* Opaque store generation for pagination cursors: "u<db_uid>g<mutation_gen>",
- * or "legacy" when the DB predates store_meta (read-only opens never create
- * it). A cursor whose embedded generation mismatches the store's current one
- * is stale — the graph may have changed under it. */
+ * or "legacy" only when the DB genuinely predates store_meta. */
int cbm_store_generation(cbm_store_t *s, char *buf, size_t bufsz) {
if (!s || !s->db || !buf || bufsz == 0) {
return CBM_STORE_ERR;
}
- snprintf(buf, bufsz, "legacy");
- sqlite3_stmt *stmt = NULL;
- if (sqlite3_prepare_v2(s->db,
- "SELECT (SELECT v FROM store_meta WHERE k='db_uid'),"
- " (SELECT v FROM store_meta WHERE k='mutation_gen');",
- CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
- return CBM_STORE_OK; /* pre-migration DB: stable "legacy" generation */
+ bool absent = false;
+ char uid[17] = {0};
+ char counter[21] = {0};
+ uint64_t counter_value = 0;
+ if (generation_metadata_read(s, &absent, uid, counter, &counter_value) != CBM_STORE_OK) {
+ buf[0] = '\0';
+ return CBM_STORE_ERR;
}
- if (sqlite3_step(stmt) == SQLITE_ROW) {
- const char *uid = (const char *)sqlite3_column_text(stmt, 0);
- const char *gen = (const char *)sqlite3_column_text(stmt, SKIP_ONE);
- if (uid && gen) {
- snprintf(buf, bufsz, "u%sg%s", uid, gen);
- }
+ (void)counter_value;
+ int written =
+ absent ? snprintf(buf, bufsz, "legacy") : snprintf(buf, bufsz, "u%sg%s", uid, counter);
+ if (written < 0 || (size_t)written >= bufsz) {
+ buf[0] = '\0';
+ store_set_error(s, "store generation output buffer is too small");
+ return CBM_STORE_ERR;
}
- sqlite3_finalize(stmt);
return CBM_STORE_OK;
}
diff --git a/src/store/store.h b/src/store/store.h
index dc1c2afce..b3acc1b0f 100644
--- a/src/store/store.h
+++ b/src/store/store.h
@@ -444,9 +444,17 @@ int cbm_store_checkpoint(cbm_store_t *s);
* connection, in bytes; -1 = unlimited (SQLite default / pre-fix). */
int64_t cbm_store_journal_size_limit(cbm_store_t *s);
+/* Advance the pagination-cursor generation atomically. Seeds a genuinely
+ * legacy database with a fresh per-file uid, preserves that uid thereafter,
+ * and increments its canonical uint64 mutation counter. Safe inside an
+ * existing transaction (implemented with a nested savepoint); malformed or
+ * partial metadata fails closed without committing a partial advance. */
+int cbm_store_generation_advance(cbm_store_t *s);
+
/* Opaque store generation for pagination-cursor staleness detection:
- * "u<db_uid>g<mutation_gen>" — db_uid is minted per DB file, mutation_gen
- * bumps on every index run. "legacy" for DBs predating store_meta. */
+ * "u<16-lower-hex-db_uid>g<canonical-uint64-mutation_gen>". Returns "legacy"
+ * only when store_meta is genuinely absent; malformed or missing metadata is
+ * an error. */
int cbm_store_generation(cbm_store_t *s, char *buf, size_t bufsz);
/* Seal a fully-written staging database before atomic publication.
diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c
index d83d4b205..cf40dd57a 100644
--- a/tests/test_pipeline.c
+++ b/tests/test_pipeline.c
@@ -1057,14 +1057,13 @@ static NamedEdgePropertyObservation observe_named_edge_callee_property(
}
observation.database_opened = true;
- static const char sql[] =
- "SELECT e.properties, json_valid(e.properties), "
- "CASE WHEN json_valid(e.properties) "
- "THEN json_extract(e.properties, '$.callee') END "
- "FROM edges e "
- "JOIN nodes src ON src.id=e.source_id AND src.project=e.project "
- "JOIN nodes tgt ON tgt.id=e.target_id AND tgt.project=e.project "
- "WHERE e.project=?1 AND e.type=?2 AND src.name=?3 AND tgt.name=?4;";
+ static const char sql[] = "SELECT e.properties, json_valid(e.properties), "
+ "CASE WHEN json_valid(e.properties) "
+ "THEN json_extract(e.properties, '$.callee') END "
+ "FROM edges e "
+ "JOIN nodes src ON src.id=e.source_id AND src.project=e.project "
+ "JOIN nodes tgt ON tgt.id=e.target_id AND tgt.project=e.project "
+ "WHERE e.project=?1 AND e.type=?2 AND src.name=?3 AND tgt.name=?4;";
sqlite3_stmt *stmt = NULL;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK ||
sqlite3_bind_text(stmt, 1, project, -1, SQLITE_TRANSIENT) != SQLITE_OK ||
@@ -1752,13 +1751,13 @@ TEST(pipeline_call_reference_sequential_parallel_edge_set_parity) {
long_reference_name[0] = 'l';
long_reference_name[LONG_REFERENCE_NAME_LEN] = '\0';
char long_reference_source[1024];
- int long_reference_source_len = snprintf(
- long_reference_source, sizeof(long_reference_source),
- "package parity\n"
- "func %s() {}\n"
- "func longPropertiesReferenceAccept(callback func()) {}\n"
- "func longPropertiesReferenceSite() { longPropertiesReferenceAccept(%s) }\n",
- long_reference_name, long_reference_name);
+ int long_reference_source_len =
+ snprintf(long_reference_source, sizeof(long_reference_source),
+ "package parity\n"
+ "func %s() {}\n"
+ "func longPropertiesReferenceAccept(callback func()) {}\n"
+ "func longPropertiesReferenceSite() { longPropertiesReferenceAccept(%s) }\n",
+ long_reference_name, long_reference_name);
if (long_reference_source_len <= 0 ||
(size_t)long_reference_source_len >= sizeof(long_reference_source)) {
th_rmtree(tmp);
@@ -1946,18 +1945,18 @@ TEST(pipeline_call_reference_sequential_parallel_edge_set_parity) {
named_edge_count(sequential_store, sequential_project, "CALLS",
shadow_controls[i].source_name, shadow_controls[i].target_name);
}
- sequential_long_reference = named_edge_count(
- sequential_store, sequential_project, "CALL_REFERENCE", "longPropertiesReferenceSite",
- long_reference_name);
- sequential_long_usage = named_edge_count(sequential_store, sequential_project, "USAGE",
- "longPropertiesReferenceSite",
- long_reference_name);
- sequential_long_calls = named_edge_count(sequential_store, sequential_project, "CALLS",
- "longPropertiesReferenceSite",
- long_reference_name);
+ sequential_long_reference =
+ named_edge_count(sequential_store, sequential_project, "CALL_REFERENCE",
+ "longPropertiesReferenceSite", long_reference_name);
+ sequential_long_usage =
+ named_edge_count(sequential_store, sequential_project, "USAGE",
+ "longPropertiesReferenceSite", long_reference_name);
+ sequential_long_calls =
+ named_edge_count(sequential_store, sequential_project, "CALLS",
+ "longPropertiesReferenceSite", long_reference_name);
sequential_long_property = observe_named_edge_callee_property(
- sequential_db_path, sequential_project, "CALL_REFERENCE",
- "longPropertiesReferenceSite", long_reference_name, long_reference_name);
+ sequential_db_path, sequential_project, "CALL_REFERENCE", "longPropertiesReferenceSite",
+ long_reference_name, long_reference_name);
cbm_store_close(sequential_store);
}
cbm_pipeline_free(sequential);
@@ -1995,9 +1994,9 @@ TEST(pipeline_call_reference_sequential_parallel_edge_set_parity) {
named_edge_count(parallel_store, parallel_project, "CALLS",
shadow_controls[i].source_name, shadow_controls[i].target_name);
}
- parallel_long_reference = named_edge_count(
- parallel_store, parallel_project, "CALL_REFERENCE", "longPropertiesReferenceSite",
- long_reference_name);
+ parallel_long_reference =
+ named_edge_count(parallel_store, parallel_project, "CALL_REFERENCE",
+ "longPropertiesReferenceSite", long_reference_name);
parallel_long_usage = named_edge_count(parallel_store, parallel_project, "USAGE",
"longPropertiesReferenceSite", long_reference_name);
parallel_long_calls = named_edge_count(parallel_store, parallel_project, "CALLS",
@@ -2477,8 +2476,8 @@ static void closure_probe_repo(const char *tmp) {
}
/* Fresh full reference build of the same tree into its own DB. */
-static void closure_fresh_full(const char *tmp, const char *db_path, int *out_nodes,
- int *out_edges, int *out_ref_edges, const char *project_hint) {
+static void closure_fresh_full(const char *tmp, const char *db_path, int *out_nodes, int *out_edges,
+ int *out_ref_edges, const char *project_hint) {
*out_nodes = -1;
*out_edges = -2;
*out_ref_edges = -3;
@@ -2495,9 +2494,9 @@ static void closure_fresh_full(const char *tmp, const char *db_path, int *out_no
if (store) {
*out_nodes = cbm_store_count_nodes(store, project);
*out_edges = cbm_store_count_edges(store, project);
- *out_ref_edges = named_edge_to_file_count(store, project, "CALL_REFERENCE",
- "closureProbeCaller", "closureProbeHelper",
- "lib.ts");
+ *out_ref_edges =
+ named_edge_to_file_count(store, project, "CALL_REFERENCE", "closureProbeCaller",
+ "closureProbeHelper", "lib.ts");
cbm_store_close(store);
}
}
@@ -2582,8 +2581,8 @@ TEST(pipeline_closure_repair_body_edit_converges_with_fresh_full) {
ASSERT_NOT_NULL(store);
repaired_nodes = cbm_store_count_nodes(store, project);
repaired_edges = cbm_store_count_edges(store, project);
- repaired_refs = named_edge_to_file_count(store, project, "CALL_REFERENCE",
- "closureProbeCaller", "closureProbeHelper", "lib.ts");
+ repaired_refs = named_edge_to_file_count(store, project, "CALL_REFERENCE", "closureProbeCaller",
+ "closureProbeHelper", "lib.ts");
cbm_store_close(store);
char full_db[512];
@@ -2639,8 +2638,8 @@ TEST(pipeline_closure_repair_removed_def_drops_dependent_edge) {
int repaired_refs = -1;
cbm_store_t *store = cbm_store_open_path(db);
ASSERT_NOT_NULL(store);
- repaired_refs = named_edge_to_file_count(store, project, "CALL_REFERENCE",
- "closureProbeCaller", "closureProbeHelper", "lib.ts");
+ repaired_refs = named_edge_to_file_count(store, project, "CALL_REFERENCE", "closureProbeCaller",
+ "closureProbeHelper", "lib.ts");
int repaired_nodes = cbm_store_count_nodes(store, project);
int repaired_edges = cbm_store_count_edges(store, project);
cbm_store_close(store);
@@ -2883,8 +2882,7 @@ TEST(pipeline_incremental_tsconfig_alias_change_matches_fresh_full) {
* target_a.ts to target_b.ts. Since alias-config governance landed this
* runs as a closure repair, and the convergence assertions below now
* prove that route rather than being satisfied by a full rebuild. */
- ASSERT_EQ(cbm_pipeline_incremental_test_last_route(),
- CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
const char *incremental_project = cbm_pipeline_project_name(incremental);
cbm_store_t *incremental_store = cbm_store_open_path(incremental_db);
ASSERT_NOT_NULL(incremental_store);
@@ -2938,6 +2936,87 @@ TEST(pipeline_incremental_tsconfig_alias_change_matches_fresh_full) {
}
#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+static int read_published_generation(const char *db_path, char *out, size_t out_size) {
+ cbm_store_t *store = cbm_store_open_path_query(db_path);
+ if (!store) {
+ return CBM_STORE_ERR;
+ }
+ int rc = cbm_store_generation(store, out, out_size);
+ cbm_store_close(store);
+ return rc;
+}
+
+static bool split_published_generation(const char *generation, char uid[18],
+ unsigned long long *mutation) {
+ if (!generation || strlen(generation) < 19 || generation[0] != 'u' || generation[17] != 'g') {
+ return false;
+ }
+ memcpy(uid, generation, 17);
+ uid[17] = '\0';
+ char *end = NULL;
+ unsigned long long parsed = strtoull(generation + 18, &end, 10);
+ if (!end || end == generation + 18 || *end != '\0') {
+ return false;
+ }
+ *mutation = parsed;
+ return true;
+}
+
+/* Every published database must carry cursor-generation metadata. A complete
+ * replacement gets a fresh database identity; an isolated delta clones the
+ * live database and advances only its mutation counter. */
+TEST(pipeline_publication_stamps_full_and_delta_generations) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_cursor_generation_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def PublishedGeneration():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ cbm_pipeline_free(baseline);
+ char first[128];
+ ASSERT_EQ(read_published_generation(db_path, first, sizeof(first)), CBM_STORE_OK);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *replacement = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(replacement);
+ ASSERT_EQ(cbm_pipeline_run(replacement), 0);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ cbm_pipeline_free(replacement);
+ char second[128];
+ ASSERT_EQ(read_published_generation(db_path, second, sizeof(second)), CBM_STORE_OK);
+
+ write_temp_file(tmp, "generation.py", "def PublishedGeneration():\n return 2\n");
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *delta = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(delta);
+ ASSERT_EQ(cbm_pipeline_run(delta), 0);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
+ cbm_pipeline_free(delta);
+ char third[128];
+ ASSERT_EQ(read_published_generation(db_path, third, sizeof(third)), CBM_STORE_OK);
+
+ char first_uid[18];
+ char second_uid[18];
+ char third_uid[18];
+ unsigned long long first_mutation = 0;
+ unsigned long long second_mutation = 0;
+ unsigned long long third_mutation = 0;
+ ASSERT_TRUE(split_published_generation(first, first_uid, &first_mutation));
+ ASSERT_TRUE(split_published_generation(second, second_uid, &second_mutation));
+ ASSERT_TRUE(split_published_generation(third, third_uid, &third_mutation));
+ ASSERT_TRUE(strcmp(first_uid, second_uid) != 0);
+ ASSERT_STR_EQ(second_uid, third_uid);
+ ASSERT_TRUE(third_mutation > second_mutation);
+ th_rmtree(tmp);
+ cbm_pipeline_incremental_test_reset_faults();
+ PASS();
+}
+
static void observe_named_generation(const char *db_path, const char *project,
const char *before_name, const char *after_name,
int *before_count, int *after_count) {
@@ -3072,8 +3151,8 @@ TEST(pipeline_publication_never_uses_a_predictable_staging_path) {
static const char canary[] = "canary-must-survive\n";
char canary_path[PREDICTABLE_CANARIES][640];
for (int i = 0; i < PREDICTABLE_CANARIES; i++) {
- snprintf(canary_path[i], sizeof(canary_path[i]), "%s.stage.%ld.%d", db_path,
- (long)getpid(), i + 1);
+ snprintf(canary_path[i], sizeof(canary_path[i]), "%s.stage.%ld.%d", db_path, (long)getpid(),
+ i + 1);
ASSERT_EQ(th_write_file(canary_path[i], canary), 0);
}
@@ -6760,7 +6839,7 @@ TEST(pipeline_swift_cross_package_import) {
cbm_edge_t *edges = NULL;
int ec = 0;
ASSERT_EQ(cbm_store_find_edges_by_source_type(s, importer.id, "IMPORTS", &edges, &ec),
- CBM_STORE_OK);
+ CBM_STORE_OK);
bool found_exact_edge = false;
for (int i = 0; i < ec; i++) {
@@ -10269,17 +10348,16 @@ static const char *pkg_entries_entry_for(const cbm_pkg_entries_t *e, const char
* above for the full end-to-end proof. */
TEST(pkgmap_swift_targets_registers_module) {
- static const char src[] =
- "// swift-tools-version:5.9\n"
- "import PackageDescription\n"
- "let package = Package(\n"
- " name: \"Core\",\n"
- " targets: [.target(name: \"Core\", dependencies: [])]\n"
- ")\n";
+ static const char src[] = "// swift-tools-version:5.9\n"
+ "import PackageDescription\n"
+ "let package = Package(\n"
+ " name: \"Core\",\n"
+ " targets: [.target(name: \"Core\", dependencies: [])]\n"
+ ")\n";
cbm_pkg_entries_t entries;
cbm_pkg_entries_init(&entries);
- bool ok = cbm_pkgmap_try_parse("Package.swift", "Core/Package.swift", src,
- (int)strlen(src), &entries);
+ bool ok = cbm_pkgmap_try_parse("Package.swift", "Core/Package.swift", src, (int)strlen(src),
+ &entries);
ASSERT_TRUE(ok);
ASSERT_TRUE(pkg_entries_has_name(&entries, "Core"));
ASSERT_STR_EQ(pkg_entries_entry_for(&entries, "Core"), "Core/Sources/Core");
@@ -10300,8 +10378,8 @@ TEST(pkgmap_swift_products_do_not_register_alias) {
")\n";
cbm_pkg_entries_t entries;
cbm_pkg_entries_init(&entries);
- bool ok = cbm_pkgmap_try_parse("Package.swift", "Core/Package.swift", src,
- (int)strlen(src), &entries);
+ bool ok = cbm_pkgmap_try_parse("Package.swift", "Core/Package.swift", src, (int)strlen(src),
+ &entries);
ASSERT_TRUE(ok);
ASSERT_FALSE(pkg_entries_has_name(&entries, "CoreKit"));
ASSERT_TRUE(pkg_entries_has_name(&entries, "CoreImpl"));
@@ -10320,15 +10398,14 @@ TEST(pkgmap_swift_products_do_not_register_alias) {
* fixture in this file happens to follow `name:` with `dependencies:` or a
* comma, so this specific shape was previously untested and unnoticed. */
TEST(pkgmap_swift_target_name_immediately_before_close_paren) {
- static const char src[] =
- "let package = Package(\n"
- " name: \"Core\",\n"
- " targets: [.target(name: \"Core\")]\n"
- ")\n";
+ static const char src[] = "let package = Package(\n"
+ " name: \"Core\",\n"
+ " targets: [.target(name: \"Core\")]\n"
+ ")\n";
cbm_pkg_entries_t entries;
cbm_pkg_entries_init(&entries);
- bool ok = cbm_pkgmap_try_parse("Package.swift", "Core/Package.swift", src,
- (int)strlen(src), &entries);
+ bool ok = cbm_pkgmap_try_parse("Package.swift", "Core/Package.swift", src, (int)strlen(src),
+ &entries);
ASSERT_TRUE(ok);
ASSERT_TRUE(pkg_entries_has_name(&entries, "Core"));
ASSERT_STR_EQ(pkg_entries_entry_for(&entries, "Core"), "Core/Sources/Core");
@@ -10346,8 +10423,8 @@ TEST(pkgmap_swift_target_honors_literal_path) {
")\n";
cbm_pkg_entries_t entries;
cbm_pkg_entries_init(&entries);
- bool ok = cbm_pkgmap_try_parse("Package.swift", "Core/Package.swift", src,
- (int)strlen(src), &entries);
+ bool ok = cbm_pkgmap_try_parse("Package.swift", "Core/Package.swift", src, (int)strlen(src),
+ &entries);
ASSERT_TRUE(ok);
ASSERT_TRUE(pkg_entries_has_name(&entries, "Core"));
ASSERT_STR_EQ(pkg_entries_entry_for(&entries, "Core"), "Core/Vendor/CoreLegacy");
@@ -10361,16 +10438,15 @@ TEST(pkgmap_swift_target_honors_literal_path) {
* target entirely (fail closed), even though its `name:` is a valid
* literal. */
TEST(pkgmap_swift_target_computed_path_fails_closed) {
- static const char src[] =
- "let customPath = computePath()\n"
- "let package = Package(\n"
- " name: \"Core\",\n"
- " targets: [.target(name: \"Core\", path: customPath)]\n"
- ")\n";
+ static const char src[] = "let customPath = computePath()\n"
+ "let package = Package(\n"
+ " name: \"Core\",\n"
+ " targets: [.target(name: \"Core\", path: customPath)]\n"
+ ")\n";
cbm_pkg_entries_t entries;
cbm_pkg_entries_init(&entries);
- bool ok = cbm_pkgmap_try_parse("Package.swift", "Core/Package.swift", src,
- (int)strlen(src), &entries);
+ bool ok = cbm_pkgmap_try_parse("Package.swift", "Core/Package.swift", src, (int)strlen(src),
+ &entries);
ASSERT_TRUE(ok);
ASSERT_EQ(entries.count, 0);
cbm_pkg_entries_free(&entries);
@@ -10392,8 +10468,8 @@ TEST(pkgmap_swift_target_in_comment_or_string_not_registered) {
")\n";
cbm_pkg_entries_t entries;
cbm_pkg_entries_init(&entries);
- bool ok = cbm_pkgmap_try_parse("Package.swift", "App/Package.swift", src,
- (int)strlen(src), &entries);
+ bool ok =
+ cbm_pkgmap_try_parse("Package.swift", "App/Package.swift", src, (int)strlen(src), &entries);
ASSERT_TRUE(ok);
ASSERT_TRUE(pkg_entries_has_name(&entries, "App"));
ASSERT_FALSE(pkg_entries_has_name(&entries, "Decoy"));
@@ -10422,8 +10498,8 @@ TEST(pkgmap_swift_dependencies_do_not_leak_entries) {
")\n";
cbm_pkg_entries_t entries;
cbm_pkg_entries_init(&entries);
- bool ok = cbm_pkgmap_try_parse("Package.swift", "App/Package.swift", src,
- (int)strlen(src), &entries);
+ bool ok =
+ cbm_pkgmap_try_parse("Package.swift", "App/Package.swift", src, (int)strlen(src), &entries);
ASSERT_TRUE(ok);
ASSERT_TRUE(pkg_entries_has_name(&entries, "App"));
ASSERT_FALSE(pkg_entries_has_name(&entries, "Core"));
@@ -10438,18 +10514,17 @@ TEST(pkgmap_swift_dependencies_do_not_leak_entries) {
* (Utils/UtilsPkg) name OTHER modules, not this manifest's own
* products/targets, so neither mints an entry. */
TEST(pkgmap_swift_target_name_dependency_does_not_leak_entry) {
- static const char src[] =
- "let package = Package(\n"
- " name: \"App\",\n"
- " targets: [.target(name: \"App\", dependencies: [\n"
- " \"Core\",\n"
- " .product(name: \"Utils\", package: \"UtilsPkg\")\n"
- " ])]\n"
- ")\n";
+ static const char src[] = "let package = Package(\n"
+ " name: \"App\",\n"
+ " targets: [.target(name: \"App\", dependencies: [\n"
+ " \"Core\",\n"
+ " .product(name: \"Utils\", package: \"UtilsPkg\")\n"
+ " ])]\n"
+ ")\n";
cbm_pkg_entries_t entries;
cbm_pkg_entries_init(&entries);
- bool ok = cbm_pkgmap_try_parse("Package.swift", "App/Package.swift", src,
- (int)strlen(src), &entries);
+ bool ok =
+ cbm_pkgmap_try_parse("Package.swift", "App/Package.swift", src, (int)strlen(src), &entries);
ASSERT_TRUE(ok);
ASSERT_TRUE(pkg_entries_has_name(&entries, "App"));
ASSERT_FALSE(pkg_entries_has_name(&entries, "Core"));
@@ -13687,6 +13762,7 @@ SUITE(pipeline_semantic_manifest_repro) {
RUN_TEST(pipeline_closure_repair_budget_declines_to_full);
RUN_TEST(pipeline_incremental_tsconfig_alias_change_matches_fresh_full);
#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ RUN_TEST(pipeline_publication_stamps_full_and_delta_generations);
RUN_TEST(pipeline_git_context_change_forces_full_and_refreshes_branch);
RUN_TEST(pipeline_global_extension_config_change_forces_full);
RUN_TEST(pipeline_publication_never_uses_a_predictable_staging_path);
diff --git a/tests/test_store_pragmas.c b/tests/test_store_pragmas.c
index 0d093589c..757d46363 100644
--- a/tests/test_store_pragmas.c
+++ b/tests/test_store_pragmas.c
@@ -143,6 +143,35 @@ TEST(store_generation_tracks_mutations) {
PASS();
}
+/* Existing store_meta is authoritative: a partially-written or malformed
+ * table is corruption, not a legacy database. Generation reads and the
+ * project-upsert mutation choke point must both fail closed, and a failed
+ * generation advance must not leave the project row committed. */
+TEST(store_generation_rejects_malformed_metadata_atomically) {
+ cbm_store_t *s = cbm_store_open_memory();
+ ASSERT_NOT_NULL(s);
+ ASSERT_EQ(cbm_store_exec(s, "CREATE TABLE store_meta (k TEXT PRIMARY KEY, v TEXT);"
+ "INSERT INTO store_meta VALUES('db_uid','0123456789abcdef');"),
+ CBM_STORE_OK);
+
+ char generation[128] = {0};
+ ASSERT_EQ(cbm_store_generation(s, generation, sizeof(generation)), CBM_STORE_ERR);
+ ASSERT_EQ(cbm_store_upsert_project(s, "must-not-commit", "/tmp/must-not-commit"),
+ CBM_STORE_ERR);
+ cbm_project_t project = {0};
+ ASSERT_EQ(cbm_store_get_project(s, "must-not-commit", &project), CBM_STORE_NOT_FOUND);
+
+ ASSERT_EQ(cbm_store_exec(s, "INSERT INTO store_meta VALUES('mutation_gen','not-a-number');"),
+ CBM_STORE_OK);
+ ASSERT_EQ(cbm_store_generation(s, generation, sizeof(generation)), CBM_STORE_ERR);
+ ASSERT_EQ(cbm_store_exec(s, "UPDATE store_meta SET v=CAST(X'31006a756e6b' AS TEXT) "
+ "WHERE k='mutation_gen';"),
+ CBM_STORE_OK);
+ ASSERT_EQ(cbm_store_generation(s, generation, sizeof(generation)), CBM_STORE_ERR);
+ cbm_store_close(s);
+ PASS();
+}
+
/* #896: a row-scan that dies mid-stream (SQLITE_CORRUPT) must surface a
* loud store error, not masquerade as a clean end of results. Counts are
* answered from covering indexes (still correct) while row fetches die at
@@ -236,6 +265,7 @@ TEST(corrupt_page_scan_returns_error_not_truncation) {
SUITE(store_pragmas) {
RUN_TEST(journal_size_limit_bounds_wal_issue1083);
RUN_TEST(store_generation_tracks_mutations);
+ RUN_TEST(store_generation_rejects_malformed_metadata_atomically);
RUN_TEST(corrupt_page_scan_returns_error_not_truncation);
RUN_TEST(mmap_size_default_when_unset);
RUN_TEST(mmap_size_zero_disables_mmap);