Skip to content

feat: add KG entity/relation/community search functions - #15689

Merged
yingfeng merged 5 commits into
infiniflow:mainfrom
xugangqiang:feat/go-kg-search
Jun 5, 2026
Merged

yingfeng merged 5 commits into
infiniflow:mainfrom
xugangqiang:feat/go-kg-search

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

Knowledge Graph search functions for entity, relation, community report, and type-samples retrieval. Uses DocEngine.SelectFields (PR #15684) for KG-specific fields.

Functions

Function Description
SearchKGEntities Hybrid search over KG entities (dense + text + fusion)
SearchKGEntitiesByTypes Entity search filtered by entity_type_kwd
SearchKGRelations Hybrid search over KG relations
SearchKGCommunityReports Community report search by entity names
SearchKGTypeSamples Type→entities mapping for query_rewrite

Internal helpers

Helper Description
buildHybridExpr Shared dense+text+fusion expression construction
buildKGDenseExpr Wraps Embed() call for vector search
Parse* Convert raw chunks to typed structs

Testing

35 tests (pure function + mock integration)

Co-Authored-By: Claude Opus 4.8 [email protected]

xugangqiang and others added 5 commits June 5, 2026 11:34
This change eliminates the duplicate filtering implementation between
service.ApplyMetaFilter and common.MetaFilter by removing the
applySingleCondition adapter layer and consolidating all operator
handling into common.MetaFilter.

Key changes:
- Remove applySingleCondition (65 lines of inline switch logic)
- ApplyMetaFilter now converts MetaFilterCondition to MetaCondition
  and delegates directly to common.MetaFilter once per filter set
- Add filterSet: O(n+m) hash-map fast path for in/not in operators
  (replaces O(n*m) linear scan in matchValue)
- Export NormalizeOperator from common for operator alias mapping
  (includes ==, !=, >=, <=, is, not is aliases)

Bug fixes:
- contains/not contains: restored case-insensitive matching (ToLower)
- not in: restored case-insensitive matching (EqualFold)
- != with date filter: non-date metadata values now correctly
  match the != operator (they are not equal to the date)
- Added == to operatorMapping so both ParseAndConvert and
  convertToMetaCondition normalize it to =

Performance:
- in/not in: O(n*m) linear scan -> O(n+m) hash-map lookup via filterSet
- = operator delegates to common.MetaFilter (O(n) iteration for
  correctness/case-insensitivity, matching Python behavior)

Cleanup:
- Removed 18 lines of dead code (matchValue's in/not in branches
  bypassed by filterOut delegation)
- Fixed orphaned godoc comment for convertOperator (reordered with
  NormalizeOperator)
- Fixed filterSet doc comment: removed incorrect 'matching EqualFold'
  claim
- Completed convertToMetaCondition operator normalization comment

Tests: 60 tests (24 service + 36 common), all passing.
New tests cover ==, !=, >=, <=, >, <, empty, not empty operators
through ApplyMetaFilter; <, <=, !=, not-in-empty-list through
MetaFilter/filterSet.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This file was accidentally included in the previous commit via
git add internal/. The change was pre-existing in the working tree
but unrelated to the metadata filter refactoring.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
When f.Value is "A,,B" or "A, ,B", strings.Split produces empty
or whitespace-only entries. These are now filtered out after TrimSpace
to prevent unintended matches against empty-string metadata values.

Add 5 test cases:
- InEmptyParts: A,,B produces [A B]
- InOnlyWhitespaceParts: A, , ,B produces [A B]
- InAllEmptyParts: ,,, produces []
- NotInEmptyParts: A,,B produces [A B]
- InMixedSpaces: spaces around values preserve trimmed values

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…earch and tests

- KGEntity, KGRelation, KGCommunityReport types with Parse*Chunks helpers
- build*SearchRequest: pure request builders for entity/relation/community/type-samples
- buildHybridExpr: shared dense+text+fusion expression construction
- buildKGDenseExpr: wraps Embed() call for vector search
- Search* functions: thin wrappers over DocEngine.Search + Parse*Chunks
- Fix ParseKGTypeSamplesChunks stub: now parses JSON
- Fix NhopEntityNames stub: now parses n_hop_with_weight JSON
- 35 tests (pure function tests + mock integration tests)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@xugangqiang xugangqiang added the ci Continue Integration label Jun 5, 2026
@xugangqiang
xugangqiang marked this pull request as ready for review June 5, 2026 04:41
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors metadata filtering logic in the common layer (operator canonicalization, set-based in/not in handling, case-insensitive text matching, and date-mismatch semantics), propagates those changes through the service-layer filter API, and introduces a complete new knowledge graph search service with data types, query builders, parsers, and search entry points.

Changes

Metadata Filter Refactoring

Layer / File(s) Summary
Operator canonicalization and normalization
internal/common/metadata_utils.go, internal/common/metadata_utils_test.go
operatorMapping adds "==" → "=" conversion; convertOperator centralizes normalization logic; exported NormalizeOperator wrapper added. TestConvertOperator updated to verify the new mapping.
Set-based in/not in filtering
internal/common/metadata_utils.go, internal/common/metadata_utils_test.go
filterOut delegates "in"/"not in" operators to new filterSet function, which builds lookup sets for case-sensitive inclusion and case-insensitive exclusion, returning nil for non-list filter values. Tests cover basic/no-match/empty/case-sensitivity cases and invalid inputs.
Text comparison and date-mismatch semantics
internal/common/metadata_utils.go, internal/common/metadata_utils_test.go
matchValue now performs case-insensitive string containment/prefix/suffix checks and removes unreachable "in"/"not in" logic. Date-mismatch behavior changes: when filter value is a date but metadata is not, match returns true only for "≠" operator. Tests added for numeric comparisons and ≠.
Service-layer filter integration
internal/service/metadata_filter.go, internal/service/metadata_filter_test.go
ApplyMetaFilter refactored to convert each MetaFilterCondition to common.MetaCondition (with operator normalization and in/not in value parsing) and delegate to common.MetaFilter, removing manual doc-ID set merging. Tests added for operator aliases, numeric comparisons, empty/not-empty filtering, and convertToMetaCondition unit tests for value transformation.

Knowledge Graph Search Service

Layer / File(s) Summary
KG data types and dense expression building
internal/service/kg_search.go
Exports KGEntity, KGRelation, and KGCommunityReport structs with rank/weight/similarity fields. buildKGDenseExpr constructs dense embedding vectors from a model/question, handles nil/empty models, and builds cosine-distance dense match expressions with similarity ranking options.
Hybrid query and entity search builders
internal/service/kg_search.go
buildKGHybridExpr combines dense, text, and fusion match expressions with weighted-sum ranking. buildKGEntitySearchRequest constructs entity search with optional hybrid features, KG type filters, and field selection; buildKGEntitySearchRequestByType adds type keyword filtering.
Relation, community report, and type-samples builders
internal/service/kg_search.go
buildKGRelationSearchRequest includes optional hybrid matching for questions. buildKGCommunitySearchRequest filters by community report type, entity names, and orders by weight. buildKGTypeSamplesRequest retrieves ty2ents mapping with large fixed limit.
KG chunk parsing functions
internal/service/kg_search.go
ParseKGEntityChunks, ParseKGRelationChunks, ParseKGCommunityReportChunks, and ParseKGTypeSamplesChunks convert raw Elasticsearch chunks into typed KG structs, handling multiple field-shape variations, missing fields, nil inputs, and JSON parsing. NhopEntityNames decodes JSON path/weight arrays and deduplicates entity names.
Top-level search functions
internal/service/kg_search.go
SearchKGEntities, SearchKGEntitiesByTypes, SearchKGRelations, SearchKGCommunityReports, and SearchKGTypeSamples orchestrate request building, execute docEngine.Search, wrap errors with KG context, and return parsed results.
KG search tests
internal/service/kg_search_test.go
Unit tests for request builders (filters, limits, hybrid MatchExpr composition), chunk parsers (field shapes, nil/empty inputs, JSON decoding), NhopEntityNames deduplication, mock engine/driver for dense expression behavior, and integration-style tests for search functions with controlled mock responses.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#15648: Both PRs modify internal/common/metadata_utils.go around operator normalization (including ==→= and !=→≠ mappings) and "in"/"not in" filtering behavior, including changes to text/date comparison semantics.
  • infiniflow/ragflow#15656: Both PRs refactor metadata filtering—this PR updates operator normalization and filtering in common/metadata_utils.go, while the related PR updates service/metadata_filter.go to delegate condition evaluation to common.MetaFilter.

Suggested labels

size:L

Suggested reviewers

  • yingfeng
  • yuzhichang
  • JinHai-CN
  • Haruko386
  • qinling0210

🐰 A rabbit hops through the filter maze,
Now operators align in normalized phase,
Sets for "in", case-blind text so kind,
And knowledge graphs dancing, intertwined! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 41.58% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main changes: addition of KG entity/relation/community search functions, which aligns with the primary feature additions in kg_search.go.
Description check ✅ Passed The PR description covers the problem being solved, provides a table of new functions and helpers with descriptions, mentions testing coverage (35 tests), and indicates co-authorship. It aligns with the required template sections despite using a different format.
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.

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jun 5, 2026

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

Actionable comments posted: 1

🧹 Nitpick comments (7)
internal/service/kg_search.go (4)

87-87: 💤 Low value

Document rationale for fusion weights.

The hybrid fusion weights 0.05,0.95 heavily favor text retrieval (95%) over dense embeddings (5%). If this is intentional for KG entity matching (where exact name matches should dominate), consider adding a brief comment explaining the rationale.

🤖 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/service/kg_search.go` at line 87, Document why the fusion weights
favor text retrieval by adding a brief inline comment next to the FusionParams
declaration that sets map[string]interface{}{"weights": "0.05,0.95"} (in the
code that builds the search parameters, i.e., the FusionParams field). Explain
that 0.05/0.95 was chosen to prioritize exact/name-based text matches over dense
embeddings for KG entity matching (or note any alternative rationale), and
include a note about when/if these should be adjusted.

306-362: ⚡ Quick win

Consider adding input validation.

The search functions don't validate inputs such as:

  • Empty kbIDs slice (would result in searching all KBs or an error)
  • topN <= 0 (could cause unexpected behavior in ES queries)
  • Nil docEngine (would panic on .Search())

Consider adding defensive checks at the entry points, especially for public API functions.

📝 Example validation for SearchKGEntities
 func SearchKGEntities(ctx context.Context, docEngine engine.DocEngine, kbIDs []string, question string, embModel *modelModule.EmbeddingModel, topN int) ([]KGEntity, error) {
+	if len(kbIDs) == 0 {
+		return nil, fmt.Errorf("kbIDs cannot be empty")
+	}
+	if topN <= 0 {
+		return nil, fmt.Errorf("topN must be positive, got %d", topN)
+	}
 	dense, err := buildKGDenseExpr(embModel, question, topN)
🤖 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/service/kg_search.go` around lines 306 - 362, Add input validation
to the public search functions (SearchKGEntities, SearchKGEntitiesByTypes,
SearchKGRelations, SearchKGCommunityReports, SearchKGTypeSamples) to guard
against nil docEngine, empty kbIDs, and invalid topN (<=0); return a descriptive
error immediately if docEngine == nil, if len(kbIDs)==0 where a KB selection is
required, or if topN <= 0 (or normalize topN to a sensible default) so
downstream calls to docEngine.Search and build*Request functions cannot panic or
send bad queries. Use the function names above to locate each entry point and
apply the same checks consistently at the start of each function.

75-75: ⚡ Quick win

Consider making similarity threshold configurable.

The similarity threshold of 0.3 is hardcoded. Depending on the embedding model quality and use case, this threshold may need tuning. Consider parameterizing this value or documenting why 0.3 was chosen.

🤖 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/service/kg_search.go` at line 75, The hardcoded similarity value
(ExtraOptions: map[string]interface{}{"similarity": 0.3}) should be made
configurable: introduce a named parameter or field (e.g., SimilarityThreshold
float64) on the KG search config/constructor (such as the searcher struct or
New... function used in kg_search.go), default it to 0.3 when unset, read an
environment/config value or accept it from callers, and replace the hardcoded
literal with that variable when building ExtraOptions so callers can tune the
threshold without editing the code.

274-276: ⚡ Quick win

Potential duplicate entities in type samples.

When multiple chunks contain the same type, entities are appended without deduplication. For example, if two chunks both have "PERSON": ["Alice"], the result will contain ["Alice", "Alice"]. If deduplication is needed, consider using a map or checking for duplicates before appending.

🔧 Proposed fix to deduplicate entities
 		for typ, entities := range typeMap {
+			seen := make(map[string]bool)
+			for _, existing := range result[typ] {
+				seen[existing] = true
+			}
+			for _, e := range entities {
+				if !seen[e] {
+					result[typ] = append(result[typ], e)
+					seen[e] = true
+				}
+			}
-			result[typ] = append(result[typ], entities...)
 		}
🤖 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/service/kg_search.go` around lines 274 - 276, The merge loop appends
entities from typeMap into result without deduplication, causing duplicate
entity strings (e.g., "Alice") when the same type appears in multiple chunks;
modify the merging code that iterates over typeMap (the for typ, entities :=
range typeMap loop) to deduplicate before appending by tracking seen entities
per type (e.g., a map[string]map[string]struct{} or a map[string]set for each
typ), only adding entities not already present in result[typ], and then convert
back to the slice for result[typ]; ensure you update or reuse result[typ]’s
existing entries when checking the seen set so no duplicates are introduced.
internal/service/kg_search_test.go (2)

196-196: ⚡ Quick win

Fragile test: potential index out of bounds.

The test directly indexes [0] without verifying that ParseKGEntityChunks returned at least one entity. If the parsing logic changes or the input is modified, this will panic.

🛡️ Proposed fix
 func TestParseKGEntityChunks_ScoreFallback(t *testing.T) {
 	chunks := []map[string]interface{}{{"entity_kwd": "Test", "score": 0.75}}
-	if ParseKGEntityChunks(chunks)[0].Similarity != 0.75 {
-		t.Error("expected 0.75 from score field")
+	entities := ParseKGEntityChunks(chunks)
+	if len(entities) != 1 || entities[0].Similarity != 0.75 {
+		t.Errorf("expected one entity with similarity 0.75, got %v", entities)
 	}
 }
🤖 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/service/kg_search_test.go` at line 196, The test indexing
ParseKGEntityChunks(chunks)[0] is fragile and can panic if ParseKGEntityChunks
returns an empty slice; change the test to first assign the result to a variable
(e.g., entities := ParseKGEntityChunks(chunks)), assert or require that
len(entities) > 0, and only then check entities[0].Similarity == 0.75 (use the
existing testing/assert helper in kg_search_test.go to fail the test cleanly if
empty).

221-221: ⚡ Quick win

Fragile test: potential index out of bounds.

Same issue as the entity test - directly indexing [0] without length check.

🛡️ Proposed fix
 func TestParseKGRelationChunks_IntWeight(t *testing.T) {
 	chunks := []map[string]interface{}{{"from_entity_kwd": "A", "to_entity_kwd": "B", "weight_int": 3}}
-	if ParseKGRelationChunks(chunks)[0].Weight != 3 {
-		t.Error("expected weight 3")
+	relations := ParseKGRelationChunks(chunks)
+	if len(relations) != 1 || relations[0].Weight != 3 {
+		t.Errorf("expected one relation with weight 3, got %v", relations)
 	}
 }
🤖 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/service/kg_search_test.go` at line 221, The test is indexing
ParseKGRelationChunks(chunks)[0] without checking the slice length, risking an
index out of bounds; update the test to first assert the returned slice has the
expected length (e.g., len(ParseKGRelationChunks(chunks)) > 0 or compare to an
exact expected length) before accessing element 0, or capture the result into a
variable (e.g., rels := ParseKGRelationChunks(chunks)) and use require/if to
guard that rels has elements then assert rels[0].Weight == 3; reference the
ParseKGRelationChunks call and the Weight check in kg_search_test.go when making
the change.
internal/common/metadata_utils_test.go (1)

518-529: ⚡ Quick win

Add a mixed date/non-date ≠ regression test.

The new branch on Line 277 only returns true for ≠ when the filter value is a date and the metadata value is not. The suite still exercises the mixed-type path with > only, so this changed behavior can regress without a failing test.

Suggested test
+func TestMetaFilter_DateVsNonDate_NotEquals(t *testing.T) {
+	metas := MetaData{
+		"date_field": {"xyz": {"doc1"}, "2024-01-01": {"doc2"}},
+	}
+	input := &MetaFilterInput{
+		Conditions: []MetaCondition{{Operator: "≠", Key: "date_field", Value: "2024-01-01"}},
+	}
+	result := MetaFilter(metas, input)
+	if len(result) != 1 || result[0] != "doc1" {
+		t.Errorf("expected only non-date mismatch [doc1], got %v", result)
+	}
+}
🤖 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/metadata_utils_test.go` around lines 518 - 529, Add a
regression test to cover the mixed date/non-date path for the "≠" operator:
create a new test (e.g., TestMetaFilter_NotEquals_MixedDateNonDate) that calls
MetaFilter with a MetaData entry where the stored value is a non-date string and
the MetaFilterInput uses a date-formatted Value (and include the reverse case
too: stored value date, filter value non-date) using MetaCondition {Operator:
"≠", Key: "author", Value: "..."} to assert the expected document is returned;
this ensures MetaFilter's ≠ handling for mixed-type (date vs non-date) values is
exercised alongside existing TestMetaFilter_NotEquals and guards the new branch
added around line ~277.
🤖 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.

Inline comments:
In `@internal/common/metadata_utils.go`:
- Around line 205-208: filterSet currently expects value to be []interface{} and
returns nil for strings, causing inconsistent behavior between
service.convertToMetaCondition and common.ParseAndConvert; fix by centralizing
coercion so the MetaCondition shape is consistent: update ParseAndConvert to
detect "in"/"not in" operators and coerce cond["value"] (including
comma-separated strings like "A,B") into []interface{} (or alternatively add
coercion inside filterSet to accept string and split into []interface{}),
ensuring both ParseAndConvert and service.convertToMetaCondition produce the
same []interface{} shape used by filterSet and MetaCondition handling.

---

Nitpick comments:
In `@internal/common/metadata_utils_test.go`:
- Around line 518-529: Add a regression test to cover the mixed date/non-date
path for the "≠" operator: create a new test (e.g.,
TestMetaFilter_NotEquals_MixedDateNonDate) that calls MetaFilter with a MetaData
entry where the stored value is a non-date string and the MetaFilterInput uses a
date-formatted Value (and include the reverse case too: stored value date,
filter value non-date) using MetaCondition {Operator: "≠", Key: "author", Value:
"..."} to assert the expected document is returned; this ensures MetaFilter's ≠
handling for mixed-type (date vs non-date) values is exercised alongside
existing TestMetaFilter_NotEquals and guards the new branch added around line
~277.

In `@internal/service/kg_search_test.go`:
- Line 196: The test indexing ParseKGEntityChunks(chunks)[0] is fragile and can
panic if ParseKGEntityChunks returns an empty slice; change the test to first
assign the result to a variable (e.g., entities := ParseKGEntityChunks(chunks)),
assert or require that len(entities) > 0, and only then check
entities[0].Similarity == 0.75 (use the existing testing/assert helper in
kg_search_test.go to fail the test cleanly if empty).
- Line 221: The test is indexing ParseKGRelationChunks(chunks)[0] without
checking the slice length, risking an index out of bounds; update the test to
first assert the returned slice has the expected length (e.g.,
len(ParseKGRelationChunks(chunks)) > 0 or compare to an exact expected length)
before accessing element 0, or capture the result into a variable (e.g., rels :=
ParseKGRelationChunks(chunks)) and use require/if to guard that rels has
elements then assert rels[0].Weight == 3; reference the ParseKGRelationChunks
call and the Weight check in kg_search_test.go when making the change.

In `@internal/service/kg_search.go`:
- Line 87: Document why the fusion weights favor text retrieval by adding a
brief inline comment next to the FusionParams declaration that sets
map[string]interface{}{"weights": "0.05,0.95"} (in the code that builds the
search parameters, i.e., the FusionParams field). Explain that 0.05/0.95 was
chosen to prioritize exact/name-based text matches over dense embeddings for KG
entity matching (or note any alternative rationale), and include a note about
when/if these should be adjusted.
- Around line 306-362: Add input validation to the public search functions
(SearchKGEntities, SearchKGEntitiesByTypes, SearchKGRelations,
SearchKGCommunityReports, SearchKGTypeSamples) to guard against nil docEngine,
empty kbIDs, and invalid topN (<=0); return a descriptive error immediately if
docEngine == nil, if len(kbIDs)==0 where a KB selection is required, or if topN
<= 0 (or normalize topN to a sensible default) so downstream calls to
docEngine.Search and build*Request functions cannot panic or send bad queries.
Use the function names above to locate each entry point and apply the same
checks consistently at the start of each function.
- Line 75: The hardcoded similarity value (ExtraOptions:
map[string]interface{}{"similarity": 0.3}) should be made configurable:
introduce a named parameter or field (e.g., SimilarityThreshold float64) on the
KG search config/constructor (such as the searcher struct or New... function
used in kg_search.go), default it to 0.3 when unset, read an environment/config
value or accept it from callers, and replace the hardcoded literal with that
variable when building ExtraOptions so callers can tune the threshold without
editing the code.
- Around line 274-276: The merge loop appends entities from typeMap into result
without deduplication, causing duplicate entity strings (e.g., "Alice") when the
same type appears in multiple chunks; modify the merging code that iterates over
typeMap (the for typ, entities := range typeMap loop) to deduplicate before
appending by tracking seen entities per type (e.g., a
map[string]map[string]struct{} or a map[string]set for each typ), only adding
entities not already present in result[typ], and then convert back to the slice
for result[typ]; ensure you update or reuse result[typ]’s existing entries when
checking the seen set so no duplicates are introduced.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8dfa65c4-c5fd-4aa0-9a3c-7456ae72b695

📥 Commits

Reviewing files that changed from the base of the PR and between ee32d91 and 02362f8.

📒 Files selected for processing (6)
  • internal/common/metadata_utils.go
  • internal/common/metadata_utils_test.go
  • internal/service/kg_search.go
  • internal/service/kg_search_test.go
  • internal/service/metadata_filter.go
  • internal/service/metadata_filter_test.go

Comment on lines +205 to +208
func filterSet(v2docs MetaValueDocs, operator string, value interface{}) []string {
list, ok := value.([]interface{})
if !ok {
return nil

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

in/not in now depend on a value shape that ParseAndConvert still doesn't produce.

Line 206 fails closed unless value is []interface{}, but ParseAndConvert still passes raw cond["value"] through unchanged. That makes the same payload behave differently depending on the entry point: service.convertToMetaCondition will split "A,B" correctly, while common.ParseAndConvert will send a string here and silently match nothing. Please centralize the list coercion so both paths build the same MetaCondition shape.

🤖 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/metadata_utils.go` around lines 205 - 208, filterSet
currently expects value to be []interface{} and returns nil for strings, causing
inconsistent behavior between service.convertToMetaCondition and
common.ParseAndConvert; fix by centralizing coercion so the MetaCondition shape
is consistent: update ParseAndConvert to detect "in"/"not in" operators and
coerce cond["value"] (including comma-separated strings like "A,B") into
[]interface{} (or alternatively add coercion inside filterSet to accept string
and split into []interface{}), ensuring both ParseAndConvert and
service.convertToMetaCondition produce the same []interface{} shape used by
filterSet and MetaCondition handling.

@codecov

codecov Bot commented Jun 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (ee32d91) to head (02362f8).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15689   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yingfeng
yingfeng merged commit e629c02 into infiniflow:main Jun 5, 2026
1 check passed
@xugangqiang
xugangqiang deleted the feat/go-kg-search 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:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants