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