Skip to content

feat: migrate meta_filter and convert_conditions to Go - #15648

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
xugangqiang:feat/go-meta-filter
Jun 4, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
xugangqiang:feat/go-meta-filter

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

Migrate the metadata filtering utilities meta_filter and convert_conditions from common/metadata_utils.py to Go as pure functions with zero external dependencies.

These functions are used by dify/retrieval, openai/chat/completions, document_api, and chunk_api for filtering documents by metadata conditions.

Changes

  • New: internal/common/metadata_utils.go — ConvertConditions() and MetaFilter() with full operator support
  • New: internal/common/metadata_utils_test.go — 18 test cases covering all operators and edge cases

Supported Operators

=, ≠, >, <, ≥, ≤, contains, not contains, in, not in, start with, end with, empty, not empty

Design

  • Numeric comparison via strconv.ParseFloat
  • Date comparison via YYYY-MM-DD format detection
  • Case-insensitive string comparison fallback
  • and / or logic support for multiple conditions
  • Zero external dependencies — pure functions only

Testing

All 18 tests pass with zero mocking:

=== RUN   TestConvertConditions_OperatorMapping  --- PASS
=== RUN   TestConvertConditions_Nil              --- PASS
=== RUN   TestConvertConditions_Empty            --- PASS
=== RUN   TestMetaFilter_Equals                  --- PASS
=== RUN   TestMetaFilter_NumberEquals            --- PASS
=== RUN   TestMetaFilter_GreaterThan             --- PASS
... (all 18 pass)

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

Add MetaCondition type, ConvertConditions, and MetaFilter functions
to internal/common/metadata_utils.go as pure functions with zero
external dependencies.

Supported operators: =, ≠, >, <, ≥, ≤, contains, not contains,
in, not in, start with, end with, empty, not empty.

Numeric comparison (ParseFloat), date comparison (YYYY-MM-DT),
and case-insensitive string comparison are supported, matching
Python's logic.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@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

Adds metadata filtering utilities: ParseAndConvert normalizes API filter payloads into MetaFilterInput; MetaFilter evaluates those conditions against a MetaData index with operators for empty/contains/prefix/suffix/in and numeric/date/string comparisons, combining results with AND/OR logic.

Changes

Metadata Filtering

Layer / File(s) Summary
Condition types and parsing
internal/common/metadata_utils.go, internal/common/metadata_utils_test.go
Defines MetaCondition/MetaFilterInput, operator mapping, and ParseAndConvert to convert API payloads into normalized conditions; tests cover operator mapping, logic propagation, and nil/malformed inputs.
Filter evaluation and comparators
internal/common/metadata_utils.go, internal/common/metadata_utils_test.go
Implements MetaFilter, filterOut, matchValue, compareValues (date/number/string modes), and helpers (isDate, toString); tests exercise equality, numeric/date comparisons, substring/prefix/suffix, membership, empty/not-empty, AND/OR composition, missing-key, and nil/empty input cases.

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I hopped through metadata, swift and fleet,
Parsing conditions and matching each beat,
Dates, numbers, substrings — I sorted with cheer,
Docs found and returned, every match brought near,
A tiny rabbit reviewer, code-bug-free and sweet.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.53% 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 clearly and concisely summarizes the main change: migrating metadata filtering utilities from Python to Go.
Description check ✅ Passed The PR description provides excellent context, details the problem being solved, lists specific operators and design decisions, and includes test results.
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.

@xugangqiang xugangqiang added the ci Continue Integration label Jun 4, 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: 2

🧹 Nitpick comments (3)
internal/common/metadata_utils.go (1)

151-154: 💤 Low value

Remove no-op condition.

Lines 152-154 assign valStr = "" when valStr is already "" — this condition has no effect.

🧹 Proposed cleanup
 	valStr := toString(value)
-	if valStr == "" && value != nil {
-		valStr = ""
-	}
🤖 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 151 - 154, The if-block
checking "if valStr == \"\" && value != nil { valStr = \"\" }" is a no-op and
should be removed; locate the code that calls toString(value) (look for the
valStr variable and the toString function usage in metadata_utils.go) and simply
keep "valStr := toString(value)" without the redundant conditional so the
behavior is unchanged but the dead code is eliminated.
internal/common/metadata_utils_test.go (2)

129-155: ⚡ Quick win

Test coverage gap: case-sensitivity for contains/not contains not verified.

The tests for contains and not contains use matching-case values, so they don't verify the expected case-insensitive behavior. Consider adding cases like filtering "REPORT" against "report 2024" to catch regressions if case-insensitivity is intended.

🤖 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 129 - 155, Update the
tests to cover case-insensitivity for contains/not contains by adding variants
that use different casing (e.g., "REPORT" or "Report") against metadata values
like "report 2024"; modify or add assertions in TestMetaFilter_Contains and
TestMetaFilter_NotContains to assert the same results when Value has different
case, ensuring MetaFilter and MetaCondition are exercised for case-insensitive
matching.

56-271: ⚡ Quick win

Missing test coverage for in and not in operators.

The implementation supports in and not in operators (lines 165-182 in metadata_utils.go), but there are no tests verifying this functionality. Consider adding tests to validate list membership matching.

📝 Example test cases
func TestMetaFilter_In(t *testing.T) {
	metas := map[string]map[string][]string{
		"status": {
			"active":   {"doc1"},
			"pending":  {"doc2"},
			"archived": {"doc3"},
		},
	}
	filters := []MetaCondition{{Operator: "in", Key: "status", Value: []interface{}{"active", "pending"}}}
	result := MetaFilter(metas, filters, "and")
	if len(result) != 2 {
		t.Errorf("expected 2 docs, got %d: %v", len(result), result)
	}
}

func TestMetaFilter_NotIn(t *testing.T) {
	metas := map[string]map[string][]string{
		"status": {
			"active":   {"doc1"},
			"archived": {"doc2"},
		},
	}
	filters := []MetaCondition{{Operator: "not in", Key: "status", Value: []interface{}{"archived"}}}
	result := MetaFilter(metas, filters, "and")
	if len(result) != 1 || result[0] != "doc1" {
		t.Errorf("expected [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 56 - 271, Add unit tests
in metadata_utils_test.go covering the "in" and "not in" operators: create
TestMetaFilter_In and TestMetaFilter_NotIn that build metas maps, construct
MetaCondition entries with Operator set to "in" and "not in" (Value as
[]interface{} containing the membership list), call MetaFilter(metas, filters,
"and") and assert the returned document IDs match expected results (e.g., two
docs for "in" and a single doc for "not in"); reference the MetaFilter function
and MetaCondition struct to locate where to add these tests.
🤖 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 156-183: The branch handling string operators in the switch for
operator (in metadata_utils.go) is inconsistent with the Python behavior: update
the "contains", "not contains", "in", and "not in" cases to perform
case-insensitive comparisons like "start with"/"end with" by normalizing both
input and value(s) to lower-case before comparing (use strings.ToLower on input
and valStr and on toString(item) for list elements) so that contains/not
contains/in/not in are all case-insensitive and behavior matches the Python
implementation.
- Around line 189-206: compareValues currently falls back to string comparison
when one side is a date and the other is not, producing false positives; change
the logic in compareValues so that after numeric parsing fails you check
date-ness: if isDate(a) and isDate(b) then use compareString(a, b, operator) as
before, but if exactly one of isDate(a) or isDate(b) is true return false
(skip/non-match) instead of falling back to case-insensitive string comparison;
keep the final fallback of compareString(strings.ToLower(a), strings.ToLower(b),
operator) for non-date strings and numeric cases handled by compareFloat,
referencing compareValues, isDate, compareString and compareFloat to locate the
code to modify.

---

Nitpick comments:
In `@internal/common/metadata_utils_test.go`:
- Around line 129-155: Update the tests to cover case-insensitivity for
contains/not contains by adding variants that use different casing (e.g.,
"REPORT" or "Report") against metadata values like "report 2024"; modify or add
assertions in TestMetaFilter_Contains and TestMetaFilter_NotContains to assert
the same results when Value has different case, ensuring MetaFilter and
MetaCondition are exercised for case-insensitive matching.
- Around line 56-271: Add unit tests in metadata_utils_test.go covering the "in"
and "not in" operators: create TestMetaFilter_In and TestMetaFilter_NotIn that
build metas maps, construct MetaCondition entries with Operator set to "in" and
"not in" (Value as []interface{} containing the membership list), call
MetaFilter(metas, filters, "and") and assert the returned document IDs match
expected results (e.g., two docs for "in" and a single doc for "not in");
reference the MetaFilter function and MetaCondition struct to locate where to
add these tests.

In `@internal/common/metadata_utils.go`:
- Around line 151-154: The if-block checking "if valStr == \"\" && value != nil
{ valStr = \"\" }" is a no-op and should be removed; locate the code that calls
toString(value) (look for the valStr variable and the toString function usage in
metadata_utils.go) and simply keep "valStr := toString(value)" without the
redundant conditional so the behavior is unchanged but the dead code is
eliminated.
🪄 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: 363ecbc3-f7b8-40c7-8b63-7692eeb7c7e8

📥 Commits

Reviewing files that changed from the base of the PR and between 423fb6f and 261a79c.

📒 Files selected for processing (2)
  • internal/common/metadata_utils.go
  • internal/common/metadata_utils_test.go

Comment thread internal/common/metadata_utils.go Resolved
Comment thread internal/common/metadata_utils.go Resolved
xugangqiang and others added 2 commits June 4, 2026 18:58
…taFilterInput

- Add MetaValueDocs, MetaData, MetaFilterInput types
- Replace ConvertConditions with ParseAndConvert (extracts logic too)
- Update MetaFilter to take MetaData + *MetaFilterInput
- Extract convertOperator as independent function
- Add nil/empty guard tests for MetaFilter

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…Python behavior)

When the filter value is in YYYY-MM-DD format but a metadata value
is not, Python's meta_filter skips that entry. Go was falling back
to string comparison, producing false positives.

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

@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 (2)
internal/common/metadata_utils_test.go (1)

111-339: ⚡ Quick win

Missing test coverage for several operators.

The test suite lacks coverage for the following operators:

  • in and not in (membership operators)
  • ≠ (not equal)
  • < (less than)
  • ≤ (less than or equal)

Adding tests for in/not in would be particularly valuable given they require []interface{} value handling.

🧪 Suggested test cases for missing operators
func TestMetaFilter_In(t *testing.T) {
	metas := MetaData{
		"status": {"active": {"doc1"}, "pending": {"doc2"}, "closed": {"doc3"}},
	}
	input := &MetaFilterInput{
		Conditions: []MetaCondition{{Operator: "in", Key: "status", Value: []interface{}{"active", "pending"}}},
	}
	result := MetaFilter(metas, input)
	if len(result) != 2 {
		t.Errorf("expected 2 docs, got %d: %v", len(result), result)
	}
}

func TestMetaFilter_NotIn(t *testing.T) {
	metas := MetaData{
		"status": {"active": {"doc1"}, "pending": {"doc2"}, "closed": {"doc3"}},
	}
	input := &MetaFilterInput{
		Conditions: []MetaCondition{{Operator: "not in", Key: "status", Value: []interface{}{"active", "pending"}}},
	}
	result := MetaFilter(metas, input)
	if len(result) != 1 || result[0] != "doc3" {
		t.Errorf("expected [doc3], got %v", result)
	}
}

func TestMetaFilter_NotEqual(t *testing.T) {
	metas := MetaData{
		"author": {"Zhang San": {"doc1"}, "Li Si": {"doc2"}},
	}
	input := &MetaFilterInput{
		Conditions: []MetaCondition{{Operator: "≠", Key: "author", Value: "Zhang San"}},
	}
	result := MetaFilter(metas, input)
	if len(result) != 1 || result[0] != "doc2" {
		t.Errorf("expected [doc2], got %v", result)
	}
}

func TestMetaFilter_LessThan(t *testing.T) {
	metas := MetaData{
		"score": {"85": {"doc1"}, "70": {"doc2"}, "92": {"doc3"}},
	}
	input := &MetaFilterInput{
		Conditions: []MetaCondition{{Operator: "<", Key: "score", Value: "80"}},
	}
	result := MetaFilter(metas, input)
	if len(result) != 1 || result[0] != "doc2" {
		t.Errorf("expected [doc2], 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 111 - 339, Add missing
unit tests exercising MetaFilter for membership and additional comparison
operators: create tests named TestMetaFilter_In, TestMetaFilter_NotIn,
TestMetaFilter_NotEqual (operator "≠"), TestMetaFilter_LessThan (operator "<")
and TestMetaFilter_LessThanOrEqual (operator "≤") that construct MetaFilterInput
with MetaCondition entries and assert expected document lists; ensure the in/not
in tests pass a Value of type []interface{} (e.g.,
[]interface{}{"active","pending"}) to validate slice handling, and reference the
MetaFilter, MetaFilterInput and MetaCondition types when creating the test cases
so the new tests mirror existing test style and exercise those operator code
paths.
internal/common/metadata_utils.go (1)

301-319: 💤 Low value

toString silently returns empty string for unhandled types.

When value is an unexpected type (e.g., int, []interface{}, or nested map), toString returns "". This silent fallback could cause surprising filter behavior—for example, an int value passed directly (not via JSON) would match as empty string.

Consider logging or returning an indicator when an unexpected type is encountered, or explicitly handling int types.

💡 Optional: Add int handling for completeness
 func toString(v interface{}) string {
 	if v == nil {
 		return ""
 	}
 	switch s := v.(type) {
 	case string:
 		return s
 	case float64:
 		return strconv.FormatFloat(s, 'f', -1, 64)
+	case int:
+		return strconv.Itoa(s)
+	case int64:
+		return strconv.FormatInt(s, 10)
 	case bool:
 		if s {
 			return "true"
 		}
 		return "false"
 	default:
 		return ""
 	}
 }
🤖 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 301 - 319, toString currently
returns an empty string for any unhandled type which silently breaks
comparisons; update the toString function to explicitly handle common missing
cases (at minimum int, int64, and uint variants) and for all other unexpected
types return a deterministic representation (e.g. use fmt.Sprint(v) or
json.Marshal fallback) or a sentinel like "<unsupported:typeName>" and
optionally log the unexpected type; modify the switch in toString to add cases
for int/int64/uint/etc. and a default branch that builds and returns a clear
string using fmt.Sprintf("%v", v) or the type name so callers won’t get a silent
empty string.
🤖 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/metadata_utils_test.go`:
- Around line 111-339: Add missing unit tests exercising MetaFilter for
membership and additional comparison operators: create tests named
TestMetaFilter_In, TestMetaFilter_NotIn, TestMetaFilter_NotEqual (operator "≠"),
TestMetaFilter_LessThan (operator "<") and TestMetaFilter_LessThanOrEqual
(operator "≤") that construct MetaFilterInput with MetaCondition entries and
assert expected document lists; ensure the in/not in tests pass a Value of type
[]interface{} (e.g., []interface{}{"active","pending"}) to validate slice
handling, and reference the MetaFilter, MetaFilterInput and MetaCondition types
when creating the test cases so the new tests mirror existing test style and
exercise those operator code paths.

In `@internal/common/metadata_utils.go`:
- Around line 301-319: toString currently returns an empty string for any
unhandled type which silently breaks comparisons; update the toString function
to explicitly handle common missing cases (at minimum int, int64, and uint
variants) and for all other unexpected types return a deterministic
representation (e.g. use fmt.Sprint(v) or json.Marshal fallback) or a sentinel
like "<unsupported:typeName>" and optionally log the unexpected type; modify the
switch in toString to add cases for int/int64/uint/etc. and a default branch
that builds and returns a clear string using fmt.Sprintf("%v", v) or the type
name so callers won’t get a silent empty string.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6222b9da-8050-428e-a80b-47686e2ac167

📥 Commits

Reviewing files that changed from the base of the PR and between 261a79c and 4287885.

📒 Files selected for processing (2)
  • internal/common/metadata_utils.go
  • internal/common/metadata_utils_test.go

@codecov

codecov Bot commented Jun 4, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15648   +/-   ##
=======================================
  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.

@wangq8
wangq8 merged commit 461c190 into infiniflow:main Jun 4, 2026
1 check passed
yingfeng pushed a commit that referenced this pull request Jun 4, 2026
…15656)

## Summary

Change `GetFlattedMetaByKBs` return type from `map[string]interface{}`
to strongly-typed `common.MetaData`.

**Depends on**: #15648 (provides `MetaData`, `MetaValueDocs` types)

### Changes
- `service/metadata.go`: Changed return type, removed type assertions
- `service/metadata_filter.go`: Updated all metadata function signatures
- `service/metadata_filter_test.go` (new): 12 test cases

### Bug fix
`applySingleCondition` used `.([]interface{})` assertions on `[]string`
data, silently breaking operators like `!=`, `contains`, `start with`,
etc.

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

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
@xugangqiang
xugangqiang deleted the feat/go-meta-filter 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