[BUG] HierarchicalDocumentSplitter emits empty segments for whitespace-only buffers
Describe the bug
When a HierarchicalDocumentSplitter (e.g. DocumentByCharacterSplitter) is configured with a small maxSegmentSizeInChars, whitespace between parts is trimmed away when the segment builder flushes. Two problems follow:
- If the buffer becomes empty after trimming (whitespace-only buffer), the flush emits an empty
TextSegment. - Consecutive whitespace inside the text similarly yields empty segments between the real ones.
Expected behavior
Whitespace-only buffers should be skipped: no empty segments are emitted, and no exception is thrown. Splitting "a b" with DocumentByCharacterSplitter(1, 0) should yield exactly ["a", "b"].
Actual behavior
Splitting "a b" with DocumentByCharacterSplitter(1, 0) produces an empty leading segment (for " a" a leading empty segment as well). Consecutive whitespace inside the text ("ab cd" with size 2) similarly yields empty segments between the real ones.
Minimal reproducible example
DocumentSplitter splitter = new DocumentByCharacterSplitter(1, 0);
List<TextSegment> segments = splitter.split(Document.from("a b"));
// expected: ["a", "b"], actual: ["", "a", "b"]Environment
- langchain4j version: current main
- Java version: 17
I have a fix with unit tests ready and will open a PR shortly.
Source: langchain4j/langchain4j