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:
@@ -48,6 +48,49 @@ func TestSplit_AutoStrategy_PicksHeadingForMarkdownDoc(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestSplit_PreservesPositionInvariantAcrossTiers ensures every chunk's
|
||||
// (Start, End, Content) triple stays consistent — End-Start must equal the
|
||||
// rune length of Content, and runes[Start:End] must equal Content. This is
|
||||
// the contract that knowledge.go:2278+ relies on for document reconstruction
|
||||
// during summary generation.
|
||||
func TestSplit_PreservesPositionInvariantAcrossTiers(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"heading-tier": "# Top\nintro paragraph here.\n\n## Section A\nbody A here.\n\n## Section B\nbody B here.\n\n## Section C\nbody C.",
|
||||
"heuristic-tier": strings.Repeat("Kapitel 1: Einleitung\n", 1) + strings.Repeat("Beispieltext. ", 50) +
|
||||
"\n\n" + strings.Repeat("Kapitel 2: Hauptteil\n", 1) + strings.Repeat("Mehr Text. ", 50),
|
||||
"recursive-tier": strings.Repeat("plain prose without structure. ", 100),
|
||||
}
|
||||
cfg := SplitterConfig{ChunkSize: 300, ChunkOverlap: 30, Separators: []string{"\n\n", "\n", "。", ". "}, Strategy: StrategyAuto}
|
||||
|
||||
for name, doc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
runes := []rune(doc)
|
||||
chunks := Split(doc, cfg)
|
||||
if len(chunks) == 0 {
|
||||
t.Fatal("expected chunks")
|
||||
}
|
||||
for i, c := range chunks {
|
||||
contentRuneLen := len([]rune(c.Content))
|
||||
spanLen := c.End - c.Start
|
||||
if spanLen != contentRuneLen {
|
||||
t.Errorf("chunk %d: End(%d)-Start(%d)=%d but Content has %d runes:\n%q",
|
||||
i, c.End, c.Start, spanLen, contentRuneLen, c.Content)
|
||||
}
|
||||
if c.Start < 0 || c.End > len(runes) {
|
||||
t.Errorf("chunk %d: position out of range Start=%d End=%d totalRunes=%d",
|
||||
i, c.Start, c.End, len(runes))
|
||||
}
|
||||
if c.Start >= 0 && c.End <= len(runes) {
|
||||
sliced := string(runes[c.Start:c.End])
|
||||
if sliced != c.Content {
|
||||
t.Errorf("chunk %d: runes[Start:End] differs from Content", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitParentChild_LegacyStrategy(t *testing.T) {
|
||||
text := strings.Repeat("This is a sentence. Another one.\n\n", 50)
|
||||
parentCfg := SplitterConfig{ChunkSize: 400, ChunkOverlap: 40, Strategy: StrategyLegacy}
|
||||
|
||||
Reference in New Issue
Block a user