Repository navigation
feat: add KG scoring utilities - #15666
Conversation
…udget) - AnalyzeNHopPaths: decompose paths into edges with distance decay - DoubleHitBoost: boost entities found by both keyword and type search - FuseRelationScores: integrate N-hop and type boosts into relations - SortAndTrimEntities/Relations: sort by sim*pagerank, cap at topN - FormatEntitiesToCSV/FormatRelationsToCSV: CSV formatting with token budget - BuildKGContent: compose final KG result string - NumTokensFromString: simple token estimation - extractDescription: parse JSON-like descriptions Co-Authored-By: Claude Opus 4.8 <[email protected]>
📝 WalkthroughWalkthroughA new KG scoring module is added with N-hop path analysis, similarity boosting, relation score fusion, ranking by computed scores, and CSV serialization with token budgeting. The implementation includes a comprehensive test suite covering all major functions and edge cases. ChangesKnowledge Graph Scoring Pipeline
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (5)
internal/common/kg_scoring_test.go (1)
251-263: ⚡ Quick winUse
strings.Containsfrom the standard library.The
containsandcontainsStrhelpers reimplement functionality already provided bystrings.Contains, which is more efficient and idiomatic.♻️ Simplified replacement
-// contains checks if a string contains a substring. -func contains(s, substr string) bool { - return len(s) >= len(substr) && containsStr(s, substr) -} - -func containsStr(s, substr string) bool { - for i := 0; i <= len(s)-len(substr); i++ { - if s[i:i+len(substr)] == substr { - return true - } - } - return false -}Then replace calls like
contains(result, "Entity A desc")withstrings.Contains(result, "Entity A desc").🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/common/kg_scoring_test.go` around lines 251 - 263, The custom helpers contains and containsStr duplicate standard library behavior; remove those functions and replace their usages (calls to contains(...)) with strings.Contains from the strings package. Update imports to include "strings" where needed and ensure all references to contains or containsStr are replaced with strings.Contains(s, substr) to use the native, optimized implementation.internal/common/kg_scoring.go (4)
198-218: 💤 Low valueRemove pointless re-slicing of input parameter.
Line 211 (
entities = entities[:i]) re-slices the input parameter, but in Go this only changes the local variable and has no effect on the caller. Since the loop breaks immediately after, this line serves no purpose and should be removed.♻️ Suggested cleanup
tokens := NumTokensFromString(line) if maxToken-tokens <= 0 { - entities = entities[:i] break }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/common/kg_scoring.go` around lines 198 - 218, The code in FormatEntitiesToCSV needlessly re-slices the input parameter with entities = entities[:i] before breaking, which has no effect on the caller and is redundant; remove that re-slice line (the assignment referencing entities in FormatEntitiesToCSV) and keep the subsequent break and logic as-is so the loop stops when token limit is reached without mutating the input slice.
220-240: 💤 Low valueRemove pointless re-slicing of input parameter.
Line 233 (
relations = relations[:i]) has the same issue as inFormatEntitiesToCSV—it re-slices the local parameter variable with no effect on the caller and is never used afterward.♻️ Suggested cleanup
tokens := NumTokensFromString(line) if maxToken-tokens <= 0 { - relations = relations[:i] break }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/common/kg_scoring.go` around lines 220 - 240, In FormatRelationsToCSV, remove the pointless re-slicing of the input parameter (the statement relations = relations[:i]) and leave the loop control to simply break; locate the re-slice in the function FormatRelationsToCSV and delete that assignment so the function stops adding lines when tokens run out without mutating the local parameter.
254-282: ⚡ Quick winConsider using
encoding/jsonfor robust parsing.The current string-based extraction is fragile and will fail on valid JSON containing:
- Escaped quotes in the description value:
{"description": "He said \"hello\""}- The literal string
"description"appearing before the actual field:{"note": "the \"description\" field", "description": "real value"}While the comment acknowledges this is "simple extraction," using
encoding/jsonwould handle these edge cases correctly with minimal overhead.🔧 Proposed refactor using encoding/json
+import "encoding/json" + func extractDescription(desc string) string { if desc == "" { return "" } - // If the description looks like JSON, try to extract the "description" field desc = strings.TrimSpace(desc) if strings.HasPrefix(desc, "{") && strings.HasSuffix(desc, "}") { - // Simple extraction: find "description" key value - // This matches Python's json.loads(desc).get("description", "") behavior - idx := strings.Index(desc, `"description"`) - if idx >= 0 { - remain := desc[idx+len(`"description"`):] - colonIdx := strings.Index(remain, ":") - if colonIdx >= 0 { - valPart := strings.TrimSpace(remain[colonIdx+1:]) - if strings.HasPrefix(valPart, `"`) { - valPart = strings.TrimPrefix(valPart, `"`) - endQuote := strings.Index(valPart, `"`) - if endQuote >= 0 { - return valPart[:endQuote] - } - } - } - } + var obj map[string]interface{} + if err := json.Unmarshal([]byte(desc), &obj); err == nil { + if d, ok := obj["description"].(string); ok { + return d + } + } } return desc }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/common/kg_scoring.go` around lines 254 - 282, The string-based parsing in extractDescription is fragile; replace it with proper JSON parsing using encoding/json: attempt json.Unmarshal(desc, &map[string]interface{}) inside extractDescription, check for a "description" key and if present return its string value (cast safely), otherwise return "" (to match Python's json.loads(...).get("description","")); if unmarshal fails (not valid JSON) preserve existing behavior by returning the original desc; update function extractDescription to use this approach and handle errors safely.
74-93: 🏗️ Heavy liftClarify PageRank handling for duplicate edges in
AnalyzeNHopPaths
AnalyzeNHopPathsoverwritesEdgeScore.PageRankfor an existing(from,to)edge (es.PageRank = weights[i]) while accumulatingSim. This matches the upstream Python logic (rag/graphrag/search.pysetsnhop_pathes[(f, t)]["pagerank"] = wts[i]). Current Go tests don’t exercise repeated identical edges, so the “overwrite vs accumulate” behavior is consistent rather than an implementation bug—only change tomax/avgPageRank aggregation if duplicates are intended to contribute cumulatively.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/common/kg_scoring.go` around lines 74 - 93, AnalyzeNHopPaths currently accumulates Sim but overwrites EdgeScore.PageRank for duplicate edges (es.PageRank = weights[i]); decide intended aggregation semantics (keep overwrite, take max, or average) and implement it consistently in AnalyzeNHopPaths: if you want max use math.Max(es.PageRank, weights[i]); if you want average add a count field to EdgeScore (e.g., PageRankSum and PageRankCount), increment them per duplicate and compute PageRank=PageRankSum/PageRankCount after the loop (or compute streaming average). Update EdgeScore struct accordingly and add/update tests to cover repeated identical edges (use ent.NhopEnts, nbr.Path and nbr.Weights to locate the change).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/common/kg_scoring_test.go`:
- Around line 251-263: The custom helpers contains and containsStr duplicate
standard library behavior; remove those functions and replace their usages
(calls to contains(...)) with strings.Contains from the strings package. Update
imports to include "strings" where needed and ensure all references to contains
or containsStr are replaced with strings.Contains(s, substr) to use the native,
optimized implementation.
In `@internal/common/kg_scoring.go`:
- Around line 198-218: The code in FormatEntitiesToCSV needlessly re-slices the
input parameter with entities = entities[:i] before breaking, which has no
effect on the caller and is redundant; remove that re-slice line (the assignment
referencing entities in FormatEntitiesToCSV) and keep the subsequent break and
logic as-is so the loop stops when token limit is reached without mutating the
input slice.
- Around line 220-240: In FormatRelationsToCSV, remove the pointless re-slicing
of the input parameter (the statement relations = relations[:i]) and leave the
loop control to simply break; locate the re-slice in the function
FormatRelationsToCSV and delete that assignment so the function stops adding
lines when tokens run out without mutating the local parameter.
- Around line 254-282: The string-based parsing in extractDescription is
fragile; replace it with proper JSON parsing using encoding/json: attempt
json.Unmarshal(desc, &map[string]interface{}) inside extractDescription, check
for a "description" key and if present return its string value (cast safely),
otherwise return "" (to match Python's json.loads(...).get("description",""));
if unmarshal fails (not valid JSON) preserve existing behavior by returning the
original desc; update function extractDescription to use this approach and
handle errors safely.
- Around line 74-93: AnalyzeNHopPaths currently accumulates Sim but overwrites
EdgeScore.PageRank for duplicate edges (es.PageRank = weights[i]); decide
intended aggregation semantics (keep overwrite, take max, or average) and
implement it consistently in AnalyzeNHopPaths: if you want max use
math.Max(es.PageRank, weights[i]); if you want average add a count field to
EdgeScore (e.g., PageRankSum and PageRankCount), increment them per duplicate
and compute PageRank=PageRankSum/PageRankCount after the loop (or compute
streaming average). Update EdgeScore struct accordingly and add/update tests to
cover repeated identical edges (use ent.NhopEnts, nbr.Path and nbr.Weights to
locate the change).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 11169005-608c-4080-bc69-a53a7114984d
📒 Files selected for processing (2)
internal/common/kg_scoring.gointernal/common/kg_scoring_test.go
…ry_rewrite, community) (#15690) ## Summary `KGSearchRetrieval` composes entity search, type search, relation search, N-hop analysis, score fusion, LLM-based query\_rewrite, and community reports into a single synthetic chunk for KG-enhanced retrieval. ### Components | Component | Source | Status | |-----------|--------|--------| | Entity/relation/community search | Direct `DocEngine.Search` calls | ✅ | | N-hop analysis + score fusion | `common.AnalyzeNHopPaths` / `DoubleHitBoost` / `FuseRelationScores` | ✅ #15666 | | Query rewrite prompt + parser | `common.BuildQueryRewritePrompt` / `ParseQueryRewriteResponse` | ✅ #15669 | | Token budget | `common.BuildKGContent` + `NumTokensFromString` | ✅ #15666 | | LLM query rewrite integration | `queryRewrite` function with fallback | ✅ | ### Testing 11 tests (pure function + mock engine): ``` === RUN TestKgEntityFromChunk_Basic --- PASS === RUN TestKgEntityFromChunk_ScoreFallback --- PASS === RUN TestKgEntityFromChunk_MissingFields --- PASS === RUN TestKgRelationFromChunk_Basic --- PASS === RUN TestKgRelationFromChunk_MissingFrom --- PASS === RUN TestSearchKGTypeSamples_Success --- PASS === RUN TestSearchKGTypeSamples_Empty --- PASS === RUN TestKGSearchRetrieval_Basic --- PASS === RUN TestKGSearchRetrieval_NoEntities --- PASS === RUN TestQueryRewrite_Fallback --- PASS === RUN TestQueryRewrite_EmptyQuestion --- PASS ``` --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
KG scoring utilities as pure functions.