Skip to content

fix: optimize dataflow indexing and logs - #17737

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
buua436:b132
Aug 3, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
buua436:b132

Conversation

@buua436

@buua436 buua436 commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Dataflow indexing performs a refresh and updates task checkpoints after every small batch, causing unnecessary Elasticsearch and MySQL overhead when processing many chunks.

Pipeline progress also records empty messages, while operation logs persist large embedding vectors that are not required for rerunning the pipeline and may exceed database packet limits.

This PR:

  • increases the default document bulk size;
  • disables per-batch refresh and refreshes the index once after insertion;
  • reduces the frequency of task chunk-ID checkpoints;
  • filters empty pipeline progress messages;
  • removes q_<dimension>_vec fields from pipeline operation logs while preserving other runtime outputs needed for reruns.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Aug 3, 2026
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR sanitizes embedding vectors from stored pipeline snapshots, adds configurable document-store refresh behavior, reduces chunk-state checkpoint frequency, increases the default document bulk size, and skips empty pipeline callback log entries.

Changes

Pipeline snapshot sanitization

Layer / File(s) Summary
Recursive snapshot sanitization
api/db/services/pipeline_operation_log_service.py, test/unit_test/api/db/services/test_pipeline_operation_log_service.py
The service recursively removes q_<number>_vec fields from nested dictionaries and lists before storing DSL snapshots. Tests verify that content and metadata remain intact.

Bulk insertion refresh control

Layer / File(s) Summary
Refresh parameter propagation
rag/utils/es_conn.py, rag/utils/infinity_conn.py, rag/utils/ob_conn.py, rag/utils/opensearch_conn.py
Document-store insertion methods accept an optional refresh parameter. Elasticsearch and OpenSearch bulk requests forward the supplied value.
Deferred refresh and checkpoints
common/settings.py, rag/svr/task_executor_refactor/chunk_service.py
The default document bulk size increases from 4 to 32. Chunk insertion disables per-batch refreshes, checkpoints task chunk IDs periodically, and performs a final refresh when supported.

Pipeline callback filtering

Layer / File(s) Summary
Skip empty callback messages
rag/flow/pipeline.py
Callbacks with empty or whitespace-only messages return before Redis log processing. Cancellation messages remain processed.

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

Sequence Diagram(s)

sequenceDiagram
  participant ChunkService
  participant DocumentStore
  participant SearchBackend
  participant TaskChunkState
  ChunkService->>DocumentStore: Insert chunks with refresh=False
  DocumentStore->>SearchBackend: Bulk index chunks
  ChunkService->>TaskChunkState: Persist chunk IDs at checkpoints
  ChunkService->>DocumentStore: Refresh index after final batch
Loading

Possibly related PRs

Suggested labels: 🌈 python

Suggested reviewers: yuzhichang

Poem

A rabbit trims vectors from logs in a row,
While chunk batches move with refresh set low.
Empty notes vanish before Redis can hear,
Checkpoints arrive at a steadier tier.
“Hop,” says the rabbit, “the pipeline is neat!”

🚥 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 clearly identifies the main indexing and logging optimizations in the changeset.
Description check ✅ Passed The description explains the problem, summarizes the changes, and identifies the change type, although it does not use the template's Summary heading.
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.

@buua436
buua436 requested a review from wangq8 August 3, 2026 09:42
@buua436 buua436 added the ci Continue Integration label Aug 3, 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: 4

🧹 Nitpick comments (4)
api/db/services/pipeline_operation_log_service.py (1)

54-68: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add aggregate logging for snapshot sanitization.

Log the number of removed vector fields when this flow sanitizes a pipeline snapshot. Do not log the DSL or vector values. This makes data removal observable during pipeline-log troubleshooting.

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 `@api/db/services/pipeline_operation_log_service.py` around lines 54 - 68,
Update _remove_embedding_vectors to count every matching q_<number>_vec field
removed throughout nested dictionaries and lists, and log the aggregate count at
the snapshot-sanitization flow boundary. Keep the log limited to the removal
count and avoid including DSL content or vector values.

Source: Coding guidelines

rag/utils/es_conn.py (1)

337-354: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add bounded logging for the new refresh flow.

Log the index, batch size, requested refresh policy, and whether the backend applied it. Do not log document payloads.

  • rag/utils/es_conn.py#L337-L354: log the refresh value before self.es.bulk.
  • rag/utils/infinity_conn.py#L382-L562: log that the requested refresh value is ignored or applied by an equivalent operation.
  • rag/utils/ob_conn.py#L1017-L1094: log that the requested refresh value is ignored or applied by an equivalent operation.

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/utils/es_conn.py` around lines 337 - 354, Add bounded logging for the
refresh flow at rag/utils/es_conn.py lines 337-354, rag/utils/infinity_conn.py
lines 382-562, and rag/utils/ob_conn.py lines 1017-1094. In the Elasticsearch
insert method, log the index, document batch size, requested refresh value, and
whether the backend applied it immediately before self.es.bulk; in the Infinity
and OpenSearch equivalents, log whether the requested refresh value is ignored
or applied by an equivalent operation. Do not include document payloads.

Source: Coding guidelines

rag/utils/opensearch_conn.py (1)

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

Log the selected refresh policy.

Line 528 starts the caller-controlled refresh flow. Add a debug log with the index name, document count, and refresh value. Do not log document content.

Proposed change
                 res = []
+                logger.debug(
+                    "OSConnection.insert(index=%s, documents=%d, refresh=%r)",
+                    indexName,
+                    len(documents),
+                    refresh,
+                )
                 r = self.os.bulk(index=(indexName), body=operations, refresh=refresh, timeout=60)

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/utils/opensearch_conn.py` at line 528, Add a debug log immediately before
the bulk call in the relevant method, recording the selected index name,
document count, and refresh value. Use the existing logger and avoid including
operation or document contents; keep the subsequent self.os.bulk invocation
unchanged.

Source: Coding guidelines

rag/flow/pipeline.py (1)

52-56: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add observability for the new early-exit path.

This branch silently drops empty callbacks. Add rate-limited debug logging with component_name and task_id, without logging the message content, so operators can verify that filtering works without creating Valkey entries.

As per coding guidelines, **/*.py requires 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/flow/pipeline.py` around lines 52 - 56, Update the empty-message early
return in the progress callback flow to emit rate-limited debug logging before
returning, including component_name and task_id but not the message content. Use
the module’s existing logging and rate-limiting conventions so filtered
callbacks remain observable without creating Valkey entries.

Source: Coding guidelines

🤖 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/flow/pipeline.py`:
- Around line 52-56: Update the callback flow around the empty-message filter so
it skips only Redis and progress persistence for blank messages, without
returning from the callback before the final has_canceled(self.task_id) check.
Keep that cancellation check reachable for every callback invocation, including
empty messages, and preserve the existing persistence behavior for non-empty
messages.

In `@rag/svr/task_executor_refactor/chunk_service.py`:
- Around line 381-383: Update the final refresh flow around refresh_idx in the
batch insert method to capture its return value, log a refresh failure, report
it through the task progress callback, and return failure when the result is
False; preserve the existing behavior when refresh_idx is unavailable or
succeeds.
- Around line 370-379: Update the checkpoint and recovery logic around
_update_task_chunk_ids so TaskService.update_chunk_ids() does not cause
previously inserted, uncheckpointed chunk IDs to be lost. Preserve a cumulative
inserted-chunk list or persist checkpoint progress frequently enough that retry
and cleanup flows can reconstruct and process every inserted chunk, including
chunks from partial batches before the latest checkpoint.

In `@rag/utils/es_conn.py`:
- Line 337: Update the insert method signatures in rag/utils/es_conn.py:337-337,
rag/utils/infinity_conn.py:382-382, and rag/utils/ob_conn.py:1017-1017 so
knowledgebase_id explicitly accepts None via a nullable string annotation while
retaining its default. No other insert parameters or behavior need to change.

---

Nitpick comments:
In `@api/db/services/pipeline_operation_log_service.py`:
- Around line 54-68: Update _remove_embedding_vectors to count every matching
q_<number>_vec field removed throughout nested dictionaries and lists, and log
the aggregate count at the snapshot-sanitization flow boundary. Keep the log
limited to the removal count and avoid including DSL content or vector values.

In `@rag/flow/pipeline.py`:
- Around line 52-56: Update the empty-message early return in the progress
callback flow to emit rate-limited debug logging before returning, including
component_name and task_id but not the message content. Use the module’s
existing logging and rate-limiting conventions so filtered callbacks remain
observable without creating Valkey entries.

In `@rag/utils/es_conn.py`:
- Around line 337-354: Add bounded logging for the refresh flow at
rag/utils/es_conn.py lines 337-354, rag/utils/infinity_conn.py lines 382-562,
and rag/utils/ob_conn.py lines 1017-1094. In the Elasticsearch insert method,
log the index, document batch size, requested refresh value, and whether the
backend applied it immediately before self.es.bulk; in the Infinity and
OpenSearch equivalents, log whether the requested refresh value is ignored or
applied by an equivalent operation. Do not include document payloads.

In `@rag/utils/opensearch_conn.py`:
- Line 528: Add a debug log immediately before the bulk call in the relevant
method, recording the selected index name, document count, and refresh value.
Use the existing logger and avoid including operation or document contents; keep
the subsequent self.os.bulk invocation unchanged.
🪄 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: 47924a39-35e3-472f-bf14-773e32412e4a

📥 Commits

Reviewing files that changed from the base of the PR and between e290a0d and 243cdcd.

📒 Files selected for processing (9)
  • api/db/services/pipeline_operation_log_service.py
  • common/settings.py
  • rag/flow/pipeline.py
  • rag/svr/task_executor_refactor/chunk_service.py
  • rag/utils/es_conn.py
  • rag/utils/infinity_conn.py
  • rag/utils/ob_conn.py
  • rag/utils/opensearch_conn.py
  • test/unit_test/api/db/services/test_pipeline_operation_log_service.py

Comment thread rag/flow/pipeline.py
Comment on lines +52 to +56
# Progress-only callbacks are used for fine-grained updates during
# tokenization and embedding. Do not persist an empty message as a log
# entry; otherwise the task log is filled with timestamp-only lines.
if not str(message or "").strip():
return

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

Keep the cancellation check reachable.

The return at Line 56 bypasses the has_canceled(self.task_id) check at Lines 110-111. If cancellation occurs after Line 49 but before this filter, the callback exits without raising TaskCanceledException. Guard only the Redis and progress persistence block, and keep the final cancellation check outside that guard.

🤖 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/flow/pipeline.py` around lines 52 - 56, Update the callback flow around
the empty-message filter so it skips only Redis and progress persistence for
blank messages, without returning from the callback before the final
has_canceled(self.task_id) check. Keep that cancellation check reachable for
every callback invocation, including empty messages, and preserve the existing
persistence behavior for non-empty messages.

Comment on lines +370 to +379
batch_end = min(b + doc_bulk_size, len(chunks))
is_last_batch = batch_end == len(chunks)
if is_last_batch or batch_end - last_checkpoint >= checkpoint_batches * doc_bulk_size:
chunk_ids = [chunk["id"] for chunk in chunks[:batch_end]]
if not await self._update_task_chunk_ids(task_id, chunk_ids):
# Roll back on failure
await self._rollback_insertion(task_tenant_id, task_dataset_id, chunk_ids)
self._task_context.progress_cb(-1, msg=f"Chunk updates failed since task {task_id} is unknown.")
return False
last_checkpoint = batch_end

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 | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

# Map the changed orchestration methods before inspecting recovery call sites.
ast-grep outline rag/svr/task_executor_refactor/chunk_service.py \
  --items all \
  --match 'ChunkService|_insert_main_chunks|_update_task_chunk_ids|_rollback_insertion'

# Locate task-state persistence and all consumers of persisted chunk IDs.
rg -nP --type py -C 5 '\b(TaskService\.update_chunk_ids|update_chunk_ids|chunk_ids)\b' .

# Locate retry, cancellation, and cleanup paths that must handle a partial checkpoint.
rg -nP --type py -C 5 '\b(retry|resume|rollback|cancel|delete)\b' .

Repository: infiniflow/ragflow

Length of output: 50375


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== outline =="
ast-grep outline rag/svr/task_executor_refactor/chunk_service.py --items all \
  --match 'ChunkService|_insert_main_chunks|_update_task_chunk_ids|_rollback_insertion|start|resume|cancel|delete' || true

echo "== focused chunk_service lines 300-410 =="
sed -n '300,410p' rag/svr/task_executor_refactor/chunk_service.py | nl -ba -v300

echo "== chunk_ids persistence consumers focused =="
rg -n --type py -C 3 '(update_chunk_ids|chunk_ids=|chunk_ids:|\.chunk_ids|\[\"chunk_ids\"|\[chunk_ids)' rag api test/unit_test/rag/svr/task_executor_refactor | head -n 240

echo "== recovery/management focused =="
rg -n --type py -C 4 'chunk_service|_insert_main_chunks|TaskStatus|TASK|RUNNING|CANCEL|CANCELED|DELETE|delete_index|cancel_all_task_of|stop_parsing|process_tasks|queue_tasks|TaskService|update_by_id' rag/svr rag/api test/unit_test/rag/svr/task_executor_refactor | head -n 360

Repository: infiniflow/ragflow

Length of output: 625


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== focused chunk_service lines 300-410 =="
awk 'NR>=300 && NR<=410 {printf "%6d %s\n", NR, $0}' rag/svr/task_executor_refactor/chunk_service.py

echo "== insert_checkpoint constants nearby =="
rg -n --type py -C 4 'checkpoint_batches|doc_bulk_size|last_checkpoint|chunk_ids' rag/svr/task_executor_refactor/chunk_service.py

echo "== focused recovery/delete management =="
rg -n --type py -C 5 '(chunk_service|ChunkService|insert_chunks|_insert_main_chunks|_intercept_doc_store_delete|cancel_all_task_of|delete_index|stop_parsing|TaskStatus|RUNNING|CANCELED|DELETE|TaskService|update_by_id).*' rag/svr rag/api test/unit_test/rag/svr/task_executor_refactor | head -n 400

Repository: infiniflow/ragflow

Length of output: 45446


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== task_service update_chunk_ids definition =="
rg -n --type py -C 10 'def update_chunk_ids|class TaskService|chunk_ids\s*=' api/db/services/task_service.py api/db/db_models.py | head -n 240

echo "== chunk service rollback/update methods =="
awk 'NR>=413 && NR<=480 {printf "%6d %s\n", NR, $0}' rag/svr/task_executor_refactor/chunk_service.py

echo "== task executor/manager deletion/cancellation callers =="
rg -n --type py -C 6 'TaskService\.delete_by_id|TaskService\.get_by_id|TaskStatus\.(CANCEL|DELETE|FAIL|DONE|RUNNING)|cancel_all_task_of|delete_index|delete\(|status.*DELETE|status.*CANCEL' rag/svr test/unit_test/rag/svr/task_executor_refactor | head -n 360

echo "== model fields around Task chunks == "
rg -n --type py -C 5 'class Task|chunk_ids' api/db/db_models.py

Repository: infiniflow/ragflow

Length of output: 26626


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== parse document flow / delete task / reuse task calls =="
rg -n --type py -C 8 'parse\(|queue_tasks|TaskService\.delete_by_id|chunk_ids|get_tasks\(|filter_delete|delete_by_id' rag/svr/api rag/app common test/unit_test/rag | head -n 400

echo "== chunk_ids field reads and consumers =="
rg -n --type py 'chunk_ids[.,:]|\.chunk_ids|split\(\)|chunk_ids\s*=|\["chunk_ids"\]' rag api test/unit_test rag/app common | head -n 360

echo "== status constants =="
rg -n --type py 'class TaskStatus|RUNNING|CANCEL|DELETE|FAIL|DONE' common constants api/db/db_models.py | head -n 200

Repository: infiniflow/ragflow

Length of output: 30954


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== locate task and document parsing files =="
git ls-files | rg '(^|/)task_service\.py$|(^|/)document_service\.py$|(^|/)task_executor_refactor/|chunk_service\.py$' | head -n 120

echo "== task executor refactor status/cleanup around _run do_handle_task =="
rg -n --type py -C 8 'class TaskContext|do_handle_task|run_do_handle_task|insert_chunks|has_canceled|update.*status|TaskStatus|queue_tasks|TaskService\.delete_by_id' rag/svr/task_executor_refactor rag/svr/task_executor.py | head -n 400

echo "== parse/queue usage =="
rg -n --type py -C 6 'queue_tasks|duplicate_and_parse|TaskService\.filter_delete|chunk_ids|update_document|begin2parse|create_tasks|TaskStatus' rag/svr/common rag/svr/api rag/svr rag/app common | head -n 400

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== task_executor_refactor lifecycle and cleanup =="
awk 'NR>=1 && NR<=260 {printf "%6d %s\n", NR, $0}' rag/svr/task_executor_refactor/task_handler.py
awk 'NR>=1 && NR<=260 {printf "%6d %s\n", NR, $0}' rag/svr/task_executor_refactor/task_manager.py
awk 'NR>=1 && NR<=260 {printf "%6d %s\n", NR, $0}' rag/svr/task_executor_refactor/task_context.py

echo "== old executor cleanup/final handling =="
awk 'NR>=1723 && NR<=1760 {printf "%6d %s\n", NR, $0}' rag/svr/task_executor.py

echo "== TaskService chunk/delete/status operations =="
awk 'NR>=280 && NR<=480 {printf "%6d %s\n", NR, $0}' api/db/services/task_service.py

echo "== all exact chunk_ids reads/splits with context =="
rg -n --type py -C 3 '\.chunk_ids|chunk_ids\.split|chunk_ids:"|chunk_ids=' \
  rag/svr/task_executor.py rag/svr/task_executor_refactor \
  api/db/services/task_service.py rag/api rag/common common r**a\g 2>/dev/null | head -n 180

Repository: infiniflow/ragflow

Length of output: 49793


Handle uncheckpointed inserted chunks in recovery paths.

TaskService.update_chunk_ids() overwrites chunk_ids, so between two checkpoints only recent inserted IDs remain in the task record. If the retry/cleanup flows rely on TaskService.get_tasks() and the stored chunk_ids, partial chunks inserted before the last checkpoint can be skipped or handled incorrectly. Make recovery reconstruct the inserted chunk list from available task state or persist checkpoint progress more frequently.

🤖 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/svr/task_executor_refactor/chunk_service.py` around lines 370 - 379,
Update the checkpoint and recovery logic around _update_task_chunk_ids so
TaskService.update_chunk_ids() does not cause previously inserted,
uncheckpointed chunk IDs to be lost. Preserve a cumulative inserted-chunk list
or persist checkpoint progress frequently enough that retry and cleanup flows
can reconstruct and process every inserted chunk, including chunks from partial
batches before the latest checkpoint.

Comment on lines +381 to +383
refresh_idx = getattr(settings.docStoreConn, "refresh_idx", None)
if callable(refresh_idx):
await thread_pool_exec(refresh_idx, search.index_name(task_tenant_id))

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

Handle a failed final index refresh.

The batch inserts use refresh=False. OSConnection.refresh_idx returns False on a refresh failure. Lines 381-383 ignore that result, so this method can return True while inserted chunks are not yet searchable.

Return failure when refresh_idx returns False. Log the failure and report it through the task progress callback.

Proposed change
         refresh_idx = getattr(settings.docStoreConn, "refresh_idx", None)
         if callable(refresh_idx):
-            await thread_pool_exec(refresh_idx, search.index_name(task_tenant_id))
+            refreshed = await thread_pool_exec(refresh_idx, search.index_name(task_tenant_id))
+            if refreshed is False:
+                logging.error("Failed to refresh document-store index for task %s", task_id)
+                self._task_context.progress_cb(-1, msg="Document-store index refresh failed.")
+                return False

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

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
refresh_idx = getattr(settings.docStoreConn, "refresh_idx", None)
if callable(refresh_idx):
await thread_pool_exec(refresh_idx, search.index_name(task_tenant_id))
refresh_idx = getattr(settings.docStoreConn, "refresh_idx", None)
if callable(refresh_idx):
refreshed = await thread_pool_exec(refresh_idx, search.index_name(task_tenant_id))
if refreshed is False:
logging.error("Failed to refresh document-store index for task %s", task_id)
self._task_context.progress_cb(-1, msg="Document-store index refresh failed.")
return False
🤖 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/svr/task_executor_refactor/chunk_service.py` around lines 381 - 383,
Update the final refresh flow around refresh_idx in the batch insert method to
capture its return value, log a refresh failure, report it through the task
progress callback, and return failure when the result is False; preserve the
existing behavior when refresh_idx is unavailable or succeeds.

Source: Coding guidelines

Comment thread rag/utils/es_conn.py
raise Exception("ESConnection.search timeout.")

def insert(self, documents: list[dict], index_name: str, knowledgebase_id: str = None) -> list[str]:
def insert(self, documents: list[dict], index_name: str, knowledgebase_id: str = None, refresh: str | bool = "wait_for") -> list[str]:

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

ruff check --select RUF013 \
  rag/utils/es_conn.py \
  rag/utils/infinity_conn.py \
  rag/utils/ob_conn.py

Repository: infiniflow/ragflow

Length of output: 2295


Use explicit None optionals for optional insertion parameters.

RUF013 reports implicit Optional at all three signatures because knowledgebase_id is annotated as str while its default is None. Update each insert signature to pass RUF013 and make the nullable contract explicit.

  • rag/utils/es_conn.py#L337: knowledgebase_id: str | None = None
  • rag/utils/infinity_conn.py#L382: knowledgebase_id: str | None = None
  • rag/utils/ob_conn.py#L1017: knowledgebase_id: str | None = None
🧰 Tools
🪛 Ruff (0.16.0)

[warning] 337-337: PEP 484 prohibits implicit Optional

Convert to T | None

(RUF013)

📍 Affects 3 files
  • rag/utils/es_conn.py#L337-L337 (this comment)
  • rag/utils/infinity_conn.py#L382-L382
  • rag/utils/ob_conn.py#L1017-L1017
🤖 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/utils/es_conn.py` at line 337, Update the insert method signatures in
rag/utils/es_conn.py:337-337, rag/utils/infinity_conn.py:382-382, and
rag/utils/ob_conn.py:1017-1017 so knowledgebase_id explicitly accepts None via a
nullable string annotation while retaining its default. No other insert
parameters or behavior need to change.

Source: Linters/SAST tools

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this PR — the optimizations make sense and the code is well-structured. A few observations and suggestions:

What works well

  • Bulk size increase (4→32): Reasonable default that cuts down Elasticsearch/OpenSearch bulk request overhead.
  • Per-batch refresh=False: This is the right call for bulk ingestion. The old "wait_for" on every small batch was expensive.
  • Checkpoint throttling: Reducing MySQL update_task_chunk_ids calls from every batch to every ~256 chunks is a good trade-off — still resumable, much less DB churn.
  • Empty progress filter in pipeline.py: Clean fix; avoids polluting the task log with timestamp-only entries.
  • Embedding vector stripping in operation logs: The _remove_embedding_vectors implementation is clean and handles nested dicts/lists correctly. The unit test covers the expected shape well.

Items worth attention

  1. refresh_idx availability: The final refresh_idx call in _insert_main_chunks only actually works on OpenSearch (the only connector that implements it). ES, Infinity, and OB don't have this method. The getattr + callable guard means no crash, but for ES specifically, documents won't be immediately searchable after the bulk insert — they'll appear after the index's default refresh_interval (~1s). This is fine for dataflow indexing (eventual consistency is acceptable), but worth a comment.

  2. Infinity / OB insert signature: These two connectors now accept refresh in their signatures but don't actually use the parameter in their method bodies. This is fine for interface consistency, but consider adding a brief comment noting the parameter is accepted for compatibility.

  3. refresh_idx only in _insert_main_chunks: _insert_mother_chunks also passes refresh=False but doesn't get a matching final refresh_idx call. If mother chunks are expected to be immediately queryable after insertion, this could be a gap. Please confirm this is intentional.

  4. Memory pressure from DOC_BULK_SIZE=32: For deployments using large embedding dimensions, 32 chunks per batch could increase memory pressure during bulk insert. Consider whether this should be a per-deployment tuning knob rather than a hardcoded default — or at least documented as adjustable via DOC_BULK_SIZE env var.

  5. Edge case — DOC_BULK_SIZE=0 or negative: The formula checkpoint_batches = max(1, 256 // doc_bulk_size) would raise ZeroDivisionError if someone set DOC_BULK_SIZE=0. Consider a guard or clamping in init_settings.

Summary

The PR is solid. The core optimizations (batch refresh, checkpoint throttling, empty-message filtering, vector stripping) are all well-reasoned and correctly implemented. The items above are minor — the main one to consider is the refresh_idx gap for non-OpenSearch backends. Approving with these suggestions.

@codecov

codecov Bot commented Aug 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (3b4a96d) to head (243cdcd).
⚠️ Report is 14 commits behind head on main.

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

@wangq8
wangq8 merged commit 1d141af into infiniflow:main Aug 3, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants