Repository navigation
Align Go knowledge compiler RAPTOR with Python and drop guardrails - #17573
Conversation
📝 WalkthroughWalkthroughThe knowledge compiler replaces RAPTOR’s prior clustering flow with watershed clustering, reuses precomputed embeddings, adds token-aware summarization, removes sink-based guardrails, buffers outputs, and updates integration and golden tests for tree-order behavior. ChangesKnowledge compiler pipeline
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Compiler
participant RAPTOR
participant LLM
participant EmbeddingModel
Compiler->>RAPTOR: invoke with chunks and tree_order
RAPTOR->>EmbeddingModel: reuse or compute embeddings
RAPTOR->>RAPTOR: watershed cluster and recursively build tree
RAPTOR->>LLM: summarize token-bounded cluster content
LLM-->>RAPTOR: return summary or retryable error
RAPTOR->>EmbeddingModel: embed generated summaries
RAPTOR-->>Compiler: return buffered products
Possibly related PRs
Suggested labels: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 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 |
left a comment
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/ingestion/component/knowledge_compiler/raptor/raptor.go (1)
167-188: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winSort cluster indices before building the Raptor processing queue.
groupsandsubGroupsare maps, so the order keys are ranged over is not stable in Go. Those orders determinequeueorder,topLevelTextsaccumulation order, and the input order forbuildClusterContent, making the root synthesis content non-reproducible even with identical inputs. Use sorted keys before buildingqueuein both the top-level and sub-cluster processing paths.🤖 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/raptor/raptor.go` around lines 167 - 188, Sort the cluster-label keys before constructing the Raptor processing queue from groups, and apply the same deterministic ordering to subGroups in the sub-cluster processing path. Update the relevant queue-building logic in the Raptor compilation function while preserving each group’s existing point indices and processing behavior, so queue order, topLevelTexts accumulation, and buildClusterContent inputs are reproducible.
🧹 Nitpick comments (1)
internal/ingestion/component/knowledge_compiler/raptor/watershed.go (1)
1-9: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPackage docs reference migration history/plan instead of only describing current behavior. Both
watershed.goandraptor.gopackage comments tie their explanation to the Python→Go port (AHC naming history, PORT_PLAN.md pointer) rather than describing only the current runtime path, per the repo's**/*.godoc-comment guideline.
internal/ingestion/component/knowledge_compiler/raptor/watershed.go#L1-L9: drop the "historically named AHC"/PORT_PLAN narrative; keep only a description of what the watershed algorithm does today.internal/ingestion/component/knowledge_compiler/raptor/raptor.go#L4-L14: drop the trailing "See PORT_PLAN.md §3.3." line; the preceding lines already describe current behavior sufficiently.🤖 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/raptor/watershed.go` around lines 1 - 9, Update the package comments in internal/ingestion/component/knowledge_compiler/raptor/watershed.go lines 1-9 and internal/ingestion/component/knowledge_compiler/raptor/raptor.go lines 4-14 to describe only current runtime behavior: remove the historical AHC/Python migration and PORT_PLAN references from watershed.go, and remove the trailing PORT_PLAN.md reference from raptor.go while preserving the existing behavior descriptions.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 `@internal/ingestion/component/knowledge_compiler/common/types.go`:
- Around line 236-250: Update VectorFromChunkMap to accept the current embedding
dimension when available and only inspect the corresponding q_<dim>_vec key.
When no dimension is supplied, collect all matching q_*_vec fields and return an
error if more than one exists instead of selecting nondeterministically;
preserve conversion through toFloat32Slice for the single valid match and
no-embedding behavior.
In `@internal/ingestion/component/knowledge_compiler/raptor/raptor.go`:
- Around line 283-297: The root synthesis path must handle the case where all
deepest-level summaries fail and topLevelTexts is empty. Before calling
allIndices and buildClusterContent in the root-building flow, return the partial
tree without creating a root when len(topLevelTexts) is zero; also guard
buildClusterContent against an empty idxs slice before dividing by its length.
- Around line 100-104: Update raptorTruncationMarkerRE to escape the trailing
question mark in the English truncation marker, ensuring the full literal
“continue?” notice is matched and removed while preserving the existing Chinese
pattern.
In `@internal/ingestion/task/knowledge_compiler_wiring.go`:
- Around line 74-90: Bound the ResolveModelConfig lookup in DepsResolver’s
ResolveDeps flow by creating a short-lived context with a finite timeout and
passing it to svc.ResolveModelConfig instead of context.Background(). Ensure the
context is canceled after the lookup, while preserving the existing default
llmMax fallback when resolution times out or returns an error.
---
Outside diff comments:
In `@internal/ingestion/component/knowledge_compiler/raptor/raptor.go`:
- Around line 167-188: Sort the cluster-label keys before constructing the
Raptor processing queue from groups, and apply the same deterministic ordering
to subGroups in the sub-cluster processing path. Update the relevant
queue-building logic in the Raptor compilation function while preserving each
group’s existing point indices and processing behavior, so queue order,
topLevelTexts accumulation, and buildClusterContent inputs are reproducible.
---
Nitpick comments:
In `@internal/ingestion/component/knowledge_compiler/raptor/watershed.go`:
- Around line 1-9: Update the package comments in
internal/ingestion/component/knowledge_compiler/raptor/watershed.go lines 1-9
and internal/ingestion/component/knowledge_compiler/raptor/raptor.go lines 4-14
to describe only current runtime behavior: remove the historical AHC/Python
migration and PORT_PLAN references from watershed.go, and remove the trailing
PORT_PLAN.md reference from raptor.go while preserving the existing behavior
descriptions.
🪄 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: 96bb3906-8fcf-443f-8b76-0bcf32993e16
📒 Files selected for processing (20)
internal/ingestion/component/knowledge_compiler/common/common_test.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/datasetnav/datasetnav.gointernal/ingestion/component/knowledge_compiler/golden/fixtures/raptor_baseline.jsoninternal/ingestion/component/knowledge_compiler/golden_test.gointernal/ingestion/component/knowledge_compiler/mindmap/mindmap.gointernal/ingestion/component/knowledge_compiler/raptor/clustering.gointernal/ingestion/component/knowledge_compiler/raptor/clustering_test.gointernal/ingestion/component/knowledge_compiler/raptor/psi.gointernal/ingestion/component/knowledge_compiler/raptor/raptor.gointernal/ingestion/component/knowledge_compiler/raptor/raptor_test.gointernal/ingestion/component/knowledge_compiler/raptor/watershed.gointernal/ingestion/component/knowledge_compiler/raptor/watershed_test.gointernal/ingestion/component/knowledge_compiler/structure/structure.gointernal/ingestion/component/knowledge_compiler/wiki/wiki.gointernal/ingestion/knowledge_compile/reader.gointernal/ingestion/task/knowledge_compiler_wiring.go
💤 Files with no reviewable changes (4)
- internal/ingestion/component/knowledge_compiler/raptor/clustering_test.go
- internal/ingestion/component/knowledge_compiler/raptor/psi.go
- internal/ingestion/component/knowledge_compiler/raptor/clustering.go
- internal/ingestion/component/knowledge_compiler/common/common_test.go
| // raptorTruncationMarkerRE strips model truncation notices that some LLMs emit | ||
| // when a response is cut short. Mirrors Python _summarize_texts (raptor.py:405). | ||
| var raptorTruncationMarkerRE = regexp.MustCompile( | ||
| strings.Repeat("\u00b7", 6) + "\n由于长度的原因,回答被截断了,要继续吗?|For the content length reason, it stopped, continue?", | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
Go regexp: does an unescaped ? at the end of a pattern quantify the preceding character instead of matching a literal question mark?
💡 Result:
In Go's regular expression syntax (which follows RE2), an unescaped ? is a metacharacter used as a repetition operator to signify that the preceding character or group should be matched zero or one times [1][2]. If you place an unescaped ? at the end of a pattern without a preceding character or group to quantify, the regular expression will be considered invalid. The Go regexp package will return an error (typically regexp: error parsing regexp: missing argument to repetition operator: ?) when attempting to compile such a pattern, because the ? requires a preceding expression to act upon [3][2]. It does not function as a literal match for a question mark in that position. To match a literal question mark, you must escape it using a backslash (\?) or include it within a character class (e.g., [?]) [4][2]. Alternatively, if you want to treat a string containing punctuation as literal text, you can use the regexp.QuoteMeta function, which automatically escapes all regular expression metacharacters [3].
Citations:
- 1: https://pkg.go.dev/regexp/syntax
- 2: https://golang.google.cn/pkg/regexp/syntax/
- 3: https://pkg.go.dev/regexp
- 4: https://go.dev/src/regexp/syntax/doc.go
Escape the English truncation-marker question mark.
In Go RE2 regex, an unescaped e? matches e with zero length, leaving real ...continue? notices in the summary with the trailing ? still present. Escape it so the marker matches the literal English notice.
🐛 Proposed fix
var raptorTruncationMarkerRE = regexp.MustCompile(
- strings.Repeat("\u00b7", 6) + "\n由于长度的原因,回答被裁断了,要继续吗?|For the content length reason, it stopped, continue?",
+ strings.Repeat("\u00b7", 6) + `\n由于长度的原因,回答被截断了,要继续吗?|For the content length reason, it stopped, continue\?`,
)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // raptorTruncationMarkerRE strips model truncation notices that some LLMs emit | |
| // when a response is cut short. Mirrors Python _summarize_texts (raptor.py:405). | |
| var raptorTruncationMarkerRE = regexp.MustCompile( | |
| strings.Repeat("\u00b7", 6) + "\n由于长度的原因,回答被截断了,要继续吗?|For the content length reason, it stopped, continue?", | |
| ) | |
| // raptorTruncationMarkerRE strips model truncation notices that some LLMs emit | |
| // when a response is cut short. Mirrors Python _summarize_texts (raptor.py:405). | |
| var raptorTruncationMarkerRE = regexp.MustCompile( | |
| strings.Repeat("\u00b7", 6) + `\n由于长度的原因,回答被截断了,要继续吗?|For the content length reason, it stopped, continue\?`, | |
| ) |
🤖 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/raptor/raptor.go` around
lines 100 - 104, Update raptorTruncationMarkerRE to escape the trailing question
mark in the English truncation marker, ensuring the full literal “continue?”
notice is matched and removed while preserving the existing Chinese pattern.
65c723d to
4a9d7ff
Compare
left a comment
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/ingestion/component/knowledge_compiler/raptor/raptor.go (1)
234-281: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winRoot synthesis silently drops content from branches that terminate before the global deepest level.
topLevelTextsis fed by comparingtask.levelagainst a single, globally-trackedmaxLevel, resetting the slice every time a strictly deeper level is reached. With the new watershed-based per-branch recursion, different branches can terminate (stop splitting) at different depths — a branch stops as soon as its re-cluster collapses tolen(subGroups) <= 1. Concretely: if branch A's recursion ends at level 2 while branch B continues to level 3+, once BFS processing reaches level 3,maxLeveladvances past 2 and clearstopLevelTexts, discarding branch A's level-2 summary from the root synthesis entirely — even though the surrounding comment states the root should be built from "the leaves of the upper tree." The dropped node is still emitted as a regular product (so the tree stays well-formed and passes the golden structural checks), but its content never reaches the root summary, degrading root completeness for any document whose clusters don't all bottom out at the same depth.🐛 Proposed fix: track true leaves instead of a global deepest level
- // Track the deepest-level summaries for the root synthesis: only those - // are fed to the root, so the root summarises the top of the tree - // rather than re-summarising every leaf. - if task.level > maxLevel { - maxLevel = task.level - topLevelTexts = topLevelTexts[:0] - } - if task.level == maxLevel { - topLevelTexts = append(topLevelTexts, summary) - } - // Recurse: re-cluster this cluster's points and enqueue sub-clusters ... subEmb := make([][]float64, 0, len(task.pointIdxs)) for _, pi := range task.pointIdxs { subEmb = append(subEmb, embeddings[pi]) } subLabels, err := watershed(subEmb, treeOrder) if err != nil { return err } subGroups := map[int][]int{} for i, li := range subLabels { subGroups[li] = append(subGroups[li], task.pointIdxs[i]) } + hasChildren := false if len(subGroups) > 1 { for _, idxs := range subGroups { if len(idxs) <= 1 { continue } queue = append(queue, nodeTask{pointIdxs: idxs, parentID: nodeID, level: task.level + 1}) + hasChildren = true } } + // A node with no enqueued children is a true leaf of the upper tree + // and feeds the root synthesis, regardless of the depth it stopped at. + if !hasChildren { + topLevelTexts = append(topLevelTexts, summary) + }(remove the now-unused
maxLevelvariable declared earlier in the function)🤖 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/raptor/raptor.go` around lines 234 - 281, Replace the global-depth tracking around topLevelTexts with true-leaf tracking: append a node’s summary when its sub-clustering produces len(subGroups) <= 1, while retaining summaries for branches that split through their queued descendants. Remove the maxLevel variable and its level comparisons/reset logic, ensuring every branch-terminating summary is included in root synthesis.
♻️ Duplicate comments (2)
internal/ingestion/component/knowledge_compiler/raptor/raptor.go (2)
283-297: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winRoot synthesis still divides by zero when every deepest-level summary fails.
If every deepest-level cluster's summarization fails while
errorCountstays undermaxErrors,topLevelTextsstays empty.buildClusterContent(line 389) then computesper := (llmMaxLength - maxToken) / len(idxs)withlen(idxs) == 0, panicking the whole ingestion call. This was flagged on a prior commit and the guard was not added.🛡️ Proposed fix
+ if len(topLevelTexts) == 0 { + log.Printf("raptor: no top-level summaries produced, skipping root node") + return nil + } rootContent := buildClusterContent(topLevelTexts, allIndices(len(topLevelTexts)), deps.LLMMaxLength, maxToken)A defensive guard in
buildClusterContentitself would also help any other zero-length caller:func buildClusterContent(texts []string, idxs []int, llmMaxLength, maxToken int) string { + if len(idxs) == 0 { + return "" + } if llmMaxLength <= 0 {🤖 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/raptor/raptor.go` around lines 283 - 297, Guard the root synthesis path before calling buildClusterContent: when topLevelTexts is empty after deepest-level failures, skip root creation and return the remaining tree without invoking summarization. Also add a defensive zero-length check in buildClusterContent so it returns safely before dividing by len(idxs) when no indices are provided.
100-104: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winTruncation-marker regex still leaves the trailing
?unescaped.
continue?at the end of the pattern makes RE2 treat?as "zero or one of the precedinge", not a literal question mark. Genuine"...continue?"truncation notices will still have their trailing?left in the summary afterReplaceAllString. This is the same defect raised on a prior commit; the fix was not applied.🐛 Proposed fix
var raptorTruncationMarkerRE = regexp.MustCompile( - strings.Repeat("\u00b7", 6) + "\n由于长度的原因,回答被截断了,要继续吗?|For the content length reason, it stopped, continue?", + strings.Repeat("\u00b7", 6) + `\n由于长度的原因,回答被截断了,要继续吗?|For the content length reason, it stopped, continue\?`, )
raptor_test.go'sTestSummarizeTextsStripsTruncationMarkeronly covers the Chinese half of the alternation, so a test asserting the English marker (including the trailing?) is fully stripped would catch this.🤖 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/raptor/raptor.go` around lines 100 - 104, Escape the trailing question mark in raptorTruncationMarkerRE so the English truncation marker matches the literal “continue?” text and is fully removed. Extend TestSummarizeTextsStripsTruncationMarker with an English-marker case covering the trailing question mark.
🧹 Nitpick comments (2)
internal/ingestion/component/knowledge_compiler/raptor/raptor.go (1)
550-559: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winCustom
extra["prompt"]override isn't validated for the{cluster_content}placeholder.If a caller supplies
extra["prompt"]without{cluster_content},strings.Replace(taskPrompt, "{cluster_content}", content, 1)at the call sites (line 199, 290) is a no-op — the LLM receives a prompt with none of the actual cluster text, silently producing a useless summary for every node.🛡️ Proposed fix
func resolveRaptorPrompt(param common.Param) string { if raw, ok := param.Extra["prompt"]; ok { - if s, ok := raw.(string); ok && strings.TrimSpace(s) != "" { + if s, ok := raw.(string); ok && strings.TrimSpace(s) != "" && strings.Contains(s, "{cluster_content}") { return s } } return defaultRaptorPrompt }🤖 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/raptor/raptor.go` around lines 550 - 559, The resolveRaptorPrompt function must validate custom extra["prompt"] values before returning them. Only accept a non-empty string containing the {cluster_content} placeholder; otherwise return defaultRaptorPrompt, preserving the existing fallback behavior.internal/ingestion/component/knowledge_compiler/raptor/watershed.go (1)
1-9: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDoc comment narrates migration history instead of current behavior.
The package comment justifies the name via the algorithm's prior Python name ("historically named 'AHC'"), which is migration narrative rather than a description of what the code does today.
As per coding guidelines,
**/*.gofiles should "keep package and doc comments aligned with the current runtime path rather than migration history."✏️ Suggested trim
-// watershed is the sole clustering method used by the RAPTOR tree. -// -// It is the algorithm historically named "AHC" in the Python raptor -// implementation (raptor.py::_get_clusters_ahc, logged as "RAPTOR seq-clus"); -// the name "watershed" reflects what the code actually does, which is not -// agglomerative hierarchical clustering. -// -// See PORT_PLAN.md §3.3 and the M6 validation gate (缺口 C). +// watershed is the sole clustering method used by the RAPTOR tree: a 1D +// scan over adjacent embeddings that starts a new cluster whenever the +// similarity between consecutive points drops below a percentile threshold. +// It is not agglomerative hierarchical clustering, despite superficial +// similarity to the term.🤖 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/raptor/watershed.go` around lines 1 - 9, Trim the package comment above the raptor package declaration to describe only the current watershed clustering behavior. Remove the historical Python naming, logging, planning, and migration references, while retaining a concise explanation of what the watershed algorithm does if useful.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 `@internal/ingestion/component/knowledge_compiler/common/types.go`:
- Around line 252-275: Update the []any branch of toFloat32Slice so any element
that is not float64 causes an immediate nil return instead of being skipped;
retain the existing conversion and successful return for vectors whose elements
are all float64.
---
Outside diff comments:
In `@internal/ingestion/component/knowledge_compiler/raptor/raptor.go`:
- Around line 234-281: Replace the global-depth tracking around topLevelTexts
with true-leaf tracking: append a node’s summary when its sub-clustering
produces len(subGroups) <= 1, while retaining summaries for branches that split
through their queued descendants. Remove the maxLevel variable and its level
comparisons/reset logic, ensuring every branch-terminating summary is included
in root synthesis.
---
Duplicate comments:
In `@internal/ingestion/component/knowledge_compiler/raptor/raptor.go`:
- Around line 283-297: Guard the root synthesis path before calling
buildClusterContent: when topLevelTexts is empty after deepest-level failures,
skip root creation and return the remaining tree without invoking summarization.
Also add a defensive zero-length check in buildClusterContent so it returns
safely before dividing by len(idxs) when no indices are provided.
- Around line 100-104: Escape the trailing question mark in
raptorTruncationMarkerRE so the English truncation marker matches the literal
“continue?” text and is fully removed. Extend
TestSummarizeTextsStripsTruncationMarker with an English-marker case covering
the trailing question mark.
---
Nitpick comments:
In `@internal/ingestion/component/knowledge_compiler/raptor/raptor.go`:
- Around line 550-559: The resolveRaptorPrompt function must validate custom
extra["prompt"] values before returning them. Only accept a non-empty string
containing the {cluster_content} placeholder; otherwise return
defaultRaptorPrompt, preserving the existing fallback behavior.
In `@internal/ingestion/component/knowledge_compiler/raptor/watershed.go`:
- Around line 1-9: Trim the package comment above the raptor package declaration
to describe only the current watershed clustering behavior. Remove the
historical Python naming, logging, planning, and migration references, while
retaining a concise explanation of what the watershed algorithm does if useful.
🪄 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: 275bd5e0-ff50-42be-9992-3548ac2adcfe
📒 Files selected for processing (20)
internal/ingestion/component/knowledge_compiler/common/common_test.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/datasetnav/datasetnav.gointernal/ingestion/component/knowledge_compiler/golden/fixtures/raptor_baseline.jsoninternal/ingestion/component/knowledge_compiler/golden_test.gointernal/ingestion/component/knowledge_compiler/mindmap/mindmap.gointernal/ingestion/component/knowledge_compiler/raptor/clustering.gointernal/ingestion/component/knowledge_compiler/raptor/clustering_test.gointernal/ingestion/component/knowledge_compiler/raptor/psi.gointernal/ingestion/component/knowledge_compiler/raptor/raptor.gointernal/ingestion/component/knowledge_compiler/raptor/raptor_test.gointernal/ingestion/component/knowledge_compiler/raptor/watershed.gointernal/ingestion/component/knowledge_compiler/raptor/watershed_test.gointernal/ingestion/component/knowledge_compiler/structure/structure.gointernal/ingestion/component/knowledge_compiler/wiki/wiki.gointernal/ingestion/knowledge_compile/reader.gointernal/ingestion/task/knowledge_compiler_wiring.go
💤 Files with no reviewable changes (4)
- internal/ingestion/component/knowledge_compiler/raptor/clustering_test.go
- internal/ingestion/component/knowledge_compiler/raptor/clustering.go
- internal/ingestion/component/knowledge_compiler/raptor/psi.go
- internal/ingestion/component/knowledge_compiler/common/common_test.go
| // toFloat32Slice normalises a numeric slice (any of []float32, []float64, or | ||
| // []any of float64) to []float32, returning nil when the value is not a usable | ||
| // vector. | ||
| func toFloat32Slice(v any) []float32 { | ||
| switch arr := v.(type) { | ||
| case []float32: | ||
| return arr | ||
| case []float64: | ||
| out := make([]float32, len(arr)) | ||
| for i, x := range arr { | ||
| out[i] = float32(x) | ||
| } | ||
| return out | ||
| case []any: | ||
| out := make([]float32, 0, len(arr)) | ||
| for _, e := range arr { | ||
| if f, ok := e.(float64); ok { | ||
| out = append(out, float32(f)) | ||
| } | ||
| } | ||
| return out | ||
| } | ||
| return nil | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Silent truncation on mixed-type []any vectors.
In the []any branch, elements that fail the float64 type assertion are silently skipped rather than causing an error, so a malformed vector yields a shorter — but still non-nil — output instead of a clear failure signal. Consider returning nil (or an error) as soon as a non-float64 element is encountered, matching the "all-or-nothing" contract implied by the doc comment.
🩹 Proposed fix
case []any:
out := make([]float32, 0, len(arr))
for _, e := range arr {
- if f, ok := e.(float64); ok {
- out = append(out, float32(f))
- }
+ f, ok := e.(float64)
+ if !ok {
+ return nil
+ }
+ out = append(out, float32(f))
}
return out📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // toFloat32Slice normalises a numeric slice (any of []float32, []float64, or | |
| // []any of float64) to []float32, returning nil when the value is not a usable | |
| // vector. | |
| func toFloat32Slice(v any) []float32 { | |
| switch arr := v.(type) { | |
| case []float32: | |
| return arr | |
| case []float64: | |
| out := make([]float32, len(arr)) | |
| for i, x := range arr { | |
| out[i] = float32(x) | |
| } | |
| return out | |
| case []any: | |
| out := make([]float32, 0, len(arr)) | |
| for _, e := range arr { | |
| if f, ok := e.(float64); ok { | |
| out = append(out, float32(f)) | |
| } | |
| } | |
| return out | |
| } | |
| return nil | |
| } | |
| // toFloat32Slice normalises a numeric slice (any of []float32, []float64, or | |
| // []any of float64) to []float32, returning nil when the value is not a usable | |
| // vector. | |
| func toFloat32Slice(v any) []float32 { | |
| switch arr := v.(type) { | |
| case []float32: | |
| return arr | |
| case []float64: | |
| out := make([]float32, len(arr)) | |
| for i, x := range arr { | |
| out[i] = float32(x) | |
| } | |
| return out | |
| case []any: | |
| out := make([]float32, 0, len(arr)) | |
| for _, e := range arr { | |
| f, ok := e.(float64) | |
| if !ok { | |
| return nil | |
| } | |
| out = append(out, float32(f)) | |
| } | |
| return out | |
| } | |
| return nil | |
| } |
🤖 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/common/types.go` around lines
252 - 275, Update the []any branch of toFloat32Slice so any element that is not
float64 causes an immediate nil return instead of being skipped; retain the
existing conversion and successful return for vectors whose elements are all
float64.
left a comment
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
internal/ingestion/component/knowledge_compiler/raptor/raptor_test.go (1)
124-128: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDescribe the current behavior, not migration history.
Reword this doc comment to state that complete summary failure returns an empty product set without error.
Proposed update
-// TestBuildTreeNoPanicWhenAllSummariesFail guards the divide-by-zero that -// occurred when every deepest cluster failed: buildClusterContent divides by -// len(idxs), and the root synthesis built a cluster from allIndices(0) when -// topLevelTexts was empty. The root is now skipped and the partial tree is -// returned without error. +// TestBuildTreeNoPanicWhenAllSummariesFail verifies that complete summary +// failure returns without error and produces no products.As per coding guidelines, keep doc comments aligned with the current runtime path rather than migration history.
🤖 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/raptor/raptor_test.go` around lines 124 - 128, Reword the doc comment for TestBuildTreeNoPanicWhenAllSummariesFail to describe the current behavior: when all summaries fail, the function returns an empty product set without error. Remove references to the former divide-by-zero, root synthesis, and migration history.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 `@internal/ingestion/component/knowledge_compiler/common/types.go`:
- Around line 243-269: Update VectorFromChunkMap to collect all q_*_vec keys
before selecting a vector, reject multiple matching keys regardless of whether
the requested key exists, and when dim > 0 require q_<dim>_vec to be present.
Validate the selected vector’s length against the dimension encoded by its key
(including the requested dim) before returning it; otherwise return an error.
In `@internal/ingestion/knowledge_compile/reader.go`:
- Around line 131-140: Update LoadCompiledProducts and the compiled-product
construction around VectorFromChunkMap to project the persisted q_*_vec field(s)
in the query, then handle the returned extraction error before creating the
product. Propagate or explicitly reject extraction failures so mixed-vector rows
cannot silently produce vectorless products, while preserving the existing
product fields and return behavior for valid vectors.
---
Nitpick comments:
In `@internal/ingestion/component/knowledge_compiler/raptor/raptor_test.go`:
- Around line 124-128: Reword the doc comment for
TestBuildTreeNoPanicWhenAllSummariesFail to describe the current behavior: when
all summaries fail, the function returns an empty product set without error.
Remove references to the former divide-by-zero, root synthesis, and migration
history.
🪄 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: 31575c75-63d0-4be7-bc03-e4ecf4e6492b
📒 Files selected for processing (6)
internal/ingestion/component/knowledge_compiler/common/types.gointernal/ingestion/component/knowledge_compiler/component.gointernal/ingestion/component/knowledge_compiler/raptor/raptor.gointernal/ingestion/component/knowledge_compiler/raptor/raptor_test.gointernal/ingestion/knowledge_compile/reader.gointernal/ingestion/task/knowledge_compiler_wiring.go
| // | ||
| // dim selects the exact "q_<dim>_vec" key when the embedding dimension is known | ||
| // (dim > 0); otherwise every "q_*_vec" key is considered. A chunk must carry at | ||
| // most one embedding vector: multiple q_*_vec fields signal mixed embedding | ||
| // models, and because Go map iteration order is nondeterministic, picking among | ||
| // them would be unstable across runs — such chunks are rejected with an error. | ||
| func VectorFromChunkMap(m map[string]any, dim int) ([]float32, error) { | ||
| if dim > 0 { | ||
| if v, ok := m[fmt.Sprintf("q_%d_vec", dim)]; ok { | ||
| return toFloat32Slice(v), nil | ||
| } | ||
| } | ||
| var keys []string | ||
| for k := range m { | ||
| if strings.HasPrefix(k, "q_") && strings.HasSuffix(k, "_vec") { | ||
| keys = append(keys, k) | ||
| } | ||
| } | ||
| switch len(keys) { | ||
| case 0: | ||
| return nil, nil | ||
| case 1: | ||
| return toFloat32Slice(m[keys[0]]), nil | ||
| default: | ||
| return nil, fmt.Errorf("knowledge_compiler: chunk carries %d embedding vectors %v; expected exactly one", len(keys), keys) | ||
| } | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Enforce the requested vector dimension before accepting a vector.
When dim > 0, a missing q_<dim>_vec falls through to a different single vector, and extra q_*_vec keys are ignored when the requested key exists. The code also never verifies that the vector length matches the dimension encoded in its key, allowing a malformed q_768_vec to be emitted later as q_<len>_vec.
Collect and validate all matching keys first, reject mixed keys, and require both the requested key and matching vector length.
🤖 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/common/types.go` around lines
243 - 269, Update VectorFromChunkMap to collect all q_*_vec keys before
selecting a vector, reject multiple matching keys regardless of whether the
requested key exists, and when dim > 0 require q_<dim>_vec to be present.
Validate the selected vector’s length against the dimension encoded by its key
(including the requested dim) before returning it; otherwise return an error.
| vec, _ := kccommon.VectorFromChunkMap(c, 0) | ||
| return kccommon.Product{ | ||
| ID: id, | ||
| DocID: docID, | ||
| TenantID: tenant, | ||
| Variant: kccommon.Variant(variant), | ||
| Content: content, | ||
| Vector: vectorFromChunkMap(c), | ||
| Vector: vec, | ||
| Meta: meta, | ||
| }, true |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Wire persisted vectors through the compiled-product read path.
LoadCompiledProducts requests explicit fields without any q_*_vec field, so this new extraction normally returns nil. It also discards extraction errors, allowing mixed-vector rows to become vectorless products. Include the stored vector field(s) in the query projection and propagate or explicitly reject extraction errors before constructing the product.
🤖 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/knowledge_compile/reader.go` around lines 131 - 140,
Update LoadCompiledProducts and the compiled-product construction around
VectorFromChunkMap to project the persisted q_*_vec field(s) in the query, then
handle the returned extraction error before creating the product. Propagate or
explicitly reject extraction failures so mixed-vector rows cannot silently
produce vectorless products, while preserving the existing product fields and
return behavior for valid vectors.
…stic vector pick - Guard buildClusterContent against empty idxs; skip root synthesis when all summaries fail (fixes divide-by-zero panic). - ResolveModelConfig now runs under a 30s bounded context to avoid blocking ingestion. - VectorFromChunkMap takes the embedding dim and errors on duplicate q_*_vec keys instead of relying on nondeterministic map iteration.
4f80859 to
ad79303
Compare
left a comment
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 (2)
internal/ingestion/knowledge_compile/reader.go (1)
50-56: 🗄️ Data Integrity & Integration | 🟠 MajorPersisted vectors still not wired through the read path.
SelectFieldsrequests noq_*_veccolumn, soVectorFromChunkMaphere always sees an empty map and returnsnil, nil— compiled products read back viaLoadCompiledProductsnever carry a vector. The extraction error is also discarded (vec, _ := ...), so a genuinely mixed-vector row would silently become vectorless instead of failing loudly. This was previously flagged and remains unaddressed.🐛 Proposed fix
SelectFields: []string{ "id", "doc_id", "tenant_id", "compile_kwd", "content_with_weight", "kc_payload", "source_chunk_ids", "source_doc_ids", "name_kwd", "entity_type_kwd", "from_entity_kwd", "to_entity_kwd", - "slug_kwd", "type", + "slug_kwd", "type", "q_*_vec", },- vec, _ := kccommon.VectorFromChunkMap(c, 0) + vec, err := kccommon.VectorFromChunkMap(c, 0) + if err != nil { + return kccommon.Product{}, false + }(Adjust the wildcard field projection to whatever the search engine's field-selection syntax actually supports.)
Also applies to: 131-140
🤖 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/knowledge_compile/reader.go` around lines 50 - 56, Update the SelectFields configuration used by LoadCompiledProducts so the query retrieves persisted q_*_vec fields using the search engine’s supported wildcard field-selection syntax, allowing VectorFromChunkMap to reconstruct vectors. Capture and propagate the error returned by VectorFromChunkMap instead of discarding it, so mixed-vector extraction failures are returned rather than producing vectorless products.internal/ingestion/component/knowledge_compiler/raptor/raptor.go (1)
174-281: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winRoot synthesis silently drops summaries from branches that terminate before the tree's deepest level.
topLevelTextstracks only the globally deepest level reached so far (reset viatopLevelTexts[:0]every timetask.level > maxLevel). Since the queue is a strict BFS (FIFO, levels processed in order), any cluster that stops recursing at a shallow level (e.g., a 2-point cluster whose sub-split yields only singleton children) has its summary permanently evicted fromtopLevelTextsthe moment any other branch reaches a deeper level — even though that node is a genuine, structurally-valid leaf directly parented to root. The root's synthesizedContenttherefore silently omits entire branches whenever the tree has uneven depth across clusters, which is the common case with watershed's per-branch termination. This isn't caught by any existing test (structural golden/e2e tests check parenting/vectors/schema/depth bounds, not root-text completeness).Track terminal-ness explicitly instead of relying on global depth.
🐛 Proposed fix: feed root from actual leaves, not the deepest global level
- rootID := common.StableRowID(tenantID, docID, string(common.VariantRaptor), "root") - var ( - maxLevel = -1 - topLevelTexts []string - ) + rootID := common.StableRowID(tenantID, docID, string(common.VariantRaptor), "root") + var topLevelTexts []string @@ - // Track the deepest-level summaries for the root synthesis: only those - // are fed to the root, so the root summarises the top of the tree - // rather than re-summarising every leaf. - if task.level > maxLevel { - maxLevel = task.level - topLevelTexts = topLevelTexts[:0] - } - if task.level == maxLevel { - topLevelTexts = append(topLevelTexts, summary) - } - // Recurse: ... subEmb := make([][]float64, 0, len(task.pointIdxs)) for _, pi := range task.pointIdxs { subEmb = append(subEmb, embeddings[pi]) } subLabels, err := watershed(subEmb, treeOrder) if err != nil { return err } subGroups := map[int][]int{} for i, li := range subLabels { subGroups[li] = append(subGroups[li], task.pointIdxs[i]) } + hasChildren := false if len(subGroups) > 1 { for _, idxs := range subGroups { if len(idxs) <= 1 { continue } queue = append(queue, nodeTask{pointIdxs: idxs, parentID: nodeID, level: task.level + 1}) + hasChildren = true } } + // This node has no children: it is a true leaf of the recursion, so + // its summary feeds the root synthesis regardless of its depth. + if !hasChildren { + topLevelTexts = append(topLevelTexts, summary) + } }🤖 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/raptor/raptor.go` around lines 174 - 281, Update the breadth-first tree construction around nodeTask and topLevelTexts to track summaries from actual terminal clusters rather than only nodes at the globally deepest level. Mark a node as terminal when its sub-clustering does not produce multiple non-singleton child groups, and retain its summary for root synthesis; remove the maxLevel-based reset/filtering so shallow leaves from uneven branches are preserved.
♻️ Duplicate comments (2)
internal/ingestion/component/knowledge_compiler/common/types.go (2)
271-294: 🗄️ Data Integrity & Integration | 🟡 Minor
[]anybranch still silently drops non-float64 elements.Elements failing the
float64assertion are skipped rather than causing a failure, so a malformed vector yields a shorter, still-truthy result instead of a clear error. Previously flagged; unchanged in the current code.🩹 Proposed fix
case []any: out := make([]float32, 0, len(arr)) for _, e := range arr { - if f, ok := e.(float64); ok { - out = append(out, float32(f)) - } + f, ok := e.(float64) + if !ok { + return nil + } + out = append(out, float32(f)) } return out🤖 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/common/types.go` around lines 271 - 294, Update toFloat32Slice’s []any branch to reject the entire input when any element is not a float64, returning nil instead of silently skipping invalid elements. Preserve conversion of valid float64 elements and ensure malformed vectors cannot produce a shorter non-nil slice.
249-269: 🗄️ Data Integrity & Integration | 🟠 MajorRequested dimension still not enforced when
q_<dim>_vecis missing.When
dim > 0andq_<dim>_vecis absent, execution falls through to the generic key scan; if exactly oneq_*_veckey exists, it is returned even though its dimension doesn't matchdim. This was previously flagged and is still present in the current code. Note current call sites (component.go,reader.go) both passdim=0, so the buggy branch is presently unreachable — worth fixing before any caller starts passing a real dimension.🐛 Proposed fix
func VectorFromChunkMap(m map[string]any, dim int) ([]float32, error) { - if dim > 0 { - if v, ok := m[fmt.Sprintf("q_%d_vec", dim)]; ok { - return toFloat32Slice(v), nil - } - } var keys []string for k := range m { if strings.HasPrefix(k, "q_") && strings.HasSuffix(k, "_vec") { keys = append(keys, k) } } + if dim > 0 { + key := fmt.Sprintf("q_%d_vec", dim) + if len(keys) > 0 && (len(keys) > 1 || keys[0] != key) { + return nil, fmt.Errorf("knowledge_compiler: chunk carries embedding vectors %v; expected only %q", keys, key) + } + if v, ok := m[key]; ok { + return toFloat32Slice(v), nil + } + return nil, nil + } switch len(keys) { case 0: return nil, nil case 1: return toFloat32Slice(m[keys[0]]), nil default: return nil, fmt.Errorf("knowledge_compiler: chunk carries %d embedding vectors %v; expected exactly one", len(keys), keys) } }🤖 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/common/types.go` around lines 249 - 269, Update VectorFromChunkMap so that when dim > 0, absence of the exact q_<dim>_vec key returns no vector (or the established missing-vector result) instead of falling through to generic key discovery. Keep the existing generic scan behavior only for dim == 0, ensuring a differently dimensioned sole vector is never returned for a requested dimension.
🧹 Nitpick comments (2)
internal/ingestion/component/knowledge_compiler/raptor/raptor.go (2)
560-569: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winNo validation that a custom prompt contains the
{cluster_content}placeholder.
strings.Replace(taskPrompt, "{cluster_content}", content, 1)is a silent no-op if the placeholder is missing from a user-suppliedextra["prompt"], so a misconfigured override sends the LLM a prompt with no cluster content at all, with no error or log to signal the problem.♻️ Proposed guard
func resolveRaptorPrompt(param common.Param) string { if raw, ok := param.Extra["prompt"]; ok { - if s, ok := raw.(string); ok && strings.TrimSpace(s) != "" { + if s, ok := raw.(string); ok && strings.TrimSpace(s) != "" && strings.Contains(s, "{cluster_content}") { return s } + log.Printf("raptor: extra[\"prompt\"] is missing the {cluster_content} placeholder, falling back to default") } return defaultRaptorPrompt }🤖 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/raptor/raptor.go` around lines 560 - 569, Update resolveRaptorPrompt to validate non-empty custom extra["prompt"] values contain the {cluster_content} placeholder before returning them. If the placeholder is absent, fall back to defaultRaptorPrompt so the prompt always includes cluster content; leave the existing handling of invalid or blank overrides unchanged.
51-54: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winConsider preserving already-buffered products when the error ceiling aborts the tree.
When
errorCount >= maxErrors,buildTreereturns an error andRundiscardsproductsentirely (common.Outputs{}, err), even though other clusters may have summarized successfully. This is inconsistent with the graceful-degradation approach used elsewhere in this function (root-synthesis/embedding failures just skip the root and return the partial tree). If full-abort-and-discard is intentional Python parity, consider at least returning the partialproductsalongside the error so the caller can decide whether to keep 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 `@internal/ingestion/component/knowledge_compiler/raptor/raptor.go` around lines 51 - 54, Update Run’s buildTree error path to preserve and return the already-buffered products alongside the error instead of discarding them via common.Outputs{}. Keep the existing error propagation intact so callers can decide whether to retain the partial results.
🤖 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/ingestion/component/knowledge_compiler/raptor/raptor.go`:
- Around line 174-281: Update the breadth-first tree construction around
nodeTask and topLevelTexts to track summaries from actual terminal clusters
rather than only nodes at the globally deepest level. Mark a node as terminal
when its sub-clustering does not produce multiple non-singleton child groups,
and retain its summary for root synthesis; remove the maxLevel-based
reset/filtering so shallow leaves from uneven branches are preserved.
In `@internal/ingestion/knowledge_compile/reader.go`:
- Around line 50-56: Update the SelectFields configuration used by
LoadCompiledProducts so the query retrieves persisted q_*_vec fields using the
search engine’s supported wildcard field-selection syntax, allowing
VectorFromChunkMap to reconstruct vectors. Capture and propagate the error
returned by VectorFromChunkMap instead of discarding it, so mixed-vector
extraction failures are returned rather than producing vectorless products.
---
Duplicate comments:
In `@internal/ingestion/component/knowledge_compiler/common/types.go`:
- Around line 271-294: Update toFloat32Slice’s []any branch to reject the entire
input when any element is not a float64, returning nil instead of silently
skipping invalid elements. Preserve conversion of valid float64 elements and
ensure malformed vectors cannot produce a shorter non-nil slice.
- Around line 249-269: Update VectorFromChunkMap so that when dim > 0, absence
of the exact q_<dim>_vec key returns no vector (or the established
missing-vector result) instead of falling through to generic key discovery. Keep
the existing generic scan behavior only for dim == 0, ensuring a differently
dimensioned sole vector is never returned for a requested dimension.
---
Nitpick comments:
In `@internal/ingestion/component/knowledge_compiler/raptor/raptor.go`:
- Around line 560-569: Update resolveRaptorPrompt to validate non-empty custom
extra["prompt"] values contain the {cluster_content} placeholder before
returning them. If the placeholder is absent, fall back to defaultRaptorPrompt
so the prompt always includes cluster content; leave the existing handling of
invalid or blank overrides unchanged.
- Around line 51-54: Update Run’s buildTree error path to preserve and return
the already-buffered products alongside the error instead of discarding them via
common.Outputs{}. Keep the existing error propagation intact so callers can
decide whether to retain the partial results.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 723ca869-178b-4231-b2ae-5b400d216a75
📒 Files selected for processing (23)
internal/ingestion/component/knowledge_compiler/common/common_test.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/datasetnav/datasetnav.gointernal/ingestion/component/knowledge_compiler/golden/fixtures/raptor_baseline.jsoninternal/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/raptor/clustering.gointernal/ingestion/component/knowledge_compiler/raptor/clustering_test.gointernal/ingestion/component/knowledge_compiler/raptor/psi.gointernal/ingestion/component/knowledge_compiler/raptor/raptor.gointernal/ingestion/component/knowledge_compiler/raptor/raptor_test.gointernal/ingestion/component/knowledge_compiler/raptor/watershed.gointernal/ingestion/component/knowledge_compiler/raptor/watershed_test.gointernal/ingestion/component/knowledge_compiler/structure/structure.gointernal/ingestion/component/knowledge_compiler/wiki/wiki.gointernal/ingestion/knowledge_compile/reader.gointernal/ingestion/task/knowledge_compiler_wiring.gointernal/utility/markdown_to_json.gointernal/utility/markdown_to_json_test.go
💤 Files with no reviewable changes (4)
- internal/ingestion/component/knowledge_compiler/raptor/psi.go
- internal/ingestion/component/knowledge_compiler/raptor/clustering.go
- internal/ingestion/component/knowledge_compiler/raptor/clustering_test.go
- internal/ingestion/component/knowledge_compiler/common/common_test.go
Port RAPTOR knowledge compilation to match Python: remove Go-only capacity guardrails, fix prompts, add token truncation, response post-processing, retries, replace AHC with watershed.