Skip to content

Go port: doc-level metadata extraction and knowledge compiler - #17536

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

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

Conversation

@yuzhichang

Copy link
Copy Markdown
Member

Ports doc-level auto-metadata extraction to Go and adds the knowledge_compiler component with scheduler/routing. Fixes Extractor metadata injection type assertion and enable_metadata default-on.

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 29, 2026
@coderabbitai

coderabbitai Bot commented Jul 29, 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

This change adds a Go KnowledgeCompiler with five compilation variants, structured metadata extraction, dataset-level scheduling and merging, pipeline registration, NATS integration, and ingestion lifecycle wiring.

Changes

Metadata extraction and ingestion integration

Layer / File(s) Summary
Metadata contracts and extraction
internal/common/*, internal/ingestion/component/extractor.go, internal/ingestion/component/schema/extractor.go
Adds metadata schemas, extractor configuration, bounded concurrent extraction, Redis caching, JSON cleanup, and delimiter normalization.
Metadata persistence and pipeline injection
internal/ingestion/task/pipeline_executor.go, internal/ingestion/service/doc_state.go, internal/utility/metadata.go, internal/ingestion/pipeline/template/*
Injects dataset metadata settings and applies list-union, scalar-preservation, and normalized persistence rules.

KnowledgeCompiler implementation

Layer / File(s) Summary
Shared compiler contracts and component boundary
internal/ingestion/component/knowledge_compiler/common/*, internal/ingestion/component/knowledge_compiler/component.go
Adds typed inputs and outputs, dependency resolvers, batching, JSON parsing, memory deduplication, guardrails, product conversion, and runtime registration.
Structure compilation
internal/ingestion/component/knowledge_compiler/structure/*
Adds schema-driven extraction, entity/relation merging, alias rewriting, graph rebuilding, chain correction, timeline cleanup, and graph output generation.
Wiki, RAPTOR, mindmap, and dataset navigation
internal/ingestion/component/knowledge_compiler/{wiki,raptor,mindmap,datasetnav}/*
Adds multi-stage wiki generation, clustering-based RAPTOR trees, Markdown mind maps, and dataset navigation trees.
Compiler validation and golden coverage
internal/ingestion/component/knowledge_compiler/*_test.go, golden/*
Adds unit, end-to-end, regression, and golden tests for compiler behavior and output structure.

Dataset-level compilation runtime

Layer / File(s) Summary
Events, scheduling, and transport
internal/engine/*, internal/entity/*, internal/dao/*, internal/ingestion/knowledge_compile/*
Adds compile events, NATS streams and leases, durable scheduling, product reading/writing, deduplication, and consumer processing.
Ingestion lifecycle and production adapters
internal/ingestion/service/ingestion_service.go, internal/ingestion/task/knowledge_compiler_wiring.go, internal/service/document/document_crud.go
Starts compile workers, wires model/search/template dependencies, publishes completion and deletion events, and joins workers during shutdown.

Pipeline and startup integration

Layer / File(s) Summary
Pipeline template and registration
internal/ingestion/pipeline/template/ingestion_pipeline_knowledge_compiler.json, internal/ingestion/pipeline/pipeline_knowledge_compiler_test.go
Adds and validates the KnowledgeCompiler pipeline template and runtime component registration.
Startup and dependency metadata
cmd/ragflow_server.go, go.mod, ragflow_deps/download_go_deps.py
Passes configured models into ingestor startup, starts ingestor synchronously, and declares added dependencies.

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

Possibly related PRs

Suggested labels: 🧪 test

Suggested reviewers: qinling0210, jinhai-cn

Poem

A rabbit sees new knowledge grow,
As graphs and pages start to flow.
Metadata hops through queues bright,
While tests guard each compile flight.
With carrots packed and models right,
The burrow ships this change tonight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 63.75% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately captures the main changes: Go porting for doc-level metadata extraction and the new knowledge compiler.
Description check ✅ Passed The description briefly states the main purpose and key areas changed, which is sufficient for the template's single Summary section.
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: 5

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

Caution

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

⚠️ Outside diff range comments (2)
internal/ingestion/component/schema/extractor.go (1)

85-131: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove port-history references from exported-field docs.

Describe the Go contract directly; references to Python internals and port-research documents will become stale. As per coding guidelines, keep Go 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/schema/extractor.go` around lines 85 - 131,
Remove Python-internal and port-research references from the exported field
comments for FieldName, LLMID, EnableMetadata, and Metadata. Rewrite them to
describe the current Go contract and runtime behavior directly, preserving the
existing field semantics without changing code or JSON tags.

Source: Coding guidelines

internal/service/document/document_crud.go (1)

352-368: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Add a timeout to the context used for the new external PublishDeleted call.

deleteDocEngineData builds ctx := context.Background() with no deadline, and this now backs two external calls: the existing DeleteChunks and the new knowledge_compile.PublishDeleted. Without a bound, a stalled downstream (queue/DB) hangs this call indefinitely.

🔧 Proposed fix
-	ctx := context.Background()
+	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+	defer cancel()
🤖 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/document/document_crud.go` around lines 352 - 368, Update
deleteDocEngineData to create a bounded context with a timeout before invoking
the external DeleteChunks and knowledge_compile.PublishDeleted calls. Ensure the
timeout context is canceled appropriately while preserving the existing
best-effort warning behavior for both operations.
🟠 Major comments (20)
internal/ingestion/component/knowledge_compiler/component.go-530-535 (1)

530-535: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

chunks is only read as []any; a []map[string]any upstream value is silently dropped.

Both mergeChunks (Line 531) and buildInputs (Line 564) fail closed to an empty list when the upstream component emits a concretely-typed slice, so the compiler would silently compile nothing and drop the input chunks from the output. Worth confirming the TokenChunker's runtime output type.

#!/bin/bash
# What Go type does the chunker put under the "chunks" output key?
fd -e go . internal/ingestion/component --exec rg -nP -C4 '"chunks":\s*' {} \;
🤖 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/component.go` around lines
530 - 535, Update mergeChunks and buildInputs to accept upstream chunks
represented as []map[string]any as well as []any, normalizing both forms into
the existing processing path. Preserve all input chunks and compiled chunks in
the merged output, and verify the TokenChunker’s emitted type when choosing the
conversion.
internal/ingestion/component/knowledge_compiler/component.go-146-169 (1)

146-169: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Template-id stamping and chunk conversion are skipped for products already flushed to the sink.

Variants stream products through common.NewProductSink(...) and out.Products only holds what remains in the buffer (see structure.go Lines 131-142; TestKnowledgeCompiler_GuardrailFlushStreams asserts the flushed units never appear in out.Products). So under OnExceed: ExceedFlush, flushed rows never get compilation_template_ids stamped and never go through productsToChunkDocs. That is exactly the "rows missing compilation_template_ids" data-loss path the comment at Lines 112-115 says must fail loudly.

Either stamp templateIDs into the variant inputs/deps before Run (so the sink sees fully-populated products), or have the sink receive already-converted chunk docs.

🤖 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/component.go` around lines
146 - 169, Ensure products flushed through common.NewProductSink receive
compilation_template_ids and chunk conversion before leaving the variant flow.
Update the setup before Run to stamp templateIDs onto variant inputs/deps so
every product seen by the sink is fully populated, or pass pre-converted chunk
docs to the sink; do not rely on out.Products after Run, since it excludes
flushed products.
internal/ingestion/component/knowledge_compiler/component_test.go-1200-1227 (1)

1200-1227: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

This assertion never runs — the test passes vacuously.

No parser_config is supplied, so InferType returns list and structure.Run stamps compile_kwd = "list" (see structure/structure.go Line 120, structure/prompt.go Line 62). The continue at Line 1212 therefore skips every chunk and the template-id check is never executed. Other tests in this file (e.g. Lines 449, 494) correctly match "hypergraph".

💚 Filter on the actual discriminator and assert at least one row was checked
+	checked := 0
 	for _, r := range out["chunks"].([]any) {
 		cm := r.(map[string]any)
-		if cm["compile_kwd"] != "structure" {
+		if cm["compile_kwd"] != "list" {
 			continue
 		}
+		checked++
 		var got []string
@@
 		if len(got) != 2 || !want[got[0]] || !want[got[1]] {
 			t.Fatalf("compiled chunk %v: compilation_template_ids = %v, want %v (group ids must resolve to template ids)", cm["id"], got, want)
 		}
 	}
+	if checked == 0 {
+		t.Fatalf("no compiled chunks were inspected; assertion was vacuous")
+	}
🤖 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/component_test.go` around
lines 1200 - 1227, Update the test around the chunk discriminator to match the
actual compile_kwd value produced by Invoke for this input, consistent with the
existing hypergraph tests, instead of filtering for "structure". Track whether a
matching chunk was inspected and fail if none was found, while preserving the
compilation_template_ids assertions.
internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav.go-458-479 (1)

458-479: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Split leaves the parent with no children, orphaning the new sub-clusters. maybeSplit sets Parent: clusterName on each group but never appends the group to t.children[clusterName], then deletes that entry — so findBestCluster can no longer descend into the split subtree, and the test encodes this as expected behavior.

  • internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav.go#L458-L479: collect the new group names into a navChild slice and assign it to t.children[clusterName] instead of deleting the key.
  • internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav_test.go#L173-L180: replace the "no direct children" assertion with a check that t.children["P"] contains exactly the two new group clusters.
🤖 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/datasetnav/datasetnav.go`
around lines 458 - 479, Update maybeSplit in
internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav.go lines
458-479 to collect each newly created group name as a navChild and assign the
resulting slice to t.children[clusterName] instead of deleting the parent entry.
Update the assertions in
internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav_test.go
lines 173-180 to verify that t.children["P"] contains exactly the two new group
clusters.
internal/ingestion/component/knowledge_compiler/raptor/clustering.go-154-201 (1)

154-201: 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

AHC is O(n³) time and O(n²) memory over all chunks.

wardAHC builds a full n × n distance matrix and then rescans every active pair on each of the n-1 merges — and recluster repeats the whole greedy loop a second time. For a document with a few thousand chunks this is ~10⁹ centroid distance computations on the ingestion path. Consider caching the best-pair heap (nearest-neighbour chain) or deriving the cut directly from the first pass instead of re-running merges.

🤖 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/clustering.go` around
lines 154 - 201, Optimize wardAHC to avoid cubic pair rescanning and the
duplicate merge pass: maintain cached best-pair candidates using a heap or
nearest-neighbor chain while clusters merge, and record the merge history needed
by chooseClusterCount so recluster does not repeat the greedy loop. Preserve
Ward linkage, heights, and final cluster-count behavior while reducing
active-pair work and avoiding unnecessary full distance-matrix allocation where
feasible.
internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav.go-179-187 (1)

179-187: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

nav_doc product IDs are not tenant/dataset scoped and collide on the positional fallback.

StableRowID("dataset_nav", "doc", d.ChunkID) omits tenantID/datasetID, unlike the cluster rows on Line 156. Combined with chunkTexts's synthetic chunk-%d ids (Line 720), any two documents/datasets whose chunks lack ids produce identical product ids (dataset_nav|doc|chunk-0, …), so writes overwrite each other across tenants.

🐛 Proposed fix
-			ID:       common.StableRowID("dataset_nav", "doc", d.ChunkID),
+			ID:       common.StableRowID("dataset_nav", tenantID, datasetID, "doc", d.ChunkID),
🤖 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/datasetnav/datasetnav.go`
around lines 179 - 187, Scope nav_doc product IDs by tenant and dataset to
prevent collisions when chunk IDs use positional fallbacks. Update the
StableRowID call in the tree.docs loop, using the same tenantID/datasetID
scoping approach as the cluster product IDs while preserving the existing doc
and chunk identity components.
internal/ingestion/component/knowledge_compiler/raptor/raptor.go-153-163 (1)

153-163: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

embedding[0] is indexed without checking the returned slice length.

An embedder that returns an empty batch (provider hiccup, filtered input) panics here, and again at Line 222-230 where e2 == nil is checked but len(embedding) is not.

🛡️ Proposed fix
 		embedding, err := deps.Embed.Encode(ctx, []string{summary})
 		if err != nil {
 			return err
 		}
+		if len(embedding) == 0 {
+			return fmt.Errorf("raptor: embedder returned no vector for L%d summary", task.level)
+		}
🤖 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 153 - 163, Validate the embedding slice length before indexing it in the
node ingestion flow around Encode and sink.Add, returning an appropriate error
when no embedding is produced. Apply the same length check to the second
embedding path near the existing e2 == nil handling before accessing
embedding[0], preserving normal behavior for non-empty results.
internal/ingestion/component/knowledge_compiler/common/types.go-163-216 (1)

163-216: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Two overlapping flush entry points; converge on one.

FlushIfNeeded and EnforceGuardrails implement the same breach→emit→reset logic, with EnforceGuardrails additionally handling the error policy. Keeping both invites variants diverging on which one they call (the doc comment already notes structure was the only variant honouring flush). Fold FlushIfNeeded into EnforceGuardrails and delete it, unless a non-test caller needs the boolean return.

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

#!/bin/bash
rg -nP -C3 '\bFlushIfNeeded\(' internal
🤖 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
163 - 216, Remove Outputs.FlushIfNeeded and consolidate all flush handling
through Outputs.EnforceGuardrails, unless the repository search confirms a
non-test caller depends on its boolean return. Update any remaining callers to
invoke EnforceGuardrails and handle its error result, preserving the existing
emit, buffer reset, and capacity-policy behavior.

Source: Coding guidelines

internal/ingestion/component/extractor.go-900-919 (1)

900-919: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

The mu *sync.Mutex parameter on the keyword/question helpers is now dead.

Both call sites pass nil since each job owns its chunk map, so every if mu != nil branch in runAutoKeywords/runAutoQuestions is unreachable locking scaffolding left over from the removed intra-invoke concurrency. Drop the parameter and the guards (check tests for other callers).

As per coding guidelines: "Treat legacy code as a liability rather than a compatibility target; prefer deletion over shims" and "Reduce public surface area when a helper can be private or internal".

#!/bin/bash
rg -nP -C2 'runAutoKeywords\(|runAutoQuestions\(' internal/ingestion/component
🤖 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/extractor.go` around lines 900 - 919, Remove the
unused mu *sync.Mutex parameter from runAutoKeywords and runAutoQuestions,
update all callers and tests accordingly, and delete their mu != nil locking
branches. Keep each helper’s existing extraction behavior unchanged while
eliminating the obsolete synchronization scaffolding.

Source: Coding guidelines

internal/ingestion/component/knowledge_compiler/common/types.go-251-267 (1)

251-267: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Reusing the flushed slice aliases memory the sink still holds.

sink.Emit(s.ctx, s.products) hands the backing array to the sink, then s.products = s.products[:0] reuses it: any sink that retains the slice (rather than copying, as the unit test happens to do) sees its elements silently overwritten by subsequent Add calls. Either document a copy-required contract on ChunkedSink.Emit or hand off ownership by setting s.products = nil.

The same pattern exists in Outputs.FlushIfNeeded (Line 180) and Outputs.EnforceGuardrails (Line 211).

🐛 Proposed fix
 			if err := s.sink.Emit(s.ctx, s.products); err != nil {
 				return err
 			}
 			s.flushed = true
-			s.products = s.products[:0]
+			s.products = nil
 			s.bytes = 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/common/types.go` around lines
251 - 267, Prevent emitted slices from sharing reusable backing arrays with
subsequent writes: update ProductSink.Add, Outputs.FlushIfNeeded, and
Outputs.EnforceGuardrails to relinquish the flushed products slice by setting it
to nil after a successful sink.Emit instead of reslicing it to zero. Preserve
the existing flush bookkeeping and byte counters.
internal/ingestion/component/knowledge_compiler/common/id.go-10-29 (1)

10-29: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Use a collision-resistant digest for persistent row IDs.

A 64-bit xxhash digest is not collision-resistant; a collision can make distinct products share an ID and be overwritten by Upsert/merge paths. Use SHA-256 or another compatibility-approved digest for both ID helpers.

#!/bin/bash
set -euo pipefail

rg -nP '\b(StableRowID|ContentHash)\s*\(' internal/ingestion/component/knowledge_compiler
fd -a 'infinity_mapping.json' . -x rg -n 'knowledge|id|row_id' {}
🤖 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/id.go` around lines 10
- 29, Replace the xxhash-based implementation in StableRowID and ContentHash
with a compatibility-approved collision-resistant digest such as SHA-256, while
preserving StableRowID’s NUL-separated input ordering, ContentHash’s
trimmed-text behavior, and each helper’s existing string-returning contract.
internal/ingestion/component/knowledge_compiler/common/memstore.go-61-112 (1)

61-112: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Revalidate the dedup candidate after the unlocked callback.

bestIdx becomes stale while cb runs. A concurrent Delete can reindex or shrink items, so KeepMerge can overwrite a different product or panic. Re-resolve a stable candidate identity/version under the write lock and retry selection if it changed.

🤖 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/memstore.go` around
lines 61 - 112, The KeepMerge path in DedupeAdd uses stale bestIdx after the
unlocked callback. Revalidate the selected candidate under the write lock using
a stable identity/version, detect deletion or replacement/reindexing, and retry
candidate selection before merging; never overwrite a different item or index
out of bounds. Preserve KeepDrop and no-candidate KeepMerge behavior.
internal/ingestion/component/schema/extractor.go-145-146 (1)

145-146: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Metadata extraction is disabled across every new default path.

The schema default and all supplied templates set enable_metadata to 0, contradicting the PR objective to enable metadata by default.

  • internal/ingestion/component/schema/extractor.go#L145-L146: default EnableMetadata to enabled.
  • internal/ingestion/pipeline/template/ingestion_pipeline_audio.json#L138-L140: set enable_metadata to enabled or omit it to inherit the schema default.
  • internal/ingestion/pipeline/template/ingestion_pipeline_book.json#L199-L201: set enable_metadata to enabled or omit it to inherit the schema default.
  • internal/ingestion/pipeline/template/ingestion_pipeline_email.json#L143-L145: set enable_metadata to enabled or omit it to inherit the schema default.
  • internal/ingestion/pipeline/template/ingestion_pipeline_general.json#L227-L229: set enable_metadata to enabled or omit it to inherit the schema default.
🤖 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/schema/extractor.go` around lines 145 - 146,
Enable metadata by default in the extractor schema’s default configuration by
setting EnableMetadata accordingly. Update enable_metadata in
internal/ingestion/pipeline/template/ingestion_pipeline_audio.json:138-140,
internal/ingestion/pipeline/template/ingestion_pipeline_book.json:199-201,
internal/ingestion/pipeline/template/ingestion_pipeline_email.json:143-145, and
internal/ingestion/pipeline/template/ingestion_pipeline_general.json:227-229 to
enabled, or remove those fields so they inherit the schema default.
internal/ingestion/pipeline/template/ingestion_pipeline_one.json-192-194 (1)

192-194: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Enable metadata in every shipped pipeline template.

Each template explicitly sets enable_metadata to 0, overriding the PR’s intended enabled default and disabling document-level metadata extraction.

  • internal/ingestion/pipeline/template/ingestion_pipeline_one.json#L192-L194: set enable_metadata to the enabled schema value.
  • internal/ingestion/pipeline/template/ingestion_pipeline_laws.json#L212-L214: set enable_metadata to the enabled schema value.
  • internal/ingestion/pipeline/template/ingestion_pipeline_manual.json#L179-L181: set enable_metadata to the enabled schema value.
  • internal/ingestion/pipeline/template/ingestion_pipeline_paper.json#L160-L162: set enable_metadata to the enabled schema value.
  • internal/ingestion/pipeline/template/ingestion_pipeline_picture.json#L152-L154: set enable_metadata to the enabled schema value.
  • internal/ingestion/pipeline/template/ingestion_pipeline_presentation.json#L138-L140: set enable_metadata to the enabled schema value.
  • internal/ingestion/pipeline/template/ingestion_pipeline_resume.json#L52-L54: enable the dedicated metadata extractor.
🤖 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/pipeline/template/ingestion_pipeline_one.json` around
lines 192 - 194, Enable metadata extraction in every shipped pipeline template
by replacing the disabled enable_metadata value with the enabled schema value in
internal/ingestion/pipeline/template/ingestion_pipeline_one.json (192-194),
ingestion_pipeline_laws.json (212-214), ingestion_pipeline_manual.json
(179-181), ingestion_pipeline_paper.json (160-162),
ingestion_pipeline_picture.json (152-154), and
ingestion_pipeline_presentation.json (138-140); in
ingestion_pipeline_resume.json (52-54), enable the dedicated metadata extractor.
internal/ingestion/component/knowledge_compiler/golden_test.go-27-34 (1)

27-34: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

The workaround comment describes an unbounded-recursion hazard in the PSI builder.

If all-non-negative embeddings collapse the corpus into one cluster and cause "unbounded recursion in buildTree", that's a stack-overflow risk in production code, not just a test-fixture problem — non-centered embeddings from real providers are common. Add a depth/no-progress guard in the raptor builder rather than only avoiding the input shape in tests.

#!/bin/bash
rg -nP -C6 'func .*buildTree' internal/ingestion/component/knowledge_compiler/raptor
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/ingestion/component/knowledge_compiler/golden_test.go` around lines
27 - 34, Add a depth or no-progress termination guard to the Raptor builder’s
buildTree recursion so a cluster that fails to split cannot recurse
indefinitely. Ensure the guard returns a valid leaf or otherwise preserves the
builder’s expected output when progress stops, while keeping normal recursive
clustering unchanged; update the production raptor implementation rather than
relying on signedEmbedder in golden tests.
internal/engine/nats/knowledgecompile.go-70-76 (1)

70-76: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Publishing the notify subject through JetStream will fail; also missing the nil-JetStream guard.

knowledgeCompileNotifySubject (notify.kc.workers) is deliberately outside the knowledge.compile.events.> stream (Line 228-232), but PublishKnowledgeCompile uses n.jetStream.Publish, which errors ("no stream matches subject") for unstreamed subjects — while the MessageQueue doc in internal/engine/engine.go (Line 121-123) states the wake-up is pushed by this method. Either route the notify publish through core NATS (n.nc.Publish) or add a dedicated method. Unlike the other methods here, this one also dereferences n.jetStream without a nil check.

#!/bin/bash
rg -nP -C3 'PublishKnowledgeCompile|notify\.kc\.workers' --type=go
🤖 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/engine/nats/knowledgecompile.go` around lines 70 - 76, The
PublishKnowledgeCompile method currently uses JetStream for subjects outside the
configured stream and lacks a nil-client guard. Update PublishKnowledgeCompile
to publish through core NATS via n.nc.Publish so knowledgeCompileNotifySubject
works, and safely handle a nil NATS client before dereferencing it; preserve the
existing timeout and error-return behavior.
internal/engine/nats/knowledgecompile.go-238-264 (1)

238-264: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

close(ch) can race with an in-flight subscription callback → send on closed channel panic.

sub.Unsubscribe() does not wait for a callback already executing on the NATS dispatcher goroutine, so the handler's ch <- p.DatasetID can run after close(ch). Prefer not closing (let GC reclaim) or gate the send with a done channel and a sync.Once-guarded close after draining.

🔒 Guard the send
 	ch := make(chan string, 256)
+	done := make(chan struct{})
 	sub, err := n.nc.Subscribe(knowledgeCompileNotifySubject, func(m *nats.Msg) {
 		var p struct {
 			DatasetID string `json:"dataset_id"`
 		}
 		if err := json.Unmarshal(m.Data, &p); err != nil || p.DatasetID == "" {
 			return
 		}
 		select {
+		case <-done:
+			return
 		case ch <- p.DatasetID:
 		default:
 		}
 	})
@@
 	go func() {
 		<-ctx.Done()
+		close(done)
 		_ = sub.Unsubscribe()
-		close(ch)
 	}()

Consumers must then treat ctx.Done() (not channel close) as the stop signal.

🤖 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/engine/nats/knowledgecompile.go` around lines 238 - 264, Update
SubscribeNotify to prevent the subscription callback from sending to ch after it
is closed: remove the direct close(ch) on context cancellation, or coordinate
callback completion with a done channel and sync.Once before closing. Preserve
the buffered, non-blocking delivery behavior, and ensure consumers use
ctx.Done() rather than channel closure as the termination signal.
internal/ingestion/component/knowledge_compiler/wiki/page.go-285-299 (1)

285-299: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

slugify drops all non-ASCII, collapsing CJK titles to page.

Every rune outside [a-z0-9-] is discarded, so titles like 中文标题 yield "page" and any two CJK-titled pages share the same slug. That slug feeds common.StableRowID (Line 203/235) and the existing[page.Slug] dedup in normalizeWikiPlanPages, so distinct pages silently collapse into one product for non-Latin documents — a common case for this repo. Keep unicode letters/digits (and fall back to a hash when the result is empty).

🐛 Preserve unicode word characters
 func slugify(s string) string {
 	s = strings.ToLower(strings.TrimSpace(s))
 	s = strings.ReplaceAll(s, " ", "-")
 	var b strings.Builder
 	for _, r := range s {
-		if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' {
+		if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '-' {
 			b.WriteRune(r)
 		}
 	}
-	if b.Len() == 0 {
+	if strings.Trim(b.String(), "-") == "" {
 		return "page"
 	}
-	return b.String()
+	return strings.Trim(b.String(), "-")
 }

Note the existing TestSlugify case {"中文 title", "-title"} documents (and locks in) the current behavior and would need updating.

🤖 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/wiki/page.go` around lines
285 - 299, Update slugify to preserve Unicode letters and digits while retaining
ASCII hyphens and existing normalization behavior, preventing distinct non-Latin
headings from collapsing to "page". Replace the empty-result fallback with a
deterministic hash-derived slug based on the original input, and update the
existing TestSlugify expectation for the Chinese-title case accordingly.
internal/ingestion/knowledge_compile/service.go-42-50 (1)

42-50: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Remove the unused WithMaxIdle option (and maxIdle field).

The option's own comment admits it's "unused by the poll loop but kept for parity with the option surface," and c.maxIdle is never read anywhere in consumer.go. As per coding guidelines, **/*: "Remove compatibility-only surfaces unless the user explicitly asks to keep them, and do not add compatibility wording to comments or documentation," and internal/{ingestion,parser,deepdoc}/**/*.go: "collapse duplicate paths rather than preserving transitional wrappers."

🤖 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/service.go` around lines 42 - 50, Remove
the unused WithMaxIdle option and its associated maxIdle field from the Consumer
configuration, including the compatibility-only comment and any related
initialization or references. Keep the remaining option surface and consumer
behavior unchanged.

Source: Coding guidelines

internal/ingestion/knowledge_compile/scheduler.go-150-178 (1)

150-178: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Initialize DatasetID before FirstOrCreate so new backlog rows are searchable.

Attrs(...).FirstOrCreate(...) only hydrates fields from the query conditions when those conditions are struct/map-based; a raw string condition is used for the lookup, but DatasetID won’t be populated on the inserted row. The first append for a new datasetID can therefore create dataset_id = "", causing later create/claim/ack/backlog queries for the real dataset id to miss that backlog entry. Use a struct-based condition or set DatasetID before calling FirstOrCreate.

🤖 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 150 - 178,
Initialize row.DatasetID with datasetID before FirstOrCreate in AppendBacklog,
or replace the raw string lookup with a struct-based condition that hydrates
DatasetID. Ensure newly inserted backlog rows persist the requested dataset ID
while preserving the existing row-locking, append, and save behavior.
🟡 Minor comments (13)
internal/ingestion/component/knowledge_compiler/structure/prompt.go-125-128 (1)

125-128: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

firstStringOf never handles a non-string type, so such fields are silently dropped. The name implies list support, but a list-valued (or numeric) type returns "" and the continue at Line 127 drops the field from both the rendered descriptions and the skeleton — with no diagnostic. Either rename to stringValue if only strings are valid, or handle the []any first-element case; a debug log on the skipped field would also help.

Also applies to: 379-384

🤖 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/structure/prompt.go` around
lines 125 - 128, The type extraction around firstStringOf currently drops
list-valued or numeric type fields without diagnostics. Update firstStringOf to
support []any by using its first element when it is a string, and preserve the
existing empty-type skip behavior; apply the same handling at the other
referenced call site.
internal/ingestion/component/knowledge_compiler/structure/chain.go-238-240 (1)

