Skip to content

refactor(knowledge_compiler): derive variant from template kind via single template id - #17630

Merged
yuzhichang merged 7 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port
Jul 31, 2026
Merged

yuzhichang merged 7 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port

Conversation

@yuzhichang

Copy link
Copy Markdown
Member

Summary

Refactor the Go KnowledgeCompilerComponent so its parameter is a single string template id instead of a DSL-level variant (or plural group id list). The variant is no longer in the DSL — it is now derived at runtime from the resolved compilation template's kind field.

This aligns the Go ingestion port with the frontend Compiler operator, which emits a singular compilation_template_group_id and does not write variant into the generated compiler.json.

Changes

Go (internal/ingestion/component/knowledge_compiler)

  • Param contract: Param now carries CompilationTemplateID / CompilationTemplateGroupID (both strings). ParseParam reads compilation_template_id / compilation_template_group_id, requires at least one, and no longer parses variant. Selection priority: compilation_template_id > compilation_template_group_id.
  • KindToVariant replaces normalizeVariant: maps template kind to a compiler variant:
    • tree → tree
    • mind_map / mindmap → mindmap
    • wiki → wiki
    • datasetnav / dataset_nav → datasetnav
    • page_index / session_essence / session_graph / timeline / knowledge_graph / structure / knowledgegraph / graph → structure
    • else → ErrUnknownVariant
  • Template resolution seam: new TemplateResolver + SetTemplateResolver / ResolveTemplate in the dependency-light common package, returning TemplateInfo{ID, Kind, Config}.
  • Wiring: knowledge_compiler_wiring.go installs the DB-backed SetTemplateResolver; new dao.GetTemplate performs a valid + tenant-scoped lookup.
  • Migration: compilation_template / compilation_template_group added to the GORM migration list in internal/dao/database.go, ensuring the tables exist on the Go side.
  • Invoke: resolves template specs (id > group), derives the variant per spec via KindToVariant, and stamps each product with compilation_template_ids, Kind, TemplateID, and Variant.

Python (rag/flow/compiler/compiler.py)

  • Consume compilation_template_group_id (singular) with a fallback to the legacy plural compilation_template_group_ids, normalizing to the internal list for backward compatibility.

Frontend

  • Compiler emits singular compilation_template_group_id (replacing compilation_template_group_ids) in compilation-node.tsx, compilation-form/index.tsx, constant/pipeline.tsx, and the agent/templates/compiler.json fixture.

Tests

  • Component + golden tests updated to the new param contract.
  • pipeline_knowledge_compiler_dsl_test.go rewritten: singular group id fixture, id>group priority, KindToVariant cases, and resolver-seam coverage via stubbed resolvers.
  • Verified: bash build.sh --test ./internal/ingestion/... compiles and all component/pipeline/task/dao test packages pass.

Notes

  • This is a deliberate scope reduction vs Python: Go supports a single template id (or group), not the multi-group fan-out from resolve_template_ids_from_groups.
  • The compilation_template_group_ids plural key is still accepted by Python for backward compatibility.

… with tree.yaml

- Rename raptor/ package to tree/ (git mv)
- VariantRaptor -> VariantTree; normalizeVariant "raptor" -> "tree"
- Align default summary prompt with production tree.yaml prompt
  (preserve 6-space indent before {cluster_content})
- Keep ES column names raptor_kwd/raptor_layer_int unchanged
- Rename golden baseline raptor_baseline.json -> tree_baseline.json
- Sync component/golden/structure tests
…ingle template id

- Replace DSL variant with a single string template id (compilation_template_id >
  compilation_template_group_id); variant is resolved at runtime from the template
  kind via common.KindToVariant.
- Add SetTemplateResolver seam + dao.GetTemplate; register compilation_template/
  compilation_template_group in the migration list.
- Frontend emits singular compilation_template_group_id; Python compiler.py accepts
  singular with plural fallback.
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds template-driven knowledge compilation. It resolves tenant-scoped templates, dispatches compilers by template kind, seeds built-in templates, uses singular group identifiers, renames RAPTOR processing to tree, improves JSON serialization, and expands tests.

Changes

Knowledge compilation template integration

