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

HTMLSemanticPreservingSplitter Corrupts Text Containing Literal PRESERVED_<N> Placeholders And Has O(Chunks × Placeholders) Reinsertion

The splitter uses a fixed in-band placeholder string PRESERVED_<n> and later reinserts preserved elements via str.replace over every chunk. If user text contains the same literal string, it is silently replaced, causing content corruption and duplicated preserved content. The reinsertion loop also scales as O(num_chunks × num_preserved_elements).

mediumConfidence 92%LangchainAgentsEmbeddingsChat ModelsAffected V1.1.3

Origin Analysis

Placeholders are generated deterministically as `PRESERVED_<n>` without checking if that sequence occurs in the source text. During reinsertion, each chunk undergoes `text.replace(placeholder, element)` for every placeholder, so any genuine occurrence of the placeholder string in the user text is treated as a marker and overwritten. Additionally, the nested loops over chunks and placeholders cause quadratic-like behavior.
Run: ```python from langchain_text_splitters import HTMLSemanticPreservingSplitter s = HTMLSemanticPreservingSplitter( headers_to_split_on=[("h1", "H1")], elements_to_preserve=["table"], max_chunk_size=1000 ) print(s.split_text("<h1>A</h1><p>see PRESERVED_0 here</p><table><td>SECRET-TABLE</td></table>")) print(s.split_text("<h1>A</h1><table><td>t</td></table><p>PRESERVED_0</p>")) ``` Observed wrong output: `[Document(metadata={'H1': 'A'}, page_content='see SECRET-TABLE here SECRET-TABLE')]` `[Document(metadata={'H1': 'A'}, page_content='t t')]`

Fixing Code Block

import re import secrets # In HTMLSemanticPreservingSplitter._split_html_elements, replace placeholder creation: # placeholders = [f"PRESERVED_{i}" for i in range(len(preserved_elements))] nonce = secrets.token_hex(8) placeholder_prefix = f"PRESERVED_{nonce}_" placeholders = [f"{placeholder_prefix}{i}" for i in range(len(preserved_elements))] # Replace the entire _reinsert_preserved_elements method with: def _reinsert_preserved_elements(self, splits): if not getattr(self, "_preserved_text", None): return splits preserved_map = self._preserved_text pattern = "|".join( re.escape(ph) for ph in sorted(preserved_map, key=len, reverse=True) ) compiled = re.compile(pattern) return [ compiled.sub(lambda m: preserved_map[m.group(0)], text) for text in splits ]
The fix uses a per-call random nonce from `secrets.token_hex` to create placeholders that cannot reasonably occur in user text, eliminating in-band collisions. Reinsertion is done with a single compiled regex alternation over sorted keys (longest first) and a replacement callback, which avoids prefix collisions such as `PRESERVED_1` matching inside `PRESERVED_10` and reduces the operation from O(chunks × placeholders) repeated string scans to one regex pass per chunk.

Edge Case Audit

The random nonce makes the internal placeholder tokens non-deterministic, but final output remains deterministic because placeholders are never exposed. If any external code introspects the splitter state or serializes intermediate placeholders, it may observe changed values. The regex approach constructs a potentially large alternation pattern; for thousands of preserved elements, compiling such a pattern may become heavy, though typical usage is fine. Rollback: revert to deterministic `PRESERVED_{i}` while keeping the regex-based insertion and adding a collision check against source text, or manually escape user text that might contain placeholders.

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