Skip to content

feat: parser pages range and parse type validation for dataset/document - #17293

Merged
yuzhichang merged 5 commits into
infiniflow:mainfrom
xugangqiang:feat/parser-pages
Jul 23, 2026
Merged

yuzhichang merged 5 commits into
infiniflow:mainfrom
xugangqiang:feat/parser-pages

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

Adds page-range parsing support to the Go-native pipeline path and introduces strict parse_type validation for both dataset and document update endpoints.

What changed

Pages range parsing

  • internal/utility/pdf_pages.go — NormalizePDFPages: normalizes raw page ranges (list of [from,to] 1-indexed inclusive ranges) into sorted, merged, deduplicated [][]int. Invalid ranges are dropped.
  • internal/ingestion/pipeline/pdf_pages.go — NormalizeParserConfigPages: walks any parser_config map and normalizes "pages" values under every component → filetype setup, so the persisted config always carries clean, merged ranges.
  • internal/deepdoc/parser/pdf/parser.go — integrates resolvePagesToProcess to filter parsed PDF pages by the configured ranges.
  • Pipeline integration (parser pages): internal/parser/parser/pdf_parser_common.go, chunk_process.go, plus associated e2e and unit tests.

Parse type validation (shared logic)

  • internal/service/parser_mode.go (new) — ValidateParseTypeMode: shared function that validates parse_type (1=BuiltIn/parser_id, 2=Pipeline/pipeline_id) and ensures the corresponding field is present. Used by both dataset and document update endpoints.
  • internal/service/dataset/crud.go / update.go — replaces inline isPipelineMode/isBuiltinMode computation with the shared service.ValidateParseTypeMode.
  • internal/service/document/document_dataset_update.go — adds strict parse_type validation in validateDatasetDocumentUpdate, simplifies the reparse logic to a two-way switch (isBuiltin/isPipeline) now that parse_type is always valid.
  • internal/service/document/document.go — adds ParseType field to UpdateDatasetDocumentRequest.
  • internal/service/document/document_dataset_update.go — updateDocumentParserConfig fallback path when DSL loading fails.
  • internal/service/parser_mode_test.go (new) — test coverage for nil, invalid, and missing-field scenarios.

Frontend

  • web/src/interfaces/request/document.ts — adds parseType to IChangeParserRequestBody.
  • web/src/hooks/use-document-request.ts — useSetDocumentPipelineParser sends parse_type in the PATCH payload.
  • web/src/pages/dataset/dataset/use-change-document-parser.ts — Go/Python branching for the document parser config dialog.
  • web/src/components/document-pipeline-dialog/use-document-pipeline-form.ts — buildSubmitData returns parseType (bugfix: was dropped from the return value).

Test changes

  • Removed: 2 tests that verified the old "mutually exclusive" error (replaced by ValidateParseTypeMode coverage).
  • Modified: 6 tests across document and dataset packages to include ParseType in request structs.
  • Added: new e2e tests for pages parsing (pages_e2e_test.go, pdf_parser_pages_e2e_test.go) and unit tests for NormalizePDFPages, NormalizeParserConfigPages, resolvePagesToProcess.

Backward compatibility

  • The parse_type field is required when parser_id or pipeline_id is sent. This changes the contract for both dataset and document PATCH endpoints, but aligns the Go backend with the existing frontend behavior (the frontend already sends parse_type). Callers that omit parse_type when updating parser/pipeline selections will receive a clear error message.
  • Existing callers that only update fields like name, enabled, or meta_fields are unaffected.
  • Test updates ensure all known call sites are compliant.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 23, 2026
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 37fe8caf-3374-4219-ac55-65aab39cecfd

📥 Commits

Reviewing files that changed from the base of the PR and between 7c7c0f6 and 133376c.

📒 Files selected for processing (1)
  • test/testcases/restful_api/test_datasets.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/testcases/restful_api/test_datasets.py

📝 Walkthrough

Walkthrough

PDF parsing now supports normalized inclusive page ranges propagated through parser configuration and frontend requests. Dataset and document parser selection uses explicit built-in or pipeline modes. Chunk metadata cleanup is narrowed to _pdf_positions, and the Tag parser registry entry is removed.

Changes

PDF Page Filtering

