From 520be78766c23611e9897d29ed93d161b0466aea Mon Sep 17 00:00:00 2001 From: xiaowang Date: Wed, 5 Aug 2026 18:00:48 +0800 Subject: [PATCH] =?UTF-8?q?fix(chunking):=20normalize=20line=20endings=20b?= =?UTF-8?q?efore=20splitting=20/=20=E5=9C=A8=E5=88=86=E5=9D=97=E5=89=8D?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E6=8D=A2=E8=A1=8C=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../application/service/knowledge_create.go | 4 ++ .../application/service/knowledge_process.go | 5 ++- internal/handler/chunker_debug.go | 7 ++-- internal/handler/chunker_debug_test.go | 42 +++++++++++++++++++ internal/infrastructure/chunker/strategy.go | 12 ++++++ .../infrastructure/chunker/strategy_test.go | 7 ++++ 6 files changed, 73 insertions(+), 4 deletions(-) diff --git a/internal/application/service/knowledge_create.go b/internal/application/service/knowledge_create.go index 9d6e5a40..b1d26ec4 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.go index 03114d2e..cb7c4b13 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) e logger.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.go index 300f5a9b..3e12d249 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.Profile if 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.go index ba11b0ed..c9762225 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.go index 349e37af..9fc8d319 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.go index b6742eb0..91677c75 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,