Skip to content

Commit 092c22b

Browse files
committed
fix: don't restart successful pipelineruns on /retest /ok-to-test
/retest and /ok-to-test should only restart failed pipelines; the changes in the PR ensure that we do not match successful pipelineruns during invocation of these gitops commands. The tests have also been updated to use /test instead wherever /retest is being used to restart successful pipelines Signed-off-by: Vibhav Bobade <[email protected]> Assisted-by: Claude-4-Sonnet (via Cursor)
1 parent e76ae6c commit 092c22b

14 files changed

+354
-53
lines changed

docs/content/_index.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ tracking using a Git workflow.
3535

3636
<--->
3737

38-
- Pull-request "*GitOps*" actions through comments with `/retest`, `/test <pipeline-name>` and so on.
38+
- Pull-request "*GitOps*" actions through comments with `/retest` (reruns failed pipelines), `/test <pipeline-name>` (force rerun specific pipeline) and so on.
3939

4040
- Automatic Task resolution in Pipelines (local Tasks, Artifact Hub, and remote URLs)
4141

docs/content/docs/guide/gitops_commands.md

Lines changed: 36 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ The advantage of using a `GitOps command` is that it provides a journal of all t
1010

1111
## GitOps Commands on Pull Requests
1212

13-
For example, when you are on a Pull Request, you may want to restart all your PipelineRuns. To do so, you can add a comment on your Pull Request starting with `/retest`, and all PipelineRuns attached to that Pull Request will be restarted.
13+
For example, when you are on a Pull Request, you may want to restart failed PipelineRuns. To do so, you can add a comment on your Pull Request starting with `/retest`, and all **failed** PipelineRuns attached to that Pull Request will be restarted. If all previous PipelineRuns for the same commit were successful, no new PipelineRuns will be created to avoid unnecessary duplication.
1414

1515
Example:
1616

@@ -21,6 +21,23 @@ failure is not with your PR but seems to be an infrastructure issue.
2121
/retest
2222
```
2323

24+
The `/retest` command will only create new PipelineRuns if:
25+
26+
- Previously **failed** PipelineRuns for the same commit, OR
27+
- No PipelineRun has been run for the same commit yet
28+
29+
If a successful PipelineRun already exists for the same commit, `/retest` will **skip** triggering a new PipelineRun to avoid unnecessary duplication.
30+
31+
**To force a rerun regardless of previous status**, use:
32+
33+
```text
34+
/retest <pipelinerun-name>
35+
```
36+
37+
This will always trigger a new PipelineRun, even if previous runs were successful.
38+
39+
Similar to `/retest`, the `/ok-to-test` command will only trigger new PipelineRuns if no successful PipelineRun already exists for the same commit. This prevents duplicate runs when repository owners repeatedly test the same commit by `/test` and `/retest` command.
40+
2441
If you have multiple `PipelineRun` and you want to target a specific `PipelineRun`, you can use the `/test` command followed by the specific PipelineRun name to restart it. Example:
2542

2643
```text
@@ -241,10 +258,10 @@ You can pass those `key=value` pairs anywhere in your comment, and they will be
241258

242259
There are different formats that can be accepted, allowing you to pass values with spaces or newlines:
243260

244-
* key=value
245-
* key="a value"
246-
* key="another \"value\" defined"
247-
* key="another
261+
- key=value
262+
- key="a value"
263+
- key="another \"value\" defined"
264+
- key="another
248265
value with newline"
249266

250267
## Event Type Annotation and Dynamic Variables
@@ -253,14 +270,14 @@ The `pipeline.tekton.dev/event-type` annotation indicates the type of GitOps com
253270

254271
Here are the possible event types:
255272

256-
* `test-all-comment`: The event is a single `/test` that would test every matched PipelineRun.
257-
* `test-comment`: The event is a `/test <PipelineRun>` comment that would test a specific PipelineRun.
258-
* `retest-all-comment`: The event is a single `/retest` that would retest every matched PipelineRun.
259-
* `retest-comment`: The event is a `/retest <PipelineRun>` that would retest a specific PipelineRun.
260-
* `on-comment`: The event is coming from a custom comment that would trigger a PipelineRun.
261-
* `cancel-all-comment`: The event is a single `/cancel` that would cancel every matched PipelineRun.
262-
* `cancel-comment`: The event is a `/cancel <PipelineRun>` that would cancel a specific PipelineRun.
263-
* `ok-to-test-comment`: The event is a `/ok-to-test` that would allow running the CI for an unauthorized user.
273+
- `test-all-comment`: The event is a single `/test` that would test every matched PipelineRun.
274+
- `test-comment`: The event is a `/test <PipelineRun>` comment that would test a specific PipelineRun.
275+
- `retest-all-comment`: The event is a single `/retest` that would retest every matched **failed** PipelineRun. If a successful PipelineRun already exists for the same commit, no new PipelineRun will be created.
276+
- `retest-comment`: The event is a `/retest <PipelineRun>` that would retest a specific PipelineRun.
277+
- `on-comment`: The event is coming from a custom comment that would trigger a PipelineRun.
278+
- `cancel-all-comment`: The event is a single `/cancel` that would cancel every matched PipelineRun.
279+
- `cancel-comment`: The event is a `/cancel <PipelineRun>` that would cancel a specific PipelineRun.
280+
- `ok-to-test-comment`: The event is a `/ok-to-test` that would allow running the CI for an unauthorized user. If a successful PipelineRun already exists for the same commit, no new PipelineRun will be created.
264281

