AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Perf(Text-Splitters): Reduce Repeated List Copying During Chunk Eviction

TextSplitter._merge_splits uses repeated list slicing (current_doc = current_doc[1:]) inside the eviction loop, causing O(k^2) reference copies when chunks contain many small split pieces. The proposed optimization counts leading pieces to remove and slices once, preserving existing semantics.

mediumConfidence 95%LangchainChainsAgentsAffected V1.1.3

Origin Analysis

In _merge_splits, when a chunk exceeds size/overlap limits, the eviction loop removes one piece at a time using current_doc = current_doc[1:]. Each slice copies all remaining references, so clearing k pieces copies roughly k(k-1)/2 references. This is triggered by RecursiveCharacterTextSplitter fallback to individual characters for long separator-free spans.
1. Create a RecursiveCharacterTextSplitter with chunk_size=16000 and chunk_overlap=800. 2. Call split_text on text = 'abcdefghijklmnopqrstuvwxyz' * 8000. 3. Observe median execution time around 1909 ms on CPython 3.13 macOS arm64. After the fix, time drops to about 56 ms, demonstrating the quadratic overhead.

Fixing Code Block

def _merge_splits(self, splits: Iterable[str], separator: str) -> list[str]: separator_len = self._length_function(separator) docs = [] current_doc: list[str] = [] total = 0 for d in splits: _len = self._length_function(d) if total + _len + (separator_len if current_doc else 0) > self._chunk_size: if total > self._chunk_size: logger.warning( f'Created a chunk of size {total}, ' f'which is longer than the specified {self._chunk_size}' ) if current_doc: doc = self._join_docs(current_doc, separator) if doc is not None: docs.append(doc) # Determine how many leading pieces must be removed to meet # overlap/size constraints without slicing on every iteration. remove_count = 0 remaining_len = len(current_doc) while total > self._chunk_overlap or ( total + _len + separator_len > self._chunk_size and total > 0 ): total -= self._length_function(current_doc[remove_count]) + ( separator_len if remaining_len > 1 else 0 ) remaining_len -= 1 remove_count += 1 if remove_count: current_doc = current_doc[remove_count:] current_doc.append(d) total += _len + (separator_len if len(current_doc) > 1 else 0) doc = self._join_docs(current_doc, separator) if doc is not None: docs.append(doc) return docs
The loop now advances an index instead of slicing after each removal. It updates total by subtracting the length of the first remaining piece and, when applicable, the separator length. The separator is included only when more than one piece remains, matching the original len(current_doc) > 1 check. After the loop, a single slice current_doc[remove_count:] replaces all O(k) intermediate copies, reducing reference copies to O(k). The original length-function invocation count and order are preserved because we still call _length_function on the current front element once per removal.

Edge Case Audit

This change preserves the observable behavior for most subclasses, but it does alter the object identity of current_doc after removals: the original created a new list on every iteration, while the new code creates one final slice. Overrides of _join_docs that retain the passed list and expect subsequent mutations via rebinding will see the same semantics, but if they rely on intermediate slice object identities (unlikely and unsupported), behavior could differ. Ensure single-threaded use of a splitter instance; concurrent mutation of chunk_size/chunk_overlap/length_function is unsafe in both old and new code. Rollback is trivial: revert to the original loop. Run the full test suite and, if possible, compare outputs on representative large inputs to confirm identical chunks.

Ecosystem Topology

Agent Frameworks

LangChain, LlamaIndex, and Pydantic

  1. highProperty graph relation keys collide when entity IDs or labels contain underscores
  2. highCodeActAgent drops assistant tool-call metadata during handoff, leaving an orphan tool response
  3. high[Bug]: HierarchicalNodeParser async methods return the documents unsplit
  4. highLLM.predict_and_call fails with ValidationError for non-function-calling models when react_chat_formatter is omitted
  5. highAnthropic streaming server-tool input_json_delta overwrites completed client tool_use arguments due to stale cur_tool_call state