From 02f819038ca73697f9cf493e24dfbd11191f9c25 Mon Sep 17 00:00:00 2001 From: berce <75228263+bercedev@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:17:35 +0300 Subject: [PATCH] fix: mask code and math spans in one pass before the CJK emphasis repair Masking fenced code, math and inline code in three passes let the math pattern match $ signs inside inline code, and the inline code pass then wrapped that placeholder in a new one, so a placeholder leaked into the stored answer. Match all three in one left-to-right pass and skip the repair when the text already has a NUL. --- deeptutor/services/session/_turn_runtime_shared.py | 11 ++++++++--- tests/services/session/test_turn_runtime.py | 13 +++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/deeptutor/services/session/_turn_runtime_shared.py b/deeptutor/services/session/_turn_runtime_shared.py index ad171ab66..ff1db47a5 100644 --- a/deeptutor/services/session/_turn_runtime_shared.py +++ b/deeptutor/services/session/_turn_runtime_shared.py @@ -112,6 +112,10 @@ _INLINE_CODE_SPAN_RE = re.compile(r"`[^`\n]*`") _MATH_SPAN_RE = re.compile( r"\\\[[\s\S]*?\\\]|\\\([\s\S]*?\\\)|\$\$[\s\S]*?\$\$|\$(?!\s)(?:\\.|[^$\n])*?(? bool: @@ -234,15 +238,16 @@ def _repair_chinese_emphasis_for_persistence(content: str, language: str) -> str """ if not content or not str(language or "").lower().startswith("zh"): return content + # NUL delimits the placeholders below; text that already has one is left as is. + if "\x00" in content: + return content protected: list[str] = [] def mask(match: re.Match[str]) -> str: protected.append(match.group(0)) return f"\x00CJK_PROTECTED_{len(protected) - 1}\x00" - masked = _FENCED_CODE_BLOCK_RE.sub(mask, content) - masked = _MATH_SPAN_RE.sub(mask, masked) - masked = _INLINE_CODE_SPAN_RE.sub(mask, masked) + masked = _PROTECTED_SPAN_RE.sub(mask, content) repaired = "\n".join(_repair_chinese_emphasis_line(line) for line in masked.split("\n")) return re.sub( r"\x00CJK_PROTECTED_(\d+)\x00", diff --git a/tests/services/session/test_turn_runtime.py b/tests/services/session/test_turn_runtime.py index 995908f84..d5a089fce 100644 --- a/tests/services/session/test_turn_runtime.py +++ b/tests/services/session/test_turn_runtime.py @@ -98,6 +98,19 @@ class TestAssemblePersistedAnswer: content = "`中文*,重点*`\n$中文*,重点*$\n中文***,重点***内容" assert _repair_chinese_emphasis_for_persistence(content, "zh") == content + def test_dollar_signs_in_code_and_literal_placeholders_survive(self) -> None: + inputs = [ + "PHP 对象:`$b = $a`;PHP 数组:`$b = $a`。", + "```php\n$b = $a;\n```\n价格 $5,`$c = $d` 与 $x^2$", + "原文 \x00CJK_PROTECTED_0\x00 与 `代码`", + ] + for content in inputs: + assert _repair_chinese_emphasis_for_persistence(content, "zh") == content + assert ( + _repair_chinese_emphasis_for_persistence("`$b = $a`,中文*,重点*内容`$c`", "zh") + == "`$b = $a`,中文 *,重点* 内容`$c`" + ) + def test_continuation_preserves_exact_visible_boundary(self) -> None: segments = [ ("round-part-1", "Part one. "),