Repository navigation
refactor(knowledge_compiler): derive variant from template kind via single template id - #17630
Conversation
… 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.
📝 WalkthroughWalkthroughThe 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. ChangesKnowledge compilation template integration
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
Possibly related PRs
Suggested labels: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
Keep the file locally; it is a working note, not part of the PR.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (4)
web/src/pages/agent/canvas/node/compilation-node.tsx (1)
13-13: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winConverge the agent form type to
string.
CompilationFormsavescompilation_template_group_idviauseWatchFormChangeas a single ID, andCompilationNodereads the sameform.compilation_template_group_idfor label lookup. The stalestring[]type in the document request/database interfaces can keep old saved nodes compatible, but align the agent form contract tostringto 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 winRemove 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 winAvoid 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 documentationand**/*.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 winRename the remaining "raptor"-branded identifiers to match the "tree" rename.
This file's package, package doc, log/error messages, and
Variantvalues were renamed fromraptortotree, butdefaultRaptorPromptandresolveRaptorPrompt(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
📒 Files selected for processing (26)
agent/templates/compiler.jsoninternal/dao/compilation_template.gointernal/dao/database.gointernal/ingestion/component/knowledge_compiler/common/deps.gointernal/ingestion/component/knowledge_compiler/common/types.gointernal/ingestion/component/knowledge_compiler/component.gointernal/ingestion/component/knowledge_compiler/component_test.gointernal/ingestion/component/knowledge_compiler/golden/corpus.gointernal/ingestion/component/knowledge_compiler/golden/fixtures/tree_baseline.jsoninternal/ingestion/component/knowledge_compiler/golden/golden_test.gointernal/ingestion/component/knowledge_compiler/golden/metrics.gointernal/ingestion/component/knowledge_compiler/golden_test.gointernal/ingestion/component/knowledge_compiler/mindmap/mindmap.gointernal/ingestion/component/knowledge_compiler/mindmap/mindmap_test.gointernal/ingestion/component/knowledge_compiler/structure/structure.gointernal/ingestion/component/knowledge_compiler/tree/raptor.gointernal/ingestion/component/knowledge_compiler/tree/raptor_test.gointernal/ingestion/component/knowledge_compiler/tree/watershed.gointernal/ingestion/component/knowledge_compiler/tree/watershed_test.gointernal/ingestion/pipeline/pipeline_knowledge_compiler_dsl_test.gointernal/ingestion/task/knowledge_compiler_wiring.gorag/flow/compiler/compiler.pytasks/knowledge_compile_tree_raptor_plan.mdweb/src/pages/agent/canvas/node/compilation-node.tsxweb/src/pages/agent/constant/pipeline.tsxweb/src/pages/agent/form/compilation-form/index.tsx
| "obj": { | ||
| "component_name": "Compiler", | ||
| "params": { | ||
| "compilation_template_group_id": "c3aa748c8b2111f191f3047c16ec874f", |
There was a problem hiding this comment.
🗄️ 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 220Repository: 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 220Repository: 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 220Repository: 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}")
PYRepository: 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.
There was a problem hiding this comment.
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 winConverge the agent form type to
string.
CompilationFormsavescompilation_template_group_idviauseWatchFormChangeas a single ID, andCompilationNodereads the sameform.compilation_template_group_idfor label lookup. The stalestring[]type in the document request/database interfaces can keep old saved nodes compatible, but align the agent form contract tostringto 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 winRemove 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 winAvoid 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 documentationand**/*.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 winRename the remaining "raptor"-branded identifiers to match the "tree" rename.
This file's package, package doc, log/error messages, and
Variantvalues were renamed fromraptortotree, butdefaultRaptorPromptandresolveRaptorPrompt(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
📒 Files selected for processing (26)
agent/templates/compiler.jsoninternal/dao/compilation_template.gointernal/dao/database.gointernal/ingestion/component/knowledge_compiler/common/deps.gointernal/ingestion/component/knowledge_compiler/common/types.gointernal/ingestion/component/knowledge_compiler/component.gointernal/ingestion/component/knowledge_compiler/component_test.gointernal/ingestion/component/knowledge_compiler/golden/corpus.gointernal/ingestion/component/knowledge_compiler/golden/fixtures/tree_baseline.jsoninternal/ingestion/component/knowledge_compiler/golden/golden_test.gointernal/ingestion/component/knowledge_compiler/golden/metrics.gointernal/ingestion/component/knowledge_compiler/golden_test.gointernal/ingestion/component/knowledge_compiler/mindmap/mindmap.gointernal/ingestion/component/knowledge_compiler/mindmap/mindmap_test.gointernal/ingestion/component/knowledge_compiler/structure/structure.gointernal/ingestion/component/knowledge_compiler/tree/raptor.gointernal/ingestion/component/knowledge_compiler/tree/raptor_test.gointernal/ingestion/component/knowledge_compiler/tree/watershed.gointernal/ingestion/component/knowledge_compiler/tree/watershed_test.gointernal/ingestion/pipeline/pipeline_knowledge_compiler_dsl_test.gointernal/ingestion/task/knowledge_compiler_wiring.gorag/flow/compiler/compiler.pytasks/knowledge_compile_tree_raptor_plan.mdweb/src/pages/agent/canvas/node/compilation-node.tsxweb/src/pages/agent/constant/pipeline.tsxweb/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.
CoverageFractionreturns1.0from structural properties and does not compare covered source chunks withnChunks. The current gate cannot detect dropped source chunks.
internal/ingestion/component/knowledge_compiler/golden/fixtures/tree_baseline.json#L8-L8: retainleaf_coverage_min: 1.0only 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 andnChunks.📍 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.
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
internal/ingestion/component/knowledge_compiler/component.gointernal/ingestion/component/knowledge_compiler/golden/golden_test.gointernal/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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
…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]>
There was a problem hiding this comment.
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 winLoad built-in templates through the tenant-agnostic path.
GetTemplateusestenant_id = ?, so it cannot match built-in rows wheretenant_idisNULL. Built-in templates are only reachable viacompilation_template_group_id; resolvingcompilation_template_iddirectly 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
📒 Files selected for processing (9)
.gitignoreinternal/dao/compilation_template.gointernal/dao/compilation_template_seed.gointernal/dao/compilation_template_seed_test.gointernal/dao/database.gointernal/dao/tenant.gointernal/ingestion/component/knowledge_compiler/golden/golden_test.gointernal/ingestion/component/knowledge_compiler/golden/metrics.gointernal/ingestion/component/knowledge_compiler/golden_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/dao/database.go
Summary
Refactor the Go
KnowledgeCompilerComponentso its parameter is a single string template id instead of a DSL-levelvariant(or plural group id list). Thevariantis no longer in the DSL — it is now derived at runtime from the resolved compilation template'skindfield.This aligns the Go ingestion port with the frontend Compiler operator, which emits a singular
compilation_template_group_idand does not writevariantinto the generatedcompiler.json.Changes
Go (
internal/ingestion/component/knowledge_compiler)Paramnow carriesCompilationTemplateID/CompilationTemplateGroupID(both strings).ParseParamreadscompilation_template_id/compilation_template_group_id, requires at least one, and no longer parsesvariant. Selection priority:compilation_template_id>compilation_template_group_id.KindToVariantreplacesnormalizeVariant: maps templatekindto a compiler variant:tree→ treemind_map/mindmap→ mindmapwiki→ wikidatasetnav/dataset_nav→ datasetnavpage_index/session_essence/session_graph/timeline/knowledge_graph/structure/knowledgegraph/graph→ structureErrUnknownVariantTemplateResolver+SetTemplateResolver/ResolveTemplatein the dependency-lightcommonpackage, returningTemplateInfo{ID, Kind, Config}.knowledge_compiler_wiring.goinstalls the DB-backedSetTemplateResolver; newdao.GetTemplateperforms a valid + tenant-scoped lookup.compilation_template/compilation_template_groupadded to the GORM migration list ininternal/dao/database.go, ensuring the tables exist on the Go side.Invoke: resolves template specs (id > group), derives the variant per spec viaKindToVariant, and stamps each product withcompilation_template_ids,Kind,TemplateID, andVariant.Python (
rag/flow/compiler/compiler.py)compilation_template_group_id(singular) with a fallback to the legacy pluralcompilation_template_group_ids, normalizing to the internal list for backward compatibility.Frontend
compilation_template_group_id(replacingcompilation_template_group_ids) incompilation-node.tsx,compilation-form/index.tsx,constant/pipeline.tsx, and theagent/templates/compiler.jsonfixture.Tests
pipeline_knowledge_compiler_dsl_test.gorewritten: singular group id fixture, id>group priority,KindToVariantcases, and resolver-seam coverage via stubbed resolvers.bash build.sh --test ./internal/ingestion/...compiles and all component/pipeline/task/dao test packages pass.Notes
resolve_template_ids_from_groups.compilation_template_group_idsplural key is still accepted by Python for backward compatibility.