Repository navigation
refactor: change GetFlattedMetaByKBs return type to common.MetaData - #15656
Conversation
📝 WalkthroughWalkthroughThis PR replaces untyped ChangesMetadata Type Safety Migration
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
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 |
These tests verify the hidden bug fix where non-equal operators
(contains, start with, etc.) were silently returning empty results
due to []interface{} type assertion mismatches.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
d0e76ed to
6519d60
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/service/metadata_filter.go (1)
258-293:⚠️ Potential issue | 🟠 Major | ⚡ Quick winNegation operators return false positives for multi-valued metadata docs.
Line 259/271/289 currently include docs from “other values” instead of excluding docs that match the negated predicate. With flattened array metadata (see
internal/service/metadata.goLine 207 onward), one doc can exist in multiple buckets, so a doc containing the excluded value can still leak into results.💡 Suggested fix (doc-centric exclusion for negation)
func applySingleCondition(metaData common.MetaData, condition MetaFilterCondition) []string { @@ - var result []string + var result []string + addToSet := func(set map[string]struct{}, ids []string) { + for _, id := range ids { + set[id] = struct{}{} + } + } + allDocs := make(map[string]struct{}) + for _, ids := range valueMap { + addToSet(allDocs, ids) + } @@ case "!=", "≠": - for val, docIDs := range valueMap { - if val != value { - result = append(result, docIDs...) - } - } + excluded := make(map[string]struct{}) + addToSet(excluded, valueMap[value]) + for id := range allDocs { + if _, blocked := excluded[id]; !blocked { + result = append(result, id) + } + } @@ case "not contains": - for val, docIDs := range valueMap { - if !strings.Contains(strings.ToLower(val), strings.ToLower(value)) { - result = append(result, docIDs...) - } - } + excluded := make(map[string]struct{}) + for val, ids := range valueMap { + if strings.Contains(strings.ToLower(val), strings.ToLower(value)) { + addToSet(excluded, ids) + } + } + for id := range allDocs { + if _, blocked := excluded[id]; !blocked { + result = append(result, id) + } + } @@ case "not in": @@ - for val, docIDs := range valueMap { + excluded := make(map[string]struct{}) + for val, docIDs := range valueMap { if !excludeValues[strings.ToLower(val)] { - result = append(result, docIDs...) + continue } + addToSet(excluded, docIDs) + } + for id := range allDocs { + if _, blocked := excluded[id]; !blocked { + result = append(result, id) + } }🤖 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/metadata_filter.go` around lines 258 - 293, Negation branches are leaking docs because valueMap is flattened by value buckets; change negation logic to be doc-centric: for "!=", "≠", "not contains" and "not in" first build an excludedDocIDs set by scanning valueMap for buckets that match the negated predicate (e.g., equal to value, contains value, or any of the excluded values), then iterate over all docIDs across valueMap and append only those whose id is not in excludedDocIDs, using a seen map to deduplicate into result; for positive branches like "contains" and "in" keep the existing bucket-lookup but also dedupe result using a seen map. Ensure you reference and update the variables valueMap, value and result when implementing this change.
🧹 Nitpick comments (1)
internal/service/metadata_filter_test.go (1)
36-89: ⚡ Quick winAdd regression tests for multi-valued docs under negation operators.
Current cases use one value per doc per key, so they miss the false-positive path where a single doc belongs to both excluded and non-excluded value buckets. Add one case each for
!=,not contains, andnot inwith a multi-valued doc.Also applies to: 149-156
🤖 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/metadata_filter_test.go` around lines 36 - 89, Tests for negation operators miss cases where a single doc has multiple values for a key; update the tests that call ApplyMetaFilter (TestApplyMetaFilter_NotEquals, TestApplyMetaFilter_NotContains, TestApplyMetaFilter_NotIn) to include a multi-valued document that appears in both the excluded and non-excluded buckets (e.g., add a doc that maps to both "Zhang San" and "Li Si" for author, or "hello" and "goodbye" for title, or both "A" and "B" for category) and assert it is correctly excluded by the negation operator so you cover the false-positive path for !=, "not contains", and "not in".
🤖 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.
Outside diff comments:
In `@internal/service/metadata_filter.go`:
- Around line 258-293: Negation branches are leaking docs because valueMap is
flattened by value buckets; change negation logic to be doc-centric: for "!=",
"≠", "not contains" and "not in" first build an excludedDocIDs set by scanning
valueMap for buckets that match the negated predicate (e.g., equal to value,
contains value, or any of the excluded values), then iterate over all docIDs
across valueMap and append only those whose id is not in excludedDocIDs, using a
seen map to deduplicate into result; for positive branches like "contains" and
"in" keep the existing bucket-lookup but also dedupe result using a seen map.
Ensure you reference and update the variables valueMap, value and result when
implementing this change.
---
Nitpick comments:
In `@internal/service/metadata_filter_test.go`:
- Around line 36-89: Tests for negation operators miss cases where a single doc
has multiple values for a key; update the tests that call ApplyMetaFilter
(TestApplyMetaFilter_NotEquals, TestApplyMetaFilter_NotContains,
TestApplyMetaFilter_NotIn) to include a multi-valued document that appears in
both the excluded and non-excluded buckets (e.g., add a doc that maps to both
"Zhang San" and "Li Si" for author, or "hello" and "goodbye" for title, or both
"A" and "B" for category) and assert it is correctly excluded by the negation
operator so you cover the false-positive path for !=, "not contains", and "not
in".
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f5d2b1ff-20e7-491c-8222-cbf9a9c23d02
📒 Files selected for processing (3)
internal/service/metadata.gointernal/service/metadata_filter.gointernal/service/metadata_filter_test.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15656 +/- ##
=======================================
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:
|
…idate metadata filter pipeline (#15686) ## Summary This PR fixes case-sensitivity regressions introduced in #15656 and consolidates the metadata filtering pipeline by removing the duplicate `applySingleCondition` adapter layer. ### Bug fixes 1. **contains / not contains**: restored case-insensitive matching (was lost when `applySingleCondition` was replaced by `common.MetaFilter.matchValue` which lacked `strings.ToLower`) 2. **not in**: restored case-insensitive matching (was lost for same reason; uses `strings.EqualFold`) 3. **!= with date filter values**: non-date metadata values now correctly match the `≠` operator (a non-date value IS not equal to any date, but was returning false) ### Architecture 4. **Removed `applySingleCondition`** (65 lines) — the inline switch was a duplicate of `common.MetaFilter` logic. `ApplyMetaFilter` now converts conditions and delegates to `common.MetaFilter` once per filter set, eliminating ~25 lines of duplicate AND/OR merge logic. 5. **Added `filterSet`** — O(n+m) hash-map fast path for `in`/`not in` operators, replacing the O(n*m) linear scan in `matchValue`. 6. **Exported `NormalizeOperator`** from `common` for consistent operator alias handling. ### Cleanup 7. Removed 18 lines of dead code (`matchValue`'s `in`/`not in` branches already bypassed by `filterOut` delegation) 8. Fixed orphaned godoc comment for `convertOperator` 9. Fixed incorrect `filterSet` doc comment (claimed "matching EqualFold" but used `strings.ToLower`) 10. Completed `convertToMetaCondition` operator normalization documentation ### Testing - 60 tests (24 service + 36 common), all passing - New tests: `==`, `≠`, `>`, `<`, `≥`, `≤`, `empty`, `not empty` through `ApplyMetaFilter` - New tests: `<`, `≤`, `≠` through `MetaFilter`; `not-in-empty-list` through `filterSet` - All 18 `MetaFilter` tests pass; all 10 `filterSet` unit tests pass --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
…nfiniflow#15672) Applies the final-review feedback from Hz-186 and CodeRabbit, and adapts to the GetFlattedMetaByKBs → common.MetaData change merged from main (infiniflow#15656). Hz-186 — Python parity gaps: - metadata condition shape: the metadata_condition filter now goes through the canonical common.ParseAndConvert + common.MetaFilter (the Go port of Python convert_conditions + meta_filter). Conditions are read as {name, comparison_operator, value} with the Python operator mapping (is→=, not is→≠, >=→≥, <=→≤, !=→≠). This also fixes a compile break: after infiniflow#15656, GetFlattedMetaByKBs returns common.MetaData, which the old ApplyMetaFilter(map[string]interface{}) call site no longer accepted. The bespoke parseMetadataConditions helper is removed. - SSRF protection: the ?url= upload now mirrors Python assert_url_is_safe — scheme allowlist, host resolved, every resolved IP must be globally routable (loopback/private/link-local/multicast/unspecified/CGNAT rejected), and the validated IP is pinned in the dialer (re-validated on each redirect hop) to defeat DNS rebinding. CodeRabbit: - BatchUpdateDocumentMetadata: the "updated" counter no longer increments when a delete fails — a document is counted only when every requested operation (updates AND deletes) succeeds. - non-string metadata condition values (numbers, booleans) are now honoured via common.ParseAndConvert's interface{} value instead of being dropped. - UploadFromURL HTTP client: added connect (10s) and overall (30s) timeouts via a custom http.Client; the body is read one byte past the 100 MB cap so an oversized file is rejected rather than silently truncated by io.LimitReader. - UploadFromURL filename: derived filename is sanitized — directory components stripped, unsafe/control chars replaced, Windows reserved names rejected, length bounded, "download" fallback. - UploadInfo: a malformed multipart body now returns HTTP 400 instead of being silently ignored; a non-multipart request (http.ErrNotMultipart) stays benign so the ?url= path is unaffected.
Closes infiniflow#15671. Ports three document/metadata endpoints from Python to Go: POST /api/v1/documents/upload (UploadInfo) PATCH /api/v1/datasets/:dataset_id/documents/metadatas (UpdateDocumentMetadatas) POST /api/v1/datasets/:dataset_id/metadata/update (MetadataBatchUpdate) Files: internal/service/file.go, internal/service/document.go, internal/handler/document.go, internal/router/router.go. Incorporates the earlier review fixes: - metadata_condition filtering goes through the canonical common.ParseAndConvert + common.MetaFilter (Python convert_conditions/meta_filter parity; works with GetFlattedMetaByKBs' common.MetaData return type) - BatchUpdateDocumentMetadata counts a document only when every requested update AND delete succeeds - ?url= upload is SSRF-guarded (scheme allowlist, resolve host, reject non-public IPs, pin the validated IP), with client timeout, truncation detection, and filename sanitization - UploadInfo returns HTTP 400 on a malformed multipart body (benign for non-multipart / ?url= requests) Rebased onto latest main: collapsed the feature + review commits (and the intermediate merge that pulled in infiniflow#15656) into a single commit, resolving the import/interface conflicts with upstream's new artifact/preview/download document APIs.
Summary
Change
GetFlattedMetaByKBsreturn type frommap[string]interface{}to strongly-typedcommon.MetaData.Depends on: #15648 (provides
MetaData,MetaValueDocstypes)Changes
service/metadata.go: Changed return type, removed type assertionsservice/metadata_filter.go: Updated all metadata function signaturesservice/metadata_filter_test.go(new): 12 test casesBug fix
applySingleConditionused.([]interface{})assertions on[]stringdata, silently breaking operators like!=,contains,start with, etc.Co-Authored-By: Claude Opus 4.8 [email protected]