← Back to Pull requests

Refactored Repowatch Controller #208

Merged
seans3 merged 3 files (838 lines) on Dec 13, 2025 21:17 UTC
View on GitHub
seans3 seans3 commented on Dec 11, 2025 20:07 UTC
Author

Refactored long reconcile function loops in the repowatch_controller to make it more readabile, testable, and maintainable.
Moved some refactored functions into new file repowatch_helpers.go
Added unit tests to repowatch_helpers_test.go (coverage: 67.0%).
TODO(Sean): Complete the refactor of the issueSandbox reconcile loop.

Diff: 838 lines (+543 / -295) across 3 files Reviewer: aaron-prindle Review duration: 2949m
All Vouch review confidence checks passed
Residual risk 0.04 = Change Risk (0.46) × (1 − Review Confidence (0.91)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.46 · 838 lines diff across 3 files
0.46
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 5 substantive comment(s)
0.89
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
90%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Real PR Conversation Timeline
6 items
aaron-prindle aaron-prindle commented on code on Dec 11, 2025 21:24 UTC
Code Review
repo-agent/repowatch/controllers/repowatch_helpers.go:1
@@ -0,0 +1,217 @@
+/*
+Copyright 2025.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controllers
+
+import (
+	"context"
+	"fmt"
+	"strconv"
+	"strings"
+	time "time"
+
+	reviewv1alpha1 "github.com/gke-labs/gemini-for-kubernetes-development/repo-agent/repowatch/api/v1alpha1"
+	"github.com/google/go-github/v39/github"
+	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+	"k8s.io/apimachinery/pkg/types"
+	"sigs.k8s.io/controller-runtime/pkg/log"
+)
+
+// createOrUpdateReviewSandboxes processes all open PRs, creating, updating, or marking them as pending.
+// It returns the lists of watched and pending PRs, and the final count of active sandboxes.
+func (r *RepoWatchReconciler) createOrUpdateReviewSandboxes(ctx context.Context, repoWatch *reviewv1alpha1.RepoWatch, allOpenPRs []*github.PullRequest, ownedSandboxes []unstructured.Unstructured, explicitPRs []*github.PullRequest, activeSandboxes int, totalSandboxes int) ([]reviewv1alpha1.WatchedPR, []reviewv1alpha1.PendingPR, int) {
+	log := log.FromContext(ctx)
+	watchedPRs := []reviewv1alpha1.WatchedPR{}
+	pendingPRs := []reviewv1alpha1.PendingPR{}
+
+	for _, pr := range allOpenPRs {
+		sandboxName := fmt.Sprintf("%s-pr-%d", repoWatch.Name, *pr.Number)
+		sandboxExists := false
+		for _, sandbox := range ownedSandboxes {
+			if sandbox.GetName() == sandboxName {
+				sandboxExists = true
+				// Scale down check
+				if repoWatch.Spec.Review.ReviewShutdownAfterMinutes > 0 {
+					creationTimestamp := sandbox.GetCreationTimestamp()
+					shutdownDuration := time.Minute * time.Duration(repoWatch.Spec.Review.ReviewShutdownAfterMinutes)
+					if time.Since(creationTimestamp.Time) > shutdownDuration {
+						replicas, found, err := unstructured.NestedInt64(sandbox.Object, "spec", "replicas")
+						if err == nil && found && replicas > 0 {
+							log.Info("scaling down sandbox", "sandbox", sandbox.GetName())
+							if err := unstructured.SetNestedField(sandbox.Object, int64(0), "spec", "replicas"); err != nil {
+								log.Error(err, "unable to set replicas for sandbox", "sandbox", sandbox.GetName())
+							} else {
+								if err := r.Update(ctx, &sandbox); err != nil {
+									log.Error(err, "unable to update sandbox", "sandbox", sandbox.GetName())
+								}
+							}
+						}
+					}
+				}
+				watchedPRs = append(watchedPRs, reviewv1alpha1.WatchedPR{
+					Number:      *pr.Number,
+					SandboxName: sandboxName,
+					Status:      "Active",
+				})
+				break
+			}
+		}
+
+		if sandboxExists {
+			continue
+		}
+
+		// Logic to create a new sandbox if it doesn't exist
+		prIsExplicit := false

minor nit: this logic is in countSandboxes and createOrUpdateReviewSandboxes. Might make sense to have a method like:

isPRExplicit(prNumber int, explicitPRs []*github.PullRequest) bool

aaron-prindle aaron-prindle commented on code on Dec 11, 2025 21:29 UTC
Code Review
repo-agent/repowatch/controllers/repowatch_helpers_test.go:1
@@ -18,240 +18,328 @@ package controllers
 
 import (
 	"context"
+	"fmt"
 	"testing"
+	"time"
 
 	reviewv1alpha1 "github.com/gke-labs/gemini-for-kubernetes-development/repo-agent/repowatch/api/v1alpha1"
 	"github.com/google/go-github/v39/github"
 	"github.com/onsi/gomega"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+	"k8s.io/apimachinery/pkg/runtime"
+	"k8s.io/apimachinery/pkg/runtime/schema"
+	"k8s.io/apimachinery/pkg/types"
+	clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake"
 )
 
-func TestFilterPRsByLabels(t *testing.T) {
+func TestCreateOrUpdateReviewSandboxes(t *testing.T) {
 	g := gomega.NewWithT(t)
+	s := runtime.NewScheme()
+	_ = reviewv1alpha1.AddToScheme(s)
 
-	// Helper to create PR with labels
-	createPR := func(number int, labels ...string) *github.PullRequest {
-		prLabels := []*github.Label{}
-		for _, l := range labels {
-			lStr := l // copy for pointer
-			prLabels = append(prLabels, &github.Label{Name: &lStr})
-		}
-		return &github.PullRequest{
-			Number: &number,
-			Labels: prLabels,
-		}
-	}
-
-	tests := []struct {
-		name           string
-		repoWatchSpec  reviewv1alpha1.RepoWatchSpec
-		inputPRs       []*github.PullRequest
-		expectedPRNums []int
-	}{
-		{
-			name: "No labels filter",
-			repoWatchSpec: reviewv1alpha1.RepoWatchSpec{
-				Review: reviewv1alpha1.PRReviewSpec{
-					Labels: [][]string{},
-				},
-			},
-			inputPRs: []*github.PullRequest{
-				createPR(1, "bug"),
-				createPR(2),
+	repoWatch := &reviewv1alpha1.RepoWatch{
+		ObjectMeta: metav1.ObjectMeta{Name: "test-watch", Namespace: "default"},
+		Spec: reviewv1alpha1.RepoWatchSpec{
+			Review: reviewv1alpha1.PRReviewSpec{
+				MaxActiveSandboxes:         1,
+				MaxSandboxes:               2,
+				ReviewShutdownAfterMinutes: 60,
 			},
-			expectedPRNums: []int{1, 2},
 		},
-		{
-			name: "Single label required",
-			repoWatchSpec: reviewv1alpha1.RepoWatchSpec{
-				Review: reviewv1alpha1.PRReviewSpec{
-					Labels: [][]string{{"bug"}},
-				},
-			},
-			inputPRs: []*github.PullRequest{
-				createPR(1, "bug"),
-				createPR(2, "enhancement"),
-				createPR(3, "bug", "critical"),
-			},
-			expectedPRNums: []int{1, 3},
-		},
-		{
-			name: "Multiple label sets (OR logic)",
-			repoWatchSpec: reviewv1alpha1.RepoWatchSpec{
-				Review: reviewv1alpha1.PRReviewSpec{
-					Labels: [][]string{{"bug"}, {"security"}},
-				},
-			},
-			inputPRs: []*github.PullRequest{
-				createPR(1, "bug"),
-				createPR(2, "enhancement"),
-				createPR(3, "security"),
-				createPR(4, "documentation"),
+	}
+
+	// PR that should be created
+	pr1Num := 1
+	pr1 := &github.PullRequest{Number: &pr1Num, Head: &github.PullRequestBranch{Repo: &github.Repository{CloneURL: github.String("url")}, Ref: github.String("ref")}} // Add dummy data to avoid nil pointers
+
+	// PR that should be pending (due to active limit)
+	pr2Num := 2
+	pr2 := &github.PullRequest{Number: &pr2Num, Head: &github.PullRequestBranch{Repo: &github.Repository{CloneURL: github.String("url")}, Ref: github.String("ref")}} // Add dummy data
+
+	// PR that should be blocked (due to total limit)
+	pr3Num := 3
+	pr3 := &github.PullRequest{Number: &pr3Num, Head: &github.PullRequestBranch{Repo: &github.Repository{CloneURL: github.String("url")}, Ref: github.String("ref")}} // Add dummy data
+
+	// PR with an existing, old sandbox that should be scaled down
+	pr4Num := 4
+	pr4 := &github.PullRequest{Number: &pr4Num}
+	oldSandbox := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"apiVersion": "custom.agents.x-k8s.io/v1alpha1",
+			"kind":       "ReviewSandbox",
+			"metadata": map[string]interface{}{
+				"name":              fmt.Sprintf("%s-pr-%d", repoWatch.Name, pr4Num),
+				"namespace":         "default",
+				"creationTimestamp": time.Now().Add(-61 * time.Minute).Format(time.RFC3339),
 			},
-			expectedPRNums: []int{1, 3},
+			"spec": map[string]interface{}{"replicas": int64(1)},
 		},
-		{
-			name: "Composite label set (AND logic)",
-			repoWatchSpec: reviewv1alpha1.RepoWatchSpec{
-				Review: reviewv1alpha1.PRReviewSpec{
-					Labels: [][]string{{"bug", "critical"}},
-				},
-			},
-			inputPRs: []*github.PullRequest{
-				createPR(1, "bug"),
-				createPR(2, "bug", "critical"),
-				createPR(3, "critical"),
+	}
+
+	r := &RepoWatchReconciler{
+		Client: clientfake.NewClientBuilder().WithScheme(s).WithObjects(oldSandbox).Build(),
+		Scheme: s,
+	}
+
+	// Start with one existing sandbox (oldSandbox)
+	ownedSandboxes := []unstructured.Unstructured{*oldSandbox}
+	active, total := 1, 1
+
+	watched, pending, finalActive := r.createOrUpdateReviewSandboxes(context.Background(), repoWatch, []*github.PullRequest{pr1, pr2, pr3, pr4}, ownedSandboxes, []*github.PullRequest{}, active, total)
+
+	// Asserts
+	g.Expect(finalActive).To(gomega.Equal(1), "Active count should be 1 because no new sandbox is created")
+	g.Expect(len(watched)).To(gomega.Equal(1), "Should have only one existing watched PR")
+	g.Expect(watched[0].Number).To(gomega.Equal(pr4Num))
+
+	g.Expect(len(pending)).To(gomega.Equal(3), "Should have three pending PRs")
+	g.Expect(pending[0].Number).To(gomega.Equal(pr1Num))
+	g.Expect(pending[1].Number).To(gomega.Equal(pr2Num))
+	g.Expect(pending[2].Number).To(gomega.Equal(pr3Num))
+
+	// Verify scale down
+	updatedSandbox := &unstructured.Unstructured{}
+	updatedSandbox.SetGroupVersionKind(schema.GroupVersionKind{Group: "custom.agents.x-k8s.io", Version: "v1alpha1", Kind: "ReviewSandbox"})
+	g.Expect(r.Client.Get(context.Background(), types.NamespacedName{Name: oldSandbox.GetName(), Namespace: "default"}, updatedSandbox)).To(gomega.Succeed())
+	replicas, _, _ := unstructured.NestedInt64(updatedSandbox.Object, "spec", "replicas")
+	g.Expect(replicas).To(gomega.Equal(int64(0)))
+}
+
+func TestCleanupClosedPRSandboxes(t *testing.T) {
+	g := gomega.NewWithT(t)
+	s := runtime.NewScheme()
+
+	closedPRSandbox := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"apiVersion": "custom.agents.x-k8s.io/v1alpha1",
+			"kind":       "ReviewSandbox",
+			"metadata": map[string]interface{}{
+				"name":      "test-repowatch-pr-2",
+				"namespace": "default",
 			},
-			expectedPRNums: []int{2},
 		},
 	}
 
-	r := &RepoWatchReconciler{}
+	openPRNumber := 1
+	openPR := &github.PullRequest{Number: &openPRNumber}
 
-	for _, tc := range tests {
-		t.Run(tc.name, func(_ *testing.T) {
-			repoWatch := &reviewv1alpha1.RepoWatch{Spec: tc.repoWatchSpec}
-			filtered := r.filterPRsByLabels(tc.inputPRs, repoWatch)
-
-			g.Expect(len(filtered)).To(gomega.Equal(len(tc.expectedPRNums)))
-			for i, pr := range filtered {
-				g.Expect(*pr.Number).To(gomega.Equal(tc.expectedPRNums[i]))
-			}
-		})
+	r := &RepoWatchReconciler{
+		Client: clientfake.NewClientBuilder().WithScheme(s).WithObjects(closedPRSandbox).Build(),
+		Scheme: s,
 	}
+
+	initialTotal := 1
+	ownedSandboxes := []unstructured.Unstructured{*closedPRSandbox}
+	allOpenPRs := []*github.PullRequest{openPR}
+
+	finalTotal := r.cleanupClosedPRSandboxes(context.Background(), initialTotal, ownedSandboxes, allOpenPRs)
+
+	g.Expect(finalTotal).To(gomega.Equal(0))
+
+	sandboxList := &unstructured.UnstructuredList{}
+	sandboxList.SetGroupVersionKind(schema.GroupVersionKind{
+		Group:   "custom.agents.x-k8s.io",
+		Version: "v1alpha1",
+		Kind:    "ReviewSandbox",
+	})
+	g.Expect(r.Client.List(context.Background(), sandboxList)).To(gomega.Succeed())
+	g.Expect(sandboxList.Items).To(gomega.HaveLen(0))
 }
 
-func TestDeduplicatePRs(t *testing.T) {
+func TestCountSandboxes(t *testing.T) {
 	g := gomega.NewWithT(t)
 
-	createPR := func(number int) *github.PullRequest {
-		return &github.PullRequest{Number: &number}
-	}
+	explicitPRNumber := 1
+	explicitPR := &github.PullRequest{Number: &explicitPRNumber}
 
-	tests := []struct {
-		name           string
-		prs            []*github.PullRequest
-		explicitPRs    []*github.PullRequest
-		expectedPRNums []int
-	}{
+	sandboxes := []unstructured.Unstructured{
 		{
-			name: "No duplicates",
-			prs: []*github.PullRequest{
-				createPR(1),
-				createPR(2),
-			},
-			explicitPRs: []*github.PullRequest{
-				createPR(3),
+			Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"name": "sandbox-pr-1", // Explicit
+				},
+				"spec": map[string]interface{}{
+					"replicas": int64(1),
+				},
 			},
-			expectedPRNums: []int{1, 2},
 		},
 		{
-			name: "With duplicates",
-			prs: []*github.PullRequest{
-				createPR(1),
-				createPR(2),
-				createPR(3),
-			},
-			explicitPRs: []*github.PullRequest{
-				createPR(2),
+			Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"name": "sandbox-pr-2", // Active
+				},
+				"spec": map[string]interface{}{
+					"replicas": int64(1),
+				},
 			},
-			expectedPRNums: []int{1, 3},
 		},
 		{
-			name: "All duplicates",
-			prs: []*github.PullRequest{
-				createPR(1),
+			Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"name": "sandbox-pr-3", // Inactive
+				},
+				"spec": map[string]interface{}{
+					"replicas": int64(0),
+				},
 			},
-			explicitPRs: []*github.PullRequest{
-				createPR(1),
+		},
+		{
+			Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"name": "sandbox-pr-4", // Active
+				},
+				"spec": map[string]interface{}{
+					"replicas": int64(1),
+				},
 			},
-			expectedPRNums: []int{},
 		},
 	}
 
-	r := &RepoWatchReconciler{}
-
-	for _, tc := range tests {
-		t.Run(tc.name, func(_ *testing.T) {
-			deduped := r.deduplicatePRs(tc.prs, tc.explicitPRs)
+	active, total := countSandboxes(sandboxes, []*github.PullRequest{explicitPR})
 
-			g.Expect(len(deduped)).To(gomega.Equal(len(tc.expectedPRNums)))
-			for i, pr := range deduped {
-				g.Expect(*pr.Number).To(gomega.Equal(tc.expectedPRNums[i]))
-			}
-		})
-	}
+	g.Expect(total).To(gomega.Equal(4))
+	g.Expect(active).To(gomega.Equal(2)) // Should not include the explicit PR's sandbox
 }
 
-func TestSortPRs(t *testing.T) {

Do we still need a test for SortPRs? I don't see such a test in the refactored code

seans3 seans3 commented on code on Dec 12, 2025 01:11 UTC
Code Review
repo-agent/repowatch/controllers/repowatch_helpers_test.go:1
@@ -18,240 +18,328 @@ package controllers
 
 import (
 	"context"
+	"fmt"
 	"testing"
+	"time"
 
 	reviewv1alpha1 "github.com/gke-labs/gemini-for-kubernetes-development/repo-agent/repowatch/api/v1alpha1"
 	"github.com/google/go-github/v39/github"
 	"github.com/onsi/gomega"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+	"k8s.io/apimachinery/pkg/runtime"
+	"k8s.io/apimachinery/pkg/runtime/schema"
+	"k8s.io/apimachinery/pkg/types"
+	clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake"
 )
 
-func TestFilterPRsByLabels(t *testing.T) {
+func TestCreateOrUpdateReviewSandboxes(t *testing.T) {
 	g := gomega.NewWithT(t)
+	s := runtime.NewScheme()
+	_ = reviewv1alpha1.AddToScheme(s)
 
-	// Helper to create PR with labels
-	createPR := func(number int, labels ...string) *github.PullRequest {
-		prLabels := []*github.Label{}
-		for _, l := range labels {
-			lStr := l // copy for pointer
-			prLabels = append(prLabels, &github.Label{Name: &lStr})
-		}
-		return &github.PullRequest{
-			Number: &number,
-			Labels: prLabels,
-		}
-	}
-
-	tests := []struct {
-		name           string
-		repoWatchSpec  reviewv1alpha1.RepoWatchSpec
-		inputPRs       []*github.PullRequest
-		expectedPRNums []int
-	}{
-		{
-			name: "No labels filter",
-			repoWatchSpec: reviewv1alpha1.RepoWatchSpec{
-				Review: reviewv1alpha1.PRReviewSpec{
-					Labels: [][]string{},
-				},
-			},
-			inputPRs: []*github.PullRequest{
-				createPR(1, "bug"),
-				createPR(2),
+	repoWatch := &reviewv1alpha1.RepoWatch{
+		ObjectMeta: metav1.ObjectMeta{Name: "test-watch", Namespace: "default"},
+		Spec: reviewv1alpha1.RepoWatchSpec{
+			Review: reviewv1alpha1.PRReviewSpec{
+				MaxActiveSandboxes:         1,
+				MaxSandboxes:               2,
+				ReviewShutdownAfterMinutes: 60,
 			},
-			expectedPRNums: []int{1, 2},
 		},
-		{
-			name: "Single label required",
-			repoWatchSpec: reviewv1alpha1.RepoWatchSpec{
-				Review: reviewv1alpha1.PRReviewSpec{
-					Labels: [][]string{{"bug"}},
-				},
-			},
-			inputPRs: []*github.PullRequest{
-				createPR(1, "bug"),
-				createPR(2, "enhancement"),
-				createPR(3, "bug", "critical"),
-			},
-			expectedPRNums: []int{1, 3},
-		},
-		{
-			name: "Multiple label sets (OR logic)",
-			repoWatchSpec: reviewv1alpha1.RepoWatchSpec{
-				Review: reviewv1alpha1.PRReviewSpec{
-					Labels: [][]string{{"bug"}, {"security"}},
-				},
-			},
-			inputPRs: []*github.PullRequest{
-				createPR(1, "bug"),
-				createPR(2, "enhancement"),
-				createPR(3, "security"),
-				createPR(4, "documentation"),
+	}
+
+	// PR that should be created
+	pr1Num := 1
+	pr1 := &github.PullRequest{Number: &pr1Num, Head: &github.PullRequestBranch{Repo: &github.Repository{CloneURL: github.String("url")}, Ref: github.String("ref")}} // Add dummy data to avoid nil pointers
+
+	// PR that should be pending (due to active limit)
+	pr2Num := 2
+	pr2 := &github.PullRequest{Number: &pr2Num, Head: &github.PullRequestBranch{Repo: &github.Repository{CloneURL: github.String("url")}, Ref: github.String("ref")}} // Add dummy data
+
+	// PR that should be blocked (due to total limit)
+	pr3Num := 3
+	pr3 := &github.PullRequest{Number: &pr3Num, Head: &github.PullRequestBranch{Repo: &github.Repository{CloneURL: github.String("url")}, Ref: github.String("ref")}} // Add dummy data
+
+	// PR with an existing, old sandbox that should be scaled down
+	pr4Num := 4
+	pr4 := &github.PullRequest{Number: &pr4Num}
+	oldSandbox := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"apiVersion": "custom.agents.x-k8s.io/v1alpha1",
+			"kind":       "ReviewSandbox",
+			"metadata": map[string]interface{}{
+				"name":              fmt.Sprintf("%s-pr-%d", repoWatch.Name, pr4Num),
+				"namespace":         "default",
+				"creationTimestamp": time.Now().Add(-61 * time.Minute).Format(time.RFC3339),
 			},
-			expectedPRNums: []int{1, 3},
+			"spec": map[string]interface{}{"replicas": int64(1)},
 		},
-		{
-			name: "Composite label set (AND logic)",
-			repoWatchSpec: reviewv1alpha1.RepoWatchSpec{
-				Review: reviewv1alpha1.PRReviewSpec{
-					Labels: [][]string{{"bug", "critical"}},
-				},
-			},
-			inputPRs: []*github.PullRequest{
-				createPR(1, "bug"),
-				createPR(2, "bug", "critical"),
-				createPR(3, "critical"),
+	}
+
+	r := &RepoWatchReconciler{
+		Client: clientfake.NewClientBuilder().WithScheme(s).WithObjects(oldSandbox).Build(),
+		Scheme: s,
+	}
+
+	// Start with one existing sandbox (oldSandbox)
+	ownedSandboxes := []unstructured.Unstructured{*oldSandbox}
+	active, total := 1, 1
+
+	watched, pending, finalActive := r.createOrUpdateReviewSandboxes(context.Background(), repoWatch, []*github.PullRequest{pr1, pr2, pr3, pr4}, ownedSandboxes, []*github.PullRequest{}, active, total)
+
+	// Asserts
+	g.Expect(finalActive).To(gomega.Equal(1), "Active count should be 1 because no new sandbox is created")
+	g.Expect(len(watched)).To(gomega.Equal(1), "Should have only one existing watched PR")
+	g.Expect(watched[0].Number).To(gomega.Equal(pr4Num))
+
+	g.Expect(len(pending)).To(gomega.Equal(3), "Should have three pending PRs")
+	g.Expect(pending[0].Number).To(gomega.Equal(pr1Num))
+	g.Expect(pending[1].Number).To(gomega.Equal(pr2Num))
+	g.Expect(pending[2].Number).To(gomega.Equal(pr3Num))
+
+	// Verify scale down
+	updatedSandbox := &unstructured.Unstructured{}
+	updatedSandbox.SetGroupVersionKind(schema.GroupVersionKind{Group: "custom.agents.x-k8s.io", Version: "v1alpha1", Kind: "ReviewSandbox"})
+	g.Expect(r.Client.Get(context.Background(), types.NamespacedName{Name: oldSandbox.GetName(), Namespace: "default"}, updatedSandbox)).To(gomega.Succeed())
+	replicas, _, _ := unstructured.NestedInt64(updatedSandbox.Object, "spec", "replicas")
+	g.Expect(replicas).To(gomega.Equal(int64(0)))
+}
+
+func TestCleanupClosedPRSandboxes(t *testing.T) {
+	g := gomega.NewWithT(t)
+	s := runtime.NewScheme()
+
+	closedPRSandbox := &unstructured.Unstructured{
+		Object: map[string]interface{}{
+			"apiVersion": "custom.agents.x-k8s.io/v1alpha1",
+			"kind":       "ReviewSandbox",
+			"metadata": map[string]interface{}{
+				"name":      "test-repowatch-pr-2",
+				"namespace": "default",
 			},
-			expectedPRNums: []int{2},
 		},
 	}
 
-	r := &RepoWatchReconciler{}
+	openPRNumber := 1
+	openPR := &github.PullRequest{Number: &openPRNumber}
 
-	for _, tc := range tests {
-		t.Run(tc.name, func(_ *testing.T) {
-			repoWatch := &reviewv1alpha1.RepoWatch{Spec: tc.repoWatchSpec}
-			filtered := r.filterPRsByLabels(tc.inputPRs, repoWatch)
-
-			g.Expect(len(filtered)).To(gomega.Equal(len(tc.expectedPRNums)))
-			for i, pr := range filtered {
-				g.Expect(*pr.Number).To(gomega.Equal(tc.expectedPRNums[i]))
-			}
-		})
+	r := &RepoWatchReconciler{
+		Client: clientfake.NewClientBuilder().WithScheme(s).WithObjects(closedPRSandbox).Build(),
+		Scheme: s,
 	}
+
+	initialTotal := 1
+	ownedSandboxes := []unstructured.Unstructured{*closedPRSandbox}
+	allOpenPRs := []*github.PullRequest{openPR}
+
+	finalTotal := r.cleanupClosedPRSandboxes(context.Background(), initialTotal, ownedSandboxes, allOpenPRs)
+
+	g.Expect(finalTotal).To(gomega.Equal(0))
+
+	sandboxList := &unstructured.UnstructuredList{}
+	sandboxList.SetGroupVersionKind(schema.GroupVersionKind{
+		Group:   "custom.agents.x-k8s.io",
+		Version: "v1alpha1",
+		Kind:    "ReviewSandbox",
+	})
+	g.Expect(r.Client.List(context.Background(), sandboxList)).To(gomega.Succeed())
+	g.Expect(sandboxList.Items).To(gomega.HaveLen(0))
 }
 
-func TestDeduplicatePRs(t *testing.T) {
+func TestCountSandboxes(t *testing.T) {
 	g := gomega.NewWithT(t)
 
-	createPR := func(number int) *github.PullRequest {
-		return &github.PullRequest{Number: &number}
-	}
+	explicitPRNumber := 1
+	explicitPR := &github.PullRequest{Number: &explicitPRNumber}
 
-	tests := []struct {
-		name           string
-		prs            []*github.PullRequest
-		explicitPRs    []*github.PullRequest
-		expectedPRNums []int
-	}{
+	sandboxes := []unstructured.Unstructured{
 		{
-			name: "No duplicates",
-			prs: []*github.PullRequest{
-				createPR(1),
-				createPR(2),
-			},
-			explicitPRs: []*github.PullRequest{
-				createPR(3),
+			Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"name": "sandbox-pr-1", // Explicit
+				},
+				"spec": map[string]interface{}{
+					"replicas": int64(1),
+				},
 			},
-			expectedPRNums: []int{1, 2},
 		},
 		{
-			name: "With duplicates",
-			prs: []*github.PullRequest{
-				createPR(1),
-				createPR(2),
-				createPR(3),
-			},
-			explicitPRs: []*github.PullRequest{
-				createPR(2),
+			Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"name": "sandbox-pr-2", // Active
+				},
+				"spec": map[string]interface{}{
+					"replicas": int64(1),
+				},
 			},
-			expectedPRNums: []int{1, 3},
 		},
 		{
-			name: "All duplicates",
-			prs: []*github.PullRequest{
-				createPR(1),
+			Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"name": "sandbox-pr-3", // Inactive
+				},
+				"spec": map[string]interface{}{
+					"replicas": int64(0),
+				},
 			},
-			explicitPRs: []*github.PullRequest{
-				createPR(1),
+		},
+		{
+			Object: map[string]interface{}{
+				"metadata": map[string]interface{}{
+					"name": "sandbox-pr-4", // Active
+				},
+				"spec": map[string]interface{}{
+					"replicas": int64(1),
+				},
 			},
-			expectedPRNums: []int{},
 		},
 	}
 
-	r := &RepoWatchReconciler{}
-
-	for _, tc := range tests {
-		t.Run(tc.name, func(_ *testing.T) {
-			deduped := r.deduplicatePRs(tc.prs, tc.explicitPRs)
+	active, total := countSandboxes(sandboxes, []*github.PullRequest{explicitPR})
 
-			g.Expect(len(deduped)).To(gomega.Equal(len(tc.expectedPRNums)))
-			for i, pr := range deduped {
-				g.Expect(*pr.Number).To(gomega.Equal(tc.expectedPRNums[i]))
-			}
-		})
-	}
+	g.Expect(total).To(gomega.Equal(4))
+	g.Expect(active).To(gomega.Equal(2)) // Should not include the explicit PR's sandbox
 }
 
-func TestSortPRs(t *testing.T) {

Good catch. I've reintroduced the TestSortPRs, and refactored the sortPRs function into the helpers file. Please have a look and let me know what you think.

seans3 seans3 commented on code on Dec 12, 2025 01:26 UTC
Code Review
repo-agent/repowatch/controllers/repowatch_helpers.go:1
@@ -0,0 +1,217 @@
+/*
+Copyright 2025.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controllers
+
+import (
+	"context"
+	"fmt"
+	"strconv"
+	"strings"
+	time "time"
+
+	reviewv1alpha1 "github.com/gke-labs/gemini-for-kubernetes-development/repo-agent/repowatch/api/v1alpha1"
+	"github.com/google/go-github/v39/github"
+	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+	"k8s.io/apimachinery/pkg/types"
+	"sigs.k8s.io/controller-runtime/pkg/log"
+)
+
+// createOrUpdateReviewSandboxes processes all open PRs, creating, updating, or marking them as pending.
+// It returns the lists of watched and pending PRs, and the final count of active sandboxes.
+func (r *RepoWatchReconciler) createOrUpdateReviewSandboxes(ctx context.Context, repoWatch *reviewv1alpha1.RepoWatch, allOpenPRs []*github.PullRequest, ownedSandboxes []unstructured.Unstructured, explicitPRs []*github.PullRequest, activeSandboxes int, totalSandboxes int) ([]reviewv1alpha1.WatchedPR, []reviewv1alpha1.PendingPR, int) {
+	log := log.FromContext(ctx)
+	watchedPRs := []reviewv1alpha1.WatchedPR{}
+	pendingPRs := []reviewv1alpha1.PendingPR{}
+
+	for _, pr := range allOpenPRs {
+		sandboxName := fmt.Sprintf("%s-pr-%d", repoWatch.Name, *pr.Number)
+		sandboxExists := false
+		for _, sandbox := range ownedSandboxes {
+			if sandbox.GetName() == sandboxName {
+				sandboxExists = true
+				// Scale down check
+				if repoWatch.Spec.Review.ReviewShutdownAfterMinutes > 0 {
+					creationTimestamp := sandbox.GetCreationTimestamp()
+					shutdownDuration := time.Minute * time.Duration(repoWatch.Spec.Review.ReviewShutdownAfterMinutes)
+					if time.Since(creationTimestamp.Time) > shutdownDuration {
+						replicas, found, err := unstructured.NestedInt64(sandbox.Object, "spec", "replicas")
+						if err == nil && found && replicas > 0 {
+							log.Info("scaling down sandbox", "sandbox", sandbox.GetName())
+							if err := unstructured.SetNestedField(sandbox.Object, int64(0), "spec", "replicas"); err != nil {
+								log.Error(err, "unable to set replicas for sandbox", "sandbox", sandbox.GetName())
+							} else {
+								if err := r.Update(ctx, &sandbox); err != nil {
+									log.Error(err, "unable to update sandbox", "sandbox", sandbox.GetName())
+								}
+							}
+						}
+					}
+				}
+				watchedPRs = append(watchedPRs, reviewv1alpha1.WatchedPR{
+					Number:      *pr.Number,
+					SandboxName: sandboxName,
+					Status:      "Active",
+				})
+				break
+			}
+		}
+
+		if sandboxExists {
+			continue
+		}
+
+		// Logic to create a new sandbox if it doesn't exist
+		prIsExplicit := false

Good Call. I've refactored the common isPRExplicit function out and added unit tests for it. Please let me know what you think.

barney-s barney-s commented on Dec 12, 2025 23:41 UTC
Contributor

@seans3 - Please rebase to get the e2e tests

Reviewers
Assignees
seans3 seans3
Labels
risk: low confidence: 90.6% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 45.9% (MEDIUM) · Higher = larger blast radius
45.9%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 90.6% · Lower = rushed or shallow review
90.6%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 4.3% · Safe to merge
4.3%