238-240: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Byte-slicing truncation can split a multi-byte rune. For CJK/emoji source chunks this emits invalid UTF-8 into the correction prompt. Truncate on a rune boundary instead.

🛡️ Rune-safe truncation
 			if len(text) > chainCorrectionMaxChunkChars {
-				text = text[:chainCorrectionMaxChunkChars]
+				r := []rune(text)
+				if len(r) > chainCorrectionMaxChunkChars {
+					r = r[:chainCorrectionMaxChunkChars]
+				}
+				text = string(r)
 			}
🤖 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/structure/chain.go` around
lines 238 - 240, Update the truncation logic in the chain correction flow around
the text length check to limit text by rune count or otherwise cut only at a
valid UTF-8 rune boundary, rather than slicing bytes at
chainCorrectionMaxChunkChars. Preserve the existing maximum-size behavior for
ASCII and ensure CJK or emoji text remains valid UTF-8.
internal/ingestion/component/knowledge_compiler/structure/compile.go-305-306 (1)

305-306: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

TrimSuffix(..., ".0") is a no-op. fmt.Sprintf("%v", float64(1)) yields "1", never "1.0", and large/small values render in scientific notation (1e+06), which then flows into payloadDescription and the embedding text. Use strconv.FormatFloat(x, 'f', -1, 64) for a stable decimal rendering.

♻️ Proposed change
 	case float64:
-		return strings.TrimSuffix(fmt.Sprintf("%v", x), ".0")
+		return strconv.FormatFloat(x, 'f', -1, 64)
🤖 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/structure/compile.go` around
lines 305 - 306, Update the float64 handling in the relevant structure
compilation switch to use strconv.FormatFloat with 'f', -1, and 64, replacing
the fmt.Sprintf and ineffective TrimSuffix call. Preserve the resulting string
flow into payloadDescription and embedding text while ensuring large and small
values use stable decimal notation.
internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav_test.go-173-180 (1)

173-180: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

This assertion locks in the missing parent→sub-cluster edge.

Requiring t.children["P"] to be absent after a split codifies the descent break flagged in datasetnav.go (Line 458-479). Once the parent relinks to the two new sub-clusters, this expectation must change to "P has exactly the 2 group children".

🤖 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/datasetnav/datasetnav_test.go`
around lines 173 - 180, Update the split-tree test around the assertions on
tree.children["P"] so it expects P to retain exactly two direct children after
reparenting, representing the new sub-clusters. Remove the absence assertion and
validate the child count (and, where appropriate, the two group identities)
while preserving the existing cluster-count expectation.
internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go-142-166 (1)

142-166: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Node product IDs ignore position, so repeated titles collide.

StableRowID(tenant, doc, variant, "node", child.ID) is derived from the node text alone. beChildren only dedups dict keys, not string/list leaves, so the same leaf text under two parents yields two products with identical IDs (last write wins, and the parent link is lost). Consider folding the parent ID or level into the row id.

🤖 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/mindmap/mindmap.go` around
lines 142 - 166, The node ID generation in the mindmap traversal must
distinguish repeated node titles. Update the StableRowID call in the
child-processing loop to incorporate a position- or hierarchy-specific value,
such as the parent product ID or level, while preserving stable IDs for the same
node location; keep metadata and parent-link construction unchanged.
internal/ingestion/component/knowledge_compiler/raptor/raptor.go-45-49 (1)

45-49: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

No count check between texts and the returned vectors.

datasetnav.Run validates len(vectors) != len(texts); here a mismatch flows into clusterByMethod, and if the embedder returns more rows than inputs, texts[pi] in buildTree goes out of range. Add the same guard.

🤖 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 45 - 49, The embedding flow in the raptor compiler must validate that the
returned vectors count matches the input texts count. In the function containing
deps.Embed.Encode and toFloat64Matrix, add a length check after encoding and
return an error before clustering or tree construction when the counts differ,
preserving the existing encode-error handling.
internal/ingestion/component/knowledge_compiler/raptor/clustering.go-216-227 (1)

216-227: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Comment and default disagree: no gap yields maximal fragmentation, not one cluster.

cutIdx defaults to len(sorted) (= n-1 merges), so numClusters becomes n — one cluster per point — while the comment claims "no cut (single cluster)". Pick the intended fallback and align the comment.

🤖 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/clustering.go` around
lines 216 - 227, Fix the no-gap fallback in the clustering logic around maxGap
and cutIdx: ensure the default produces the intended single-cluster result
rather than one cluster per point, and update the adjacent comments to
accurately describe the chosen cut index and numClusters behavior. Preserve the
existing largest-gap selection when a positive gap is found.
internal/ingestion/component/knowledge_compiler/raptor/clustering.go-433-436 (1)

433-436: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Degenerate fallback returns a label slice shorter than the input.

Callers (buildTree) derive n from len(labels) and index texts/embeddings by label position, so returning []int{0} for an n > 1 input silently drops every point but the first. Return a full-length zero slice instead.

🐛 Proposed fix
-	if bestMeans == nil {
-		// Degenerate: fall back to a single-cluster partition.
-		return []int{0}, cloneRows(embeddings[:1])
-	}
+	if bestMeans == nil {
+		// Degenerate: fall back to a single-cluster partition over all points.
+		return make([]int, n), cloneRows(embeddings[:1])
+	}
🤖 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/clustering.go` around
lines 433 - 436, Update the bestMeans == nil fallback in the clustering function
to return a zero-valued label slice with one entry per input embedding, while
preserving the existing single-centroid clone behavior. Ensure buildTree
receives labels matching the full input length so no points are dropped.
internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav.go-331-342 (1)

331-342: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Root selection iterates a map, so equal similarities resolve nondeterministically.

t.clusters is a map; when two depth-0 clusters tie on cosine (identical or duplicate vectors, a common case for repeated chunk text), the winner depends on map iteration order, contradicting the determinism claim on Line 130. Iterate t.order instead.

♻️ Proposed fix
-	for _, c := range t.clusters {
-		if c.Depth != 0 {
+	for _, name := range t.order {
+		c := t.clusters[name]
+		if c == nil || c.Depth != 0 {
 			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/datasetnav/datasetnav.go`
around lines 331 - 342, Update findBestCluster to iterate depth-0 clusters
through the deterministic t.order sequence instead of ranging over t.clusters.
Preserve the existing cosine comparison and selection behavior, including
retaining the first cluster encountered when similarities tie.
internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go-189-208 (1)

189-208: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Hand-rolled JSON quoting emits invalid JSON for control characters.

\r, \b, \f and any other rune < 0x20 are written raw, so serializeNode's output can fail downstream json.Unmarshal. Use encoding/json instead of maintaining an escape table.

♻️ Proposed fix
 func quoteJSON(s string) string {
-	var b strings.Builder
-	b.WriteByte('"')
-	for _, r := range s {
-		switch r {
-		case '"':
-			b.WriteString("\\\"")
-		case '\\':
-			b.WriteString("\\\\")
-		case '\n':
-			b.WriteString("\\n")
-		case '\t':
-			b.WriteString("\\t")
-		default:
-			b.WriteRune(r)
-		}
-	}
-	b.WriteByte('"')
-	return b.String()
+	var buf bytes.Buffer
+	enc := json.NewEncoder(&buf)
+	enc.SetEscapeHTML(false)
+	if err := enc.Encode(s); err != nil {
+		return `""`
+	}
+	return strings.TrimSpace(buf.String())
 }
🤖 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/mindmap/mindmap.go` around
lines 189 - 208, Replace the hand-rolled escaping in quoteJSON with
encoding/json’s standard string marshaling so all control characters, including
carriage return, backspace, form feed, and other runes below 0x20, produce valid
JSON. Preserve quoteJSON’s quoted-string return behavior and update its callers
only as needed to use the standard encoder safely.
internal/common/metadata_utils.go-456-479 (1)

456-479: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Fallback path leaks raw delimiter/whitespace-only values into output.

When an item trims to a string made up entirely of delimiter characters (or is whitespace-only, so it doesn't hit the item == "" check), every split part is empty, got stays false, and the code falls back to appending the original, un-trimmed item — contradicting the documented "empties dropped" contract and polluting the output with garbage tokens (e.g. "," or " ").

🐛 Proposed fix: drop the fallback instead of re-adding the raw item
 func splitCombinedStringList(items []string) []string {
 	out := make([]string, 0, len(items))
 	for _, item := range items {
 		if item == "" {
 			continue
 		}
 		parts := combinedValueDelim.Split(strings.TrimSpace(item), -1)
-		got := false
 		for _, p := range parts {
 			p = strings.TrimSpace(p)
 			if p == "" {
 				continue
 			}
 			out = append(out, p)
-			got = true
 		}
-		if !got {
-			out = append(out, item)
-		}
 	}
 	return dedupeMetaStrings(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/common/metadata_utils.go` around lines 456 - 479, Update
splitCombinedStringList to remove the got-based fallback that appends the
original item when all trimmed split parts are empty. Continue skipping empty
parts and only append non-empty trimmed tokens, so delimiter-only and
whitespace-only inputs produce no output.
internal/ingestion/component/extractor.go-993-1002 (1)

993-1002: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Merged metadata keys are not restricted to the declared schema.

Anything the model returns lands in ck["metadata"], including hallucinated keys outside c.Param.Metadata, which then propagate through mergeChunkMetadata into doc-level metadata. Filtering to the declared field keys bounds the doc metadata surface and matches the prompt's schema contract.

🛡️ Proposed filter
+	allowed := make(map[string]struct{}, len(c.Param.Metadata))
+	for _, f := range c.Param.Metadata {
+		allowed[f.Key] = struct{}{}
+	}
 	for k, v := range parsed {
+		if _, ok := allowed[k]; !ok {
+			continue
+		}
 		if v == nil {
 			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/extractor.go` around lines 993 - 1002, Restrict
the metadata merge loop in the extractor to keys declared by c.Param.Metadata
before assigning entries to meta. Preserve the existing nil and blank-string
filtering, and ensure undeclared model-returned keys are excluded from
ck["metadata"] so mergeChunkMetadata only receives schema-approved fields.
internal/ingestion/component/knowledge_compiler/common/deps.go-52-55 (1)

52-55: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove rollout-milestone wording from runtime contracts.

M1, M5/M9, and M8 document migration sequencing rather than the current interface behavior. As per coding guidelines, keep Go doc comments aligned with the current runtime path rather than migration history.

Also applies to: 82-85

🤖 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/deps.go` around lines
52 - 55, Update the Go doc comments for HistoricalKNN and the additionally
referenced contract to describe only their current runtime purpose and behavior.
Remove migration milestone and rollout-sequencing wording such as M1, M5/M9, and
M8, while preserving the interface definitions unchanged.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d9f1536d-9c47-413a-adb4-91f4d177b578

📥 Commits

Reviewing files that changed from the base of the PR and between f8e01d5 and 13ddfd4.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (92)
  • cmd/ragflow_server.go
  • go.mod
  • internal/common/metadata_utils.go
  • internal/common/metadata_utils_test.go
  • internal/common/parser_config.go
  • internal/common/parser_config_test.go
  • internal/common/task.go
  • internal/dao/compilation_template.go
  • internal/dao/database.go
  • internal/engine/engine.go
  • internal/engine/nats/knowledgecompile.go
  • internal/engine/nats/nats.go
  • internal/entity/knowledge_compile_doc.go
  • internal/ingestion/component/extractor.go
  • internal/ingestion/component/extractor_test.go
  • internal/ingestion/component/knowledge_compiler/PORT_PLAN.md
  • internal/ingestion/component/knowledge_compiler/common/batch.go
  • internal/ingestion/component/knowledge_compiler/common/batch_packing.go
  • internal/ingestion/component/knowledge_compiler/common/common_test.go
  • internal/ingestion/component/knowledge_compiler/common/deps.go
  • internal/ingestion/component/knowledge_compiler/common/id.go
  • internal/ingestion/component/knowledge_compiler/common/jsonchat.go
  • internal/ingestion/component/knowledge_compiler/common/memstore.go
  • internal/ingestion/component/knowledge_compiler/common/parserconfig.go
  • internal/ingestion/component/knowledge_compiler/common/pool.go
  • internal/ingestion/component/knowledge_compiler/common/tokenize.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/datasetnav/datasetnav_test.go
  • internal/ingestion/component/knowledge_compiler/golden/corpus.go
  • internal/ingestion/component/knowledge_compiler/golden/fixtures/raptor_baseline.json
  • internal/ingestion/component/knowledge_compiler/golden/fixtures/structure_wiki_baseline.json
  • internal/ingestion/component/knowledge_compiler/golden/golden_test.go
  • internal/ingestion/component/knowledge_compiler/golden/metrics.go
  • internal/ingestion/component/knowledge_compiler/golden_test.go
  • internal/ingestion/component/knowledge_compiler/mindmap/dictify.go
  • internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go
  • internal/ingestion/component/knowledge_compiler/mindmap/mindmap_test.go
  • internal/ingestion/component/knowledge_compiler/mindmap/prompt.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/structure/chain.go
  • internal/ingestion/component/knowledge_compiler/structure/chain_test.go
  • internal/ingestion/component/knowledge_compiler/structure/compile.go
  • internal/ingestion/component/knowledge_compiler/structure/graph.go
  • internal/ingestion/component/knowledge_compiler/structure/merge.go
  • internal/ingestion/component/knowledge_compiler/structure/prompt.go
  • internal/ingestion/component/knowledge_compiler/structure/structure.go
  • internal/ingestion/component/knowledge_compiler/structure/structure_test.go
  • internal/ingestion/component/knowledge_compiler/wiki/page.go
  • internal/ingestion/component/knowledge_compiler/wiki/page_test.go
  • internal/ingestion/component/knowledge_compiler/wiki/prompt.go
  • internal/ingestion/component/knowledge_compiler/wiki/wiki.go
  • internal/ingestion/component/knowledge_compiler/wiki/wiki_test.go
  • internal/ingestion/component/schema/extractor.go
  • internal/ingestion/knowledge_compile/consumer.go
  • internal/ingestion/knowledge_compile/consumer_test.go
  • internal/ingestion/knowledge_compile/dedup.go
  • internal/ingestion/knowledge_compile/event.go
  • internal/ingestion/knowledge_compile/reader.go
  • internal/ingestion/knowledge_compile/scheduler.go
  • internal/ingestion/knowledge_compile/service.go
  • internal/ingestion/knowledge_compile/writer.go
  • internal/ingestion/pipeline/pipeline_knowledge_compiler_test.go
  • internal/ingestion/pipeline/template/ingestion_pipeline_audio.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_book.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_email.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_general.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_knowledge_compiler.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_laws.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_manual.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_one.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_paper.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_picture.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_presentation.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_resume.json
  • internal/ingestion/pipeline/template_integration_test.go
  • internal/ingestion/service/doc_state.go
  • internal/ingestion/service/doc_state_test.go
  • internal/ingestion/service/ingestion_service.go
  • internal/ingestion/task/knowledge_compiler_wiring.go
  • internal/ingestion/task/pipeline_executor.go
  • internal/ingestion/task/pipeline_executor_defaults_test.go
  • internal/ingestion/task/pipeline_executor_test.go
  • internal/service/document/document_crud.go
  • internal/utility/metadata.go
  • internal/utility/metadata_test.go
  • ragflow_deps/download_go_deps.py

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

🧹 Nitpick comments (1)
internal/ingestion/component/knowledge_compiler/common/types.go (1)

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

Remove obsolete migration references from ownership comments.

FlushIfNeeded no longer exists, and M9 does not explain current runtime behavior. Replace these with a short statement about clearing the emitted buffer.

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

Also applies to: 242-243

🤖 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
190 - 191, Update the ownership comments beside the buffer-clearing assignments
in the relevant product and additional affected section to remove references to
FlushIfNeeded and M9. Replace each with a concise description that the emitted
buffer is being cleared.

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/id.go`:
- Around line 14-22: Update the rollout plan for StableRowID to address the
xxHash-to-SHA-256 identifier change: provide a migration/backfill or cleanup
procedure for existing row IDs and lookups, or explicitly document and enforce
that existing data is disposable before deployment.
- Around line 9-22: Update StableRowID to prevent collisions when part values
contain NUL bytes by using unambiguous length-prefix encoding or rejecting such
values. Align the function documentation with the chosen contract, and add a
test covering ["a\x00b"] versus ["a", "b"] if the API continues accepting
arbitrary strings.

In `@internal/ingestion/component/knowledge_compiler/common/types.go`:
- Around line 189-191: Update the flush cleanup in the Outputs flow so all
per-buffer accounting is reset after ownership of Products is handed to the
sink: clear Products and reset Items and VectorBytes to their zero values.
Ensure reused Outputs start with empty accounting and do not trigger repeated
flushes based on stale thresholds.

In `@internal/ingestion/component/knowledge_compiler/raptor/clustering.go`:
- Around line 200-205: Update the centroid calculation in the merged cluster
construction to weight ca.centroid and cb.centroid by ca.size and cb.size
respectively before normalizing by the combined size. Adjust the meanCentroid
call or its implementation as needed, while preserving the existing merged
members, size, and id assignments.

---

Nitpick comments:
In `@internal/ingestion/component/knowledge_compiler/common/types.go`:
- Around line 190-191: Update the ownership comments beside the buffer-clearing
assignments in the relevant product and additional affected section to remove
references to FlushIfNeeded and M9. Replace each with a concise description that
the emitted buffer is being cleared.
🪄 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: 688b232a-35f9-462b-8563-3d2efcb023b0

📥 Commits

Reviewing files that changed from the base of the PR and between c3c016e and 8e1e65f.

📒 Files selected for processing (31)
  • internal/engine/nats/knowledgecompile.go
  • internal/ingestion/component/extractor.go
  • internal/ingestion/component/knowledge_compiler/common/common_test.go
  • internal/ingestion/component/knowledge_compiler/common/id.go
  • internal/ingestion/component/knowledge_compiler/common/memstore.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/datasetnav/datasetnav_test.go
  • internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go
  • internal/ingestion/component/knowledge_compiler/raptor/clustering.go
  • internal/ingestion/component/knowledge_compiler/raptor/raptor.go
  • internal/ingestion/component/knowledge_compiler/wiki/page.go
  • internal/ingestion/component/knowledge_compiler/wiki/page_test.go
  • internal/ingestion/component/schema/extractor.go
  • internal/ingestion/knowledge_compile/consumer.go
  • internal/ingestion/knowledge_compile/scheduler.go
  • internal/ingestion/knowledge_compile/service.go
  • internal/ingestion/pipeline/template/ingestion_pipeline_audio.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_book.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_email.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_general.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_laws.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_manual.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_one.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_paper.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_picture.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_presentation.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_resume.json
  • internal/service/document/document_crud.go
💤 Files with no reviewable changes (1)
  • internal/ingestion/knowledge_compile/service.go
🚧 Files skipped from review as they are similar to previous changes (25)
  • internal/ingestion/pipeline/template/ingestion_pipeline_general.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_picture.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_audio.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_laws.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_resume.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_one.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_manual.json
  • internal/ingestion/pipeline/template/ingestion_pipeline_presentation.json
  • internal/service/document/document_crud.go
  • internal/ingestion/pipeline/template/ingestion_pipeline_email.json
  • internal/ingestion/component/knowledge_compiler/wiki/page_test.go
  • internal/ingestion/component/knowledge_compiler/common/common_test.go
  • internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go
  • internal/ingestion/component/knowledge_compiler/wiki/page.go
  • internal/ingestion/component/schema/extractor.go
  • internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav_test.go
  • internal/ingestion/component/knowledge_compiler/raptor/raptor.go
  • internal/engine/nats/knowledgecompile.go
  • internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav.go
  • internal/ingestion/component/knowledge_compiler/common/memstore.go
  • internal/ingestion/pipeline/template/ingestion_pipeline_paper.json
  • internal/ingestion/knowledge_compile/consumer.go
  • internal/ingestion/component/knowledge_compiler/component.go
  • internal/ingestion/knowledge_compile/scheduler.go
  • internal/ingestion/component/knowledge_compiler/component_test.go

- Add knowledge_compiler ingestion component (structure/wiki/golden/mindmap/raptor/datasetnav variants) with DB-independent DI seams (DepsResolver, GroupResolver).
- GenJSON fails loud on unparseable replies; pass-through envelope forwards chunker-shaped fields for headless chaining.
- Add dao.CompilationTemplateDAO.ResolveGroupTemplateIDs mirroring Python resolve_template_ids (tenant/status verification, fails loud on missing/empty groups).
- Wire SetGroupResolver into production composition root so compilation_template_group_ids configs resolve instead of failing at runtime.
- Add golden-gated regression tests and skip KnowledgeCompiler in headless smoke run.

align wiki

feat(knowledge_compiler): align structure/mindmap/datasetnav with Python port

- structure: rewrite to Python items contract (two-stage node→edge prompts,
  payload JSON rows, chunk-id filtering); LLM merge dedup reusing MemStore;
  5-kind post-processing chain validation (list/timeline) + timeline orphan
  cleanup; graph rebuild emits {entities,relations}
- mindmap: verbatim MIND_MAP prompt + goldmark dictify/todict/merge/shapeTree,
  byte-identical to Python MindMapExtractor on fixtures
- datasetnav: sequential incremental clustering with 2-means split, verbatim
  _llm_merge/_llm_create_summary, depth-quirk parity, dataset-keyed lock
- common: shared parserconfig.Get/GetMap/Localize; ChatRequest.Temperature
- fix task wiring (service ctx arg) + add knowledge_compiler template golden
- rewrite docs/develop/knowledge_compile_wiki_design.md to current Go impl

feat(ingestion): own dataset-level compile consumer in Ingestor + update design doc

- Move KC fetch into a dedicated compileFetchLoop goroutine; Start() is now
  non-blocking and runs the tasks.RAGFLOW consumeLoop as a separate goroutine
  (standard Start/Stop lifecycle contract).
- Gate fetches on a counting semaphore (compileSem, a buffered chan) so messages
  stay in the stream instead of being held un-acked when all workers are busy.
- Add kcConcurrency compileLoop workers driven by the Ingestor lifecycle
  (joined via workerWg/compileWg in Stop).
- Update docs/develop/knowledge_compile_design.md §11 to reflect the implemented
  design (actual NATS identifiers, Ingestor integration, lifecycle); fix stale
  comments that still described the fetch as merged into Start's main loop.

feat(knowledge_compile): migrate dataset-level compile consumer to Option E scheduling

Replace the NATS-KV lease + Nak-churn model with MySQL-centered scheduling
(Option E, docs/develop/knowledge_compile_design.md §11): MySQL
knowledge_compile_docs is the system of record and the source of same-KB
serialization; NATS notify.kc.workers is only a wake-up.

- Add entity.KnowledgeCompileDoc + register in dao.InitDB dataModels
- New Scheduler interface (mysqlScheduler + FakeScheduler) in scheduler.go,
  replacing lease.go/transport.go: Claim moves backlog->inflight under a row
  lock (closed batch boundary), Ack verifies claim_token, ReclaimExpired
  recovers crashed inflight
- event.go Publish* now AppendBacklog + Notify instead of publishing NATS
  events directly
- consumer.go: processOnce -> Run/processDataset (claim -> heartbeat ->
  merge -> ack), no Nak churn
- ingestion_service.go: kcConcurrency owned compileLoop workers each run
  Consumer.Run (incl. sweep ticker); drop compileCh/compileSem/compileFetchLoop
- engine: add MessageQueue.SubscribeNotify + NatsEngine impl
…_metadata->enable_metadata, metadata_fields->metadata)

- Add doc-level metadata extraction on Extractor nodes: prompt (rag/prompts/meta_data.md
  parity), JSON-schema via common.Turn2JSONSchema, result cleaning, chunk merge, LLM cache,
  combined-value split, and persist-merge union (utility.UpdateMetadataTo) mirroring Python.
- Rename misnamed Extractor params to align with Python: auto_metadata->enable_metadata,
  metadata_fields->metadata (DSL templates + Go struct/params/injection fn + tests).
- Chat-reference metadata_fields (openai_chat/reference_metadata/chat_pipeline) intentionally
  left unchanged (separate concept).
- Add design doc docs/develop/doc_metadata_go_port_research.md.
NATS (C1, M15, M16): use CreateOrUpdateKeyValue; publish compile events
over core NATS with nil-conn guard; guard SubscribeNotify against
send-on-closed-channel races.

RAPTOR (C2, C3, M6, M14): bound PCA dims to n; replace recluster with
cutTree union-find replay; guard embedding[0] access on nodes and root;
cap build-tree recursion depth.

knowledge_compile consumer (C4, C5, M18): per-doc seqs map; return/propagate
batch error so only successful batches are Acked; drop unused maxIdle.

scheduler (M19): set DatasetID/TenantID before FirstOrCreate.

component (M1, M2): stamp compilation_template_ids on streamed products;
fix component_test discriminator filter.

common (M7, M9, M10, M11): keep EnforceGuardrails only; reset Products to
nil; SHA-256 stable ids; memstore resolvedIdx reparse under write lock.

extractor (M8, M12, M13): drop redundant mutex guards on auto
keyword/question; enable_metadata=1 default in templates/schema.

datasetnav (M3, M5): tenant+dataset-prefixed nav_doc ids; keep split-parent
children so findBestCluster can descend.

wiki (M17): unicode-preserving slugify with FNV-1a fallback for
symbol-only titles.

document (M20): bound PublishDeleted with a 15s timeout context.
raptor (MAJOR 3673227716): size-weight merged centroids by cluster
sizes instead of equal-averaging, so Ward merge costs select correct
clusters when sizes differ. Removes now-dead meanCentroid helper.

common/id.go (MAJOR 3673227684 + MINOR 3673227680): length-prefix each
part in StableRowID so NUL-containing parts can never collide (e.g.
["a\x00b"] vs ["a","b"]); document the encoding/hash stability
contract and that pre-GA row ids are disposable (migration required only
post-GA). Adds TestStableRowID_NULCollision.

common/types.go (MINOR 3673227688): EnforceGuardrails flush also resets
Items and VectorBytes so a reused Outputs does not re-trigger flushes on
stale thresholds.
@yuzhichang yuzhichang added the ci Continue Integration label Jul 29, 2026

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

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

🟡 Minor comments (13)
internal/ingestion/component/knowledge_compiler/common/id.go-13-14 (1)

13-14: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Use a 64-bit length prefix.

Line 31 truncates lengths above 4 GiB, allowing distinct part sequences to produce the same encoded byte stream. This contradicts the unambiguous-framing contract.

Proposed fix
-// uint32 byte-length followed by the raw part bytes) before hashing. Length
+// uint64 byte-length followed by the raw part bytes) before hashing. Length
-	var lenBuf [4]byte
+	var lenBuf [8]byte
 	for _, p := range parts {
-		binary.BigEndian.PutUint32(lenBuf[:], uint32(len(p)))
+		binary.BigEndian.PutUint64(lenBuf[:], uint64(len(p)))
 		h.Write(lenBuf[:])

Also applies to: 29-33

🤖 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/id.go` around lines 13
- 14, Update the length-prefix encoding used by the identifier construction in
the affected function to use a 64-bit big-endian byte length instead of uint32,
including the buffer allocation and serialization at the referenced lines.
Preserve the existing raw-part ordering and hashing behavior while ensuring
parts larger than 4 GiB are encoded without truncation.

Source: Linters/SAST tools

internal/ingestion/component/knowledge_compiler/raptor/clustering.go-430-433 (1)

430-433: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Degenerate-BIC fallback returns a wrong-length label slice.

If bestMeans stays nil (all bic values compare as NaN), the fallback returns len(labels)==1 regardless of n, which will silently corrupt or index-panic in any caller expecting len(labels)==len(embeddings).

🐛 Proposed fix
 	if bestMeans == nil {
 		// Degenerate: fall back to a single-cluster partition.
-		return []int{0}, cloneRows(embeddings[:1])
+		labels := make([]int, n)
+		return labels, []([]float64){meanCentroid(embeddings, n)}
 	}

(or any helper that produces an n-length all-zero label slice and a single mean centroid over all n points).

🤖 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/clustering.go` around
lines 430 - 433, Update the bestMeans == nil fallback to return an all-zero
label slice with one entry per embedding and a single centroid computed from all
embeddings, preserving the single-cluster behavior while ensuring labels length
matches embeddings length.
internal/ingestion/knowledge_compile/scheduler.go-323-353 (1)

323-353: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

total is incremented before the liveness re-check, so refreshed leases are counted as reclaimed. Move the accumulation inside the transaction (after the ClaimExpiresAt.After(now) early return) so the returned count matches what was actually moved back.

🤖 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 323 - 353,
Move the total accumulation for each row from before the transaction into the
transaction callback, placing it after the ClaimExpiresAt.After(now) early
return and only when the inflight entries are actually moved to backlog.
Preserve the existing error handling and return count in the surrounding
scheduler flow.
internal/ingestion/component/knowledge_compiler/common/memstore.go-249-260 (1)

249-260: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

source_chunk_ids union silently drops prior provenance when the value isn't []string. Products reconstructed from stored JSON can carry []any here; the assertion then yields nil and the existing ids are overwritten by only the incoming ones. Handle []any too (same tolerance as structure.metaStrings).

🐛 Proposed fix
-	existing, _ := p.Meta["source_chunk_ids"].([]string)
+	var existing []string
+	switch v := p.Meta["source_chunk_ids"].(type) {
+	case []string:
+		existing = v
+	case []any:
+		for _, e := range v {
+			if s, ok := e.(string); ok {
+				existing = append(existing, s)
+			}
+		}
+	}
🤖 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/memstore.go` around
lines 249 - 260, Update the source_chunk_ids merge logic around the existing
assertion to accept both []string and []any, converting []any elements to
strings as needed before building seen and appending chunkIDs. Preserve all
valid prior provenance and retain the current deduplication behavior.
internal/engine/nats/knowledgecompile.go-133-137 (1)

133-137: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Handle messages.Error() after batch iteration. Iterating messages.Messages() can stop before all messages are delivered and report mid-fetch failures only via messages.Error(); return that error unless it is a normal nats.ErrTimeout, otherwise the caller receives a short batch while the stream failure is lost.

🤖 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/engine/nats/knowledgecompile.go` around lines 133 - 137, Update the
batch iteration in the knowledge compilation method around messages.Messages()
to check messages.Error() after the loop completes. Return any reported error
except normal nats.ErrTimeout, while preserving the collected out result for
successful or timeout-terminated iterations.
internal/ingestion/task/knowledge_compiler_wiring.go-96-99 (1)

96-99: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

A system message is always sent, even when SystemPrompt is empty.

Several call sites (e.g. datasetnav's merge/summary helpers) leave SystemPrompt unset; some providers reject a message with empty content. Skip the system role when blank.

🛡️ Proposed fix
-	msgs := []models.Message{
-		{Role: "system", Content: req.SystemPrompt},
-		{Role: "user", Content: req.UserPrompt},
-	}
+	msgs := make([]models.Message, 0, 2)
+	if strings.TrimSpace(req.SystemPrompt) != "" {
+		msgs = append(msgs, models.Message{Role: "system", Content: req.SystemPrompt})
+	}
+	msgs = append(msgs, models.Message{Role: "user", Content: req.UserPrompt})
#!/bin/bash
# How do other call sites build chat messages — is an empty system message normal here?
rg -nP -C4 'Role:\s*"system"' --type=go
🤖 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/knowledge_compiler_wiring.go` around lines 96 - 99,
Update message construction in the knowledge compiler wiring to include the
system-role message only when req.SystemPrompt is non-blank. Always retain the
user message, and preserve the existing ordering when a system prompt is
provided.
internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav.go-204-206 (1)

204-206: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Root overview uses creation-time cluster descriptions, so the comment overstates coverage.

place returns descriptions only on the create branches; merged documents (and the LLM-merged cluster description that replaces the original) never reach clusterDescs. The root prompt therefore contains stale, pre-merge text. Either build the prompt from tree.clusters[name].Desc over tree.order, or correct the comment.

♻️ Proposed fix: derive descriptions from the final tree
-	rootSummary, err := summarize(ctx, deps, llmID, "Compose a navigation overview from these section summaries:\n\n"+formatNavSummaries(clusterDescs))
+	finalDescs := make([]string, 0, len(tree.order))
+	for _, name := range tree.order {
+		finalDescs = append(finalDescs, tree.clusters[name].Desc)
+	}
+	rootSummary, err := summarize(ctx, deps, llmID, "Compose a navigation overview from these section summaries:\n\n"+formatNavSummaries(finalDescs))
🤖 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/datasetnav/datasetnav.go`
around lines 204 - 206, Build the root overview input from the final tree state
rather than creation-time cluster descriptions: iterate over tree.order and
collect each corresponding tree.clusters[name].Desc, then pass those
descriptions to formatNavSummaries for the root summarize call. Update the
nearby comment to state that the overview uses final cluster descriptions.
internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav.go-108-118 (1)

108-118: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Lock release error is discarded and a typed-nil deps.Redis still passes the guard.

l != nil only checks the interface value, so a non-nil interface holding a nil pointer passes and Acquire runs on a nil receiver. Also, defer l.Release(ctx, lockKey) swallows the error and reuses a possibly-cancelled ctx, which can leak the dataset lock until TTL.

🛡️ Suggested hardening
-		defer l.Release(ctx, lockKey)
+		defer func() {
+			if rerr := l.Release(context.WithoutCancel(ctx), lockKey); rerr != nil {
+				// best-effort; the lock TTL is the backstop
+				_ = rerr
+			}
+		}()
🤖 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/datasetnav/datasetnav.go`
around lines 108 - 118, Harden the lock handling around the dataset navigation
flow by detecting and skipping typed-nil implementations of deps.Redis before
calling datasetnavLock methods, and ensure the deferred Release uses a
non-cancelled context. Capture and handle the Release error rather than
discarding it, while preserving the existing Acquire failure behavior and lock
key construction.
internal/ingestion/component/knowledge_compiler/golden_test.go-184-189 (1)

184-189: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

want != 0 makes the golden gate silently vacuous if the baseline key is missing or renamed.

num() returns 0 for an absent/mistyped key, so a fixture typo turns this required CI gate into a no-op instead of failing. Distinguish "absent" from "0" and fail on absence. The same pattern is at Line 221-224 for wiki.

💚 Suggested change
-	want := num(baseline, "structure_products")
-	if want != 0 && len(prods) != want {
+	want, ok := numKey(baseline, "structure_products")
+	if !ok {
+		t.Fatalf("golden baseline missing key structure_products")
+	}
+	if len(prods) != want {
 		t.Errorf("structure product count = %d, golden baseline = %d (review contract if intentional)", len(prods), want)
 	}

with a helper returning presence:

func numKey(m map[string]any, key string) (int, bool) {
	switch v := m[key].(type) {
	case float64:
		return int(v), true
	case int:
		return v, true
	}
	return 0, false
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/ingestion/component/knowledge_compiler/golden_test.go` around lines
184 - 189, Update the golden baseline validation around the structure product
count and the corresponding wiki count near the second occurrence so missing or
mistyped keys fail instead of being skipped. Add a presence-aware helper
alongside num, then use its boolean result to report an error when the baseline
key is absent while still allowing an explicit zero and preserving the existing
count comparison.
internal/ingestion/component/knowledge_compiler/wiki/prompt.go-434-447 (1)

434-447: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Localization language is hard-coded to "en".

wikiNamedFieldDescription ignores the caller's language (available at the buildWikiMapPrompt call site) and always localizes with "en", so non-English deployments get English field descriptions. Thread language through.

🤖 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/wiki/prompt.go` around lines
434 - 447, Update wikiNamedFieldDescription to accept the caller’s language and
pass that value to common.Localize instead of the hard-coded "en". Thread
language through its call sites, including buildWikiMapPrompt, while preserving
the existing field matching and fallback behavior.
internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go-158-188 (1)

158-188: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Row ids are derived from labels alone, so repeated labels collide. Both product builders feed only the node/section title into common.StableRowID, so two nodes or sections that happen to share a label produce the same id and one row overwrites the other downstream.

  • internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go#L158-L188: include the parent id (or a sibling ordinal) in the StableRowID inputs for child nodes.
  • internal/ingestion/component/knowledge_compiler/wiki/page.go#L229-L257: include the section index i in the StableRowID inputs for section rows.
🤖 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/mindmap/mindmap.go` around
lines 158 - 188, Prevent row ID collisions in both product builders: in
internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go:158-188,
update the child-node StableRowID inputs to include the parent ID or sibling
ordinal; in
internal/ingestion/component/knowledge_compiler/wiki/page.go:229-257, include
section index i in the section-row StableRowID inputs. Preserve deterministic
IDs while distinguishing repeated labels.
internal/ingestion/component/knowledge_compiler/structure/structure.go-132-136 (1)

132-136: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Writing into a possibly-nil Meta map panics.

prods[i].Meta["compile_kwd"] = ... assumes every row built by buildRows/RewriteRelations carries a non-nil Meta. A single row without it aborts the whole compile. Initialize defensively (or guarantee it at the row-construction site, which is the owning abstraction).

🐛 Proposed fix
 	for i := range prods {
+		if prods[i].Meta == nil {
+			prods[i].Meta = map[string]any{}
+		}
 		prods[i].Meta["compile_kwd"] = string(compileType)
 	}
🤖 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/structure/structure.go`
around lines 132 - 136, Ensure each product row has a non-nil Meta map before
assigning compile_kwd in the prods loop, initializing it when absent while
preserving existing metadata. Prefer enforcing this in the row-construction path
used by buildRows or RewriteRelations if that abstraction owns Meta
initialization.
internal/ingestion/component/knowledge_compiler/structure/chain.go-238-240 (1)

238-240: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Truncate on a rune boundary.

text[:chainCorrectionMaxChunkChars] slices bytes, so multi-byte (e.g. CJK) source chunks can be cut mid-rune and the prompt then carries invalid UTF-8.

🐛 Proposed fix
-			if len(text) > chainCorrectionMaxChunkChars {
-				text = text[:chainCorrectionMaxChunkChars]
-			}
+			if len(text) > chainCorrectionMaxChunkChars {
+				cut := chainCorrectionMaxChunkChars
+				for cut > 0 && !utf8.RuneStart(text[cut]) {
+					cut--
+				}
+				text = text[:cut]
+			}
🤖 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/structure/chain.go` around
lines 238 - 240, Update the text truncation in the chain correction flow to
limit by Unicode runes rather than byte offsets, ensuring multi-byte characters
remain intact and the resulting prompt is valid UTF-8. Preserve the existing
chainCorrectionMaxChunkChars limit and truncation behavior for ASCII text.
🧹 Nitpick comments (28)
internal/ingestion/knowledge_compile/reader.go (1)

133-140: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Map iteration makes the vector column pick nondeterministic. If a document ever carries more than one q_<dim>_vec field, the chosen embedding varies run to run. Selecting by the expected dimension (or the sorted-first key) would be deterministic.

🤖 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 133 - 140, The
vectorFromChunkMap function selects a matching embedding nondeterministically
because map iteration order is undefined. Make selection deterministic by
choosing the entry with the expected dimension, or otherwise collecting matching
keys and using the lexicographically sorted first key, while preserving the
existing toFloat32Slice conversion.
internal/ingestion/component/knowledge_compiler/structure/merge.go (1)

484-495: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Redundant Snapshot() copies the whole bucket a second time. Compare against the snapshot you already iterated instead of re-snapshotting (which also re-acquires the store lock).

♻️ Suggested tweak
 		var remaining []common.Product
-		for _, row := range store.Snapshot() {
+		rows := store.Snapshot()
+		for _, row := range rows {
 			if kind, _ := row.Meta["kind"].(string); kind == "relation" {
 				relations = append(relations, row)
 			} else {
 				remaining = append(remaining, row)
 			}
 		}
-		if len(remaining) == len(store.Snapshot()) {
+		if len(remaining) == len(rows) {
🤖 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/structure/merge.go` around
lines 484 - 495, Reuse the single snapshot captured for the iteration in the
surrounding merge logic when checking whether all rows remain, instead of
calling store.Snapshot() again in the len comparison. Update the comparison near
relations/remaining processing to use that existing snapshot while preserving
the current keptOrder behavior.
internal/dao/compilation_template.go (1)

85-93: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Duplicate group ids yield duplicated template ids. If groupIDs contains the same group twice (a plausible caller/config artifact), out repeats that group's template ids. Consider deduping group ids up front or skipping already-emitted groups.

♻️ Suggested tweak
 	var out []string
+	emitted := make(map[string]struct{}, len(groupIDs))
 	for _, gid := range groupIDs {
+		if _, dup := emitted[gid]; dup {
+			continue
+		}
+		emitted[gid] = struct{}{}
 		ids := byGroup[gid]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/dao/compilation_template.go` around lines 85 - 93, Update the group
expansion logic around byGroup and groupIDs to avoid emitting duplicate template
IDs when groupIDs contains repeated group identifiers. Track already-emitted
group IDs or deduplicate groupIDs before iteration, while preserving the
existing error for groups that resolve to no valid templates and the ordering of
first occurrences.
internal/ingestion/knowledge_compile/dedup.go (1)

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

llmDeduper is stateful across Dedup calls. The embedded GroupedDeduper keeps every row it has seen, so a reused instance returns rows from prior batches. Either document/enforce single-use, or construct the GroupedDeduper inside Dedup.

🤖 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/dedup.go` around lines 38 - 46, The
llmDeduper instance retains GroupedDeduper state across Dedup calls, causing
results from earlier batches to leak into later ones. Update llmDeduper and its
Dedup method to construct a fresh structure.GroupedDeduper for each call, or
explicitly enforce and document single-use semantics; preserve the existing
merge-decider configuration.
internal/ingestion/knowledge_compile/scheduler.go (2)

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

Prefer the built-in min over a hand-rolled minInt. Available since Go 1.21 for ordered types.

#!/bin/bash
grep -n '^go ' go.mod
🤖 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 127 - 132,
Replace the hand-rolled minInt helper with Go 1.21's built-in min function at
its call sites, then remove the minInt function. Preserve the existing integer
minimum behavior and ensure no references to minInt remain.

150-186: 🚀 Performance & Scalability | 🔵 Trivial

Operational note: the backlog is an ever-growing JSON blob in a single row. Every append rewrites the whole backlog_doc_ids TEXT value under a row lock, so a hot KB serializes publishers and the payload can approach the column limit (silent truncation on MySQL non-strict mode). A child table with one row per event would scale better and let Claim use LIMIT/ORDER BY directly.

🤖 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 150 - 186,
The current AppendBacklog implementation stores an ever-growing event array in
KnowledgeCompileDoc.BacklogDocIDs, causing serialized row-lock contention and
potential TEXT truncation. Replace this blob-based backlog with a child-table
model containing one row per backlog event, update AppendBacklog to insert an
event row directly, and revise the related Claim flow to select pending events
with LIMIT and ORDER BY rather than parsing and rewriting BacklogDocIDs;
preserve tenant, dataset, sequence, and event ordering semantics.
internal/ingestion/knowledge_compile/consumer.go (2)

231-234: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Silent fallback to the no-op deduper hides a degraded merge path. A factory error means the batch is written without cross-document dedup, with no signal anywhere. Log the error (dataset/tenant + reason) before falling back.

🤖 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 231 - 234,
Update the deduper factory error path around c.factory(tenant) to log the tenant
or dataset context and the factory error before assigning NewNoopDeduper;
preserve the existing fallback for nil dedupers, but do not log an error when
the factory succeeds and returns nil.

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

Swallowed errors on the sweep and ack paths. _ = err discards a failed ReclaimExpired and a failed Ack — the latter means the batch stays inflight until reclaimed and will be reprocessed, which is worth a log line.

Also applies to: 178-180

🤖 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 92 - 96,
Update the consumer’s ReclaimExpired sweep and Ack error paths to log failures
with the relevant error details instead of discarding them via _ = err. Preserve
the existing best-effort retry and reprocessing behavior while adding a
contextual log entry for each failed operation.
internal/ingestion/knowledge_compile/consumer_test.go (1)

84-129: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add regression coverage for the two recently fixed invariants. Neither the per-doc Seq guard (doc B's seq=1 must survive after doc A's seq=5) nor the "no ack on batch error" path is exercised here; both are easy to assert with the fakes (a writer stub returning an error, then FindClaimable still returning the dataset).

🤖 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_test.go` around lines 84 - 129,
Extend the consumer tests with regression cases for both invariants: verify
processing documents preserves each document’s per-document Seq independently,
including doc B at seq=1 after doc A at seq=5, and verify a writer error
prevents acknowledgment by using a failing writer stub and asserting
FindClaimable still returns the dataset. Anchor the additions near
TestConsumerCompletedWritesMerged and reuse the existing fake scheduler, reader,
writer, and processDataset helpers.
internal/engine/nats/knowledgecompile.go (1)

224-228: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Substring matching on "wrong" is a fragile revision-mismatch check. A wording change in the server/client error breaks lease-release semantics silently (returns error instead of no-op) — or over-matches unrelated errors. Prefer matching the JetStream API error (e.g. *jetstream.APIError with the wrong-last-sequence error code) instead of a substring.

Please confirm the exact error/type returned by KeyValue.Delete with jetstream.LastRevision on mismatch in the pinned nats.go.

#!/bin/bash
grep -n 'nats-io/nats.go' go.mod
fd -t f 'kv.go' --exec grep -n 'LastRevision\|ErrKeyExists\|JSErrCodeStreamWrongLastSequence' {} \;
🤖 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/engine/nats/knowledgecompile.go` around lines 224 - 228, The
revision-mismatch handling in the lease-release path currently relies on fragile
`"wrong"` substring matching. Inspect the pinned nats.go implementation to
confirm the error returned by KeyValue.Delete with jetstream.LastRevision, then
update the logic around n.kv.Delete to use the typed JetStream API error and the
wrong-last-sequence error code; preserve the no-op behavior only for that
specific mismatch and return all other errors.
internal/entity/knowledge_compile_doc.go (1)

32-43: 🚀 Performance & Scalability | 🔵 Trivial

Consider an index for lease-sweep queries.

The claim/lease recovery pattern (owner + token + expiry) typically requires scanning for expired claims (claim_expires_at < now()), but no index is declared on claim_expires_at (or claim_owner). As the table grows this becomes a full scan on every sweep cycle. Also worth noting: backlog_doc_ids/inflight_doc_ids are unbounded JSON TEXT columns with no size guard, so a stuck/backlogged dataset can grow a single row without bound.

🤖 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/entity/knowledge_compile_doc.go` around lines 32 - 43, Add a
database index for lease-sweep lookups, centered on the claim_expires_at field
in KnowledgeCompileDoc and including claim_owner if the recovery query filters
by ownership. Leave the unbounded TEXT fields unchanged unless an existing
validation or storage constraint is available to apply.
internal/ingestion/component/knowledge_compiler/PORT_PLAN.md (1)

137-138: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

GMM sections are now stale — GMM is already implemented.

This plan repeatedly marks GMM/BIC as deferred/"TODO(M6+)" (e.g. "GMM/BIC + predict_proba 软分配:留 ClusteringMethod 可插拔接口,后补"), but raptor/raptor.go's package doc already documents a delivered gmm (ClusteringGMM) diagonal-covariance backend, and raptor/clustering_test.go has passing tests for it (TestGMMCluster_TwoBlobs, TestGMMCluster_SinglePoint). Please update these sections (or remove them) so the plan reflects the current runtime path instead of outdated migration history.

As per coding guidelines, "Remove dead tests, commented-out code, stale documentation, and 'move later' notes instead of preserving them" and keep docs aligned "with the current runtime path rather than migration history."

Also applies to: 148-149, 316-316, 361-362

🤖 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/PORT_PLAN.md` around lines
137 - 138, Update PORT_PLAN.md to remove or rewrite all stale GMM/BIC deferred,
TODO(M6+), “留后补,” and migration-history references, including the sections
around the ClusteringMethod note and the additional affected locations. Align
the plan with the delivered runtime path documented by ClusteringGMM and covered
by TestGMMCluster_TwoBlobs and TestGMMCluster_SinglePoint; do not retain
outdated deferral language.

Source: Coding guidelines

internal/ingestion/component/knowledge_compiler/datasetnav/datasetnav_test.go (1)

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

parentByID is populated but never asserted.

Dead bookkeeping in the test (and the unchecked .(string) assertions will panic rather than fail cleanly). Either assert the parent relationships or drop the map.

🤖 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/datasetnav/datasetnav_test.go`
around lines 241 - 258, Update the product validation loop around parentByID to
either assert the expected cluster parent relationships using the populated map
or remove the unused map and its assignments. Avoid unchecked string type
assertions when reading cluster metadata; validate the types and report test
failures cleanly instead of panicking.
internal/ingestion/component/knowledge_compiler/common/jsonchat.go (1)

37-37: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Error text embeds up to 200 chars of model output derived from customer documents.

This error propagates up to task/pipeline logs, so document-derived content (potentially PII) is persisted in logs. Consider logging the excerpt at debug level only and keeping the returned error content-free (e.g. include length/hash instead).

🤖 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/jsonchat.go` at line
37, Update the JSON parsing error path in the knowledge compiler to avoid
embedding resp.Content in the returned error. Keep the propagated error
content-free by including only non-sensitive metadata such as response length or
a hash, and emit the truncated model-output excerpt only through debug-level
logging.
internal/ingestion/component/knowledge_compiler/golden/corpus.go (1)

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

Doc comments carry porting/migration history instead of describing the current runtime path. Both comments explain the change in terms of the Python original and PORT_PLAN.md rather than what the code does today.

  • internal/ingestion/component/knowledge_compiler/golden/corpus.go#L1-L10: drop the "when a live Python baseline is available" note and the PORT_PLAN 缺口 C/E references; describe what the fixed corpus locks.
  • internal/ingestion/task/knowledge_compiler_wiring.go#L32-L42: drop the "see PORT_PLAN.md §4" pointer and state the dependency-direction rule (component stays DB-independent; deps injected at the task composition root) directly.

As per coding guidelines: "Keep Go package comments and 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/golden/corpus.go` around
lines 1 - 10, Update the package comment in
internal/ingestion/component/knowledge_compiler/golden/corpus.go (lines 1-10) to
remove Python-baseline and PORT_PLAN references, describing only that the fixed
corpus locks product counts and clustering structure for CI. Update the wiring
documentation in internal/ingestion/task/knowledge_compiler_wiring.go (lines
32-42) to remove the PORT_PLAN.md pointer and state directly that the component
remains database-independent while dependencies are injected at the task
composition root.

Source: Coding guidelines

internal/ingestion/component/knowledge_compiler/common/common_test.go (1)

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

checkGuardrails duplicates production logic inside the test.

Line 106 asserts against this local mirror rather than the real Run path, so a regression in the production guardrail check would not fail here. TestEnforceGuardrails already covers the real API; consider dropping the mirror.

🤖 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/common_test.go` around
lines 209 - 219, Remove the local checkGuardrails helper and update the affected
assertions to exercise the production Run path directly, reusing the existing
TestEnforceGuardrails coverage/API. Keep sinkFunc and unrelated test setup
unchanged.
internal/ingestion/component/knowledge_compiler/mindmap/mindmap_test.go (1)

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

Drop the import-keeper assignment.

var _ = common.EstimateTokens exists only to keep an otherwise-unused import; remove both it and the common import (the tests satisfy common.Tokenizer structurally via fakeTok).

♻️ Proposed cleanup
-var _ = common.EstimateTokens // keep common import when unused helpers shift
 import (
 	"strings"
 	"testing"
-
-	"ragflow/internal/ingestion/component/knowledge_compiler/common"
 )

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

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

In `@internal/ingestion/component/knowledge_compiler/mindmap/mindmap_test.go` at
line 239, Remove the import-keeper declaration var _ = common.EstimateTokens and
delete the now-unused common import from the mindmap tests. Keep fakeTok’s
structural common.Tokenizer compatibility unchanged.

Source: Coding guidelines

internal/ingestion/component/knowledge_compiler/common/tokenize.go (1)

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

Dead branch: n == 0 returns n.

The guard has no effect; (len(s)+3)/4 is already 0 for empty input.

♻️ Simplify
 func EstimateTokens(s string) int {
-	n := (len(s) + 3) / 4
-	if n == 0 {
-		return 0
-	}
-	return n
+	return (len(s) + 3) / 4
 }
🤖 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/tokenize.go` around
lines 6 - 12, Remove the redundant n == 0 conditional from EstimateTokens and
return the calculated n directly, preserving the existing token estimate for all
inputs.
internal/ingestion/component/knowledge_compiler/wiki/wiki.go (2)

1386-1407: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the unused helpers.

buildEvidenceChecklist, asPlanPayload, compactJSON, maybeSourceIDs, runMapBatch (a duplicate of the body inlined in runMap), prefixWithDash (line 1721) and firstPageCandidate (line 1092) have no callers in this package — they add a second, divergent path for map batching and JSON encoding.

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

#!/bin/bash
# Confirm these helpers have no callers anywhere.
for sym in buildEvidenceChecklist asPlanPayload compactJSON maybeSourceIDs runMapBatch prefixWithDash firstPageCandidate; do
  echo "== $sym"
  rg -n --type=go "\b$sym\s*\(" || echo "  (no calls)"
done

Also applies to: 1852-1894

🤖 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/wiki/wiki.go` around lines
1386 - 1407, Remove the unused helper functions buildEvidenceChecklist,
asPlanPayload, compactJSON, maybeSourceIDs, runMapBatch, prefixWithDash, and
firstPageCandidate from the package, including their associated dead code. Keep
the active runMap implementation and existing callers unchanged; do not replace
the removed helpers with alternate paths.

1614-1629: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Replace deprecated strings.Title.

Deprecated since Go 1.18 and flagged by staticcheck SA1019; favor golang.org/x/text/cases with a language tag, or a focused local titlecaser over strings.Fields.

🤖 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/wiki/wiki.go` around lines
1614 - 1629, Replace the deprecated strings.Title call in the displayText
closure with a supported title-casing implementation, preferably
golang.org/x/text/cases using an appropriate language tag, while preserving the
existing readable-string construction and fallback behavior.
internal/ingestion/component/knowledge_compiler/mindmap/prompt.go (1)

83-88: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate numTokens helper.

The identical fallback logic already lives in common/tokenize.go (unexported there). Export it once from common and call it here instead of re-implementing per variant package.

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

🤖 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/mindmap/prompt.go` around
lines 83 - 88, Remove the duplicate numTokens helper from the mindmap prompt
implementation and export the existing equivalent helper from
common/tokenize.go. Update callers in this package to use the exported common
helper, preserving tokenizer-based counting and the existing estimation fallback
through a single implementation path.

Source: Coding guidelines

internal/ingestion/component/knowledge_compiler/wiki/page_test.go (1)

95-98: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assertion is weaker than the stated expectation.

The message says "want page + 3 sections (>= 4)" but the check only requires >= 2, so a regression that drops sections still passes. Assert the exact count (4).

🤖 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/wiki/page_test.go` around
lines 95 - 98, Update the assertion around buildPageProducts to require exactly
4 products, matching the expected page plus three sections. Replace the
len(products) threshold check with an exact-count validation while preserving
the existing failure reporting.
internal/ingestion/component/knowledge_compiler/wiki/prompt.go (1)

219-240: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Unused docID parameter, and ids are emitted for skipped chunks.

_ = docID signals the parameter is unnecessary — drop it. Also ids is appended before the empty-text continue, so chunk_id_list advertises ids that never appear in packed_chunks, contradicting the prompt rule that source_chunk_id must be one of the listed ids present in the batch.

♻️ Proposed fix
-	for i, c := range batch {
-		id := strings.TrimSpace(c.ID)
-		if id == "" {
-			id = fmt.Sprintf("chunk-%d", i+1)
-		}
-		ids = append(ids, id)
-		text := firstNonEmpty(c.Text, c.Content)
-		if strings.TrimSpace(text) == "" {
-			continue
-		}
+	for i, c := range batch {
+		text := firstNonEmpty(c.Text, c.Content)
+		if strings.TrimSpace(text) == "" {
+			continue
+		}
+		id := strings.TrimSpace(c.ID)
+		if id == "" {
+			id = fmt.Sprintf("chunk-%d", i+1)
+		}
+		ids = append(ids, id)
🤖 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/wiki/prompt.go` around lines
219 - 240, The formatWikiChunkBatch function should no longer accept or
reference the unused docID parameter. Move the ids append operation after the
empty-text check so ids are returned only for chunks actually written to
packed_chunks, keeping chunk_id_list consistent with the emitted batch content.
internal/ingestion/component/knowledge_compiler/common/types.go (2)

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

Move ctx to the first parameter position.

EnforceGuardrails(g, sink, ctx) puts context.Context last, which reads against Go convention and against the call sites (out.EnforceGuardrails(param.Guardrails, inputs.Sink, ctx) in structure/mindmap). Since this is a brand-new internal API, fixing it now is cheap.

♻️ Proposed signature change
-func (o *Outputs) EnforceGuardrails(g CapacityGuardrails, sink ChunkedSink, ctx context.Context) error {
+func (o *Outputs) EnforceGuardrails(ctx context.Context, g CapacityGuardrails, sink ChunkedSink) error {
🤖 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` at line 175,
Update the Outputs.EnforceGuardrails method signature to place context.Context
as the first parameter, followed by CapacityGuardrails and ChunkedSink, and
adjust all call sites such as the structure and mindmap invocations to pass ctx
first.

92-95: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

New code ships legacy variant aliases plus a deprecation log.

mind_map / dataset_nav are being introduced as accepted-but-deprecated spellings in a brand-new port. Per the repo guidance to prefer deletion over deprecated branches and compatibility wording, consider accepting only the canonical names and dropping LogDeprecated — unless an external DSL contract already emits the underscore forms.

As per coding guidelines: "Treat legacy code as a liability rather than a compatibility target; prefer deletion over shims, deprecated branches, wrapper APIs, and dual-track migration notes."

Also applies to: 310-333

🤖 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
92 - 95, Remove the legacy underscore variant aliases and their deprecation
handling, including LogDeprecated and the related branches around the
variant-name parsing logic. Accept only the canonical variant names introduced
by this port, unless an existing external DSL contract demonstrably requires the
underscore spellings.

Source: Coding guidelines

internal/ingestion/component/knowledge_compiler/structure/graph.go (1)

79-98: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

order is dead state.

order is only ever appended to and never read (first-seen order is already preserved by out). Remove it. While here, the unchecked entity["name"].(string) / entity["type"].(string) assertions on line 83 will panic on any map that doesn't come from graphEntity; a , _ form keeps the merge robust if this helper is ever reused.

♻️ Proposed cleanup
 	merged := map[key]int{}
-	var order []key
 	var out []map[string]any
 	for _, entity := range entities {
-		k := key{name: entity["name"].(string), typ: entity["type"].(string)}
+		name, _ := entity["name"].(string)
+		typ, _ := entity["type"].(string)
+		k := key{name: name, typ: typ}
 		idx, ok := merged[k]
 		if !ok {
 			merged[k] = len(out)
-			order = append(order, k)
 			out = append(out, entity)
🤖 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/structure/graph.go` around
lines 79 - 98, Remove the unused order variable and its append operation from
the entity merge loop, relying on out to preserve first-seen order. In the merge
logic, replace the unchecked name and type assertions used to construct key with
safe extraction that yields zero values when fields are missing or not strings,
preventing panics for unexpected entity maps.
internal/ingestion/component/knowledge_compiler/component.go (1)

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

Dead default branch after the pre-validation switch.

The variant is already rejected at lines 97-103, so the default at 148-150 is unreachable. Drop it (or drop the pre-check and keep one switch) to keep a single validation path.

Also applies to: 148-150

🤖 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/component.go` around lines 95
- 103, The variant is validated twice, leaving the later default branch
unreachable. Remove the redundant validation path by keeping one switch-based
validation and dispatch flow around the variant handling, specifically
consolidating the pre-validation switch and the later dispatch switch so unknown
variants still return common.ErrUnknownVariant exactly once.
internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go (1)

40-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated comment, and f.Wait's own error is discarded.

Line 40 and line 43 carry the identical fan-out comment; drop one. In the collection loop the first return value's error is dropped (res, _ := f.Wait(ctx)), so a pool/context failure that never populates res.Err is treated as success.

Also applies to: 72-76

🤖 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/mindmap/mindmap.go` around
lines 40 - 47, Remove the duplicate fan-out comment, keeping only one near the
batch setup. In the collection loop, update the f.Wait call to retain and handle
its returned error instead of discarding it; propagate pool or context failures
even when the returned result has no res.Err, while preserving the existing
result processing for successful waits.

@codecov

codecov Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (06562cb) to head (6abb248).
⚠️ Report is 18 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17536   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

The previous commit (1bc8464) flipped Extractor enable_metadata from 0
to 1 in all 11 built-in DSL templates and in ExtractorParam.Defaults(),
but left the golden test (pipeline_executor_defaults_test.go) expecting 0
and, more importantly, broke InjectExtractorEnableMetadata's design.

The injection logic (common/parser_config.go) is dataset-flag-driven: it
only injects the metadata field schema into an Extractor node when that
node's enable_metadata is falsy, so a DSL default of 1 makes the
injection skip the node and never set its field schema (auto-metadata
extracts nothing), while also forcing metadata extraction on even when
the dataset flag is off. The documented contract is: DSL defaults to 0,
the dataset flag turns it on + injects the schema.

Revert the 11 DSL templates and ExtractorParam.Defaults() back to
enable_metadata: 0 so the golden test is correct and the
dataset-flag-driven injection works as intended. Also gofmt the
Defaults() block (pre-existing 3-tab indentation).
…dge_compiler

Fixes 20 major+ review findings from the latest CodeRabbit pass:

knowledge_compiler (component):
- batch_packing.go: count tokens from Text with Content fallback (c.Text can be empty while c.Content holds the body).
- component.go: only wrap a real sink with templateIDStampingSink; wrapping a nil sink silently drained flushed products.
- datasetnav.go: pre-compute every cluster StableRowID before resolving parent edges (fixes reparenting -> dropped ParentID) and tenant-scope cluster ids to match nav_doc ids.
- clustering.go: fix inverted chooseClusterCount formula (numClusters = n - cutIdx); update raptor_baseline.json AHC leaf-cluster contract 11 -> 2.
- raptor.go: propagate root synthesis (summarize/embed) errors instead of silently swallowing them.
- structure/merge.go: guard nil row.Meta before writing relation endpoint values.
- structure/structure.go: guard nil deps.Embed in buildGraphProduct.
- wiki/prompt.go: wire the computed schema/custom-rule values into the map prompt via placeholders (they were computed but discarded).
- wiki/wiki.go: validate deps.Chat at Run entry + nil-guard resp at both Chat sites; gate fallback pages so they are only added when the planner produced no pages.

knowledge_compile (service):
- service.go: Provision now takes a ctx and bounds the startup AutoMigrate with a 30s timeout.
- writer.go: emit the merged product's vector under q_<dim>_vec so dataset-level rows stay searchable; paginate DeleteMergedForDoc.
- consumer.go: store the delete seq in the tombstone and clear it on a higher-seq re-ingest (was permanent skip + unbounded map growth).
- dedup.go: apply recorded LLM-merge aliases via RewriteRelations in the dataset-level dedup.
- event.go: remove the dead, never-recorded chunkIDs param/field (caller passed nil).
- reader.go: paginate LoadCompiledProducts and DeleteMergedForDoc so large KBs are fully scanned.
- scheduler.go: clarify the duplicate-key safety (dataset_id primary key + FOR UPDATE gap lock).

ingestion service / wiring:
- ingestion_service.go: make Start idempotent via startOnce (extract start()); retain first init error.
- knowledge_compiler_wiring.go: make kcEmbedder.dim an atomic.Int64 (was an unsynchronized race).
- task/pipeline_executor.go: update PublishCompleted caller to the new signature.
@yuzhichang
yuzhichang merged commit 90f46b0 into infiniflow:main Jul 29, 2026
5 checks passed
yuzhichang added a commit that referenced this pull request Jul 31, 2026
…ck) (#17599)

Two regressions from #17536: (1) MySQL 8.0 AutoMigrate crash on
knowledge_compile_docs (Error 1101) from a TEXT default; (2) ingestor
Start() sync.Once re-entrant deadlock. Both fixed with regression tests.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. 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