Skip to content

fix: avoid quadratic dedup in RAG merge paths - #18135

Merged
JinHai-CN merged 10 commits into
infiniflow:mainfrom
DeviousDrops:fix/quadratic-dedup-rag-merge-18025
Aug 20, 2026
Merged

JinHai-CN merged 10 commits into
infiniflow:mainfrom
DeviousDrops:fix/quadratic-dedup-rag-merge-18025

Conversation

@DeviousDrops

@DeviousDrops DeviousDrops commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #18025. Both merge paths deduplicated IDs by scanning a plain list (item not in list) inside a loop while appending — O(n²) per merge. Replaced with a set-backed seen check alongside the existing ordered list: same order, same dedup result, O(n).

  • rag/advanced_rag/tree_structured_query_decomposition_retrieval.py: chunk_id/doc_id merge in _async_update_chunk_info
  • rag/svr/task_executor_refactor/dataset_structure_merger.py:
    • _merge_bucket: chunk/doc/description/original-name merge
    • _merge_relations: chunk/doc/description merge
    • _cleanup_deleted_docs: the deleted_doc_ids membership filter had the same O(n²) list-scan pattern over the same per-row hot path as the other three, so it's included here rather than split into a follow-up PR

Follow-up fix 1: the set-backed rewrite requires values to be hashable, whereas the original list-based in checks tolerated any type. Malformed provenance (e.g. a chunk_id/doc_id/description that's a list or dict instead of a string) would now raise TypeError instead of being silently tolerated like before.

Follow-up fix 2: the first fix's repr() fallback for unhashable values was itself unsound — (a) two equal dicts with different key insertion order produce different repr() strings and were wrongly kept as separate entries, and (b) a genuine hashable value could collide with an unrelated malformed value whose repr() happened to equal it, silently dropping the genuine one. Replaced with a recursive canonical key (_canonicalize() + a _CanonKey wrapper type) that preserves dict/list equality semantics and can never collide with an unrelated plain value.

Follow-up fix 3: _canonicalize() itself tagged list and tuple identically (so a nested list/tuple pair with equal elements wrongly deduped together, despite list != tuple in Python) and only matched set, missing frozenset (a distinct type that compares equal to set by value). Gave tuple its own tag and unified set/frozenset under one.

Test plan

  • Randomized equivalence check (500 trials) confirming the set-backed rewrite produces identical output (order + dedup) to the original list-scan logic on inputs with duplicate/interleaved IDs
  • Regression tests added covering duplicate inputs, existing-ID overlap, order preservation, structure-bucket dedup, malformed/unhashable provenance values, dict-key-order equality, the repr()-collision case, and the list-vs-tuple type distinction:
    • test/unit_test/rag/advanced_rag/test_tree_structured_query_decomposition_retrieval.py
    • test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger_dedup.py
  • python -m py_compile on all changed/added files
  • Directly exercised the real _hashable_key/_canonicalize/_CanonKey implementation from both source files in isolation (heavy unrelated imports stubbed out) to confirm dict-order independence, list-order sensitivity, list/tuple distinction, set/frozenset equivalence, and no repr-collision
  • uv run pytest test/unit_test/rag/advanced_rag test/unit_test/rag/svr/task_executor_refactor (could not run locally — uv sync fails in this environment on an unrelated native build error in editdistance, pre-existing and unrelated to this change)

Replace list-membership scans (item not in list, O(n) per check) with
a set-backed seen check alongside the existing ordered list, so
dedup-while-merging is O(n) instead of O(n^2). Order and dedup
behavior are unchanged.

- tree_structured_query_decomposition_retrieval.py: chunk_id/doc_id
  merge in _async_update_chunk_info
- dataset_structure_merger.py: chunk/doc/description/original-name
  merge in _merge_bucket, chunk/doc/description merge in
  _merge_relations, and the deleted_doc_ids membership filter in
  _cleanup_deleted_docs (same O(n^2) pattern, confirmed to run over
  the same per-row hot path as the other three, so included here
  rather than split into a separate PR)
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Aug 11, 2026
@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Retrieval and dataset structure merge paths now use recursive canonicalization and normalized sets for duplicate detection. Ordered output remains unchanged. Deleted-document cleanup uses normalized membership checks and original values for datastore queries. Regression tests cover malformed and unhashable provenance values.

Changes

RAG merge deduplication

Layer / File(s) Summary
Retrieval result deduplication
rag/advanced_rag/tree_structured_query_decomposition_retrieval.py, test/unit_test/rag/advanced_rag/test_tree_structured_query_decomposition_retrieval.py
Recursive canonicalization supports unhashable values and prevents representation collisions. Chunk and document merging uses incrementally updated sets. Tests cover ordering, repeated merges, reordered dictionaries, nested sequences, and totals.
Structure aggregation and cleanup
rag/svr/task_executor_refactor/dataset_structure_merger.py, test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger_dedup.py
Entity and relation aggregation use normalized-key sets. Deleted-document cleanup separates normalized membership checks from datastore query values. Tests cover malformed values, relation fallbacks, live-document updates, and ghost cleanup.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related issues

  • infiniflow/ragflow#18025 — Covers set-backed deduplication in the same retrieval and merge paths, including unhashable provenance handling.

Possibly related PRs

Suggested labels: 🐞 bug, 🌈 python, ☯️ refactor

Poem

A rabbit sorts each chunk in line,
Canonical keys keep values aligned.
Sets reject repeats with care,
Ordered results stay where they were.
Ghost IDs vanish into clean air.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: replacing quadratic deduplication in RAG merge paths.
Description check ✅ Passed The description includes the required Summary section and provides clear context, scope, implementation details, and test results.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

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.

@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

🤖 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 `@rag/advanced_rag/tree_structured_query_decomposition_retrieval.py`:
- Around line 82-92: Make deduplication hashability-safe across all affected
merge paths. In
rag/advanced_rag/tree_structured_query_decomposition_retrieval.py lines 82-92,
normalize or validate chunk_id and doc_id before set construction and membership
checks. Apply the same handling to source chunk IDs, document IDs, and
descriptions in rag/svr/task_executor_refactor/dataset_structure_merger.py lines
333-357 and 426-443; make deleted-document set construction safe at lines
544-545 and current-document membership checks safe at line 585. Preserve
deduplication while preventing malformed unhashable values from raising
TypeError.
🪄 Autofix

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 Plus

Run ID: 8ac5110e-b5c3-4954-bab1-d18a58648f8c

📥 Commits

Reviewing files that changed from the base of the PR and between a0e091e and 08a4c16.

📒 Files selected for processing (2)
  • rag/advanced_rag/tree_structured_query_decomposition_retrieval.py
  • rag/svr/task_executor_refactor/dataset_structure_merger.py

)

Pin dedup + relative-order behavior across duplicate, interleaved, and
malformed inputs for the three merge functions touched by the O(n) fix,
so the O(n^2) list-scan pattern (or an order regression from a bare
set() swap) can't silently come back:

- _async_update_chunk_info (tree_structured_query_decomposition_retrieval.py)
- _merge_bucket / _merge_relations / _cleanup_deleted_docs
  (dataset_structure_merger.py)
…nfiniflow#18025)

The set-backed dedup swap made membership checks require __hash__,
where the old list-based `in` checks only required __eq__. A malformed
chunk_id/doc_id/description (e.g. a list or dict instead of a string,
from bad upstream data) would now raise TypeError instead of being
tolerated like before.

Add a small _hashable_key() helper (falls back to repr() for
unhashable values) and use it for every set-backed membership check
and insertion touched by the earlier fix, in both files. Output lists
still store the original values — only the dedup key changes.
Regression tests added for the unhashable-value case in each function.

@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

🤖 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 `@rag/svr/task_executor_refactor/dataset_structure_merger.py`:
- Around line 100-107: Update _hashable_key() in
rag/svr/task_executor_refactor/dataset_structure_merger.py:100-107 to use a
typed, recursive canonical key for JSON-like lists and dictionaries, preserving
equality regardless of dictionary insertion order and preventing collisions with
equal repr() strings. Add coverage in
rag/svr/task_executor_refactor/test_dataset_structure_merger_dedup.py:89-102,
:121-141, and :193-220, plus
rag/advanced_rag/test_tree_structured_query_decomposition_retrieval.py:84-105,
covering reordered dictionaries, string/repr collisions, and malformed entity,
description, relation, and cleanup-filter identifiers; update every other
_hashable_key() implementation in this PR consistently.
🪄 Autofix

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 Plus

Run ID: 070e352d-b492-4735-bb45-3c3b8d9b36f6

📥 Commits

Reviewing files that changed from the base of the PR and between 08a4c16 and 522171f.

📒 Files selected for processing (4)
  • rag/advanced_rag/tree_structured_query_decomposition_retrieval.py
  • rag/svr/task_executor_refactor/dataset_structure_merger.py
  • test/unit_test/rag/advanced_rag/test_tree_structured_query_decomposition_retrieval.py
  • test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger_dedup.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • rag/advanced_rag/tree_structured_query_decomposition_retrieval.py

repr() as a dedup key had two bugs: (1) equal dicts with different key
insertion order produced different repr() strings and were wrongly kept
as separate entries, and (2) a genuine hashable value (e.g. a string)
could collide with an unrelated malformed value whose repr() happened
to equal it, silently dropping the genuine one.

Replace it with _canonicalize(), which recursively converts dict/list/
set into a structural key (dict comparison order-independent, list
order-preserving), wrapped in a _CanonKey type so a canonicalized key
can never accidentally equal a plain hashable value. Applied to every
_hashable_key() site in both files. Added regression tests for
dict-key-order dedup and the repr-collision case in each affected
function (chunk merge, entity/relation bucket merge, cleanup filter).
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Aug 11, 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

🤖 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 `@rag/advanced_rag/tree_structured_query_decomposition_retrieval.py`:
- Around line 43-68: Update _canonicalize in
rag/advanced_rag/tree_structured_query_decomposition_retrieval.py:43-68 to use
distinct canonical tags for list and tuple values, and canonicalize both set and
frozenset through the same wrapped representation. Apply the identical canonical
representation in
rag/svr/task_executor_refactor/dataset_structure_merger.py:117-142 so
_hashable_key and related deduplication logic preserve equality semantics
consistently across retrieval, merging, and cleanup.
🪄 Autofix

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 Plus

Run ID: 24298fd8-cac1-436c-b213-5b87f7d76e22

📥 Commits

Reviewing files that changed from the base of the PR and between 522171f and 09d44b8.

📒 Files selected for processing (4)
  • rag/advanced_rag/tree_structured_query_decomposition_retrieval.py
  • rag/svr/task_executor_refactor/dataset_structure_merger.py
  • test/unit_test/rag/advanced_rag/test_tree_structured_query_decomposition_retrieval.py
  • test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger_dedup.py

…p key

_canonicalize() tagged both list and tuple as "__list__", so a nested
list and a nested tuple with equal elements produced the same dedup
key even though list != tuple in Python. It also only matched
isinstance(value, set), missing frozenset (a distinct, unrelated type
in CPython), so a nested frozenset and an equal-valued set produced
different keys even though frozenset == set by value.

Give tuple its own "__tuple__" tag and canonicalize set/frozenset
through the same "__set__" wrapped form, in both files. Added one
regression test per affected merge path pinning the list-vs-tuple
distinction.

@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 (1)
test/unit_test/rag/advanced_rag/test_tree_structured_query_decomposition_retrieval.py (1)

175-177: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Assert the merged identifiers and their order.

len(chunk_info["chunks"]) == 2 proves only that both entries remain. It does not prove that _async_update_chunk_info preserved the list value, tuple value, or first-seen order. Assert the identifier sequence directly.

The upstream helper appends the original chunk object for a new canonical key, so this test should verify that contract.

Suggested assertion
-    assert len(chunk_info["chunks"]) == 2
+    assert [chunk["chunk_id"]["ids"] for chunk in chunk_info["chunks"]] == [
+        ["a", "b"],
+        ("a", "b"),
+    ]
🤖 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
`@test/unit_test/rag/advanced_rag/test_tree_structured_query_decomposition_retrieval.py`
around lines 175 - 177, Strengthen the test for _async_update_chunk_info by
replacing the length-only assertion with a direct assertion of the expected
chunk identifier sequence. Verify that the merged result preserves the original
list/tuple values and their first-seen order, matching the helper’s behavior of
appending the original chunk object for each new canonical key.
🤖 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
`@test/unit_test/rag/advanced_rag/test_tree_structured_query_decomposition_retrieval.py`:
- Around line 175-177: Strengthen the test for _async_update_chunk_info by
replacing the length-only assertion with a direct assertion of the expected
chunk identifier sequence. Verify that the merged result preserves the original
list/tuple values and their first-seen order, matching the helper’s behavior of
appending the original chunk object for each new canonical key.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8a3e8841-e4cb-4915-8721-251fd20a7e6f

📥 Commits

Reviewing files that changed from the base of the PR and between 09d44b8 and c63c9fa.

📒 Files selected for processing (4)
  • rag/advanced_rag/tree_structured_query_decomposition_retrieval.py
  • rag/svr/task_executor_refactor/dataset_structure_merger.py
  • test/unit_test/rag/advanced_rag/test_tree_structured_query_decomposition_retrieval.py
  • test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger_dedup.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger_dedup.py
  • rag/advanced_rag/tree_structured_query_decomposition_retrieval.py
  • rag/svr/task_executor_refactor/dataset_structure_merger.py

len(chunks) == 2 only proves both entries survived, not that the
original list/tuple values and first-seen order were preserved.
Assert the identifier sequence directly, per CodeRabbit nitpick.
@JinHai-CN
JinHai-CN requested a review from buua436 August 19, 2026 06:22
@buua436 buua436 added the ci Continue Integration label Aug 19, 2026

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

The fix looks correct and the regression coverage is comprehensive. One maintainability concern is that _CanonKey, _canonicalize, and _hashable_key are duplicated in two modules; please consider extracting them into a shared utility to prevent the canonicalization behavior from diverging over time.

DeviousDrops and others added 3 commits August 19, 2026 19:06
_CanonKey/_canonicalize/_hashable_key were duplicated in
dataset_structure_merger.py and tree_structured_query_decomposition_retrieval.py,
so the canonicalization behavior could drift between the two merge paths.
Move them to common.misc_utils (stdlib-only) and export the entry point as
hashable_key().

Co-Authored-By: Claude Opus 5 <[email protected]>
_merge_bucket groups by (lowercased name, type) with no alias resolution, so
"Apple Inc" and "Apple Incorporated" are two groups, not one. Use a casing
variant of the same name instead, which keeps the row in the group and also
covers case-insensitive grouping.

Add unit tests for the extracted hashable_key() helper: dict key order,
list vs. tuple, nested set/frozenset, and the repr() collision case.

Co-Authored-By: Claude Opus 5 <[email protected]>
…-rag-merge-18025

# Conflicts:
#	rag/svr/task_executor_refactor/dataset_structure_merger.py
@codecov

codecov Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (ec9c08d) to head (68b3234).
⚠️ Report is 21 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #18135   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

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

@DeviousDrops

DeviousDrops commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Good catch extracted _CanonKey, _canonicalize, and _hashable_key into common/misc_utils.py (exported as hashable_key()), imported by both modules now. Added unit tests for the shared helper too.

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

LGTM

@JinHai-CN
JinHai-CN merged commit ab40c90 into infiniflow:main Aug 20, 2026
3 checks passed
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.

Avoid Quadratic Deduplication in RAG Merge Paths

3 participants