fix: stop markdown table regex catastrophic backtracking (#2770)
* fix: stop markdown table regex catastrophic backtracking The line_pattern in MarkdownTableUtil used overlapping character classes ([\t ]* and [^|\r\n]*) so a `|`-prefixed line missing its trailing `|` forced the engine to explore an exponential number of backtracking paths, stalling the single-threaded docreader gRPC event loop (100% CPU, health check timeout). Replace whole-text regex substitution with an O(n) line-based pass that only treats rows beginning and ending with `|` as tables, and preserves the previous align_pattern semantics via _is_alignment_row. Fixes #2768 Co-Authored-By: Claude <noreply@anthropic.com> * fix: keep lone pipe rows and normalize CRLF in table formatter A single "|" was rewritten into an empty table row and then dropped. Unify CR/LF before the line scan so exported Markdown tables format without mixed endings. --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: wizardchen <wizardchen@tencent.com>main
parent
aa30ced85f
commit
3842068d22
|
|
@ -27,6 +27,9 @@ from docreader.utils import endecode
|
|||
logger = logging.getLogger(__name__)
|
||||
|
||||
_SEPARATOR_CELL = re.compile(r"^:?-{3,}:?$")
|
||||
# Cells of a GFM alignment row as matched by the previous ``align_pattern``.
|
||||
# Looser than ``_SEPARATOR_CELL``: any non-empty run of ``:``/``-`` qualifies.
|
||||
_ALIGNMENT_CELL = re.compile(r"^[:-]+$")
|
||||
|
||||
|
||||
class MarkdownTableUtil:
|
||||
|
|
@ -48,18 +51,6 @@ class MarkdownTableUtil:
|
|||
| 张三 | 25 | 北京 |
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# Pattern to match alignment row (e.g., |:---|---:|:---:|)
|
||||
self.align_pattern = re.compile(
|
||||
r"^([\t ]*)\|[\t ]*[:-]+(?:[\t ]*\|[\t ]*[:-]+)*[\t ]*\|[\t ]*$",
|
||||
re.MULTILINE,
|
||||
)
|
||||
# Pattern to match regular table rows (header or data)
|
||||
self.line_pattern = re.compile(
|
||||
r"^([\t ]*)\|[\t ]*[^|\r\n]*(?:[\t ]*\|[^|\r\n]*)*\|[\t ]*$",
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _split_row_cells(row_line: str) -> List[str]:
|
||||
"""Split a markdown table row into cells, preserving empty cells."""
|
||||
|
|
@ -83,6 +74,17 @@ class MarkdownTableUtil:
|
|||
cells = cls._split_row_cells(line)
|
||||
return bool(cells) and all(_SEPARATOR_CELL.match(cell) for cell in cells)
|
||||
|
||||
@classmethod
|
||||
def _is_alignment_row(cls, line: str) -> bool:
|
||||
"""Detect a GFM alignment row, matching the previous ``align_pattern``.
|
||||
|
||||
Deliberately looser than :meth:`_is_separator_row` (which needs three
|
||||
or more dashes per cell) so formatting output is unchanged for rows
|
||||
like ``| - | - |``.
|
||||
"""
|
||||
cells = cls._split_row_cells(line)
|
||||
return bool(cells) and all(_ALIGNMENT_CELL.match(cell) for cell in cells)
|
||||
|
||||
@classmethod
|
||||
def _is_empty_row(cls, line: str) -> bool:
|
||||
cells = cls._split_row_cells(line)
|
||||
|
|
@ -128,6 +130,12 @@ class MarkdownTableUtil:
|
|||
def format_table(self, content: str) -> str:
|
||||
"""Format all Markdown tables in the content.
|
||||
|
||||
Line-based and regex-free: only well-formed rows (leading *and*
|
||||
trailing ``|``, with at least one cell) are treated as tables, so a
|
||||
malformed row can never trigger the catastrophic backtracking
|
||||
described in https://github.com/Tencent/WeKnora/issues/2768.
|
||||
CRLF/CR input is normalized to LF before scanning.
|
||||
|
||||
Args:
|
||||
content: Raw Markdown text containing tables
|
||||
|
||||
|
|
@ -135,10 +143,8 @@ class MarkdownTableUtil:
|
|||
Formatted Markdown text with standardized table formatting
|
||||
"""
|
||||
|
||||
def process_align(match: Match[str]) -> str:
|
||||
"""Process alignment row to standardize format."""
|
||||
columns = self._split_row_cells(match.group(0))
|
||||
|
||||
def format_alignment_row(prefix: str, columns: List[str]) -> str:
|
||||
"""Standardize an alignment row, preserving ``:`` markers."""
|
||||
processed = []
|
||||
for col in columns:
|
||||
# Preserve left alignment marker (:---)
|
||||
|
|
@ -146,25 +152,39 @@ class MarkdownTableUtil:
|
|||
# Preserve right alignment marker (---:)
|
||||
right_colon = ":" if col.endswith(":") else ""
|
||||
processed.append(left_colon + "---" + right_colon)
|
||||
|
||||
# Preserve original indentation
|
||||
prefix = match.group(1)
|
||||
return prefix + "| " + " | ".join(processed) + " |"
|
||||
|
||||
def process_line(match: Match[str]) -> str:
|
||||
"""Process regular table row to standardize format."""
|
||||
columns = self._split_row_cells(match.group(0))
|
||||
|
||||
# Preserve original indentation
|
||||
prefix = match.group(1)
|
||||
def format_data_row(prefix: str, columns: List[str]) -> str:
|
||||
"""Standardize a header or data row."""
|
||||
return prefix + "| " + " | ".join(columns) + " |"
|
||||
|
||||
formatted_content = content
|
||||
# First format regular rows (header and data)
|
||||
formatted_content = self.line_pattern.sub(process_line, formatted_content)
|
||||
# Then format alignment rows (must be done after to avoid conflicts)
|
||||
formatted_content = self.align_pattern.sub(process_align, formatted_content)
|
||||
return self.normalize_spurious_table_prefixes(formatted_content)
|
||||
# Unify CRLF/CR first so a trailing ``\r`` left by split("\n") cannot
|
||||
# be mistaken for "ends with |" via str.rstrip(), and so we do not
|
||||
# emit mixed line endings. Trailing newlines are preserved.
|
||||
unified = content.replace("\r\n", "\n").replace("\r", "\n")
|
||||
lines = unified.split("\n")
|
||||
out: List[str] = []
|
||||
for line in lines:
|
||||
stripped = line.lstrip(" \t")
|
||||
# A row must both begin and end with a pipe to be a table row;
|
||||
# anything else is passed through unchanged. This also keeps
|
||||
# unclosed rows (the old regex's exponential worst case) cheap.
|
||||
# rstrip only spaces/tabs (old ``\|[\t ]*$``), not all whitespace.
|
||||
if stripped.startswith("|") and line.rstrip(" \t").endswith("|"):
|
||||
prefix = line[: len(line) - len(stripped)]
|
||||
columns = self._split_row_cells(line)
|
||||
# Lone "|" is not a table row: the old line_pattern required
|
||||
# opening *and* closing pipes. Formatting it to "| |" would
|
||||
# let normalize_spurious_table_prefixes drop the line.
|
||||
if not columns:
|
||||
out.append(line)
|
||||
elif self._is_alignment_row(line):
|
||||
out.append(format_alignment_row(prefix, columns))
|
||||
else:
|
||||
out.append(format_data_row(prefix, columns))
|
||||
else:
|
||||
out.append(line)
|
||||
return self.normalize_spurious_table_prefixes("\n".join(out))
|
||||
|
||||
@staticmethod
|
||||
def _self_test():
|
||||
|
|
|
|||
|
|
@ -54,6 +54,56 @@ class TestMarkdownTableUtil(unittest.TestCase):
|
|||
normalized,
|
||||
)
|
||||
|
||||
def test_malformed_unclosed_row_is_passthrough(self):
|
||||
"""An unclosed ``|``-prefixed row must not hang the process.
|
||||
|
||||
Regression for Tencent/WeKnora#2768: the old line_pattern explored an
|
||||
exponential number of backtracking paths on such rows and stalled the
|
||||
single-threaded docreader event loop.
|
||||
"""
|
||||
line = "| " + " | ".join(f"col{i}" for i in range(100)) + " unclosed"
|
||||
formatted = MarkdownTableUtil().format_table(line)
|
||||
self.assertEqual(formatted, line)
|
||||
|
||||
def test_long_valid_table_formats(self):
|
||||
"""A long, well-formed table still formats in linear time."""
|
||||
header = "| " + " | ".join(f"c{i}" for i in range(200)) + " |"
|
||||
sep = "| " + " | ".join("---" for _ in range(200)) + " |"
|
||||
row = "| " + " | ".join(f"v{i}" for i in range(200)) + " |"
|
||||
formatted = MarkdownTableUtil().format_table("\n".join([header, sep, row]))
|
||||
self.assertIn("| c0 | c1 |", formatted)
|
||||
self.assertIn("| c199 |", formatted)
|
||||
self.assertIn("| --- |", formatted)
|
||||
self.assertIn("| v0 | v1 |", formatted)
|
||||
self.assertIn("| v199 |", formatted)
|
||||
|
||||
def test_lone_pipe_is_passthrough(self):
|
||||
"""A single-pipe line is not a table row and must not be deleted."""
|
||||
self.assertEqual(MarkdownTableUtil().format_table("|"), "|")
|
||||
self.assertEqual(MarkdownTableUtil().format_table(" | "), " | ")
|
||||
|
||||
def test_lone_pipe_above_table_is_kept(self):
|
||||
raw = "|\n| a | b |\n| --- | --- |\n| 1 | 2 |"
|
||||
formatted = MarkdownTableUtil().format_table(raw)
|
||||
self.assertEqual(formatted.split("\n")[0], "|")
|
||||
self.assertIn("| a | b |", formatted)
|
||||
self.assertIn("| 1 | 2 |", formatted)
|
||||
|
||||
def test_alignment_colons_preserved(self):
|
||||
raw = "| a | b | c |\n| :---------- | -------: | :------: |\n| 1 | 2 | 3 |"
|
||||
formatted = MarkdownTableUtil().format_table(raw)
|
||||
self.assertIn("| :--- | ---: | :---: |", formatted)
|
||||
|
||||
def test_crlf_table_formats_without_mixed_endings(self):
|
||||
raw = "# Title\r\n\r\n|Name|Age|\r\n|---|---|\r\n|John|30|\r\n\r\nparagraph\r\n"
|
||||
formatted = MarkdownTableUtil().format_table(raw)
|
||||
self.assertIn("| Name | Age |", formatted)
|
||||
self.assertIn("| --- | --- |", formatted)
|
||||
self.assertIn("| John | 30 |", formatted)
|
||||
self.assertIn("paragraph", formatted)
|
||||
self.assertNotIn("\r", formatted)
|
||||
self.assertTrue(formatted.endswith("\n"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
Loading…
Reference in New Issue