Skip to content

refactor: change GetFlattedMetaByKBs return type to common.MetaData - #15656

Merged
yingfeng merged 3 commits into
infiniflow:mainfrom
xugangqiang:feat/go-metadata-typed
Jun 4, 2026
Merged

yingfeng merged 3 commits into
infiniflow:mainfrom
xugangqiang:feat/go-metadata-typed

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

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]

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code labels Jun 4, 2026
@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR replaces untyped map[string]interface{} with the typed common.MetaData structure across metadata flattening and filtering, eliminating runtime type assertions and simplifying filter evaluation logic while maintaining the same operator semantics.

Changes

Metadata Type Safety Migration

Layer / File(s) Summary
Return type contract in GetFlattedMetaByKBs
internal/service/metadata.go
GetFlattedMetaByKBs signature returns common.MetaData instead of untyped map; import ragflow/internal/common and adjust empty-input early return to use typed constructor.
Flattened metadata container initialization
internal/service/metadata.go
Per-field value containers initialize as make(common.MetaValueDocs) with direct assignment, replacing generic map creation and type assertion patterns.
Filter function signature migration
internal/service/metadata_filter.go
GenMetaFilter, ApplyMetaFilter, and ApplyMetaDataFilter accept common.MetaData instead of untyped map; semi-auto path filteredMeta uses typed constructor.
Filter evaluation logic simplification
internal/service/metadata_filter.go
GenMetaFilter metadata structure construction iterates over typed value maps directly; applySingleCondition uses typed metadata lookups and directly appends document IDs, removing prior []interface{} conversions; operators include =, !=, contains, not contains, in, not in, start with, end with.
Comprehensive filter behavior tests
internal/service/metadata_filter_test.go
Unit tests validate ApplyMetaFilter across all operators, boolean combination modes (and, or), and edge cases (empty filters, missing metadata keys), with expected document ID assertions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#15648: Introduces the common.MetaData and common.MetaValueDocs types that this PR adopts throughout the metadata filtering layer.

Suggested reviewers

  • yingfeng
  • yuzhichang
  • JinHai-CN
  • Haruko386

Poem

🐰 Types bloom where chaos lay,
Maps transform throughout the day,
No assertions, clean and clear,
Metadata flows, precise and near,
Tests affirm what types declare! 🎯

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.41% 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 and concisely describes the main change: updating GetFlattedMetaByKBs to return the typed common.MetaData instead of map[string]interface{}.
Description check ✅ Passed The description covers the problem (type safety and bug fix), lists the changes clearly, identifies the refactoring type, and acknowledges dependencies.
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 and others added 2 commits June 4, 2026 20:41
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]>
@xugangqiang
xugangqiang force-pushed the feat/go-metadata-typed branch from d0e76ed to 6519d60 Compare June 4, 2026 12:43
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 4, 2026
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Jun 4, 2026
@xugangqiang xugangqiang added the ci Continue Integration label Jun 4, 2026
@xugangqiang
xugangqiang marked this pull request as draft June 4, 2026 12:54
@xugangqiang
xugangqiang marked this pull request as ready for review June 4, 2026 12:54

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

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 win

Negation 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.go Line 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 win

Add 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, and not in with 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

📥 Commits

Reviewing files that changed from the base of the PR and between 461c190 and 4db5f02.

📒 Files selected for processing (3)
  • internal/service/metadata.go
  • internal/service/metadata_filter.go
  • internal/service/metadata_filter_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 (461c190) to head (4db5f02).
⚠️ Report is 2 commits behind head on main.

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.
📢 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 96a4166 into infiniflow:main Jun 4, 2026
2 of 3 checks passed
yingfeng pushed a commit that referenced this pull request Jun 5, 2026
…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]>
hunnyboy1217 added a commit to hunnyboy1217/ragflow that referenced this pull request Jun 5, 2026
…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.
hunnyboy1217 added a commit to hunnyboy1217/ragflow that referenced this pull request Jun 8, 2026
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.
@xugangqiang
xugangqiang deleted the feat/go-metadata-typed branch August 12, 2026 10:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code 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