From 2a02807a618a18196ebc1ddbe9888fb742b24117 Mon Sep 17 00:00:00 2001 From: clumsypsc Date: Sat, 3 Oct 2026 15:02:52 +0800 Subject: [PATCH] fix(chunker): respect Markdown fences during heading detection --- .../infrastructure/chunker/fenced_code.go | 53 +++++++ .../chunker/fenced_code_test.go | 145 ++++++++++++++++++ .../chunker/heading_splitter.go | 35 +---- internal/infrastructure/chunker/profiler.go | 15 +- 4 files changed, 209 insertions(+), 39 deletions(-) create mode 100644 internal/infrastructure/chunker/fenced_code.go create mode 100644 internal/infrastructure/chunker/fenced_code_test.go diff --git a/internal/infrastructure/chunker/fenced_code.go b/internal/infrastructure/chunker/fenced_code.go new file mode 100644 index 00000000..439077bb --- /dev/null +++ b/internal/infrastructure/chunker/fenced_code.go @@ -0,0 +1,53 @@ +package chunker + +import "strings" + +// markdownFence tracks top-level backtick and tilde fences during line scans. +// It deliberately does not parse Markdown container blocks (lists/quotes). +type markdownFence struct { + marker byte + length int +} + +// consume reports whether line belongs to fenced code, including delimiters. +// The second result identifies opening/closing delimiters, so the profiler can +// count code content without counting fence lines. An unclosed fence remains +// active through the end of the scan. +func (f *markdownFence) consume(line string) (code, delimiter bool) { + inside := f.length > 0 + // Scanners split on LF; remove the line ending's CR for CRLF documents. + line = strings.TrimSuffix(line, "\r") + indent := 0 + for indent < len(line) && line[indent] == ' ' { + indent++ + } + if indent > 3 || indent == len(line) { + return inside, false + } + line = line[indent:] + marker := line[0] + if marker != '`' && marker != '~' { + return inside, false + } + length := 0 + for length < len(line) && line[length] == marker { + length++ + } + if length < 3 { + return inside, false + } + rest := line[length:] + if inside { + if marker == f.marker && length >= f.length && strings.Trim(rest, " \t") == "" { + *f = markdownFence{} + return true, true + } + return true, false + } + // Backtick info strings cannot themselves contain backticks. + if marker == '`' && strings.Contains(rest, "`") { + return false, false + } + f.marker, f.length = marker, length + return true, true +} diff --git a/internal/infrastructure/chunker/fenced_code_test.go b/internal/infrastructure/chunker/fenced_code_test.go new file mode 100644 index 00000000..24f1a77d --- /dev/null +++ b/internal/infrastructure/chunker/fenced_code_test.go @@ -0,0 +1,145 @@ +package chunker + +import ( + "math" + "strings" + "testing" + "unicode/utf8" +) + +func TestHeadingScansRespectFences(t *testing.T) { + cases := []struct { + name, open, body, close string + }{ + {"backticks", "```go", "# Fake\n## Fake sub", "```"}, + {"tildes", "~~~markdown", "# Fake\n## Fake sub", "~~~"}, + {"long backticks", "````markdown", "```\n# Fake\n## Fake sub", "````"}, + {"long tildes", "~~~~", "~~~\n# Fake\n## Fake sub", "~~~~~"}, + {"mismatched closer", "```", "~~~\n# Fake\n## Fake sub", "```"}, + {"closer with text", "```", "``` trailing\n# Fake\n## Fake sub", "```"}, + {"indented closer", "```", " ```\n# Fake\n## Fake sub", "```"}, + {"tab indented closer", "```", "\t```\n# Fake\n## Fake sub", "```"}, + {"indented fences", " ~~~go", "# Fake\n## Fake sub", " ~~~~ \t"}, + {"backtick info", "```go title=example", "# Fake\n## Fake sub", "```"}, + {"tilde info with backtick", "~~~go `example`", "# Fake\n## Fake sub", "~~~"}, + {"unclosed", "~~~", "# Fake\n## Fake sub", ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + doc := "# Real\n" + tc.open + "\n" + tc.body + wantTotal := 1 + if tc.close != "" { + doc += "\n" + tc.close + "\n# After\n## Real sub" + wantTotal = 3 + } + p := ProfileDocument(doc) + if p.MdHeadingTotal != wantTotal || p.MdHeadingCounts[1] != wantTotal/2+1 || + p.MdHeadingCounts[2] != wantTotal/2 { + t.Errorf("unexpected heading counts: %v (total %d)", p.MdHeadingCounts, p.MdHeadingTotal) + } + codeChars := 0 + for _, line := range strings.Split(tc.body, "\n") { + codeChars += utf8.RuneCountInString(line) + } + wantRatio := float64(codeChars) / float64(utf8.RuneCountInString(doc)) + if !p.HasCode || math.Abs(p.CodeRatio-wantRatio) > 1e-12 { + t.Errorf("HasCode=%v CodeRatio=%g, want true and %g", p.HasCode, p.CodeRatio, wantRatio) + } + + bounds := findHeadingBoundaries(doc, 1) + if len(bounds) != wantTotal/2+1 || bounds[0].line != "# Real" { + t.Errorf("unexpected boundaries: %+v", bounds) + } + if tc.close != "" && len(bounds) == 2 { + wantOffset := utf8.RuneCountInString(doc[:strings.Index(doc, "# After")]) + if bounds[1].line != "# After" || bounds[1].runeStart != wantOffset { + t.Errorf("unexpected closing boundary: %+v, want offset %d", bounds[1], wantOffset) + } + } + + seed := NewHeadingHierarchy() + seed.Observe("# Real") + bcs := sectionBreadcrumbs([]rune(doc), 1, *seed) + observeSubHeadings([]rune(doc), 1, seed) + wantBreadcrumb := "# Real" + if tc.close != "" { + wantBreadcrumb += "\n## Real sub" + } + if seed.BreadcrumbWithHashes() != wantBreadcrumb || len(bcs) != wantTotal/2+1 || + bcs[len(bcs)-1].breadcrumb != wantBreadcrumb { + t.Errorf("unexpected heading context: %q, breadcrumbs: %+v", seed.BreadcrumbWithHashes(), bcs) + } + }) + } +} + +func TestHeadingScansRejectInvalidFenceOpeners(t *testing.T) { + for _, open := range []string{"``", "~~", " ```", "\t~~~", "```go `example`", "`~`"} { + t.Run(open, func(t *testing.T) { + doc := open + "\n# Real\n## Real sub" + p := ProfileDocument(doc) + if p.HasCode || p.CodeRatio != 0 || p.MdHeadingTotal != 2 { + t.Errorf("invalid opener hid headings or counted code: %+v", p) + } + bounds := findHeadingBoundaries(doc, 1) + if len(bounds) != 2 || bounds[1].line != "# Real" { + t.Errorf("unexpected boundaries: %+v", bounds) + } + h := NewHeadingHierarchy() + h.Observe("# Seed") + bcs := sectionBreadcrumbs([]rune(doc), 1, *h) + observeSubHeadings([]rune(doc), 1, h) + if h.BreadcrumbWithHashes() != "# Seed\n## Real sub" || len(bcs) != 2 { + t.Errorf("unexpected context: %q, breadcrumbs: %+v", h.BreadcrumbWithHashes(), bcs) + } + }) + } +} + +func TestSplitByHeadings_FencedSubHeadingContext(t *testing.T) { + for _, fence := range []string{"~~~", "````"} { + for _, newline := range []string{"\n", "\r\n"} { + t.Run(fence+newline, func(t *testing.T) { + filler := strings.Repeat("中文 clause body sentence. ", 25) + doc := "# Real\n" + filler + "\n## Section\n" + filler + "\n" + + fence + "markdown\n```\n### Fake\n" + filler + "\n" + fence + "\n" + + filler + "AFTER_CODE_MARKER\n" + filler + "\n### Real sub\n" + filler + + "REAL_SUB_MARKER\n" + filler + "\n## Next\n" + filler + "\n## Last\n" + filler + doc = strings.ReplaceAll(doc, "\n", newline) + cfg := SplitterConfig{ChunkSize: 200, ChunkOverlap: 20, Separators: []string{". "}} + chunks := splitByHeadingsImpl(doc, cfg, nil) + if len(chunks) < 4 { + t.Fatalf("expected large section to be sub-split, got %d chunks", len(chunks)) + } + runes := []rune(doc) + seenCode, seenSub := false, false + for i, c := range chunks { + if c.Seq != i || c.Start < 0 || c.End < c.Start || c.End > len(runes) { + t.Fatalf("invalid chunk position or sequence: %+v", c) + } + if c.End-c.Start != utf8.RuneCountInString(c.Content) || string(runes[c.Start:c.End]) != c.Content { + t.Errorf("chunk %d does not match its source slice", i) + } + if strings.Contains(c.ContextHeader, "Fake") { + t.Errorf("chunk %d contains code heading in context: %q", i, c.ContextHeader) + } + if strings.Contains(c.Content, "AFTER_CODE_MARKER") { + seenCode = true + if c.ContextHeader != "# Real\n## Section" { + t.Errorf("context after code = %q", c.ContextHeader) + } + } + if strings.Contains(c.Content, "REAL_SUB_MARKER") { + seenSub = true + if c.ContextHeader != "# Real\n## Section\n### Real sub" { + t.Errorf("context after real sub-heading = %q", c.ContextHeader) + } + } + } + if !seenCode || !seenSub { + t.Error("marker content lost during chunking") + } + }) + } + } +} diff --git a/internal/infrastructure/chunker/heading_splitter.go b/internal/infrastructure/chunker/heading_splitter.go index fc685491..a6d09f13 100644 --- a/internal/infrastructure/chunker/heading_splitter.go +++ b/internal/infrastructure/chunker/heading_splitter.go @@ -214,19 +214,10 @@ func findHeadingBoundaries(text string, primaryLevel int) []headingBoundary { } pos := 0 - inFence := false + var fence markdownFence lines := strings.Split(text, "\n") for i, line := range lines { - trimmed := strings.TrimSpace(line) - if strings.HasPrefix(trimmed, "```") { - inFence = !inFence - pos += utf8.RuneCountInString(line) - if i < len(lines)-1 { - pos++ // newline - } - continue - } - if !inFence { + if code, _ := fence.consume(line); !code { m := MarkdownHeadingPattern.FindStringSubmatch(line) if m != nil { level := len(m[1]) @@ -259,14 +250,9 @@ func observeSubHeadings(runes []rune, primaryLevel int, h *HeadingHierarchy) { return } text := string(runes) - inFence := false + var fence markdownFence for _, line := range strings.Split(text, "\n") { - trimmed := strings.TrimSpace(line) - if strings.HasPrefix(trimmed, "```") { - inFence = !inFence - continue - } - if inFence { + if code, _ := fence.consume(line); code { continue } m := MarkdownHeadingPattern.FindStringSubmatch(line) @@ -298,19 +284,10 @@ func sectionBreadcrumbs(sectionRunes []rune, primaryLevel int, seed HeadingHiera h := seed result := []sectionBreadcrumb{{runeStart: 0, breadcrumb: h.BreadcrumbWithHashes()}} pos := 0 - inFence := false + var fence markdownFence lines := strings.Split(string(sectionRunes), "\n") for i, line := range lines { - trimmed := strings.TrimSpace(line) - if strings.HasPrefix(trimmed, "```") { - inFence = !inFence - pos += utf8.RuneCountInString(line) - if i < len(lines)-1 { - pos++ - } - continue - } - if !inFence { + if code, _ := fence.consume(line); !code { if m := MarkdownHeadingPattern.FindStringSubmatch(line); m != nil && len(m[1]) > primaryLevel { h.Observe(line) result = append(result, sectionBreadcrumb{ diff --git a/internal/infrastructure/chunker/profiler.go b/internal/infrastructure/chunker/profiler.go index 40aa4c5b..950f2199 100644 --- a/internal/infrastructure/chunker/profiler.go +++ b/internal/infrastructure/chunker/profiler.go @@ -101,21 +101,16 @@ func ProfileDocument(text string) *DocProfile { // First pass: per-line markers and length stats var lengths []float64 - inFence := false + var fence markdownFence codeChars := 0 for _, line := range lines { trimmed := strings.TrimSpace(line) - // Toggle fenced-code state. We use a 3-backtick prefix detector here - // rather than a full regex so we don't have to fight with the - // protected-pattern logic later. - if strings.HasPrefix(trimmed, "```") { - inFence = !inFence + if code, delimiter := fence.consume(line); code { p.HasCode = true - continue - } - if inFence { - codeChars += len([]rune(line)) + if !delimiter { + codeChars += len([]rune(line)) + } continue }