Repository navigation
feat: migrate meta_filter and convert_conditions to Go - #15648
Conversation
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]>
📝 WalkthroughWalkthroughAdds 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. ChangesMetadata Filtering
Estimated Code Review Effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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.
Actionable comments posted: 2
🧹 Nitpick comments (3)
internal/common/metadata_utils.go (1)
151-154: 💤 Low valueRemove no-op condition.
Lines 152-154 assign
valStr = ""whenvalStris 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 winTest coverage gap: case-sensitivity for
contains/not containsnot verified.The tests for
containsandnot containsuse 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 winMissing test coverage for
inandnot inoperators.The implementation supports
inandnot inoperators (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
📒 Files selected for processing (2)
internal/common/metadata_utils.gointernal/common/metadata_utils_test.go
…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]>
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/common/metadata_utils_test.go (1)
111-339: ⚡ Quick winMissing test coverage for several operators.
The test suite lacks coverage for the following operators:
inandnot in(membership operators)≠(not equal)<(less than)≤(less than or equal)Adding tests for
in/not inwould 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
toStringsilently returns empty string for unhandled types.When
valueis an unexpected type (e.g.,int,[]interface{}, or nestedmap),toStringreturns"". This silent fallback could cause surprising filter behavior—for example, anintvalue 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
inttypes.💡 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
📒 Files selected for processing (2)
internal/common/metadata_utils.gointernal/common/metadata_utils_test.go
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
…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]>
Summary
Migrate the metadata filtering utilities
meta_filterandconvert_conditionsfromcommon/metadata_utils.pyto Go as pure functions with zero external dependencies.These functions are used by
dify/retrieval,openai/chat/completions,document_api, andchunk_apifor filtering documents by metadata conditions.Changes
internal/common/metadata_utils.go—ConvertConditions()andMetaFilter()with full operator supportinternal/common/metadata_utils_test.go— 18 test cases covering all operators and edge casesSupported Operators
=,≠,>,<,≥,≤,contains,not contains,in,not in,start with,end with,empty,not emptyDesign
strconv.ParseFloatand/orlogic support for multiple conditionsTesting
All 18 tests pass with zero mocking:
Co-Authored-By: Claude Opus 4.8 [email protected]