Skip to content

Fetch complete patches for patch files written by workflows - #947

Open
opohorel wants to merge 1 commit into
packit:mainfrom
opohorel:fix-full-patch-fetch
Open

opohorel wants to merge 1 commit into
packit:mainfrom
opohorel:fix-full-patch-fetch

Conversation

@opohorel

Copy link
Copy Markdown
Collaborator

Triage and backport wrote get_patch_from_url output, an LLM preview truncated to 2,000 characters, into the clone as the patch to apply (RHEL-298213). Add get_patch_from_url_full, which fails instead of returning truncated, incomplete, binary or non-patch content, and emits applicable git headers for GitLab API diffs.

Assisted-by: Claude Opus 5.5

@qodo-for-packit

qodo-for-packit Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Fetch complete patches for triage and backport workflows

🐞 Bug fix ✨ Enhancement 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Route workflow patch files through full-content fetch tools instead of truncated previews.
• Reject oversized, partial, or invalid responses and convert GitLab API diffs into applicable
 patches.
• Protect GitLab tokens during patch fetches and add coverage for retrieval and application.
Merge Risk 🟡 Medium

Blast radius 🟡 Medium 💥 3 capabilities

  • 3 affected capabilities within one bounded functional scope: upstream_patch_preparation_integration.
  • The backport workflow selects complete retrieval, writes each returned patch into the backport checkout, and only then invokes the backport agent.
  • Retrieval, local storage, and preparation are hops of one end-to-end backport-preparation behavior.
  • Preview retrieval and complete retrieval are distinct useful operations of the same upstream patch-preparation integration.
  • They share request handling and GitLab conversion, while preview preserves truncation and permissive error-string behavior.
  • The triage workflow fetches supplied fixes, writes them into the applicability checkout, and gates the applicability agent on complete inputs.
  • These are producer, storage, and consumer hops of one bounded CVE patch-preparation behavior.
Sources

ymir/tools/privileged/gitlab.py[1558-1562]

        headers = gitlab_headers(patch_url)
        authenticated = "PRIVATE-TOKEN" in headers
        if authenticated:
            request_url = urlparse(request_url)._replace(scheme="https").geturl()
        complete = self.max_content_length is None

ymir/agents/utils.py[43-48]

def patch_fetch_tool_name(patch_url: str) -> str:
    """Select a tool that retrieves complete patch content for deterministic application."""
    parsed_url = urlparse(patch_url)
    if parsed_url.scheme == "https" and parsed_url.hostname in {"github.com", "www.github.com"}:
        return "get_github_patch_full"
    return "get_patch_from_url_full"

ymir/agents/triage_agent.py[1535-1542]

                    except Exception as e:
                        logger.warning(f"Could not fetch patch from {url}: {e}")
                        failed_urls.append(url)
                if failed_urls:
                    # Judging applicability without a supplied fix could wrongly
                    # conclude the CVE does not apply.
                    state.applicability_skip_reason = "upstream fix patch could not be fetched"
                    raise RuntimeError(f"Could not fetch complete patches: {', '.join(failed_urls)}")
Behavioral complexity 🟡 Medium 🧩 Multiple interactions

  • Before: the shared tool fetched response text, optionally converted generic JSON, and truncated large output.
  • After: complete mode differs from preview mode, authenticated and unauthenticated requests use different transport rules, response status and size are enforced, GitLab API entries are validated and converted into git patch headers/hunks, and omissions, pagination, binary content, and commit-stat mismatches are rejected.
  • Before, the API response did not have to become a complete applyable patch.
  • After, supported GitLab entries include ordinary, new, deleted, renamed, mode-only, and special-path cases.
  • New correctness conditions: every supported API diff shape must serialize to an applyable complete patch; complete and preview modes must preserve their distinct contracts; and completeness checks must prevent partial content from reaching patch consumers.
  • Established HTTP, retry, and mapping helpers are reused, but the new transformation and compatibility interactions materially alter correctness conditions.
Sources

ymir/tools/privileged/gitlab.py[1558-1562]

        headers = gitlab_headers(patch_url)
        authenticated = "PRIVATE-TOKEN" in headers
        if authenticated:
            request_url = urlparse(request_url)._replace(scheme="https").geturl()
        complete = self.max_content_length is None
Potential damage 🟡 Medium 🩹 Temporary loss

  • If complete retrieval rejects a valid patch, mishandles a supported GitLab diff shape, or otherwise fails, normal backport preparation raises before the backport agent runs.
  • The inspected path establishes no persistent application-state mutation or external effect at this fetch step.
  • A valid patch can be retrieved after correction and the backport rerun; an automatic retry or repair of later backport state is not established.
  • Recoverable by correcting or restoring retrieval, obtaining a valid patch, and rerunning backport preparation.
  • Code rollback alone would not repair any later backport state, but no such later state is created by the changed preparation step.
Sources

ymir/tools/privileged/gitlab.py[1558-1562]

        headers = gitlab_headers(patch_url)
        authenticated = "PRIVATE-TOKEN" in headers
        if authenticated:
            request_url = urlparse(request_url)._replace(scheme="https").geturl()
        complete = self.max_content_length is None
Assessed commit 5a72759
Diagram

graph TD
  W["Triage and backport"] --> S{"Select fetch tool"} --> G["Privileged gateway"] --> F["Full URL fetcher"] --> P["Patch source"] --> V["Validate and convert"] --> O["Patch files"]
  G --> H["GitHub full fetcher"] --> O
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Fetch GitLab commits with git
  • ➕ Could inspect complete commit data without GitLab API diff pagination or omission limits.
  • ➖ Requires repository access and git operations where the current workflow accepts a patch URL.
  • ➖ Adds credential and clone-management complexity.
2. Paginate GitLab API diffs
  • ➕ Could support commits spanning more than 100 changed files.
  • ➖ Adds requests and assembly logic without resolving GitLab's silently omitted diffs.
  • ➖ Still needs size and completeness checks.

Recommendation: Keep the separate full-fetch tool and fail-closed behavior: patch files must not be built from an LLM-sized preview. The git-based approach is worth considering if silent GitLab API omissions must be ruled out; pagination alone cannot provide that guarantee.

Files changed (9) +633 / -38

Enhancement (1) +2 / -0
gateway.pyRegister the complete URL patch fetcher +2/-0

Register the complete URL patch fetcher

• Makes get_patch_from_url_full available through the privileged gateway alongside the existing preview tool.

ymir/tools/privileged/gateway.py

Bug fix (4) +189 / -35
backport_agent.pySurface complete-patch fetch failures in backport preparation +12/-5

Surface complete-patch fetch failures in backport preparation

• Wraps patch tool failures with the affected URL and a readable error before any failed fetch is written as a patch file.

ymir/agents/backport_agent.py

triage_agent.pyInclude fetch failure details in triage warnings +2/-2

Include fetch failure details in triage warnings

• Logs the exception when a patch cannot be fetched, making skipped applicability patches easier to diagnose. Full-fetch selection comes from the shared helper.

ymir/agents/triage_agent.py

utils.pySelect complete patch tools for workflow files +15/-2

Select complete patch tools for workflow files

• Routes HTTPS GitHub URLs to the existing full fetcher and other URLs to the new full URL fetcher. Adds a helper for extracting readable MCP tool errors.

ymir/agents/utils.py

gitlab.pyFetch and validate complete URL patches +160/-26

Fetch and validate complete URL patches

• Adds a size-bounded full-fetch tool while retaining the 2,000-character preview. Secures authenticated GitLab requests, converts commit API entries into git patch headers, and rejects known incomplete, binary API, and non-patch responses.

ymir/tools/privileged/gitlab.py

Tests (3) +436 / -3
test_backport_helpers.pyTest full-fetch selection and error formatting +22/-3

Test full-fetch selection and error formatting

• Checks that non-HTTPS-GitHub patch URLs select the new full-fetch tool and that MCP error messages are unwrapped for reporting.

ymir/agents/tests/unit/test_backport_helpers.py

test_gateway.pyVerify both URL patch tools are registered +2/-0

Verify both URL patch tools are registered

• Extends the gateway registration assertion to cover the preview and full-content URL patch tools.

ymir/tools/privileged/tests/unit/test_gateway.py

test_gitlab.pyExercise full patch retrieval and git application +412/-0

Exercise full patch retrieval and git application

• Covers preview compatibility, size and HTTP failures, authentication safety, malformed or incomplete GitLab diffs, and conversion of file changes. An integration-style test verifies the converted patch applies with git.

ymir/tools/privileged/tests/unit/test_gitlab.py

Documentation (1) +6 / -0
gitlab_distgit_data_flow.mdDocument safe patch-fetch behavior +6/-0

Document safe patch-fetch behavior

• Explains private GitLab commit URL rewriting, HTTPS-only authenticated requests, redirect restrictions, and the full-fetch requirement for workflow patch files.

gitlab_distgit_data_flow.md

@qodo-for-packit

qodo-for-packit Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

Nice, no open findings for this group


Remediation recommended

Nice, no open findings for this group


Informational

Nice, no open findings for this group

Grey Divider

Resolved findings

1. Incomplete GitLab patches reach backports ✓ Resolved High

Resolving commit: 6b804f8

Resolution reason
Adds a verification step that compares the diff's added/removed line counts with the commit's stats
from the GitLab commit API and raises an error on mismatch, so truncated GitLab diffs fail instead
of being returned as complete patches.
Description
_ensure_complete_api_diff accepts a first-page response when it has no pagination header or
per-file omission flag, even though GitLab can stop returning files at its configured diff limit
without either signal. When that limit is reached on the first page, _json_hunks_to_text converts
the shortened list and prepare_normal_backport writes it as the complete patch.

2. Incomplete GitLab diffs pass as full patches ✓ Resolved High

Resolving commit: fe18787

Resolution reason
The omission check no longer uses a_mode == b_mode equality. It now uses `_api_mode_change(hunk) is
None`, which returns None unless both modes are non-"0" strings and differ. For a_mode null / b_mode
"100644", _api_mode_change returns None, so an empty ordinary modification is flagged as omitted and
rejected with ToolError. Also the header emission only writes mode lines when an explicit mode
change exists. A new parametrized test covers (None, "100644") and ("100644", None) with an empty
diff expecting the "omitted the diff" error. This is a different mechanism from the suggested fix
but achieves the same protection.
Description
_ensure_complete_api_diff rejects an empty ordinary diff only when a_mode == b_mode, but GitLab
can return a_mode: null and b_mode: "100644" for an ordinary modification. If that entry has an
empty diff, conversion emits only a diff --git header, which the full-fetch check accepts and
backport writes as a patch.

3. Large patches bypass the response limit ✓ Resolved Medium

Resolving commit: 5a72759

Resolution reason
After conversion of GitLab API diff entries, the commit checks len(text.encode()) against
MAX_FULL_PATCH_CONTENT_LENGTH in the complete branch and raises ToolError when exceeded, before the
patch is returned. A regression test with an input under the limit whose converted output exceeds it
was also added.
Description
GetPatchFromUrlFullTool._run checks the size of the HTTP body but does not check text again
after _json_hunks_to_text adds patch headers. A GitLab API response just under the five-megabyte
limit can expand beyond it during conversion and still be returned to the workflow.

View resolved (4)
4. Cut-off raw patches are written to clones ✓ Resolved Medium

Resolving commit: 6b804f8

Resolution reason
Adds a verification that the diff's added/removed line counts match the commit's stats from GitLab,
raising a ToolError for incomplete diffs, plus a unit test for a truncated diff.
Description
GetPatchFromUrlFullTool._run treats a raw response as a patch if any line matches
_PATCH_CONTENT_RE, without checking that its hunks are complete. A successful response ending
midway through a hunk passes that check and is written by prepare_normal_backport, although it
cannot be applied as a complete fix.

5. Patch fetch failures still reach CVE analysis ✓ Resolved Medium

Resolving commit: fe18787

Resolution reason
In triage_agent.py run_workflow, the patch fetch loop now records failed URLs and, if any failed,
sets state.applicability_skip_reason to "upstream fix patch could not be fetched" and raises
RuntimeError before the applicability agent runs. The applicability check is therefore skipped
rather than run with the patch omitted, and the skip reason is surfaced in the comment. A test
asserts the applicability agent is never run and applicability_check_skipped is True. The gitlab.py
changes address the fetcher's conversion logic, not the swallowing itself.
Description
patch_fetch_tool_name now selects a full fetcher that raises for incomplete or unsupported
patches, but check_cve_applicability catches the failure and continues with the patch omitted.
When an upstream fix cannot be fetched, the applicability prompt can say no fix patch is available
and still proceed to a not-affected decision.

6. Binary additions can become empty files ✓ Resolved Medium

Resolving commit: 5a72759

Resolution reason
N/A
Description
_ensure_complete_api_diff exempts new and deleted files with empty diffs, while its binary check
recognizes only diffs beginning with Binary files . When GitLab represents a binary addition with
an empty diff, the converter emits an empty-file patch instead of rejecting the binary content.

7. Some valid filenames block backports ✓ Resolved Medium

Resolving commit: fe18787

Resolution reason
The commit removes _is_plain_patch_path and its rejection of tabs/newlines/quotes/backslashes. Paths
are now only checked to be non-empty strings, and a new _git_quote_path helper quotes/escapes paths
(C-style escapes, octal for control chars) in the "diff --git", "---", "+++", and "rename" headers.
Mode-change detection was also made explicit. A test with a tab-and-quote filename and a backslash
rename target was added to verify patch application, matching the suggested fix's intent.
Description
_parse_api_diff rejects GitLab paths containing tabs, newlines, quotes or backslashes rather than
encoding them in Git's quoted patch-path syntax. A commit changing such a valid filename leaves its
API JSON unconverted, so the full fetcher raises a non-patch error before backport can write the
patch.

Grey Divider

Context sources
✅ Compliance rules (platform): 5 rules
✅ Context preparation
  Past issues: summarized; full text retained for this review
Review mode: Auto: ⚖️ Balanced: Comparison failure: full PR diff.

Grey Divider

Tip of the day
💡 Did you know, you can copy the agent prompt from any finding and feed it to your IDE agent

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit 5a72759 ⚖️ Balanced

Results up to commit bebc9c1 🧠 Deep


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Action required

Nice, no open findings for this group


Remediation recommended

Nice, no open findings for this group


Informational

Nice, no open findings for this group

Resolved findings

1. Incomplete GitLab diffs pass as full patches ✓ Resolved High

Resolving commit: fe18787

Resolution reason
The omission check no longer uses a_mode == b_mode equality. It now uses `_api_mode_change(hunk) is
None`, which returns None unless both modes are non-"0" strings and differ. For a_mode null / b_mode
"100644", _api_mode_change returns None, so an empty ordinary modification is flagged as omitted and
rejected with ToolError. Also the header emission only writes mode lines when an explicit mode
change exists. A new parametrized test covers (None, "100644") and ("100644", None) with an empty
diff expecting the "omitted the diff" error. This is a different mechanism from the suggested fix
but achieves the same protection.
Description
_ensure_complete_api_diff rejects an empty ordinary diff only when a_mode == b_mode, but GitLab
can return a_mode: null and b_mode: "100644" for an ordinary modification. If that entry has an
empty diff, conversion emits only a diff --git header, which the full-fetch check accepts and
backport writes as a patch.

2. Binary additions can become empty files ✓ Resolved Medium

Resolving commit: 5a72759

Resolution reason
N/A
Description
_ensure_complete_api_diff exempts new and deleted files with empty diffs, while its binary check
recognizes only diffs beginning with Binary files . When GitLab represents a binary addition with
an empty diff, the converter emits an empty-file patch instead of rejecting the binary content.

3. Patch fetch failures still reach CVE analysis ✓ Resolved Medium

Resolving commit: fe18787

Resolution reason
In triage_agent.py run_workflow, the patch fetch loop now records failed URLs and, if any failed,
sets state.applicability_skip_reason to "upstream fix patch could not be fetched" and raises
RuntimeError before the applicability agent runs. The applicability check is therefore skipped
rather than run with the patch omitted, and the skip reason is surfaced in the comment. A test
asserts the applicability agent is never run and applicability_check_skipped is True. The gitlab.py
changes address the fetcher's conversion logic, not the swallowing itself.
Description
patch_fetch_tool_name now selects a full fetcher that raises for incomplete or unsupported
patches, but check_cve_applicability catches the failure and continues with the patch omitted.
When an upstream fix cannot be fetched, the applicability prompt can say no fix patch is available
and still proceed to a not-affected decision.

View resolved (1)
4. Some valid filenames block backports ✓ Resolved Medium

Resolving commit: fe18787

Resolution reason
The commit removes _is_plain_patch_path and its rejection of tabs/newlines/quotes/backslashes. Paths
are now only checked to be non-empty strings, and a new _git_quote_path helper quotes/escapes paths
(C-style escapes, octal for control chars) in the "diff --git", "---", "+++", and "rename" headers.
Mode-change detection was also made explicit. A test with a tab-and-quote filename and a backslash
rename target was added to verify patch application, matching the suggested fix's intent.
Description
_parse_api_diff rejects GitLab paths containing tabs, newlines, quotes or backslashes rather than
encoding them in Git's quoted patch-path syntax. A commit changing such a valid filename leaves its
API JSON unconverted, so the full fetcher raises a non-patch error before backport can write the
patch.

Results up to commit fe18787 ⚖️ Balanced


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Action required

Nice, no open findings for this group


Remediation recommended

Nice, no open findings for this group


Informational

Nice, no open findings for this group

Resolved findings

1. Incomplete GitLab patches reach backports ✓ Resolved High

Resolving commit: 6b804f8

Resolution reason
Adds a verification step that compares the diff's added/removed line counts with the commit's stats
from the GitLab commit API and raises an error on mismatch, so truncated GitLab diffs fail instead
of being returned as complete patches.
Description
_ensure_complete_api_diff accepts a first-page response when it has no pagination header or
per-file omission flag, even though GitLab can stop returning files at its configured diff limit
without either signal. When that limit is reached on the first page, _json_hunks_to_text converts
the shortened list and prepare_normal_backport writes it as the complete patch.

2. Cut-off raw patches are written to clones ✓ Resolved Medium

Resolving commit: 6b804f8

Resolution reason
Adds a verification that the diff's added/removed line counts match the commit's stats from GitLab,
raising a ToolError for incomplete diffs, plus a unit test for a truncated diff.
Description
GetPatchFromUrlFullTool._run treats a raw response as a patch if any line matches
_PATCH_CONTENT_RE, without checking that its hunks are complete. A successful response ending
midway through a hunk passes that check and is written by prepare_normal_backport, although it
cannot be applied as a complete fix.

Results up to commit 6b804f8 ⚖️ Balanced


No changes from previous review

Grey Divider

Qodo Logo

Comment thread ymir/tools/privileged/gitlab.py Resolved
Comment thread ymir/tools/privileged/gitlab.py Resolved
Comment thread ymir/tools/privileged/gitlab.py Resolved
Comment thread ymir/agents/utils.py Resolved
@opohorel
opohorel force-pushed the fix-full-patch-fetch branch from bebc9c1 to fe18787 Compare November 25, 2026 15:44
Comment thread ymir/tools/privileged/gitlab.py Resolved
Comment thread ymir/tools/privileged/gitlab.py Resolved
Comment thread ymir/tools/privileged/gitlab.py Resolved
Comment thread ymir/tools/privileged/gitlab.py Resolved
Comment thread ymir/tools/privileged/gitlab.py Resolved
Comment thread ymir/tools/privileged/gitlab.py Resolved
Comment thread ymir/tools/privileged/gitlab.py Resolved
@opohorel
opohorel force-pushed the fix-full-patch-fetch branch from fe18787 to 6b804f8 Compare November 25, 2026 16:03
Comment thread ymir/tools/privileged/gitlab.py Resolved
@qodo-for-packit

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 6b804f8

@opohorel

Copy link
Copy Markdown
Collaborator Author

/agentic_review

Triage and backport wrote get_patch_from_url output, an LLM preview
truncated to 2,000 characters, into the clone as the patch to apply
(RHEL-298213). Add get_patch_from_url_full, which fails instead of
returning truncated, incomplete, binary or non-patch content, and emits
applicable git headers for GitLab API diffs.

Assisted-by: Claude Opus 5.5
@opohorel
opohorel force-pushed the fix-full-patch-fetch branch from 6b804f8 to 5a72759 Compare November 25, 2026 17:01
@qodo-for-packit

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 5a72759

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant