Skip to content

fix: improve pipeline compilation, template updates, and document resets - #16815

Merged
yingfeng merged 4 commits into
infiniflow:mainfrom
buua436:b104
Jul 10, 2026
Merged

yingfeng merged 4 commits into
infiniflow:mainfrom
buua436:b104

Conversation

@buua436

@buua436 buua436 commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

  • Clear stale pipeline IDs and generated data when updating documents without pipeline_id.
  • Support tree compilation results in pipeline workflows.
  • Update compilation templates in place while preserving existing template IDs.
  • Improve duplicate-template validation messages.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

An error occurred during the review process. Please try again later.


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 added the ci Continue Integration label Jul 10, 2026
@buua436
buua436 requested review from KevinHuSh and cike8899 and removed request for cike8899 July 10, 2026 08:50
@buua436
buua436 marked this pull request as ready for review July 10, 2026 08:51
@dosubot dosubot Bot added 🐞 bug Something isn't working, pull request that fix bug. 💞 feature Feature request, pull request that fullfill a new feature. size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 10, 2026
@buua436
buua436 marked this pull request as draft July 10, 2026 08:51
@buua436
buua436 marked this pull request as ready for review July 10, 2026 08:51
@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
putComment timed out

@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 (6)
rag/flow/compiler/compiler.py (2)

104-105: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add strict=True to zip to catch encode/text count mismatch.

encode should return one vector per text, but a silent length mismatch would drop trailing chunks unnoticed. strict=True surfaces the invariant break loudly (also clears Ruff B905).

♻️ Proposed fix
-        tree_chunks = [(text, vector, chunk_id) for (text, chunk_id), vector in zip(tree_inputs, vectors)]
+        tree_chunks = [(text, vector, chunk_id) for (text, chunk_id), vector in zip(tree_inputs, vectors, strict=True)]
🤖 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/compiler/compiler.py` around lines 104 - 105, Update the zip call in
the compiler’s embedding construction logic to use strict=True, ensuring vectors
and tree_inputs must have equal lengths and mismatches raise immediately while
resolving Ruff B905.

Source: Linters/SAST tools


190-193: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Fallback loop selects the last list, not the first meaningful one.

Without a break, the loop keeps overwriting chunks with every list-valued kwarg, so the last list wins (and empty lists still trigger a wasteful deepcopy). If upstream ever passes more than one list, this silently picks the wrong upstream payload. Stop at the first non-empty list.

♻️ Proposed fix
         chunks = deepcopy(kwargs.get("chunks") or [])
         if not chunks:
             for val in kwargs.values():
                 if isinstance(val, list):
                     chunks = deepcopy(val)
+                    if chunks:
+                        break
🤖 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/compiler/compiler.py` around lines 190 - 193, Update the fallback
loop in the compiler logic guarded by `if not chunks` to select the first
non-empty list-valued kwarg: require `isinstance(val, list) and val`, deepcopy
it into `chunks`, then immediately break to prevent later lists from overwriting
it.
api/db/services/compilation_template_group_service.py (2)

333-342: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Duplicate-name check is duplicated between update_group and _insert_child.

For the insert path, the tenant-wide duplicate-name query at Lines 333-342 is immediately re-run inside _insert_child (Lines 416-423). Only the update path needs the inline check (to exclude target.id); the insert path can rely solely on _insert_child.

Also applies to: 416-423

🤖 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/compilation_template_group_service.py` around lines 333 -
342, Remove the redundant tenant-wide duplicate-name query from the insert path
in update_group, retaining only the update-specific check that excludes
target.id; ensure _insert_child remains the single place performing
duplicate-name validation for new templates.

298-376: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add logging to the reconciliation flow.

This new reconciliation path (matched/inserted/updated/removed child ids) runs no logging, making failures and unexpected removals hard to diagnose in production. Consider logging a summary (e.g., counts of inserted/updated/removed children) at the end of the block.

As per coding guidelines: "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/compilation_template_group_service.py` around lines 298 -
376, Add a reconciliation summary log at the end of the templates block,
tracking inserted, updated, and removed child IDs or counts throughout the loop
and removal handling. Use the service’s existing logger, if available, and
include the group identifier plus reconciliation counts in the message; ensure
logging occurs after all operations complete.

Source: Coding guidelines

api/apps/restful_apis/document_api.py (1)

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

Add logging for the new pipeline clearing flow.

The new pipeline_id clearing logic across these branches is a new flow with no logging. Adding a log line in reset_document_for_reparse when pipeline_id is explicitly set (especially to "") would aid debugging stale-pipeline issues.

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

📝 Suggested logging addition in `reset_document_for_reparse`
     if pipeline_id is not None:
         update_fields["pipeline_id"] = pipeline_id
+        if pipeline_id == "":
+            logging.info(f"Clearing pipeline_id for document {doc.id}")
🤖 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/apps/restful_apis/document_api.py` around lines 275 - 294, Add logging in
reset_document_for_reparse whenever pipeline_id is explicitly provided,
including when it is set to an empty string. Log the document identifier, tenant
context, and selected pipeline value so pipeline-clearing and stale-pipeline
transitions are traceable.

Source: Coding guidelines

api/apps/services/document_api_service.py (1)

65-95: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Update docstring to reflect the new elif doc.pipeline_id reset path.

The docstring states resets and chunk clearing happen "if the chunk method changes" / "if the method changes", but the new elif doc.pipeline_id branch now also resets and clears chunks when the method is unchanged but a pipeline was previously set.

📝 Proposed docstring update
     """
     Update chunk method only (without validation).

     Updates the chunk method and parser configuration for a document,
-    and resets the document's progress if the chunk method changes.
-    Also clears existing chunks from the document store if the method changes.
+    and resets the document's progress if the chunk method changes or if
+    a previously-set pipeline_id needs to be cleared. Also clears existing
+    chunks from the document store in either case.
🤖 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/apps/services/document_api_service.py` around lines 65 - 95, Update the
docstring for update_chunk_method to state that the document is reset and
existing chunks are cleared when the chunk method changes or when an existing
pipeline must be cleared, including when the method is unchanged.
🤖 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 `@api/apps/restful_apis/document_api.py`:
- Around line 281-286: Prevent duplicate reparse resetting in the chunk-method
update branch: after update_chunk_method() handles an unchanged chunk method
with an existing pipeline, do not call reset_document_for_reparse() again from
the parser_config_template_group_changed condition. Adjust the logic around
update_chunk_method and reset_document_for_reparse so each document is reset at
most once while preserving necessary resets for cases not already handled.

In `@api/db/services/compilation_template_group_service.py`:
- Around line 311-319: Restrict the positional fallback in the
template-processing loop to legacy payloads containing no child IDs at all.
Before iterating, determine whether any submitted child has an ID, then allow
the `current_children[index]` assignment only when the entire payload is
ID-less; retain normal ID-based matching and validation for mixed or fully
identified payloads.

In `@rag/flow/compiler/compiler.py`:
- Around line 262-268: Guard the result of KnowledgebaseService.get_by_id in the
KB configuration branch before accessing kb. If the lookup indicates failure or
returns None, raise LookupError (or otherwise handle the missing knowledge base)
and only evaluate kb.tenant_embd_id after confirming kb exists.

---

Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 275-294: Add logging in reset_document_for_reparse whenever
pipeline_id is explicitly provided, including when it is set to an empty string.
Log the document identifier, tenant context, and selected pipeline value so
pipeline-clearing and stale-pipeline transitions are traceable.

In `@api/apps/services/document_api_service.py`:
- Around line 65-95: Update the docstring for update_chunk_method to state that
the document is reset and existing chunks are cleared when the chunk method
changes or when an existing pipeline must be cleared, including when the method
is unchanged.

In `@api/db/services/compilation_template_group_service.py`:
- Around line 333-342: Remove the redundant tenant-wide duplicate-name query
from the insert path in update_group, retaining only the update-specific check
that excludes target.id; ensure _insert_child remains the single place
performing duplicate-name validation for new templates.
- Around line 298-376: Add a reconciliation summary log at the end of the
templates block, tracking inserted, updated, and removed child IDs or counts
throughout the loop and removal handling. Use the service’s existing logger, if
available, and include the group identifier plus reconciliation counts in the
message; ensure logging occurs after all operations complete.

In `@rag/flow/compiler/compiler.py`:
- Around line 104-105: Update the zip call in the compiler’s embedding
construction logic to use strict=True, ensuring vectors and tree_inputs must
have equal lengths and mismatches raise immediately while resolving Ruff B905.
- Around line 190-193: Update the fallback loop in the compiler logic guarded by
`if not chunks` to select the first non-empty list-valued kwarg: require
`isinstance(val, list) and val`, deepcopy it into `chunks`, then immediately
break to prevent later lists from overwriting it.
🪄 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: 348b8288-132a-46c0-99a6-43fad6b8df1f

📥 Commits

Reviewing files that changed from the base of the PR and between 07a3523 and 909ed92.

📒 Files selected for processing (7)
  • api/apps/restful_apis/document_api.py
  • api/apps/services/document_api_service.py
  • api/db/services/compilation_template_group_service.py
  • rag/flow/compiler/compiler.py
  • web/src/interfaces/request/compilation-template.ts
  • web/src/pages/user-setting/compilation-templates/edit-template/schema.ts
  • web/src/pages/user-setting/compilation-templates/edit-template/utils.ts

Comment on lines 281 to 286
elif update_doc_req.chunk_method:
if error := update_chunk_method(req, doc, tenant_id):
return error
if parser_config_template_group_changed and doc.parser_id.lower() == req["chunk_method"].lower():
if error := reset_document_for_reparse(doc, tenant_id):
if error := reset_document_for_reparse(doc, tenant_id, pipeline_id=""):
return error

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Find and inspect the implementation of increment_chunk_num.
rg -n -A 20 'def increment_chunk_num' --type py api/db/services/

Repository: infiniflow/ragflow

Length of output: 1928


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the full increment/reset/update path around the cited functions.
sed -n '600,700p' api/db/services/document_service.py
printf '\n==== update_chunk_method ====\\n'
sed -n '70,120p' api/apps/restful_apis/document_api_service.py
printf '\n==== document_api update branch ====\\n'
sed -n '260,295p' api/apps/restful_apis/document_api.py

Repository: infiniflow/ragflow

Length of output: 4629


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the owning files and inspect the relevant branch.
fd -a 'document_api*.py' api | sort
printf '\n==== update_chunk_method definitions ====\\n'
rg -n -A 25 -B 10 'def update_chunk_method|reset_document_for_reparse|chunk_method' api/apps api/db -g '*.py'

Repository: infiniflow/ragflow

Length of output: 41593


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Narrowly inspect the actual document API handler around the cited lines.
python3 - <<'PY'
from pathlib import Path
for path in [Path('api/apps/restful_apis/document_api.py')]:
    if path.exists():
        text = path.read_text().splitlines()
        for start in [270]:
            end = min(len(text), 300)
            print(f'==== {path} {start+1}-{end} ====')
            for i in range(start, end):
                print(f'{i+1}: {text[i]}')
    else:
        print(f'missing: {path}')
PY

Repository: infiniflow/ragflow

Length of output: 2183


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find the actual API file and the reset path around the chunk_method branch.
fd -a 'document_api.py' api | sort
printf '\n==== chunk_method branch ====\\n'
rg -n -A 20 -B 10 'elif update_doc_req\.chunk_method|parser_config_template_group_changed|reset_document_for_reparse|update_chunk_method' api -g '*.py'

Repository: infiniflow/ragflow

Length of output: 14352


Avoid the duplicate reparse reset in api/apps/restful_apis/document_api.py:281-286
When chunk_method is unchanged and a pipeline is already set, update_chunk_method() resets the document once, then line 284-286 resets it again for the same document. That repeats the KB/document counter adjustment path and can silently double-decrement aggregate counts.

🤖 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/apps/restful_apis/document_api.py` around lines 281 - 286, Prevent
duplicate reparse resetting in the chunk-method update branch: after
update_chunk_method() handles an unchanged chunk method with an existing
pipeline, do not call reset_document_for_reparse() again from the
parser_config_template_group_changed condition. Adjust the logic around
update_chunk_method and reset_document_for_reparse so each document is reset at
most once while preserving necessary resets for cases not already handled.

Comment on lines +311 to +319
for index, child in enumerate(templates):
child_id = str((child or {}).get("id") or "").strip()
target = current_by_id.get(child_id) if child_id else None
if child_id and target is None:
raise GroupValidationError(f"Template {child_id} does not belong to this group.")
# Older clients did not send child ids. Preserve their
# existing ids by matching the submitted order.
if target is None and not child_id and index < len(current_children):
target = current_children[index]

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the target file and inspect the surrounding function.
ast-grep outline api/db/services/compilation_template_group_service.py --view expanded || true
wc -l api/db/services/compilation_template_group_service.py
sed -n '240,380p' api/db/services/compilation_template_group_service.py

# Find nearby references to current_by_id / retained_ids / current_children.
rg -n "current_by_id|retained_ids|current_children|seen_names|does not belong to this group" api/db/services/compilation_template_group_service.py

Repository: infiniflow/ragflow

Length of output: 8730


Restrict positional fallback to all-id-less payloads. Mixed payloads can bind an id-less child to current_children[index] and then bind the same row again by id later, so the new template is dropped and an existing row is updated twice. Guard the positional path so it only applies to legacy payloads with no ids.

🤖 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/compilation_template_group_service.py` around lines 311 -
319, Restrict the positional fallback in the template-processing loop to legacy
payloads containing no child IDs at all. Before iterating, determine whether any
submitted child has an ID, then allow the `current_children[index]` assignment
only when the entire payload is ID-less; retain normal ID-based matching and
validation for mixed or fully identified payloads.

Comment on lines +262 to +268
if self._canvas._kb_id:
e, kb = KnowledgebaseService.get_by_id(self._canvas._kb_id)
if kb.tenant_embd_id:
try:
embd_model_config = get_model_config_by_id(self._canvas._tenant_id, LLMType.EMBEDDING, kb.tenant_embd_id)
except LookupError:
embd_model_config = resolve_model_config(self._canvas._tenant_id, LLMType.EMBEDDING, kb.embd_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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- compiler outline ---'
ast-grep outline rag/flow/compiler/compiler.py --view expanded | sed -n '1,220p'

echo
echo '--- search KnowledgebaseService/get_by_id ---'
rg -n "class KnowledgebaseService|get_by_id\(" -S rag | sed -n '1,220p'

Repository: infiniflow/ragflow

Length of output: 3288


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Read the relevant slices with line numbers.
for f in rag/flow/compiler/compiler.py; do
  echo "--- $f (250-290) ---"
  sed -n '250,290p' "$f" | cat -n
done

# Locate service definitions and any base implementation.
rg -n "class KnowledgebaseService|def get_by_id\(" rag -S | sed -n '1,220p'

Repository: infiniflow/ragflow

Length of output: 2243


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the service class and the implementation behind get_by_id.
files=$(rg -l "class KnowledgebaseService|def get_by_id\(" rag | tr '\n' ' ')
echo "--- candidate files ---"
printf '%s\n' $files

for f in $files; do
  echo
  echo "--- $f ---"
  # Keep reads small.
  sed -n '1,220p' "$f" | cat -n
done

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find the file that defines KnowledgebaseService and inspect only the relevant slice.
file=$(rg -l "^class KnowledgebaseService\b" rag | head -n 1)
echo "FILE=$file"

if [ -n "$file" ]; then
  ast-grep outline "$file" --view expanded | sed -n '1,220p'
  echo
  # show the class area around get_by_id if present
  rg -n "class KnowledgebaseService|def get_by_id\(" "$file" -n -S
fi

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find the concrete implementation of KnowledgebaseService and its base get_by_id behavior.
rg -n "KnowledgebaseService|class .*Service|def get_by_id\(" rag -S | sed -n '1,260p'

echo
echo '--- files containing KnowledgebaseService ---'
rg -l "KnowledgebaseService" rag -S | sed -n '1,120p'

Repository: infiniflow/ragflow

Length of output: 5977


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the service implementation and its base class contract.
fd -a "knowledgebase_service.py|common_service.py|base_service.py" .

echo
for f in $(fd -a "knowledgebase_service.py|common_service.py|base_service.py" .); do
  echo "--- $f ---"
  sed -n '1,260p' "$f" | cat -n
  echo
done

Repository: infiniflow/ragflow

Length of output: 24337


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show the portion of CommonService around get_by_id and nearby helpers.
sed -n '260,360p' /home/jailuser/git/api/db/services/common_service.py | cat -n

echo
# Also show any direct overrides of get_by_id in knowledgebase_service.py.
rg -n "def get_by_id\(" /home/jailuser/git/api/db/services/knowledgebase_service.py -n -S

Repository: infiniflow/ragflow

Length of output: 3966


Guard the KB lookup before dereferencing kb. CommonService.get_by_id() returns (False, None) for a missing ID, so a stale self._canvas._kb_id will crash here on kb.tenant_embd_id. Raise a LookupError or handle the missing KB before this branch.

🧰 Tools
🪛 Ruff (0.15.20)

[warning] 263-263: Unpacked variable e is never used

Prefix it with an underscore or any other dummy variable pattern

(RUF059)

🤖 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/compiler/compiler.py` around lines 262 - 268, Guard the result of
KnowledgebaseService.get_by_id in the KB configuration branch before accessing
kb. If the lookup indicates failure or returns None, raise LookupError (or
otherwise handle the missing knowledge base) and only evaluate kb.tenant_embd_id
after confirming kb exists.

Source: Linters/SAST tools

@codecov

codecov Bot commented Jul 10, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (eca8e87) to head (4aeebde).
⚠️ Report is 15 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16815   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

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

@yingfeng
yingfeng merged commit d291e46 into infiniflow:main Jul 10, 2026
4 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 💞 feature Feature request, pull request that fullfill a new feature. size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants