fix: preserve semantic boundaries in chunk overlap

main
ttommybot 2026-07-27 16:24:32 +08:00 committed by lyingbug
parent 36206ae62f
commit 2dfc696740
2 changed files with 372 additions and 37 deletions

View File

@ -122,6 +122,7 @@ var protectedPatterns = []*regexp.Regexp{
regexp.MustCompile("(?m)[ ]*(?:\\|[^|\\n]*)+\\|[\\r\\n]+\\s*(?:\\|\\s*:?-{3,}:?\\s*)+\\|[\\r\\n]+"), // Table header+separator
regexp.MustCompile("(?m)[ ]*(?:\\|[^|\\n]*)+\\|[\\r\\n]+"), // Table rows
regexp.MustCompile("(?s)```(?:\\w+)?[\\r\\n].*?```"), // Fenced code blocks
regexp.MustCompile("`[^`\\r\\n]+`"), // Markdown inline code
}
type span struct {
@ -580,57 +581,234 @@ func buildChunk(units []splitUnit, seq int) Chunk {
}
}
// computeOverlap returns the units to keep for overlap and their total rune length.
// computeOverlap returns the semantic suffix to keep for overlap and its total
// rune length.
//
// The configured overlap is a hard upper bound, not a raw character slice.
// Within that tail window we look for semantic boundaries using this priority:
//
// 1. paragraph break (\n\n / \r\n\r\n)
// 2. line break (\n / \r\n)
// 3. sentence end (。?!, ". ", and English ?/!)
//
// Priority wins first; for boundaries with the same priority, the earliest
// one in the window wins so the useful overlap is as large as possible. The
// next chunk starts immediately after the selected separator. If the window
// has no valid semantic boundary, no overlap is retained. This keeps overlap
// deterministic and bounded while allowing a boundary inside a large split
// unit (the previous implementation could only retain whole units and often
// collapsed to zero overlap for ordinary paragraphs).
func computeOverlap(current []splitUnit, chunkOverlap, chunkSize, nextLen int) ([]splitUnit, int) {
if chunkOverlap <= 0 {
return nil, 0
}
// Walk backward from end, accumulating overlap
overlapLen := 0
startIdx := len(current)
for i := len(current) - 1; i >= 0; i-- {
uLen := runeLen(current[i].text)
if overlapLen+uLen > chunkOverlap {
break
}
// Check that overlap + next unit fits in chunk
if overlapLen+uLen+nextLen > chunkSize {
break
}
overlapLen += uLen
startIdx = i
// Overlap is part of the next chunk's total size. When the incoming unit
// is already close to the chunk budget, shrink the search window rather
// than creating an oversized chunk.
maxOverlap := chunkOverlap
if remaining := chunkSize - nextLen; remaining < maxOverlap {
maxOverlap = remaining
}
// Skip leading separator-only and header-marker units in the overlap
for startIdx < len(current) {
u := current[startIdx]
isHeaderMarker := u.start == u.end
trimmed := strings.TrimSpace(u.text)
if isHeaderMarker || trimmed == "" || isSeparatorOnly(u.text) {
overlapLen -= runeLen(u.text)
startIdx++
} else {
break
}
}
if startIdx >= len(current) {
if maxOverlap <= 0 {
return nil, 0
}
overlap := make([]splitUnit, len(current)-startIdx)
copy(overlap, current[startIdx:])
window := semanticOverlapWindow(current, maxOverlap)
if len(window) == 0 {
return nil, 0
}
windowText := unitsText(window)
boundaryEnd, ok := findSemanticOverlapBoundary(windowText)
if !ok {
return nil, 0
}
overlap := trimUnitsPrefix(window, boundaryEnd)
overlapLen := 0
for _, u := range overlap {
overlapLen += runeLen(u.text)
}
if overlapLen <= 0 || strings.TrimSpace(unitsText(overlap)) == "" {
return nil, 0
}
return overlap, overlapLen
}
func isSeparatorOnly(s string) bool {
for _, r := range s {
if r != '\n' && r != '\r' && r != ' ' && r != '\t' && r != '。' {
return false
// semanticOverlapWindow returns at most maxLen source-backed runes from the
// tail of current. It may slice inside the first retained splitUnit so a
// semantic boundary inside a large paragraph remains discoverable. Synthetic
// zero-width units (for example repeated table headers) form a hard barrier:
// crossing them would break the Start/End-to-Content source invariant.
func semanticOverlapWindow(current []splitUnit, maxLen int) []splitUnit {
if maxLen <= 0 || len(current) == 0 {
return nil
}
remaining := maxLen
reversed := make([]splitUnit, 0, len(current))
for i := len(current) - 1; i >= 0 && remaining > 0; i-- {
u := current[i]
uLen := runeLen(u.text)
if uLen == 0 {
continue
}
// Header markers contain generated text but occupy no source range.
// Do not include or cross them when deriving an overlap suffix.
if u.start == u.end || u.end-u.start != uLen {
break
}
if uLen <= remaining {
reversed = append(reversed, u)
remaining -= uLen
continue
}
runes := []rune(u.text)
start := uLen - remaining
reversed = append(reversed, splitUnit{
text: string(runes[start:]),
start: u.start + start,
end: u.end,
})
remaining = 0
}
if len(reversed) == 0 {
return nil
}
window := make([]splitUnit, len(reversed))
for i := range reversed {
window[len(reversed)-1-i] = reversed[i]
}
return window
}
type semanticOverlapBoundary struct {
start int
end int
priority int
}
// findSemanticOverlapBoundary returns the rune offset immediately after the
// selected separator. Boundaries inside protected Markdown/code/math regions
// are ignored, and a boundary is invalid when only whitespace follows it.
func findSemanticOverlapBoundary(text string) (int, bool) {
runes := []rune(text)
if len(runes) == 0 {
return 0, false
}
protected := protectedSpansRune(text, protectedSpans(text))
insideProtected := func(pos int) bool {
for _, p := range protected {
if pos < p.start {
return false
}
if pos >= p.start && pos < p.end {
return true
}
}
return false
}
hasMeaningfulTail := func(end int) bool {
return end >= 0 && end < len(runes) && strings.TrimSpace(string(runes[end:])) != ""
}
var best semanticOverlapBoundary
found := false
consider := func(start, end, priority int) {
if start < 0 || end <= start || end > len(runes) || insideProtected(start) || !hasMeaningfulTail(end) {
return
}
candidate := semanticOverlapBoundary{start: start, end: end, priority: priority}
if !found || candidate.priority < best.priority ||
(candidate.priority == best.priority && candidate.start < best.start) {
best = candidate
found = true
}
}
return true
// Mark paragraph-break runes so their component newlines are not also
// emitted as lower-priority line-break candidates.
paragraphRune := make([]bool, len(runes))
for i := 0; i < len(runes); i++ {
switch {
case i+3 < len(runes) && runes[i] == '\r' && runes[i+1] == '\n' &&
runes[i+2] == '\r' && runes[i+3] == '\n':
consider(i, i+4, 1)
for j := i; j < i+4; j++ {
paragraphRune[j] = true
}
i += 3
case i+1 < len(runes) && runes[i] == '\n' && runes[i+1] == '\n':
consider(i, i+2, 1)
paragraphRune[i], paragraphRune[i+1] = true, true
i++
}
}
for i := 0; i < len(runes); i++ {
if paragraphRune[i] {
continue
}
if runes[i] == '\r' && i+1 < len(runes) && runes[i+1] == '\n' && !paragraphRune[i+1] {
consider(i, i+2, 2)
i++
continue
}
if runes[i] == '\n' {
consider(i, i+1, 2)
}
}
for i := 0; i < len(runes); i++ {
switch runes[i] {
case '。', '?', '!':
consider(i, i+1, 3)
case '.':
if i+1 < len(runes) && runes[i+1] == ' ' {
consider(i, i+2, 3)
}
case '?', '!':
consider(i, i+1, 3)
}
}
if !found {
return 0, false
}
return best.end, true
}
// trimUnitsPrefix removes prefixLen source runes while preserving the
// remaining units' original positions. prefixLen is relative to unitsText.
func trimUnitsPrefix(units []splitUnit, prefixLen int) []splitUnit {
if prefixLen <= 0 {
out := make([]splitUnit, len(units))
copy(out, units)
return out
}
remaining := prefixLen
out := make([]splitUnit, 0, len(units))
for _, u := range units {
uLen := runeLen(u.text)
if remaining >= uLen {
remaining -= uLen
continue
}
if remaining > 0 {
runes := []rune(u.text)
u.text = string(runes[remaining:])
u.start += remaining
remaining = 0
}
out = append(out, u)
}
return out
}
// ParentChildResult holds the two-level chunking output.

View File

@ -270,6 +270,163 @@ func TestSplitText_OverlapChunks_NonNegativeStart(t *testing.T) {
}
}
func TestFindSemanticOverlapBoundary_PriorityThenEarliest(t *testing.T) {
tests := []struct {
name string
text string
want string
}{
{
name: "paragraph outranks earlier sentence and line",
text: "第一句。第二句\n普通换行后的内容\n\n最后一段",
want: "最后一段",
},
{
name: "earliest sentence wins within same priority",
text: "第一句。第二句。第三句",
want: "第二句。第三句",
},
{
name: "windows paragraph break",
text: "第一段。\r\n\r\n第二段",
want: "第二段",
},
{
name: "line outranks earlier sentence",
text: "第一句。第一行\n第二行",
want: "第二行",
},
{
name: "windows line break",
text: "第一句。第一行\r\n第二行",
want: "第二行",
},
{
name: "chinese question mark",
text: "第一句?第二句",
want: "第二句",
},
{
name: "chinese exclamation mark",
text: "第一句!第二句",
want: "第二句",
},
{
name: "english period requires following space",
text: "First sentence. Second sentence",
want: "Second sentence",
},
{
name: "english question mark needs no following space",
text: "Question?Answer",
want: "Answer",
},
{
name: "english exclamation mark needs no following space",
text: "Warning!Continue",
want: "Continue",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
end, ok := findSemanticOverlapBoundary(tt.text)
if !ok {
t.Fatal("expected semantic overlap boundary")
}
got := string([]rune(tt.text)[end:])
if got != tt.want {
t.Fatalf("overlap tail = %q, want %q", got, tt.want)
}
})
}
}
func TestFindSemanticOverlapBoundary_NoConfiguredSemanticSeparator(t *testing.T) {
for _, text := range []string{
"没有任何语义分隔符的连续文本",
"只有,逗号;分号:冒号",
"version1.2 remains one unit",
"address 192.168.1.1 remains one unit",
} {
if end, ok := findSemanticOverlapBoundary(text); ok {
t.Errorf("findSemanticOverlapBoundary(%q) returned boundary at %d", text, end)
}
}
}
func TestFindSemanticOverlapBoundary_IgnoresProtectedContent(t *testing.T) {
for _, text := range []string{
"代码是 `fmt.Println(\"hello. world\")` 后续内容",
"代码块 ```go\nfmt.Println(\"hello. world\")\n``` 后续内容",
"公式 $$x. y$$ 后续内容",
} {
if end, ok := findSemanticOverlapBoundary(text); ok {
t.Errorf("findSemanticOverlapBoundary(%q) returned protected boundary at %d", text, end)
}
}
}
func TestComputeOverlap_FindsBoundaryInsideLargeUnit(t *testing.T) {
text := "abcdefgh。尾巴内容"
unit := splitUnit{text: text, start: 100, end: 100 + len([]rune(text))}
overlap, overlapLen := computeOverlap([]splitUnit{unit}, 8, 32, 8)
if got := unitsText(overlap); got != "尾巴内容" {
t.Fatalf("overlap = %q, want %q", got, "尾巴内容")
}
if overlapLen != len([]rune("尾巴内容")) {
t.Fatalf("overlapLen = %d, want %d", overlapLen, len([]rune("尾巴内容")))
}
if len(overlap) != 1 || overlap[0].start != 109 || overlap[0].end != 113 {
t.Fatalf("overlap source span = %+v, want [109,113)", overlap)
}
}
func TestComputeOverlap_NoBoundaryMeansNoOverlap(t *testing.T) {
text := "abcdefgh尾巴内容"
unit := splitUnit{text: text, start: 0, end: len([]rune(text))}
overlap, overlapLen := computeOverlap([]splitUnit{unit}, 8, 32, 8)
if len(overlap) != 0 || overlapLen != 0 {
t.Fatalf("expected no overlap, got %q (%d)", unitsText(overlap), overlapLen)
}
}
func TestComputeOverlap_RespectsNextChunkCapacity(t *testing.T) {
text := "abcdefgh。尾巴"
unit := splitUnit{text: text, start: 0, end: len([]rune(text))}
overlap, overlapLen := computeOverlap([]splitUnit{unit}, 10, 8, 5)
if got := unitsText(overlap); got != "尾巴" {
t.Fatalf("overlap = %q, want %q", got, "尾巴")
}
if overlapLen+5 > 8 {
t.Fatalf("overlap plus next content exceeds chunk size: %d + %d > %d", overlapLen, 5, 8)
}
}
func TestSplitText_SemanticOverlapInsideParagraph(t *testing.T) {
first := strings.Repeat("甲", 15) + "。尾巴"
text := first + "\n\n" + "后续内容"
cfg := SplitterConfig{
ChunkSize: 20,
ChunkOverlap: 10,
Separators: []string{"\n\n", "\n", "。"},
}
chunks := SplitText(text, cfg)
if len(chunks) != 2 {
t.Fatalf("expected 2 chunks, got %d: %#v", len(chunks), chunks)
}
if !strings.HasPrefix(chunks[1].Content, "尾巴\n\n") {
t.Fatalf("second chunk should start at the sentence boundary inside the large unit, got %q", chunks[1].Content)
}
if got := chunks[1].End - chunks[1].Start; got != len([]rune(chunks[1].Content)) {
t.Fatalf("position invariant broken: span=%d content=%d", got, len([]rune(chunks[1].Content)))
}
}
func TestBuildUnitsWithProtection_RuneOffsets(t *testing.T) {
text := "你好世界"
units := buildUnitsWithProtection(text, nil, []string{"\n"}, 0)