265282
If a repository owner comments `/ok-to-test` on a pull request from an external contributor but no PipelineRun **matches** the `pull_request` event (or the repository has no `.tekton` directory), Pipelines-as-Code sets a **neutral** commit status. This indicates that no PipelineRun was matched, allowing other workflows—such as auto-merge—to proceed without being blocked.
266283

@@ -272,12 +289,12 @@ Note: This neutral check-run status functionality is only supported on GitHub.
272289

273290
When using the `{{ event_type }}` [dynamic variable]({{< relref "/docs/guide/authoringprs.md#dynamic-variables" >}}) for the following event types:
274291

275-
* `test-all-comment`
276-
* `test-comment`
277-
* `retest-all-comment`
278-
* `retest-comment`
279-
* `cancel-all-comment`
280-
* `ok-to-test-comment`
292+
- `test-all-comment`
293+
- `test-comment`
294+
- `retest-all-comment`
295+
- `retest-comment`
296+
- `cancel-all-comment`
297+
- `ok-to-test-comment`
281298

282299
The dynamic variable will return `pull_request` as the event type instead of the specific categorized GitOps command type. This is to handle backward compatibility with previous releases for users relying on this dynamic variable.
283300

docs/content/docs/guide/policy.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ or other supported Git providers (currently GitHub and Gitea).
2323
to trigger the CI for a pull request by commenting `/ok-to-test`. This enables
2424
CI to run on pull requests submitted by contributors who are not collaborators
2525
of the repository or organization. It also applies to `/test` and `/retest`
26-
commands. This action takes precedence over the `pull_request` action.
26+
commands. Note that `/retest` will only trigger failed PipelineRuns. This action takes precedence over the `pull_request` action.
2727

2828
## Configuring Policies in the Repository CR
2929

