Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(chunking): normalize line endings before splitting / 在分块前统一换行符
xiaowang520be78766c2
diff --git a/internal/application/service/knowledge_create.go b/internal/application/service/knowledge_create.goindex 9d6e5a40b..b1d26ec43 100644--- a/internal/application/service/knowledge_create.go+++ b/internal/application/service/knowledge_create.go@@ -1208,6 +1208,10 @@ func (s *knowledgeService) triggerManualProcessing(ctx context.Context,}}+ // Keep manually entered CRLF text aligned with the LF values sent by the+ // chunking preview endpoint.+ clean = chunker.NormalizeLineEndings(clean)+processOverrides, _ := knowledge.ProcessOverrides()eff := ResolveProcessConfig(kb, processOverrides)diff --git a/internal/application/service/knowledge_process.go b/internal/application/service/knowledge_process.goindex 03114d2eb..cb7c4b13e 100644--- a/internal/application/service/knowledge_process.go+++ b/internal/application/service/knowledge_process.go@@ -3350,7 +3350,10 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) elogger.Infof(ctx, "Resolved %d total images for knowledge %s", len(storedImages), knowledge.ID)}- // Step 3: Split into chunks using Go chunker+ // Step 3: Split into chunks using Go chunker. Browser textareas normalize+ // pasted content to LF, so normalize uploaded source text before calculating+ // chunk boundaries as well.+ convertResult.MarkdownContent = chunker.NormalizeLineEndings(convertResult.MarkdownContent)chunkCfg := buildSplitterConfigFromChunking(eff.ChunkingConfig)processOpts := ProcessChunksOptions{diff --git a/internal/handler/chunker_debug.go b/internal/handler/chunker_debug.goindex 300f5a9b1..3e12d2496 100644--- a/internal/handler/chunker_debug.go+++ b/internal/handler/chunker_debug.go@@ -146,6 +146,7 @@ func PreviewChunking(c *gin.Context) {})return}+ text := chunker.NormalizeLineEndings(req.Text)cfg := chunker.NormalizeSplitterConfig(chunker.SplitterConfig{ChunkSize: req.ChunkingConfig.ChunkSize,@@ -173,14 +174,14 @@ func PreviewChunking(c *gin.Context) {req.ChunkingConfig.ParentChunkSize,req.ChunkingConfig.ChildChunkSize,)- result, parentDiag := chunker.SplitParentChildWithDiagnostics(req.Text, parentCfg, childCfg)+ result, parentDiag := chunker.SplitParentChildWithDiagnostics(text, parentCfg, childCfg)chunks = make([]chunker.Chunk, len(result.Children))for i, child := range result.Children {chunks[i] = child.Chunk}diag = parentDiag} else {- chunks, diag = chunker.SplitWithDiagnostics(req.Text, cfg)+ chunks, diag = chunker.SplitWithDiagnostics(text, cfg)}resCh <- splitResult{chunks: chunks, diag: diag}}()@@ -203,7 +204,7 @@ func PreviewChunking(c *gin.Context) {// can still show document stats. Avoids the previous double-pass.profile := diag.Profileif profile == nil {- profile = chunker.ProfileDocument(req.Text)+ profile = chunker.ProfileDocument(text)}logger.Debugf(ctx, "chunker preview: tier=%s chunks=%d", diag.SelectedTier, len(chunks))diff --git a/internal/handler/chunker_debug_test.go b/internal/handler/chunker_debug_test.goindex ba11b0eda..c97622254 100644--- a/internal/handler/chunker_debug_test.go+++ b/internal/handler/chunker_debug_test.go@@ -298,3 +298,45 @@ func TestPreviewChunking_ParentChildDefaultSizes(t *testing.T) {t.Fatalf("chunk count: got %d want %d", len(got), len(want.Children))}}++func TestPreviewChunking_LineEndingsMatchUpload(t *testing.T) {+ uploaded := strings.Repeat("## Record\r\n"+strings.Repeat("A sufficiently long entry body. ", 10)+"\r\n\r\n", 12)+ pasted := strings.ReplaceAll(uploaded, "\r\n", "\n") // HTML textarea normalization+ payload := PreviewChunkingPayload{+ ChunkSize: 500,+ ChunkOverlap: 20,+ Separators: []string{"\n\n", "\n", "。", "!", "?", ";", ";"},+ Strategy: chunker.StrategyHeading,+ }+ actual := chunker.Split(chunker.NormalizeLineEndings(uploaded), chunker.NormalizeSplitterConfig(chunker.SplitterConfig{+ ChunkSize: payload.ChunkSize,+ ChunkOverlap: payload.ChunkOverlap,+ Separators: payload.Separators,+ Strategy: payload.Strategy,+ }))+ for name, text := range map[string]string{+ "uploaded CRLF": uploaded,+ "pasted LF": pasted,+ } {+ t.Run(name, func(t *testing.T) {+ w, parsed := postPreview(t, PreviewChunkingRequest{Text: text, ChunkingConfig: payload})+ if w.Code != http.StatusOK {+ t.Fatalf("status %d body=%s", w.Code, w.Body.String())+ }+ data := parsed["data"].(map[string]any)+ preview := data["chunks"].([]any)+ if len(preview) != len(actual) {+ t.Fatalf("chunk count: got %d want %d", len(preview), len(actual))+ }+ for i, chunk := range actual {+ previewChunk := preview[i].(map[string]any)+ if previewChunk["content"] != chunk.Content {+ t.Errorf("chunk %d content differs", i)+ }+ if int(previewChunk["start"].(float64)) != chunk.Start || int(previewChunk["end"].(float64)) != chunk.End {+ t.Errorf("chunk %d span: got %v-%v want %d-%d", i, previewChunk["start"], previewChunk["end"], chunk.Start, chunk.End)+ }+ }+ })+ }+}diff --git a/internal/infrastructure/chunker/strategy.go b/internal/infrastructure/chunker/strategy.goindex 349e37af6..9fc8d319c 100644--- a/internal/infrastructure/chunker/strategy.go+++ b/internal/infrastructure/chunker/strategy.go@@ -200,6 +200,18 @@ func NormalizeSplitterConfig(cfg SplitterConfig) SplitterConfig {return cfg}+// NormalizeLineEndings canonicalizes text before chunking. Browser textareas+// normalize pasted CRLF text to LF, while uploaded files preserve their+// original line endings; without this, the same document produces different+// character counts and chunk boundaries.+func NormalizeLineEndings(text string) string {+ if !strings.Contains(text, "\r") {+ return text+ }+ text = strings.ReplaceAll(text, "\r\n", "\n")+ return strings.ReplaceAll(text, "\r", "\n")+}+// DeriveParentChildConfigs produces the exact parent and child splitter// configurations used by knowledge ingestion. Keeping this here lets preview// and ingestion remain in lockstep as the parent-child defaults evolve.diff --git a/internal/infrastructure/chunker/strategy_test.go b/internal/infrastructure/chunker/strategy_test.goindex b6742eb06..91677c75f 100644--- a/internal/infrastructure/chunker/strategy_test.go+++ b/internal/infrastructure/chunker/strategy_test.go@@ -237,6 +237,13 @@ func TestNormalizeSplitterConfig_MatchesIngestionDefaults(t *testing.T) {}}+func TestNormalizeLineEndings(t *testing.T) {+ input := "first\r\nsecond\rthird\nfourth"+ if got, want := NormalizeLineEndings(input), "first\nsecond\nthird\nfourth"; got != want {+ t.Errorf("NormalizeLineEndings() = %q, want %q", got, want)+ }+}+func TestDeriveParentChildConfigs_DefaultSizes(t *testing.T) {base := SplitterConfig{ChunkSize: 1000,