Skip to content

fix(gitlab): restore ticket context in reviews - #2802

Merged
IsmaelMartinez merged 3 commits into
The-PR-Agent:mainfrom
Fnine59:fix/pr-agent-2799-gitlab-ticket-context
Aug 25, 2026
Merged

IsmaelMartinez merged 3 commits into
The-PR-Agent:mainfrom
Fnine59:fix/pr-agent-2799-gitlab-ticket-context

Conversation

@Fnine59

@Fnine59 Fnine59 commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

Fixes #2799.

Summary

  • Parse documented GitLab issue references from merge request descriptions.
  • Fetch each issue through the configured GitLab project client and map it to the existing ticket context shape.
  • Keep branch-name detection GitHub-only and preserve the three-ticket and body-length bounds.

Tests

  • RED: the focused GitLab extraction test returns no ticket context on the unmodified base.
  • GREEN: PYTHONPATH=. .venv/bin/pytest tests/unittest -q --color=no

@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Fix GitLab ticket context extraction for reviews

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Parse GitLab issue references from merge request descriptions.
• Fetch referenced issues via GitLabProvider and map into ticket context.
• Add unit tests covering URL, scoped, and local issue reference formats.
Diagram

graph TD
  MR["MR description"] --> Parse["GitLab refs regex"] --> Provider["GitLabProvider"] --> API{{"GitLab API"}} --> Map["Ticket context"] --> Check["Compliance check"]
  Tests["test_ticket_extraction_async.py"] --> Extract["extract_tickets()"] --> Map
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use GitLab MR/issue metadata instead of parsing description
  • ➕ Avoids regex parsing edge cases (markdown quirks, odd spacing)
  • ➕ Leverages GitLab’s own understanding of references/closing keywords
  • ➖ Requires additional API calls/permissions and potentially different endpoints per GitLab version
  • ➖ Harder to keep behavior consistent with existing provider-agnostic ticket extraction constraints
2. Centralize reference extraction into a provider-specific helper module
  • ➕ Keeps ticket_pr_compliance_check.py smaller and easier to extend for other providers
  • ➕ Encourages reuse if other GitLab features need similar parsing
  • ➖ Refactor cost for a contained bug fix
  • ➖ May add indirection without immediate reuse

Recommendation: The PR’s approach (documented-format regex extraction + bounded fetch/mapping) is appropriate for restoring functionality with minimal behavioral impact. Consider modularizing provider-specific extraction later if GitLab logic grows, but it’s not necessary for this fix.

Files changed (2) +151 / -2

Bug fix (1) +97 / -1
ticket_pr_compliance_check.pyAdd GitLab issue reference parsing and ticket-context fetching +97/-1

Add GitLab issue reference parsing and ticket-context fetching

• Introduces a GitLab-specific regex and 'extract_gitlab_ticket_references()' helper to detect documented issue reference formats (full URLs, 'group/project#iid', and local '#iid'). Extends 'extract_tickets()' to fetch each referenced issue via the configured GitLab client, map it into the existing ticket context shape, and enforce the same ticket-count and body-length bounds.

pr_agent/tools/ticket_pr_compliance_check.py

Tests (1) +54 / -1
test_ticket_extraction_async.pyAdd unit coverage for GitLab ticket extraction mapping +54/-1

Add unit coverage for GitLab ticket extraction mapping

• Adds a GitLabProvider test double backed by MagicMock GitLab client/project/issue objects. Verifies that URL, scoped, and local issue references in the MR description produce the expected ticket context and that the correct GitLab client methods are invoked.

tests/unittest/test_ticket_extraction_async.py

@qodo-code-review

qodo-code-review Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

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

Grey Divider


Action required

1. Bypass GitLab project resolver 🐞 Bug ≡ Correctness
Description
extract_tickets() fetches GitLab issues via git_provider.gl.projects.get(project_path),
bypassing GitLabProvider._project_by_path() which exists to handle encoded-path resolution and
safer lookup strategies. This can cause valid GitLab issue references to be skipped at runtime
(ticket context missing) when raw projects.get(project_path) does not resolve correctly for a
given project path.
Code

pr_agent/tools/ticket_pr_compliance_check.py[R507-510]

