Skip to content

feat: add KG scoring utilities - #15666

Merged
yingfeng merged 1 commit into
infiniflow:mainfrom
xugangqiang:feat/go-kg-scoring
Jun 5, 2026
Merged

yingfeng merged 1 commit into
infiniflow:mainfrom
xugangqiang:feat/go-kg-scoring

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

KG scoring utilities as pure functions.

…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]>
@xugangqiang xugangqiang added the ci Continue Integration label Jun 4, 2026
@xugangqiang
xugangqiang marked this pull request as ready for review June 4, 2026 13:50
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 4, 2026
@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

A 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.

Changes

Knowledge Graph Scoring Pipeline

Layer / File(s) Summary
KG Data Model and Type System
internal/common/kg_scoring.go
Seven exported types define the domain: KGEntity, NhopEntity, KGRelation, Edge, EdgeScore, ScoredEntity, and ScoredRelation, used throughout the scoring pipeline.
N-Hop Path Scoring
internal/common/kg_scoring.go, internal/common/kg_scoring_test.go
AnalyzeNHopPaths iterates N-hop neighbor paths to accumulate per-directed-edge similarity with hop-distance decay and PageRank weights. Tests cover basic two-hop cases, multiple contributing paths, and empty input.
Similarity Boosting and Relation Score Fusion
internal/common/kg_scoring.go, internal/common/kg_scoring_test.go
DoubleHitBoost amplifies entity similarities for type-set matches. FuseRelationScores combines N-hop edge scores with type-based endpoint signals into relation similarities and creates new relations for N-hop-discovered edges. Tests verify contribution aggregation, type boosting, and new relation creation.
Entity and Relation Ranking and Selection
internal/common/kg_scoring.go, internal/common/kg_scoring_test.go
SortAndTrimEntities and SortAndTrimRelations rank by sim * pagerank and truncate to top-N, with fallback defaults when limit is non-positive. Tests verify correct ordering and default behavior.
CSV Formatting and Token-Budgeted Output
internal/common/kg_scoring.go, internal/common/kg_scoring_test.go
NumTokensFromString estimates tokens via character heuristic. FormatEntitiesToCSV and FormatRelationsToCSV emit CSV rows while tracking token budget. extractDescription parses JSON-like description strings. BuildKGContent concatenates entity and relation CSVs with remaining-token tracking. Tests verify token budget enforcement, description extraction (JSON and plain text), and content assembly.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A graph of knowledge, ranked and refined,
With N-hop hops and boosts combined,
From entity to relation, CSV-bound,
Token budgets keep us earthbound,
Scoring flows through filters sound! 📊

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is incomplete. It lacks required sections from the template: no problem statement, no type of change selection, and minimal context for reviewers. Expand the description to include: (1) What problem does this PR solve with background context, and (2) Select the appropriate Type of change checkbox (New Feature applies here).
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding KG scoring utilities as a new feature.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (5)
internal/common/kg_scoring_test.go (1)

251-263: ⚡ Quick win

Use strings.Contains from the standard library.

The contains and containsStr helpers reimplement functionality already provided by strings.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") with strings.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 value

Remove 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 value

Remove pointless re-slicing of input parameter.

Line 233 (relations = relations[:i]) has the same issue as in FormatEntitiesToCSV—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 win

Consider using encoding/json for robust parsing.

The current string-based extraction is fragile and will fail on valid JSON containing:

  1. Escaped quotes in the description value: {"description": "He said \"hello\""}
  2. 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/json would 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 lift

Clarify PageRank handling for duplicate edges in AnalyzeNHopPaths

AnalyzeNHopPaths overwrites EdgeScore.PageRank for an existing (from,to) edge (es.PageRank = weights[i]) while accumulating Sim. This matches the upstream Python logic (rag/graphrag/search.py sets nhop_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 to max/avg PageRank 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

📥 Commits

Reviewing files that changed from the base of the PR and between 98f2a2e and 900c801.

📒 Files selected for processing (2)
  • internal/common/kg_scoring.go
  • internal/common/kg_scoring_test.go

@yingfeng
yingfeng merged commit bf6c091 into infiniflow:main Jun 5, 2026
1 check passed
yingfeng pushed a commit that referenced this pull request Jun 5, 2026
…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]>
@xugangqiang
xugangqiang deleted the feat/go-kg-scoring branch August 7, 2026 12:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants