fix(chunker): QA audit — position invariant, recursive split, perf

Resolves the issues surfaced by a self-review of the adaptive chunking
work. Tests covering each regression were added first to prove the
fix.

Critical
- Heading splitter no longer prepends breadcrumb to Content. The
  breadcrumb now lives on Chunk.ContextHeader; EmbeddingContent()
  combines header + content for the embedder. This restores the
  End-Start == len(Content) invariant relied on by knowledge.go's
  document-reconstruction path (summary generation, UI highlight) and
  also eliminates the duplicate-heading regression where the section
  heading appeared twice in a chunk's body.
- splitBySeparators is now genuinely recursive: when one separator
  leaves a piece > ChunkSize, the next-priority separator is applied
  inside that piece. Mirrors the Python reference. Without this, a
  document with one paragraph break followed by a long run of
  newline-separated lines could emit a single ~1950-rune chunk for
  ChunkSize=300.

Medium
- SplitParentChild forces children onto the recursive tier, skipping
  the per-parent profile pass (was N extra O(N) scans).
- Heuristic splitter snaps overlap start to the nearest semantic
  boundary or newline instead of slicing mid-line / mid-word.
- Strategy.Split returns the legacy tier's output directly when the
  whole chain rejects rather than running SplitText a second time.

Low
- ensureDefaults caps ChunkOverlap at ChunkSize/2 so pathological
  configs (TokenLimit clamping ChunkSize tiny while Overlap stays
  high) cannot produce ~97% overlap chunks.
- DefaultChunkOverlap docstring spells out the migration story for
  KBs that stored ChunkOverlap=0.

ContextHeader plumbing
- chunker.Chunk and types.ParsedChunk gain ContextHeader plus an
  EmbeddingContent() helper.
- types.Chunk gets a transient (gorm:"-") ContextHeader field so the
  knowledge service can build embedding inputs as
  titlePrefix + chunk.EmbeddingContent() without a DB schema change.

https://claude.ai/code/session_01XADhx6mtu2ZYW3DE9Lun6k
This commit is contained in:
Claude
2026-05-02 10:06:53 +00:00
committed by lyingbug
parent b0fbb8da9f
commit bc44c31cec
10 changed files with 392 additions and 117 deletions
+82 -25
View File
@@ -12,11 +12,33 @@ import (
)
// Chunk represents a piece of split text with position tracking.
//
// Content holds exactly the text from the original document between Start
// and End (rune offsets), so End-Start == utf8.RuneCountInString(Content).
// This invariant is relied on by document-reconstruction code paths
// (knowledge.go:2278+ for summary generation, UI highlighting, etc.).
//
// ContextHeader is a separately-tracked context string (e.g. a Markdown
// heading breadcrumb) that should be prepended at embedding/retrieval time
// but is NOT part of Content. Keeping the two apart preserves the
// position invariant while still letting embedding pipelines see the
// section context.
type Chunk struct {
Content string
Seq int
Start int
End int
Content string
ContextHeader string
Seq int
Start int
End int
}
// EmbeddingContent returns the text that should be fed to the embedding
// model — the ContextHeader prepended (when set) plus the chunk content.
// Use this where Content alone would lose semantic context (Tier-1 chunks).
func (c Chunk) EmbeddingContent() string {
if c.ContextHeader == "" {
return c.Content
}
return c.ContextHeader + "\n\n" + c.Content
}
// ImageRef is an image reference found within a chunk's content.
@@ -46,9 +68,20 @@ type SplitterConfig struct {
// Default sizes used by all entry points (DefaultConfig, ensureDefaults,
// and buildSplitterConfig in the knowledge service).
//
// MIGRATION NOTE: Prior versions had three different overlap defaults
// (Go DefaultConfig: 64, knowledge.go buildSplitterConfig: 50, Python
// docreader: 100). This file is now the single source of truth at 80
// (≈15% of DefaultChunkSize) — a community-recommended sweet spot.
//
// Existing knowledge bases that stored ChunkOverlap=0 in the DB will pick
// up 80 on next re-index; their previously-indexed embeddings will not
// match new ones bit-for-bit. Recall stays similar but search ranking
// can shift slightly. To freeze the old behavior on a per-KB basis,
// explicitly set ChunkingConfig.ChunkOverlap to 64 before re-indexing.
const (
DefaultChunkSize = 512
DefaultChunkOverlap = 80 // ≈ 15% of DefaultChunkSize
DefaultChunkOverlap = 80
)
// DefaultConfig returns sensible defaults.
@@ -122,17 +155,24 @@ type splitUnit struct {
start, end int
}
// splitBySeparators splits text by separators in priority order, keeping the
// separators themselves as standalone units. Walks the separator list in
// order: the first separator that actually splits the text wins, the rest
// are not applied. Mirrors the recursive priority semantics of the Python
// reference splitter (docreader/splitter/splitter.py:_split).
func splitBySeparators(text string, separators []string) []string {
if len(separators) == 0 || text == "" {
// splitBySeparators splits text by separators in priority order, recursively
// applying the next separator to any piece that is still larger than
// chunkSize. Mirrors the recursive priority semantics of the Python
// reference splitter (docreader/splitter/splitter.py:_split): if `\n\n`
// produces a piece that's still too big, `\n` (and subsequent separators)
// are applied within that piece — not to the whole text.
//
// chunkSize == 0 disables the recursion guard; callers that don't care
// about size budget (e.g. a final mergeUnits-style pass) pass 0.
func splitBySeparators(text string, separators []string, chunkSize int) []string {
if text == "" || len(separators) == 0 {
return []string{text}
}
if chunkSize > 0 && runeLen(text) <= chunkSize {
return []string{text}
}
for _, sep := range separators {
for i, sep := range separators {
if sep == "" {
continue
}
@@ -143,18 +183,31 @@ func splitBySeparators(text string, separators []string) []string {
continue
}
var result []string
for i, s := range splits {
var pieces []string
for j, s := range splits {
if s != "" {
result = append(result, s)
pieces = append(pieces, s)
}
if i < len(matches) && matches[i] != "" {
result = append(result, matches[i])
if j < len(matches) && matches[j] != "" {
pieces = append(pieces, matches[j])
}
}
if len(result) > 1 {
return result
if len(pieces) <= 1 {
continue
}
// Recursively split any piece that is still too large with the
// remaining (lower-priority) separators.
var out []string
remaining := separators[i+1:]
for _, p := range pieces {
if chunkSize > 0 && runeLen(p) > chunkSize && len(remaining) > 0 {
out = append(out, splitBySeparators(p, remaining, chunkSize)...)
} else {
out = append(out, p)
}
}
return out
}
return []string{text}
}
@@ -184,8 +237,10 @@ func SplitText(text string, cfg SplitterConfig) []Chunk {
// Step 1: Find protected spans
protected := protectedSpans(text)
// Step 2: Split non-protected regions by separators, keep protected as atomic units
units := buildUnitsWithProtection(text, protected, separators)
// Step 2: Split non-protected regions by separators, keep protected as atomic units.
// chunkSize is forwarded so splitBySeparators can recursively apply lower-priority
// separators to oversize pieces (Python-parity recursive split).
units := buildUnitsWithProtection(text, protected, separators, chunkSize)
// Step 3: Merge units into chunks with overlap
return mergeUnits(units, chunkSize, chunkOverlap)
@@ -196,7 +251,9 @@ func SplitText(text string, cfg SplitterConfig) []Chunk {
// because downstream merge logic indexes content via []rune slicing.
// If a protected span exceeds maxProtectedSize, it will be forcibly split to prevent
// creating chunks that are too large for downstream processing (e.g., embedding APIs).
func buildUnitsWithProtection(text string, protected []span, separators []string) []splitUnit {
// chunkSize is forwarded to splitBySeparators so recursive splitting can keep pieces
// under the budget when one separator alone leaves a piece oversize.
func buildUnitsWithProtection(text string, protected []span, separators []string, chunkSize int) []splitUnit {
const maxProtectedSize = 7500 // Maximum size for a protected unit (留余量给标题等)
var units []splitUnit
@@ -206,7 +263,7 @@ func buildUnitsWithProtection(text string, protected []span, separators []string
for _, p := range protected {
if p.start > bytePos {
pre := text[bytePos:p.start]
parts := splitBySeparators(pre, separators)
parts := splitBySeparators(pre, separators, chunkSize)
runeOffset := runePos
for _, part := range parts {
partRuneLen := runeLen(part)
@@ -265,7 +322,7 @@ func buildUnitsWithProtection(text string, protected []span, separators []string
if bytePos < len(text) {
remaining := text[bytePos:]
parts := splitBySeparators(remaining, separators)
parts := splitBySeparators(remaining, separators, chunkSize)
runeOffset := runePos
for _, part := range parts {
partRuneLen := runeLen(part)