Layer / File(s) Summary
Page range normalization
internal/utility/pdf_pages.go, internal/utility/pdf_pages_test.go, internal/ingestion/pipeline/pdf_pages.go, internal/ingestion/pipeline/pdf_pages_test.go, internal/ingestion/pipeline/template/...
Page ranges are validated, sorted, merged, and normalized across parser configuration maps.
Parser configuration wiring
internal/deepdoc/parser/type/types.go, internal/parser/parser/pdf_parser_common.go, internal/parser/parser/pdf_parser_cgo.go, internal/parser/parser/pdf_parser_pages_*
Parser setup accepts normalized page ranges and passes them into deepdoc parsing.
Deepdoc page execution
internal/deepdoc/parser/pdf/parser.go, internal/deepdoc/parser/pdf/parser_pages_test.go, internal/deepdoc/parser/pdf/pages_e2e_test.go, internal/deepdoc/parser/pdf/pagespdfiumtest/*
Configured ranges are clamped, deduplicated, converted to zero-based pages, and applied during parsing.

Parse Mode Propagation

Layer / File(s) Summary
Parse-mode validation
internal/service/parser_mode.go, internal/service/parser_mode_test.go, internal/service/pipeline_params.go
Built-in and pipeline modes validate required identifiers and resolve effective parser state.
Dataset and document handling
internal/service/dataset/*, internal/service/document/*, internal/service/dataset_types.go
Create and update flows validate parse modes, clear conflicting identifiers, normalize parser pages, and select reparse targets.
Web and API request propagation
web/src/interfaces/request/document.ts, web/src/components/document-pipeline-dialog/*, web/src/hooks/use-document-request.ts, web/src/pages/dataset/dataset/*, test/testcases/restful_api/test_datasets.py
Parser requests now carry optional parseType as parse_type, with updated request validation tests.

Chunk and Registry Updates

Layer / File(s) Summary
Position metadata pruning
internal/ingestion/task/chunk_process.go, internal/ingestion/task/chunk_process_test.go
_pdf_positions is removed during position processing, including when positions are absent; image cleanup is no longer asserted there.
Tag parser removal
internal/admin/service.go, internal/entity/dataset.go, internal/ingestion/pipeline/*_test.go
The Tag parser constant, tenant mapping, registry expectations, and component golden coverage are removed.

Estimated code review effort: 4 (Complex) | ~50 minutes

Possibly related PRs

Suggested labels: 💞 feature

Poem

A bunny hops through pages neat,
Merging ranges into one smooth beat.
Built-in or pipeline, modes align,
Chunks shed old tracks by design.
“Parse just these!” the rabbit sings.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 39.34% 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 is concise and accurately summarizes the main changes to page-range parsing and parse-type validation.
Description check ✅ Passed The description includes the required summary and adds clear implementation and compatibility details beyond the template.
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.

@xugangqiang xugangqiang added the ci Continue Integration label Jul 23, 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: 3

🧹 Nitpick comments (3)
internal/service/document/document.go (1)

125-127: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the compatibility-only wording from this comment.

The optional *int behavior is sufficient documentation; "(backward compat)" conflicts with the repository rule against compatibility wording in comments.

Suggested wording
-	// 2 = Pipeline (pipeline_id). nil means unspecified (backward compat).
+	// 2 = Pipeline (pipeline_id). nil means unspecified.
🤖 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/document/document.go` around lines 125 - 127, Update the
ParseType field comment to remove the “backward compat” wording while retaining
the descriptions of the BuiltIn, Pipeline, and unspecified modes.

Source: Coding guidelines

internal/service/document/document_test.go (1)

2295-2319: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Seed an existing pipeline to test the built-in transition.

This test passes an empty pipeline_id, but does not explicitly create a document currently using a pipeline. Add that state and assert the persisted pipeline ID is cleared; otherwise a regression in the built-in branch’s canvas-clearing behavior would go undetected.

🤖 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/document/document_test.go` around lines 2295 - 2319, Update
TestUpdateDatasetDocumentParseTypeBuiltin to seed an existing pipeline-backed
document before the update, using the test helpers and persisted document state
available in the setup. After calling UpdateDatasetDocument with the built-in
parse type and empty pipeline_id, assert that the saved document’s pipeline ID
is cleared, not merely that the response is empty.
internal/deepdoc/parser/pdf/parser.go (1)

541-549: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Consider downgrading the "no ranges configured" log to Debug.

The else branch fires on every parse where no page ranges are configured — i.e. the default/common case for most documents — at slog.Info level. This adds a log line per document parse for the majority of workloads, whereas the configured-ranges branch (a less common, more actionable case) is the one worth keeping at Info.

♻️ Suggested tweak
 	} else {
-		slog.Info("deepdoc pdf parse: parsing all pages", "page_count", pageCount)
+		slog.Debug("deepdoc pdf parse: parsing all pages", "page_count", pageCount)
 	}
🤖 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/deepdoc/parser/pdf/parser.go` around lines 541 - 549, Change the
no-ranges branch in the page-processing flow around resolvePagesToProcess from
slog.Info to slog.Debug, preserving its existing message and fields; keep the
configured-ranges log at Info.
🤖 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/parser/parser/pdf_parser_pages_e2e_test.go`:
- Around line 41-85: Update the no-CGO ParseWithResult implementations in
PDFParser, DOCParser, DOCXParser, PPTParser, and PPTXParser to satisfy the
ParseResultProducer context-aware method contract returned by GetParser. Add the
context parameter consistently and propagate it through parsePDFWith... helpers,
office parser stages, and deepdoc parsing calls instead of using a background
context. Keep behavior unchanged apart from honoring the caller-provided
context.

In `@internal/service/dataset/update.go`:
- Line 137: The pages normalizer must remove all-invalid values instead of
retaining them. Update pipelinepkg.NormalizeParserConfigPages and apply the
cleanup in internal/service/dataset/update.go lines 137-137 before building and
storing parser config; apply the same cleanup in
internal/service/document/document_dataset_update.go lines 146-149 before
fallback merging or DSL-based config construction, yielding an omitted or empty
page selection.

In `@internal/service/document/document_dataset_update.go`:
- Around line 187-192: The parser configuration resolution must honor the
selected parse mode before processing IDs. Update the earlier parser-config
logic to derive effective parser ID, pipeline ID, and isCanvas from
req.ParseType, ensuring parse_type=2 ignores parser_id and uses pipeline
settings even when both IDs are provided; add a regression test covering
pipeline mode with both IDs and pipeline-specific configuration.

---

Nitpick comments:
In `@internal/deepdoc/parser/pdf/parser.go`:
- Around line 541-549: Change the no-ranges branch in the page-processing flow
around resolvePagesToProcess from slog.Info to slog.Debug, preserving its
existing message and fields; keep the configured-ranges log at Info.

In `@internal/service/document/document_test.go`:
- Around line 2295-2319: Update TestUpdateDatasetDocumentParseTypeBuiltin to
seed an existing pipeline-backed document before the update, using the test
helpers and persisted document state available in the setup. After calling
UpdateDatasetDocument with the built-in parse type and empty pipeline_id, assert
that the saved document’s pipeline ID is cleared, not merely that the response
is empty.

In `@internal/service/document/document.go`:
- Around line 125-127: Update the ParseType field comment to remove the
“backward compat” wording while retaining the descriptions of the BuiltIn,
Pipeline, and unspecified modes.
🪄 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 Plus

Run ID: 298dc9e3-7fe3-4c24-b965-75b9c42fafc2

📥 Commits

Reviewing files that changed from the base of the PR and between 6467df3 and 167aae9.

📒 Files selected for processing (34)
  • internal/deepdoc/parser/pdf/ocr_merge_test.go
  • internal/deepdoc/parser/pdf/pages_e2e_test.go
  • internal/deepdoc/parser/pdf/pagespdfiumtest/pages_pdfium_e2e_test.go
  • internal/deepdoc/parser/pdf/parser.go
  • internal/deepdoc/parser/pdf/parser_pages_test.go
  • internal/deepdoc/parser/pdf/parser_pipeline_integration_test.go
  • internal/deepdoc/parser/pdf/pipeline_parity_test.go
  • internal/deepdoc/parser/pdf/table_rotate_integration_test.go
  • internal/deepdoc/parser/pdf/text_dump_test.go
  • internal/deepdoc/parser/type/types.go
  • internal/ingestion/component/tokenizer_test.go
  • internal/ingestion/pipeline/pdf_pages.go
  • internal/ingestion/pipeline/pdf_pages_test.go
  • internal/ingestion/task/chunk_process.go
  • internal/ingestion/task/chunk_process_test.go
  • internal/parser/parser/pdf_parser_cgo.go
  • internal/parser/parser/pdf_parser_common.go
  • internal/parser/parser/pdf_parser_pages_e2e_test.go
  • internal/parser/parser/pdf_parser_pages_test.go
  • internal/service/dataset/create_test.go
  • internal/service/dataset/crud.go
  • internal/service/dataset/update.go
  • internal/service/dataset/update_test.go
  • internal/service/document/document.go
  • internal/service/document/document_dataset_update.go
  • internal/service/document/document_test.go
  • internal/service/parser_mode.go
  • internal/service/parser_mode_test.go
  • internal/utility/pdf_pages.go
  • internal/utility/pdf_pages_test.go
  • web/src/components/document-pipeline-dialog/use-document-pipeline-form.ts
  • web/src/hooks/use-document-request.ts
  • web/src/interfaces/request/document.ts
  • web/src/pages/dataset/dataset/use-change-document-parser.ts
💤 Files with no reviewable changes (1)
  • internal/deepdoc/parser/pdf/parser_pipeline_integration_test.go

Comment on lines +41 to +85
func TestPDFParser_PagesEndToEnd_FromConfigureFromSetup(t *testing.T) {
// Build a 10-page mock engine where page N carries the text "pN".
chars := make(map[int][]deepdoctype.TextChar, 10)
for i := 0; i < 10; i++ {
chars[i] = []deepdoctype.TextChar{
{Text: fmt.Sprintf("p%d", i), X0: 10, X1: 50, Top: 10, Bottom: 30, PageNumber: i},
}
}
eng := &deepdocpdf.MockEngine{NumPages: 10, Chars: chars, RenderW: 100, RenderH: 100}

// 1. ConfigureFromSetup reads "pages" exactly as the pipeline would pass
// it (JSON-decoded []any of []any of float64).
p := &PDFParser{}
p.ConfigureFromSetup(map[string]any{
"pages": []any{
[]any{float64(1), float64(3)},
[]any{float64(8), float64(10)},
},
})
wantPages := [][]int{{1, 3}, {8, 10}}
if !reflect.DeepEqual(p.Pages, wantPages) {
t.Fatalf("PDFParser.Pages = %v, want %v", p.Pages, wantPages)
}

// 2. Build the deepdoc config the same way ParseWithResult does
// (cfg.Pages = p.Pages) and run the parser.
cfg := deepdoctype.DefaultParserConfig()
cfg.Pages = p.Pages
docParser := deepdocpdf.NewParser(cfg)

result, err := docParser.ParseRaw(context.Background(), eng, noopDocAnalyzer{})
if err != nil {
t.Fatalf("ParseRaw: %v", err)
}

// 3. [1,3] -> 0-based 0..2 ; [8,10] -> 7..9
gotPages := make(map[int]struct{}, len(result.PageHeight))
for k := range result.PageHeight {
gotPages[k] = struct{}{}
}
want := map[int]struct{}{0: {}, 1: {}, 2: {}, 7: {}, 8: {}, 9: {}}
if !reflect.DeepEqual(gotPages, want) {
t.Errorf("PageHeight keys = %v, want %v", gotPages, want)
}
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect the interface and nocgo variant referenced by the lint errors.
fd -t f 'parser_type.go|pdf_parser_nocgo.go' internal/parser/parser
ast-grep run --pattern 'type ParseResultProducer interface { $$$ }' --lang go internal/parser/parser/parser_type.go
rg -n 'func.*ParseWithResult' internal/parser/parser
rg -n 'func parsePDFWithMinerU|func parsePDFWithPaddleOCR|func parsePDFWithDocling|func parsePDFWithOpenDataLoader' internal/parser/parser

Repository: infiniflow/ragflow

Length of output: 10495


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== parser_type.go =="
cat -n internal/parser/parser/parser_type.go | sed -n '1,80p'

echo
echo "== pdf_parser_nocgo.go =="
cat -n internal/parser/parser/pdf_parser_nocgo.go | sed -n '1,80p'

echo
echo "== office_parsers_no_cgo.go =="
cat -n internal/parser/parser/office_parsers_no_cgo.go | sed -n '1,80p'

echo
echo "== parse_with_result dispatch callers =="
rg -n 'ParseWithResult\(|ParseResultProducer|MakePDFParser|NewPDFParser|parsePDFWith' internal/parser/parser -g '*.go'

Repository: infiniflow/ragflow

Length of output: 27258


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== parse_result.go =="
cat -n internal/parser/parser/parse_result.go | sed -n '1,120p'

echo
echo "== PDFParser no-CGO stub implementation =="
cat -n internal/parser/parser/pdf_parser_no_cgo_stub.go | sed -n '1,140p' 2>/dev/null || true

echo
echo "== common PDF parse helpers signatures =="
cat -n internal/parser/parser/pdf_parser_common.go | sed -n '630,690p'

echo
echo "== all parsePDFWithPlainText definitions =="
rg -n 'func parsePDFWithPlainText|func parsePDFWith.*Plain|parsePDFWithPlainText' internal/parser/parser -g '*.go'

echo
echo "== Go parse result assignment from package data only =="
python3 - <<'PY'
from pathlib import Path
for p in [Path("internal/parser/parser/parser_type.go"),
          Path("internal/parser/parser/parse_result.go"),
          Path("internal/parser/parser/pdf_parser_cgo.go"),
          Path("internal/parser/parser/pdf_parser_nocgo.go"),
          Path("internal/parser/parser/office_parsers_no_cgo.go")]:
    print(f"\n-- {p} --")
    text = p.read_text()
    for marker in ["type ParseResultProducer interface", "func GetParser", "ParseWithResult"]:
        print(f"{marker}: {text.count(marker)}")
PY

Repository: infiniflow/ragflow

Length of output: 7595


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== PDFParser declarations and constructors =="
fd -t f 'pdf_parser.*\.go' internal/parser/parser | sort | while read -r f; do
  echo "--- $f ---"
  rg -n 'type PDFParser|func NewPDFParser|ParseMethod|validateParseMethod|ParseWithResult' "$f" || true
done

echo
echo "== parsePDF helpers that nocgo dispatches to =="
cat -n internal/parser/parser/pdf_parser_paddleocr.go | sed -n '1,45p'
cat -n internal/parser/parser/pdf_parser_docling.go | sed -n '1,60p'
cat -n internal/parser/parser/pdf_parser_mineru.go | sed -n '1,45p'
cat -n internal/parser/parser/pdf_parser_opendataloader.go | sed -n '1,45p'
cat -n internal/parser/parser/pdf_parser_somark.go | sed -n '1,45p'
cat -n internal/parser/parser/pdf_parser_tcadp.go | sed -n '1,45p'
cat -n internal/parser/parser/pdf_parser_plaintext_nocgo.go | sed -n '1,45p'

echo
echo "== PDFParser no stub/source candidates =="
git ls-files internal/parser/parser | grep -E 'pdf_parser_|pdf.*parser' | sort

Repository: infiniflow/ragflow

Length of output: 21305


Fix internal/parser/parser to implement ParseResultProducer before relying on this PDF pages test.

GetParser returns DOCParser, DOCXParser, PPTParser, PPTXParser, and PDFParser as ParseResultProducers, but the no-CGO implementations have ParseWithResult methods without ctx context.Context: pdf_parser_nocgo.go and office_parsers_no_cgo.go. Align all returned parser stubs/stages with the ParseResultProducer contract, including using ctx in calls such as parsePDFWith...*() and deepdoc parsing.

🤖 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/parser/parser/pdf_parser_pages_e2e_test.go` around lines 41 - 85,
Update the no-CGO ParseWithResult implementations in PDFParser, DOCParser,
DOCXParser, PPTParser, and PPTXParser to satisfy the ParseResultProducer
context-aware method contract returned by GetParser. Add the context parameter
consistently and propagate it through parsePDFWith... helpers, office parser
stages, and deepdoc parsing calls instead of using a background context. Keep
behavior unchanged apart from honoring the caller-provided context.

Source: Linters/SAST tools

Comment thread internal/service/dataset/update.go Resolved

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/utility/pdf_pages.go (1)

74-74: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Avoid overflow when merging adjacent maximum-sized ranges.

last[1] + 1 overflows when the previous valid range ends at MaxInt, so overlapping/adjacent ranges can be split incorrectly.

Proposed fix
-		if r[0] <= last[1]+1 { // overlap or adjacent
+		if r[0] <= last[1] || (r[0] > last[1] && r[0]-last[1] == 1) {
🤖 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/utility/pdf_pages.go` at line 74, Update the range-merging condition
in the relevant function around last[1] so checking overlap or adjacency does
not compute last[1] + 1 when the endpoint is MaxInt. Use an overflow-safe
comparison that preserves merging for overlapping or adjacent ranges, including
ranges ending at the maximum integer value.
internal/deepdoc/parser/pdf/parser.go (1)

120-121: 🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Allocate for selected pages, not the entire document.

A narrow configured range still preallocates the map and slice for pageCount. Large PDFs can therefore incur full-document allocation even when parsing one page.

Proposed fix
-	seen := make(map[int]struct{}, pageCount)
-	out := make([]int, 0, pageCount)
+	seen := make(map[int]struct{})
+	out := make([]int, 0)
🤖 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/deepdoc/parser/pdf/parser.go` around lines 120 - 121, Update the
allocations for seen and out in the PDF parser to use the number of selected
pages in the configured range rather than pageCount. Preserve the existing
collection behavior while ensuring narrow ranges do not preallocate capacity for
the entire document.
🤖 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/ingestion/pipeline/template/ingestion_pipeline_general.json`:
- Around line 106-111: Remove the default "pages" value from the ingestion
pipeline template so parsing remains uncapped when users provide no page
selection. Only persist the pages field when the user explicitly selects pages;
do not introduce another implicit page limit.

In `@internal/service/parser_mode.go`:
- Around line 41-45: The no-CGO/no-op parser implementations have outdated
ParseResultProducer method signatures. Update ParseWithResult on DOCXParser,
DOCParser, PPTParser, and PDFParser to accept context.Context, string, and
[]byte in the required order, preserving their existing no-op behavior and
return values.

In `@internal/utility/pdf_pages_test.go`:
- Around line 9-11: Update the page-range test cases and comments in the
relevant test block to match normalization semantics: ignore invalid ranges,
while sorting, merging, and deduplicating valid ranges. Change cases such as
[1,10], [9,2], [20,30] to expect [[1,10],[20,30]], and retain nil/empty input as
the parse-all-pages behavior.

---

Outside diff comments:
In `@internal/deepdoc/parser/pdf/parser.go`:
- Around line 120-121: Update the allocations for seen and out in the PDF parser
to use the number of selected pages in the configured range rather than
pageCount. Preserve the existing collection behavior while ensuring narrow
ranges do not preallocate capacity for the entire document.

In `@internal/utility/pdf_pages.go`:
- Line 74: Update the range-merging condition in the relevant function around
last[1] so checking overlap or adjacency does not compute last[1] + 1 when the
endpoint is MaxInt. Use an overflow-safe comparison that preserves merging for
overlapping or adjacent ranges, including ranges ending at the maximum integer
value.
🪄 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 Plus

Run ID: 0dd250e2-97bc-4c06-9e82-fb1e56682775

📥 Commits

Reviewing files that changed from the base of the PR and between 167aae9 and ada4f71.

📒 Files selected for processing (19)
  • internal/deepdoc/parser/pdf/pages_e2e_test.go
  • internal/deepdoc/parser/pdf/parser.go
  • internal/ingestion/pipeline/pdf_pages.go
  • internal/ingestion/pipeline/pdf_pages_test.go
  • internal/ingestion/pipeline/template/ingestion_pipeline_general.json
  • internal/parser/parser/pdf_parser_common.go
  • internal/service/dataset/update.go
  • internal/service/dataset/update_test.go
  • internal/service/dataset_types.go
  • internal/service/document/document.go
  • internal/service/document/document_dataset_update.go
  • internal/service/document/document_test.go
  • internal/service/parser_mode.go
  • internal/service/parser_mode_test.go
  • internal/service/pipeline_params.go
  • internal/utility/pdf_pages.go
  • internal/utility/pdf_pages_test.go
  • test/testcases/restful_api/test_datasets.py
  • web/src/components/chunk-method-dialog/index.tsx
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/service/document/document.go
  • internal/parser/parser/pdf_parser_common.go
  • internal/service/dataset/update.go
  • internal/service/document/document_dataset_update.go

Comment on lines +106 to +111
"pages": [
[
1,
100000
]
]

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Do not cap the default parse at 100,000 pages.

Without pages, the parser processes every page; this new default silently excludes page 100001 onward. Leave the field absent and only persist explicit user selections.

🤖 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/ingestion/pipeline/template/ingestion_pipeline_general.json` around
lines 106 - 111, Remove the default "pages" value from the ingestion pipeline
template so parsing remains uncapped when users provide no page selection. Only
persist the pages field when the user explicitly selects pages; do not introduce
another implicit page limit.

Comment on lines +41 to +45
// ResolveParseMode returns the effective (isPipeline, parserID, pipelineID)
// after applying an update. It is the single source of truth for "which DSL
// should parser_config be cleaned against" and "which mode should reparse
// target", shared by the dataset and document update paths.
//

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm whether ParseWithResult signatures across parser implementations were updated
# consistently with the ParseResultProducer interface change.
rg -n 'func.*ParseWithResult' internal/parser/parser internal/deepdoc -A2
rg -n 'ParseResultProducer' internal/parser/parser -A5

Repository: infiniflow/ragflow

Length of output: 33020


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== ParseResultProducer interface =="
sed -n '80,92p' internal/parser/parser/parse_result.go

echo
echo "== office noparse / nocgo implementations =="
sed -n '1,55p' internal/parser/parser/office_parsers_no_cgo.go

echo
echo "== PDF nocgo implementation =="
sed -n '1,25p' internal/parser/parser/pdf_parser_nocgo.go

echo
echo "== Go docs parser: interface typecheck without building =="
go tool compile -I . -p main <<'EOF'
package main

type ParseResult struct{}

type ParseResultProducer interface {
	ParseWithResult(ctx interface{}, filename string, data []byte) ParseResult
}

type PDFParser struct{}

func (p *PDFParser) ParseWithResult(filename string, data []byte) ParseResult {
	return ParseResult{}
}

func main() {
	var _ ParseResultProducer = &PDFParser{}
}
EOF

Repository: infiniflow/ragflow

Length of output: 6578


Fix the remaining ParseResultProducer signatures

ParseResultProducer.ParseWithResult requires (context.Context, string, []byte), but these no-CGO/no-op implementations still omit context.Context, so GetParser no longer returns valid producers on those build tags:

  • internal/parser/parser/office_parsers_no_cgo.go: DOCXParser, DOCParser, and PPTParser
  • internal/parser/parser/pdf_parser_nocgo.go: PDFParser
🤖 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/parser_mode.go` around lines 41 - 45, The no-CGO/no-op
parser implementations have outdated ParseResultProducer method signatures.
Update ParseWithResult on DOCXParser, DOCParser, PPTParser, and PDFParser to
accept context.Context, string, and []byte in the required order, preserving
their existing no-op behavior and return values.

Comment on lines +9 to +11
// "pages" ranges under fail-fast semantics: valid ranges are normalized
// (sorted/merged/deduplicated), any invalid range rejects the whole input,
// and nil/empty means "no value" (parse all pages).

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Align invalid-range expectations with the normalization contract.

The PR requires invalid ranges to be dropped while valid ranges are sorted and merged. These assertions instead require any invalid entry to discard the entire input. For example, [1,10], [9,2], [20,30] should retain [[1,10],[20,30]]; update the comments and cases accordingly.

Also applies to: 69-93

🤖 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/utility/pdf_pages_test.go` around lines 9 - 11, Update the
page-range test cases and comments in the relevant test block to match
normalization semantics: ignore invalid ranges, while sorting, merging, and
deduplicating valid ranges. Change cases such as [1,10], [9,2], [20,30] to
expect [[1,10],[20,30]], and retain nil/empty input as the parse-all-pages
behavior.

@codecov

codecov Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (8af2467) to head (133376c).
⚠️ Report is 15 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17293   +/-   ##
=======================================
  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.

@yuzhichang
yuzhichang merged commit d12fd3b into infiniflow:main Jul 23, 2026
5 checks passed
@xugangqiang
xugangqiang deleted the feat/parser-pages branch August 7, 2026 12:27
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.

2 participants