hack/gh-workflow-ci.sh

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,10 @@ get_tests() {
7474
mapfile -t testfiles < <(find test/ -maxdepth 1 -name '*.go')
7575
ghglabre="Github|Gitlab|Bitbucket"
7676
if [[ ${target} == "providers" ]]; then
77+
# echo "TestGithubMaxKeepRuns"
7778
grep -hioP "^func Test.*(${ghglabre})(\w+)\(" "${testfiles[@]}" | sed -e 's/func[ ]*//' -e 's/($//'
78-
elif [[ ${target} == "gitea_others" ]]; then
79+
elif [[ ${target} == "gitea_others" ]]; then
80+
# echo "TestGiteaParamsOnRepoCR"
7981
grep -hioP '^func Test(\w+)\(' "${testfiles[@]}" | grep -iPv "(${ghglabre})" | sed -e 's/func[ ]*//' -e 's/($//'
8082
else
8183
echo "Invalid target: ${target}"

pkg/matcher/annotation_matcher.go

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
apipac "github.com/openshift-pipelines/pipelines-as-code/pkg/apis/pipelinesascode/v1alpha1"
1212
pacerrors "github.com/openshift-pipelines/pipelines-as-code/pkg/errors"
1313
"github.com/openshift-pipelines/pipelines-as-code/pkg/events"
14+
"github.com/openshift-pipelines/pipelines-as-code/pkg/formatting"
1415
"github.com/openshift-pipelines/pipelines-as-code/pkg/opscomments"
1516
"github.com/openshift-pipelines/pipelines-as-code/pkg/params"
1617
"github.com/openshift-pipelines/pipelines-as-code/pkg/params/info"
@@ -21,6 +22,8 @@ import (
2122
"github.com/google/cel-go/common/types"
2223
tektonv1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1"
2324
"go.uber.org/zap"
25+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
26+
"knative.dev/pkg/apis"
2427
)
2528

2629
const (
@@ -366,12 +369,120 @@ func MatchPipelinerunByAnnotation(ctx context.Context, logger *zap.SugaredLogger
366369
}
367370

368371
if len(matchedPRs) > 0 {
372+
// Filter out templates that already have successful PipelineRuns for /retest and /ok-to-test
373+
if event.EventType == opscomments.RetestAllCommentEventType.String() ||
374+
event.EventType == opscomments.OkToTestCommentEventType.String() {
375+
return filterSuccessfulTemplates(ctx, logger, cs, event, repo, matchedPRs), nil
376+
}
369377
return matchedPRs, nil
370378
}
371379

372380
return nil, fmt.Errorf("%s", buildAvailableMatchingAnnotationErr(event, pruns))
373381
}
374382

383+
// filterSuccessfulTemplates filters out templates that already have successful PipelineRuns
384+
// when executing /ok-to-test or /retest gitops commands, implementing per-template checking.
385+
func filterSuccessfulTemplates(ctx context.Context, logger *zap.SugaredLogger, cs *params.Run, event *info.Event, repo *apipac.Repository, matchedPRs []Match) []Match {
386+
if event.SHA == "" {
387+
return matchedPRs
388+
}
389+
390+
// Get all existing PipelineRuns for this SHA
391+
labelSelector := fmt.Sprintf("%s=%s", keys.SHA, formatting.CleanValueKubernetes(event.SHA))
392+
existingPRs, err := cs.Clients.Tekton.TektonV1().PipelineRuns(repo.GetNamespace()).List(ctx, metav1.ListOptions{
393+
LabelSelector: labelSelector,
394+
})
395+
if err != nil {
396+
logger.Errorf("failed to list existing PipelineRuns for SHA %s: %v", event.SHA, err)
397+
return matchedPRs // Return all templates if we can't check
398+
}
399+
400+
// Create a map of template names to their most recent successful run
401+
successfulTemplates := make(map[string]*tektonv1.PipelineRun)
402+
403+
for i := range existingPRs.Items {
404+
pr := &existingPRs.Items[i]
405+
406+
// Get the original template name this PipelineRun came from
407+
originalPRName, ok := pr.GetAnnotations()[keys.OriginalPRName]
408+
if !ok {
409+
originalPRName, ok = pr.GetLabels()[keys.OriginalPRName]
410+
}
411+
if !ok {
412+
continue // Skip PipelineRuns without template identification
413+
}
414+
415+
// Check if this PipelineRun succeeded
416+
if pr.Status.GetCondition(apis.ConditionSucceeded).IsTrue() {
417+
// Keep the most recent successful run for each template
418+
if existing, exists := successfulTemplates[originalPRName]; !exists ||
419+
pr.CreationTimestamp.After(existing.CreationTimestamp.Time) {
420+
successfulTemplates[originalPRName] = pr
421+
}
422+
}
423+
}
424+
425+
// Filter out templates that have successful runs
426+
var filteredPRs []Match
427+
var anySkipped bool
428+
429+
for _, match := range matchedPRs {
430+
templateName := getName(match.PipelineRun)
431+
432+
if successfulPR, hasSuccessfulRun := successfulTemplates[templateName]; hasSuccessfulRun {
433+
logger.Infof("skipping template '%s' for sha %s as it already has a successful pipelinerun '%s'",
434+
templateName, event.SHA, successfulPR.Name)
435+
anySkipped = true
436+
} else {
437+
filteredPRs = append(filteredPRs, match)
438+
}
439+
}
440+
441+
// If all templates were skipped, return a reference to the first successful one
442+
if len(filteredPRs) == 0 && anySkipped && len(successfulTemplates) > 0 {
443+
// Return any successful run as reference
444+
for _, successfulPR := range successfulTemplates {
445+
return []Match{{PipelineRun: successfulPR, Repo: repo}}
446+
}
447+
}
448+
449+
return filteredPRs
450+
}
451+
452+
// checkForExistingSuccessfulPipelineRun is a helper function for testing.
453+
// It checks if there's an existing successful PipelineRun for the same SHA.
454+
func checkForExistingSuccessfulPipelineRun(ctx context.Context, logger *zap.SugaredLogger, cs *params.Run, event *info.Event, repo *apipac.Repository) *tektonv1.PipelineRun {
455+
// Only check for /retest and /ok-to-test commands
456+
if event.EventType != opscomments.RetestAllCommentEventType.String() &&
457+
event.EventType != opscomments.OkToTestCommentEventType.String() ||
458+
event.SHA == "" {
459+
return nil
460+
}
461+
462+
labelSelector := fmt.Sprintf("%s=%s", keys.SHA, formatting.CleanValueKubernetes(event.SHA))
463+
existingPRs, err := cs.Clients.Tekton.TektonV1().PipelineRuns(repo.GetNamespace()).List(ctx, metav1.ListOptions{
464+
LabelSelector: labelSelector,
465+
})
466+
if err != nil {
467+
logger.Errorf("failed to list existing PipelineRuns for SHA %s: %v", event.SHA, err)
468+
return nil
469+
}
470+
471+
// Find the most recent successful PipelineRun
472+
var mostRecentSuccessfulPR *tektonv1.PipelineRun
473+
for i := range existingPRs.Items {
474+
pr := &existingPRs.Items[i]
475+
if pr.Status.GetCondition(apis.ConditionSucceeded).IsTrue() {
476+
if mostRecentSuccessfulPR == nil ||
477+
pr.CreationTimestamp.After(mostRecentSuccessfulPR.CreationTimestamp.Time) {
478+
mostRecentSuccessfulPR = pr
479+
}
480+
}
481+
}
482+
483+
return mostRecentSuccessfulPR
484+
}
485+
375486
func buildAvailableMatchingAnnotationErr(event *info.Event, pruns []*tektonv1.PipelineRun) string {
376487
errmsg := "available annotations of the PipelineRuns annotations in .tekton/ dir:"
377488
for _, prun := range pruns {

0 commit comments

Comments
 (0)