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
Improve MinHash quality: leaf-only tokens, structural weighting, unique trigram gate
Martin Vogel09ce20afc8cf
diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.cindex e4c0b4dc5..887c103d9 100644--- a/internal/cbm/extract_defs.c+++ b/internal/cbm/extract_defs.c@@ -36,7 +36,6 @@ static void compute_fingerprint(CBMExtractCtx *ctx, CBMDefinition *def, TSNode f/* Find the function body child */TSNode body = ts_node_child_by_field_name(func_node, TS_FIELD("body"));if (ts_node_is_null(body)) {- /* Some languages use "block" or the function itself as the body */body = func_node;}cbm_minhash_t result;diff --git a/src/simhash/minhash.c b/src/simhash/minhash.cindex 549d828da..5cdc0d970 100644--- a/src/simhash/minhash.c+++ b/src/simhash/minhash.c@@ -33,8 +33,15 @@ enum { AST_WALK_CAP = 2048 };/* Hex encoding constants */enum { HEX_CHARS_PER_U32 = 8, HEX_BASE = 16 };-/* Trigram window and minimum threshold */-enum { TRIGRAM_WINDOW = 2, MIN_TRIGRAM_COUNT = 3 };+/* Trigram constants */+enum { TRIGRAM_WINDOW = 2 };++/* Minimum unique structural trigrams for a meaningful fingerprint.+ * K/2 = 32 ensures most MinHash slots get populated from distinct features. */+enum { MIN_UNIQUE_TRIGRAMS = 32 };++/* Maximum structural weight per trigram (3 tokens × 1 each). */+enum { MAX_STRUCTURAL_WEIGHT = 3 };/* Hash truncation mask (uint64 → uint32) */enum { U32_MASK = 0xFFFFFFFF };@@ -42,6 +49,15 @@ enum { U32_MASK = 0xFFFFFFFF };/* Dynamic array growth constants */enum { BUCKET_INIT_CAP = 8, GROW_FACTOR = 2, ENTRY_INIT_CAP = 64, RESULT_INIT_CAP = 64 };+/* Maximum bucket size — skip oversized buckets (noise from trivially similar functions). */+enum { MAX_BUCKET_SIZE = 200 };++/* Seen-set for O(1) dedup during query (simple open-addressing hash table). */+enum { SEEN_SET_BITS = 14, SEEN_SET_SIZE = 16384, SEEN_SET_MASK = 16383 };++/* Knuth multiplicative hash constant for node_id → seen-set slot. */+enum { KNUTH_MULT = 2654435761ULL };+/* Maximum normalised tokens per function body. */enum { MAX_TOKENS = 4096 };@@ -97,7 +113,32 @@ static const char *normalise_node_type(const char *kind) {/* ── MinHash computation ─────────────────────────────────────────── */-/* Phase 1: Walk AST iteratively and collect normalised token types. */+/* Check if a normalised token is one of the generic types (I/S/N/T).+ * These carry no structural info — used to compute trigram weight. */+static bool is_normalised_token(const char *tok) {+ return tok[0] != '\0' && tok[SKIP_ONE] == '\0' &&+ (tok[0] == 'I' || tok[0] == 'S' || tok[0] == 'N' || tok[0] == 'T');+}++/* Compute structural weight of a trigram: count of non-normalised tokens (0-3).+ * Weight 0 = pure data manipulation (noise), weight 3 = rich control flow (signal). */+static int trigram_structural_weight(const char *a, const char *b, const char *c) {+ int w = 0;+ if (!is_normalised_token(a)) {+ w++;+ }+ if (!is_normalised_token(b)) {+ w++;+ }+ if (!is_normalised_token(c)) {+ w++;+ }+ return w;+}++/* Phase 1: Walk AST iteratively and collect normalised LEAF token types.+ * Leaf-only counting is language-agnostic: leaf nodes correspond to actual+ * source tokens, not grammar-internal structure that varies across parsers. */static int collect_ast_tokens(TSNode root, const char **tokens, int max_tokens) {int token_count = 0;TSNode stack[AST_WALK_CAP];@@ -107,16 +148,16 @@ static int collect_ast_tokens(TSNode root, const char **tokens, int max_tokens)while (top > 0 && token_count < max_tokens) {TSNode node = stack[--top];uint32_t child_count = ts_node_child_count(node);- const char *kind = ts_node_type(node);if (child_count == 0) {+ /* Leaf node — actual source token. Normalise and record. */+ const char *kind = ts_node_type(node);if (kind[0] != '\0') {tokens[token_count++] = normalise_node_type(kind);}} else {- if (kind[0] != '\0' && ts_node_is_named(node)) {- tokens[token_count++] = normalise_node_type(kind);- }+ /* Internal node — push children only (skip the node itself).+ * Structural info comes from leaf token patterns, not grammar nodes. */for (int i = (int)child_count - SKIP_ONE; i >= 0 && top < AST_WALK_CAP; i--) {stack[top++] = ts_node_child(node, (uint32_t)i);}@@ -125,31 +166,84 @@ static int collect_ast_tokens(TSNode root, const char **tokens, int max_tokens)return token_count;}-/* Phase 2: Hash trigrams from token sequence into MinHash signature. */+/* Phase 2: Hash trigrams into MinHash signature with structural weighting.+ *+ * - Skip weight-0 trigrams (all tokens are I/S/N/T — pure noise)+ * - Use repetition-based weighted MinHash: hash w times per seed for weight w+ * - Track unique trigrams via hash set; reject if < MIN_UNIQUE_TRIGRAMS+ *+ * Returns the number of unique structural trigrams processed. */+/* Unique-trigram set: open addressing on 64-bit hashes. */+enum { UNIQ_SET_SIZE = 4096, UNIQ_SET_MASK = 4095 };++typedef struct {+ uint64_t slots[UNIQ_SET_SIZE];+ int count;+} uniq_trig_set_t;++static void uniq_trig_init(uniq_trig_set_t *s) {+ memset(s->slots, 0, sizeof(s->slots));+ s->count = 0;+}++/* Insert a trigram hash. Returns true if newly inserted. */+static bool uniq_trig_insert(uniq_trig_set_t *s, uint64_t trig_hash) {+ uint64_t val = trig_hash | SKIP_ONE; /* ensure non-zero */+ uint32_t slot = (uint32_t)(trig_hash & UNIQ_SET_MASK);+ for (int probe = 0; probe < UNIQ_SET_SIZE; probe++) {+ uint32_t idx = (slot + (uint32_t)probe) & UNIQ_SET_MASK;+ if (s->slots[idx] == 0) {+ s->slots[idx] = val;+ s->count++;+ return true;+ }+ if (s->slots[idx] == val) {+ return false;+ }+ }+ return false;+}++/* Apply weighted MinHash for one trigram: hash w times per seed. */+static void weighted_minhash_update(cbm_minhash_t *out, const char *trigram, int len, int w) {+ for (int k = 0; k < CBM_MINHASH_K; k++) {+ for (int rep = 0; rep < w; rep++) {+ uint64_t seed = ((uint64_t)k * MAX_STRUCTURAL_WEIGHT) + (uint64_t)rep;+ uint64_t h = XXH3_64bits_withSeed(trigram, (size_t)len, seed);+ uint32_t h32 = (uint32_t)(h & U32_MASK);+ if (h32 < out->values[k]) {+ out->values[k] = h32;+ }+ }+ }+}+static int hash_trigrams(const char **tokens, int token_count, cbm_minhash_t *out) {for (int k = 0; k < CBM_MINHASH_K; k++) {out->values[k] = UINT32_MAX;}+ uniq_trig_set_t uniq;+ uniq_trig_init(&uniq);char trigram_buf[TRIGRAM_BUF_LEN];- int trigram_count = 0;for (int i = 0; i + TRIGRAM_WINDOW < token_count; i++) {- int len = snprintf(trigram_buf, sizeof(trigram_buf), "%s|%s|%s", tokens[i], tokens[i + 1],- tokens[i + 2]);- if (len <= 0 || (size_t)len >= sizeof(trigram_buf)) {+ int w =+ trigram_structural_weight(tokens[i], tokens[i + SKIP_ONE], tokens[i + TRIGRAM_WINDOW]);+ if (w == 0) {continue;}- trigram_count++;- for (int k = 0; k < CBM_MINHASH_K; k++) {- uint64_t h = XXH3_64bits_withSeed(trigram_buf, (size_t)len, (uint64_t)k);- uint32_t h32 = (uint32_t)(h & U32_MASK);- if (h32 < out->values[k]) {- out->values[k] = h32;- }++ int len = snprintf(trigram_buf, sizeof(trigram_buf), "%s|%s|%s", tokens[i],+ tokens[i + SKIP_ONE], tokens[i + TRIGRAM_WINDOW]);+ if (len <= 0 || (size_t)len >= sizeof(trigram_buf)) {+ continue;}++ uniq_trig_insert(&uniq, XXH3_64bits(trigram_buf, (size_t)len));+ weighted_minhash_update(out, trigram_buf, len, w);}- return trigram_count;+ return uniq.count;}bool cbm_minhash_compute(TSNode func_body, const char *source, int language, cbm_minhash_t *out) {@@ -166,8 +260,8 @@ bool cbm_minhash_compute(TSNode func_body, const char *source, int language, cbmreturn false;}- int trigram_count = hash_trigrams(tokens, token_count, out);- return trigram_count >= MIN_TRIGRAM_COUNT;+ int unique_structural = hash_trigrams(tokens, token_count, out);+ return unique_structural >= MIN_UNIQUE_TRIGRAMS;}/* ── Jaccard similarity ──────────────────────────────────────────── */@@ -304,17 +398,42 @@ void cbm_lsh_insert(cbm_lsh_index_t *idx, const cbm_lsh_entry_t *entry) {}}-/* Check if a node_id is already in the result buffer. */-static bool result_contains(const cbm_lsh_index_t *idx, int64_t node_id) {- for (int j = 0; j < idx->result_count; j++) {- if (idx->result_buf[j]->node_id == node_id) {- return true;+/* O(1) seen-set: open-addressing hash table on node_id for dedup. */+typedef struct {+ int64_t *slots;+ int cap;+} seen_set_t;++static void seen_set_init(seen_set_t *s) {+ s->slots = calloc(SEEN_SET_SIZE, sizeof(int64_t));+ s->cap = SEEN_SET_SIZE;+ /* 0 means empty — node_ids are always > 0 */+}++static bool seen_set_insert(seen_set_t *s, int64_t node_id) {+ if (!s->slots) {+ return false;+ }+ uint32_t idx = (uint32_t)(node_id * KNUTH_MULT) & SEEN_SET_MASK;+ for (int probe = 0; probe < SEEN_SET_SIZE; probe++) {+ uint32_t slot = (idx + (uint32_t)probe) & SEEN_SET_MASK;+ if (s->slots[slot] == 0) {+ s->slots[slot] = node_id;+ return true; /* inserted (was not present) */+ }+ if (s->slots[slot] == node_id) {+ return false; /* already present */}}- return false;+ return false; /* table full */+}++static void seen_set_free(seen_set_t *s) {+ free(s->slots);+ s->slots = NULL;}-/* Append a candidate to the result buffer, growing if needed. Returns false on OOM. */+/* Append a candidate to the result buffer, growing if needed. */static bool result_push(cbm_lsh_index_t *idx, const cbm_lsh_entry_t *candidate) {if (idx->result_count >= idx->result_cap) {int new_cap =@@ -340,17 +459,24 @@ void cbm_lsh_query(const cbm_lsh_index_t *idx, const cbm_minhash_t *fp,return;}- /* Cast away const for result buffer management — query is logically const */cbm_lsh_index_t *mut_idx = (cbm_lsh_index_t *)idx;mut_idx->result_count = 0;+ /* O(1) dedup via open-addressing hash set */+ seen_set_t seen;+ seen_set_init(&seen);+for (int b = 0; b < CBM_LSH_BANDS; b++) {uint32_t h = band_hash(fp, b);const lsh_bucket_t *bucket = &idx->bands[b][h];+ /* Skip oversized buckets — noise from trivially similar utility functions */+ if (bucket->count > MAX_BUCKET_SIZE) {+ continue;+ }for (int i = 0; i < bucket->count; i++) {const cbm_lsh_entry_t *candidate = &idx->entries[bucket->items[i]];- if (result_contains(idx, candidate->node_id)) {- continue;+ if (!seen_set_insert(&seen, candidate->node_id)) {+ continue; /* already seen */}if (!result_push(mut_idx, candidate)) {break;@@ -358,6 +484,7 @@ void cbm_lsh_query(const cbm_lsh_index_t *idx, const cbm_minhash_t *fp,}}+ seen_set_free(&seen);*out = mut_idx->result_buf;*count = mut_idx->result_count;}diff --git a/src/simhash/minhash.h b/src/simhash/minhash.hindex 7250cda37..301a611f1 100644--- a/src/simhash/minhash.h+++ b/src/simhash/minhash.h@@ -22,10 +22,12 @@* error on Jaccard — sufficient for a 0.95 threshold. */#define CBM_MINHASH_K 64-/* Minimum number of normalized AST body nodes required to compute a- * fingerprint. Functions shorter than this are skipped to prevent- * trivial getter/setter fingerprint explosion. */-#define CBM_MINHASH_MIN_NODES 10+/* Minimum number of leaf AST tokens required to compute a fingerprint.+ * Leaf-only counting is language-agnostic: leaf nodes correspond to+ * actual source tokens (identifiers, literals, keywords, operators),+ * not grammar-internal structure that varies across parsers.+ * 30 leaf tokens ≈ BigCloneBench standard of 50 raw source tokens. */+#define CBM_MINHASH_MIN_NODES 30/* Default Jaccard threshold for SIMILAR_TO edge emission. */#define CBM_MINHASH_JACCARD_THRESHOLD 0.95diff --git a/tests/test_simhash.c b/tests/test_simhash.cindex 671fd6e8d..c464dbd7d 100644--- a/tests/test_simhash.c+++ b/tests/test_simhash.c@@ -66,34 +66,138 @@ static int count_similar_to_edges(const cbm_gbuf_t *gb) {return count;}+/* Large Go function template for fingerprint tests. Must have enough+ * structural diversity (>= 32 unique structural trigrams) after leaf-only+ * tokenisation and normalisation. */+#define GO_VALIDATE_USER_SRC \+ "package main\n" \+ "import \"errors\"\n" \+ "import \"strings\"\n" \+ "func ValidateUser(u User) error {\n" \+ " if u.Name == \"\" {\n" \+ " return errors.New(\"name required\")\n" \+ " }\n" \+ " if len(u.Name) > 100 {\n" \+ " return errors.New(\"name too long\")\n" \+ " }\n" \+ " if u.Age < 0 {\n" \+ " return errors.New(\"invalid age\")\n" \+ " }\n" \+ " if u.Age > 200 {\n" \+ " return errors.New(\"age too high\")\n" \+ " }\n" \+ " if u.Email == \"\" {\n" \+ " return errors.New(\"email required\")\n" \+ " }\n" \+ " if !strings.Contains(u.Email, \"@\") {\n" \+ " return errors.New(\"invalid email\")\n" \+ " }\n" \+ " if u.Phone == \"\" {\n" \+ " return errors.New(\"phone required\")\n" \+ " }\n" \+ " if len(u.Phone) < 7 {\n" \+ " return errors.New(\"phone too short\")\n" \+ " }\n" \+ " if u.Country == \"\" {\n" \+ " return errors.New(\"country required\")\n" \+ " }\n" \+ " for _, c := range u.Tags {\n" \+ " if c == \"\" {\n" \+ " return errors.New(\"empty tag\")\n" \+ " }\n" \+ " }\n" \+ " return nil\n" \+ "}\n"++/* Same structure, different names/types — near-clone */+#define GO_VALIDATE_ORDER_SRC \+ "package main\n" \+ "import \"errors\"\n" \+ "import \"strings\"\n" \+ "func ValidateOrder(o Order) error {\n" \+ " if o.Title == \"\" {\n" \+ " return errors.New(\"title required\")\n" \+ " }\n" \+ " if len(o.Title) > 100 {\n" \+ " return errors.New(\"title too long\")\n" \+ " }\n" \+ " if o.Amount < 0 {\n" \+ " return errors.New(\"invalid amount\")\n" \+ " }\n" \+ " if o.Amount > 200 {\n" \+ " return errors.New(\"amount too high\")\n" \+ " }\n" \+ " if o.Status == \"\" {\n" \+ " return errors.New(\"status required\")\n" \+ " }\n" \+ " if !strings.Contains(o.Status, \"@\") {\n" \+ " return errors.New(\"invalid status\")\n" \+ " }\n" \+ " if o.Region == \"\" {\n" \+ " return errors.New(\"region required\")\n" \+ " }\n" \+ " if len(o.Region) < 7 {\n" \+ " return errors.New(\"region too short\")\n" \+ " }\n" \+ " if o.Vendor == \"\" {\n" \+ " return errors.New(\"vendor required\")\n" \+ " }\n" \+ " for _, c := range o.Items {\n" \+ " if c == \"\" {\n" \+ " return errors.New(\"empty item\")\n" \+ " }\n" \+ " }\n" \+ " return nil\n" \+ "}\n"++/* Completely different structure */+#define GO_HANDLE_REQUEST_SRC \+ "package main\n" \+ "import \"net/http\"\n" \+ "import \"encoding/json\"\n" \+ "import \"io\"\n" \+ "func HandleRequest(w http.ResponseWriter, r *http.Request) {\n" \+ " body, err := io.ReadAll(r.Body)\n" \+ " if err != nil {\n" \+ " http.Error(w, err.Error(), 400)\n" \+ " return\n" \+ " }\n" \+ " defer r.Body.Close()\n" \+ " var data map[string]interface{}\n" \+ " if err := json.Unmarshal(body, &data); err != nil {\n" \+ " http.Error(w, err.Error(), 400)\n" \+ " return\n" \+ " }\n" \+ " result := make(map[string]interface{})\n" \+ " for k, v := range data {\n" \+ " switch val := v.(type) {\n" \+ " case string:\n" \+ " result[k] = strings.ToUpper(val)\n" \+ " case float64:\n" \+ " result[k] = val * 2\n" \+ " default:\n" \+ " result[k] = v\n" \+ " }\n" \+ " }\n" \+ " w.Header().Set(\"Content-Type\", \"application/json\")\n" \+ " json.NewEncoder(w).Encode(result)\n" \+ "}\n"+/* ═══════════════════════════════════════════════════════════════════* Suite 1: MinHash Core* ═══════════════════════════════════════════════════════════════════ *//* Two identical Go functions must produce identical MinHash signatures. */TEST(minhash_identical_source_same_fingerprint) {- const char *src =- "package main\n"- "func Validate(u User) error {\n"- " if u.Name == \"\" {\n"- " return errors.New(\"name required\")\n"- " }\n"- " if u.Age < 0 {\n"- " return errors.New(\"invalid age\")\n"- " }\n"- " if u.Email == \"\" {\n"- " return errors.New(\"email required\")\n"- " }\n"- " return nil\n"- "}\n";+ const char *src = GO_VALIDATE_USER_SRC;CBMFileResult *r1 = extract_one(src, CBM_LANG_GO, "test", "a.go");CBMFileResult *r2 = extract_one(src, CBM_LANG_GO, "test", "b.go");ASSERT_NOT_NULL(r1);ASSERT_NOT_NULL(r2);- const CBMDefinition *d1 = find_def(r1, "Validate");- const CBMDefinition *d2 = find_def(r2, "Validate");+ const CBMDefinition *d1 = find_def(r1, "ValidateUser");+ const CBMDefinition *d2 = find_def(r2, "ValidateUser");ASSERT_NOT_NULL(d1);ASSERT_NOT_NULL(d2);ASSERT_NOT_NULL(d1->fingerprint);@@ -111,35 +215,8 @@ TEST(minhash_identical_source_same_fingerprint) {/* Renamed variables should produce the same fingerprint (identifiers normalised). */TEST(minhash_renamed_vars_same_fingerprint) {- const char *src_a =- "package main\n"- "func ValidateUser(u User) error {\n"- " if u.Name == \"\" {\n"- " return errors.New(\"name required\")\n"- " }\n"- " if u.Age < 0 {\n"- " return errors.New(\"invalid age\")\n"- " }\n"- " if u.Email == \"\" {\n"- " return errors.New(\"email required\")\n"- " }\n"- " return nil\n"- "}\n";-- const char *src_b =- "package main\n"- "func ValidateOrder(o Order) error {\n"- " if o.Title == \"\" {\n"- " return errors.New(\"title required\")\n"- " }\n"- " if o.Amount < 0 {\n"- " return errors.New(\"invalid amount\")\n"- " }\n"- " if o.Status == \"\" {\n"- " return errors.New(\"status required\")\n"- " }\n"- " return nil\n"- "}\n";+ const char *src_a = GO_VALIDATE_USER_SRC;+ const char *src_b = GO_VALIDATE_ORDER_SRC;CBMFileResult *ra = extract_one(src_a, CBM_LANG_GO, "test", "a.go");CBMFileResult *rb = extract_one(src_b, CBM_LANG_GO, "test", "b.go");@@ -166,38 +243,15 @@ TEST(minhash_renamed_vars_same_fingerprint) {/* Completely different function bodies → low Jaccard. */TEST(minhash_different_code_different_fingerprint) {- const char *src_a =- "package main\n"- "func Validate(u User) error {\n"- " if u.Name == \"\" {\n"- " return errors.New(\"name required\")\n"- " }\n"- " if u.Age < 0 {\n"- " return errors.New(\"invalid age\")\n"- " }\n"- " if u.Email == \"\" {\n"- " return errors.New(\"email required\")\n"- " }\n"- " return nil\n"- "}\n";-- const char *src_b =- "package main\n"- "import \"net/http\"\n"- "func HandleRequest(w http.ResponseWriter, r *http.Request) {\n"- " data := make(map[string]interface{})\n"- " for k, v := range r.URL.Query() {\n"- " data[k] = v[0]\n"- " }\n"- " json.NewEncoder(w).Encode(data)\n"- "}\n";+ const char *src_a = GO_VALIDATE_USER_SRC;+ const char *src_b = GO_HANDLE_REQUEST_SRC;CBMFileResult *ra = extract_one(src_a, CBM_LANG_GO, "test", "a.go");CBMFileResult *rb = extract_one(src_b, CBM_LANG_GO, "test", "b.go");ASSERT_NOT_NULL(ra);ASSERT_NOT_NULL(rb);- const CBMDefinition *da = find_def(ra, "Validate");+ const CBMDefinition *da = find_def(ra, "ValidateUser");const CBMDefinition *db = find_def(rb, "HandleRequest");ASSERT_NOT_NULL(da);ASSERT_NOT_NULL(db);@@ -215,33 +269,52 @@ TEST(minhash_different_code_different_fingerprint) {PASS();}-/* Same function with one added statement → high but not perfect Jaccard. */+/* Same function with one added check → high but not perfect Jaccard. */TEST(minhash_minor_edit_high_jaccard) {- const char *src_a =- "package main\n"- "func Process(x int) int {\n"- " if x < 0 {\n"- " return -1\n"- " }\n"- " if x > 100 {\n"- " return 100\n"- " }\n"- " result := x * 2\n"- " return result\n"- "}\n";+ const char *src_a = GO_VALIDATE_USER_SRC;+ /* ValidateUser with one extra check added at the end */const char *src_b ="package main\n"- "func Process(x int) int {\n"- " if x < 0 {\n"- " return -1\n"+ "import \"errors\"\n"+ "import \"strings\"\n"+ "func ValidateUser(u User) error {\n"+ " if u.Name == \"\" {\n"+ " return errors.New(\"name required\")\n"+ " }\n"+ " if len(u.Name) > 100 {\n"+ " return errors.New(\"name too long\")\n"+ " }\n"+ " if u.Age < 0 {\n"+ " return errors.New(\"invalid age\")\n"+ " }\n"+ " if u.Age > 200 {\n"+ " return errors.New(\"age too high\")\n"+ " }\n"+ " if u.Email == \"\" {\n"+ " return errors.New(\"email required\")\n"+ " }\n"+ " if !strings.Contains(u.Email, \"@\") {\n"+ " return errors.New(\"invalid email\")\n"+ " }\n"+ " if u.Phone == \"\" {\n"+ " return errors.New(\"phone required\")\n"+ " }\n"+ " if len(u.Phone) < 7 {\n"+ " return errors.New(\"phone too short\")\n"" }\n"- " if x > 100 {\n"- " return 100\n"+ " if u.Country == \"\" {\n"+ " return errors.New(\"country required\")\n"" }\n"- " result := x * 2\n"- " result = result + 1\n"- " return result\n"+ " for _, c := range u.Tags {\n"+ " if c == \"\" {\n"+ " return errors.New(\"empty tag\")\n"+ " }\n"+ " }\n"+ " if u.Active == false {\n"+ " return errors.New(\"user inactive\")\n"+ " }\n"+ " return nil\n""}\n";CBMFileResult *ra = extract_one(src_a, CBM_LANG_GO, "test", "a.go");@@ -249,8 +322,8 @@ TEST(minhash_minor_edit_high_jaccard) {ASSERT_NOT_NULL(ra);ASSERT_NOT_NULL(rb);- const CBMDefinition *da = find_def(ra, "Process");- const CBMDefinition *db = find_def(rb, "Process");+ const CBMDefinition *da = find_def(ra, "ValidateUser");+ const CBMDefinition *db = find_def(rb, "ValidateUser");ASSERT_NOT_NULL(da);ASSERT_NOT_NULL(db);ASSERT_NOT_NULL(da->fingerprint);@@ -291,41 +364,21 @@ TEST(minhash_empty_body_skipped) {PASS();}-/* Type annotations normalised: int vs long → same fingerprint. */+/* Type names normalised: User vs Order → same fingerprint (identifiers → "I"). */TEST(minhash_type_annotation_normalized) {- const char *src_a =- "package main\n"- "func Compute(x int, y int) int {\n"- " if x > y {\n"- " return x - y\n"- " }\n"- " if x < 0 {\n"- " return -x\n"- " }\n"- " result := x + y\n"- " return result\n"- "}\n";+ /* ValidateUser uses "User" type, ValidateOrder uses "Order" type.+ * Both should normalise identifiers to "I" and produce high Jaccard. */+ const char *src_a = GO_VALIDATE_USER_SRC;- const char *src_b =- "package main\n"- "func Compute(x int64, y int64) int64 {\n"- " if x > y {\n"- " return x - y\n"- " }\n"- " if x < 0 {\n"- " return -x\n"- " }\n"- " result := x + y\n"- " return result\n"- "}\n";+ const char *src_b = GO_VALIDATE_ORDER_SRC;CBMFileResult *ra = extract_one(src_a, CBM_LANG_GO, "test", "a.go");CBMFileResult *rb = extract_one(src_b, CBM_LANG_GO, "test", "b.go");ASSERT_NOT_NULL(ra);ASSERT_NOT_NULL(rb);- const CBMDefinition *da = find_def(ra, "Compute");- const CBMDefinition *db = find_def(rb, "Compute");+ const CBMDefinition *da = find_def(ra, "ValidateUser");+ const CBMDefinition *db = find_def(rb, "ValidateOrder");ASSERT_NOT_NULL(da);ASSERT_NOT_NULL(db);ASSERT_NOT_NULL(da->fingerprint);@@ -759,72 +812,51 @@ static int setup_sim_test_repo(void) {return -1;}- /* Near-clone: ValidateUser and ValidateOrder have same structure, different names */+ /* Near-clone: ValidateUser and ValidateOrder have same structure, different names.+ * Must be large enough (>= 30 leaf tokens, >= 32 unique structural trigrams). */th_write_file(TH_PATH(g_sim_tmpdir, "pkg/validation/user_validator.go"),"package validation\n"- "\n""import \"errors\"\n"- "\n"- "type User struct {\n"- " Name string\n"- " Age int\n"- " Email string\n"- "}\n"- "\n"+ "import \"strings\"\n""func ValidateUser(u User) error {\n"- " if u.Name == \"\" {\n"- " return errors.New(\"name required\")\n"- " }\n"- " if u.Age < 0 {\n"- " return errors.New(\"invalid age\")\n"- " }\n"- " if u.Email == \"\" {\n"- " return errors.New(\"email required\")\n"+ " if u.Name == \"\" { return errors.New(\"name required\") }\n"+ " if len(u.Name) > 100 { return errors.New(\"name too long\") }\n"+ " if u.Age < 0 { return errors.New(\"invalid age\") }\n"+ " if u.Age > 200 { return errors.New(\"age too high\") }\n"+ " if u.Email == \"\" { return errors.New(\"email required\") }\n"+ " if !strings.Contains(u.Email, \"@\") { return errors.New(\"invalid email\") }\n"+ " if u.Phone == \"\" { return errors.New(\"phone required\") }\n"+ " if len(u.Phone) < 7 { return errors.New(\"phone too short\") }\n"+ " if u.Country == \"\" { return errors.New(\"country required\") }\n"+ " for _, c := range u.Tags {\n"+ " if c == \"\" { return errors.New(\"empty tag\") }\n"" }\n"" return nil\n""}\n");th_write_file(TH_PATH(g_sim_tmpdir, "pkg/validation/order_validator.go"),"package validation\n"- "\n""import \"errors\"\n"- "\n"- "type Order struct {\n"- " Title string\n"- " Amount int\n"- " Status string\n"- "}\n"- "\n"+ "import \"strings\"\n""func ValidateOrder(o Order) error {\n"- " if o.Title == \"\" {\n"- " return errors.New(\"title required\")\n"- " }\n"- " if o.Amount < 0 {\n"- " return errors.New(\"invalid amount\")\n"- " }\n"- " if o.Status == \"\" {\n"- " return errors.New(\"status required\")\n"+ " if o.Title == \"\" { return errors.New(\"title required\") }\n"+ " if len(o.Title) > 100 { return errors.New(\"title too long\") }\n"+ " if o.Amount < 0 { return errors.New(\"invalid amount\") }\n"+ " if o.Amount > 200 { return errors.New(\"amount too high\") }\n"+ " if o.Status == \"\" { return errors.New(\"status required\") }\n"+ " if !strings.Contains(o.Status, \"@\") { return errors.New(\"invalid status\") }\n"+ " if o.Region == \"\" { return errors.New(\"region required\") }\n"+ " if len(o.Region) < 7 { return errors.New(\"region too short\") }\n"+ " if o.Vendor == \"\" { return errors.New(\"vendor required\") }\n"+ " for _, c := range o.Items {\n"+ " if c == \"\" { return errors.New(\"empty item\") }\n"" }\n"" return nil\n""}\n");- /* Completely different function */+ /* Completely different function — also large enough for fingerprinting */th_write_file(TH_PATH(g_sim_tmpdir, "pkg/handler/user_handler.go"),- "package handler\n"- "\n"- "import (\n"- " \"encoding/json\"\n"- " \"net/http\"\n"- ")\n"- "\n"- "func HandleUser(w http.ResponseWriter, r *http.Request) {\n"- " data := make(map[string]interface{})\n"- " for k, v := range r.URL.Query() {\n"- " data[k] = v[0]\n"- " }\n"- " w.Header().Set(\"Content-Type\", \"application/json\")\n"- " json.NewEncoder(w).Encode(data)\n"- "}\n");+ GO_HANDLE_REQUEST_SRC);/* Tiny function — should be skipped */th_write_file(TH_PATH(g_sim_tmpdir, "pkg/util/tiny_helper.go"),@@ -1060,24 +1092,20 @@ TEST(pipeline_minhash_incremental_new_clone) {/* Step 2: Add a new near-clone of ValidateUser */th_write_file(TH_PATH(g_sim_tmpdir, "pkg/validation/address_validator.go"),"package validation\n"- "\n""import \"errors\"\n"- "\n"- "type Address struct {\n"- " Street string\n"- " Zip int\n"- " City string\n"- "}\n"- "\n"+ "import \"strings\"\n""func ValidateAddress(a Address) error {\n"- " if a.Street == \"\" {\n"- " return errors.New(\"street required\")\n"- " }\n"- " if a.Zip < 0 {\n"- " return errors.New(\"invalid zip\")\n"- " }\n"- " if a.City == \"\" {\n"- " return errors.New(\"city required\")\n"+ " if a.Street == \"\" { return errors.New(\"street required\") }\n"+ " if len(a.Street) > 100 { return errors.New(\"street too long\") }\n"+ " if a.Zip < 0 { return errors.New(\"invalid zip\") }\n"+ " if a.Zip > 99999 { return errors.New(\"zip too high\") }\n"+ " if a.City == \"\" { return errors.New(\"city required\") }\n"+ " if !strings.Contains(a.City, \" \") { return errors.New(\"invalid city\") }\n"+ " if a.State == \"\" { return errors.New(\"state required\") }\n"+ " if len(a.State) < 2 { return errors.New(\"state too short\") }\n"+ " if a.Country == \"\" { return errors.New(\"country required\") }\n"+ " for _, c := range a.Lines {\n"+ " if c == \"\" { return errors.New(\"empty line\") }\n"" }\n"" return nil\n""}\n");