+                    project = git_provider.gl.projects.get(project_path)
+                    issue = project.issues.get(issue_iid)
+                except Exception as e:
+                    get_logger().error(
Relevance

●●● Strong

Close precedent accepted hardening GitLab project resolution and specifically recommends reusable
encoded-path lookup.

PR-#2014

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The PR introduces direct gl.projects.get(project_path) usage for GitLab issue resolution. The
GitLab provider already contains _project_by_path() explicitly to resolve a project by path using
encoded/raw strategies and controlled fallback, implying direct projects.get(proj_path) is not
always sufficient/reliable.

pr_agent/tools/ticket_pr_compliance_check.py[498-514]
pr_agent/git_providers/gitlab_provider.py[243-283]
PR-#2014

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 GitLab ticket extraction path resolves projects using `git_provider.gl.projects.get(project_path)` directly, which is less robust than the provider’s existing `_project_by_path()` helper.

## Issue Context
`GitLabProvider` already implements `_project_by_path()` to handle multiple strategies (including URL-encoded paths and safer fallback behavior). The new ticket extraction should use that same resolver to avoid failing to fetch issues for valid project paths.

## Fix Focus Areas
- pr_agent/tools/ticket_pr_compliance_check.py[498-514]
- pr_agent/git_providers/gitlab_provider.py[243-283]

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



Remediation recommended

2. Markdown heading misdetected ✓ Resolved 🐞 Bug ≡ Correctness ⭐ New
Description
GITLAB_TICKET_PATTERN will match the second # in markdown headings like ##7 as a local issue
reference, which can produce incorrect GitLab ticket context and unnecessary issue fetches. This
happens because the negative lookbehind for #(?P<local_issue>\d+) does not exclude a preceding
#.
Code

pr_agent/tools/ticket_pr_compliance_check.py[R57-60]

+    r"(?P<url>https?://[^\s<>(),;]+)"
+    r"|(?<![\w./-])(?P<project>[\w.-]+(?:/[\w.-]+)+)#(?P<project_issue>\d+)\b"
+    r"|(?<![\w/])#(?P<local_issue>\d+)\b"
+)
Relevance

●●● Strong

Accepted history favors defensive regex correctness fixes; this deterministic boundary bug causes
false ticket fetches.

PR-#2231

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The local-issue alternative only forbids a word character or / before #, so a preceding # (as
in markdown headings ##7) is allowed and will be interpreted as an issue reference.

pr_agent/tools/ticket_pr_compliance_check.py[55-61]

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

## Issue description
`GITLAB_TICKET_PATTERN` currently matches local issue references via `(?<![\w/])#(?P<local_issue>\d+)\b`. This will also match markdown heading tokens like `##7` (the second `#` passes the negative lookbehind), causing false-positive ticket extraction.

## Issue Context
This regex is used to scan the entire MR description for GitLab issue references, so false positives can lead to incorrect ticket context and unnecessary GitLab API calls.

## Fix Focus Areas
- pr_agent/tools/ticket_pr_compliance_check.py[55-61]

### Suggested change
Tighten the local-issue alternative to ensure the `#` is not itself preceded by another `#` (and keep the existing word/`/` boundary rule). For example:
- Change the lookbehind to also exclude `#`: `(?<![\w/#])#(?P<local_issue>\d+)\b`

Optionally add a unit test asserting `extract_gitlab_ticket_references("##7", "group/repo", "https://gitlab.com") == []`.

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


  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Grey Divider

Context sources
✅ Compliance rules (platform): 34 rules
Review mode: ⚖️ Balanced

Grey Divider

Tip of the day
💡 Did you know, you can hide the parts of a finding you never read, like the evidence or the agent prompt

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit bc13b4a

Results up to commit fe97b38 ⚖️ Balanced


🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 📜 Skill insights (0)


Action required
1. Bypass GitLab project resolver 🐞 Bug ≡ Correctness
Description
extract_tickets() fetches GitLab issues via git_provider.gl.projects.get(project_path),
bypassing GitLabProvider._project_by_path() which exists to handle encoded-path resolution and
safer lookup strategies. This can cause valid GitLab issue references to be skipped at runtime
(ticket context missing) when raw projects.get(project_path) does not resolve correctly for a
given project path.
Code

pr_agent/tools/ticket_pr_compliance_check.py[R507-510]

+                    project = git_provider.gl.projects.get(project_path)
+                    issue = project.issues.get(issue_iid)
+                except Exception as e:
+                    get_logger().error(
Relevance

●●● Strong

Close precedent accepted hardening GitLab project resolution and specifically recommends reusable
encoded-path lookup.

PR-#2014

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The PR introduces direct gl.projects.get(project_path) usage for GitLab issue resolution. The
GitLab provider already contains _project_by_path() explicitly to resolve a project by path using
encoded/raw strategies and controlled fallback, implying direct projects.get(proj_path) is not
always sufficient/reliable.

pr_agent/tools/ticket_pr_compliance_check.py[498-514]
pr_agent/git_providers/gitlab_provider.py[243-283]
PR-#2014

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 GitLab ticket extraction path resolves projects using `git_provider.gl.projects.get(project_path)` directly, which is less robust than the provider’s existing `_project_by_path()` helper.

## Issue Context
`GitLabProvider` already implements `_project_by_path()` to handle multiple strategies (including URL-encoded paths and safer fallback behavior). The new ticket extraction should use that same resolver to avoid failing to fetch issues for valid project paths.

## Fix Focus Areas
- pr_agent/tools/ticket_pr_compliance_check.py[498-514]
- pr_agent/git_providers/gitlab_provider.py[243-283]

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


Grey Divider

Qodo Logo

Comment on lines +507 to +510
project = git_provider.gl.projects.get(project_path)
issue = project.issues.get(issue_iid)
except Exception as e:
get_logger().error(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. Bypass gitlab project resolver 🐞 Bug ≡ Correctness

extract_tickets() fetches GitLab issues via git_provider.gl.projects.get(project_path),
bypassing GitLabProvider._project_by_path() which exists to handle encoded-path resolution and
safer lookup strategies. This can cause valid GitLab issue references to be skipped at runtime
(ticket context missing) when raw projects.get(project_path) does not resolve correctly for a
given project path.
Agent Prompt
## Issue description
The GitLab ticket extraction path resolves projects using `git_provider.gl.projects.get(project_path)` directly, which is less robust than the provider’s existing `_project_by_path()` helper.

## Issue Context
`GitLabProvider` already implements `_project_by_path()` to handle multiple strategies (including URL-encoded paths and safer fallback behavior). The new ticket extraction should use that same resolver to avoid failing to fetch issues for valid project paths.

## Fix Focus Areas
- pr_agent/tools/ticket_pr_compliance_check.py[498-514]
- pr_agent/git_providers/gitlab_provider.py[243-283]

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

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fix is right and the coverage is genuine: all three reference forms go red on main without the source change. One change requested before merge: the URL branch of the new regex is quadratic on adversarial input, measured at 38 s for a 1 MB description (GitLab's documented cap) on input the MR author controls; details and a committable rewrite are inline. On Qodo's resolver finding: python-gitlab already URL-encodes string project IDs via EncodedId, and _project_by_path is the submodule resolver that swallows errors and returns None, so the direct projects.get call with logged errors looks right; no change needed there. Thanks @Fnine59 for the fast turnaround with tests included.

Comment on lines +56 to +60
GITLAB_TICKET_PATTERN = re.compile(
r"(?P<url>https?://[^\s<>()]+?/-/issues/(?P<url_issue>\d+))(?=$|[^\w])"
r"|(?<![\w./-])(?P<project>[\w.-]+(?:/[\w.-]+)+)#(?P<project_issue>\d+)\b"
r"|(?<![\w/])#(?P<local_issue>\d+)\b"
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The URL branch is quadratic: the lazy [^\s<>()]+? rescans to end-of-input from every https:// start. Measured ~4x per input doubling: 150 ms at 64 KB, 38 s at 1 MB. The rewrite below matches any URL greedily (linear, 0.3 ms at 64 KB) and moves the issue check onto the parsed path. Output matches on 27 realistic cases (trailing punctuation, backtick and bold wrappers, subpath installs, ports, #note_ fragments), and the three divergences are deliberate: comma-joined URL lists no longer yield a garbage project path, zero-padded iids resolve, and trailing text glued to the iid no longer counts. Your three tests stay green.

Suggested change
GITLAB_TICKET_PATTERN = re.compile(
r"(?P<url>https?://[^\s<>()]+?/-/issues/(?P<url_issue>\d+))(?=$|[^\w])"
r"|(?<![\w./-])(?P<project>[\w.-]+(?:/[\w.-]+)+)#(?P<project_issue>\d+)\b"
r"|(?<![\w/])#(?P<local_issue>\d+)\b"
)
GITLAB_TICKET_PATTERN = re.compile(
r"(?P<url>https?://[^\s<>(),;]+)"
r"|(?<![\w./-])(?P<project>[\w.-]+(?:/[\w.-]+)+)#(?P<project_issue>\d+)\b"
r"|(?<![\w/])#(?P<local_issue>\d+)\b"
)
GITLAB_ISSUE_PATH_PATTERN = re.compile(r"/-/issues/(?P<iid>\d+)(?=/|$)")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 65e0af41: URL matching now uses a greedy, delimiter-bounded token and leaves issue extraction to a separate path pattern. Added boundary regressions; the focused GitLab tests pass (9/9), the related ticket suite passes (157 passed, 1 xfailed), and the full unit suite passes (2097 passed, 1 skipped, 1 xfailed).

Comment on lines +202 to +220
if match.group("url"):
try:
parsed_ticket_url = urlparse(match.group("url"))
except ValueError:
continue
if not provider_host or parsed_ticket_url.hostname != provider_host:
continue

ticket_path = parsed_ticket_url.path
if provider_base_path:
if not ticket_path.startswith(f"{provider_base_path}/"):
continue
ticket_path = ticket_path[len(provider_base_path):]

issue_iid = int(match.group("url_issue"))
issue_suffix = f"/-/issues/{issue_iid}"
if not ticket_path.endswith(issue_suffix):
continue
issue_project = ticket_path[:-len(issue_suffix)].strip("/")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code half of the linear rewrite, pairs with the pattern change above.

Suggested change
if match.group("url"):
try:
parsed_ticket_url = urlparse(match.group("url"))
except ValueError:
continue
if not provider_host or parsed_ticket_url.hostname != provider_host:
continue
ticket_path = parsed_ticket_url.path
if provider_base_path:
if not ticket_path.startswith(f"{provider_base_path}/"):
continue
ticket_path = ticket_path[len(provider_base_path):]
issue_iid = int(match.group("url_issue"))
issue_suffix = f"/-/issues/{issue_iid}"
if not ticket_path.endswith(issue_suffix):
continue
issue_project = ticket_path[:-len(issue_suffix)].strip("/")
if match.group("url"):
try:
parsed_ticket_url = urlparse(match.group("url").rstrip(".:!?'\"]}`*"))
except ValueError:
continue
if not provider_host or parsed_ticket_url.hostname != provider_host:
continue
ticket_path = parsed_ticket_url.path
if provider_base_path:
if not ticket_path.startswith(f"{provider_base_path}/"):
continue
ticket_path = ticket_path[len(provider_base_path):]
path_match = GITLAB_ISSUE_PATH_PATTERN.search(ticket_path)
if not path_match:
continue
issue_iid = int(path_match.group("iid"))
issue_project = ticket_path[:path_match.start()].strip("/")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 65e0af41: the parser trims trailing wrappers, validates the host and configured base path, then extracts the project and IID from GITLAB_ISSUE_PATH_PATTERN. Coverage now includes wrappers, custom ports/subpaths, fragments, zero-padded IDs, glued suffixes, and comma-separated URLs.

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 65e0af4

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for turning both points around within the hour. Verified the new pattern is linear, roughly 2x per input doubling on adversarial inputs. One character left: Qodo's remaining finding is real, I reproduced it, a Markdown heading reads as a reference, so ##7 matches as issue #7. Suggestion inline; with it applied this is ready to merge.

GITLAB_TICKET_PATTERN = re.compile(
r"(?P<url>https?://[^\s<>(),;]+)"
r"|(?<![\w./-])(?P<project>[\w.-]+(?:/[\w.-]+)+)#(?P<project_issue>\d+)\b"
r"|(?<![\w/])#(?P<local_issue>\d+)\b"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Excludes # from the lookbehind so a Markdown heading no longer reads as a reference; the 38 tests stay green and group/proj#7 still extracts.

Suggested change
r"|(?<![\w/])#(?P<local_issue>\d+)\b"
r"|(?<![\w/#])#(?P<local_issue>\d+)\b"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in bc13b4a6: local shorthand references now exclude a preceding #. The regression verifies that ##7 is ignored while group/proj#7 and #7 still extract. Focused GitLab tests pass (12/12), the related ticket suite passes (160 passed, 1 xfailed), and the full unit suite passes (2100 passed, 1 skipped, 1 xfailed).

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit bc13b4a

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The lookbehind fix and the three boundary cases are exactly right; 41 pass on the merged tree. Thanks for the quick turnarounds today.

@IsmaelMartinez
IsmaelMartinez merged commit ae84eec into The-PR-Agent:main Aug 25, 2026
5 checks passed
@qodo-code-review qodo-code-review Bot mentioned this pull request Aug 28, 2026
3 tasks done
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.

pr_reviewer.require_ticket_analysis_review doesn't take any effect in GitLab pipeline

2 participants