Layer / File(s) Summary
Template workflow and persistence contracts
agent/templates/compiler.json, internal/dao/..., web/src/pages/agent/..., rag/flow/compiler/compiler.py
Adds the compiler workflow, template lookup and seeding, database migration, singular group-ID fields, and Python compatibility handling.
Resolver seam and parameter binding
internal/ingestion/component/knowledge_compiler/common/..., internal/ingestion/task/..., internal/ingestion/pipeline/...
Adds template resolver hooks, template metadata, required template identifiers, kind-to-variant mapping, production wiring, and DSL tests.
Compiler orchestration and tree variant
internal/ingestion/component/knowledge_compiler/component.go, .../tree/..., .../mindmap/..., .../structure/...
Resolves templates or groups, overlays configuration, dispatches compilers, records provenance, renames RAPTOR processing to tree, and uses standard JSON serialization.
Outputs, metrics, and regression coverage
internal/ingestion/component/knowledge_compiler/*_test.go, .../golden/*
Validates template provenance, group resolution, dataset behavior, tree execution, source coverage, JSON handling, and fixtures.

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

Sequence Diagram(s)

sequenceDiagram
  participant Frontend
  participant KnowledgeCompiler
  participant TemplateResolver
  participant CompilationTemplateDAO
  participant VariantCompiler
  Frontend->>KnowledgeCompiler: submit template or group ID
  KnowledgeCompiler->>TemplateResolver: resolve template metadata
  TemplateResolver->>CompilationTemplateDAO: load tenant-scoped template
  CompilationTemplateDAO-->>TemplateResolver: return template kind and config
  TemplateResolver-->>KnowledgeCompiler: return TemplateInfo
  KnowledgeCompiler->>VariantCompiler: compile using mapped variant
  VariantCompiler-->>KnowledgeCompiler: return products with provenance
Loading

Possibly related PRs

Suggested labels: 💞 feature

Poem

A rabbit maps each template line,
Tree-shaped outputs now align.
Groups resolve and JSON gleams,
IDs flow through compiler streams.
“Hop onward,” says the rabbit bright. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 74.19% 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 summarizes the primary refactor: deriving the compiler variant from the template kind using a single template ID.
Description check ✅ Passed The description includes a clear summary, background, implementation details, compatibility notes, scope limits, and test results.
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.

@yuzhichang yuzhichang added the ci Continue Integration label Jul 31, 2026
Keep the file locally; it is a working note, not part of the PR.

@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 (4)
web/src/pages/agent/canvas/node/compilation-node.tsx (1)

13-13: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Converge the agent form type to string.

CompilationForm saves compilation_template_group_id via useWatchFormChange as a single ID, and CompilationNode reads the same form.compilation_template_group_id for label lookup. The stale string[] type in the document request/database interfaces can keep old saved nodes compatible, but align the agent form contract to string to avoid false array/null failures.

🤖 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 `@web/src/pages/agent/canvas/node/compilation-node.tsx` at line 13, Update the
agent form contract for compilation_template_group_id from string[] to string,
including the CompilationForm/useWatchFormChange types and related
CompilationNode form typing. Keep document request and database interfaces that
intentionally support legacy string[] values unchanged, while preserving the
existing label lookup in CompilationNode.
tasks/knowledge_compile_tree_raptor_plan.md (1)

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

Remove this completed execution log.

This file records completed phases, prior review findings, and historical decisions. It creates a second source of truth that will drift from the code and tests. Keep current behavior in code, tests, and PR discussion, then delete this file.

As per coding guidelines, “Remove dead tests, commented-out code, stale documentation, and 'move later' notes instead of preserving them.”

🤖 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 `@tasks/knowledge_compile_tree_raptor_plan.md` around lines 1 - 286, Delete
this completed implementation-plan document entirely. The current behavior and
decisions are already represented by the knowledge compiler code, tests, and PR
discussion, so do not preserve or relocate the historical execution log.

Source: Coding guidelines

rag/flow/compiler/compiler.py (1)

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

Avoid compatibility wording and add logging for the fallback path.

The docstring states the plural key compilation_template_group_ids "is still accepted as a fallback so existing pipelines keep working." Coding guidelines direct removal of compatibility wording from comments and documentation. Rephrase the docstring to describe the accepted inputs without wording of that kind.

check() also introduces a new normalization flow with no logging. Add a log statement when the legacy plural key is used, so operators can track remaining reliance on it.

♻️ Proposed fix
     def check(self):
         # Prefer the singular group id emitted by the frontend; fall back to the
-        # legacy plural key for backward compatibility. check() normalises the
+        # legacy plural key when the singular key is absent. check() normalises the
         # chosen value into self.compilation_template_group_ids (a list) so the
         # rest of the Compiler only ever reads that.
         group = self.compilation_template_group_id or self.compilation_template_group_ids
+        if not self.compilation_template_group_id and self.compilation_template_group_ids:
+            logging.warning("Compiler: using legacy compilation_template_group_ids field")
         self.check_empty(group, "Compilation Template Group")

Based on learnings, this comment applies the coding guidelines **/*: Do not add compatibility wording in comments or documentation and **/*.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/flow/compiler/compiler.py` around lines 46 - 68, Update the class
docstring to describe the singular and plural configuration inputs without
compatibility or legacy-pipeline wording. In the configuration normalization
logic of __init__/check, log when compilation_template_group_id is absent and
the plural compilation_template_group_ids value is selected, while preserving
the existing normalization and validation behavior.

Source: Coding guidelines

internal/ingestion/component/knowledge_compiler/tree/raptor.go (1)

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

Rename the remaining "raptor"-branded identifiers to match the "tree" rename.

This file's package, package doc, log/error messages, and Variant values were renamed from raptor to tree, but defaultRaptorPrompt and resolveRaptorPrompt (and their call site, plus "raptor: summarization failed after %d attempts" at line 374) still carry the old name. This leaves the file half-migrated: the constant's own comment says it mirrors "the tree compilation template," while the identifier itself still says "Raptor."

♻️ Proposed rename
-const defaultRaptorPrompt = "..."
+const defaultTreePrompt = "..."
-func resolveRaptorPrompt(param common.Param) string {
+func resolveTreePrompt(param common.Param) string {
 	if raw, ok := param.Extra["prompt"]; ok {
 		if s, ok := raw.(string); ok && strings.TrimSpace(s) != "" {
 			return s
 		}
 	}
-	return defaultRaptorPrompt
+	return defaultTreePrompt
 }

Update the call site (taskPrompt := resolveRaptorPrompt(param)) and the "raptor: summarization failed after %d attempts" message at line 374 to match.

As per coding guidelines: "**/*.go: Remove commented-out Go code and keep package and doc comments aligned with the current runtime path rather than migration history." Based on learnings, "In actively refactored Go ingestion, parser, and DeepDOC code, collapse duplicate paths and do not preserve transitional wrappers or deprecated APIs."

🤖 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/component/knowledge_compiler/tree/raptor.go` around lines
543 - 571, Rename the remaining Raptor-branded symbols to tree equivalents:
update defaultRaptorPrompt and resolveRaptorPrompt, their call site, and the
summarization failure message to use “tree” consistently. Keep the existing
prompt behavior unchanged and remove migration-history wording or commented-out
Go code if present in the affected area.

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 `@agent/templates/compiler.json`:
- Line 8: Update the compilation template setup associated with
compilation_template_group_id so the fixed group
c3aa748c8b2111f191f3047c16ec874f is provisioned for every tenant before
CompilationTemplateGroupService.resolve_template_ids() runs. Ensure each tenant
has a valid group for that ID, rather than relying on a missing-group fallback,
so the Compiler receives active template IDs.

In `@internal/ingestion/component/knowledge_compiler/component.go`:
- Around line 218-240: The overlayTemplateConfig function currently overwrites
explicit per-call LLMID and EmbeddingModel values with template configuration.
Only apply cfg["llm_id"] and cfg["embedding_model"] when the corresponding param
fields are empty, preserving caller-provided overrides while retaining template
defaults.

In
`@internal/ingestion/component/knowledge_compiler/golden/fixtures/tree_baseline.json`:
- Line 8: Update
internal/ingestion/component/knowledge_compiler/golden/metrics.go at line 73 to
track source-to-leaf assignments and compute CoverageFraction from the number of
covered source chunks divided by nChunks, rather than structural properties. In
internal/ingestion/component/knowledge_compiler/golden/fixtures/tree_baseline.json
at line 8, retain leaf_coverage_min: 1.0 once the metric uses source-chunk
coverage.

---

Nitpick comments:
In `@internal/ingestion/component/knowledge_compiler/tree/raptor.go`:
- Around line 543-571: Rename the remaining Raptor-branded symbols to tree
equivalents: update defaultRaptorPrompt and resolveRaptorPrompt, their call
site, and the summarization failure message to use “tree” consistently. Keep the
existing prompt behavior unchanged and remove migration-history wording or
commented-out Go code if present in the affected area.

In `@rag/flow/compiler/compiler.py`:
- Around line 46-68: Update the class docstring to describe the singular and
plural configuration inputs without compatibility or legacy-pipeline wording. In
the configuration normalization logic of __init__/check, log when
compilation_template_group_id is absent and the plural
compilation_template_group_ids value is selected, while preserving the existing
normalization and validation behavior.

In `@tasks/knowledge_compile_tree_raptor_plan.md`:
- Around line 1-286: Delete this completed implementation-plan document
entirely. The current behavior and decisions are already represented by the
knowledge compiler code, tests, and PR discussion, so do not preserve or
relocate the historical execution log.

In `@web/src/pages/agent/canvas/node/compilation-node.tsx`:
- Line 13: Update the agent form contract for compilation_template_group_id from
string[] to string, including the CompilationForm/useWatchFormChange types and
related CompilationNode form typing. Keep document request and database
interfaces that intentionally support legacy string[] values unchanged, while
preserving the existing label lookup in CompilationNode.
🪄 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: 9058263e-1e15-4afb-9ba0-a0fcb61aa4e4

📥 Commits

Reviewing files that changed from the base of the PR and between 4f05866 and 768d784.

📒 Files selected for processing (26)
  • agent/templates/compiler.json
  • internal/dao/compilation_template.go
  • internal/dao/database.go
  • internal/ingestion/component/knowledge_compiler/common/deps.go
  • internal/ingestion/component/knowledge_compiler/common/types.go
  • internal/ingestion/component/knowledge_compiler/component.go
  • internal/ingestion/component/knowledge_compiler/component_test.go
  • internal/ingestion/component/knowledge_compiler/golden/corpus.go
  • internal/ingestion/component/knowledge_compiler/golden/fixtures/tree_baseline.json
  • internal/ingestion/component/knowledge_compiler/golden/golden_test.go
  • internal/ingestion/component/knowledge_compiler/golden/metrics.go
  • internal/ingestion/component/knowledge_compiler/golden_test.go
  • internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go
  • internal/ingestion/component/knowledge_compiler/mindmap/mindmap_test.go
  • internal/ingestion/component/knowledge_compiler/structure/structure.go
  • internal/ingestion/component/knowledge_compiler/tree/raptor.go
  • internal/ingestion/component/knowledge_compiler/tree/raptor_test.go
  • internal/ingestion/component/knowledge_compiler/tree/watershed.go
  • internal/ingestion/component/knowledge_compiler/tree/watershed_test.go
  • internal/ingestion/pipeline/pipeline_knowledge_compiler_dsl_test.go
  • internal/ingestion/task/knowledge_compiler_wiring.go
  • rag/flow/compiler/compiler.py
  • tasks/knowledge_compile_tree_raptor_plan.md
  • web/src/pages/agent/canvas/node/compilation-node.tsx
  • web/src/pages/agent/constant/pipeline.tsx
  • web/src/pages/agent/form/compilation-form/index.tsx

"obj": {
"component_name": "Compiler",
"params": {
"compilation_template_group_id": "c3aa748c8b2111f191f3047c16ec874f",

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

group_id='c3aa748c8b2111f191f3047c16ec874f'

# Find the authoritative seed, migration, or resolver path for this ID.
rg -n -C 5 --fixed-strings "$group_id" .

# Inspect group creation and tenant-scoped resolution paths.
rg -n -C 5 'CompilationTemplateGroup|compilation_template_group|SeedCanvasTemplates' \
  --glob '*.go' --glob '*.py' --glob '*.sql' .

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the template group resolver and compiler fallback path.
for f in \
  api/db/services/compilation_template_group_service.py \
  rag/svr/task_executor_refactor/chunk_post_processor.py \
  rag/flow/compiler/compiler.py \
  rag/svr/task_executor_refactor/task_handler.py \
  rag/advanced_rag/knowlege_compile/runner.py
do
  if [ -f "$f" ]; then
    echo "===== $f ====="
    nl -ba "$f" | sed -n '/CompilationTemplateGroupService.resolve_template_ids/,/Exception$/p
                   /resolve_template_ids_from_groups/,/No active compilation templates resolved/p
                   /No compiler templates resolved from the configured groups/p
                   /parser_config_compilation_template_group_ids/,/elif selected_template_ids:/p' \
      | head -n 220
  else
    echo "MISSING $f"
  fi
done

# Locate the group seed/migration references for the static template group id.
python3 - <<'PY'
import pathlib, re
id_ = "c3aa748c8b2111f191f3047c16ec874f"
for p in pathlib.Path(".").rglob("*"):
    if not p.is_file():
        continue
    try:
        text = p.read_text(errors="ignore")
    except Exception:
        continue
    if id_ in text:
        line = text.count("\n", 0, text.index(id_)) + 1
        print(f"{p}:{line}:{id_}")
PY

# Locate SeedCanvasTemplates definitions.
rg -n --glob '*.go' --glob '*.py' --glob '*.sql' 'SeedCanvasTemplates|SeedCompilation|canvas|compilation_template|CompilationTemplateGroup' . \
  | head -n 220

Repository: infiniflow/ragflow

Length of output: 263


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Use awk instead of nl.
for f in \
  api/db/services/compilation_template_group_service.py \
  rag/svr/task_executor_refactor/chunk_post_processor.py \
  rag/flow/compiler/compiler.py \
  rag/svr/task_executor_refactor/task_handler.py \
  rag/advanced_rag/knowlege_compile/runner.py
do
  if [ -f "$f" ]; then
    echo "===== $f ====="
    awk '{printf "%6d  %s\n", NR, $0}' "$f" | sed -n '/CompilationTemplateGroupService.resolve_template_ids/,/Exception$/p
                   /resolve_template_ids_from_groups/,/No active compilation templates resolved/p
                   /No compiler templates resolved from the configured groups/p
                   /parser_config_compilation_template_group_ids/,/elif selected_template_ids:/p' \
      | head -n 220
  else
    echo "MISSING $f"
  fi
done

# Locate the group seed/migration references for the static template group id.
python3 - <<'PY'
import pathlib
id_ = "c3aa748c8b2111f191f3047c16ec874f"
for p in pathlib.Path(".").rglob("*"):
    if not p.is_file():
        continue
    try:
        text = p.read_text(errors="ignore")
    except Exception:
        continue
    if id_ in text:
        line = text.count("\n", 0, text.index(id_)) + 1
        print(f"{p}:{line}:{id_}")
PY

# Locate SeedCanvasTemplates definitions.
rg -n --glob '*.go' --glob '*.py' --glob '*.sql' 'SeedCanvasTemplates|SeedCompilation|canvas|compilation_template|CompilationTemplateGroup' . \
  | head -n 220

Repository: infiniflow/ragflow

Length of output: 10694


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the exact resolver and compiler fallback behavior.
sed -n '210,240p' api/db/services/compilation_template_group_service.py
sed -n '510,540p' rag/flow/compiler/compiler.py
sed -n '90,120p' rag/svr/task_executor_refactor/chunk_post_processor.py
sed -n '60,90p' api/db/services/compilation_template_service.py

# Find all exact references to the static id with file name and line count.
python3 - <<'PY'
import pathlib
id_ = "c3aa748c8b2111f191f3047c16ec874f"
for p in pathlib.Path(".").rglob("*"):
    if not p.is_file():
        continue
    if p.name in (".DS_Store",):
        continue
    try:
        text = p.read_text(errors="ignore")
    except Exception:
        continue
    count = text.count(id_)
    if count:
        print(f"ref{count}: {p}")
PY

# Find SeedCanvasTemplates candidates.
sed -n '1,260p' internal/development/seed/init.go 2>/dev/null || true
rg -n --glob '*.go' --glob '*.py' --glob '*.sql' 'SeedCanvasTemplates|canvas|agent/templates/compiler.json|compiler.json|compilation_template_group_id|c3aa748c8b2111f191f3047c16ec874f' . \
  | head -n 220

Repository: infiniflow/ragflow

Length of output: 29288


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
for f in [
    Path("api/db/services/compilation_template_group_service.py"),
    Path("api/db/services/compilation_template_service.py"),
    Path("api/db/init_data.py"),
]:
    print(f"===== {f} =====")
    for i, line in enumerate(f.read_text(errors="ignore").splitlines(), 1):
        if not (f"CompilationTemplateGroupService.resolve_template_ids" in line or
                "status == StatusEnum.VALID.value" in line or
                "select(CompilationTemplate.id)" in line or
                "def resolve_template_ids_from_groups" in line or
                "def resolve_template_ids" in line or
                "def seed" in (line.lower().strip() and line.split("#", 1)[0].lower()) or
                "canvas_template" in line or
                "agent/templates/compiler.json" in line or
                "compilation_template_group_id" in line or
                "c3aa748c8b2111f191f3047c16ec874f" in line):
            continue
        print(f"{i}: {line}")
PY

python3 - <<'PY'
from pathlib import Path
id_ = "c3aa748c8b2111f191f3047c16ec874f"
for p in Path(".").rglob("*"):
    if p.is_file() and p.name not in {".DS_Store"} and p.exists():
        s = p.read_bytes(errors="ignore")
        if id_.encode() in s:
            line = s.count(b"\n", 0, s.index(id_.encode())) + 1
            print(f"ref:{line}: {p}")
PY

Repository: infiniflow/ragflow

Length of output: 2505


Seed this fixed compilation template group for every tenant.

compilation_template_group_id: "c3aa748c8b2111f191f3047c16ec874f" always resolves through CompilationTemplateGroupService.resolve_template_ids(), which only returns IDs when a valid group exists for that tenant_id. This template does not provision or fallback to a built-in group, so tenants without this group will run the Compiler with no active templates.

🤖 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 `@agent/templates/compiler.json` at line 8, Update the compilation template
setup associated with compilation_template_group_id so the fixed group
c3aa748c8b2111f191f3047c16ec874f is provisioned for every tenant before
CompilationTemplateGroupService.resolve_template_ids() runs. Ensure each tenant
has a valid group for that ID, rather than relying on a missing-group fallback,
so the Compiler receives active template IDs.

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

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 3

🧹 Nitpick comments (4)
web/src/pages/agent/canvas/node/compilation-node.tsx (1)

13-13: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Converge the agent form type to string.

CompilationForm saves compilation_template_group_id via useWatchFormChange as a single ID, and CompilationNode reads the same form.compilation_template_group_id for label lookup. The stale string[] type in the document request/database interfaces can keep old saved nodes compatible, but align the agent form contract to string to avoid false array/null failures.

🤖 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 `@web/src/pages/agent/canvas/node/compilation-node.tsx` at line 13, Update the
agent form contract for compilation_template_group_id from string[] to string,
including the CompilationForm/useWatchFormChange types and related
CompilationNode form typing. Keep document request and database interfaces that
intentionally support legacy string[] values unchanged, while preserving the
existing label lookup in CompilationNode.
tasks/knowledge_compile_tree_raptor_plan.md (1)

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

Remove this completed execution log.

This file records completed phases, prior review findings, and historical decisions. It creates a second source of truth that will drift from the code and tests. Keep current behavior in code, tests, and PR discussion, then delete this file.

As per coding guidelines, “Remove dead tests, commented-out code, stale documentation, and 'move later' notes instead of preserving them.”

🤖 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 `@tasks/knowledge_compile_tree_raptor_plan.md` around lines 1 - 286, Delete
this completed implementation-plan document entirely. The current behavior and
decisions are already represented by the knowledge compiler code, tests, and PR
discussion, so do not preserve or relocate the historical execution log.

Source: Coding guidelines

rag/flow/compiler/compiler.py (1)

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

Avoid compatibility wording and add logging for the fallback path.

The docstring states the plural key compilation_template_group_ids "is still accepted as a fallback so existing pipelines keep working." Coding guidelines direct removal of compatibility wording from comments and documentation. Rephrase the docstring to describe the accepted inputs without wording of that kind.

check() also introduces a new normalization flow with no logging. Add a log statement when the legacy plural key is used, so operators can track remaining reliance on it.

♻️ Proposed fix
     def check(self):
         # Prefer the singular group id emitted by the frontend; fall back to the
-        # legacy plural key for backward compatibility. check() normalises the
+        # legacy plural key when the singular key is absent. check() normalises the
         # chosen value into self.compilation_template_group_ids (a list) so the
         # rest of the Compiler only ever reads that.
         group = self.compilation_template_group_id or self.compilation_template_group_ids
+        if not self.compilation_template_group_id and self.compilation_template_group_ids:
+            logging.warning("Compiler: using legacy compilation_template_group_ids field")
         self.check_empty(group, "Compilation Template Group")

Based on learnings, this comment applies the coding guidelines **/*: Do not add compatibility wording in comments or documentation and **/*.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/flow/compiler/compiler.py` around lines 46 - 68, Update the class
docstring to describe the singular and plural configuration inputs without
compatibility or legacy-pipeline wording. In the configuration normalization
logic of __init__/check, log when compilation_template_group_id is absent and
the plural compilation_template_group_ids value is selected, while preserving
the existing normalization and validation behavior.

Source: Coding guidelines

internal/ingestion/component/knowledge_compiler/tree/raptor.go (1)

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

Rename the remaining "raptor"-branded identifiers to match the "tree" rename.

This file's package, package doc, log/error messages, and Variant values were renamed from raptor to tree, but defaultRaptorPrompt and resolveRaptorPrompt (and their call site, plus "raptor: summarization failed after %d attempts" at line 374) still carry the old name. This leaves the file half-migrated: the constant's own comment says it mirrors "the tree compilation template," while the identifier itself still says "Raptor."

♻️ Proposed rename
-const defaultRaptorPrompt = "..."
+const defaultTreePrompt = "..."
-func resolveRaptorPrompt(param common.Param) string {
+func resolveTreePrompt(param common.Param) string {
 	if raw, ok := param.Extra["prompt"]; ok {
 		if s, ok := raw.(string); ok && strings.TrimSpace(s) != "" {
 			return s
 		}
 	}
-	return defaultRaptorPrompt
+	return defaultTreePrompt
 }

Update the call site (taskPrompt := resolveRaptorPrompt(param)) and the "raptor: summarization failed after %d attempts" message at line 374 to match.

As per coding guidelines: "**/*.go: Remove commented-out Go code and keep package and doc comments aligned with the current runtime path rather than migration history." Based on learnings, "In actively refactored Go ingestion, parser, and DeepDOC code, collapse duplicate paths and do not preserve transitional wrappers or deprecated APIs."

🤖 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/component/knowledge_compiler/tree/raptor.go` around lines
543 - 571, Rename the remaining Raptor-branded symbols to tree equivalents:
update defaultRaptorPrompt and resolveRaptorPrompt, their call site, and the
summarization failure message to use “tree” consistently. Keep the existing
prompt behavior unchanged and remove migration-history wording or commented-out
Go code if present in the affected area.

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 `@agent/templates/compiler.json`:
- Line 8: Update the compilation template setup associated with
compilation_template_group_id so the fixed group
c3aa748c8b2111f191f3047c16ec874f is provisioned for every tenant before
CompilationTemplateGroupService.resolve_template_ids() runs. Ensure each tenant
has a valid group for that ID, rather than relying on a missing-group fallback,
so the Compiler receives active template IDs.

In `@internal/ingestion/component/knowledge_compiler/component.go`:
- Around line 218-240: The overlayTemplateConfig function currently overwrites
explicit per-call LLMID and EmbeddingModel values with template configuration.
Only apply cfg["llm_id"] and cfg["embedding_model"] when the corresponding param
fields are empty, preserving caller-provided overrides while retaining template
defaults.

In
`@internal/ingestion/component/knowledge_compiler/golden/fixtures/tree_baseline.json`:
- Line 8: Update
internal/ingestion/component/knowledge_compiler/golden/metrics.go at line 73 to
track source-to-leaf assignments and compute CoverageFraction from the number of
covered source chunks divided by nChunks, rather than structural properties. In
internal/ingestion/component/knowledge_compiler/golden/fixtures/tree_baseline.json
at line 8, retain leaf_coverage_min: 1.0 once the metric uses source-chunk
coverage.

---

Nitpick comments:
In `@internal/ingestion/component/knowledge_compiler/tree/raptor.go`:
- Around line 543-571: Rename the remaining Raptor-branded symbols to tree
equivalents: update defaultRaptorPrompt and resolveRaptorPrompt, their call
site, and the summarization failure message to use “tree” consistently. Keep the
existing prompt behavior unchanged and remove migration-history wording or
commented-out Go code if present in the affected area.

In `@rag/flow/compiler/compiler.py`:
- Around line 46-68: Update the class docstring to describe the singular and
plural configuration inputs without compatibility or legacy-pipeline wording. In
the configuration normalization logic of __init__/check, log when
compilation_template_group_id is absent and the plural
compilation_template_group_ids value is selected, while preserving the existing
normalization and validation behavior.

In `@tasks/knowledge_compile_tree_raptor_plan.md`:
- Around line 1-286: Delete this completed implementation-plan document
entirely. The current behavior and decisions are already represented by the
knowledge compiler code, tests, and PR discussion, so do not preserve or
relocate the historical execution log.

In `@web/src/pages/agent/canvas/node/compilation-node.tsx`:
- Line 13: Update the agent form contract for compilation_template_group_id from
string[] to string, including the CompilationForm/useWatchFormChange types and
related CompilationNode form typing. Keep document request and database
interfaces that intentionally support legacy string[] values unchanged, while
preserving the existing label lookup in CompilationNode.
🪄 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: 9058263e-1e15-4afb-9ba0-a0fcb61aa4e4

📥 Commits

Reviewing files that changed from the base of the PR and between 4f05866 and 768d784.

📒 Files selected for processing (26)
  • agent/templates/compiler.json
  • internal/dao/compilation_template.go
  • internal/dao/database.go
  • internal/ingestion/component/knowledge_compiler/common/deps.go
  • internal/ingestion/component/knowledge_compiler/common/types.go
  • internal/ingestion/component/knowledge_compiler/component.go
  • internal/ingestion/component/knowledge_compiler/component_test.go
  • internal/ingestion/component/knowledge_compiler/golden/corpus.go
  • internal/ingestion/component/knowledge_compiler/golden/fixtures/tree_baseline.json
  • internal/ingestion/component/knowledge_compiler/golden/golden_test.go
  • internal/ingestion/component/knowledge_compiler/golden/metrics.go
  • internal/ingestion/component/knowledge_compiler/golden_test.go
  • internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go
  • internal/ingestion/component/knowledge_compiler/mindmap/mindmap_test.go
  • internal/ingestion/component/knowledge_compiler/structure/structure.go
  • internal/ingestion/component/knowledge_compiler/tree/raptor.go
  • internal/ingestion/component/knowledge_compiler/tree/raptor_test.go
  • internal/ingestion/component/knowledge_compiler/tree/watershed.go
  • internal/ingestion/component/knowledge_compiler/tree/watershed_test.go
  • internal/ingestion/pipeline/pipeline_knowledge_compiler_dsl_test.go
  • internal/ingestion/task/knowledge_compiler_wiring.go
  • rag/flow/compiler/compiler.py
  • tasks/knowledge_compile_tree_raptor_plan.md
  • web/src/pages/agent/canvas/node/compilation-node.tsx
  • web/src/pages/agent/constant/pipeline.tsx
  • web/src/pages/agent/form/compilation-form/index.tsx
🛑 Comments failed to post (1)
internal/ingestion/component/knowledge_compiler/golden/fixtures/tree_baseline.json (1)

8-8: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Make the golden coverage gate measure source-chunk coverage.

CoverageFraction returns 1.0 from structural properties and does not compare covered source chunks with nChunks. The current gate cannot detect dropped source chunks.

  • internal/ingestion/component/knowledge_compiler/golden/fixtures/tree_baseline.json#L8-L8: retain leaf_coverage_min: 1.0 only after the metric measures source-to-leaf assignments.
  • internal/ingestion/component/knowledge_compiler/golden/metrics.go#L73-L73: track source-to-leaf assignments and calculate coverage from the covered source-chunk count and nChunks.
📍 Affects 2 files
  • internal/ingestion/component/knowledge_compiler/golden/fixtures/tree_baseline.json#L8-L8 (this comment)
  • internal/ingestion/component/knowledge_compiler/golden/metrics.go#L73-L73
🤖 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/component/knowledge_compiler/golden/fixtures/tree_baseline.json`
at line 8, Update
internal/ingestion/component/knowledge_compiler/golden/metrics.go at line 73 to
track source-to-leaf assignments and compute CoverageFraction from the number of
covered source chunks divided by nChunks, rather than structural properties. In
internal/ingestion/component/knowledge_compiler/golden/fixtures/tree_baseline.json
at line 8, retain leaf_coverage_min: 1.0 once the metric uses source-chunk
coverage.

…ation_template_id

All direct-construction cases now use the synthetic id "tpl-<variant>"
resolved via installVariantTemplateResolver, selecting the variant through
the production id -> kind -> variant path. Intentional exceptions kept:
UnknownVariant ("nope") and Alias_Mindmap ("mind_map") test resolver behavior.
- overlayTemplateConfig: per-call llm_id / embedding_model overrides now win
  over the template config; the config only fills them in when the caller left
  them empty (previously the template config silently overwrote caller values).
- golden CoverageFraction: measure real source-chunk coverage from
  source_chunk_ids of level-0 leaf clusters (covered / nChunks) instead of
  returning 1.0 purely from structural well-formedness, so the gate can detect
  dropped source chunks. Added CoveredSources to TreeMetrics and updated the
  coverage unit tests.

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

🤖 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/component/knowledge_compiler/golden/metrics.go`:
- Around line 52-63: Update AnalyzeTreeProducts and its callers to receive the
source chunk IDs produced during tree compilation, and filter values from
GetExtraStringSlice("source_chunk_ids") against that input set before updating
m.covered or CoveredSources. Preserve CoverageFraction’s bounded coverage
behavior, and add a golden-case test replacing one valid source ID with an
unknown ID to verify it is excluded.
🪄 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: 55183305-5762-4e73-a13c-a6aacca0743e

📥 Commits

Reviewing files that changed from the base of the PR and between 41e6d9c and 2bb51e9.

📒 Files selected for processing (3)
  • internal/ingestion/component/knowledge_compiler/component.go
  • internal/ingestion/component/knowledge_compiler/golden/golden_test.go
  • internal/ingestion/component/knowledge_compiler/golden/metrics.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/ingestion/component/knowledge_compiler/component.go

@codecov

codecov Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (93513eb) to head (4a0b48a).
⚠️ Report is 11 commits behind head on main.

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

…and clamp coverage

- Seed built-in compilation template group (c3aa748c...) globally at startup
  and per tenant via SeedBuiltinCompilationTemplates/ForTenant; treat the
  builtin group id as tenant-agnostic in ResolveGroupTemplateIDs.
- golden: AnalyzeTreeProducts now accepts validSourceIDs and only counts
  known source chunk ids; CoverageFraction is clamped to <= 1.0.

Co-Authored-By: Chengyu Zhang <[email protected]>

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

Caution

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

⚠️ Outside diff range comments (1)
internal/dao/compilation_template.go (1)

112-125: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Load built-in templates through the tenant-agnostic path.

GetTemplate uses tenant_id = ?, so it cannot match built-in rows where tenant_id is NULL. Built-in templates are only reachable via compilation_template_group_id; resolving compilation_template_id directly for a built-in template fails. Either make this direct lookup tenant-agnostic for built-in IDs or disallow direct built-in ID usage.

🤖 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/dao/compilation_template.go` around lines 112 - 125, Update
CompilationTemplateDAO.GetTemplate to resolve built-in templates identified
through compilation_template_group_id without requiring tenant_id, while
retaining tenant-scoped filtering for tenant-owned templates. Ensure direct
compilation_template_id resolution succeeds for valid built-in rows with NULL
tenant_id, or explicitly reject such IDs before the tenant-scoped query.
🤖 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.

Outside diff comments:
In `@internal/dao/compilation_template.go`:
- Around line 112-125: Update CompilationTemplateDAO.GetTemplate to resolve
built-in templates identified through compilation_template_group_id without
requiring tenant_id, while retaining tenant-scoped filtering for tenant-owned
templates. Ensure direct compilation_template_id resolution succeeds for valid
built-in rows with NULL tenant_id, or explicitly reject such IDs before the
tenant-scoped query.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f06d32ef-2402-4707-83bc-f4115e683fbf

📥 Commits

Reviewing files that changed from the base of the PR and between 2bb51e9 and 4a0b48a.

📒 Files selected for processing (9)
  • .gitignore
  • internal/dao/compilation_template.go
  • internal/dao/compilation_template_seed.go
  • internal/dao/compilation_template_seed_test.go
  • internal/dao/database.go
  • internal/dao/tenant.go
  • internal/ingestion/component/knowledge_compiler/golden/golden_test.go
  • internal/ingestion/component/knowledge_compiler/golden/metrics.go
  • internal/ingestion/component/knowledge_compiler/golden_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/dao/database.go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant