Skip to content

Port dataset-level knowledge compile to Go with variant dispatch - #18161

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
yuzhichang:agent-go-port
Aug 12, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
yuzhichang:agent-go-port

Conversation

@yuzhichang

@yuzhichang yuzhichang commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

Ports dataset-level knowledge compilation (tree/structure/wiki) to Go: add compile-type variants to backlog events, route per-variant dataset-level paths, move dataset-nav to the consumer, add structure merge and per-variant clean, plus rebuild variant recovery.

image

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

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change propagates compile variants through completion events, scheduler backlog entries, rebuilds, and persistence. It moves navigation and structure processing into the consumer, adds dataset-level structure aggregation and cleanup, and extends navigation cluster lifecycle handling.

Changes

Knowledge compilation lifecycle

Layer / File(s) Summary
Variant metadata contracts
internal/ingestion/component/knowledge_compiler/common/types_test.go, internal/ingestion/knowledge_compile/{event,scheduler,reader}.go, internal/ingestion/task/pipeline_executor.go
Completion events, backlog entries, product reconstruction, and pipeline publication now preserve validated compile variants.
Compiler output and navigation ownership
internal/ingestion/component/knowledge_compiler/component.go
Deferred tree and structure navigation generation was removed. Converted products now use document scope.
Rebuild and completion dispatch
internal/ingestion/knowledge_compile/consumer.go, internal/ingestion/knowledge_compile/nav_dispatch_test.go
Rebuilds recover variants and clear managed data. Completion processing dispatches navigation inputs, merges structures, and uses claim-fenced writes.
Structure persistence and cleanup
internal/ingestion/knowledge_compile/writer.go, internal/ingestion/knowledge_compile/*_test.go
Dataset-scoped structure rows, source tracking, vector aggregation, ghost cleanup, and variant-specific deletion were added.
Navigation lifecycle and cluster management
internal/service/nav/nav.go, internal/service/nlp/datasetnav.go, internal/service/nlp/datasetnav_test.go
Optional LLM naming, stable row IDs, cascading document removal, and overfull-cluster splitting were added with deterministic fallbacks.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PipelineExecutor
  participant Scheduler
  participant Consumer
  participant KnowledgeCompileWriter
  participant NavService
  PipelineExecutor->>Scheduler: publish completion with variants
  Scheduler->>Consumer: deliver variant-bearing backlog entry
  Consumer->>KnowledgeCompileWriter: merge structure products
  Consumer->>NavService: upsert navigation inputs
  Consumer->>KnowledgeCompileWriter: persist build time and cleanup rows
Loading

Possibly related PRs

Suggested labels: 💞 feature

Suggested reviewers: jinhai-cn

Poem

A rabbit sorts variants in rows,
Structures gather by name.
Clusters split when limits grow,
Stable IDs keep records the same.
Old ghosts leave, and events start—
The compiler keeps its careful heart.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: moving dataset-level knowledge compilation to Go with variant dispatch.
Description check ✅ Passed The description clearly states the PR purpose and covers variant dispatch, dataset navigation, structure merging, cleanup, and rebuild recovery.
Docstring Coverage ✅ Passed Docstring coverage is 95.38% which is sufficient. The required threshold is 80.00%.
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 18

🧹 Nitpick comments (8)
internal/service/nlp/datasetnav.go (4)

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

Remove the discarded total binding.

total is only consumed by _ = total. Discard it at the call site instead.

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

♻️ Proposed change
-	children, total, err := s.navSearch(ctx, tenantID, kbID,
+	children, _, err := s.navSearch(ctx, tenantID, kbID,
-	_ = total
 	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/service/nlp/datasetnav.go` at line 607, Remove the `_ = total`
statement and discard the unused `total` value directly at the call site where
it is returned. Preserve the other returned values and existing behavior.

Source: Coding guidelines


302-317: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Delegate the changed-summary cleanup to RemoveDoc.

Lines 305-316 repeat the body of RemoveDoc (lines 730-755) except for the findClusterContainingDoc fallback. Two consequences follow:

  1. The logic is duplicated and can drift.
  2. If the document has no separate nav_doc row, deleteNavDoc returns an empty parent. This path then skips the cluster-membership decrement that RemoveDoc performs through findClusterContainingDoc. The old cluster keeps the document in doc_ids_kwd and keeps its doc_count_int.

Call RemoveDoc here to converge on one implementation path.

As per coding guidelines: "When old and new implementations coexist, converge on one implementation path unless an external contract requires compatibility."

♻️ Proposed refactor
-		// Changed summary: remove the old nav_doc first (and prune any emptied
-		// cluster). The doc may have lived in a cluster; the cluster is then
-		// decremented/cascaded by RemoveDoc's cleanup logic.
-		parent, err := s.deleteNavDoc(ctx, in.TenantID, in.KbID, in.DocID)
-		if err != nil {
-			return err
-		}
-		if parent != "" && parent != navRootParent {
-			if err := s.removeDocFromCluster(ctx, in.TenantID, in.KbID, parent, in.DocID); err != nil {
-				return err
-			}
-		}
-		if err := s.cleanupEmptyCluster(ctx, in.TenantID, in.KbID, parent); err != nil {
+		// Changed summary: remove the old nav_doc and cascade cluster cleanup.
+		if err := s.RemoveDoc(ctx, in.TenantID, in.KbID, in.DocID); err != nil {
 			return err
 		}
🤖 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/service/nlp/datasetnav.go` around lines 302 - 317, Replace the
duplicated changed-summary cleanup around deleteNavDoc, removeDocFromCluster,
and cleanupEmptyCluster with a call to RemoveDoc using the same tenant,
knowledge-base, and document identifiers. Ensure this path also uses RemoveDoc’s
findClusterContainingDoc fallback when no nav_doc row exists, and preserve the
existing error propagation.

Source: Coding guidelines


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

Normalize the LLM-supplied cluster name.

This file treats title_kwd as the cluster key. appendDocToCluster, removeDocFromCluster, cleanupEmptyCluster, and maybeSplitCluster all look clusters up by title_kwd. The LLM name is returned verbatim at line 629 with no validation.

Two risks follow:

  1. If the LLM returns a name that an existing cluster already uses, the insert at line 370 creates a second row with the same key. Every later lookup uses limit 1 and picks one row arbitrarily.
  2. maybeSplitCluster derives :A and :B suffixes from the name. A name that already contains : produces ambiguous split names.

Trim the name, reject empty or oversized values, and check for an existing cluster with the same title_kwd before insert.

🤖 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/service/nlp/datasetnav.go` around lines 623 - 633, Normalize the LLM
result in NavService.llmCreateSummary by trimming whitespace, rejecting empty,
oversized, or colon-containing names, and falling back to the deterministic
cluster name when invalid. In the cluster creation flow used by
appendDocToCluster, check whether the normalized title_kwd already exists before
inserting and avoid creating a duplicate key, preserving consistent lookups and
split suffixes.

611-621: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove or wire llmMergeDescription

llmMergeDescription has no call sites. Remove this dead helper, or call it from maybeSplitCluster when constructing split descriptions.

🤖 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/service/nlp/datasetnav.go` around lines 611 - 621, Remove the unused
NavService.llmMergeDescription helper, or integrate it into maybeSplitCluster
when constructing descriptions for split clusters. If integrating, replace the
existing description construction with llmMergeDescription while preserving the
current fallback behavior.

Source: Coding guidelines

internal/service/nlp/datasetnav_test.go (1)

389-411: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Strengthen the assertions; the test cannot fail for the behavior it documents.

The comment at line 391 states that the document is dropped from its parent cluster's doc_ids_kwd. The loop at lines 403-410 only asserts absence of rows. It never inspects doc_ids_kwd or doc_count_int.

The scenario also does not exercise the path the test name implies. With an empty index, the first UpsertDoc creates a root cluster and no nav_doc row, so deleteNavDoc returns an empty parent and RemoveDoc takes the findClusterContainingDoc fallback branch.

Add a second document that merges into an existing cluster, then assert the surviving cluster's doc_ids_kwd and doc_count_int after removing the first. That covers the nav_doc branch and would catch a membership-list regression.

🤖 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/service/nlp/datasetnav_test.go` around lines 389 - 411, Strengthen
TestNavService_RemoveDoc_CascadesToEmptyCluster by upserting a second document
that merges into the first document’s existing cluster, then remove the first
document through the nav_doc path. Assert the surviving cluster’s doc_ids_kwd
excludes the removed ID and doc_count_int reflects one document, while retaining
the existing absence assertions for the removed nav_doc and pruned empty
clusters.
internal/ingestion/component/knowledge_compiler/common/types_test.go (1)

37-53: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add the mind_map/mindmap alias equality assertion.

The test locks the structure/knowledge_graph/graph alias group. The mind_map alias is only checked for a non-empty result in TestKindToVariant_WhitelistCoversAllValidKinds. A regression that maps mind_map to a different variant would still pass. Lock the equality here.

Based on learnings: "In internal/ingestion/component/knowledge_compiler/common.KindToVariant, mind_map must remain a supported compatibility alias for the canonical mindmap variant."

♻️ Proposed addition
 	if a != b || a != c {
 		t.Errorf("structure/knowledge_graph/graph should map to the same variant, got %q %q %q", a, b, c)
 	}
+
+	m, err := KindToVariant("mindmap")
+	if err != nil {
+		t.Fatalf("mindmap: %v", err)
+	}
+	ma, err := KindToVariant("mind_map")
+	if err != nil {
+		t.Fatalf("mind_map: %v", err)
+	}
+	if m != ma {
+		t.Errorf("mind_map should alias mindmap, got %q %q", ma, m)
+	}
 }
🤖 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_test.go` around
lines 37 - 53, Add assertions in TestKindToVariant_CanonicalForms that
KindToVariant("mind_map") and KindToVariant("mindmap") both succeed and return
the same variant. Preserve the existing structure/knowledge_graph/graph alias
checks and ensure the test locks mind_map to the canonical mindmap variant.

Source: Learnings

internal/ingestion/knowledge_compile/scheduler.go (1)

277-281: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Log the published variants.

The variants now determine which dataset-level path the consumer takes. The publish log does not record them. Add the field to make mis-routing traceable.

♻️ Proposed change
 	common.Info("knowledge_compile: published backlog entry",
 		zap.String("dataset_id", datasetID),
 		zap.String("tenant_id", tenantID),
 		zap.String("doc_id", docID),
-		zap.String("event_type", eventType))
+		zap.String("event_type", eventType),
+		zap.Strings("variants", variants))
🤖 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/scheduler.go` around lines 277 - 281,
Update the “knowledge_compile: published backlog entry” log in the publishing
flow to include the published variants field, using the existing variants value
and the established structured logging pattern so dataset-level routing can be
traced.
internal/ingestion/task/pipeline_executor.go (1)

333-371: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log skipped compile kinds, and drop the redundant duplicate check.

Two points:

  1. Lines 343 and 353 skip unmappable products silently. If every compiled product is skipped, compiledVariants returns nil. Per the BacklogEntry.Variants contract in internal/ingestion/knowledge_compile/scheduler.go lines 64-66, the consumer then treats the document as legacy and takes the unified path. The routing degradation leaves no trace. Add a warn log with the rejected kind.
  2. Lines 357-360 are redundant. A map assignment is idempotent, so the duplicate check does not change the result.
♻️ Proposed change
 		if kind, ok := ck["compilation_template_kind_kwd"].(string); ok && kind != "" {
 			mapped, err := kccommon.KindToVariant(kind)
 			if err != nil {
-				continue // unknown template kind (O2a): skip, do not mis-route
+				// unknown template kind (O2a): skip, do not mis-route
+				common.Logger.Warn(fmt.Sprintf("knowledge_compile: skipping unknown template kind %q for doc %s", kind, ck["doc_id"]))
+				continue
 			}
 			v = mapped
 		} else {
 			// Fallback on compile_kwd. Structure products stamp the inferred
 			// compile kind verbatim (list/set/hypergraph — structure.InferType),
 			// which is NOT in the KindToVariant whitelist, so map those explicitly
 			// (mirrors knowledge_compile.kwdToVariant) before the whitelist lookup.
-			mapped, err := compileKwdToVariant(asCompiledKwd(ck))
+			kwd := asCompiledKwd(ck)
+			mapped, err := compileKwdToVariant(kwd)
 			if err != nil {
+				common.Logger.Warn(fmt.Sprintf("knowledge_compile: skipping unmappable compile_kwd %q for doc %s", kwd, ck["doc_id"]))
 				continue
 			}
 			v = mapped
 		}
-		if _, dup := seen[string(v)]; dup {
-			continue
-		}
 		seen[string(v)] = struct{}{}
 	}
🤖 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/task/pipeline_executor.go` around lines 333 - 371, Update
compiledVariants to warn whenever a compile kind cannot be mapped, including the
rejected kind and whether it came from compilation_template_kind_kwd or
compile_kwd, before continuing. Use the existing logging facility available to
this package. Remove the dup check around seen and retain direct map assignment,
preserving the sorted unique output behavior.
🤖 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/knowledge_compile/consumer.go`:
- Around line 399-405: Update the fallback path in the product variant
collection loop to skip entries where p.Variant is empty before deduplication
and appending. Preserve the existing reverse-mapped variant handling for
non-empty values so RebuildDataset never republishes an empty variant.
- Around line 1054-1075: Replace the pairwise averaging in averageVectors with
sum accumulation and explicit fold-count tracking so the final bucket vector is
the true batch mean, independent of fold order. Add or reuse helpers to grow and
sum accumulated vectors, then scale each bucket vector by its corresponding
count before constructing the buckets slice; update the misleading
averageVectors comment and all callers accordingly.
- Around line 636-646: Move the G1 `mergeStructureDataset` call and G2
`SaveStructureBuildTime` operation into the existing `c.withWriteLock(ctx, kb,
token, ...)` claim-fenced block in `processBatch`. Preserve their current error
handling and warning behavior while ensuring both writes execute only while the
claim token remains valid.
- Around line 987-1036: Update mergeStructureDataset and/or WriteMergedStructure
to perform a read-modify-write for each stable (name, type) bucket, loading
existing dataset buckets before merging incoming descriptions, source
document/chunk IDs, and vectors. Preserve existing bucket data when incremental
batches omit it, then write the combined buckets without changing the stable IDs
or current sorting behavior.

In `@internal/ingestion/knowledge_compile/reader.go`:
- Around line 266-270: Normalize all restored keyword columns through the
existing asString helper in internal/ingestion/knowledge_compile/reader.go:
update the knowledge_graph_kwd and raptor_kwd handling at lines 266-270, and
compilation_template_kind_kwd handling at lines 307-316. This must support
list-wrapped engine values so meta["kind"] and Product.Kind are populated
correctly.

In `@internal/ingestion/knowledge_compile/scheduler_test.go`:
- Around line 69-76: Update the nil-Variants assertion in the BacklogEntry JSON
test to compare the encoded JSON directly with the expected legacy JSON string,
rather than comparing byte lengths. Keep the existing marshal error handling and
expected field content unchanged.

In `@internal/ingestion/knowledge_compile/writer.go`:
- Around line 296-302: Update the ghost scan in StripMergedSources to paginate
Search results using the existing Limit/Offset pattern, continuing until no
further rows remain. Preserve the current filters and selected fields while
ensuring structure dataset rows beyond the 10,000-row page are also processed.
- Around line 993-1002: Update the VariantStructure deletion in the
variant-clean logic to include the compile_kwd filter using compileKwdStructure
alongside kb_id and scope_kwd, so only structure merged rows are removed. Extend
TestDeleteMergedForVariant_StructureScopesToDataset to assert the compile_kwd
filter as well as scope_kwd.
- Around line 701-717: Remove the duplicate firstStringSlice helper and update
DeleteStructureForDocs to call the existing metaStringSlice helper for
extracting string slices. Preserve the current handling of []string, []any, and
unsupported values through metaStringSlice.
- Around line 341-392: Update SaveStructureBuildTime and LoadStructureBuildTime
to follow the metadata schema: derive a stable record ID from kb and
"structure_build_time", include it in the saved row, and place the timestamp
payload in meta_fields instead of a top-level value. Change loading to retrieve
the record by that same ID, then extract the timestamp from meta_fields while
preserving the empty-result behavior.

In `@internal/ingestion/task/pipeline_executor.go`:
- Around line 373-384: Move the shared list/set/hypergraph-to-VariantStructure
mapping into a kccommon helper, then reuse it from compileKwdToVariant and
kwdToVariant. Keep kwdToVariant’s wiki-specific aliases and direct tree/mindmap
handling local, and preserve errors for unknown kinds. Add focused tests
covering the shared mappings and unknown-kind behavior.

In `@internal/service/nlp/datasetnav_test.go`:
- Around line 425-452: Update the split test around maybeSplitCluster to select
the unsplit cluster by parent_kwd == navRootParent, avoiding clusters already
created by seeding. After splitting, assert the original clusterName row is
deleted, both :A and :B rows exist, and affected child rows now have parent_kwd
pointing to one of the new clusters.

In `@internal/service/nlp/datasetnav.go`:
- Around line 528-582: Update internal/service/nlp/datasetnav.go lines 528-582
in maybeSplitCluster to select type_kwd when searching children and skip
children whose typ is empty before calling UpdateChunks. Strengthen
internal/service/nlp/datasetnav_test.go lines 425-452 to verify every split
child has parent_kwd set to the expected :A or :B cluster and that the original
cluster row is deleted.
- Around line 802-813: Replace the direct []interface{} assertion used to read
doc_ids_kwd in both the shown cluster-removal flow and appendDocToCluster with
firstStringSlice, preserving all existing IDs while excluding the target
document. Initialize ids from the helper’s returned slice before applying the
existing count and update logic so doc_ids_kwd remains consistent with
doc_count_int.
- Around line 684-688: Update appendDocToCluster to call maybeSplitCluster only
when the existing local count exceeds the shared document threshold, avoiding
unnecessary searches for underfull clusters. Promote the threshold from
maybeSplitCluster to the package-level navMaxDocsPerCluster constant, and
likewise promote its fanout limit as navMaxFanout so the function uses the
shared constants.
- Around line 583-606: Update the split flow around the original cluster lookup
and insertion loop: select and retain the row id, depth_int, and doc_ids_kwd;
delete using the returned cluster row id, falling back to navClusterID when it
is empty. Preserve the original depth and distribute the original document IDs
between splitA and splitB, setting each new cluster’s doc_count_int to match its
assigned IDs instead of initializing both clusters empty.
- Around line 758-783: Update findClusterContainingDoc to search all matching
nav clusters instead of truncating at Limit 1000; paginate through results using
navSearch or apply a supported doc_ids_kwd membership filter, while preserving
the existing title return and empty-result behavior.
- Around line 698-713: Update the navSearch filter in the surrounding deletion
flow to include type_kwd restricted to nav_doc alongside doc_id. In the result
loop, collect every distinct non-empty parent_kwd and ensure the subsequent
cleanup processes each affected parent rather than only the first one;
alternatively, use navDocID(tenantID, kbID, docID) if that reliably targets the
single intended row.

---

Nitpick comments:
In `@internal/ingestion/component/knowledge_compiler/common/types_test.go`:
- Around line 37-53: Add assertions in TestKindToVariant_CanonicalForms that
KindToVariant("mind_map") and KindToVariant("mindmap") both succeed and return
the same variant. Preserve the existing structure/knowledge_graph/graph alias
checks and ensure the test locks mind_map to the canonical mindmap variant.

In `@internal/ingestion/knowledge_compile/scheduler.go`:
- Around line 277-281: Update the “knowledge_compile: published backlog entry”
log in the publishing flow to include the published variants field, using the
existing variants value and the established structured logging pattern so
dataset-level routing can be traced.

In `@internal/ingestion/task/pipeline_executor.go`:
- Around line 333-371: Update compiledVariants to warn whenever a compile kind
cannot be mapped, including the rejected kind and whether it came from
compilation_template_kind_kwd or compile_kwd, before continuing. Use the
existing logging facility available to this package. Remove the dup check around
seen and retain direct map assignment, preserving the sorted unique output
behavior.

In `@internal/service/nlp/datasetnav_test.go`:
- Around line 389-411: Strengthen
TestNavService_RemoveDoc_CascadesToEmptyCluster by upserting a second document
that merges into the first document’s existing cluster, then remove the first
document through the nav_doc path. Assert the surviving cluster’s doc_ids_kwd
excludes the removed ID and doc_count_int reflects one document, while retaining
the existing absence assertions for the removed nav_doc and pruned empty
clusters.

In `@internal/service/nlp/datasetnav.go`:
- Line 607: Remove the `_ = total` statement and discard the unused `total`
value directly at the call site where it is returned. Preserve the other
returned values and existing behavior.
- Around line 302-317: Replace the duplicated changed-summary cleanup around
deleteNavDoc, removeDocFromCluster, and cleanupEmptyCluster with a call to
RemoveDoc using the same tenant, knowledge-base, and document identifiers.
Ensure this path also uses RemoveDoc’s findClusterContainingDoc fallback when no
nav_doc row exists, and preserve the existing error propagation.
- Around line 623-633: Normalize the LLM result in NavService.llmCreateSummary
by trimming whitespace, rejecting empty, oversized, or colon-containing names,
and falling back to the deterministic cluster name when invalid. In the cluster
creation flow used by appendDocToCluster, check whether the normalized title_kwd
already exists before inserting and avoid creating a duplicate key, preserving
consistent lookups and split suffixes.
- Around line 611-621: Remove the unused NavService.llmMergeDescription helper,
or integrate it into maybeSplitCluster when constructing descriptions for split
clusters. If integrating, replace the existing description construction with
llmMergeDescription while preserving the current fallback behavior.
🪄 Autofix

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: 36e6f562-c7fd-436a-b905-cbd2f9112f92

📥 Commits

Reviewing files that changed from the base of the PR and between 9cece9c and 8c91544.

📒 Files selected for processing (18)
  • internal/ingestion/component/knowledge_compiler/common/types_test.go
  • internal/ingestion/component/knowledge_compiler/component.go
  • internal/ingestion/component/knowledge_compiler/component_test.go
  • internal/ingestion/knowledge_compile/consumer.go
  • internal/ingestion/knowledge_compile/event.go
  • internal/ingestion/knowledge_compile/fake_engine_test.go
  • internal/ingestion/knowledge_compile/nav_dispatch_test.go
  • internal/ingestion/knowledge_compile/reader.go
  • internal/ingestion/knowledge_compile/rebuild_variants_test.go
  • internal/ingestion/knowledge_compile/scheduler.go
  • internal/ingestion/knowledge_compile/scheduler_test.go
  • internal/ingestion/knowledge_compile/structure_merge_test.go
  • internal/ingestion/knowledge_compile/writer.go
  • internal/ingestion/knowledge_compile/writer_test.go
  • internal/ingestion/task/pipeline_executor.go
  • internal/service/nav/nav.go
  • internal/service/nlp/datasetnav.go
  • internal/service/nlp/datasetnav_test.go
💤 Files with no reviewable changes (1)
  • internal/ingestion/component/knowledge_compiler/component_test.go

Comment thread internal/service/nlp/datasetnav.go Resolved
Comment thread internal/service/nlp/datasetnav.go Resolved
Comment thread internal/service/nlp/datasetnav.go Resolved
Comment thread internal/service/nlp/datasetnav.go Resolved
Comment thread internal/service/nlp/datasetnav.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/ingestion/knowledge_compile/consumer.go (1)

429-437: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove review-history references from comments.

Keep comments focused on current behavior.

  • internal/ingestion/knowledge_compile/consumer.go#L429-L437: remove “review issue 2” while retaining the wiki-page filtering contract.
  • internal/ingestion/knowledge_compile/consumer.go#L1012-L1014: remove “review issue 3” while retaining the relation-bucketing contract.
  • internal/ingestion/knowledge_compile/structure_merge_test.go#L94-L96: describe the tested relation-bucket behavior without referencing review history.

As per coding guidelines, remove stale documentation and keep Go comments aligned with the current runtime path.

🤖 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/consumer.go` around lines 429 - 437,
Remove the review-history references while preserving the current behavior
documentation: in internal/ingestion/knowledge_compile/consumer.go lines 429-437
remove “review issue 2” from the wiki-page filtering comment; in consumer.go
lines 1012-1014 remove “review issue 3” while retaining the relation-bucketing
contract; and in internal/ingestion/knowledge_compile/structure_merge_test.go
lines 94-96 rewrite the comment to describe the tested relation-bucket behavior
without review-history references.

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/knowledge_compile/consumer.go`:
- Around line 1026-1031: Update the relation-bucket creation logic around the
relByKey map to require both from and to endpoints to be non-empty, including
when kind is "relation"; skip incomplete relations instead of creating or
merging buckets with missing endpoints. Add a focused test covering a relation
with one empty endpoint and verify no relation bucket or dataset row is
produced.

---

Nitpick comments:
In `@internal/ingestion/knowledge_compile/consumer.go`:
- Around line 429-437: Remove the review-history references while preserving the
current behavior documentation: in
internal/ingestion/knowledge_compile/consumer.go lines 429-437 remove “review
issue 2” from the wiki-page filtering comment; in consumer.go lines 1012-1014
remove “review issue 3” while retaining the relation-bucketing contract; and in
internal/ingestion/knowledge_compile/structure_merge_test.go lines 94-96 rewrite
the comment to describe the tested relation-bucket behavior without
review-history references.
🪄 Autofix

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: f07a55de-c382-47a1-977d-db897e400e59

📥 Commits

Reviewing files that changed from the base of the PR and between 8c91544 and f2d8a94.

📒 Files selected for processing (6)
  • internal/ingestion/knowledge_compile/consumer.go
  • internal/ingestion/knowledge_compile/rebuild_variants_test.go
  • internal/ingestion/knowledge_compile/structure_merge_test.go
  • internal/ingestion/knowledge_compile/writer.go
  • internal/service/nlp/datasetnav.go
  • internal/service/nlp/datasetnav_test.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/service/nlp/datasetnav_test.go
  • internal/ingestion/knowledge_compile/rebuild_variants_test.go
  • internal/service/nlp/datasetnav.go
  • internal/ingestion/knowledge_compile/writer.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/ingestion/knowledge_compile/writer.go`:
- Around line 234-256: Update buildBoolQueryFromCondition to recognize []string
values in the id condition and emit the corresponding ID clause. In the
read-modify-write load around eng.Search, split ids into batches bounded by the
supported result window, execute one search per batch, and accumulate all
returned chunks into existing before overwriting sources. Preserve error
propagation for each batch.
🪄 Autofix

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: 694637c1-5474-478a-8f3a-218c94461844

📥 Commits

Reviewing files that changed from the base of the PR and between 79f8068 and d07ee9c.

📒 Files selected for processing (9)
  • internal/ingestion/knowledge_compile/consumer.go
  • internal/ingestion/knowledge_compile/reader.go
  • internal/ingestion/knowledge_compile/scheduler_test.go
  • internal/ingestion/knowledge_compile/structure_merge_test.go
  • internal/ingestion/knowledge_compile/writer.go
  • internal/ingestion/knowledge_compile/writer_test.go
  • internal/ingestion/task/pipeline_executor.go
  • internal/service/nlp/datasetnav.go
  • internal/service/nlp/datasetnav_test.go
🚧 Files skipped from review as they are similar to previous changes (7)
  • internal/ingestion/knowledge_compile/structure_merge_test.go
  • internal/ingestion/task/pipeline_executor.go
  • internal/service/nlp/datasetnav_test.go
  • internal/ingestion/knowledge_compile/reader.go
  • internal/ingestion/knowledge_compile/writer_test.go
  • internal/ingestion/knowledge_compile/consumer.go
  • internal/service/nlp/datasetnav.go

Comment on lines +234 to +256
if len(ids) > 0 {
res, err := eng.Search(ctx, &types.SearchRequest{
IndexNames: []string{baseName},
KbIDs: []string{kb},
SelectFields: []string{"id", "source_doc_ids", "source_chunk_ids"},
Filter: map[string]interface{}{"kb_id": kb, "id": ids},
Limit: len(ids),
})
if err != nil {
return fmt.Errorf("structure merge read-modify-write load: %w", err)
}
for _, c := range res.Chunks {
id, _ := c["id"].(string)
if id == "" {
continue
}
existing[id] = StructureBucket{
SourceDocIDs: firstStringSlice(c["source_doc_ids"]),
SourceChunkIDs: firstStringSlice(c["source_chunk_ids"]),
}
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Inspect engine Search limit handling and result-window caps.
set -uo pipefail

rg -n -C6 'max_result_window|MaxResultWindow|req\.Limit|Limit\b' internal/engine --glob '*.go' -g '!**/*_test.go' | head -200

# Confirm how each backend translates SearchRequest.Limit and an "id" IN filter.
for f in $(fd -t f 'search.*\.go|chunk.*\.go' internal/engine); do
  echo "### $f"
  rg -n -C4 'Limit|Offset|"id"' "$f" | head -60
done

Repository: infiniflow/ragflow

Length of output: 31398


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '### Elasticsearch search request construction'
sed -n '970,1185p' internal/engine/elasticsearch/chunk.go

echo '### Elasticsearch filter handling for typed ID slices'
rg -n -C8 'func .*Filter|build.*Filter|case \[\]string|terms|id.*\[\]' internal/engine/elasticsearch --glob '*.go' -g '!**/*_test.go'

echo '### Search call sites and backend interfaces'
rg -n -C5 'func \(.*\) Search|Search\(ctx|type Engine interface|type SearchResult' internal/engine --glob '*.go' -g '!**/*_test.go'

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '### Search condition builder'
sed -n '1640,1810p' internal/engine/elasticsearch/chunk.go

echo '### WriteMergedStructure and related engine calls'
sed -n '180,275p' internal/ingestion/knowledge_compile/writer.go

echo '### Search pagination response path'
sed -n '1180,1325p' internal/engine/elasticsearch/chunk.go
rg -n -C5 'buildBoolQueryFromCondition|searchAfterCursor|MAX_RESULT_WINDOW' internal/engine/elasticsearch/chunk.go internal/engine/common --glob '*.go'

Repository: infiniflow/ragflow

Length of output: 20869


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path

p = Path("internal/engine/elasticsearch/chunk.go")
src = p.read_text()

start = src.index('\t\tif k == "id" {')
end = src.index('\n\t\tif v == nil || v == "" {', start)
block = src[start:end]

print("### id-filter branch")
print(block)

print("typed []string handled:", "[]string" in block)
print("branch exits before generic handling:", "\n\t\t\tcontinue" in block)
print("Search uses request limit as size:", 'queryBody["size"] = limit' in src)
print("deep-pagination fallback requires explicit sort:",
      'hasExplicitSort := req.OrderBy != nil && len(req.OrderBy.Fields) > 0' in src)
PY

Repository: infiniflow/ragflow

Length of output: 1210


Fix the ID filter and page the read-modify-write load.

ids is a []string, but Elasticsearch’s buildBoolQueryFromCondition does not handle []string in its id branch and exits without adding an ID clause. The search can therefore load unrelated rows. Also, Limit: len(ids) can exceed index.max_result_window; Elasticsearch can reject the request, while Search continues with no loaded rows. Add []string support to the ID filter and load IDs in bounded batches before overwriting accumulated sources.

🤖 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/writer.go` around lines 234 - 256,
Update buildBoolQueryFromCondition to recognize []string values in the id
condition and emit the corresponding ID clause. In the read-modify-write load
around eng.Search, split ids into batches bounded by the supported result
window, execute one search per batch, and accumulate all returned chunks into
existing before overwriting sources. Preserve error propagation for each batch.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

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

641-648: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Retry when the navigation service is unavailable.

If nav.GetNavService() returns nil, this code logs and continues. If later writes succeed, processClaim acknowledges the completion while this document never reaches the navigation tree. Return a retryable error instead. If navigation is intentionally disabled, prevent navigation-producing variants from entering this consumer.

🤖 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/consumer.go` around lines 641 - 648, The
navigation-unavailable branch in processClaim’s navIn handling must return a
retryable error instead of warning and continuing, so the claim is not
acknowledged without the navigation update; preserve the existing
upsertNavLocked error propagation, and ensure intentionally disabled navigation
prevents navigation-producing variants from reaching this consumer.
🤖 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/knowledge_compile/consumer.go`:
- Around line 625-631: Defer wiki deduper creation in the consumer flow until
after filterWikiPageCandidates identifies at least one candidate. Ensure
tree-only and structure-only batches bypass c.factory(tenant) and common.Fatal,
while wiki batches still initialize and use the deduper before navigation
dispatch.

---

Outside diff comments:
In `@internal/ingestion/knowledge_compile/consumer.go`:
- Around line 641-648: The navigation-unavailable branch in processClaim’s navIn
handling must return a retryable error instead of warning and continuing, so the
claim is not acknowledged without the navigation update; preserve the existing
upsertNavLocked error propagation, and ensure intentionally disabled navigation
prevents navigation-producing variants from reaching this consumer.
🪄 Autofix

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: d128454f-5ddb-47df-ba8a-05375704c4c2

📥 Commits

Reviewing files that changed from the base of the PR and between d07ee9c and 066a7ff.

📒 Files selected for processing (4)
  • internal/ingestion/knowledge_compile/consumer.go
  • internal/ingestion/knowledge_compile/nav_dispatch_test.go
  • internal/service/nlp/datasetnav.go
  • internal/service/nlp/datasetnav_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/service/nlp/datasetnav_test.go
  • internal/ingestion/knowledge_compile/nav_dispatch_test.go
  • internal/service/nlp/datasetnav.go

Comment on lines +625 to +631
// A0-4: the event's Variants are the authoritative dispatch signal — route
// ONLY the products whose variant the compiler actually produced for this
// doc. A doc re-compiled under a new template may still hold stale
// doc-level rows of an earlier variant in storage; without this gate those
// would leak into the nav/structure paths despite the event asking only
// for, say, wiki. Legacy events with empty Variants keep all products.
incoming = append(incoming, productsForVariants(docProducts, e.Variants)...)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Defer deduper initialization for non-wiki batches.

A tree-only or structure-only completion reaches c.factory(tenant) before Line 625 filters products and before Line 640 dispatches navigation. If the wiki deduper factory fails, common.Fatal runs even though this batch has no wiki candidate and does not require deduplication. Initialize the deduper only after filterWikiPageCandidates returns at least one candidate.

🤖 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/consumer.go` around lines 625 - 631,
Defer wiki deduper creation in the consumer flow until after
filterWikiPageCandidates identifies at least one candidate. Ensure tree-only and
structure-only batches bypass c.factory(tenant) and common.Fatal, while wiki
batches still initialize and use the deduper before navigation dispatch.

Add compile-type variants to backlog events; route tree/structure/wiki
to per-variant dataset-level paths; move dataset-nav to consumer; add
structure merge, per-variant clean, scope_kwd, and rebuild variant
recovery. Fix reader kind reconstruction for structure/tree.
@yuzhichang yuzhichang added the ci Continue Integration label Aug 12, 2026
@yuzhichang
yuzhichang merged commit c677e9a into infiniflow:main Aug 12, 2026
6 checks passed
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