Skip to content

Align Go knowledge compiler RAPTOR with Python and drop guardrails - #17573

Merged
yuzhichang merged 3 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port
Jul 30, 2026
Merged

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

Conversation

@yuzhichang

Copy link
Copy Markdown
Member

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.

@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jul 30, 2026
@coderabbitai

ghost commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Knowledge compiler pipeline

Layer / File(s) Summary
Shared contracts and embedding plumbing
internal/ingestion/component/knowledge_compiler/common/..., internal/ingestion/component/knowledge_compiler/component.go, internal/ingestion/knowledge_compile/reader.go, internal/ingestion/task/knowledge_compiler_wiring.go
Chat requests and dependencies gain token/context limits; vector extraction is centralized and precomputed chunk embeddings are reused.
Buffered output and template stamping
internal/ingestion/component/knowledge_compiler/common/..., internal/ingestion/component/knowledge_compiler/{component,datasetnav,mindmap,structure,wiki}/*
Sink-based product emission, capacity guardrails, and flush accounting are removed; variants return buffered products and template IDs are applied after compilation.
Watershed clustering implementation
internal/ingestion/component/knowledge_compiler/raptor/watershed*
RAPTOR adds normalized adjacent-similarity clustering with bounded tree_order and deterministic edge-case coverage.
RAPTOR tree and summarization flow
internal/ingestion/component/knowledge_compiler/raptor/raptor*
RAPTOR uses watershed recursion, token-bounded content, configurable prompts, summary retries, response cleanup, and buffered product construction.
Exported Markdown tree utilities
internal/utility/markdown_to_json*, internal/ingestion/component/knowledge_compiler/mindmap/*
Markdown parsing and tree-shaping helpers move to exported utility APIs, and mindmap generation adopts them with expanded tests.
RAPTOR validation and migration coverage
internal/ingestion/component/knowledge_compiler/{component_test,golden_test}.go, internal/ingestion/component/knowledge_compiler/golden/fixtures/*
Integration tests and golden bounds now validate watershed tree orders and complete summary inclusion.

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
Loading

Possibly related PRs

  • infiniflow/ragflow#17536: Removes the knowledge compiler capacity guardrails and sink/flush plumbing that this change also replaces.

Suggested labels: 🐞 bug

Poem

I’m a bunny with clusters in line,
Watershed branches neatly entwine.
Summaries retry, tokens stay light,
Vectors hop through the pipeline just right.
Sinks nap while products grow—
Golden roots bloom in the show!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is missing the required ### Summary section and lacks the requested background context. Add a ### Summary section with a brief problem statement and background context describing why these RAPTOR changes are needed.
Docstring Coverage ⚠️ Warning Docstring coverage is 60.87% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: aligning Go RAPTOR with Python and removing guardrails.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@yuzhichang yuzhichang added the ci Continue Integration label Jul 30, 2026

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

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 win

Sort cluster indices before building the Raptor processing queue.

groups and subGroups are maps, so the order keys are ranged over is not stable in Go. Those orders determine queue order, topLevelTexts accumulation order, and the input order for buildClusterContent, making the root synthesis content non-reproducible even with identical inputs. Use sorted keys before building queue in 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 win

Package docs reference migration history/plan instead of only describing current behavior. Both watershed.go and raptor.go package 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 **/*.go doc-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

📥 Commits

Reviewing files that changed from the base of the PR and between 1629357 and 65c723d.

📒 Files selected for processing (20)
  • internal/ingestion/component/knowledge_compiler/common/common_test.go
  • internal/ingestion/component/knowledge_compiler/common/deps.go
  • internal/ingestion/component/knowledge_compiler/common/types.go
  • internal/ingestion/component/knowledge_compiler/component.go
  • internal/ingestion/component/knowledge_compiler/component_test.go
  • internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav.go
  • internal/ingestion/component/knowledge_compiler/golden/fixtures/raptor_baseline.json
  • internal/ingestion/component/knowledge_compiler/golden_test.go
  • internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go
  • internal/ingestion/component/knowledge_compiler/raptor/clustering.go
  • internal/ingestion/component/knowledge_compiler/raptor/clustering_test.go
  • internal/ingestion/component/knowledge_compiler/raptor/psi.go
  • internal/ingestion/component/knowledge_compiler/raptor/raptor.go
  • internal/ingestion/component/knowledge_compiler/raptor/raptor_test.go
  • internal/ingestion/component/knowledge_compiler/raptor/watershed.go
  • internal/ingestion/component/knowledge_compiler/raptor/watershed_test.go
  • internal/ingestion/component/knowledge_compiler/structure/structure.go
  • internal/ingestion/component/knowledge_compiler/wiki/wiki.go
  • internal/ingestion/knowledge_compile/reader.go
  • internal/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

Comment on lines +100 to +104
// 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?",
)

ghost Jul 30, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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:


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.

Suggested change
// 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.

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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 win

Root synthesis silently drops content from branches that terminate before the global deepest level.

topLevelTexts is fed by comparing task.level against a single, globally-tracked maxLevel, 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 to len(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, maxLevel advances past 2 and clears topLevelTexts, 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 maxLevel variable 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 win

Root synthesis still divides by zero when every deepest-level summary fails.

If every deepest-level cluster's summarization fails while errorCount stays under maxErrors, topLevelTexts stays empty. buildClusterContent (line 389) then computes per := (llmMaxLength - maxToken) / len(idxs) with len(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 buildClusterContent itself 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 win

Truncation-marker regex still leaves the trailing ? unescaped.

continue? at the end of the pattern makes RE2 treat ? as "zero or one of the preceding e", not a literal question mark. Genuine "...continue?" truncation notices will still have their trailing ? left in the summary after ReplaceAllString. 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's TestSummarizeTextsStripsTruncationMarker only 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 win

Custom 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 win

Doc 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, **/*.go files 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

📥 Commits

Reviewing files that changed from the base of the PR and between 65c723d and 4a9d7ff.

📒 Files selected for processing (20)
  • internal/ingestion/component/knowledge_compiler/common/common_test.go
  • internal/ingestion/component/knowledge_compiler/common/deps.go
  • internal/ingestion/component/knowledge_compiler/common/types.go
  • internal/ingestion/component/knowledge_compiler/component.go
  • internal/ingestion/component/knowledge_compiler/component_test.go
  • internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav.go
  • internal/ingestion/component/knowledge_compiler/golden/fixtures/raptor_baseline.json
  • internal/ingestion/component/knowledge_compiler/golden_test.go
  • internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go
  • internal/ingestion/component/knowledge_compiler/raptor/clustering.go
  • internal/ingestion/component/knowledge_compiler/raptor/clustering_test.go
  • internal/ingestion/component/knowledge_compiler/raptor/psi.go
  • internal/ingestion/component/knowledge_compiler/raptor/raptor.go
  • internal/ingestion/component/knowledge_compiler/raptor/raptor_test.go
  • internal/ingestion/component/knowledge_compiler/raptor/watershed.go
  • internal/ingestion/component/knowledge_compiler/raptor/watershed_test.go
  • internal/ingestion/component/knowledge_compiler/structure/structure.go
  • internal/ingestion/component/knowledge_compiler/wiki/wiki.go
  • internal/ingestion/knowledge_compile/reader.go
  • internal/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

Comment on lines +252 to +275
// 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
}

ghost Jul 30, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 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.

Suggested change
// 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.

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
internal/ingestion/component/knowledge_compiler/raptor/raptor_test.go (1)

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

Describe 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4a9d7ff and 6e311ee.

📒 Files selected for processing (6)
  • internal/ingestion/component/knowledge_compiler/common/types.go
  • internal/ingestion/component/knowledge_compiler/component.go
  • internal/ingestion/component/knowledge_compiler/raptor/raptor.go
  • internal/ingestion/component/knowledge_compiler/raptor/raptor_test.go
  • internal/ingestion/knowledge_compile/reader.go
  • internal/ingestion/task/knowledge_compiler_wiring.go

Comment on lines +243 to +269
//
// 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)
}
}

ghost Jul 30, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

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.

Comment on lines +131 to 140
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

ghost Jul 30, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

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.

yzc added 3 commits July 30, 2026 19:25
…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.

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (2)
internal/ingestion/knowledge_compile/reader.go (1)

50-56: 🗄️ Data Integrity & Integration | 🟠 Major

Persisted vectors still not wired through the read path.

SelectFields requests no q_*_vec column, so VectorFromChunkMap here always sees an empty map and returns nil, nil — compiled products read back via LoadCompiledProducts never 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 win

Root synthesis silently drops summaries from branches that terminate before the tree's deepest level.

topLevelTexts tracks only the globally deepest level reached so far (reset via topLevelTexts[:0] every time task.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 from topLevelTexts the 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 synthesized Content therefore 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

[]any branch still silently drops non-float64 elements.

Elements failing the float64 assertion 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 | 🟠 Major

Requested dimension still not enforced when q_<dim>_vec is missing.

When dim > 0 and q_<dim>_vec is absent, execution falls through to the generic key scan; if exactly one q_*_vec key exists, it is returned even though its dimension doesn't match dim. This was previously flagged and is still present in the current code. Note current call sites (component.go, reader.go) both pass dim=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 win

No 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-supplied extra["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 win

Consider preserving already-buffered products when the error ceiling aborts the tree.

When errorCount >= maxErrors, buildTree returns an error and Run discards products entirely (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 partial products alongside 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6e311ee and ad79303.

📒 Files selected for processing (23)
  • internal/ingestion/component/knowledge_compiler/common/common_test.go
  • internal/ingestion/component/knowledge_compiler/common/deps.go
  • internal/ingestion/component/knowledge_compiler/common/types.go
  • internal/ingestion/component/knowledge_compiler/component.go
  • internal/ingestion/component/knowledge_compiler/component_test.go
  • internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav.go
  • internal/ingestion/component/knowledge_compiler/golden/fixtures/raptor_baseline.json
  • internal/ingestion/component/knowledge_compiler/golden_test.go
  • internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go
  • internal/ingestion/component/knowledge_compiler/mindmap/mindmap_test.go
  • internal/ingestion/component/knowledge_compiler/raptor/clustering.go
  • internal/ingestion/component/knowledge_compiler/raptor/clustering_test.go
  • internal/ingestion/component/knowledge_compiler/raptor/psi.go
  • internal/ingestion/component/knowledge_compiler/raptor/raptor.go
  • internal/ingestion/component/knowledge_compiler/raptor/raptor_test.go
  • internal/ingestion/component/knowledge_compiler/raptor/watershed.go
  • internal/ingestion/component/knowledge_compiler/raptor/watershed_test.go
  • internal/ingestion/component/knowledge_compiler/structure/structure.go
  • internal/ingestion/component/knowledge_compiler/wiki/wiki.go
  • internal/ingestion/knowledge_compile/reader.go
  • internal/ingestion/task/knowledge_compiler_wiring.go
  • internal/utility/markdown_to_json.go
  • internal/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

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

Labels

ci Continue Integration size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant