Skip to content

feat(gitlab): add update comment stategy#2446

Merged
zakisk merged 1 commit intotektoncd:mainfrom
theakshaypant:SRVKP-10453-gitlab-update-comment-strategy
Feb 19, 2026
Merged

feat(gitlab): add update comment stategy#2446
zakisk merged 1 commit intotektoncd:mainfrom
theakshaypant:SRVKP-10453-gitlab-update-comment-strategy

Conversation

@theakshaypant
Copy link
Copy Markdown
Member

📝 Description of the Change

Adds an "update" comment strategy which updates a single comment per PipelineRun on every trigger.

This comment strategy reports CEL validation errors immediately with a PipelineRun-specific prefix when using the update comment strategy, allowing them to be consolidated into a single updatable comment per PipelineRun.

👨🏻‍ Linked Jira

https://issues.redhat.com/browse/SRVKP-10453

🔗 Linked GitHub Issue

N/A

🚀 Type of Change

  • 🐛 Bug fix (fix:)
  • ✨ New feature (feat:)
  • 💥 Breaking change (feat!:, fix!:)
  • 📚 Documentation update (docs:)
  • ⚙️ Chore (chore:)
  • 💅 Refactor (refactor:)
  • 🔧 Enhancement (enhance:)
  • 📦 Dependency update (deps:)

🧪 Testing Strategy

  • Unit tests

  • Integration tests

  • End-to-end tests

  • Manual testing

  • Not Applicable

  • Pull Request 1 with /retest
    Screenshot From 2026-02-04 13-59-50

  • Pull Request 2 with CEL validation errors
    Screenshot From 2026-02-04 13-45-44

  • Pull request 2 status after CEL errors were resolved with an validation error
    Screenshot From 2026-02-04 13-46-55

🤖 AI Assistance

  • I have not used any AI assistance for this PR.
  • I have used AI assistance for this PR.

If you have used AI assistance, please provide the following details:

Which LLM was used?

  • GitHub Copilot
  • ChatGPT (OpenAI)
  • Claude (Anthropic)
  • Cursor
  • Gemini (Google)
  • Other: ____________

Extent of AI Assistance:

  • Documentation and research only
  • Unit tests or E2E tests only
  • Code generation (parts of the code)
  • Full code generation (most of the PR)
  • PR description and comments
  • Commit message(s)

Important

If the majority of the code in this PR was generated by an AI, please add a Co-authored-by trailer to your commit message.
For example:

Co-authored-by: Gemini gemini@google.com
Co-authored-by: ChatGPT noreply@chatgpt.com
Co-authored-by: Claude noreply@anthropic.com
Co-authored-by: Cursor noreply@cursor.com
Co-authored-by: Copilot Copilot@users.noreply.github.com

**💡You can use the script ./hack/add-llm-coauthor.sh to automatically add
these co-author trailers to your commits.

✅ Submitter Checklist

  • 📝 My commit messages are clear, informative, and follow the project's How to write a git commit message guide. The Gitlint linter ensures in CI it's properly validated
  • ✨ I have ensured my commit message prefix (e.g., fix:, feat:) matches the "Type of Change" I selected above.
  • ♽ I have run make test and make lint locally to check for and fix any
    issues. For an efficient workflow, I have considered installing
    pre-commit and running pre-commit install to
    automate these checks.
  • 📖 I have added or updated documentation for any user-facing changes.
  • 🧪 I have added sufficient unit tests for my code changes.
  • 🎁 I have added end-to-end tests where feasible. See README for more details.
  • 🔎 I have addressed any CI test flakiness or provided a clear reason to bypass it.
  • If adding a provider feature, I have filled in the following and updated the provider documentation:
    • GitHub App
    • GitHub Webhook
    • Gitea/Forgejo
    • GitLab
    • Bitbucket Cloud
    • Bitbucket Data Center

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello @theakshaypant, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the GitLab integration by introducing an "update" comment strategy. This new feature streamlines communication on merge requests by consolidating all PipelineRun status updates and CEL validation errors into a single, continuously updated comment. This approach reduces comment clutter and provides a clear, real-time overview of pipeline execution directly within the merge request interface.

Highlights

  • New GitLab Comment Strategy: Introduced an "update" comment strategy for GitLab, allowing a single comment per PipelineRun to be updated on every trigger. This prevents comment spam and provides a consolidated view of pipeline status.
  • Enhanced CEL Validation Error Reporting: When the "update" comment strategy is active, Common Expression Language (CEL) validation errors are now reported immediately within the single updatable comment, using a PipelineRun-specific prefix for clarity.
  • API and CRD Updates: The CommentStrategy field in GitlabSettings within both the Custom Resource Definition (CRD) and the Go type definition has been extended to include the new "update" option, making it a configurable choice.
  • Standardized Comment Formatting: A new internal helper function, formatPipelineComment, was added to generate standardized, emoji-rich status comments for PipelineRuns, ensuring consistent and easily understandable messages.
Changelog
  • config/300-repositories.yaml
    • Added update as a valid option for CommentStrategy in GitLab repository settings within the CRD.
  • pkg/apis/pipelinesascode/v1alpha1/types.go
    • Updated GitlabSettings to include update in the CommentStrategy enum validation for the Go type.
  • pkg/matcher/annotation_matcher.go
    • Modified CEL validation error reporting logic to conditionally use the new "update" comment strategy if enabled, allowing immediate and consolidated error reporting.
    • Adjusted the call to reportCELValidationErrors to pass an empty prefix for default behavior.
  • pkg/matcher/errors.go
    • Enhanced reportCELValidationErrors to accept an optional prefix string, enabling the "update" strategy to prepend specific identifiers to comments for update purposes.
  • pkg/provider/gitlab/gitlab.go
    • Modified CreateStatus to accept a context.Context parameter.
    • Implemented the core logic for the "update" comment strategy within CreateStatus, including formatting and updating comments.
    • Added a new helper function formatPipelineComment to generate consistent, emoji-based status messages for PipelineRuns.
  • pkg/provider/provider.go
    • Imported v1alpha1 for repository type access.
    • Defined new constants: PlrStatusCommentPrefixTemplate, UpdateCommentStrategy, and DisableAllCommentStrategy.
    • Added IsCommentStrategyUpdate helper function to check if the repository's GitLab comment strategy is set to "update".
  • pkg/webhook/validation.go
    • Imported the provider package.
    • Updated webhook validation to recognize and allow the new UpdateCommentStrategy.
Activity
  • The author, theakshaypant, initiated this pull request to introduce a new feature related to GitLab comment handling.
  • The pull request includes screenshots from manual testing, demonstrating the functionality of the new comment strategy and how CEL validation errors are reported.
  • The author has confirmed that no AI assistance was used in the creation of this pull request.
  • The submitter checklist indicates that the author has ensured clear commit messages, matching type of change, local test execution, and consideration for documentation and additional tests.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@pipelines-as-code
Copy link
Copy Markdown

pipelines-as-code bot commented Feb 4, 2026

🔍 PR Lint Feedback

Note: This automated check helps ensure your PR follows our contribution guidelines.

⚠️ Items that need attention:

🤖 AI attribution

The following commits lack an explicit AI attribution footer:

  • 922bb39 feat(gitlab): add update comment stategy

If no AI assistance was used for a commit, you can ignore this warning.
Otherwise add an Assisted-by: or Co-authored-by: footer referencing the AI used.


ℹ️ Next Steps

  • Review and address the items above
  • Push new commits to update this PR
  • This comment will be automatically updated when issues are resolved
🔧 Admin Tools (click to expand)

Automated Issue/Ticket Creation:

  • /issue-create - Generate a GitHub issue from this PR content using AI
  • /jira-create - Create a SRVKP Jira ticket from this PR content using AI

⚠️ Important: Always review and edit generated content before finalizing tickets/issues.
The AI-generated content should be used as a starting point and may need adjustments.

These commands are available to maintainers and will post the generated content as PR comments for review.

🤖 This feedback was generated automatically by the PR CI system

@pipelines-as-code pipelines-as-code bot added enhancement New feature or request feature New feature or request gitlab labels Feb 4, 2026
Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request introduces a new 'update' comment strategy for GitLab, allowing for a single comment per PipelineRun to be updated on every trigger. This feature is implemented by adding new enum values to the API and schema definitions, and modifying the logic for reporting CEL validation errors and pipeline statuses to use this new strategy. The changes include adding constants for comment strategies and a helper function to check the current strategy. Overall, the changes are well-structured and integrate the new functionality effectively, with a minor suggestion regarding markdown formatting.

@theakshaypant theakshaypant force-pushed the SRVKP-10453-gitlab-update-comment-strategy branch 2 times, most recently from eec6744 to 43bf4b1 Compare February 4, 2026 09:06
@theakshaypant
Copy link
Copy Markdown
Member Author

/review

@qodo-code-review
Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Markdown Formatting

The markdown table rows are built using the raw error string (err.Err.Error()) wrapped in backticks. If an error contains characters like |, newlines, or backticks, it can break the markdown table formatting and potentially make the comment unreadable. Consider escaping/normalizing error strings for markdown tables (similar to how sanitizeErrorAsMarkdown is used elsewhere).

func reportCELValidationErrors(ctx context.Context, repo *apipac.Repository, validationErrors []*pacerrors.PacYamlValidations, eventEmitter *events.EventEmitter, vcx provider.Interface, event *info.Event, prefix string) {
	errorRows := make([]string, 0, len(validationErrors))
	for _, err := range validationErrors {
		errorRows = append(errorRows, fmt.Sprintf("| %s | `%s` |", err.Name, err.Err.Error()))
	}
	if len(errorRows) == 0 {
		return
	}

	var err error

	// The prefix is used for a single comment "update" strategy where the same comment is updated
	// with the celValidationError and the PipelineRun status for any subsequent or prior "runs".
	if prefix != "" {
		markdownErrMessage := fmt.Sprintf(`%s
%s
%s`, prefix, provider.ValidationErrorTemplate, strings.Join(errorRows, "\n"))
		err = vcx.CreateComment(ctx, event, markdownErrMessage, prefix)
	} else {
		markdownErrMessage := fmt.Sprintf(`%s
%s`, provider.ValidationErrorTemplate, strings.Join(errorRows, "\n"))
		err = vcx.CreateComment(ctx, event, markdownErrMessage, provider.ValidationErrorTemplate)
	}
	if err != nil {
		eventEmitter.EmitMessage(repo, zap.ErrorLevel, "PipelineRunCommentCreationError",
			fmt.Sprintf("failed to create comment: %s", err.Error()))
	}
Behavioral Consistency

When provider.IsCommentStrategyUpdate(repo) is true, CEL evaluation errors are reported immediately via reportCELValidationErrors instead of being aggregated into celValidationErrors. Confirm this matches the desired UX for multiple PipelineRuns and events (e.g., whether multiple failing PipelineRuns should still produce multiple distinct updated comments, and whether non-GitLab providers should ever reach this path).

	if provider.IsCommentStrategyUpdate(repo) {
		reportCELValidationErrors(ctx, repo, []*pacerrors.PacYamlValidations{{
			Name: prName,
			Err:  fmt.Errorf("CEL expression evaluation error: %s", sanitizeErrorAsMarkdown(err)),
		}}, eventEmitter, vcx, event, fmt.Sprintf(provider.PlrStatusCommentPrefixTemplate, prName))
	} else {
		celValidationErrors = append(celValidationErrors, &pacerrors.PacYamlValidations{
			Name: prName,
			Err:  fmt.Errorf("CEL expression evaluation error: %s", sanitizeErrorAsMarkdown(err)),
		})
	}
}
Comment Update Semantics

The update flow relies on a per-PipelineRun prefix (provider.PlrStatusCommentPrefixTemplate) and calls v.CreateComment with that prefix. Verify CreateComment truly updates the existing note by prefix for GitLab (vs always creating a new note), and that the prefix is stable/unique across retries and name changes (e.g., if statusOpts.OriginalPipelineRunName differs from prName in some paths).

case provider.UpdateCommentStrategy:
	if eventType == triggertype.PullRequest || provider.Valid(event.EventType, anyMergeRequestEventType) {
		statusComment := v.formatPipelineComment(event.SHA, statusOpts)
		// Creating the prefix that is added to the status comment for a pipeline run.
		plrStatusCommentPrefix := fmt.Sprintf(provider.PlrStatusCommentPrefixTemplate, statusOpts.OriginalPipelineRunName)
		// The entire markdown comment, including the prefix that is added to the pull request for the pipelinerun.
		markdownStatusComment := fmt.Sprintf("%s\n%s", plrStatusCommentPrefix, statusComment)

		if err := v.CreateComment(ctx, event, markdownStatusComment, plrStatusCommentPrefix); err != nil {
			v.eventEmitter.EmitMessage(
				v.repo,
				zap.ErrorLevel,
				"PipelineRunCommentCreationError",
				fmt.Sprintf("failed to create comment: %s", err.Error()),
			)
			return err
		}
	}

@theakshaypant theakshaypant force-pushed the SRVKP-10453-gitlab-update-comment-strategy branch from 43bf4b1 to ab9acbe Compare February 4, 2026 09:27
@theakshaypant
Copy link
Copy Markdown
Member Author

... Verify ... prefix is stable/unique across retries and name changes (e.g., if statusOpts.OriginalPipelineRunName differs from prName in some paths).

This is a good catch, addressed in ab9acbe

@theakshaypant theakshaypant force-pushed the SRVKP-10453-gitlab-update-comment-strategy branch from ab9acbe to 57a7295 Compare February 5, 2026 07:05
@qodo-code-review
Copy link
Copy Markdown

PR-Agent failed to apply 'global' repo settings

The configuration file needs to be a valid TOML, please fix it.


Error message:
cannot access local variable 'file_data' where it is not associated with a value

Configuration content:
[github_app]
pr_commands = [ "/review" ]

[pr_reviewer]
enable_review_labels_security = true
enable_chat_in_code_suggestions=false
enable_chat_in_code_suggestions = false
enable_summary=false
enable_help_text=false

[pr_description]
publish_description_as_comment = true

[pr_code_suggestions]
commitable_code_suggestions = true

[pr_test]
num_tests = 0

@theakshaypant theakshaypant force-pushed the SRVKP-10453-gitlab-update-comment-strategy branch 2 times, most recently from daed45e to 443b123 Compare February 6, 2026 04:17
@chmouel
Copy link
Copy Markdown
Member

chmouel commented Feb 12, 2026

if it's ready for review, can you remove the draft?

@theakshaypant theakshaypant force-pushed the SRVKP-10453-gitlab-update-comment-strategy branch from 443b123 to 8cf4d57 Compare February 12, 2026 09:32
@theakshaypant
Copy link
Copy Markdown
Member Author

if it's ready for review, can you remove the draft?

Will update with changes from this week and move it to ready.

@theakshaypant theakshaypant force-pushed the SRVKP-10453-gitlab-update-comment-strategy branch from 8cf4d57 to 6640a25 Compare February 12, 2026 09:38
Copy link
Copy Markdown
Member Author

@theakshaypant theakshaypant left a comment

Choose a reason for hiding this comment

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

I also decided to skip caching the comment ID in the PLR annotation in this implementation.
Consider a scenario where 5 PLRs complete, their respective comments are added, and the PLRs are patched with the comment IDs. If a new push triggers the same 5 PLRs again, and the previous runs have been cleaned up (eg, due to the max-keep-runs annotation or the pruner), we would end up fetching the comment via the Gitlab API using the original PR name marker anyway.
In my local testing, most lookups were done via the Gitlab API because older PLRs had already been cleaned up, so the annotation-based caching was rarely used. Given that, I felt the added complexity of maintaining this caching mechanism wasn’t justified, especially if it’s unlikely to be used frequently.
That said, I’m not sure if the same would hold true in other use cases, open to hearing other thoughts.

