Repository navigation
fix(mindie): decode escaped newlines correctly inside tilde-fenced code blocks - #7285
Conversation
…ding escaped newlines _decode_escaped_newlines_outside_fences only recognised ``` fences, so replies that used ~~~ fences (e.g. code blocks rendered by the model with ~~~python ...) kept literal backslash-n sequences escaped instead of decoding the ones outside fences, and a fence whose closer was split as backslash+tilde across chunks was misread mid-stream. Fixes bytedance#7262. - detect the opening fence with (?:```|~~~) and remember which delimiter the fence was opened with, so closing requires the same delimiter - while inside a fence, hold back a closer that begins with a backslash so a fence ending in backslash+tilde mid-stream is not misread; the held tail is revisited on the next push and normalised on flush - keep backtick hold semantics unchanged
willem-bd
left a comment
There was a problem hiding this comment.
Reviewed at head 789a5d2. Ran the head backend/tests/test_mindie_provider.py against the head tree with PYTHONPATH pinned to it (147 passed) and probed both decoders directly (module __file__ asserted into the head tree).
Relationship to #7264 — duplicates with a conflict (case a). Two independent fixes of the same two functions: both rewrite _decode_escaped_newlines_outside_fences and _EscapedNewlineStreamDecoder.push over the same base lines, so whichever lands second will conflict. Neither rebases on the other (this PR's diff context is still the pre-#7264 code). The streaming halves are semantically equivalent (delimiter latch closable only by the same delimiter; hold-back of backtick/tilde/backslash tails outside fences and closer-char tails inside). The one-shot halves differ, and #7264's current head (dd4575c, updated after review 5608995400) is strictly ahead: an unterminated fence extends to EOF verbatim, so one-shot == streaming there, with explicit one-shot assertions and stream-parity tests for the mixed-delimiter cases.
The gap here (blocking): this PR's one-shot regex pairs only complete fences, while its own streaming decoder keeps everything after any opener verbatim even when the fence is never closed — so the class docstring's "joined stream equals the one-shot decode" invariant breaks for any reply with an unterminated fence preceded by prose (details inline). Empirically: running #7264's head test file against this module gives 4 failed / 150 passed — both test_unterminated_fence_preserves_other_delimiter_pair params and both unterminated test_no_tools_stream_decode_matches_non_streaming params. This PR regresses exactly the property #7264 just fixed and pinned.
Verified working: complete ~~~ fences are protected in both paths; ~~~ opener and closer splits across chunk boundaries are held correctly; the latch resets on a same-delimiter close; no double-decode found; the existing 147 tests pass.
CommonMark note (shared with #7264): delimiter matching is not line-anchored and closing-fence length is ignored, so a bare ~~~ (thematic break) or an inline ~~~ span toggles fence state and suppresses escape decoding between occurrences — pre-existing looseness for backticks now extended to tildes. Acceptable for LLM output; just not CommonMark-strict.
Suggested order: land #7264 first (complete fix, tested). This PR should then rebase onto it; if its helper structure is preferred, land it as a pure refactor of #7264's decoder — with tests added either way (repo policy is TDD for backend changes, and the PR body notes the suite was not run).
| return content | ||
|
|
||
| parts = re.split(r"(```[\s\S]*?```)", content) | ||
| parts = re.split(r"(```[\s\S]*?```|~~~[\s\S]*?~~~)", content) |
There was a problem hiding this comment.
Here the one-shot path protects only complete pairs, but the streaming decoder in this same PR preserves everything after any opener even when the fence is never closed (docstring: "A fence the stream never closes keeps its escapes"). For a reply with an unterminated fence preceded by prose the two entry points disagree — verified at this head:
- one-shot of
p1\n~~~json\ncode\nline(literal\ntwo-char escapes) decodes the escapes after the opener into real newlines - streaming the same reply keeps everything from
~~~on verbatim, escapes intact
so joined stream != one-shot decode — the invariant this class documents, and the exact stream/one-shot parity bug #7264 fixed at dd4575c. Running #7264's head tests against this module: 4 failed / 150 passed (both test_unterminated_fence_preserves_other_delimiter_pair params, both unterminated stream-parity params). The backtick mirror (p + ```a + q\nr) and an unterminated tilde wrapping a complete backtick pair diverge identically. Suggest #7264's rule: earliest delimiter of either kind wins; missing closer keeps the remainder verbatim.
| parts = re.split(r"(```[\s\S]*?```|~~~[\s\S]*?~~~)", content) | ||
| for idx, part in enumerate(parts): | ||
| if part.startswith("```"): | ||
| if part.startswith("```") or part.startswith("~~~"): |
There was a problem hiding this comment.
This filter also skips prose: even-index parts are prose, but when the content begins with an unmatched opener the first prose part itself starts with ``` or ~~~ and is preserved undecoded. Verified here: one-shot of ```a\n~~~x\ny~~~ (unterminated backtick opener, complete tilde pair) returns the prefix's literal \n untouched — only because of this line, not because the regex protected it. That coincidence is the only reason position-0 unterminated fences match streaming today; shift the fence one token later (p + ```a + q\nr) and one-shot decodes q\nr while streaming preserves it. #7264's cursor loop avoids the special case entirely: earliest delimiter wins, unterminated keeps the remainder verbatim.
| _DELIMS = ("```", "~~~") | ||
|
|
||
| def _find_open(self, data: str): | ||
| """Return (index, delimiter) of the earliest fence opener, or (-1, b"").""" |
There was a problem hiding this comment.
Docstring nit: b"" should be "" — the helper returns str, not bytes.
Match one-shot decoding to streaming by choosing the earliest backtick or tilde opener and preserving the remainder when its matching closer is absent. Correct the string-return docstring and cover mixed delimiters across every two-chunk split and character-by-character streaming.
willem-bd
left a comment
There was a problem hiding this comment.
Reviewed at head 11b0491. The blocking parity break from review 5613655843 is fixed at this head: the one-shot decoder now uses the suggested cursor loop — earliest of the triple-backtick/triple-tilde delimiters wins, only the same delimiter closes it, and a missing closer keeps the remainder verbatim — so the documented stream == one-shot invariant now holds for unterminated fences, the prose-filter coincidence thread is moot with the re.split path deleted, and the b"" docstring nit is fixed. Verified behaviorally against 7264@dd4575c: all four prior-thread divergence cases (p1\n~~~json\ncode\nline; unterminated backtick + complete tilde pair; p + backtick-opener + escaped tail; unterminated tilde wrapping a closed backtick pair) now produce identical output from this PR's one-shot, this PR's stream at every two-chunk split and char-by-char, and 7264 — and a 20-case battery plus a 4000-iteration fuzz over fence/escape alphabets found 0 mismatches either within each decoder or across the two PRs. The 16 tests in the new test_mindie_newline_fences.py (exhaustive chunk boundaries x both delimiters x closed/unterminated) pass at this head, and also pass unmodified against 7264's module, so the two implementations are behaviorally interchangeable; the pre-existing suite passes at head (163 total, module __file__ asserted) and both files are clean under ruff format --check/ruff check with backend/ruff.toml.
Landing guidance (updating review 5613655843): 7264 is no longer strictly ahead — the heads are equivalent, so this is now a pure duplicate needing coordination, not a quality race. Land 7264 first per precedent (original PR, minimal two-file footprint), then rebase this PR onto it keeping its unique value: the chunk-boundary sweep test file and the README/CONFIGURATION/models-AGENTS doc updates. The mirror option (land this PR, close 7264 and donate its model-level stream tests) is equally sound behaviorally — but exactly one should land, and whichever lands second must rebase onto the other rather than merge independently.
Keep main's equivalent MindIE fence decoder and retain this branch's exhaustive streaming regression coverage and documentation.
Summary
_decode_escaped_newlines_outside_fenceshard-codes triple-backtick fences, so~`~`tilde fences were invisible to it and every\`inside a~~~block was rewritten to a real newline — both in the one-shot helper and in the streaming decoder. Fixes #7262.(?:\``|~~~)`, and the decoder remembers which delimiter opened the current fence, so a fence is only closed again by that same delimiter (per CommonMark, three tildes do not close three backticks and vice versa).\(e.g. the stream ends with\in ~``~
split as...` + `~~~`) is held back in `_pending` and re-examined on the next push; `flush()` normalises the held tail. Backtick hold-back semantics are unchanged.Offline-verified the exact case from the issue (tilde-fenced block keeps
\`literal, real newlines outside the fence still decode), all previously-passing cases including`-fenced code (no regression), and the backslash-tail hold-back scenario in both orders.ast.parsepasses on the modified file. I could not run the repo suite in my environment — happy for CI to verify.