Skip to content

Refactor: enhance graphrag - part 2 - #14972

Merged
KevinHuSh merged 6 commits into
infiniflow:mainfrom
wangq8:feature/add-spacy-3
May 18, 2026
Merged

KevinHuSh merged 6 commits into
infiniflow:mainfrom
wangq8:feature/add-spacy-3

Conversation

@wangq8

@wangq8 wangq8 commented May 18, 2026 •

Copy link
Copy Markdown
Collaborator

What problem does this PR solve?

  1. expose batch_chunk_token_size for configuration
  2. retrieve chunks when build subgraph for the doc, not retreive all docs chunks at the begining
  3. get all chunks for a document, used to be hard coded 10000
  4. delete not used method run_graphrag

Type of change

  • New Feature (non-breaking change which adds functionality)
  • Refactoring

Follow on: #14617

@coderabbitai

coderabbitai Bot commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds a configurable GraphRAG parameter batch_chunk_token_size (default 4096, bounds 512–8196) and wires it through backend validation, chunk retrieval pagination, GraphRAG core processing, task initialization, frontend types/schema/UI, localization, and tests.

Changes

GraphRAG Batch Chunk Token Size Configuration

Layer / File(s) Summary
Configuration schema and validation
api/utils/validation_utils.py, api/utils/api_utils.py
GraphragConfig adds batch_chunk_token_size: 4096 with bounds (512–8196); API default parser config for the naive chunking method is updated.
Chunk retrieval pagination
rag/nlp/search.py
Dealer.chunk_list gains retrieve_all and switches pagination to a cursor while loop to allow exhausting all pages when requested.
GraphRAG core processing refactor
rag/graphrag/general/index.py
run_graphrag_for_kb now derives batch_chunk_token_size, calls retriever.chunk_list(retrieve_all=True), builds token-bounded batches using that value, moves chunk loading into worker on checkpoint miss, accumulates total_chunks, and early-returns when no chunks/subgraphs exist; old run_graphrag entrypoint removed.
Task executor integration
rag/svr/task_executor.py
Adds batch_chunk_token_size: 4096 to the graphrag parser configuration written when enabling GraphRAG for a KB.
Frontend UI component
web/src/components/parse-configuration/graph-rag-form-fields.tsx
Adds SliderInputFormField (with min/max/step/default) bound to parser_config.graphrag.batch_chunk_token_size in GraphRagItems.
Frontend type definitions
web/src/interfaces/database/dataset.ts, web/src/interfaces/database/document.ts
Adds optional batch_chunk_token_size?: number to Graphrag / GraphRag interfaces.
Frontend form schema validation
web/src/pages/dataset/dataset-setting/form-schema.ts
Adds batch_chunk_token_size to form schema with integer validation and range 512–8196.
Frontend defaults and localization
web/src/pages/dataset/dataset-setting/index.tsx, web/src/locales/en.ts, web/src/locales/zh.ts
Sets default value to 4096 and adds i18n entries describing the LLM-batching token limit (not applied to NER).
Tests and default constants
test/testcases/configs.py, test/testcases/*/test_update_document.py
Updates DEFAULT_PARSER_CONFIG and test defaults to include graphrag.batch_chunk_token_size: 4096.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

💞 feature, 🌈 python, 🧰 typescript

Suggested reviewers

  • yingfeng

"🐰 A small rabbit in a codey glade,
Tucked a token limit in the config shade,
From backend rules to slider bright,
Batches hop steady, extraction light,
Hooray — GraphRAG tuned just right!"

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Refactor: enhance graphrag - part 2' is vague and generic, referring to part 2 of a refactoring without specifying what improvements or features were added. Consider using a more descriptive title that highlights the main changes, such as 'Add configurable batch_chunk_token_size for GraphRAG processing' or similar.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Description check ✅ Passed PR description addresses the four main changes (expose batch_chunk_token_size, retrieve chunks on-demand, retrieve all chunks, remove run_graphrag) and correctly identifies this as a New Feature and Refactoring.

✏️ 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.

@wangq8 wangq8 added the ci Continue Integration label May 18, 2026
@wangq8
wangq8 marked this pull request as ready for review May 18, 2026 07:03
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 18, 2026
@wangq8 wangq8 changed the title (draft) refactor: enhance graphrag - part 2 Refactor: enhance graphrag - part 2 May 18, 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

Caution

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

⚠️ Outside diff range comments (1)
rag/nlp/search.py (1)

647-661: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add a log when retrieve_all=True path is used.

The new unbounded pagination flow has no trace point, which makes production diagnosis harder for large documents.

Suggested patch
         p = offset
+        if retrieve_all:
+            logging.debug("chunk_list retrieve_all enabled for doc_id=%s, tenant_id=%s, kb_ids=%s", doc_id, tenant_id, kb_ids)
         while retrieve_all or p < max_count:

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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 `@rag/nlp/search.py` around lines 647 - 661, Add a log entry whenever the
unbounded pagination path is taken (when retrieve_all is True) so production
traces show the large-doc flow; inside the loop in rag/nlp/search.py (the block
using variables retrieve_all, p, max_count, bs and calling
self.dataStore.search/self.dataStore.get_fields) emit an info/debug log at the
start of the iteration indicating that unbounded retrieval is active and include
contextual identifiers (tenant_id, kb_ids), current page offset p and batch size
limit (bs), and optionally a cumulative count or marker so operators can trace
progress.
🤖 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/graphrag/general/index.py`:
- Around line 60-70: The helper _positive_int_config currently accepts any
positive integer; change it to enforce the API bounds 512–8196 by
validating/clamping the parsed value to that range (e.g., if parsed value < 512
or > 8196, log a warning and return the default or clamp to the nearest bound),
and apply the same bounded validation wherever this helper is used (refer to
_positive_int_config and the call sites around the previous lines 157–159) so
persisted/manual configs cannot pass out-of-contract values that break batching.
- Around line 292-294: The early-return returns failed_docs as list[str] causing
inconsistency; change the return so failed_docs is a list[tuple[str,str]] to
match other exits. In the block that checks total_chunks == 0 and not subgraphs,
transform doc_ids into tuples (doc_id, "<reason>") — e.g. (doc_id,
"no_available_chunks") — and return {"ok_docs": [], "failed_docs":
failed_tuples, "total_docs": len(doc_ids), "total_chunks": 0, "seconds": 0.0};
reference variables/functions: total_chunks, subgraphs, callback, kb_id,
doc_ids.

In `@web/src/pages/dataset/dataset-setting/form-schema.ts`:
- Around line 73-78: The zod schema for batch_chunk_token_size currently allows
values below the backend's allowed range; update the validator for the
batch_chunk_token_size field to enforce the backend contract by adding a minimum
of 512 (e.g., replace/augment .positive() with .min(512)) while keeping the
existing .max(8196) and .int() constraints so client-side validation matches the
GraphRAG range 512..8196.

---

Outside diff comments:
In `@rag/nlp/search.py`:
- Around line 647-661: Add a log entry whenever the unbounded pagination path is
taken (when retrieve_all is True) so production traces show the large-doc flow;
inside the loop in rag/nlp/search.py (the block using variables retrieve_all, p,
max_count, bs and calling self.dataStore.search/self.dataStore.get_fields) emit
an info/debug log at the start of the iteration indicating that unbounded
retrieval is active and include contextual identifiers (tenant_id, kb_ids),
current page offset p and batch size limit (bs), and optionally a cumulative
count or marker so operators can trace progress.
🪄 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

Run ID: f94b65ce-2308-4f03-8a69-4a98a194eac4

📥 Commits

Reviewing files that changed from the base of the PR and between 9d94527 and 50060cb.

📒 Files selected for processing (12)
  • api/utils/api_utils.py
  • api/utils/validation_utils.py
  • rag/graphrag/general/index.py
  • rag/nlp/search.py
  • rag/svr/task_executor.py
  • web/src/components/parse-configuration/graph-rag-form-fields.tsx
  • web/src/interfaces/database/dataset.ts
  • web/src/interfaces/database/document.ts
  • web/src/locales/en.ts
  • web/src/locales/zh.ts
  • web/src/pages/dataset/dataset-setting/form-schema.ts
  • web/src/pages/dataset/dataset-setting/index.tsx

Comment thread rag/graphrag/general/index.py Resolved
Comment thread rag/graphrag/general/index.py Resolved
@codecov

codecov Bot commented May 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (14c0985) to head (fccce19).
⚠️ Report is 16 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14972   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ View full report in Codecov by Sentry.
📢 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.

@wangq8
wangq8 requested a review from KevinHuSh May 18, 2026 07:46
@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label May 18, 2026
@KevinHuSh
KevinHuSh merged commit 13b4220 into infiniflow:main May 18, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request May 22, 2026
2 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer 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