Comment on lines +301 to +320
if provider.IsCommentStrategyUpdate(repo) {
// Using the same logic for getting OriginalPipelineRun as the one used for setting
// the annotation which is used in the provider's "update" comment strategy.
originPipelineRunName := prun.GetName()
if originPipelineRunName == "" && prun.GenerateName != "" {
originPipelineRunName = prun.GetGenerateName()
}

if reportErrors {
reportCELValidationErrors(ctx, repo, []*pacerrors.PacYamlValidations{{
Name: originPipelineRunName,
Err: fmt.Errorf("CEL expression evaluation error: %s", sanitizeErrorAsMarkdown(err)),
}}, eventEmitter, vcx, event, fmt.Sprintf(provider.PlrStatusCommentPrefixTemplate, originPipelineRunName))
}
} else {
celValidationErrors = append(celValidationErrors, &pacerrors.PacYamlValidations{
Name: prName,
Err: fmt.Errorf("CEL expression evaluation error: %s", sanitizeErrorAsMarkdown(err)),
})
}
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Input needed here.
I’ve updated the behavior so that pipeline CEL validation error comments are replaced with the current PLR status once the issue is resolved. With this change, users will only see the latest state of a PLR (e.g., CEL error, validation error, running, success, failure).
This differs from the current behavior, where CEL error comments remain on the MR even after they’ve been fixed. I believe this provides a better UX by reflecting the most up-to-date status for each PLR.
WDYT @zakisk @chmouel?

@theakshaypant theakshaypant marked this pull request as ready for review February 12, 2026 10:19
@chmouel
Copy link
Copy Markdown
Member

chmouel commented Feb 13, 2026

I like this direction overall.

  • Dropping comment-ID caching sounds like the right tradeoff for now..
  • I also agree with the UX change for comment_strategy: update showing only the latest PLR state (CEL error -> running/success/failure) is cleaner than leaving stale CEL error comments around.

One thing I’d like us to fix before merge:

  • when dong the comment update matching, we currently compile the marker directly as regex. Since marker includes PLR name, regex-significant characters can make incorrect matches. Can we switch to regexp.QuoteMeta(updateMarker) before regexp.MustCompile(...)? (ie:
    would mismatch to and others).

Test coverage I’d like to see but skip it if they are too hard to implement for the values they gives:

  • CEL error is posted for a PLR, then replaced by status comment after the CEL issue is fixed.
  • Multiple PLRs in one MR each update only their own comment (no cross-updates).
  • Marker matching remains exact even when PLR names contain regex-relevant characters.

@theakshaypant
Copy link
Copy Markdown
Member Author

when dong the comment update matching, we currently compile the marker directly as regex. Since marker includes
PLR name, regex-significant characters can make incorrect matches. Can we switch to
regexp.QuoteMeta(updateMarker) before regexp.MustCompile(...)? (ie:
would mismatch to and others).

That's a good point, will make this change.

Test coverage I’d like to see but skip it if they are too hard to implement for the values they gives:

* CEL error is posted for a PLR, then replaced by status comment after the CEL issue is fixed.

* Multiple PLRs in one MR each update only their own comment (no cross-updates).

* Marker matching remains exact even when PLR names contain regex-relevant characters.

I was planning on adding the first 2 cases you mentioned but for github. Since comments are fallback on gitlab, I thought it would be easier to have this in e2e tests for github provider using webhook.

@theakshaypant theakshaypant force-pushed the SRVKP-10453-gitlab-update-comment-strategy branch from 6640a25 to 922bb39 Compare February 16, 2026 10:17
Adds an "update" comment strategy which updates a single comment
per PipelineRun on every trigger.

This comment strategy reports CEL validation errors immediately
with a PipelineRun-specific prefix when using the update comment
strategy, allowing them to be consolidated into a single updatable
comment per PipelineRun.

Jira: https://issues.redhat.com/browse/SRVKP-10453

Signed-off-by: Akshay Pant <akshay.akshaypant@gmail.com>
@theakshaypant theakshaypant force-pushed the SRVKP-10453-gitlab-update-comment-strategy branch from 922bb39 to 17e7020 Compare February 18, 2026 03:44
@zakisk zakisk merged commit 4c847ce into tektoncd:main Feb 19, 2026
10 checks passed
@theakshaypant theakshaypant deleted the SRVKP-10453-gitlab-update-comment-strategy branch February 19, 2026 06:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request feature New feature or request gitlab priority/p0

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants