Skip to content

fix(structure-graph): page dataset merge past ES max_result_window - #20400

Merged
wangq8 merged 3 commits into
infiniflow:0.27.xfrom
errmakov:fix/structure-merge-pagination
Oct 22, 2026
Merged

wangq8 merged 3 commits into
infiniflow:0.27.xfrom
errmakov:fix/structure-merge-pagination

Conversation

@errmakov

Copy link
Copy Markdown
Contributor

Summary

Fixes #19649 on 0.27.x. This carries forward #19650 by @rosaetempus, which targets main and now conflicts there because the Python code was removed from main. The original author is credited as co-author. The change also covers the review point @buua436 left open on #19650.

Problem. The dataset structure merge pages doc-level rows with an empty OrderByExpr. ESConnection.search switches to search_after only when the query has an explicit sort. Past index.max_result_window, the query therefore fails with Result window is too large. _index_search caught that error and returned [], so the task reported Built 1/1 without writing any dataset rows. ESConnection.search also silently dropped any sort on id.

Changes

  • rag/utils/es_conn.py: a sort on id now follows the live mapping. Indices created after Fix: handle id as keyword #14729 map id as keyword, and the sort uses id. Older indices map id as text with an id.keyword sub-field, and the sort uses id.keyword. As buua436 noted on fix(structure-graph): paginate dataset merge past ES max_result_window via search_after #19650, sorting on the text field there fails with a fielddata error. If the queried indices disagree, or id has no sortable form, the sort is dropped as before.
  • dataset_structure_merger.py:
    • On Elasticsearch, all five paged scans now sort by id. Other engines keep their current order. OpenSearch chunk indices map id as text, and OpenSearch has no search_after path.
    • Store errors now propagate from _index_search, _collect_structure_pairs, _cleanup_deleted_docs pass 1 and _consume_deletion_markers. They are no longer treated as end of results, so the merge does not run on partial data and deletion markers are not dropped. This also covers the CodeRabbit findings on fix(structure-graph): paginate dataset merge past ES max_result_window via search_after #19650.
    • If any dataset graph fails to build, run_structure_merge now reports progress(-1, "...; retry required.") instead of 1.0. dataset_wiki_generator already reports failures the same way.

Tests

  • test/unit_test/rag/utils/test_es_conn_id_sort_field.py: which sort field is chosen for keyword, legacy text, unmapped and mixed indices, plus a legacy-index page at offset 10000 that goes through search_after with id.keyword.
  • test/unit_test/rag/svr/task_executor_refactor/test_dataset_structure_merger_scan.py: id ordering on ES only, error propagation from each paged scan with no deletes on failure, and the task failing when a build fails.
  • 10 of the 12 new tests fail on the current 0.27.x. The other 2 check behaviour this change keeps: default order on non-ES engines, and dropping the sort on mixed mappings. All pass with the fix. The existing merger and search-pagination tests still pass.

The dataset structure merge scanned doc-level rows with an empty
OrderByExpr. ESConnection.search only takes its search_after path with an
explicit sort, so past index.max_result_window the scan hit a from+size
error, _index_search swallowed it as an empty page, and the task reported
success after writing no dataset rows (infiniflow#19649).

- Order the merger's paged scans by id on Elasticsearch.
- Sort on id according to the live mapping: indices created before id
  matched the keyword template map it as text, so use id.keyword there.
- Propagate store errors from every paged scan instead of treating them
  as end of results, and fail the task when a dataset graph build fails.

Co-authored-by: rosaetempus <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 56ecfb77-c838-4b1d-aa1b-1705f18c2b64

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 38.06%. Comparing base (4f2c2ff) to head (9fce23d).
⚠️ Report is 2 commits behind head on 0.27.x.

Additional details and impacted files
@@            Coverage Diff             @@
##           0.27.x   #20400      +/-   ##
==========================================
- Coverage   38.11%   38.06%   -0.05%     
==========================================
  Files          54       54              
  Lines       15567    15567              
  Branches      125      125              
==========================================
- Hits         5933     5926       -7     
- Misses       9606     9613       +7     
  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.

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

rag/utils/es_conn.py:324-326

        has_explicit_sort = bool(order_by and order_by.fields)
        use_search_after = limit > 0 and (offset + limit > MAX_RESULT_WINDOW) and has_explicit_sort and not has_dense

has_explicit_sort is derived from order_by.fields, not from the sorts that were actually emitted above. When _id_sort_field() returns None (mixed mapping such as keyword + legacy text, or an id with no sortable form), the entry is skipped at :310-314, so the query carries no sort — but use_search_after is still True.

_search_with_search_after() then receives hits without a sort array, hits[-1].get("sort") is None, and it breaks at :158-160 while remaining_skip > 0, so collected_hits == [] and the call returns an empty page. _do_build treats an empty page as end-of-scan (rag/svr/task_executor_refactor/dataset_structure_merger.py:800), so the merge keeps only the first 10 000 rows and still reports progress(1.0, "Built 1/1 ...") — the #19649 shape again, just behind a rarer precondition. This is the case the Go counterpart #20408 guards by failing loudly in searchAfterPaginate.

Suggested fix (2 lines — hoist orders out of the if so the gate reflects what is really sent):

        orders = list()
        if order_by:
            for field, order in order_by.fields:
                ...
            s = s.sort(*orders)
        ...
        has_explicit_sort = bool(orders)
        use_search_after = limit > 0 and (offset + limit > MAX_RESULT_WINDOW) and has_explicit_sort and not has_dense

With that, an unsortable id falls back to from/size, Elasticsearch raises Result window is too large, and since this PR no longer swallows the error in _index_search, the task ends with progress(-1, "... retry required.") instead of silently truncating the dataset graph.

Please also add the matching regression to test/unit_test/rag/utils/test_es_conn_id_sort_field.py: mixed mapping with offset + limit > MAX_RESULT_WINDOW must raise rather than return an empty hit list.

def test_unsortable_id_mapping_and_deep_offset_raises():
    conn = _connection(
        {
            "ragflow_a": {"mappings": {"id": _KEYWORD_ID}},
            "ragflow_b": {"mappings": {"id": _TEXT_ID}},
        }
    )
    conn._es_search_once = MagicMock(return_value={"timed_out": False, "hits": {"total": {"value": 20000}, "hits": []}})

    with pytest.raises(Exception, match="Result window|sort cursor"):
        conn.search(["id"], [], {}, [], OrderByExpr().asc("id"), 10000, 1000, ["ragflow_a", "ragflow_b"], ["kb-1"])

When the id sort is dropped (mixed or unsortable id mappings), the query
carries no sort, but use_search_after still followed order_by.fields. The
search_after loop then got hits without sort values and returned an empty
page past max_result_window, which the structure merge read as end of scan.
Derive the gate from the emitted sorts so such queries fall back to
from/size and fail loudly instead.
@qinling0210

Copy link
Copy Markdown
Contributor

@errmakov Thanks for your quick reply. The code change looks good.

But your branch is far behind 0.27.x, please rebase onto 0.27.x before merging.

@wangq8
wangq8 merged commit 1cde8c9 into infiniflow:0.27.x Oct 22, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants