[BUG] HierarchicalDocumentSplitter emits empty segments for whitespace-only buffers

Author: Ayomipo18Created Sep 26, 2026Updated Sep 26, 2026

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:

  1. If the buffer becomes empty after trimming (whitespace-only buffer), the flush emits an empty TextSegment.
  2. 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

java
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.