Skip to content

fix: try_fix_yaml failed on snippets with prefix or yml - #2097

Merged
naorpeled merged 4 commits into
The-PR-Agent:mainfrom
XinyuWuu:fix_yaml
May 14, 2026
Merged

naorpeled merged 4 commits into
The-PR-Agent:mainfrom
XinyuWuu:fix_yaml

Conversation

@XinyuWuu

@XinyuWuu XinyuWuu commented Nov 7, 2025 •

Copy link
Copy Markdown
Contributor

User description

LLMs might return code wrapped with ``` or ```yml.


PR Type

Bug fix


Description

  • Enhanced try_fix_yaml to handle code snippets with \``, ```yaml, or ```yml` prefixes

  • Updated regex pattern to match optional language identifiers (yaml/yml)

  • Added dynamic prefix detection to correctly remove code fence markers

  • Extended test coverage with three snippet format variations


Diagram Walkthrough

flowchart LR
  A["Code snippet with prefix"] --> B["Updated regex pattern"]
  B --> C["Detect prefix type"]
  C --> D["Remove correct prefix"]
  D --> E["Parse YAML successfully"]
Loading

File Walkthrough

Relevant files
Bug fix
utils.py
Enhance regex and prefix handling for code fences               

pr_agent/algo/utils.py

  • Updated snippet_pattern regex from r'yaml([\s\S]*?)(?=\s*$|")' to
    r'(yaml|yml)?([\s\S]*?)(?=\s*$|")' to match optional language
    identifiers
  • Added dynamic prefix detection logic that determines whether snippet
    starts with \\\yaml, \\\yml, or plain \\\
  • Modified removeprefix() call to use detected prefix instead of
    hardcoded
    'yaml'
+7/-2     
Tests
test_try_fix_yaml.py
Add test cases for multiple code fence formats                     

tests/unittest/test_try_fix_yaml.py

  • Renamed original test variable from review_text to review_text1 for
    clarity
  • Added review_text2 test case with \\\yml prefix format
  • Added review_text3 test case with plain \\\ prefix format
  • Updated assertions to test all three snippet format variations
+20/-2   

more robust try_fix_yaml
test extract snippet with prefix "```" or "```yml"
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 7, 2025 •

Copy link
Copy Markdown
Contributor

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
⚪
ReDoS vulnerability

Description: The regex pattern r'(yaml|yml)?([\s\S]?)(?=\s$|")' is vulnerable to ReDoS (Regular
Expression Denial of Service) attacks due to nested quantifiers ([\s\S]*?) combined with
lookahead, which can cause catastrophic backtracking on malicious input with many
backticks.
utils.py [815-815]

Referred Code
snippet_pattern = r'```(yaml|yml)?([\s\S]*?)```(?=\s*$|")'
snippet = re.search(snippet_pattern, '\n'.join(response_text_lines_copy))
Ticket Compliance
⚪
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
⚪
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Consistent Naming Conventions

Objective: All new variables, functions, and classes must follow the project's established naming
standards

Status: Passed

No Dead or Commented-Out Code

Objective: Keep the codebase clean by ensuring all submitted code is active and necessary

Status: Passed

Single Responsibility for Functions

Objective: Each function should have a single, well-defined responsibility

Status: Passed

When relevant, utilize early return

Objective: In a code snippet containing multiple logic conditions (such as 'if-else'), prefer an
early return on edge cases than deep nesting

Status: Passed

⚪
Robust Error Handling

Objective: Ensure potential errors and edge cases are anticipated and handled gracefully throughout
the code

Status:
Bare except clause: The code uses bare except: clauses without specifying exception types or logging errors,
which may silently suppress important exceptions.

Referred Code
try:
    data = yaml.safe_load(snippet_text.removeprefix(prefix).rstrip('`'))
    get_logger().info(f"Successfully parsed AI prediction after extracting yaml snippet")
    return data
except:
    pass
  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 7, 2025 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to 46f889b

CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Use captured regex groups correctly
Suggestion Impact:Updated the extraction logic to use the regex capture group for the snippet body (group(2)) and removed the manual prefix detection and string stripping before parsing with yaml.safe_load.

code diff:

@@ -817,14 +817,10 @@
     if not snippet:
         snippet = re.search(snippet_pattern, response_text_original) # before we removed the "```"
     if snippet:
-        snippet_text = snippet.group()
-        prefix = (
-            '```yaml'
-            if snippet_text.startswith('```yaml')
-            else ('```yml' if snippet_text.startswith('```yml') else '```')
-        )
+        # group(2) is the snippet body, without the ``` fences or the optional yaml/yml language identifier
+        snippet_text = snippet.group(2)
         try:
-            data = yaml.safe_load(snippet_text.removeprefix(prefix).rstrip('`'))
+            data = yaml.safe_load(snippet_text)
             get_logger().info(f"Successfully parsed AI prediction after extracting yaml snippet")

Refactor the YAML extraction logic to use regex capture groups to get the
content directly, rather than getting the full match and manually stripping
prefixes and suffixes.

pr_agent/algo/utils.py [815-825]

 snippet_pattern = r'```(yaml|yml)?([\s\S]*?)```(?=\s*$|")'
 snippet = re.search(snippet_pattern, '\n'.join(response_text_lines_copy))
 if not snippet:
     snippet = re.search(snippet_pattern, response_text_original)
 if snippet:
-    snippet_text = snippet.group()
-    prefix = (
-        '```yaml'
-        if snippet_text.startswith('```yaml')
-        else ('```yml' if snippet_text.startswith('```yml') else '```')
-    )
+    lang_identifier = snippet.group(1) or ''
+    yaml_content = snippet.group(2)
+    try:
+        data = yaml.safe_load(yaml_content)
+        get_logger().info(f"Successfully parsed AI prediction after extracting yaml snippet")
+        return data
+    except:
+        pass

[Suggestion processed]

Suggestion importance[1-10]: 6

__

Why: The suggestion offers a cleaner and more direct way to extract YAML content by using regex capture groups, which simplifies the code and improves readability over the current string manipulation approach.

Low
Learned
best practice
✅ Capture exception object for logging
Suggestion Impact:Replaced the bare `except:` with `except Exception as e:` and added a debug log that includes the exception details when YAML parsing fails.

code diff:

-        except:
-            pass
+        except Exception as e:
+            get_logger().debug(f"Failed to parse AI prediction after extracting yaml snippet: {e}")

Capture the exception object in the except block to enable proper error logging.
Replace bare 'except:' with 'except Exception as e:' and log the error for
debugging purposes.

pr_agent/algo/utils.py [826-831]

 try:
     data = yaml.safe_load(snippet_text.removeprefix(prefix).rstrip('`'))
     get_logger().info(f"Successfully parsed AI prediction after extracting yaml snippet")
     return data
-except:
+except Exception as e:
+    get_logger().debug(f"Failed to parse yaml snippet: {e}")
     pass

[Suggestion processed]

Suggestion importance[1-10]: 6

__

Why:
Relevant best practice - When catching exceptions in try-except blocks, always capture the exception object using 'as e' syntax to enable proper error logging and debugging.

Low
  • Update
  • Author self-review: I have reviewed the PR code suggestions, and addressed the relevant ones.

Previous suggestions

✅ Suggestions up to commit 46f889b
CategorySuggestion                                                                                                                                    Impact
General
✅ Simplify code by using regex group
Suggestion Impact:The commit removed manual prefix detection and removeprefix/rstrip logic, and now extracts the YAML body via snippet.group(2) and passes it directly to yaml.safe_load.

code diff:

-        snippet_text = snippet.group()
-        prefix = (
-            '```yaml'
-            if snippet_text.startswith('```yaml')
-            else ('```yml' if snippet_text.startswith('```yml') else '```')
-        )
+        # group(2) is the snippet body, without the ``` fences or the optional yaml/yml language identifier
+        snippet_text = snippet.group(2)
         try:
-            data = yaml.safe_load(snippet_text.removeprefix(prefix).rstrip('`'))
+            data = yaml.safe_load(snippet_text)
             get_logger().info(f"Successfully parsed AI prediction after extracting yaml snippet")

Refactor the YAML parsing logic to directly use the second capture group from
the snippet_pattern regex, which simplifies the code by removing manual prefix
and suffix stripping.

pr_agent/algo/utils.py [820-831]

-snippet_text = snippet.group()
-prefix = (
-    '```yaml'
-    if snippet_text.startswith('```yaml')
-    else ('```yml' if snippet_text.startswith('```yml') else '```')
-)
 try:
-    data = yaml.safe_load(snippet_text.removeprefix(prefix).rstrip('`'))
+    # The YAML content is in the second capture group of the regex
+    yaml_content = snippet.group(2)
+    data = yaml.safe_load(yaml_content)
     get_logger().info(f"Successfully parsed AI prediction after extracting yaml snippet")
     return data
 except:
     pass
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that using the second capture group from the regex is a more direct and robust way to extract the YAML content, simplifying the code and improving readability.

Medium
Learned
best practice
✅ Capture and log exceptions properly
Suggestion Impact:The code now catches exceptions as `Exception as e` instead of a bare `except:` and logs a debug message including the exception, improving diagnosability of YAML parsing failures.

code diff:

         try:
-            data = yaml.safe_load(snippet_text.removeprefix(prefix).rstrip('`'))
+            data = yaml.safe_load(snippet_text)
             get_logger().info(f"Successfully parsed AI prediction after extracting yaml snippet")
             return data
-        except:
-            pass
+        except Exception as e:
+            get_logger().debug(f"Failed to parse AI prediction after extracting yaml snippet: {e}")
 

Capture the exception into a variable and log it for debugging. Replace bare
except: with except Exception as e: and log the error details to help diagnose
parsing failures.

pr_agent/algo/utils.py [826-831]

 try:
     data = yaml.safe_load(snippet_text.removeprefix(prefix).rstrip('`'))
     get_logger().info(f"Successfully parsed AI prediction after extracting yaml snippet")
     return data
-except:
+except Exception as e:
+    get_logger().debug(f"Failed to parse yaml snippet: {str(e)}")
     pass
Suggestion importance[1-10]: 6

__

Why:
Relevant best practice - Improve exception handling by preserving context (raise from), capturing exceptions into variables, sanitizing logs to avoid secrets leakage, and converting returns of exception objects into proper raises.

Low

@DanaFineTLV

Copy link
Copy Markdown
Collaborator

Hi @LawrenceMantin
Apologies for the delayed response, and thank you for your questions and contributions 🙏

We offer a free Qodo version for free-trial for developers [www.qodo.ai],
and offer a free version of our paid product for open-source projects [https://www.qodo.ai/solutions/open-source/]. 🚀

We’re currently restructuring the project and contributing it to the community, with plans to move it under a foundation.
If you’re interested in taking part, please reach out to me at dana.f@qodo.ai
or via LinkedIn

We’ll also be launching an Ambassador Program soon — if you’d like to join, stay tuned for more details!

@hussam789

Copy link
Copy Markdown
Contributor

/improve

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Persistent suggestions updated to latest commit 46f889b

@naorpeled

Copy link
Copy Markdown
Member

/agentic_review

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jan 31, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0)

Grey Divider


Remediation recommended

1. snippet_pattern matches non-YAML fences ✓ Resolved 📘 Rule violation ≡ Correctness
Description
In try_fix_yaml(), the updated fenced-snippet regex is overly permissive: because (yaml|yml)? is
optional (and the pattern doesn’t enforce a newline boundary after the opening fence), it can match
non‑YAML fenced blocks like ``python/``diff and parse/return incorrect data instead of falling
through to later YAML-repair strategies. Additionally, since the code uses re.search to take only
the first match, an earlier non‑YAML fence can cause the function to miss a later valid YAML fence
and fail to parse it.
Code

pr_agent/algo/utils.py[R815-824]

+    snippet_pattern = r'```(yaml|yml)?([\s\S]*?)```(?=\s*$|")'
snippet = re.search(snippet_pattern, '\n'.join(response_text_lines_copy))
if not snippet:
  snippet = re.search(snippet_pattern, response_text_original) # before we removed the "```"
if snippet:
-        snippet_text = snippet.group()
+        # group(2) is the snippet body, without the ``` fences or the optional yaml/yml language identifier
+        snippet_text = snippet.group(2)
  try:
-            data = yaml.safe_load(snippet_text.removeprefix('```yaml').rstrip('`'))
+            data = yaml.safe_load(snippet_text)
      get_logger().info(f"Successfully parsed AI prediction after extracting yaml snippet")
Evidence
The cited snippet_pattern makes the yaml/yml identifier optional, then takes the captured snippet
body (via group(2) in the current structure) and passes it directly to yaml.safe_load(), so
fences such as ``python/`diff can still be matched by letting (yaml|yml)?` match empty and
treating the language identifier as part of the body; this may even parse as a YAML scalar without
raising, producing silent incorrect results. Because the implementation uses re.search, only the
first fenced block is considered, so if a non-YAML fenced block appears before a valid YAML block,
the function can latch onto the wrong fence and never attempt the later correct YAML snippet; the
note that the repository generates fenced diff blocks elsewhere further supports that non-YAML
fences are common in this codebase’s markdown and could precede YAML in mixed responses.

Rule 3: Robust Error Handling
pr_agent/algo/utils.py[814-825]
pr_agent/tools/pr_code_suggestions.py[839-846]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`try_fix_yaml()`’s fenced-snippet extraction regex is too permissive: it matches any triple-backtick code fence even when a non-YAML language identifier is present (e.g., ```python / ```diff) because `(yaml|yml)?` is optional and there is no strict newline/whitespace boundary after the opening fence. This can silently parse/return incorrect data (e.g., as a YAML scalar) and, because `re.search` returns only the first match, a non-YAML fence earlier in the text can prevent extracting/parsing a later valid YAML fence.
## Issue Context
This code path is a fallback for parsing LLM responses as YAML and should only target code fences that are either untagged (```\n) or explicitly YAML (```yaml / ```yml), rather than matching arbitrary fenced blocks and accidentally capturing the language identifier into the snippet body.
## Fix Focus Areas
- pr_agent/algo/utils.py[814-825]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Bare except block at line 830 ✓ Resolved 📘 Rule violation ≡ Correctness
Description
• The try-except block at line 826-831 uses a bare except: clause without capturing the exception
object • This prevents proper error logging and debugging when YAML parsing fails • The compliance
rule requires exception objects to be captured using 'as e' syntax for proper error handling
Code

pr_agent/algo/utils.py[R826-830]

try:
-            data = yaml.safe_load(snippet_text.removeprefix('```yaml').rstrip('`'))
+            data = yaml.safe_load(snippet_text.removeprefix(prefix).rstrip('`'))
    get_logger().info(f"Successfully parsed AI prediction after extracting yaml snippet")
    return data
except:
Evidence
The code at line 826-831 contains a try-except block that catches exceptions without capturing them.
According to PR Compliance ID 6, all except blocks that reference or could benefit from referencing
the exception object should use 'as e' syntax. While this specific block doesn't reference the
exception, the broader function context shows error logging is used elsewhere (line 828), suggesting
exception details would be valuable for debugging YAML parsing failures.

pr_agent/algo/utils.py[826-831]
Best Practice: Learned patterns

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The try-except block uses a bare `except:` clause without capturing the exception object, preventing proper error logging and debugging.
## Issue Context
This is part of a YAML parsing fallback mechanism in the `try_fix_yaml` function. The function attempts multiple strategies to parse YAML, and capturing exception details would help diagnose why specific parsing attempts fail.
## Fix Focus Areas
- pr_agent/algo/utils.py[826-831]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Previous review results

Review updated until commit d2070e2

Results up to commit N/A


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)


Remediation recommended
1. snippet_pattern matches non-YAML fences ✓ Resolved 📘 Rule violation ≡ Correctness
Description
In try_fix_yaml(), the updated fenced-snippet regex is overly permissive: because (yaml|yml)? is
optional (and the pattern doesn’t enforce a newline boundary after the opening fence), it can match
non‑YAML fenced blocks like ``python/``diff and parse/return incorrect data instead of falling
through to later YAML-repair strategies. Additionally, since the code uses re.search to take only
the first match, an earlier non‑YAML fence can cause the function to miss a later valid YAML fence
and fail to parse it.
Code

pr_agent/algo/utils.py[R815-824]

+    snippet_pattern = r'```(yaml|yml)?([\s\S]*?)```(?=\s*$|")'
snippet = re.search(snippet_pattern, '\n'.join(response_text_lines_copy))
if not snippet:
    snippet = re.search(snippet_pattern, response_text_original) # before we removed the "```"
if snippet:
-        snippet_text = snippet.group()
+        # group(2) is the snippet body, without the ``` fences or the optional yaml/yml language identifier
+        snippet_text = snippet.group(2)
    try:
-            data = yaml.safe_load(snippet_text.removeprefix('```yaml').rstrip('`'))
+            data = yaml.safe_load(snippet_text)
        get_logger().info(f"Successfully parsed AI prediction after extracting yaml snippet")
Evidence
The cited snippet_pattern makes the yaml/yml identifier optional, then takes the captured snippet
body (via group(2) in the current structure) and passes it directly to yaml.safe_load(), so
fences such as ``python/`diff can still be matched by letting (yaml|yml)?` match empty and
treating the language identifier as part of the body; this may even parse as a YAML scalar without
raising, producing silent incorrect results. Because the implementation uses re.search, only the
first fenced block is considered, so if a non-YAML fenced block appears before a valid YAML block,
the function can latch onto the wrong fence and never attempt the later correct YAML snippet; the
note that the repository generates fenced diff blocks elsewhere further supports that non-YAML
fences are common in this codebase’s markdown and could precede YAML in mixed responses.

Rule 3: Robust Error Handling
pr_agent/algo/utils.py[814-825]
pr_agent/tools/pr_code_suggestions.py[839-846]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`try_fix_yaml()`’s fenced-snippet extraction regex is too permissive: it matches any triple-backtick code fence even when a non-YAML language identifier is present (e.g., ```python / ```diff) because `(yaml|yml)?` is optional and there is no strict newline/whitespace boundary after the opening fence. This can silently parse/return incorrect data (e.g., as a YAML scalar) and, because `re.search` returns only the first match, a non-YAML fence earlier in the text can prevent extracting/parsing a later valid YAML fence.
## Issue Context
This code path is a fallback for parsing LLM responses as YAML and should only target code fences that are either untagged (```\n) or explicitly YAML (```yaml / ```yml), rather than matching arbitrary fenced blocks and accidentally capturing the language identifier into the snippet body.
## Fix Focus Areas
- pr_agent/algo/utils.py[814-825]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Bare except block at line 830 ✓ Resolved 📘 Rule violation ≡ Correctness
Description
• The try-except block at line 826-831 uses a bare except: clause without capturing the exception
object • This prevents proper error logging and debugging when YAML parsing fails • The compliance
rule requires exception objects to be captured using 'as e' syntax for proper error handling
Code

pr_agent/algo/utils.py[R826-830]

  try:
-            data = yaml.safe_load(snippet_text.removeprefix('```yaml').rstrip('`'))
+            data = yaml.safe_load(snippet_text.removeprefix(prefix).rstrip('`'))
      get_logger().info(f"Successfully parsed AI prediction after extracting yaml snippet")
      return data
  except:
Evidence
The code at line 826-831 contains a try-except block that catches exceptions without capturing them.
According to PR Compliance ID 6, all except blocks that reference or could benefit from referencing
the exception object should use 'as e' syntax. While this specific block doesn't reference the
exception, the broader function context shows error logging is used elsewhere (line 828), suggesting
exception details would be valuable for debugging YAML parsing failures.

pr_agent/algo/utils.py[826-831]
Best Practice: Learned patterns

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The try-except block uses a bare `except:` clause without capturing the exception object, preventing proper error logging and debugging.
## Issue Context
This is part of a YAML parsing fallback mechanism in the `try_fix_yaml` function. The function attempts multiple strategies to parse YAML, and capturing exception details would help diagnose why specific parsing attempts fail.
## Fix Focus Areas
- pr_agent/algo/utils.py[826-831]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Qodo Logo

@naorpeled naorpeled self-assigned this Jan 31, 2026
Extract the YAML snippet directly from the regex capture group instead
of taking the full match and manually detecting/stripping the ```yaml,
```yml, or ``` prefix and trailing backticks. Same behavior, less
string juggling, and avoids rstrip('`') accidentally eating legitimate
trailing backticks in the content.
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 7b69b64

Replace the bare except with `except Exception as e:` and a debug log,
addressing the agentic review flag on PR The-PR-Agent#2097. Matches the
`except Exception as e:` + get_logger() convention used elsewhere in
utils.py.
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit d2070e2

naorpeled added a commit to XinyuWuu/pr-agent that referenced this pull request May 14, 2026
Replace the bare `except:` with `except Exception:` so the fallback no
longer swallows KeyboardInterrupt/SystemExit, addressing the agentic
review flag on PR The-PR-Agent#2097. Kept silent (`pass`) to stay consistent with
the other fallback rungs in try_fix_yaml.
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit d2070e2

@naorpeled
naorpeled merged commit a85a3b6 into The-PR-Agent:main May 14, 2026
6 checks passed
@naorpeled

Copy link
Copy Markdown
Member

Hey @XinyuWuu,
thanks for this!

Sorry for the delay on this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants