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
@@ -74,35 +74,34 @@ func splitByHeadingsImpl(text string, cfg SplitterConfig) []Chunk {
}
bcLen := utf8.RuneCountInString(breadcrumb)
// Reserve some headroom (breadcrumb + 2 newlines) when fitting a section.
// Single-chunk section: emit as-is, breadcrumb tracked separately.
// The breadcrumb is delivered via Chunk.ContextHeader (not Content)
// to preserve End-Start == len(Content) invariants relied on by
// document reconstruction (knowledge.go:2278+).
if bcLen+2+secLen <= cfg.ChunkSize {
content := prependBreadcrumb(sectionContent, breadcrumb)
out = append(out, Chunk{
Content: content,
Seq: seq,
Start: b.runeStart,
End: endRune,
Content: sectionContent,
ContextHeader: breadcrumb,
Seq: seq,
Start: b.runeStart,
End: endRune,
})
seq++
continue
}
// Section too large for one chunk: defer to the legacy splitter for
// inner segmentation, then prepend the breadcrumb to every sub-chunk.
// Reduce the inner budget by the breadcrumb length so the final
// chunk (incl. breadcrumb) still fits under cfg.ChunkSize.
innerCfg := cfg
if bcLen > 0 && innerCfg.ChunkSize > bcLen+10 {
innerCfg.ChunkSize -= bcLen + 2
}
subChunks := SplitText(sectionContent, innerCfg)
// Section too large: defer to the legacy splitter for inner
// segmentation. Sub-chunks inherit the same breadcrumb via
// ContextHeader. We do NOT shrink the inner ChunkSize budget here
// because the breadcrumb no longer counts against Content size.
subChunks := SplitText(sectionContent, cfg)
for _, sub := range subChunks {
content := prependBreadcrumb(sub.Content, breadcrumb)
out = append(out, Chunk{
Content: content,
Seq: seq,
Start: b.runeStart + sub.Start,
End: b.runeStart + sub.End,
Content: sub.Content,
ContextHeader: breadcrumb,
Seq: seq,
Start: b.runeStart + sub.Start,
End: b.runeStart + sub.End,
})
seq++
}
@@ -189,16 +188,3 @@ func observeSubHeadings(runes []rune, primaryLevel int, h *HeadingHierarchy) {
}
}
// prependBreadcrumb attaches the breadcrumb to content unless content
// already begins with that exact breadcrumb (avoid duplication when a
// section's first line is itself the section heading).
func prependBreadcrumb(content, breadcrumb string) string {
if breadcrumb == "" {
return content
}
trimmed := strings.TrimLeft(content, " \t\r\n")
if strings.HasPrefix(trimmed, breadcrumb) {
return content
}
return breadcrumb + "\n\n" + content
}