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,8 +82,9 @@ func splitByHeuristicsImpl(text string, cfg SplitterConfig) []Chunk {
if accumulated > cfg.ChunkSize && curEnd-chunkStart >= minChunkSize {
// Flush accumulated content as a chunk, restart at curEnd.
out = appendChunk(out, runes, chunkStart, curEnd, &seq)
// Apply overlap by shifting chunkStart back a bit.
chunkStart = applyOverlap(curEnd, cfg.ChunkOverlap)
// Snap overlap start to the nearest semantic boundary or line
// break instead of slicing mid-line / mid-word.
chunkStart = applyOverlapAligned(runes, curEnd, cfg.ChunkOverlap, bounds)
}
curEnd = nextEnd
}
@@ -227,16 +228,42 @@ func appendOversizeBlock(out []Chunk, runes []rune, start, end int, cfg Splitter
return out
}
// applyOverlap shifts the next chunk's start back by `overlap` runes (but
// not before zero) so consecutive chunks share content. Mirrors the
// computeOverlap behavior of the legacy splitter.
func applyOverlap(curEnd, overlap int) int {
// applyOverlapAligned returns the rune offset where the next chunk should
// start. The target is `curEnd - overlap`, but we snap to the nearest
// preceding boundary (within 2x overlap) or, failing that, the previous
// newline so chunks don't begin mid-line / mid-word. Falls back to the raw
// target only if neither option is available.
func applyOverlapAligned(runes []rune, curEnd, overlap int, bounds []boundary) int {
if overlap <= 0 {
return curEnd
}
start := curEnd - overlap
if start < 0 {
start = 0
target := curEnd - overlap
if target < 0 {
target = 0
}
return start
// Allowed search window: [curEnd - 2*overlap, curEnd]
windowStart := curEnd - 2*overlap
if windowStart < 0 {
windowStart = 0
}
// Prefer a semantic boundary inside the window.
bestBound := -1
for _, b := range bounds {
if b.runeStart >= windowStart && b.runeStart <= curEnd && b.runeStart > bestBound {
bestBound = b.runeStart
}
}
if bestBound >= 0 {
return bestBound
}
// Fallback: scan backwards from `target` to the previous newline, but
// not past windowStart so we keep the overlap roughly the right size.
for i := target; i > windowStart && i < len(runes); i-- {
if runes[i] == '\n' {
return i + 1
}
}
return target
}