Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(review): run the standard rule review in place of V1 on dev builds (#21630)

rebelice7ef3306741d2
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index 324a33a48e..9237ac7175 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -15155,6 +15155,12 @@ components:
description: |-
Every database the result applies to, sorted.
Format: instances/{instance}/databases/{database}
+ superseded:
+ type: boolean
+ title: superseded
+ description: |-
+ A later run of the same reviewer has completed, so the result is not
+ from the latest review, whatever its thread state.
title: ReviewMetadata
additionalProperties: false
description: What a review result carries beyond its text.
@@ -19558,6 +19564,14 @@ components:
failed to execute (a platform problem, never the SQL — SQL problems are
review results on a DONE run).
readOnly: true
+ outdated:
+ type: boolean
+ title: outdated
+ description: |-
+ Whether the plan's SQL changed after this run started, so the run
+ reviews an earlier version of it. The server starts a new run before it
+ creates the rollout automatically.
+ readOnly: true
title: ReviewRun
additionalProperties: false
bytebase.v1.ReviewRun.Status:
diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.go
index 2331bed420..f69fd45a24 100644
--- a/backend/api/v1/issue_service.go
+++ b/backend/api/v1/issue_service.go
@@ -19,6 +19,7 @@ import (
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/common/permission"
"github.com/bytebase/bytebase/backend/component/bus"
+ "github.com/bytebase/bytebase/backend/component/config"
"github.com/bytebase/bytebase/backend/component/iam"
"github.com/bytebase/bytebase/backend/component/review"
"github.com/bytebase/bytebase/backend/component/webhook"
@@ -38,6 +39,7 @@ type IssueService struct {
bus *bus.Bus
licenseService *enterprise.LicenseService
iamManager *iam.Manager
+ profile *config.Profile
reviewWorkflow *review.Workflow
}
@@ -48,6 +50,7 @@ func NewIssueService(
bus *bus.Bus,
licenseService *enterprise.LicenseService,
iamManager *iam.Manager,
+ profile *config.Profile,
) *IssueService {
return &IssueService{
store: store,
@@ -55,6 +58,7 @@ func NewIssueService(
bus: bus,
licenseService: licenseService,
iamManager: iamManager,
+ profile: profile,
reviewWorkflow: review.NewWorkflow(store),
}
}
@@ -521,6 +525,11 @@ func (s *IssueService) CreateIssue(ctx context.Context, req *connect.Request[v1p
}
}
+ // The review starts before the workflow, whose approval check can create
+ // the rollout: a slot already in place holds it until the review is done.
+ if created {
+ startRuleReview(ctx, s.profile, s.store, s.bus, issue)
+ }
if created && !issue.Payload.GetDraft() {
issue, err = startIssueWorkflow(ctx, s.store, s.webhookManager, s.licenseService, s.bus, project, user.Name, user.Email, issue)
if err != nil {
@@ -1408,6 +1417,9 @@ func (s *IssueService) UpdateIssueComment(ctx context.Context, req *connect.Requ
if err := s.store.UpdateIssueComment(ctx, update); err != nil {
return nil, issueCommentError(err)
}
+ if s.profile.SQLReviewV2 && update.ThreadState != nil && *update.ThreadState == store.ThreadStateResolved {
+ requestRolloutCheck(ctx, s.store, s.bus, parentProjectID, parentIssueUID)
+ }
issueComment, err = s.store.GetIssueComment(ctx, &store.FindIssueCommentMessage{ProjectID: parentProjectID, ResourceID: &issueCommentID})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get issue comment: %v", err))
diff --git a/backend/api/v1/issue_service_converter.go b/backend/api/v1/issue_service_converter.go
index 8147bbe25e..10b331f3c8 100644
--- a/backend/api/v1/issue_service_converter.go
+++ b/backend/api/v1/issue_service_converter.go
@@ -187,10 +187,11 @@ func convertToIssueComments(issueName string, issueComments []*store.IssueCommen
// enums; TestReviewRuleTypeEnumsMirror holds the rule numbering together.
func convertToIssueCommentReviewMetadata(metadata *storepb.IssueCommentPayload_ReviewMetadata) *v1pb.IssueComment_ReviewMetadata {
return &v1pb.IssueComment_ReviewMetadata{
- RunType: convertToReviewRunType(metadata.RunType.String()),
- RuleType: v1pb.ReviewRuleType(metadata.RuleType),
- Priority: v1pb.IssueComment_ReviewMetadata_Priority(metadata.Priority),
- Targets: metadata.Targets,
+ RunType: convertToReviewRunType(metadata.RunType.String()),
+ RuleType: v1pb.ReviewRuleType(metadata.RuleType),
+ Priority: v1pb.IssueComment_ReviewMetadata_Priority(metadata.Priority),
+ Targets: metadata.Targets,
+ Superseded: metadata.Superseded,
}
}
diff --git a/backend/api/v1/issue_service_review_run.go b/backend/api/v1/issue_service_review_run.go
index 59d617a30b..19f69c150e 100644
--- a/backend/api/v1/issue_service_review_run.go
+++ b/backend/api/v1/issue_service_review_run.go
@@ -2,12 +2,16 @@ package v1
import (
"context"
+ "log/slog"
"connectrpc.com/connect"
"github.com/pkg/errors"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/component/bus"
+ "github.com/bytebase/bytebase/backend/component/config"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/plugin/aireview"
@@ -22,7 +26,8 @@ const (
reviewRunIDAI = "ai"
)
-// GetReviewRun returns the run in a review slot as stored.
+// GetReviewRun returns the run in a review slot as stored, and whether the
+// plan's SQL changed after it started.
func (s *IssueService) GetReviewRun(ctx context.Context, req *connect.Request[v1pb.GetReviewRunRequest]) (*connect.Response[v1pb.ReviewRun], error) {
projectID, issueUID, reviewRunID, err := common.GetProjectIDIssueUIDReviewRunID(req.Msg.Name)
if err != nil {
@@ -40,7 +45,36 @@ func (s *IssueService) GetReviewRun(ctx context.Context, req *connect.Request[v1
if reviewRun == nil {
return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("review run %q not found", req.Msg.Name))
}
- return connect.NewResponse(convertToReviewRun(reviewRun)), nil
+ converted := convertToReviewRun(reviewRun)
+ converted.Outdated, err = reviewRunOutdated(ctx, s.store, reviewRun)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, err)
+ }
+ return connect.NewResponse(converted), nil
+}
+
+// reviewRunOutdated reports whether the run's approval input version is no
+// longer its issue's plan's: the plan's SQL changed after the run started.
+func reviewRunOutdated(ctx context.Context, stores *store.Store, reviewRun *store.ReviewRunMessage) (bool, error) {
+ issue, err := stores.GetIssue(ctx, &store.FindIssueMessage{
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ ProjectIDs: []string{reviewRun.ProjectID},
+ UID: &reviewRun.IssueUID,
+ })
+ if err != nil {
+ return false, errors.Wrapf(err, "failed to get issue")
+ }
+ if issue == nil || issue.PlanUID == nil {
+ return false, nil
+ }
+ plan, err := stores.GetPlan(ctx, &store.FindPlanMessage{ProjectID: reviewRun.ProjectID, UID: issue.PlanUID})
+ if err != nil {
+ return false, errors.Wrapf(err, "failed to get plan")
+ }
+ if plan == nil {
+ return false, nil
+ }
+ return reviewRun.Payload.GetApprovalInputVersion() != plan.Config.GetApprovalInputVersion(), nil
}
// RunReview triggers a review run. The slot is reset unconditionally: a
@@ -55,6 +89,9 @@ func (s *IssueService) RunReview(ctx context.Context, req *connect.Request[v1pb.
if !ok {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("unknown reviewer type %q", reviewRunID))
}
+ if reviewType == store.ReviewRunTypeRule && !s.profile.SQLReviewV2 {
+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("the standard rule review is not available on this server yet"))
+ }
issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{
Workspace: common.GetWorkspaceIDFromContext(ctx),
@@ -67,42 +104,10 @@ func (s *IssueService) RunReview(ctx context.Context, req *connect.Request[v1pb.
if issue == nil {
return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("issue %d not found in project %s", issueUID, projectID))
}
- if issue.Status != storepb.Issue_OPEN {
- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("review runs only on an open issue; issue is %s", issue.Status))
- }
- if issue.PlanUID == nil {
- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("issue %d has no SQL to review", issueUID))
- }
- plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{ProjectID: projectID, UID: issue.PlanUID})
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get plan"))
- }
- if plan == nil {
- return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("plan %d not found in project %s", *issue.PlanUID, projectID))
- }
- if plan.Config.GetHasRollout() {
- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("the plan already has a rollout; its SQL is frozen"))
- }
-
// Applicability: the review type must apply to this issue right now — a
// slot for an inapplicable type must not exist, so it is not created.
- project, err := s.store.GetProjectByResourceID(ctx, projectID)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get project"))
- }
- if project == nil {
- return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("project %s not found", projectID))
- }
- databaseGroup, err := plancheck.GetDatabaseGroupForPlan(ctx, s.store, plan, nil)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get database group for plan"))
- }
- targets, err := plancheck.DeriveReviewTargets(ctx, s.store, project, plan, databaseGroup)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to derive review targets"))
- }
- if len(targets) == 0 {
- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("the plan has no reviewable SQL"))
+ if err := checkReviewable(ctx, s.store, issue); err != nil {
+ return nil, err
}
if reviewType == store.ReviewRunTypeAI {
aiSetting, err := s.store.GetAISettingUncached(ctx, common.GetWorkspaceIDFromContext(ctx))
@@ -127,6 +132,91 @@ func (s *IssueService) RunReview(ctx context.Context, req *connect.Request[v1pb.
return connect.NewResponse(convertToReviewRun(reviewRun)), nil
}
+// checkReviewable refuses a review the issue cannot have now: the issue must
+// be open, and its plan's SQL must be unfrozen by a rollout and reach at least
+// one reviewable target.
+func checkReviewable(ctx context.Context, stores *store.Store, issue *store.IssueMessage) error {
+ if issue.Status != storepb.Issue_OPEN {
+ return connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("review runs only on an open issue; issue is %s", issue.Status))
+ }
+ if issue.PlanUID == nil {
+ return connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("issue %d has no SQL to review", issue.UID))
+ }
+ plan, err := stores.GetPlan(ctx, &store.FindPlanMessage{ProjectID: issue.ProjectID, UID: issue.PlanUID})
+ if err != nil {
+ return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get plan"))
+ }
+ if plan == nil {
+ return connect.NewError(connect.CodeNotFound, errors.Errorf("plan %d not found in project %s", *issue.PlanUID, issue.ProjectID))
+ }
+ if plan.Config.GetHasRollout() {
+ return connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("the plan already has a rollout; its SQL is frozen"))
+ }
+ project, err := stores.GetProjectByResourceID(ctx, issue.ProjectID)
+ if err != nil {
+ return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get project"))
+ }
+ if project == nil {
+ return connect.NewError(connect.CodeNotFound, errors.Errorf("project %s not found", issue.ProjectID))
+ }
+ hasTargets, err := plancheck.HasReviewTargets(ctx, stores, project, plan)
+ if err != nil {
+ return connect.NewError(connect.CodeInternal, err)
+ }
+ if !hasTargets {
+ return connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("the plan has no reviewable SQL"))
+ }
+ return nil
+}
+
+// startRuleReview starts the standard rule review of the issue where SQL
+// Review V2 is on, at the points the plan checks run. It never fails its
+// caller: an issue the review does not apply to is skipped, and a failure is
+// logged.
+func startRuleReview(ctx context.Context, profile *config.Profile, stores *store.Store, b *bus.Bus, issue *store.IssueMessage) {
+ if !profile.SQLReviewV2 || issue == nil || issue.Type != storepb.Issue_DATABASE_CHANGE {
+ return
+ }
+ if err := checkReviewable(ctx, stores, issue); err != nil {
+ if connect.CodeOf(err) != connect.CodeFailedPrecondition {
+ slog.Warn("failed to start the standard rule review",
+ slog.String("project", issue.ProjectID),
+ slog.Int64("issue_id", issue.UID),
+ log.BBError(err))
+ }
+ return
+ }
+ if _, err := stores.CreateReviewRun(ctx, issue.ProjectID, issue.UID, store.ReviewRunTypeRule); err != nil {
+ slog.Error("failed to start the standard rule review",
+ slog.String("project", issue.ProjectID),
+ slog.Int64("issue_id", issue.UID),
+ log.BBError(err))
+ return
+ }
+ b.ReviewRunTickleChan <- 0
+}
+
+// requestRolloutCheck asks the rollout creator to look at the issue's plan
+// again. Under SQL Review V2 open threads hold the automatic rollout, so
+// resolving one can release it.
+func requestRolloutCheck(ctx context.Context, stores *store.Store, b *bus.Bus, projectID string, issueUID int64) {
+ issue, err := stores.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{projectID}, UID: &issueUID})
+ if err != nil {
+ slog.Warn("failed to get the issue to check its rollout",
+ slog.String("project", projectID),
+ slog.Int64("issue_id", issueUID),
+ log.BBError(err))
+ return
+ }
+ if issue == nil || issue.PlanUID == nil {
+ return
+ }
+ select {
+ case b.RolloutCreationChan <- bus.PlanRef{ProjectID: projectID, PlanID: *issue.PlanUID}:
+ case <-ctx.Done():
+ }
+}
+
// reviewRunTypeFromID maps a review run resource ID to the stored reviewer
// type.
func reviewRunTypeFromID(reviewRunID string) (string, bool) {
diff --git a/backend/api/v1/issue_service_review_run_test.go b/backend/api/v1/issue_service_review_run_test.go
index f6ff19d533..877dfe0e19 100644
--- a/backend/api/v1/issue_service_review_run_test.go
+++ b/backend/api/v1/issue_service_review_run_test.go
@@ -4,13 +4,19 @@ import (
"context"
"fmt"
"testing"
+ "time"
"connectrpc.com/connect"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/fieldmaskpb"
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/bus"
+ "github.com/bytebase/bytebase/backend/component/config"
+ "github.com/bytebase/bytebase/backend/component/iam"
+ "github.com/bytebase/bytebase/backend/component/webhook"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/store"
@@ -223,3 +229,283 @@ func TestRunReviewRefusesAIReviewWhileItsSwitchIsOff(t *testing.T) {
require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))
require.ErrorContains(t, err, "AI is not enabled")
}
+
+func TestRunReviewRefusesRuleReviewWithoutSQLReviewV2(t *testing.T) {
+ t.Parallel()
+ ctx := issueServiceTestContext()
+ stores := setupIssueServiceTestStore(ctx, t)
+ _, issue := createIssueServiceApprovalIssue(ctx, t, stores)
+ service := newIssueServiceForTest(t, stores)
+ service.profile = &config.Profile{}
+ runReview := func(reviewRunID string) (*connect.Response[v1pb.ReviewRun], error) {
+ return service.RunReview(ctx, connect.NewRequest(&v1pb.RunReviewRequest{
+ Name: fmt.Sprintf("projects/project-a/issues/%d/reviewRuns/%s", issue.UID, reviewRunID),
+ }))
+ }
+
+ _, err := runReview("rule")
+ require.Equal(t, connect.CodeUnimplemented, connect.CodeOf(err))
+ claimed, err := stores.ClaimAvailableReviewRuns(ctx, "replica")
+ require.NoError(t, err)
+ require.Empty(t, claimed, "a refused review creates no run")
+
+ _, err = stores.UpsertSetting(ctx, &store.SettingMessage{
+ Name: storepb.SettingName_AI,
+ Workspace: "default",
+ Value: &storepb.AISetting{Enabled: true, SqlReviewEnabled: true},
+ })
+ require.NoError(t, err)
+ resp, err := runReview("ai")
+ require.NoError(t, err, "the AI review does not depend on SQL Review V2")
+ require.Equal(t, v1pb.ReviewRun_AVAILABLE, resp.Msg.Status)
+}
+
+func TestStartRuleReview(t *testing.T) {
+ t.Parallel()
+ ctx := issueServiceTestContext()
+ stores := setupIssueServiceTestStore(ctx, t)
+ b, err := bus.New()
+ require.NoError(t, err)
+ claimRuleRuns := func() []*store.ClaimedReviewRun {
+ t.Helper()
+ claimed, err := stores.ClaimAvailableReviewRuns(ctx, "replica")
+ require.NoError(t, err)
+ return claimed
+ }
+
+ issue := createReviewRunIssue(ctx, t, stores, "project-a")
+ startRuleReview(ctx, &config.Profile{}, stores, b, issue)
+ require.Empty(t, claimRuleRuns(), "SQL Review V2 is off")
+
+ startRuleReview(ctx, &config.Profile{SQLReviewV2: true}, stores, b, issue)
+ claimed := claimRuleRuns()
+ require.Len(t, claimed, 1)
+ require.Equal(t, issue.UID, claimed[0].IssueUID)
+ require.Equal(t, store.ReviewRunTypeRule, claimed[0].Type)
+ require.Len(t, b.ReviewRunTickleChan, 1)
+
+ issue.Status = storepb.Issue_DONE
+ startRuleReview(ctx, &config.Profile{SQLReviewV2: true}, stores, b, issue)
+ require.Empty(t, claimRuleRuns(), "a closed issue is skipped")
+}
+
+func TestGetReviewRunReportsAnOutdatedRun(t *testing.T) {
+ t.Parallel()
+ ctx := issueServiceTestContext()
+ stores := setupIssueServiceTestStore(ctx, t)
+ service := newIssueServiceForTest(t, stores)
+ issue := createReviewRunIssue(ctx, t, stores, "project-a")
+ _, err := stores.CreateReviewRun(ctx, issue.ProjectID, issue.UID, store.ReviewRunTypeRule)
+ require.NoError(t, err)
+ getRun := func() *v1pb.ReviewRun {
+ t.Helper()
+ resp, err := service.GetReviewRun(ctx, connect.NewRequest(&v1pb.GetReviewRunRequest{
+ Name: fmt.Sprintf("projects/project-a/issues/%d/reviewRuns/rule", issue.UID),
+ }))
+ require.NoError(t, err)
+ return resp.Msg
+ }
+ require.False(t, getRun().Outdated)
+
+ _, err = stores.GetDB().ExecContext(ctx, `
+ UPDATE plan SET config = jsonb_set(config, '{approvalInputVersion}', '"1"')
+ WHERE project = $1 AND id = $2
+ `, issue.ProjectID, *issue.PlanUID)
+ require.NoError(t, err)
+ require.True(t, getRun().Outdated, "the plan's SQL changed after the run started")
+
+ _, err = stores.CreateReviewRun(ctx, issue.ProjectID, issue.UID, store.ReviewRunTypeRule)
+ require.NoError(t, err)
+ require.False(t, getRun().Outdated)
+}
+
+func TestResolvingAThreadRequestsARolloutCheck(t *testing.T) {
+ t.Parallel()
+ ctx := issueServiceTestContext()
+ stores := setupIssueServiceTestStore(ctx, t)
+ issue := createReviewRunIssue(ctx, t, stores, "project-a")
+ open := store.ThreadStateOpen
+ root, err := stores.CreateIssueComments(ctx, "[email protected]", &store.IssueCommentMessage{
+ ProjectID: "project-a",
+ IssueUID: issue.UID,
+ Payload: &storepb.IssueCommentPayload{Comment: "Is this safe?"},
+ ThreadState: &open,
+ })
+ require.NoError(t, err)
+ parent := fmt.Sprintf("projects/project-a/issues/%d", issue.UID)
+ setThreadState := func(service *IssueService, state v1pb.IssueComment_ThreadState) {
+ t.Helper()
+ _, err := service.UpdateIssueComment(ctx, connect.NewRequest(&v1pb.UpdateIssueCommentRequest{
+ Parent: parent,
+ IssueComment: &v1pb.IssueComment{
+ Name: fmt.Sprintf("%s/issueComments/%s", parent, root.ResourceID),
+ ThreadState: &state,
+ },
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"thread_state"}},
+ }))
+ require.NoError(t, err)
+ }
+
+ withoutV2 := newIssueServiceForTest(t, stores)
+ withoutV2.profile = &config.Profile{}
+ setThreadState(withoutV2, v1pb.IssueComment_RESOLVED)
+ require.Empty(t, withoutV2.bus.RolloutCreationChan)
+
+ service := newIssueServiceForTest(t, stores)
+ setThreadState(service, v1pb.IssueComment_OPEN)
+ require.Empty(t, service.bus.RolloutCreationChan, "reopening holds the rollout; it releases nothing")
+ setThreadState(service, v1pb.IssueComment_RESOLVED)
+ require.Len(t, service.bus.RolloutCreationChan, 1)
+ require.Equal(t, bus.PlanRef{ProjectID: "project-a", PlanID: *issue.PlanUID}, <-service.bus.RolloutCreationChan)
+}
+
+// TestCreateIssueStartsTheRuleReviewBeforeTheWorkflow pins the order that
+// keeps a new issue's rollout held: the workflow's approval check can create
+// the rollout, so the rule review slot must exist by the time it is sent.
+func TestCreateIssueStartsTheRuleReviewBeforeTheWorkflow(t *testing.T) {
+ t.Parallel()
+ ctx := issueServiceTestContext()
+ stores := setupIssueServiceTestStore(ctx, t)
+ service := newIssueServiceForTest(t, stores)
+ plan, err := stores.CreatePlan(ctx, &store.PlanMessage{
+ ProjectID: "project-a",
+ Name: "plan",
+ Config: &storepb.PlanConfig{Specs: []*storepb.PlanConfig_Spec{{
+ Id: "spec-1",
+ Config: &storepb.PlanConfig_Spec_ChangeDatabaseConfig{
+ ChangeDatabaseConfig: &storepb.PlanConfig_ChangeDatabaseConfig{
+ Targets: []string{"instances/prod/databases/app"},
+ },
+ },
+ }}},
+ require.NoError(t, err)
+
+ // Unbuffered and not yet received, so the workflow's send blocks: a slot
+ // that is not in place before the send cannot appear until the listener
+ // takes it.
+ approvalCheck := make(chan bus.IssueRef)
+ service.bus.ApprovalCheckChan = approvalCheck
+ slotBeforeApprovalCheck := make(chan bool, 1)
+ go func() {
+ defer func() { <-approvalCheck }()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ issue, err := stores.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, PlanUID: &plan.UID})
+ if err == nil && issue != nil {
+ run, err := stores.GetReviewRun(ctx, issue.ProjectID, issue.UID, store.ReviewRunTypeRule)
+ if err == nil && run != nil {
+ slotBeforeApprovalCheck <- true
+ return
+ }
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ slotBeforeApprovalCheck <- false
+ }()
+
+ _, err = service.CreateIssue(ctx, connect.NewRequest(&v1pb.CreateIssueRequest{
+ Parent: "projects/project-a",
+ Issue: &v1pb.Issue{
+ Type: v1pb.Issue_DATABASE_CHANGE,
+ Plan: common.FormatPlan("project-a", plan.UID),
+ },
+ }))
+ require.NoError(t, err)
+ require.True(t, <-slotBeforeApprovalCheck, "the rule review slot exists before the approval check is sent")
+}
+
+// TestUpdatePlanStartsTheRuleReviewBeforeTheChecks pins the order that keeps
+// an edited plan's rollout held: the plan checks and the approval check can
+// each lead to the rollout, so the rule review slot must be reset first.
+func TestUpdatePlanStartsTheRuleReviewBeforeTheChecks(t *testing.T) {
+ t.Parallel()
+ ctx := issueServiceTestContext()
+ stores := setupIssueServiceTestStore(ctx, t)
+ projectID := "project-a"
+ _, err := stores.CreateInstance(ctx, &store.InstanceMessage{
+ ResourceID: "prod",
+ Workspace: "default",
+ Metadata: &storepb.Instance{
+ Engine: storepb.Engine_POSTGRES,
+ Activation: true,
+ DataSources: []*storepb.DataSource{{Id: "admin", Type: storepb.DataSourceType_ADMIN}},
+ },
+ })
+ require.NoError(t, err)
+ _, err = stores.UpsertDatabase(ctx, &store.DatabaseMessage{
+ InstanceID: "prod",
+ DatabaseName: "app",
+ ProjectID: projectID,
+ Metadata: &storepb.DatabaseMetadata{},
+ })
+ require.NoError(t, err)
+ sheets, err := stores.CreateSheets(ctx, projectID, &store.SheetMessage{Statement: "ALTER TABLE t ADD COLUMN c INT;"})
+ require.NoError(t, err)
+ issue := createReviewRunIssue(ctx, t, stores, projectID)
+ _, err = stores.CreateReviewRun(ctx, issue.ProjectID, issue.UID, store.ReviewRunTypeRule)
+ require.NoError(t, err)
+ claimed, err := stores.ClaimAvailableReviewRuns(ctx, "replica")
+ require.NoError(t, err)
+ require.Len(t, claimed, 1)
+ updated, err := stores.CompleteReviewRun(ctx, claimed[0], "replica", storepb.ReviewRun_DONE, &storepb.ReviewRunPayload{}, nil)
+ require.NoError(t, err)
+ require.True(t, updated)
+
+ b, err := bus.New()
+ require.NoError(t, err)
+ iamManager, err := iam.NewManager(stores, nil, false)
+ require.NoError(t, err)
+ service := NewPlanService(stores, b, iamManager, webhook.NewManager(stores, nil), nil, &config.Profile{SQLReviewV2: true})
+ // Unbuffered and not yet received, so either signal blocks the update: a
+ // slot not reset before the first signal stays DONE until the listener
+ // takes it.
+ b.PlanCheckTickleChan = make(chan int)
+ b.ApprovalCheckChan = make(chan bus.IssueRef)
+ slotResetBeforeSignal := make(chan bool, 1)
+ signals := make(chan int, 1)
+ updateDone := make(chan struct{})
+ go func() {
+ reset := false
+ for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
+ run, err := stores.GetReviewRun(ctx, issue.ProjectID, issue.UID, store.ReviewRunTypeRule)
+ if err == nil && run != nil && run.Status == storepb.ReviewRun_AVAILABLE {
+ reset = true
+ break
+ }
+ }
+ slotResetBeforeSignal <- reset
+ received := 0
+ for {
+ select {
+ case <-b.PlanCheckTickleChan:
+ received++
+ case <-b.ApprovalCheckChan:
+ received++
+ case <-updateDone:
+ signals <- received
+ return
+ }
+ }
+ }()
+
+ _, err = service.UpdatePlan(ctx, connect.NewRequest(&v1pb.UpdatePlanRequest{
+ Plan: &v1pb.Plan{
+ Name: common.FormatPlan(projectID, *issue.PlanUID),
+ Specs: []*v1pb.Plan_Spec{{
+ Id: "spec-1",
+ Config: &v1pb.Plan_Spec_ChangeDatabaseConfig{
+ ChangeDatabaseConfig: &v1pb.Plan_ChangeDatabaseConfig{
+ Targets: []string{"instances/prod/databases/app"},
+ Sheet: common.FormatSheet(projectID, sheets[0].Sha256),
+ },
+ },
+ }},
+ },
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"specs"}},
+ }))
+ close(updateDone)
+ require.NoError(t, err)
+ require.Positive(t, <-signals, "the update signals the plan checks or the approval check")
+ require.True(t, <-slotResetBeforeSignal, "the rule review slot is reset before the first signal")
+}
diff --git a/backend/api/v1/issue_service_test.go b/backend/api/v1/issue_service_test.go
index 8a8dedc00a..f92400174b 100644
--- a/backend/api/v1/issue_service_test.go
+++ b/backend/api/v1/issue_service_test.go
@@ -12,6 +12,7 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/component/bus"
+ "github.com/bytebase/bytebase/backend/component/config"
"github.com/bytebase/bytebase/backend/component/iam"
"github.com/bytebase/bytebase/backend/component/review"
"github.com/bytebase/bytebase/backend/component/webhook"
@@ -335,7 +336,7 @@ func newIssueServiceForTest(t *testing.T, stores *store.Store) *IssueService {
require.NoError(t, err)
iamManager, err := iam.NewManager(stores, nil, false)
require.NoError(t, err)
- return NewIssueService(stores, webhook.NewManager(stores, nil), b, nil, iamManager)
+ return NewIssueService(stores, webhook.NewManager(stores, nil), b, nil, iamManager, &config.Profile{SQLReviewV2: true})
}
func createIssueServiceApprovalIssue(ctx context.Context, t *testing.T, stores *store.Store) (*store.PlanMessage, *store.IssueMessage) {
diff --git a/backend/api/v1/org_policy_service_review_rule_test.go b/backend/api/v1/org_policy_service_review_rule_test.go
index 409ff187ec..ac589b7bb9 100644
--- a/backend/api/v1/org_policy_service_review_rule_test.go
+++ b/backend/api/v1/org_policy_service_review_rule_test.go
@@ -43,19 +43,21 @@ func TestConvertToIssueCommentReviewResult(t *testing.T) {
Payload: &storepb.IssueCommentPayload{
Comment: "UPDATE without WHERE",
ReviewMetadata: &storepb.IssueCommentPayload_ReviewMetadata{
- RunType: storepb.ReviewRun_RULE,
- RuleType: storepb.ReviewRuleType_REQUIRE_WHERE,
- Priority: storepb.IssueCommentPayload_ReviewMetadata_P1,
- Targets: []string{"instances/i/databases/a", "instances/i/databases/b"},
+ RunType: storepb.ReviewRun_RULE,
+ RuleType: storepb.ReviewRuleType_REQUIRE_WHERE,
+ Priority: storepb.IssueCommentPayload_ReviewMetadata_P1,
+ Targets: []string{"instances/i/databases/a", "instances/i/databases/b"},
+ Superseded: true,
},
},
})
require.Empty(t, got.Creator, "a review result has no creator")
require.Equal(t, &v1pb.IssueComment_ReviewMetadata{
- RunType: v1pb.ReviewRun_RULE,
- RuleType: v1pb.ReviewRuleType_REQUIRE_WHERE,
- Priority: v1pb.IssueComment_ReviewMetadata_P1,
- Targets: []string{"instances/i/databases/a", "instances/i/databases/b"},
+ RunType: v1pb.ReviewRun_RULE,
+ RuleType: v1pb.ReviewRuleType_REQUIRE_WHERE,
+ Priority: v1pb.IssueComment_ReviewMetadata_P1,
+ Targets: []string{"instances/i/databases/a", "instances/i/databases/b"},
+ Superseded: true,
}, got.ReviewMetadata)
person := convertToIssueComment("projects/p/issues/101", &store.IssueCommentMessage{
diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.go
index d04be593bb..79b03fc5d0 100644
--- a/backend/api/v1/plan_service.go
+++ b/backend/api/v1/plan_service.go
@@ -16,6 +16,7 @@ import (
"github.com/bytebase/bytebase/backend/common/permission"
"github.com/bytebase/bytebase/backend/component/bus"
+ "github.com/bytebase/bytebase/backend/component/config"
"github.com/bytebase/bytebase/backend/component/iam"
"github.com/bytebase/bytebase/backend/component/review"
"github.com/bytebase/bytebase/backend/component/webhook"
@@ -34,17 +35,19 @@ type PlanService struct {
iamManager *iam.Manager
webhookManager *webhook.Manager
licenseService *enterprise.LicenseService
+ profile *config.Profile
reviewWorkflow *review.Workflow
}
// NewPlanService returns a plan service instance.
-func NewPlanService(store *store.Store, bus *bus.Bus, iamManager *iam.Manager, webhookManager *webhook.Manager, licenseService *enterprise.LicenseService) *PlanService {
+func NewPlanService(store *store.Store, bus *bus.Bus, iamManager *iam.Manager, webhookManager *webhook.Manager, licenseService *enterprise.LicenseService, profile *config.Profile) *PlanService {
return &PlanService{
store: store,
bus: bus,
iamManager: iamManager,
webhookManager: webhookManager,
licenseService: licenseService,
+ profile: profile,
reviewWorkflow: review.NewWorkflow(store),
}
}
@@ -383,6 +386,13 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *connect.Request[v
}
}
+ // The review starts before the plan checks and the approval check are
+ // signaled, as either can create the rollout: a slot already reset holds it
+ // until the review of the new SQL is done.
+ if planCheckRunsTrigger {
+ startRuleReview(ctx, s.profile, s.store, s.bus, updateResult.Issue)
+ }
+
if updatedIssue := updateResult.Issue; updateResult.ApprovalReset && updatedIssue != nil {
if updatedIssue.Type == storepb.Issue_DATABASE_CHANGE && planCheckRunsTrigger && !planCheckRunCreated {
s.bus.ApprovalCheckChan <- bus.IssueRef{ProjectID: updatedIssue.ProjectID, UID: updatedIssue.UID}
@@ -442,6 +452,27 @@ func (s *PlanService) GetPlanCheckRun(ctx context.Context, request *connect.Requ
return connect.NewResponse(converted), nil
}
+// startRuleReviewOfPlan starts the standard rule review of the plan's issue,
+// if it has one.
+func (s *PlanService) startRuleReviewOfPlan(ctx context.Context, plan *store.PlanMessage) {
+ if !s.profile.SQLReviewV2 {
+ return
+ }
+ issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{
+ Workspace: common.GetWorkspaceIDFromContext(ctx),
+ ProjectIDs: []string{plan.ProjectID},
+ PlanUID: &plan.UID,
+ })
+ if err != nil {
+ slog.Warn("failed to find the plan's issue for the standard rule review",
+ slog.String("project", plan.ProjectID),
+ slog.Int64("plan_id", plan.UID),
+ log.BBError(err))
+ return
+ }
+ startRuleReview(ctx, s.profile, s.store, s.bus, issue)
+}
+
// RunPlanChecks runs plan checks for a plan.
func (s *PlanService) RunPlanChecks(ctx context.Context, request *connect.Request[v1pb.RunPlanChecksRequest]) (*connect.Response[v1pb.RunPlanChecksResponse], error) {
req := request.Msg
@@ -497,6 +528,7 @@ func (s *PlanService) RunPlanChecks(ctx context.Context, request *connect.Reques
}
}
}
+ s.startRuleReviewOfPlan(ctx, plan)
planCheckRun, err := getPlanCheckRunFromPlan(ctx, s.store, project, plan, databaseGroup)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get plan check run for plan"))
diff --git a/backend/bin/server/cmd/profile_dev.go b/backend/bin/server/cmd/profile_dev.go
index cc3cd8cc61..0f2c44398b 100644
--- a/backend/bin/server/cmd/profile_dev.go
+++ b/backend/bin/server/cmd/profile_dev.go
@@ -10,5 +10,6 @@ import (
func activeProfile(dataDir string) *config.Profile {
p := getBaseProfile(dataDir)
p.Mode = common.ReleaseModeDev
+ p.SQLReviewV2 = true
return p
}
diff --git a/backend/component/config/profile.go b/backend/component/config/profile.go
index 335d391742..74ae35f8a3 100644
--- a/backend/component/config/profile.go
+++ b/backend/component/config/profile.go
@@ -12,6 +12,9 @@ import (
type Profile struct {
// Mode can be "prod" or "dev"
Mode common.ReleaseMode
+ // SQLReviewV2 replaces the plan check's SQL review (V1) with the review
+ // runs (V2). Only a dev build turns it on.
+ SQLReviewV2 bool
// ExternalURL is the URL user visits Bytebase.
ExternalURL string
// DatastorePort is the binding port for database instance for storing Bytebase metadata.
diff --git a/backend/generated-go/store/issue_comment.pb.go b/backend/generated-go/store/issue_comment.pb.go
index e65e572def..911c7deb7e 100644
--- a/backend/generated-go/store/issue_comment.pb.go
+++ b/backend/generated-go/store/issue_comment.pb.go
@@ -465,7 +465,8 @@ func (x *IssueCommentPayload_PlanUpdate) GetToSpecs() []*PlanConfig_Spec {
// reviewer posted it, what it was judged against, its priority, and the
// databases it applies to. Results from the same reviewer are superseded
// together: when a run completes, it resolves every OPEN root of its type
-// in the transaction that posts the new results.
+// and marks every earlier root of its type superseded, in the transaction
+// that posts the new results.
type IssueCommentPayload_ReviewMetadata struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The reviewer slot that posted the result; review_run.type stores the
@@ -479,7 +480,11 @@ type IssueCommentPayload_ReviewMetadata struct {
// Every database the result applies to, sorted. Always complete; the
// renderer collapses it when it equals the spec's target set.
// Format: instances/{instance}/databases/{database}
- Targets []string `protobuf:"bytes,4,rep,name=targets,proto3" json:"targets,omitempty"`
+ Targets []string `protobuf:"bytes,4,rep,name=targets,proto3" json:"targets,omitempty"`
+ // A later run of the same reviewer has completed, so the result is not
+ // from the latest review. Set by that run whatever the thread state, and
+ // never cleared.
+ Superseded bool `protobuf:"varint,5,opt,name=superseded,proto3" json:"superseded,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -542,6 +547,13 @@ func (x *IssueCommentPayload_ReviewMetadata) GetTargets() []string {
return nil
}
+func (x *IssueCommentPayload_ReviewMetadata) GetSuperseded() bool {
+ if x != nil {
+ return x.Superseded
+ }
+ return false
+}
+
// StatementAnchor records the anchored statement revision and range.
// The SQL excerpt and current/changed/unavailable state are computed on
// read against the anchored sheet and the current plan, not stored.
@@ -626,7 +638,7 @@ var File_store_issue_comment_proto protoreflect.FileDescriptor
const file_store_issue_comment_proto_rawDesc = "" +
"\n" +
- "\x19store/issue_comment.proto\x12\x0ebytebase.store\x1a\x14store/approval.proto\x1a\x12store/common.proto\x1a\x11store/issue.proto\x1a\x10store/plan.proto\x1a\x17store/review_rule.proto\x1a\x16store/review_run.proto\"\xac\x0e\n" +
+ "\x19store/issue_comment.proto\x12\x0ebytebase.store\x1a\x14store/approval.proto\x1a\x12store/common.proto\x1a\x11store/issue.proto\x1a\x10store/plan.proto\x1a\x17store/review_rule.proto\x1a\x16store/review_run.proto\"\xcc\x0e\n" +
"\x13IssueCommentPayload\x12\x18\n" +
"\acomment\x18\x01 \x01(\tR\acomment\x12J\n" +
"\bapproval\x18\x02 \x01(\v2,.bytebase.store.IssueCommentPayload.ApprovalH\x00R\bapproval\x12T\n" +
@@ -663,12 +675,15 @@ const file_store_issue_comment_proto_rawDesc = "" +
"PlanUpdate\x12>\n" +
"\n" +
"from_specs\x18\x01 \x03(\v2\x1f.bytebase.store.PlanConfig.SpecR\tfromSpecs\x12:\n" +
- "\bto_specs\x18\x02 \x03(\v2\x1f.bytebase.store.PlanConfig.SpecR\atoSpecs\x1a\xb9\x02\n" +
+ "\bto_specs\x18\x02 \x03(\v2\x1f.bytebase.store.PlanConfig.SpecR\atoSpecs\x1a\xd9\x02\n" +
"\x0eReviewMetadata\x129\n" +
"\brun_type\x18\x01 \x01(\x0e2\x1e.bytebase.store.ReviewRun.TypeR\arunType\x12;\n" +
"\trule_type\x18\x02 \x01(\x0e2\x1e.bytebase.store.ReviewRuleTypeR\bruleType\x12W\n" +
"\bpriority\x18\x03 \x01(\x0e2;.bytebase.store.IssueCommentPayload.ReviewMetadata.PriorityR\bpriority\x12\x18\n" +
- "\atargets\x18\x04 \x03(\tR\atargets\"<\n" +
+ "\atargets\x18\x04 \x03(\tR\atargets\x12\x1e\n" +
+ "\n" +
+ "superseded\x18\x05 \x01(\bR\n" +
+ "superseded\"<\n" +
"\bPriority\x12\x18\n" +
"\x14PRIORITY_UNSPECIFIED\x10\x00\x12\x06\n" +
"\x02P0\x10\x01\x12\x06\n" +
diff --git a/backend/generated-go/store/issue_comment_equal.pb.go b/backend/generated-go/store/issue_comment_equal.pb.go
index 5e8df01c41..35ccb438c1 100644
--- a/backend/generated-go/store/issue_comment_equal.pb.go
+++ b/backend/generated-go/store/issue_comment_equal.pb.go
@@ -120,6 +120,9 @@ func (x *IssueCommentPayload_ReviewMetadata) Equal(y *IssueCommentPayload_Review
return false
}
}
+ if x.Superseded != y.Superseded {
+ return false
+ }
return true
}
diff --git a/backend/generated-go/store/review_run.pb.go b/backend/generated-go/store/review_run.pb.go
index daa7ebad24..c4b7df8f26 100644
--- a/backend/generated-go/store/review_run.pb.go
+++ b/backend/generated-go/store/review_run.pb.go
@@ -175,9 +175,12 @@ type ReviewRunPayload struct {
// Fatal execution error for the FAILED status, e.g. "metadata not synced:
// instances/prod/databases/db1, db2, db3 (+497 more)". Written by the
// executor or by the reaper.
- Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"`
+ // The plan's PlanConfig.approval_input_version when the slot was reset: the
+ // version of the plan's SQL this run reviews. Completion keeps it.
+ ApprovalInputVersion int64 `protobuf:"varint,2,opt,name=approval_input_version,json=approvalInputVersion,proto3" json:"approval_input_version,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *ReviewRunPayload) Reset() {
@@ -217,6 +220,13 @@ func (x *ReviewRunPayload) GetError() string {
return ""
}
+func (x *ReviewRunPayload) GetApprovalInputVersion() int64 {
+ if x != nil {
+ return x.ApprovalInputVersion
+ }
+ return 0
+}
+
var File_store_review_run_proto protoreflect.FileDescriptor
const file_store_review_run_proto_rawDesc = "" +
@@ -233,9 +243,10 @@ const file_store_review_run_proto_rawDesc = "" +
"\aRUNNING\x10\x02\x12\b\n" +
"\x04DONE\x10\x03\x12\n" +
"\n" +
- "\x06FAILED\x10\x04\"(\n" +
+ "\x06FAILED\x10\x04\"^\n" +
"\x10ReviewRunPayload\x12\x14\n" +
- "\x05error\x18\x01 \x01(\tR\x05errorB\x91\x01\n" +
+ "\x05error\x18\x01 \x01(\tR\x05error\x124\n" +
+ "\x16approval_input_version\x18\x02 \x01(\x03R\x14approvalInputVersionB\x91\x01\n" +
"\x12com.bytebase.storeB\x0eReviewRunProtoP\x01Z\x12generated-go/store\xa2\x02\x03BSX\xaa\x02\x0eBytebase.Store\xca\x02\x0eBytebase\\Store\xe2\x02\x1aBytebase\\Store\\GPBMetadata\xea\x02\x0fBytebase::Storeb\x06proto3"
var (
diff --git a/backend/generated-go/store/review_run_equal.pb.go b/backend/generated-go/store/review_run_equal.pb.go
index 0745d4674b..d7235c9fcf 100644
--- a/backend/generated-go/store/review_run_equal.pb.go
+++ b/backend/generated-go/store/review_run_equal.pb.go
@@ -23,5 +23,8 @@ func (x *ReviewRunPayload) Equal(y *ReviewRunPayload) bool {
if x.Error != y.Error {
return false
}
+ if x.ApprovalInputVersion != y.ApprovalInputVersion {
+ return false
+ }
return true
}
diff --git a/backend/generated-go/v1/issue_service.pb.go b/backend/generated-go/v1/issue_service.pb.go
index e7b7d26cbf..9c9934520c 100644
--- a/backend/generated-go/v1/issue_service.pb.go
+++ b/backend/generated-go/v1/issue_service.pb.go
@@ -2212,7 +2212,11 @@ type ReviewRun struct {
// Fatal execution error, set if and only if status is FAILED: the review
// failed to execute (a platform problem, never the SQL — SQL problems are
// review results on a DONE run).
- Error string `protobuf:"bytes,6,opt,name=error,proto3" json:"error,omitempty"`
+ Error string `protobuf:"bytes,6,opt,name=error,proto3" json:"error,omitempty"`
+ // Whether the plan's SQL changed after this run started, so the run
+ // reviews an earlier version of it. The server starts a new run before it
+ // creates the rollout automatically.
+ Outdated bool `protobuf:"varint,7,opt,name=outdated,proto3" json:"outdated,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -2289,6 +2293,13 @@ func (x *ReviewRun) GetError() string {
return ""
}
+func (x *ReviewRun) GetOutdated() bool {
+ if x != nil {
+ return x.Outdated
+ }
+ return false
+}
+
type GetReviewRunRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The name of the review run to retrieve.
@@ -2445,7 +2456,10 @@ type IssueComment_ReviewMetadata struct {
Priority IssueComment_ReviewMetadata_Priority `protobuf:"varint,3,opt,name=priority,proto3,enum=bytebase.v1.IssueComment_ReviewMetadata_Priority" json:"priority,omitempty"`
// Every database the result applies to, sorted.
// Format: instances/{instance}/databases/{database}
- Targets []string `protobuf:"bytes,4,rep,name=targets,proto3" json:"targets,omitempty"`
+ Targets []string `protobuf:"bytes,4,rep,name=targets,proto3" json:"targets,omitempty"`
+ // A later run of the same reviewer has completed, so the result is not
+ // from the latest review, whatever its thread state.
+ Superseded bool `protobuf:"varint,5,opt,name=superseded,proto3" json:"superseded,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -2508,6 +2522,13 @@ func (x *IssueComment_ReviewMetadata) GetTargets() []string {
return nil
}
+func (x *IssueComment_ReviewMetadata) GetSuperseded() bool {
+ if x != nil {
+ return x.Superseded
+ }
+ return false
+}
+
// Approval event information.
type IssueComment_Approval struct {
state protoimpl.MessageState `protogen:"open.v1"`
@@ -2882,7 +2903,7 @@ const file_v1_issue_service_proto_rawDesc = "" +
"\rissue_comment\x18\x02 \x01(\v2\x19.bytebase.v1.IssueCommentR\fissueComment\x12@\n" +
"\vupdate_mask\x18\x03 \x01(\v2\x1a.google.protobuf.FieldMaskB\x03\xe0A\x02R\n" +
"updateMask\x12#\n" +
- "\rallow_missing\x18\x04 \x01(\bR\fallowMissing\"\xd6\x0f\n" +
+ "\rallow_missing\x18\x04 \x01(\bR\fallowMissing\"\xf6\x0f\n" +
"\fIssueComment\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x12#\n" +
"\acomment\x18\x02 \x01(\tB\t\xbaH\x06r\x04\x18\x80\x80\x04R\acomment\x12\x18\n" +
@@ -2900,12 +2921,15 @@ const file_v1_issue_service_proto_rawDesc = "" +
"\fissue_update\x18\b \x01(\v2%.bytebase.v1.IssueComment.IssueUpdateH\x00R\vissueUpdate\x12G\n" +
"\vplan_update\x18\f \x01(\v2$.bytebase.v1.IssueComment.PlanUpdateH\x00R\n" +
"planUpdate\x12Y\n" +
- "\x11review_submission\x18\r \x01(\v2*.bytebase.v1.IssueComment.ReviewSubmissionH\x00R\x10reviewSubmission\x1a\xa9\x02\n" +
+ "\x11review_submission\x18\r \x01(\v2*.bytebase.v1.IssueComment.ReviewSubmissionH\x00R\x10reviewSubmission\x1a\xc9\x02\n" +
"\x0eReviewMetadata\x126\n" +
"\brun_type\x18\x01 \x01(\x0e2\x1b.bytebase.v1.ReviewRun.TypeR\arunType\x128\n" +
"\trule_type\x18\x02 \x01(\x0e2\x1b.bytebase.v1.ReviewRuleTypeR\bruleType\x12M\n" +
"\bpriority\x18\x03 \x01(\x0e21.bytebase.v1.IssueComment.ReviewMetadata.PriorityR\bpriority\x12\x18\n" +
- "\atargets\x18\x04 \x03(\tR\atargets\"<\n" +
+ "\atargets\x18\x04 \x03(\tR\atargets\x12\x1e\n" +
+ "\n" +
+ "superseded\x18\x05 \x01(\bR\n" +
+ "superseded\"<\n" +
"\bPriority\x12\x18\n" +
"\x14PRIORITY_UNSPECIFIED\x10\x00\x12\x06\n" +
"\x02P0\x10\x01\x12\x06\n" +
@@ -2954,7 +2978,7 @@ const file_v1_issue_service_proto_rawDesc = "" +
"\x04spec\x18\x01 \x01(\tR\x04spec\x12!\n" +
"\fsheet_sha256\x18\x02 \x01(\tR\vsheetSha256\x12<\n" +
"\x0estart_position\x18\x03 \x01(\v2\x15.bytebase.v1.PositionR\rstartPosition\x128\n" +
- "\fend_position\x18\x04 \x01(\v2\x15.bytebase.v1.PositionR\vendPosition\"\x85\x04\n" +
+ "\fend_position\x18\x04 \x01(\v2\x15.bytebase.v1.PositionR\vendPosition\"\xa6\x04\n" +
"\tReviewRun\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x124\n" +
"\x04type\x18\x02 \x01(\x0e2\x1b.bytebase.v1.ReviewRun.TypeB\x03\xe0A\x03R\x04type\x12:\n" +
@@ -2962,7 +2986,8 @@ const file_v1_issue_service_proto_rawDesc = "" +
"\vcreate_time\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampB\x03\xe0A\x03R\n" +
"createTime\x12:\n" +
"\bend_time\x18\x05 \x01(\v2\x1a.google.protobuf.TimestampB\x03\xe0A\x03R\aendTime\x12\x19\n" +
- "\x05error\x18\x06 \x01(\tB\x03\xe0A\x03R\x05error\".\n" +
+ "\x05error\x18\x06 \x01(\tB\x03\xe0A\x03R\x05error\x12\x1f\n" +
+ "\boutdated\x18\a \x01(\bB\x03\xe0A\x03R\boutdated\".\n" +
"\x04Type\x12\x14\n" +
"\x10TYPE_UNSPECIFIED\x10\x00\x12\b\n" +
"\x04RULE\x10\x01\x12\x06\n" +
diff --git a/backend/generated-go/v1/issue_service_equal.pb.go b/backend/generated-go/v1/issue_service_equal.pb.go
index 1dd641789f..540bc9cba1 100644
--- a/backend/generated-go/v1/issue_service_equal.pb.go
+++ b/backend/generated-go/v1/issue_service_equal.pb.go
@@ -517,6 +517,9 @@ func (x *IssueComment_ReviewMetadata) Equal(y *IssueComment_ReviewMetadata) bool
return false
}
}
+ if x.Superseded != y.Superseded {
+ return false
+ }
return true
}
@@ -712,6 +715,9 @@ func (x *ReviewRun) Equal(y *ReviewRun) bool {
if x.Error != y.Error {
return false
}
+ if x.Outdated != y.Outdated {
+ return false
+ }
return true
}
diff --git a/backend/plugin/db/util/ssh_test.go b/backend/plugin/db/util/ssh_test.go
index 8484422bda..9ed43100f2 100644
--- a/backend/plugin/db/util/ssh_test.go
+++ b/backend/plugin/db/util/ssh_test.go
@@ -1,3 +1,4 @@
+//nolint:revive
package util
import (
diff --git a/backend/runner/plancheck/derive.go b/backend/runner/plancheck/derive.go
index 85147cb6ba..398002000c 100644
--- a/backend/runner/plancheck/derive.go
+++ b/backend/runner/plancheck/derive.go
@@ -27,6 +27,20 @@ func DeriveReviewTargets(ctx context.Context, s *store.Store, project *store.Pro
return deriveTargets(ctx, s, project, plan, databaseGroup, false)
}
+// HasReviewTargets reports whether the rule review has SQL to read in the
+// plan: whether DeriveReviewTargets finds any target.
+func HasReviewTargets(ctx context.Context, s *store.Store, project *store.ProjectMessage, plan *store.PlanMessage) (bool, error) {
+ databaseGroup, err := GetDatabaseGroupForPlan(ctx, s, plan, nil)
+ if err != nil {
+ return false, errors.Wrap(err, "failed to get database group for plan")
+ }
+ targets, err := DeriveReviewTargets(ctx, s, project, plan, databaseGroup)
+ if err != nil {
+ return false, errors.Wrap(err, "failed to derive review targets")
+ }
+ return len(targets) > 0, nil
+}
+
func deriveTargets(ctx context.Context, s *store.Store, project *store.ProjectMessage, plan *store.PlanMessage, databaseGroup *v1pb.DatabaseGroup, applySampling bool) ([]*CheckTarget, error) {
var targets []*CheckTarget
diff --git a/backend/runner/plancheck/executor_combined.go b/backend/runner/plancheck/executor_combined.go
index 4ff2dbf336..f196cafdfc 100644
--- a/backend/runner/plancheck/executor_combined.go
+++ b/backend/runner/plancheck/executor_combined.go
@@ -15,6 +15,9 @@ type CombinedExecutor struct {
store *store.Store
sheetManager *sheet.Manager
dbFactory *dbfactory.DBFactory
+ // ruleReviewCovers reports whether SQL Review V2's standard rule review
+ // covers an engine; nil where SQL Review V2 is off.
+ ruleReviewCovers func(storepb.Engine) bool
}
// NewCombinedExecutor creates a combined executor.
@@ -22,11 +25,13 @@ func NewCombinedExecutor(
store *store.Store,
sheetManager *sheet.Manager,
dbFactory *dbfactory.DBFactory,
+ ruleReviewCovers func(storepb.Engine) bool,
) *CombinedExecutor {
return &CombinedExecutor{
- store: store,
- sheetManager: sheetManager,
- dbFactory: dbFactory,
+ store: store,
+ sheetManager: sheetManager,
+ dbFactory: dbFactory,
+ ruleReviewCovers: ruleReviewCovers,
}
}
@@ -35,6 +40,9 @@ func (e *CombinedExecutor) RunForTarget(ctx context.Context, target *CheckTarget
var allResults []*storepb.PlanCheckRunResult_Result
for _, checkType := range target.Types {
+ if e.supersededBySQLReviewV2(ctx, target, checkType) {
+ continue
+ }
results, err := e.runCheck(ctx, target, checkType)
if err != nil {
// Add error result for this target/type, continue to next
@@ -61,6 +69,23 @@ func (e *CombinedExecutor) RunForTarget(ctx context.Context, target *CheckTarget
return allResults, nil
}
+// supersededBySQLReviewV2 reports whether the standard rule review replaces
+// the check where SQL Review V2 is on: only the SQL review advice, and only on
+// an engine the rule review covers; V1 keeps advising the others. The gh-ost
+// check stays, since it dry-runs the migration against the instance, which
+// the ONLINE_MIGRATION rule, reading the SQL alone, cannot.
+func (e *CombinedExecutor) supersededBySQLReviewV2(ctx context.Context, target *CheckTarget, checkType storepb.PlanCheckType) bool {
+ if e.ruleReviewCovers == nil || checkType != storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE {
+ return false
+ }
+ instance, _, err := ResolveDatabaseTarget(ctx, e.store, target.Target)
+ if err != nil {
+ // The advice runs, and reports the target it cannot resolve.
+ return false
+ }
+ return e.ruleReviewCovers(instance.Metadata.GetEngine())
+}
+
func (e *CombinedExecutor) runCheck(ctx context.Context, target *CheckTarget, checkType storepb.PlanCheckType) ([]*storepb.PlanCheckRunResult_Result, error) {
switch checkType {
case storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE:
diff --git a/backend/runner/plancheck/executor_combined_test.go b/backend/runner/plancheck/executor_combined_test.go
new file mode 100644
index 0000000000..894606cb6f
--- /dev/null
+++ b/backend/runner/plancheck/executor_combined_test.go
@@ -0,0 +1,57 @@
+package plancheck
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+func TestCombinedExecutorLeavesSQLReviewToV2(t *testing.T) {
+ ctx := context.Background()
+ s := setupPlancheckStore(ctx, t)
+ for instanceID, engine := range map[string]storepb.Engine{
+ "pg": storepb.Engine_POSTGRES,
+ "dynamo": storepb.Engine_DYNAMODB,
+ } {
+ _, err := s.CreateInstance(ctx, &store.InstanceMessage{
+ ResourceID: instanceID,
+ Workspace: "default",
+ Metadata: &storepb.Instance{
+ Engine: engine,
+ DataSources: []*storepb.DataSource{{Id: "admin", Type: storepb.DataSourceType_ADMIN}},
+ },
+ })
+ require.NoError(t, err)
+ _, err = s.UpsertDatabase(ctx, &store.DatabaseMessage{
+ ProjectID: "project-a",
+ InstanceID: instanceID,
+ DatabaseName: "app",
+ Metadata: &storepb.DatabaseMetadata{Labels: map[string]string{}},
+ })
+ require.NoError(t, err)
+ }
+ coversPostgres := func(engine storepb.Engine) bool { return engine == storepb.Engine_POSTGRES }
+ withV2 := NewCombinedExecutor(s, nil, nil, coversPostgres)
+ withoutV2 := NewCombinedExecutor(s, nil, nil, nil)
+ target := func(instanceID string) *CheckTarget {
+ return &CheckTarget{Target: "instances/" + instanceID + "/databases/app"}
+ }
+ advise := storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE
+
+ require.True(t, withV2.supersededBySQLReviewV2(ctx, target("pg"), advise))
+ require.False(t, withV2.supersededBySQLReviewV2(ctx, target("dynamo"), advise), "V1 keeps advising an engine the rule review does not cover")
+ require.False(t, withV2.supersededBySQLReviewV2(ctx, target("pg"), storepb.PlanCheckType_PLAN_CHECK_TYPE_GHOST_SYNC), "no rule dry-runs gh-ost against the instance")
+ require.False(t, withV2.supersededBySQLReviewV2(ctx, target("pg"), storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT))
+ require.False(t, withoutV2.supersededBySQLReviewV2(ctx, target("pg"), advise))
+
+ // Without a sheet manager, running the advice would panic.
+ pg := target("pg")
+ pg.Types = []storepb.PlanCheckType{advise}
+ results, err := withV2.RunForTarget(ctx, pg)
+ require.NoError(t, err)
+ require.Empty(t, results)
+}
diff --git a/backend/runner/reviewrun/review_funcs.go b/backend/runner/reviewrun/review_funcs.go
index b138b98781..8ad5956842 100644
--- a/backend/runner/reviewrun/review_funcs.go
+++ b/backend/runner/reviewrun/review_funcs.go
@@ -14,9 +14,9 @@ import (
)
// reviewFuncs maps an engine to its omni Review entry point. An engine absent
-// here has no standard rule review, and a run touching it fails. The map
-// fills in as omni ships engine review packages: each one is a line here and
-// nothing else.
+// here has no standard rule review: a run skips its targets, and the plan
+// checks keep V1's statement advice for it. The map fills in as omni ships
+// engine review packages: each one is a line here and nothing else.
var reviewFuncs = map[storepb.Engine]review.ReviewFunc{
storepb.Engine_POSTGRES: pgreview.Review,
storepb.Engine_MYSQL: mysqlreview.Review,
@@ -27,3 +27,9 @@ var reviewFuncs = map[storepb.Engine]review.ReviewFunc{
storepb.Engine_ORACLE: oraclereview.Review,
storepb.Engine_SNOWFLAKE: snowflakereview.Review,
}
+
+// ReviewsEngine reports whether the standard rule review covers the engine.
+func ReviewsEngine(engine storepb.Engine) bool {
+ _, ok := reviewFuncs[engine]
+ return ok
+}
diff --git a/backend/runner/reviewrun/rule_executor.go b/backend/runner/reviewrun/rule_executor.go
index 764545d280..642d26cdb5 100644
--- a/backend/runner/reviewrun/rule_executor.go
+++ b/backend/runner/reviewrun/rule_executor.go
@@ -71,6 +71,9 @@ func (e *RuleExecutor) RunOnce(ctx context.Context, projectID string, issueUID i
return nil, err
}
target, err := e.resolveReviewTarget(ctx, project, checkTarget)
+ if errors.Is(err, errNoRuleReviewer) {
+ continue
+ }
if err != nil {
unitErrs = append(unitErrs, errors.Wrapf(err, "%s", checkTarget.Target))
continue
@@ -137,15 +140,22 @@ func (u *reviewUnit) failures(err error) []error {
return errs
}
+// errNoRuleReviewer marks a target whose engine has no standard rule review.
+var errNoRuleReviewer = errors.New("the engine has no standard rule reviewer")
+
// resolveReviewTarget gathers the inputs the engine cannot derive from the
// SQL: the synced schema, and the instance facts the review contract lists.
-// A database whose schema is not synced cannot be reviewed.
+// A database whose schema is not synced cannot be reviewed. A target on an
+// engine with no reviewer returns errNoRuleReviewer before its schema is read.
func (e *RuleExecutor) resolveReviewTarget(ctx context.Context, project *store.ProjectMessage, checkTarget *plancheck.CheckTarget) (*reviewTarget, error) {
instance, database, err := plancheck.ResolveDatabaseTarget(ctx, e.store, checkTarget.Target)
if err != nil {
return nil, err
}
engine := instance.Metadata.GetEngine()
+ if _, ok := e.reviewFuncs[engine]; !ok {
+ return nil, errNoRuleReviewer
+ }
dbSchema, err := e.store.GetDBSchema(ctx, &store.FindDBSchemaMessage{
Workspace: instance.Workspace,
InstanceID: database.InstanceID,
diff --git a/backend/runner/reviewrun/rule_executor_test.go b/backend/runner/reviewrun/rule_executor_test.go
index 36c928b4cf..80a8004cf2 100644
--- a/backend/runner/reviewrun/rule_executor_test.go
+++ b/backend/runner/reviewrun/rule_executor_test.go
@@ -79,3 +79,83 @@ func TestRuleExecutorSkipsAnEmptyPolicy(t *testing.T) {
_, err = executor.RunOnce(ctx, "p", issue.UID)
require.Error(t, err)
}
+
+// TestRuleExecutorSkipsAnEngineWithoutAReviewer pins that the rule review
+// leaves an engine it has no reviewer for to V1's statement advice: the run
+// skips its target and completes with no findings.
+func TestRuleExecutorSkipsAnEngineWithoutAReviewer(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ db, stores, _ := testcontainer.NewMetadataDB(t)
+ _, err := db.ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES ('ws');
+ INSERT INTO principal (name, email, password_hash) VALUES ('creator', '[email protected]', 'unused');
+ INSERT INTO project (resource_id, workspace, name) VALUES ('p', 'ws', 'P');
+ `)
+ require.NoError(t, err)
+ payload, err := protojson.Marshal(&storepb.ReviewRulePolicy{Rules: []storepb.ReviewRuleType{storepb.ReviewRuleType_SYNTAX}})
+ require.NoError(t, err)
+ _, err = stores.CreatePolicy(ctx, &store.PolicyMessage{
+ Workspace: "ws",
+ ResourceType: storepb.Policy_PROJECT,
+ Resource: common.FormatProject("p"),
+ Type: storepb.Policy_REVIEW_RULE,
+ Payload: string(payload),
+ Enforce: true,
+ })
+ require.NoError(t, err)
+ sheets, err := stores.CreateSheets(ctx, "p", &store.SheetMessage{Statement: "DELETE FROM t;"})
+ require.NoError(t, err)
+
+ runOn := func(instanceID string, engine storepb.Engine) error {
+ t.Helper()
+ require.False(t, ReviewsEngine(engine))
+ _, err := stores.CreateInstance(ctx, &store.InstanceMessage{
+ ResourceID: instanceID,
+ Workspace: "ws",
+ Metadata: &storepb.Instance{
+ Engine: engine,
+ DataSources: []*storepb.DataSource{{Id: "admin", Type: storepb.DataSourceType_ADMIN}},
+ },
+ })
+ require.NoError(t, err)
+ _, err = stores.UpsertDatabase(ctx, &store.DatabaseMessage{
+ ProjectID: "p",
+ InstanceID: instanceID,
+ DatabaseName: "app",
+ Metadata: &storepb.DatabaseMetadata{},
+ })
+ require.NoError(t, err)
+ plan, err := stores.CreatePlan(ctx, &store.PlanMessage{
+ ProjectID: "p",
+ Name: "plan",
+ Config: &storepb.PlanConfig{
+ Specs: []*storepb.PlanConfig_Spec{{
+ Id: "spec-1",
+ Config: &storepb.PlanConfig_Spec_ChangeDatabaseConfig{
+ ChangeDatabaseConfig: &storepb.PlanConfig_ChangeDatabaseConfig{
+ Targets: []string{"instances/" + instanceID + "/databases/app"},
+ SheetSha256: sheets[0].Sha256,
+ },
+ },
+ }},
+ },
+ require.NoError(t, err)
+ issue, err := stores.CreateIssue(ctx, &store.IssueMessage{
+ ProjectID: "p",
+ CreatorEmail: "[email protected]",
+ Title: "issue",
+ Type: storepb.Issue_DATABASE_CHANGE,
+ Payload: &storepb.Issue{},
+ PlanUID: &plan.UID,
+ })
+ require.NoError(t, err)
+ comments, err := NewRuleExecutor(stores).RunOnce(ctx, "p", issue.UID)
+ require.Empty(t, comments)
+ return err
+ }
+
+ require.NoError(t, runOn("dynamo", storepb.Engine_DYNAMODB))
+ require.NoError(t, runOn("clickhouse", storepb.Engine_CLICKHOUSE))
+}
diff --git a/backend/runner/reviewrun/scheduler.go b/backend/runner/reviewrun/scheduler.go
index aa1d4d8cd9..aaa9e28643 100644
--- a/backend/runner/reviewrun/scheduler.go
+++ b/backend/runner/reviewrun/scheduler.go
@@ -196,6 +196,31 @@ func (s *Scheduler) completeReviewRun(ctx context.Context, claimed *store.Claime
slog.Int64("issue_id", claimed.IssueUID),
slog.String("type", claimed.Type),
slog.Int64("attempt", claimed.Attempt))
+ return
+ }
+ if s.profile.SQLReviewV2 {
+ s.requestRolloutCheck(ctx, claimed)
+ }
+}
+
+// requestRolloutCheck asks the rollout creator to look at the issue's plan
+// again: under SQL Review V2 the review holds the automatic rollout until it
+// completes.
+func (s *Scheduler) requestRolloutCheck(ctx context.Context, claimed *store.ClaimedReviewRun) {
+ issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{claimed.ProjectID}, UID: &claimed.IssueUID})
+ if err != nil {
+ slog.Warn("failed to get the issue to check its rollout",
+ slog.String("project", claimed.ProjectID),
+ slog.Int64("issue_id", claimed.IssueUID),
+ log.BBError(err))
+ return
+ }
+ if issue == nil || issue.PlanUID == nil {
+ return
+ }
+ select {
+ case s.bus.RolloutCreationChan <- bus.PlanRef{ProjectID: claimed.ProjectID, PlanID: *issue.PlanUID}:
+ case <-ctx.Done():
}
}
diff --git a/backend/runner/taskrun/rollout_creator.go b/backend/runner/taskrun/rollout_creator.go
index 808af50c88..8ee1600797 100644
--- a/backend/runner/taskrun/rollout_creator.go
+++ b/backend/runner/taskrun/rollout_creator.go
@@ -5,11 +5,14 @@ import (
"log/slog"
"sync"
+ "github.com/pkg/errors"
+
apiv1 "github.com/bytebase/bytebase/backend/api/v1"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/component/bus"
"github.com/bytebase/bytebase/backend/component/webhook"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/runner/plancheck"
"github.com/bytebase/bytebase/backend/store"
"github.com/bytebase/bytebase/backend/utils"
)
@@ -20,14 +23,16 @@ type RolloutCreator struct {
store *store.Store
bus *bus.Bus
webhookManager *webhook.Manager
+ sqlReviewV2 bool
}
// NewRolloutCreator creates a new rollout creator.
-func NewRolloutCreator(store *store.Store, bus *bus.Bus, webhookManager *webhook.Manager) *RolloutCreator {
+func NewRolloutCreator(store *store.Store, bus *bus.Bus, webhookManager *webhook.Manager, sqlReviewV2 bool) *RolloutCreator {
return &RolloutCreator{
store: store,
bus: bus,
webhookManager: webhookManager,
+ sqlReviewV2: sqlReviewV2,
}
}
@@ -180,6 +185,23 @@ func (rc *RolloutCreator) tryCreateRollout(ctx context.Context, ref bus.PlanRef)
}
}
+ if rc.sqlReviewV2 {
+ blocked, err := rc.reviewBlocksRollout(ctx, project, plan, issue)
+ if err != nil {
+ slog.Error("failed to check the review for rollout creation",
+ slog.String("project", ref.ProjectID),
+ slog.Int("plan_id", int(planID)),
+ log.BBError(err))
+ return
+ }
+ if blocked {
+ slog.Debug("review not finished or threads open, skipping rollout creation",
+ slog.String("project", ref.ProjectID),
+ slog.Int("plan_id", int(planID)))
+ return
+ }
+ }
+
// All conditions met - create the rollout
slog.Info("auto-creating rollout", slog.String("project", ref.ProjectID), slog.Int("plan_id", int(planID)))
@@ -211,6 +233,54 @@ func (rc *RolloutCreator) tryCreateRollout(ctx context.Context, ref bus.PlanRef)
slog.Info("successfully auto-created rollout", slog.String("project", ref.ProjectID), slog.Int("plan_id", int(planID)))
}
+// reviewBlocksRollout reports whether the issue's review holds its rollout
+// under SQL Review V2: the rule review of the plan's current SQL has not
+// finished, or a thread on the issue is open. An open thread blocks whatever
+// its priority, and whoever started it.
+//
+// A run for an earlier approval input version holds too, and so does a
+// missing run on a plan with SQL to review: the slot write that should have
+// started the review failed, or never happened. The review starts here then,
+// as the approval evaluator does for a missing or stale plan check run, and its
+// completion asks for this check again. A stale run restarts even when the
+// plan has nothing left to review: it then completes with no findings, which
+// supersedes those of the earlier SQL.
+func (rc *RolloutCreator) reviewBlocksRollout(ctx context.Context, project *store.ProjectMessage, plan *store.PlanMessage, issue *store.IssueMessage) (bool, error) {
+ run, err := rc.store.GetReviewRun(ctx, issue.ProjectID, issue.UID, store.ReviewRunTypeRule)
+ if err != nil {
+ return false, errors.Wrap(err, "failed to get the rule review run")
+ }
+ start := run != nil && run.Payload.GetApprovalInputVersion() != plan.Config.GetApprovalInputVersion()
+ if run == nil {
+ start, err = plancheck.HasReviewTargets(ctx, rc.store, project, plan)
+ if err != nil {
+ return false, err
+ }
+ }
+ if start {
+ if _, err := rc.store.CreateReviewRun(ctx, issue.ProjectID, issue.UID, store.ReviewRunTypeRule); err != nil {
+ return false, errors.Wrap(err, "failed to start the rule review")
+ }
+ bus.Tickle(rc.bus.ReviewRunTickleChan)
+ return true, nil
+ }
+ if run != nil && run.Status != storepb.ReviewRun_DONE {
+ return true, nil
+ }
+ open := store.ThreadStateOpen
+ limit := 1
+ threads, err := rc.store.ListIssueComment(ctx, &store.FindIssueCommentMessage{
+ ProjectID: issue.ProjectID,
+ IssueUID: &issue.UID,
+ ThreadState: &open,
+ Limit: &limit,
+ })
+ if err != nil {
+ return false, errors.Wrap(err, "failed to list open threads")
+ }
+ return len(threads) > 0, nil
+}
+
func planCheckRunBlocksRollout(plan *store.PlanMessage, planCheckRun *store.PlanCheckRunMessage) bool {
if planCheckRun == nil {
return false
diff --git a/backend/runner/taskrun/rollout_creator_test.go b/backend/runner/taskrun/rollout_creator_test.go
index fdbd99d56f..8bfc7f5d9e 100644
--- a/backend/runner/taskrun/rollout_creator_test.go
+++ b/backend/runner/taskrun/rollout_creator_test.go
@@ -92,7 +92,7 @@ func TestTryCreateRolloutSkipsDraft(t *testing.T) {
b, err := bus.New()
require.NoError(t, err)
- NewRolloutCreator(s, b, nil).tryCreateRollout(ctx, bus.PlanRef{
+ NewRolloutCreator(s, b, nil, false).tryCreateRollout(ctx, bus.PlanRef{
ProjectID: plan.ProjectID,
PlanID: plan.UID,
})
@@ -192,7 +192,7 @@ func TestTryCreateRolloutSkipsArchivedProject(t *testing.T) {
b, err := bus.New()
require.NoError(t, err)
- NewRolloutCreator(s, b, nil).tryCreateRollout(ctx, bus.PlanRef{
+ NewRolloutCreator(s, b, nil, false).tryCreateRollout(ctx, bus.PlanRef{
ProjectID: plan.ProjectID,
PlanID: plan.UID,
})
@@ -269,7 +269,7 @@ func TestTryCreateRolloutResolvesProjectInstanceOutsideRequestContext(t *testing
b, err := bus.New()
require.NoError(t, err)
- NewRolloutCreator(s, b, nil).tryCreateRollout(ctx, bus.PlanRef{ProjectID: projectID, PlanID: plan.UID})
+ NewRolloutCreator(s, b, nil, false).tryCreateRollout(ctx, bus.PlanRef{ProjectID: projectID, PlanID: plan.UID})
gotPlan, err := s.GetPlan(ctx, &store.FindPlanMessage{ProjectID: projectID, UID: &plan.UID})
require.NoError(t, err)
@@ -359,7 +359,7 @@ func TestTryCreateRolloutRejectsArchivedProjectInstanceWithWarmDatabaseCache(t *
b, err := bus.New()
require.NoError(t, err)
- NewRolloutCreator(s, b, nil).tryCreateRollout(ctx, bus.PlanRef{ProjectID: projectID, PlanID: plan.UID})
+ NewRolloutCreator(s, b, nil, false).tryCreateRollout(ctx, bus.PlanRef{ProjectID: projectID, PlanID: plan.UID})
gotPlan, err := s.GetPlan(ctx, &store.FindPlanMessage{ProjectID: projectID, UID: &plan.UID})
require.NoError(t, err)
@@ -370,6 +370,316 @@ func TestTryCreateRolloutRejectsArchivedProjectInstanceWithWarmDatabaseCache(t *
require.Empty(t, b.TaskRunPendingTickleChan)
}
+func TestTryCreateRolloutWaitsForTheReview(t *testing.T) {
+ ctx := context.Background()
+ s, plan, issue := newAutoRolloutIssue(ctx, t)
+ b, err := bus.New()
+ require.NoError(t, err)
+ creator := NewRolloutCreator(s, b, nil, true)
+ tryCreateRollout := func() bool {
+ t.Helper()
+ creator.tryCreateRollout(ctx, bus.PlanRef{ProjectID: plan.ProjectID, PlanID: plan.UID})
+ got, err := s.GetPlan(ctx, &store.FindPlanMessage{ProjectID: plan.ProjectID, UID: &plan.UID})
+ require.NoError(t, err)
+ return got.Config.GetHasRollout()
+ }
+
+ // An open thread on the colliding issue of another project must not hold
+ // this one.
+ _, err = s.GetDB().ExecContext(ctx, "INSERT INTO project (resource_id, workspace, name) VALUES ('project-b', $1, 'Project B')", autoRolloutWorkspaceID)
+ require.NoError(t, err)
+ planB, err := s.CreatePlan(ctx, &store.PlanMessage{ProjectID: "project-b", Name: "colliding plan", Config: &storepb.PlanConfig{}}, "[email protected]")
+ require.NoError(t, err)
+ issueB, err := s.CreateIssue(ctx, &store.IssueMessage{
+ ProjectID: "project-b",
+ CreatorEmail: "[email protected]",
+ Title: "colliding issue",
+ Type: storepb.Issue_DATABASE_CHANGE,
+ Payload: &storepb.Issue{},
+ PlanUID: &planB.UID,
+ })
+ require.NoError(t, err)
+ require.Equal(t, issue.UID, issueB.UID, "issue ids should collide")
+ open := store.ThreadStateOpen
+ _, err = s.CreateIssueComments(ctx, "[email protected]", &store.IssueCommentMessage{
+ ProjectID: "project-b",
+ IssueUID: issueB.UID,
+ Payload: &storepb.IssueCommentPayload{Comment: "Is this safe?"},
+ ThreadState: &open,
+ })
+ require.NoError(t, err)
+
+ _, err = s.CreateReviewRun(ctx, issue.ProjectID, issue.UID, store.ReviewRunTypeRule)
+ require.NoError(t, err)
+ require.False(t, tryCreateRollout(), "the rule review has not finished")
+
+ claimed, err := s.ClaimAvailableReviewRuns(ctx, "replica")
+ require.NoError(t, err)
+ require.Len(t, claimed, 1)
+ updated, err := s.CompleteReviewRun(ctx, claimed[0], "replica", storepb.ReviewRun_DONE, &storepb.ReviewRunPayload{}, []*store.IssueCommentMessage{{
+ ProjectID: issue.ProjectID,
+ IssueUID: issue.UID,
+ Payload: &storepb.IssueCommentPayload{
+ Comment: "UPDATE without WHERE",
+ ReviewMetadata: &storepb.IssueCommentPayload_ReviewMetadata{
+ RunType: storepb.ReviewRun_RULE,
+ RuleType: storepb.ReviewRuleType_REQUIRE_WHERE,
+ Priority: storepb.IssueCommentPayload_ReviewMetadata_P1,
+ },
+ },
+ }})
+ require.NoError(t, err)
+ require.True(t, updated)
+ require.False(t, tryCreateRollout(), "the finding's thread is open")
+
+ threads, err := s.ListIssueComment(ctx, &store.FindIssueCommentMessage{ProjectID: issue.ProjectID, IssueUID: &issue.UID, ThreadState: &open})
+ require.NoError(t, err)
+ require.Len(t, threads, 1)
+ resolved := store.ThreadStateResolved
+ require.NoError(t, s.UpdateIssueComment(ctx, &store.UpdateIssueCommentMessage{
+ ProjectID: issue.ProjectID,
+ ResourceID: threads[0].ResourceID,
+ ThreadState: &resolved,
+ }))
+ require.True(t, tryCreateRollout(), "every thread is resolved")
+}
+
+func TestTryCreateRolloutStartsAMissingOrStaleReview(t *testing.T) {
+ ctx := context.Background()
+ s, plan, issue := newAutoRolloutIssue(ctx, t)
+ b, err := bus.New()
+ require.NoError(t, err)
+ creator := NewRolloutCreator(s, b, nil, true)
+ tryCreateRollout := func() bool {
+ t.Helper()
+ creator.tryCreateRollout(ctx, bus.PlanRef{ProjectID: plan.ProjectID, PlanID: plan.UID})
+ got, err := s.GetPlan(ctx, &store.FindPlanMessage{ProjectID: plan.ProjectID, UID: &plan.UID})
+ require.NoError(t, err)
+ return got.Config.GetHasRollout()
+ }
+ ruleRun := func(projectID string) *store.ReviewRunMessage {
+ t.Helper()
+ run, err := s.GetReviewRun(ctx, projectID, issue.UID, store.ReviewRunTypeRule)
+ require.NoError(t, err)
+ return run
+ }
+ completeRuleRun := func() {
+ t.Helper()
+ claimed, err := s.ClaimAvailableReviewRuns(ctx, "replica")
+ require.NoError(t, err)
+ require.Len(t, claimed, 1)
+ updated, err := s.CompleteReviewRun(ctx, claimed[0], "replica", storepb.ReviewRun_DONE, &storepb.ReviewRunPayload{}, nil)
+ require.NoError(t, err)
+ require.True(t, updated)
+ }
+
+ // The colliding issue of another project must not get a review.
+ _, err = s.GetDB().ExecContext(ctx, "INSERT INTO project (resource_id, workspace, name) VALUES ('project-b', $1, 'Project B')", autoRolloutWorkspaceID)
+ require.NoError(t, err)
+ planB, err := s.CreatePlan(ctx, &store.PlanMessage{ProjectID: "project-b", Name: "colliding plan", Config: &storepb.PlanConfig{}}, "[email protected]")
+ require.NoError(t, err)
+ issueB, err := s.CreateIssue(ctx, &store.IssueMessage{
+ ProjectID: "project-b",
+ CreatorEmail: "[email protected]",
+ Title: "colliding issue",
+ Type: storepb.Issue_DATABASE_CHANGE,
+ Payload: &storepb.Issue{},
+ PlanUID: &planB.UID,
+ })
+ require.NoError(t, err)
+ require.Equal(t, issue.UID, issueB.UID, "issue ids should collide")
+
+ require.False(t, tryCreateRollout(), "the review never started")
+ run := ruleRun(issue.ProjectID)
+ require.NotNil(t, run)
+ require.Equal(t, storepb.ReviewRun_AVAILABLE, run.Status)
+ require.Equal(t, int64(2), run.Payload.GetApprovalInputVersion())
+ require.Len(t, b.ReviewRunTickleChan, 1)
+ require.Nil(t, ruleRun("project-b"))
+
+ // The plan's SQL changes and is approved again, but the slot was not
+ // reset: the DONE run reviewed version 2.
+ completeRuleRun()
+ _, err = s.GetDB().ExecContext(ctx, `
+ UPDATE plan SET config = jsonb_set(config, '{approvalInputVersion}', '"3"')
+ WHERE project = $1 AND id = $2
+ `, plan.ProjectID, plan.UID)
+ require.NoError(t, err)
+ _, err = s.GetDB().ExecContext(ctx, `
+ UPDATE issue SET payload = jsonb_set(payload, '{approval,approvalInputVersion}', '"3"')
+ WHERE project = $1 AND id = $2
+ `, issue.ProjectID, issue.UID)
+ require.NoError(t, err)
+ require.False(t, tryCreateRollout(), "the done run reviewed older SQL")
+ run = ruleRun(issue.ProjectID)
+ require.Equal(t, storepb.ReviewRun_AVAILABLE, run.Status)
+ require.Equal(t, int64(1), run.Attempt)
+ require.Equal(t, int64(3), run.Payload.GetApprovalInputVersion())
+
+ completeRuleRun()
+ require.True(t, tryCreateRollout(), "the review of the current SQL is done")
+}
+
+func TestReviewRestartsWhenThePlanLosesItsSQL(t *testing.T) {
+ ctx := context.Background()
+ s, plan, issue := newAutoRolloutIssue(ctx, t)
+ project, err := s.GetProjectByResourceID(ctx, plan.ProjectID)
+ require.NoError(t, err)
+ b, err := bus.New()
+ require.NoError(t, err)
+ creator := NewRolloutCreator(s, b, nil, true)
+
+ // The review of version 2 left an open finding.
+ _, err = s.CreateReviewRun(ctx, issue.ProjectID, issue.UID, store.ReviewRunTypeRule)
+ require.NoError(t, err)
+ claimed, err := s.ClaimAvailableReviewRuns(ctx, "replica")
+ require.NoError(t, err)
+ require.Len(t, claimed, 1)
+ updated, err := s.CompleteReviewRun(ctx, claimed[0], "replica", storepb.ReviewRun_DONE, &storepb.ReviewRunPayload{}, []*store.IssueCommentMessage{{
+ ProjectID: issue.ProjectID,
+ IssueUID: issue.UID,
+ Payload: &storepb.IssueCommentPayload{
+ Comment: "UPDATE without WHERE",
+ ReviewMetadata: &storepb.IssueCommentPayload_ReviewMetadata{
+ RunType: storepb.ReviewRun_RULE,
+ RuleType: storepb.ReviewRuleType_REQUIRE_WHERE,
+ Priority: storepb.IssueCommentPayload_ReviewMetadata_P1,
+ },
+ },
+ }})
+ require.NoError(t, err)
+ require.True(t, updated)
+
+ // Version 3 has nothing to review.
+ _, err = s.GetDB().ExecContext(ctx, `
+ UPDATE plan SET config = jsonb_set(config, '{approvalInputVersion}', '"3"')
+ WHERE project = $1 AND id = $2
+ `, plan.ProjectID, plan.UID)
+ require.NoError(t, err)
+ plan, err = s.GetPlan(ctx, &store.FindPlanMessage{ProjectID: plan.ProjectID, UID: &plan.UID})
+ require.NoError(t, err)
+ plan.Config.Specs[0].GetChangeDatabaseConfig().Targets = nil
+
+ blocked, err := creator.reviewBlocksRollout(ctx, project, plan, issue)
+ require.NoError(t, err)
+ require.True(t, blocked)
+ run, err := s.GetReviewRun(ctx, issue.ProjectID, issue.UID, store.ReviewRunTypeRule)
+ require.NoError(t, err)
+ require.Equal(t, storepb.ReviewRun_AVAILABLE, run.Status)
+ require.Equal(t, int64(3), run.Payload.GetApprovalInputVersion())
+
+ // The restarted run finds nothing, which supersedes the earlier finding.
+ claimed, err = s.ClaimAvailableReviewRuns(ctx, "replica")
+ require.NoError(t, err)
+ require.Len(t, claimed, 1)
+ updated, err = s.CompleteReviewRun(ctx, claimed[0], "replica", storepb.ReviewRun_DONE, &storepb.ReviewRunPayload{}, nil)
+ require.NoError(t, err)
+ require.True(t, updated)
+ blocked, err = creator.reviewBlocksRollout(ctx, project, plan, issue)
+ require.NoError(t, err)
+ require.False(t, blocked)
+}
+
+func TestReviewDoesNotHoldARolloutWithNothingToRead(t *testing.T) {
+ ctx := context.Background()
+ s, plan, issue := newAutoRolloutIssue(ctx, t)
+ project, err := s.GetProjectByResourceID(ctx, plan.ProjectID)
+ require.NoError(t, err)
+ plan.Config.Specs[0].GetChangeDatabaseConfig().Targets = nil
+
+ b, err := bus.New()
+ require.NoError(t, err)
+ blocked, err := NewRolloutCreator(s, b, nil, true).reviewBlocksRollout(ctx, project, plan, issue)
+ require.NoError(t, err)
+ require.False(t, blocked)
+ run, err := s.GetReviewRun(ctx, issue.ProjectID, issue.UID, store.ReviewRunTypeRule)
+ require.NoError(t, err)
+ require.Nil(t, run, "no review starts without SQL to read")
+}
+
+func TestTryCreateRolloutIgnoresThreadsWithoutSQLReviewV2(t *testing.T) {
+ ctx := context.Background()
+ s, plan, issue := newAutoRolloutIssue(ctx, t)
+ open := store.ThreadStateOpen
+ _, err := s.CreateIssueComments(ctx, "[email protected]", &store.IssueCommentMessage{
+ ProjectID: issue.ProjectID,
+ IssueUID: issue.UID,
+ Payload: &storepb.IssueCommentPayload{Comment: "Is this safe?"},
+ ThreadState: &open,
+ })
+ require.NoError(t, err)
+
+ b, err := bus.New()
+ require.NoError(t, err)
+ NewRolloutCreator(s, b, nil, false).tryCreateRollout(ctx, bus.PlanRef{ProjectID: plan.ProjectID, PlanID: plan.UID})
+ got, err := s.GetPlan(ctx, &store.FindPlanMessage{ProjectID: plan.ProjectID, UID: &plan.UID})
+ require.NoError(t, err)
+ require.True(t, got.Config.GetHasRollout())
+}
+
+const autoRolloutWorkspaceID = "workspace-a"
+
+// newAutoRolloutIssue sets up a store with an approved issue in project-a whose
+// plan the rollout creator would roll out at once.
+func newAutoRolloutIssue(ctx context.Context, t *testing.T) (*store.Store, *store.PlanMessage, *store.IssueMessage) {
+ t.Helper()
+ s := setupRolloutCreatorStoreInWorkspace(ctx, t, autoRolloutWorkspaceID)
+ require.NoError(t, s.UpdateProjects(ctx, &store.UpdateProjectMessage{
+ ResourceID: "project-a",
+ Workspace: autoRolloutWorkspaceID,
+ Setting: &storepb.Project{RequireIssueApproval: false},
+ }))
+ environment := "prod"
+ projectID := "project-a"
+ _, err := s.CreateInstance(ctx, &store.InstanceMessage{
+ ResourceID: "prod",
+ Workspace: autoRolloutWorkspaceID,
+ ProjectID: &projectID,
+ EnvironmentID: &environment,
+ Metadata: &storepb.Instance{
+ Engine: storepb.Engine_POSTGRES,
+ DataSources: []*storepb.DataSource{{Id: "admin", Type: storepb.DataSourceType_ADMIN}},
+ },
+ })
+ require.NoError(t, err)
+ _, err = s.UpsertDatabase(ctx, &store.DatabaseMessage{
+ ProjectID: projectID,
+ InstanceID: "prod",
+ DatabaseName: "app",
+ Metadata: &storepb.DatabaseMetadata{Labels: map[string]string{}},
+ })
+ require.NoError(t, err)
+ plan, err := s.CreatePlan(ctx, &store.PlanMessage{
+ ProjectID: projectID,
+ Name: "auto rollout plan",
+ Config: &storepb.PlanConfig{
+ ApprovalInputVersion: 2,
+ Specs: []*storepb.PlanConfig_Spec{{
+ Id: "change",
+ Config: &storepb.PlanConfig_Spec_ChangeDatabaseConfig{
+ ChangeDatabaseConfig: &storepb.PlanConfig_ChangeDatabaseConfig{
+ Targets: []string{"projects/project-a/instances/prod/databases/app"},
+ },
+ },
+ }},
+ },
+ require.NoError(t, err)
+ issue, err := s.CreateIssue(ctx, &store.IssueMessage{
+ ProjectID: projectID,
+ CreatorEmail: "[email protected]",
+ Title: "auto rollout issue",
+ Type: storepb.Issue_DATABASE_CHANGE,
+ Payload: &storepb.Issue{Approval: &storepb.IssuePayloadApproval{
+ ApprovalFindingDone: true,
+ ApprovalInputVersion: 2,
+ }},
+ PlanUID: &plan.UID,
+ })
+ require.NoError(t, err)
+ return s, plan, issue
+}
+
func setupRolloutCreatorStore(ctx context.Context, t *testing.T) *store.Store {
return setupRolloutCreatorStoreInWorkspace(ctx, t, "default")
}
diff --git a/backend/runner/taskrun/scheduler.go b/backend/runner/taskrun/scheduler.go
index 15295b7616..74f402dd43 100644
--- a/backend/runner/taskrun/scheduler.go
+++ b/backend/runner/taskrun/scheduler.go
@@ -166,7 +166,7 @@ func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
wg.Go(func() { s.runTaskCompletionListener(ctx) })
// Start rollout creator component
- rolloutCreator := NewRolloutCreator(s.store, s.bus, s.webhookManager)
+ rolloutCreator := NewRolloutCreator(s.store, s.bus, s.webhookManager, s.profile.SQLReviewV2)
wg.Add(3)
go rolloutCreator.Run(ctx, wg, s.bus.RolloutCreationChan)
go s.runPendingTaskRunsScheduler(ctx, wg)
diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.go
index 288c462b4a..20d9388f93 100644
--- a/backend/server/grpc_routes.go
+++ b/backend/server/grpc_routes.go
@@ -104,9 +104,9 @@ func configureGrpcRouters(
identityProviderService := apiv1.NewIdentityProviderService(stores, licenseService, profile)
instanceRoleService := apiv1.NewInstanceRoleService(stores)
instanceService := apiv1.NewInstanceService(stores, profile, licenseService, dbFactory, schemaSyncer, sampleManager)
- issueService := apiv1.NewIssueService(stores, webhookManager, bus, licenseService, iamManager)
+ issueService := apiv1.NewIssueService(stores, webhookManager, bus, licenseService, iamManager, profile)
orgPolicyService := apiv1.NewOrgPolicyService(stores, licenseService, iamManager)
- planService := apiv1.NewPlanService(stores, bus, iamManager, webhookManager, licenseService)
+ planService := apiv1.NewPlanService(stores, bus, iamManager, webhookManager, licenseService, profile)
projectService := apiv1.NewProjectService(stores, profile, iamManager, sampleManager)
queryHistoryService := apiv1.NewQueryHistoryService(stores)
releaseService := apiv1.NewReleaseService(stores, sheetManager, dbFactory, licenseService)
diff --git a/backend/server/server.go b/backend/server/server.go
index 0b6fda6ff5..b7eb26ec36 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -241,7 +241,11 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
s.taskScheduler.Register(storepb.Task_DATABASE_CREATE, taskrun.NewDatabaseCreateExecutor(stores, s.dbFactory, s.schemaSyncer))
s.taskScheduler.Register(storepb.Task_DATABASE_MIGRATE, taskrun.NewDatabaseMigrateExecutor(stores, s.dbFactory, s.bus, s.schemaSyncer, profile))
- combinedExecutor := plancheck.NewCombinedExecutor(stores, sheetManager, s.dbFactory)
+ var ruleReviewCovers func(storepb.Engine) bool
+ if profile.SQLReviewV2 {
+ ruleReviewCovers = reviewrun.ReviewsEngine
+ }
+ combinedExecutor := plancheck.NewCombinedExecutor(stores, sheetManager, s.dbFactory, ruleReviewCovers)
s.planCheckScheduler = plancheck.NewScheduler(stores, s.bus, combinedExecutor, s.licenseService, productMetrics)
s.reviewRunScheduler = reviewrun.NewScheduler(stores, s.bus, profile, s.licenseService, productMetrics)
diff --git a/backend/store/issue_service_concurrency_test.go b/backend/store/issue_service_concurrency_test.go
index e2078bba42..243c53549a 100644
--- a/backend/store/issue_service_concurrency_test.go
+++ b/backend/store/issue_service_concurrency_test.go
@@ -22,6 +22,7 @@ import (
apiv1 "github.com/bytebase/bytebase/backend/api/v1"
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/component/bus"
+ "github.com/bytebase/bytebase/backend/component/config"
"github.com/bytebase/bytebase/backend/component/iam"
"github.com/bytebase/bytebase/backend/component/webhook"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
@@ -330,7 +331,7 @@ func TestCreateDraftIssueIsIdempotent(t *testing.T) {
stores := setupIssueServiceTestStore(ctx, t)
b, err := bus.New()
require.NoError(t, err)
- service := apiv1.NewIssueService(stores, nil, b, nil, nil)
+ service := apiv1.NewIssueService(stores, nil, b, nil, nil, &config.Profile{})
plan, err := stores.CreatePlan(ctx, &store.PlanMessage{
ProjectID: "project-a",
@@ -550,7 +551,7 @@ func newIssueServiceForTest(t *testing.T, stores *store.Store) (*apiv1.IssueServ
require.NoError(t, err)
iamManager, err := iam.NewManager(stores, nil, false)
require.NoError(t, err)
- return apiv1.NewIssueService(stores, webhook.NewManager(stores, nil), b, nil, iamManager), b
+ return apiv1.NewIssueService(stores, webhook.NewManager(stores, nil), b, nil, iamManager, &config.Profile{}), b
}
func createIssueServiceApprovalIssue(ctx context.Context, t *testing.T, stores *store.Store) (*store.PlanMessage, *store.IssueMessage) {
diff --git a/backend/store/review_run.go b/backend/store/review_run.go
index 41391a031a..8c01bbf183 100644
--- a/backend/store/review_run.go
+++ b/backend/store/review_run.go
@@ -38,8 +38,9 @@ type ReviewRunMessage struct {
// CreateReviewRun creates a new AVAILABLE run in the (issue, reviewer type)
// slot. The slot row is reset in place unconditionally: created at attempt 0
-// when absent, attempt bumped otherwise, with created_at restarted and
-// replica_id and payload cleared. A RUNNING execution is superseded — its
+// when absent, attempt bumped otherwise, with created_at restarted,
+// replica_id cleared, and the payload reset to the approval input version of
+// the issue's plan as of this write. A RUNNING execution is superseded — its
// completion transaction is fenced on the old attempt and will match zero
// rows.
//
@@ -57,9 +58,11 @@ func (s *Store) CreateReviewRun(ctx context.Context, projectID string, issueUID
}
q := qb.Q().Space(`
- INSERT INTO review_run (project, issue_id, type, status)
- SELECT issue.project, issue.id, ?, ?
+ INSERT INTO review_run (project, issue_id, type, status, payload)
+ SELECT issue.project, issue.id, ?, ?,
+ jsonb_strip_nulls(jsonb_build_object('approvalInputVersion', plan.config->'approvalInputVersion'))
FROM issue
+ LEFT JOIN plan ON plan.project = issue.project AND plan.id = issue.plan_id
WHERE issue.project = ? AND issue.id = ?
ON CONFLICT (project, issue_id, type) DO UPDATE
SET status = EXCLUDED.status,
@@ -67,8 +70,8 @@ func (s *Store) CreateReviewRun(ctx context.Context, projectID string, issueUID
created_at = now(),
updated_at = now(),
replica_id = NULL,
- payload = '{}'
- RETURNING attempt, created_at, updated_at
+ payload = EXCLUDED.payload
+ RETURNING attempt, payload, created_at, updated_at
`, reviewType, storepb.ReviewRun_AVAILABLE.String(), projectID, issueUID)
query, args, err := q.ToSQL()
@@ -83,12 +86,16 @@ func (s *Store) CreateReviewRun(ctx context.Context, projectID string, issueUID
Status: storepb.ReviewRun_AVAILABLE,
Payload: &storepb.ReviewRunPayload{},
}
- if err := tx.QueryRowContext(ctx, query, args...).Scan(&reviewRun.Attempt, &reviewRun.CreatedAt, &reviewRun.UpdatedAt); err != nil {
+ var payload []byte
+ if err := tx.QueryRowContext(ctx, query, args...).Scan(&reviewRun.Attempt, &payload, &reviewRun.CreatedAt, &reviewRun.UpdatedAt); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, common.Errorf(common.NotFound, "issue %d not found in project %s", issueUID, projectID)
}
return nil, errors.Wrapf(err, "failed to create review run")
}
+ if err := common.ProtojsonUnmarshaler.Unmarshal(payload, reviewRun.Payload); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal review run payload")
+ }
if err := tx.Commit(); err != nil {
return nil, errors.Wrapf(err, "failed to commit tx")
@@ -96,6 +103,12 @@ func (s *Store) CreateReviewRun(ctx context.Context, projectID string, issueUID
return reviewRun, nil
}
+// keepApprovalInputVersion is the payload a terminal write stores: the new
+// payload, with the slot's approval input version carried over. Losing it would
+// make a finished run look stale to the rollout creator, which would start it
+// again.
+const keepApprovalInputVersion = `CAST(? AS JSONB) || jsonb_strip_nulls(jsonb_build_object('approvalInputVersion', review_run.payload->'approvalInputVersion'))`
+
// GetReviewRun returns the run in the (issue, reviewer type) slot as stored,
// or nil when the slot was never created.
func (s *Store) GetReviewRun(ctx context.Context, projectID string, issueUID int64, reviewType string) (*ReviewRunMessage, error) {
@@ -195,9 +208,10 @@ func (s *Store) ClaimAvailableReviewRuns(ctx context.Context, replicaID string)
// CompleteReviewRun moves a RUNNING run this replica owns to a terminal
// status, fenced on the claim's attempt. On DONE it posts the run's results in
-// the same transaction: every OPEN root the same reviewer posted on the issue
-// is resolved, then the results are inserted as OPEN roots with no creator. A
-// FAILED run leaves the comments alone and takes no results. False means
+// the same transaction: every earlier root the same reviewer posted on the
+// issue is marked superseded and, if OPEN, resolved; then the results are
+// inserted as OPEN roots with no creator. A FAILED run leaves the comments
+// alone and takes no results. False means
// superseded: the slot was reset or reaped since the claim, and nothing was
// written.
//
@@ -233,13 +247,16 @@ func (s *Store) CompleteReviewRun(ctx context.Context, claimed *ClaimedReviewRun
defer tx.Rollback()
if status == storepb.ReviewRun_DONE {
- // The literal 'OPEN' lets the planner use idx_issue_comment_open_thread.
+ // Each earlier root is marked once, and resolved again if someone
+ // reopened it. updated_at marks content edits, so it is left alone.
q := qb.Q().Space(`
UPDATE issue_comment
- SET thread_state = ?
+ SET thread_state = ?,
+ payload = jsonb_set(payload, '{reviewMetadata,superseded}', 'true'::jsonb)
WHERE project = ? AND issue_id = ?
- AND parent_id IS NULL AND thread_state = 'OPEN'
+ AND parent_id IS NULL
AND payload->'reviewMetadata'->>'runType' = ?
+ AND (thread_state = 'OPEN' OR payload->'reviewMetadata'->'superseded' IS NULL)
`, string(ThreadStateResolved), claimed.ProjectID, claimed.IssueUID, claimed.Type)
query, args, err := q.ToSQL()
if err != nil {
@@ -252,10 +269,10 @@ func (s *Store) CompleteReviewRun(ctx context.Context, claimed *ClaimedReviewRun
q := qb.Q().Space(`
UPDATE review_run
- SET status = ?, updated_at = now(), payload = ?
+ SET status = ?, updated_at = now(), payload = `+keepApprovalInputVersion+`
WHERE project = ? AND issue_id = ? AND type = ?
AND status = ? AND replica_id = ? AND attempt = ?
- `, status.String(), payloadBytes,
+ `, status.String(), string(payloadBytes),
claimed.ProjectID, claimed.IssueUID, claimed.Type,
storepb.ReviewRun_RUNNING.String(), replicaID, claimed.Attempt)
query, args, err := q.ToSQL()
@@ -346,7 +363,7 @@ func (s *Store) FailStaleReviewRuns(ctx context.Context, stalenessThreshold time
q := qb.Q().Space(`
UPDATE review_run
- SET status = ?, updated_at = now(), payload = ?
+ SET status = ?, updated_at = now(), payload = `+keepApprovalInputVersion+`
WHERE status = ?
AND replica_id IS NOT NULL
AND NOT EXISTS (
@@ -354,7 +371,7 @@ func (s *Store) FailStaleReviewRuns(ctx context.Context, stalenessThreshold time
WHERE rh.replica_id = review_run.replica_id
AND rh.last_heartbeat >= now() - ?::INTERVAL
)
- `, storepb.ReviewRun_FAILED.String(), payloadBytes,
+ `, storepb.ReviewRun_FAILED.String(), string(payloadBytes),
storepb.ReviewRun_RUNNING.String(), stalenessThreshold.String())
query, args, err := q.ToSQL()
diff --git a/backend/store/review_run_results_test.go b/backend/store/review_run_results_test.go
index f6c860bc8e..b42eb30b00 100644
--- a/backend/store/review_run_results_test.go
+++ b/backend/store/review_run_results_test.go
@@ -2,6 +2,7 @@ package store_test
import (
"testing"
+ "time"
"github.com/stretchr/testify/require"
@@ -247,3 +248,122 @@ func TestCompleteReviewRunPostsResults(t *testing.T) {
require.Equal(t, "RESOLVED", c.ThreadState, c.Comment)
}
}
+
+type supersession struct {
+ Comment string
+ ThreadState string
+ Superseded bool
+}
+
+func listSupersession(t *testing.T, fixture *storePostgresFixture, projectID string) ([]supersession, map[string]time.Time) {
+ t.Helper()
+ rows, err := fixture.db.QueryContext(fixture.ctx, `
+ SELECT payload->>'comment', thread_state,
+ COALESCE((payload->'reviewMetadata'->>'superseded')::boolean, false), updated_at
+ FROM issue_comment
+ WHERE project = $1 AND issue_id = $2 AND payload ? 'reviewMetadata'
+ ORDER BY created_at, resource_id
+ `, projectID, reviewResultIssue)
+ require.NoError(t, err)
+ defer rows.Close()
+ var out []supersession
+ updatedAt := make(map[string]time.Time)
+ for rows.Next() {
+ var s supersession
+ var at time.Time
+ require.NoError(t, rows.Scan(&s.Comment, &s.ThreadState, &s.Superseded, &at))
+ out = append(out, s)
+ updatedAt[s.Comment] = at
+ }
+ require.NoError(t, rows.Err())
+ return out, updatedAt
+}
+
+// TestCompleteReviewRunSupersedesEarlierResults pins what tells the latest
+// review apart: a DONE completion marks every earlier result of its reviewer
+// on its issue superseded, whatever its thread state, without touching
+// updated_at; a FAILED completion marks nothing; another reviewer's results
+// and the colliding issue in another project keep theirs.
+func TestCompleteReviewRunSupersedesEarlierResults(t *testing.T) {
+ t.Parallel()
+ fixture := newStorePostgresFixture(t, `
+ INSERT INTO project (resource_id, workspace, name) VALUES ('other', 'default', 'Other');
+ INSERT INTO issue (id, creator, project, name, status, type)
+ VALUES (301, '[email protected]', 'default', 'Issue Default', 'OPEN', 'DATABASE_CHANGE');
+ INSERT INTO issue (id, creator, project, name, status, type)
+ VALUES (301, '[email protected]', 'other', 'Issue Other', 'OPEN', 'DATABASE_CHANGE');
+ `)
+ ctx, s := fixture.ctx, fixture.store
+ const issueUID = reviewResultIssue
+ complete := func(projectID, reviewType string, status storepb.ReviewRun_Status, results ...*store.IssueCommentMessage) {
+ t.Helper()
+ _, err := s.CreateReviewRun(ctx, projectID, issueUID, reviewType)
+ require.NoError(t, err)
+ claimed, err := s.ClaimAvailableReviewRuns(ctx, "replica-1")
+ require.NoError(t, err)
+ require.Len(t, claimed, 1)
+ updated, err := s.CompleteReviewRun(ctx, claimed[0], "replica-1", status, &storepb.ReviewRunPayload{}, results)
+ require.NoError(t, err)
+ require.True(t, updated)
+ }
+ setThreadState := func(comment string, state store.ThreadState) {
+ t.Helper()
+ roots, err := s.ListIssueComment(ctx, &store.FindIssueCommentMessage{ProjectID: "default", IssueUID: &[]int64{issueUID}[0]})
+ require.NoError(t, err)
+ for _, root := range roots {
+ if root.Payload.Comment == comment {
+ require.NoError(t, s.UpdateIssueComment(ctx, &store.UpdateIssueCommentMessage{ProjectID: "default", ResourceID: root.ResourceID, ThreadState: &state}))
+ return
+ }
+ }
+ t.Fatalf("no comment %q", comment)
+ }
+ aiResult := reviewResult("default", "ai", storepb.ReviewRuleType_REVIEW_RULE_TYPE_UNSPECIFIED)
+ aiResult.Payload.ReviewMetadata.RunType = storepb.ReviewRun_AI
+
+ complete("default", store.ReviewRunTypeAI, storepb.ReviewRun_DONE, aiResult)
+ complete("other", store.ReviewRunTypeRule, storepb.ReviewRun_DONE, reviewResult("other", "other first", storepb.ReviewRuleType_REQUIRE_WHERE))
+ complete("default", store.ReviewRunTypeRule, storepb.ReviewRun_DONE,
+ reviewResult("default", "first", storepb.ReviewRuleType_REQUIRE_WHERE),
+ reviewResult("default", "dismissed", storepb.ReviewRuleType_DISALLOW_TRUNCATE),
+ )
+ // A person resolves one result of the run, as a false positive.
+ setThreadState("dismissed", store.ThreadStateResolved)
+ _, updatedBefore := listSupersession(t, fixture, "default")
+
+ complete("default", store.ReviewRunTypeRule, storepb.ReviewRun_DONE, reviewResult("default", "second", storepb.ReviewRuleType_REQUIRE_WHERE))
+ got, updatedAfter := listSupersession(t, fixture, "default")
+ require.Equal(t, []supersession{
+ {Comment: "ai", ThreadState: "OPEN"},
+ {Comment: "first", ThreadState: "RESOLVED", Superseded: true},
+ {Comment: "dismissed", ThreadState: "RESOLVED", Superseded: true},
+ {Comment: "second", ThreadState: "OPEN"},
+ }, got)
+ for _, comment := range []string{"first", "dismissed"} {
+ require.Equal(t, updatedBefore[comment], updatedAfter[comment], "superseding %q is no content edit", comment)
+ }
+ other, _ := listSupersession(t, fixture, "other")
+ require.Equal(t, []supersession{{Comment: "other first", ThreadState: "OPEN"}}, other, "the colliding issue in the other project is untouched")
+
+ // A FAILED run supersedes nothing: the latest review is still the last DONE.
+ setThreadState("first", store.ThreadStateOpen)
+ complete("default", store.ReviewRunTypeRule, storepb.ReviewRun_FAILED)
+ afterFailure, _ := listSupersession(t, fixture, "default")
+ require.Equal(t, []supersession{
+ {Comment: "ai", ThreadState: "OPEN"},
+ {Comment: "first", ThreadState: "OPEN", Superseded: true},
+ {Comment: "dismissed", ThreadState: "RESOLVED", Superseded: true},
+ {Comment: "second", ThreadState: "OPEN"},
+ }, afterFailure)
+
+ // The next DONE, here with no findings, supersedes the rest and resolves
+ // the reopened result again.
+ complete("default", store.ReviewRunTypeRule, storepb.ReviewRun_DONE)
+ final, _ := listSupersession(t, fixture, "default")
+ require.Equal(t, []supersession{
+ {Comment: "ai", ThreadState: "OPEN"},
+ {Comment: "first", ThreadState: "RESOLVED", Superseded: true},
+ {Comment: "dismissed", ThreadState: "RESOLVED", Superseded: true},
+ {Comment: "second", ThreadState: "RESOLVED", Superseded: true},
+ }, final)
+}
diff --git a/backend/store/review_run_test.go b/backend/store/review_run_test.go
index 4da9e7bd7c..647560a3af 100644
--- a/backend/store/review_run_test.go
+++ b/backend/store/review_run_test.go
@@ -194,3 +194,73 @@ func TestGetReviewRunCollidingIssues(t *testing.T) {
require.NoError(t, err)
require.Nil(t, got)
}
+
+func TestReviewRunKeepsItsApprovalInputVersion(t *testing.T) {
+ t.Parallel()
+ fixture := newStorePostgresFixture(t, `
+ INSERT INTO project (resource_id, workspace, name) VALUES ('other', 'default', 'Other');
+ INSERT INTO plan (id, creator, project, name, description, config)
+ VALUES (101, '[email protected]', 'default', 'Plan Default', '', '{"approvalInputVersion": "2"}');
+ INSERT INTO plan (id, creator, project, name, description, config)
+ VALUES (101, '[email protected]', 'other', 'Plan Other', '', '{"approvalInputVersion": "7"}');
+ INSERT INTO issue (id, creator, project, name, status, type, plan_id)
+ VALUES (201, '[email protected]', 'default', 'Issue Default', 'OPEN', 'DATABASE_CHANGE', 101);
+ INSERT INTO issue (id, creator, project, name, status, type, plan_id)
+ VALUES (201, '[email protected]', 'other', 'Issue Other', 'OPEN', 'DATABASE_CHANGE', 101);
+ `)
+ ctx, db, s := fixture.ctx, fixture.db, fixture.store
+ slot := func(projectID string) *store.ReviewRunMessage {
+ t.Helper()
+ run, err := s.GetReviewRun(ctx, projectID, 201, store.ReviewRunTypeRule)
+ require.NoError(t, err)
+ require.NotNil(t, run)
+ return run
+ }
+
+ run, err := s.CreateReviewRun(ctx, "default", 201, store.ReviewRunTypeRule)
+ require.NoError(t, err)
+ require.Equal(t, int64(2), run.Payload.GetApprovalInputVersion())
+ run, err = s.CreateReviewRun(ctx, "other", 201, store.ReviewRunTypeRule)
+ require.NoError(t, err)
+ require.Equal(t, int64(7), run.Payload.GetApprovalInputVersion())
+ claimed, err := s.ClaimAvailableReviewRuns(ctx, "replica-1")
+ require.NoError(t, err)
+ require.Len(t, claimed, 2)
+
+ // The plan's SQL changes while the run reads version 2: the run finishes
+ // with the version it reviewed.
+ _, err = db.ExecContext(ctx, `
+ UPDATE plan SET config = jsonb_set(config, '{approvalInputVersion}', '"3"')
+ WHERE project = 'default' AND id = 101
+ `)
+ require.NoError(t, err)
+ for _, c := range claimed {
+ if c.ProjectID != "default" {
+ continue
+ }
+ updated, err := s.CompleteReviewRun(ctx, c, "replica-1", storepb.ReviewRun_DONE, &storepb.ReviewRunPayload{}, nil)
+ require.NoError(t, err)
+ require.True(t, updated)
+ }
+ require.Equal(t, storepb.ReviewRun_DONE, slot("default").Status)
+ require.Equal(t, int64(2), slot("default").Payload.GetApprovalInputVersion())
+
+ run, err = s.CreateReviewRun(ctx, "default", 201, store.ReviewRunTypeRule)
+ require.NoError(t, err)
+ require.Equal(t, int64(3), run.Payload.GetApprovalInputVersion())
+ require.Equal(t, int64(3), slot("default").Payload.GetApprovalInputVersion())
+ _, err = s.ClaimAvailableReviewRuns(ctx, "replica-1")
+ require.NoError(t, err)
+
+ // replica-1 has no heartbeat, so the reaper fails both running slots; each
+ // keeps its own version.
+ reaped, err := s.FailStaleReviewRuns(ctx, time.Minute)
+ require.NoError(t, err)
+ require.Equal(t, int64(2), reaped)
+ for projectID, version := range map[string]int64{"default": 3, "other": 7} {
+ got := slot(projectID)
+ require.Equal(t, storepb.ReviewRun_FAILED, got.Status)
+ require.NotEmpty(t, got.Payload.GetError())
+ require.Equal(t, version, got.Payload.GetApprovalInputVersion(), projectID)
+ }
+}
diff --git a/backend/tests/review_run_lifecycle_test.go b/backend/tests/review_run_lifecycle_test.go
index 549e0d8035..929caf0b17 100644
--- a/backend/tests/review_run_lifecycle_test.go
+++ b/backend/tests/review_run_lifecycle_test.go
@@ -18,6 +18,7 @@ import (
"google.golang.org/protobuf/types/known/fieldmaskpb"
"github.com/bytebase/bytebase/backend/common"
+ component "github.com/bytebase/bytebase/backend/component/config"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
)
@@ -59,7 +60,7 @@ func TestCollision_RunReviewLifecycle(t *testing.T) {
a := require.New(t)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
- ctl, ctx := startWorkspace(ctx, t)
+ ctl, ctx := startWorkspace(ctx, t, func(p *component.Profile) { p.SQLReviewV2 = true })
fixture := setupCollidingProjects(ctx, t, ctl)
@@ -69,7 +70,7 @@ func TestCollision_RunReviewLifecycle(t *testing.T) {
a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err))
// Fresh colliding plan+issue pairs without rollouts.
- _, issueA := createPlanAndIssue(ctx, t, ctl, fixture.ProjectA, fixture.DatabaseA, "Review lifecycle A")
+ planA, issueA := createPlanAndIssue(ctx, t, ctl, fixture.ProjectA, fixture.DatabaseA, "Review lifecycle A")
_, issueB := createPlanAndIssue(ctx, t, ctl, fixture.ProjectB, fixture.DatabaseB, "Review lifecycle B")
projectAID, issueAUID, err := common.GetProjectIDIssueUID(issueA.Name)
a.NoError(err)
@@ -77,6 +78,14 @@ func TestCollision_RunReviewLifecycle(t *testing.T) {
a.NoError(err)
a.Equal(issueAUID, issueBUID, "fixture issue ids should collide")
+ // Creating an issue starts its rule review.
+ rowA := waitReviewRunTerminal(ctx, t, ctl, projectAID, issueAUID, "RULE")
+ a.Equal("DONE", rowA.Status, "rule review on project A, got payload %s", rowA.Payload)
+ a.Equal(int64(0), rowA.Attempt)
+ rowB := waitReviewRunTerminal(ctx, t, ctl, projectBID, issueBUID, "RULE")
+ a.Equal("DONE", rowB.Status, "rule review on project B, got payload %s", rowB.Payload)
+ a.Equal(int64(0), rowB.Attempt)
+
// Unknown reviewer type.
_, err = runReview(ctx, ctl, issueA.Name, "bogus")
a.Equal(connect.CodeInvalidArgument, connect.CodeOf(err))
@@ -100,25 +109,51 @@ func TestCollision_RunReviewLifecycle(t *testing.T) {
// The scheduler claims and executes both. The rule executor evaluates
// the real test databases through omni's SQL Review V2 contract.
- rowA := waitReviewRunTerminal(ctx, t, ctl, projectAID, issueAUID, "RULE")
+ rowA = waitReviewRunTerminal(ctx, t, ctl, projectAID, issueAUID, "RULE")
a.Equal("DONE", rowA.Status, "rule review on project A, got payload %s", rowA.Payload)
- a.Equal(int64(0), rowA.Attempt)
- rowB := waitReviewRunTerminal(ctx, t, ctl, projectBID, issueBUID, "RULE")
+ a.Equal(int64(1), rowA.Attempt)
+ rowB = waitReviewRunTerminal(ctx, t, ctl, projectBID, issueBUID, "RULE")
a.Equal("DONE", rowB.Status, "rule review on project B, got payload %s", rowB.Payload)
- a.Equal(int64(0), rowB.Attempt)
+ a.Equal(int64(1), rowB.Attempt)
// Re-running A bumps only A's attempt; B's colliding slot is untouched.
+ // The fixture's own issues started reviews too; they settle first.
+ a.Eventually(func() bool {
+ for _, r := range listReviewRuns(ctx, t, ctl, projectBID) {
+ if r.Status != "DONE" && r.Status != "FAILED" {
+ return false
+ }
+ }
+ return true
+ }, 90*time.Second, 500*time.Millisecond, "project B review runs should settle")
beforeB := listReviewRuns(ctx, t, ctl, projectBID)
a.Greater(len(beforeB), 0, "project B should have review_run rows")
runA2, err := runReview(ctx, ctl, issueA.Name, "rule")
a.NoError(err)
a.Equal(v1pb.ReviewRun_AVAILABLE, runA2.Status)
rowA2 := waitReviewRunTerminal(ctx, t, ctl, projectAID, issueAUID, "RULE")
- a.Equal(int64(1), rowA2.Attempt)
+ a.Equal(int64(2), rowA2.Attempt)
a.Equal("DONE", rowA2.Status)
afterB := listReviewRuns(ctx, t, ctl, projectBID)
a.Equal(beforeB, afterB, "project B review_run rows must be untouched by A's re-run")
+ // Running the plan checks re-runs the rule review, and the checks leave
+ // the SQL review to it.
+ _, err = ctl.planServiceClient.RunPlanChecks(ctx, connect.NewRequest(&v1pb.RunPlanChecksRequest{Name: planA.Name}))
+ a.NoError(err)
+ rowA2 = waitReviewRunTerminal(ctx, t, ctl, projectAID, issueAUID, "RULE")
+ a.Equal(int64(3), rowA2.Attempt)
+ a.Equal("DONE", rowA2.Status)
+ waitPlanCheckRunSettled(ctx, t, ctl, planA.Name)
+ checkRun, err := ctl.planServiceClient.GetPlanCheckRun(ctx, connect.NewRequest(&v1pb.GetPlanCheckRunRequest{Name: planA.Name + "/planCheckRun"}))
+ a.NoError(err)
+ var checkTypes []v1pb.PlanCheckRun_Result_Type
+ for _, result := range checkRun.Msg.Results {
+ checkTypes = append(checkTypes, result.Type)
+ }
+ a.Contains(checkTypes, v1pb.PlanCheckRun_Result_STATEMENT_SUMMARY_REPORT)
+ a.NotContains(checkTypes, v1pb.PlanCheckRun_Result_STATEMENT_ADVISE)
+
brokenModel := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, `{"error": {"message": "quota exceeded"}}`, http.StatusServiceUnavailable)
}))
@@ -150,7 +185,7 @@ func TestCollision_RunReviewLifecycle(t *testing.T) {
a.Contains(aiRow.Payload, "model call 1 failed")
// The failed AI run left A's rule slot alone.
rowA3 := waitReviewRunTerminal(ctx, t, ctl, projectAID, issueAUID, "RULE")
- a.Equal(int64(1), rowA3.Attempt)
+ a.Equal(int64(3), rowA3.Attempt)
a.Equal("DONE", rowA3.Status)
// A table in A's database for the model to read through the tools.
diff --git a/backend/tests/tests.go b/backend/tests/tests.go
index 794626ab79..c215613f77 100644
--- a/backend/tests/tests.go
+++ b/backend/tests/tests.go
@@ -180,10 +180,10 @@ func sharedServer(t *testing.T) *controller {
// when the test writes what the workspace shares — a setting, a workspace or
// environment policy, the license, the IAM policy, a workspace-scoped ID, the
// demo principal's credentials — or asserts on a workspace-wide list.
-func startWorkspace(ctx context.Context, t *testing.T) (*controller, context.Context) {
+func startWorkspace(ctx context.Context, t *testing.T, configure ...func(*component.Profile)) (*controller, context.Context) {
t.Helper()
ctl := &controller{}
- ctx, err := ctl.StartServerWithExternalPg(ctx)
+ ctx, err := ctl.StartServerWithExternalPg(ctx, configure...)
require.NoError(t, err)
t.Cleanup(func() { _ = ctl.Close(ctx) })
return ctl, ctx
@@ -222,7 +222,8 @@ func startProject(ctx context.Context, t *testing.T) (*controller, context.Conte
}
// StartServerWithExternalPg starts the main server with external Postgres.
-func (ctl *controller) StartServerWithExternalPg(ctx context.Context) (context.Context, error) {
+// configure adjusts the server profile before the server starts.
+func (ctl *controller) StartServerWithExternalPg(ctx context.Context, configure ...func(*component.Profile)) (context.Context, error) {
pgMainURL := fmt.Sprintf("postgresql://postgres:root-password@%s:%s/postgres", externalPgHost, externalPgPort)
db, err := sql.Open("pgx", pgMainURL)
if err != nil {
@@ -237,6 +238,9 @@ func (ctl *controller) StartServerWithExternalPg(ctx context.Context) (context.C
pgURL := fmt.Sprintf("postgresql://postgres:root-password@%s:%s/%s", externalPgHost, externalPgPort, databaseName)
serverPort := getTestPort()
profile := getTestProfileWithExternalPg(serverPort, pgURL)
+ for _, c := range configure {
+ c(profile)
+ }
server, err := server.NewServer(ctx, profile)
if err != nil {
return nil, err
diff --git a/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx b/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx
index b48ace6834..6094610627 100644
--- a/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx
+++ b/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx
@@ -12,6 +12,7 @@ import {
IssueComment_ReviewSubmissionSchema,
IssueCommentSchema,
IssueSchema,
+ ReviewRun_Type,
} from "@/types/proto-es/v1/issue_service_pb";
import {
Plan_ChangeDatabaseConfigSchema,
@@ -154,6 +155,19 @@ describe("canEditIssueComment", () => {
expect(canEditIssueComment(reviewSubmission, project)).toBe(false);
expect(canEditIssueComment(own, undefined)).toBe(false);
});
+
+ test("a review result is never editable: its text is the reviewer's", () => {
+ mocks.hasPermission.mockImplementation(
+ (_project: unknown, permission: unknown) =>
+ permission === "bb.issueComments.update"
+ );
+ const result = create(IssueCommentSchema, {
+ name: "projects/p1/issues/1/issueComments/10",
+ comment: "DELETE FROM employee has no WHERE clause",
+ reviewMetadata: { runType: ReviewRun_Type.RULE },
+ });
+ expect(canEditIssueComment(result, project)).toBe(false);
+ });
});
describe("IssueCommentRow", () => {
diff --git a/frontend/src/components/issue-activity/IssueCommentActivity.tsx b/frontend/src/components/issue-activity/IssueCommentActivity.tsx
index e0f8febb68..6c0b2f5af6 100644
--- a/frontend/src/components/issue-activity/IssueCommentActivity.tsx
+++ b/frontend/src/components/issue-activity/IssueCommentActivity.tsx
@@ -96,12 +96,13 @@ function isDoneRolloutComment(
// Whether the current user may edit a comment: only user comments and approval
// decisions that carry a note are editable, and only with the update
-// permission. Shared so every activity surface gates edits alike.
+// permission. A review result's text is its reviewer's, which the server
+// refuses to edit. Shared so every activity surface gates edits alike.
export function canEditIssueComment(
comment: IssueComment,
project: Parameters<typeof hasProjectPermissionV2>[0] | undefined
): boolean {
- if (!project) {
+ if (!project || comment.reviewMetadata) {
return false;
}
const type = getIssueCommentType(comment);
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index e626e82872..8704a49981 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1812,6 +1812,10 @@
"gate-review-approved": "Changes approved",
"gate-review-pending": "Review in progress",
"gate-review-rejected": "Changes requested",
+ "gate-threads-open-sub": "Resolve every thread to create the rollout",
+ "gate-threads-open_one": "{{count}} unresolved thread",
+ "gate-threads-open_other": "{{count}} unresolved threads",
+ "gate-threads-resolved": "All threads resolved",
"incomplete": "Incomplete",
"preparing-rollout": "Preparing rollout…",
"rejected": "Rejected",
@@ -1842,6 +1846,7 @@
"create-rollout-action": "Manually create rollout",
"deploy-description": "Bytebase will automatically create the rollout when all checks pass and the issue is approved.",
"deploy-description-gitops": "This plan is ready to roll out. Create a rollout to deploy the linked release.",
+ "deploy-description-v2": "Bytebase will automatically create the rollout when all checks pass, every thread is resolved, and the issue is approved.",
"hide-details": "Hide details",
"review-description": "Submit for review to proceed",
"show-details": "Show details"
@@ -1879,6 +1884,7 @@
"footer": {
"all-gates-passed": "All gates passed",
"approved-but-checks-failed": "Review approved, but plan checks failed",
+ "approved-but-threads-open": "Review approved, but threads are unresolved",
"auto-rollout-after-approval": "rollout is created automatically after approval",
"blocked-by-rejection": "Blocked by the rejected review — address the feedback above to continue",
"bypass-and-deploy": "Bypass and deploy",
@@ -1889,6 +1895,10 @@
"confirm-checks-running": "Plan checks still running",
"confirm-review-not-approved": "Review not yet approved",
"confirm-review-rejected": "Review rejected",
+ "confirm-rule-review-unknown": "SQL review status unknown",
+ "confirm-threads-unknown": "Thread status unknown",
+ "confirm-unresolved-threads_one": "{{count}} unresolved thread",
+ "confirm-unresolved-threads_other": "{{count}} unresolved threads",
"creating-rollout-automatically": "creating rollout automatically...",
"errors-passed-not-created_one": "{{count}} error, {{passed}} passed. Rollout was not created automatically.",
"errors-passed-not-created_other": "{{count}} errors, {{passed}} passed. Rollout was not created automatically.",
@@ -1902,6 +1912,8 @@
"rollout-auto-creates": "Rollout auto-creates after approval",
"rollout-blocked-by-failed-checks": "rollout won't be created automatically until checks pass",
"rollout-not-created": "Rollout was not created automatically",
+ "threads-open-not-created_one": "{{count}} unresolved thread. Rollout was not created automatically.",
+ "threads-open-not-created_other": "{{count}} unresolved threads. Rollout was not created automatically.",
"waiting-on-review": "Waiting on review"
},
"last-plan-editor-cannot-approve": "You can't approve this issue because you were the last person to change its plan. A different reviewer must approve it.",
@@ -1943,6 +1955,7 @@
"resolve": "Resolve",
"resolve-thread": "Resolve thread",
"resolved": "Resolved",
+ "rule": "Rule",
"threads-on-line_one": "{{count}} thread on this line",
"threads-on-line_other": "{{count}} threads on this line",
"walker": {
@@ -1962,6 +1975,16 @@
"description_other": "Roll back {{count}} selected tasks from rollout #{{rolloutId}}.",
"title": "Rollback rollout #{{rolloutId}}"
},
+ "rule-review": {
+ "failed": "SQL review failed",
+ "load-failed": "The SQL review status could not be loaded.",
+ "no-open-findings": "No open findings",
+ "not-run": "SQL review not run",
+ "open-findings_one": "{{count}} open finding",
+ "open-findings_other": "{{count}} open findings",
+ "queued": "SQL review queued",
+ "running": "SQL review running"
+ },
"run": "Run checks",
"select-isolation-level": "Select isolation level",
"select-targets": "Select Targets",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index fd88f88f87..06c147585f 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1812,6 +1812,10 @@
"gate-review-approved": "Cambios aprobados",
"gate-review-pending": "Revisión en curso",
"gate-review-rejected": "Cambios solicitados",
+ "gate-threads-open-sub": "Resuelve todos los hilos para crear el rollout",
+ "gate-threads-open_one": "{{count}} hilo sin resolver",
+ "gate-threads-open_other": "{{count}} hilos sin resolver",
+ "gate-threads-resolved": "Todos los hilos resueltos",
"incomplete": "Incompleto",
"preparing-rollout": "Preparando despliegue…",
"rejected": "Rechazado",
@@ -1842,6 +1846,7 @@
"create-rollout-action": "Crear rollout manualmente",
"deploy-description": "Bytebase creará automáticamente el rollout cuando todas las comprobaciones pasen y el issue esté aprobado.",
"deploy-description-gitops": "Este plan está listo para implementarse. Crea un rollout para desplegar la versión vinculada.",
+ "deploy-description-v2": "Bytebase creará automáticamente el rollout cuando todas las comprobaciones pasen, todos los hilos estén resueltos y el issue esté aprobado.",
"hide-details": "Ocultar detalles",
"review-description": "Envíe para revisión para continuar",
"show-details": "Mostrar detalles"
@@ -1879,6 +1884,7 @@
"footer": {
"all-gates-passed": "Todos los requisitos cumplidos",
"approved-but-checks-failed": "Revisión aprobada, pero las comprobaciones del plan fallaron",
+ "approved-but-threads-open": "Revisión aprobada, pero hay hilos sin resolver",
"auto-rollout-after-approval": "el despliegue se crea automáticamente tras la aprobación",
"blocked-by-rejection": "Bloqueado por la revisión rechazada — atiende los comentarios de arriba para continuar",
"bypass-and-deploy": "Omitir y desplegar",
@@ -1889,6 +1895,10 @@
"confirm-checks-running": "Comprobaciones del plan en ejecución",
"confirm-review-not-approved": "Revisión aún no aprobada",
"confirm-review-rejected": "Revisión rechazada",
+ "confirm-rule-review-unknown": "Estado de la revisión SQL desconocido",
+ "confirm-threads-unknown": "Estado de los hilos desconocido",
+ "confirm-unresolved-threads_one": "{{count}} hilo sin resolver",
+ "confirm-unresolved-threads_other": "{{count}} hilos sin resolver",
"creating-rollout-automatically": "creando el despliegue automáticamente...",
"errors-passed-not-created_one": "{{count}} error, {{passed}} superadas. El despliegue no se creó automáticamente.",
"errors-passed-not-created_other": "{{count}} errores, {{passed}} superadas. El despliegue no se creó automáticamente.",
@@ -1902,6 +1912,8 @@
"rollout-auto-creates": "El despliegue se crea automáticamente tras la aprobación",
"rollout-blocked-by-failed-checks": "el despliegue no se creará automáticamente hasta que las comprobaciones pasen",
"rollout-not-created": "El despliegue no se creó automáticamente",
+ "threads-open-not-created_one": "{{count}} hilo sin resolver. El despliegue no se creó automáticamente.",
+ "threads-open-not-created_other": "{{count}} hilos sin resolver. El despliegue no se creó automáticamente.",
"waiting-on-review": "Esperando revisión"
},
"last-plan-editor-cannot-approve": "No puedes aprobar este issue porque fuiste la última persona en modificar su plan. Otra persona debe aprobarlo.",
@@ -1943,6 +1955,7 @@
"resolve": "Resolver",
"resolve-thread": "Resolver hilo",
"resolved": "Resuelto",
+ "rule": "Regla",
"threads-on-line_one": "{{count}} hilo en esta línea",
"threads-on-line_other": "{{count}} hilos en esta línea",
"walker": {
@@ -1962,6 +1975,16 @@
"description_other": "Revertir {{count}} tareas seleccionadas del rollout #{{rolloutId}}.",
"title": "Revertir rollout #{{rolloutId}}"
},
+ "rule-review": {
+ "failed": "La revisión SQL falló",
+ "load-failed": "No se pudo cargar el estado de la revisión SQL.",
+ "no-open-findings": "No hay hallazgos abiertos",
+ "not-run": "Revisión SQL no ejecutada",
+ "open-findings_one": "{{count}} hallazgo abierto",
+ "open-findings_other": "{{count}} hallazgos abiertos",
+ "queued": "Revisión SQL en cola",
+ "running": "Revisión SQL en curso"
+ },
"run": "Volver a verificar",
"select-isolation-level": "Seleccionar nivel de aislamiento",
"select-targets": "Seleccionar destinos",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 9ca0c9e765..3dc8dde404 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1812,6 +1812,10 @@
"gate-review-approved": "変更が承認されました",
"gate-review-pending": "レビュー中",
"gate-review-rejected": "変更がリクエストされました",
+ "gate-threads-open-sub": "すべてのスレッドを解決するとロールアウトが作成されます",
+ "gate-threads-open_one": "未解決のスレッド {{count}} 件",
+ "gate-threads-open_other": "未解決のスレッド {{count}} 件",
+ "gate-threads-resolved": "すべてのスレッドが解決済み",
"incomplete": "未完了",
"preparing-rollout": "ロールアウトを準備中…",
"rejected": "却下されました",
@@ -1842,6 +1846,7 @@
"create-rollout-action": "手動でロールアウトを作成",
"deploy-description": "すべてのチェックが通過し、Issue が承認されると、Bytebase は自動的にロールアウトを作成します。",
"deploy-description-gitops": "このプランはロールアウトの準備ができています。リンクされたリリースをデプロイするにはロールアウトを作成してください。",
+ "deploy-description-v2": "すべてのチェックが通過し、すべてのスレッドが解決され、Issue が承認されると、Bytebase は自動的にロールアウトを作成します。",
"hide-details": "詳細を隠す",
"review-description": "続行するにはレビューに提出してください",
"show-details": "詳細を表示"
@@ -1879,6 +1884,7 @@
"footer": {
"all-gates-passed": "すべての条件を満たしました",
"approved-but-checks-failed": "レビューは承認されましたが、プランチェックに失敗しました",
+ "approved-but-threads-open": "レビューは承認されましたが、未解決のスレッドがあります",
"auto-rollout-after-approval": "承認後にロールアウトが自動作成されます",
"blocked-by-rejection": "却下されたレビューによりブロックされています — 続行するには上記のフィードバックに対応してください",
"bypass-and-deploy": "バイパスしてデプロイ",
@@ -1889,6 +1895,10 @@
"confirm-checks-running": "プランチェック実行中",
"confirm-review-not-approved": "レビュー未承認",
"confirm-review-rejected": "レビュー却下",
+ "confirm-rule-review-unknown": "SQL レビューの状態が不明",
+ "confirm-threads-unknown": "スレッドの状態が不明",
+ "confirm-unresolved-threads_one": "未解決のスレッド {{count}} 件",
+ "confirm-unresolved-threads_other": "未解決のスレッド {{count}} 件",
"creating-rollout-automatically": "ロールアウトを自動作成中...",
"errors-passed-not-created_one": "{{count}} 件のエラー、{{passed}} 件合格。ロールアウトは自動作成されませんでした。",
"errors-passed-not-created_other": "{{count}} 件のエラー、{{passed}} 件合格。ロールアウトは自動作成されませんでした。",
@@ -1902,6 +1912,8 @@
"rollout-auto-creates": "承認後にロールアウトが自動作成されます",
"rollout-blocked-by-failed-checks": "チェックが通過するまでロールアウトは自動作成されません",
"rollout-not-created": "ロールアウトは自動作成されませんでした",
+ "threads-open-not-created_one": "未解決のスレッド {{count}} 件。ロールアウトは自動作成されませんでした。",
+ "threads-open-not-created_other": "未解決のスレッド {{count}} 件。ロールアウトは自動作成されませんでした。",
"waiting-on-review": "レビュー待ち"
},
"last-plan-editor-cannot-approve": "この Issue を承認できません。最後にプランを変更したユーザーであるためです。別のレビュー担当者による承認が必要です。",
@@ -1943,6 +1955,7 @@
"resolve": "解決",
"resolve-thread": "スレッドを解決",
"resolved": "解決済み",
+ "rule": "ルール",
"threads-on-line_one": "この行に {{count}} 件のスレッド",
"threads-on-line_other": "この行に {{count}} 件のスレッド",
"walker": {
@@ -1962,6 +1975,16 @@
"description_other": "ロールアウト #{{rolloutId}} の選択したタスク {{count}} 件をロールバックします。",
"title": "ロールアウト #{{rolloutId}} のロールバック"
},
+ "rule-review": {
+ "failed": "SQL レビューに失敗しました",
+ "load-failed": "SQL レビューの状態を読み込めませんでした。",
+ "no-open-findings": "未解決の指摘はありません",
+ "not-run": "SQL レビュー未実行",
+ "open-findings_one": "未解決の指摘 {{count}} 件",
+ "open-findings_other": "未解決の指摘 {{count}} 件",
+ "queued": "SQL レビュー待機中",
+ "running": "SQL レビュー実行中"
+ },
"run": "再チェック",
"select-isolation-level": "分離レベルを選択",
"select-targets": "対象を選択",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index d00877a43d..22c33915c7 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1812,6 +1812,10 @@
"gate-review-approved": "Đã duyệt thay đổi",
"gate-review-pending": "Đang xem xét",
"gate-review-rejected": "Yêu cầu thay đổi",
+ "gate-threads-open-sub": "Giải quyết mọi luồng để tạo rollout",
+ "gate-threads-open_one": "{{count}} luồng chưa giải quyết",
+ "gate-threads-open_other": "{{count}} luồng chưa giải quyết",
+ "gate-threads-resolved": "Tất cả luồng đã được giải quyết",
"incomplete": "Chưa hoàn tất",
"preparing-rollout": "Đang chuẩn bị triển khai…",
"rejected": "Đã từ chối",
@@ -1842,6 +1846,7 @@
"create-rollout-action": "Tạo rollout thủ công",
"deploy-description": "Bytebase sẽ tự động tạo rollout khi tất cả kiểm tra đều đạt và issue đã được phê duyệt.",
"deploy-description-gitops": "Kế hoạch này đã sẵn sàng để triển khai. Tạo một rollout để triển khai bản phát hành được liên kết.",
+ "deploy-description-v2": "Bytebase sẽ tự động tạo rollout khi tất cả kiểm tra đều đạt, mọi luồng đã được giải quyết và issue đã được phê duyệt.",
"hide-details": "Ẩn chi tiết",
"review-description": "Gửi để xem xét để tiếp tục",
"show-details": "Hiển thị chi tiết"
@@ -1879,6 +1884,7 @@
"footer": {
"all-gates-passed": "Đã đạt mọi điều kiện",
"approved-but-checks-failed": "Xét duyệt đã được phê duyệt, nhưng kiểm tra kế hoạch thất bại",
+ "approved-but-threads-open": "Xét duyệt đã được phê duyệt, nhưng còn luồng chưa giải quyết",
"auto-rollout-after-approval": "bản triển khai được tạo tự động sau khi phê duyệt",
"blocked-by-rejection": "Bị chặn bởi xét duyệt đã từ chối — hãy xử lý phản hồi ở trên để tiếp tục",
"bypass-and-deploy": "Bỏ qua và triển khai",
@@ -1889,6 +1895,10 @@
"confirm-checks-running": "Kiểm tra kế hoạch đang chạy",
"confirm-review-not-approved": "Đánh giá chưa được phê duyệt",
"confirm-review-rejected": "Đánh giá bị từ chối",
+ "confirm-rule-review-unknown": "Không rõ trạng thái đánh giá SQL",
+ "confirm-threads-unknown": "Không rõ trạng thái luồng",
+ "confirm-unresolved-threads_one": "{{count}} luồng chưa giải quyết",
+ "confirm-unresolved-threads_other": "{{count}} luồng chưa giải quyết",
"creating-rollout-automatically": "đang tự động tạo bản triển khai...",
"errors-passed-not-created_one": "{{count}} lỗi, {{passed}} đạt. Bản triển khai không được tạo tự động.",
"errors-passed-not-created_other": "{{count}} lỗi, {{passed}} đạt. Bản triển khai không được tạo tự động.",
@@ -1902,6 +1912,8 @@
"rollout-auto-creates": "Bản triển khai tự động tạo sau khi phê duyệt",
"rollout-blocked-by-failed-checks": "bản triển khai sẽ không được tạo tự động cho đến khi các kiểm tra đạt",
"rollout-not-created": "Bản triển khai chưa được tạo tự động",
+ "threads-open-not-created_one": "{{count}} luồng chưa giải quyết. Bản triển khai không được tạo tự động.",
+ "threads-open-not-created_other": "{{count}} luồng chưa giải quyết. Bản triển khai không được tạo tự động.",
"waiting-on-review": "Đang chờ xét duyệt"
},
"last-plan-editor-cannot-approve": "Bạn không thể phê duyệt issue này vì bạn là người thay đổi kế hoạch gần đây nhất. Một người xét duyệt khác phải phê duyệt issue này.",
@@ -1943,6 +1955,7 @@
"resolve": "Giải quyết",
"resolve-thread": "Giải quyết luồng",
"resolved": "Đã giải quyết",
+ "rule": "Quy tắc",
"threads-on-line_one": "{{count}} chủ đề trên dòng này",
"threads-on-line_other": "{{count}} chủ đề trên dòng này",
"walker": {
@@ -1962,6 +1975,16 @@
"description_other": "Hoàn tác {{count}} tác vụ đã chọn từ bản triển khai #{{rolloutId}}.",
"title": "Hoàn tác bản triển khai #{{rolloutId}}"
},
+ "rule-review": {
+ "failed": "Đánh giá SQL thất bại",
+ "load-failed": "Không thể tải trạng thái đánh giá SQL.",
+ "no-open-findings": "Không có phát hiện chưa giải quyết",
+ "not-run": "Chưa chạy đánh giá SQL",
+ "open-findings_one": "{{count}} phát hiện chưa giải quyết",
+ "open-findings_other": "{{count}} phát hiện chưa giải quyết",
+ "queued": "Đánh giá SQL đang chờ",
+ "running": "Đang đánh giá SQL"
+ },
"run": "Kiểm tra lại",
"select-isolation-level": "Chọn mức độ cô lập",
"select-targets": "Chọn mục tiêu",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 8715cbbfac..53c69c95ea 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1812,6 +1812,10 @@
"gate-review-approved": "变更已批准",
"gate-review-pending": "审批中",
"gate-review-rejected": "请求变更",
+ "gate-threads-open-sub": "解决所有讨论后才会创建发布",
+ "gate-threads-open_one": "{{count}} 个未解决的讨论",
+ "gate-threads-open_other": "{{count}} 个未解决的讨论",
+ "gate-threads-resolved": "所有讨论已解决",
"incomplete": "不完整",
"preparing-rollout": "正在准备发布…",
"rejected": "已拒绝",
@@ -1842,6 +1846,7 @@
"create-rollout-action": "手动创建发布",
"deploy-description": "当所有检查都通过且工单审批完成后,Bytebase 会自动创建发布。",
"deploy-description-gitops": "此计划已就绪,可以发布。创建一个发布以部署关联的 Release。",
+ "deploy-description-v2": "当所有检查都通过、所有讨论都已解决且工单审批完成后,Bytebase 会自动创建发布。",
"hide-details": "隐藏详情",
"review-description": "提交审批以继续",
"show-details": "显示详情"
@@ -1879,6 +1884,7 @@
"footer": {
"all-gates-passed": "所有条件已满足",
"approved-but-checks-failed": "审批已通过,但变更检查失败",
+ "approved-but-threads-open": "审批已通过,但还有未解决的讨论",
"auto-rollout-after-approval": "审批通过后将自动创建发布",
"blocked-by-rejection": "已被拒绝的审批阻塞 — 请先处理上方反馈",
"bypass-and-deploy": "跳过并发布",
@@ -1889,6 +1895,10 @@
"confirm-checks-running": "检查仍在运行",
"confirm-review-not-approved": "审批尚未通过",
"confirm-review-rejected": "审批已被拒绝",
+ "confirm-rule-review-unknown": "SQL 审核状态未知",
+ "confirm-threads-unknown": "讨论状态未知",
+ "confirm-unresolved-threads_one": "{{count}} 个未解决的讨论",
+ "confirm-unresolved-threads_other": "{{count}} 个未解决的讨论",
"creating-rollout-automatically": "正在自动创建发布...",
"errors-passed-not-created_one": "{{count}} 项错误,{{passed}} 项通过。未自动创建发布。",
"errors-passed-not-created_other": "{{count}} 项错误,{{passed}} 项通过。未自动创建发布。",
@@ -1902,6 +1912,8 @@
"rollout-auto-creates": "审批通过后自动创建发布",
"rollout-blocked-by-failed-checks": "在检查通过前不会自动创建发布",
"rollout-not-created": "发布未自动创建",
+ "threads-open-not-created_one": "{{count}} 个未解决的讨论。未自动创建发布。",
+ "threads-open-not-created_other": "{{count}} 个未解决的讨论。未自动创建发布。",
"waiting-on-review": "等待审批"
},
"last-plan-editor-cannot-approve": "由于您最后修改了该计划,因此无法审批此工单。请由其他审批人进行审批。",
@@ -1943,6 +1955,7 @@
"resolve": "解决",
"resolve-thread": "解决线程",
"resolved": "已解决",
+ "rule": "规则",
"threads-on-line_one": "此行有 {{count}} 个讨论",
"threads-on-line_other": "此行有 {{count}} 个讨论",
"walker": {
@@ -1962,6 +1975,16 @@
"description_other": "回滚发布 #{{rolloutId}} 中选中的 {{count}} 个任务。",
"title": "回滚发布 #{{rolloutId}}"
},
+ "rule-review": {
+ "failed": "SQL 审核失败",
+ "load-failed": "无法加载 SQL 审核状态。",
+ "no-open-findings": "没有未解决的问题",
+ "not-run": "SQL 审核未运行",
+ "open-findings_one": "{{count}} 个未解决的问题",
+ "open-findings_other": "{{count}} 个未解决的问题",
+ "queued": "SQL 审核排队中",
+ "running": "SQL 审核运行中"
+ },
"run": "重新检查",
"select-isolation-level": "选择隔离级别",
"select-targets": "选择目标",
diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.test.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.test.tsx
index daf928868f..d4863e4803 100644
--- a/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.test.tsx
+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.test.tsx
@@ -9,6 +9,7 @@ import {
IssueSchema,
ReviewRun_Type,
} from "@/types/proto-es/v1/issue_service_pb";
+import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
const ISSUE = "projects/p/issues/1";
@@ -156,6 +157,23 @@ describe("IssueDetailCommentList", () => {
);
});
+ test("names the standard rule of a RULE result", () => {
+ const rule = comment("rule", true);
+ if (rule.reviewMetadata) {
+ rule.reviewMetadata.runType = ReviewRun_Type.RULE;
+ rule.reviewMetadata.ruleType = ReviewRuleType.REQUIRE_WHERE;
+ }
+ mocks.comments = [rule];
+ render(<IssueDetailCommentList />);
+
+ expect(screen.getByTestId("row-header").textContent).toContain(
+ "sql-review.standard-rules.self"
+ );
+ expect(screen.getByTestId("review-rule").textContent).toContain(
+ "sql-review.standard-rules.rule.require-where.title"
+ );
+ });
+
test("renders a member's comment with its images, as before", () => {
mocks.comments = [comment("member")];
const { container } = render(<IssueDetailCommentList />);
diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx
index d8e92f7136..0a1606a56f 100644
--- a/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx
+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx
@@ -35,6 +35,7 @@ import {
type IssueComment,
type IssueComment_ReviewMetadata,
IssueSchema,
+ ReviewRun_Type,
UpdateIssueRequestSchema,
} from "@/types/proto-es/v1/issue_service_pb";
import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
@@ -44,6 +45,7 @@ import { PlanSpecChangeReference } from "../../plan-detail/components/PlanChange
import {
ReviewerIcon,
ReviewPriorityBadge,
+ ReviewRule,
ReviewTargets,
reviewerName,
} from "../../plan-detail/components/threads/ReviewResult";
@@ -589,6 +591,9 @@ function ReviewResultActivityRow({
<div className="flex flex-col gap-y-2">
<ReviewTargets spec={spec} targets={review.targets} />
{body}
+ {review.runType === ReviewRun_Type.RULE && (
+ <ReviewRule ruleType={review.ruleType} />
+ )}
</div>
}
header={
diff --git a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx
index 194f9d5a0f..8803e31534 100644
--- a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx
+++ b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx
@@ -16,6 +16,7 @@ import { cn } from "@/lib/utils";
import { IssueStatus } from "@/types/proto-es/v1/common_pb";
import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
import { getRolloutStatus } from "@/utils";
+import { sqlReviewV2Enabled } from "@/utils/featureGates";
import { getReviewBadge } from "../utils/reviewBadge";
import { DeployBranch } from "./components/deploy/DeployBranch";
import { PlanDetailChangesBranch } from "./components/PlanDetailChangesBranch";
@@ -26,6 +27,7 @@ import { PlanReviewSection } from "./components/review/PlanReviewSection";
import { useUnresolvedThreadTotal } from "./components/threads/useUnresolvedThreadCounts";
import { useIssueCommentThreadsSync } from "./hooks/useIssueCommentThreadsSync";
import { usePlacementSync } from "./hooks/usePlacementSync";
+import { SqlReviewV2Provider } from "./hooks/useSqlReviewV2";
import { PlanDetailStoreProvider } from "./shared/stores/PlanDetailStoreProvider";
import { planPhaseAnchorId } from "./shell/focusPhase";
import { usePlanDetailPage } from "./shell/hooks/usePlanDetailPage";
@@ -261,144 +263,152 @@ function ProjectPlanDetailPageInner({
return (
<PlanDetailProvider value={page}>
- <div
- ref={setPageHost}
- data-testid="plan-detail-page"
- className="relative min-h-full overflow-x-clip bg-control-bg/50"
- >
+ <SqlReviewV2Provider>
<div
- className={cn(
- "flex min-h-full flex-col",
- page.ready ? "" : "invisible pointer-events-none"
- )}
+ ref={setPageHost}
+ data-testid="plan-detail-page"
+ className="relative min-h-full overflow-x-clip bg-control-bg/50"
>
- {/* Only the title/action row is sticky (GitHub issue-header pattern);
+ <div
+ className={cn(
+ "flex min-h-full flex-col",
+ page.ready ? "" : "invisible pointer-events-none"
+ )}
+ >
+ {/* Only the title/action row is sticky (GitHub issue-header pattern);
the description + metadata below scroll away beneath it. The
dashboard main pane is the scroll container, so top-0 pins to it;
z-20 keeps it above the phase rail nodes (z-10). The border appears
only when stuck, so the row is flat at the top. */}
- <header
- className={cn(
- "sticky top-0 z-20 shrink-0 bg-background",
- headerStuck && "border-b"
- )}
- >
- <PlanDetailHeader />
- </header>
- <PlanDetailHeaderDetails />
+ <header
+ className={cn(
+ "sticky top-0 z-20 shrink-0 bg-background",
+ headerStuck && "border-b"
+ )}
+ >
+ <PlanDetailHeader />
+ </header>
+ <PlanDetailHeaderDetails />
- <main className="min-h-[calc(100vh-4rem)] min-w-0 flex-1">
- {/* No row gap here: each PhaseSection's pb-6 carries the spacing,
+ <main className="min-h-[calc(100vh-4rem)] min-w-0 flex-1">
+ {/* No row gap here: each PhaseSection's pb-6 carries the spacing,
which the connector line fills so it stays continuous. */}
- <div className="flex min-w-0 flex-col pb-6 pl-2 pr-4 pt-4 xl:pr-8 2xl:pr-12">
- <PhaseSection
- anchorId={planPhaseAnchorId("changes")}
- badge={phaseConfigs.changes.badge}
- expanded={page.activePhases.has("changes")}
- icon={<Code2 className="size-3 md:size-4" />}
- lineClass={phaseConfigs.changes.lineClass}
- label={t("plan.navigator.changes")}
- onSelect={() => selectPhase("changes")}
- status={phaseConfigs.changes.status}
- onToggle={() => page.togglePhase("changes")}
- summary={buildChangesSummary(page.plan, t)}
- >
- <PlanDetailChangesBranch
- onSelectedSpecIdChange={setSelectedSpecId}
- selectedSpecId={effectiveSelectedSpecId}
- />
- </PhaseSection>
+ <div className="flex min-w-0 flex-col pb-6 pl-2 pr-4 pt-4 xl:pr-8 2xl:pr-12">
+ <PhaseSection
+ anchorId={planPhaseAnchorId("changes")}
+ badge={phaseConfigs.changes.badge}
+ expanded={page.activePhases.has("changes")}
+ icon={<Code2 className="size-3 md:size-4" />}
+ lineClass={phaseConfigs.changes.lineClass}
+ label={t("plan.navigator.changes")}
+ onSelect={() => selectPhase("changes")}
+ status={phaseConfigs.changes.status}
+ onToggle={() => page.togglePhase("changes")}
+ summary={buildChangesSummary(page.plan, t)}
+ >
+ <PlanDetailChangesBranch
+ onSelectedSpecIdChange={setSelectedSpecId}
+ selectedSpecId={effectiveSelectedSpecId}
+ />
+ </PhaseSection>
+
+ {reviewVisible && (
+ <PhaseSection
+ anchorId={planPhaseAnchorId("review")}
+ badge={phaseConfigs.review.badge}
+ expanded={page.activePhases.has("review")}
+ icon={<MessageSquareMore className="size-3 md:size-4" />}
+ lineClass={phaseConfigs.review.lineClass}
+ label={t("plan.navigator.review")}
+ onSelect={() => selectPhase("review")}
+ status={phaseConfigs.review.status}
+ onToggle={() => page.togglePhase("review")}
+ summary={buildReviewSummary(
+ page.issue,
+ t,
+ unresolvedThreads
+ )}
+ future={
+ <p className="mt-0.5 text-sm text-control-placeholder">
+ {t("plan.phase.review-description")}
+ </p>
+ }
+ >
+ <PlanReviewSection />
+ </PhaseSection>
+ )}
- {reviewVisible && (
<PhaseSection
- anchorId={planPhaseAnchorId("review")}
- badge={phaseConfigs.review.badge}
- expanded={page.activePhases.has("review")}
- icon={<MessageSquareMore className="size-3 md:size-4" />}
- lineClass={phaseConfigs.review.lineClass}
- label={t("plan.navigator.review")}
- onSelect={() => selectPhase("review")}
- status={phaseConfigs.review.status}
- onToggle={() => page.togglePhase("review")}
- summary={buildReviewSummary(page.issue, t, unresolvedThreads)}
+ anchorId={planPhaseAnchorId("deploy")}
+ badge={phaseConfigs.deploy.badge}
+ expanded={page.activePhases.has("deploy")}
+ icon={<Rocket className="size-3 md:size-4" />}
+ isLast
+ label={t("plan.navigator.deploy")}
+ status={phaseConfigs.deploy.status}
+ onSelect={() => selectPhase("deploy")}
+ onToggle={() => page.togglePhase("deploy")}
+ summary={buildDeploySummary(
+ page.issue?.draft ? undefined : page.rollout,
+ t
+ )}
future={
- <p className="mt-0.5 text-sm text-control-placeholder">
- {t("plan.phase.review-description")}
- </p>
+ page.issue?.draft ? (
+ <p className="mt-0.5 text-sm text-control-placeholder">
+ {sqlReviewV2Enabled()
+ ? t("plan.phase.deploy-description-v2")
+ : t("plan.phase.deploy-description")}
+ </p>
+ ) : (
+ <PlanDetailDeployFuture />
+ )
}
>
- <PlanReviewSection />
+ <DeployBranch />
</PhaseSection>
- )}
-
- <PhaseSection
- anchorId={planPhaseAnchorId("deploy")}
- badge={phaseConfigs.deploy.badge}
- expanded={page.activePhases.has("deploy")}
- icon={<Rocket className="size-3 md:size-4" />}
- isLast
- label={t("plan.navigator.deploy")}
- status={phaseConfigs.deploy.status}
- onSelect={() => selectPhase("deploy")}
- onToggle={() => page.togglePhase("deploy")}
- summary={buildDeploySummary(
- page.issue?.draft ? undefined : page.rollout,
- t
- )}
- future={
- page.issue?.draft ? (
- <p className="mt-0.5 text-sm text-control-placeholder">
- {t("plan.phase.deploy-description")}
- </p>
- ) : (
- <PlanDetailDeployFuture />
- )
- }
- >
- <DeployBranch />
- </PhaseSection>
- </div>
- </main>
- </div>
+ </div>
+ </main>
+ </div>
- {!page.ready && (
- <div className="absolute inset-0 flex flex-col items-center justify-center gap-y-3 bg-background">
- <Loader2 className="h-8 w-8 animate-spin text-accent" />
- <div className="text-sm text-control-light">
- {t("common.loading")}
+ {!page.ready && (
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-y-3 bg-background">
+ <Loader2 className="h-8 w-8 animate-spin text-accent" />
+ <div className="text-sm text-control-light">
+ {t("common.loading")}
+ </div>
</div>
- </div>
- )}
+ )}
- <AlertDialog
- open={page.pendingLeaveConfirm}
- onOpenChange={(open) => {
- if (!open) {
- page.resolveLeaveConfirm(false);
- }
- }}
- >
- <AlertDialogContent>
- <AlertDialogTitle>
- {t("common.leave-without-saving")}
- </AlertDialogTitle>
- <AlertDialogFooter>
- <Button
- appearance="outline"
- onClick={() => page.resolveLeaveConfirm(false)}
- >
- {t("common.cancel")}
- </Button>
- <Button
- variant="destructive"
- onClick={() => page.resolveLeaveConfirm(true)}
- >
- {t("common.discard-changes")}
- </Button>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
+ <AlertDialog
+ open={page.pendingLeaveConfirm}
+ onOpenChange={(open) => {
+ if (!open) {
+ page.resolveLeaveConfirm(false);
+ }
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogTitle>
+ {t("common.leave-without-saving")}
+ </AlertDialogTitle>
+ <AlertDialogFooter>
+ <Button
+ appearance="outline"
+ onClick={() => page.resolveLeaveConfirm(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={() => page.resolveLeaveConfirm(true)}
+ >
+ {t("common.discard-changes")}
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ </SqlReviewV2Provider>
</PlanDetailProvider>
);
}
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.test.tsx
new file mode 100644
index 0000000000..9f0274d733
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.test.tsx
@@ -0,0 +1,93 @@
+import { act, render } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { beforeEach, expect, test, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ page: {} as Record<string, unknown>,
+ reload: vi.fn(),
+ runChecks: vi.fn(),
+ section: {} as { onRun?: () => Promise<void>; trailingSummary?: ReactNode },
+ sqlReview: undefined as unknown,
+}));
+
+vi.mock("@/components/plan-check/PlanCheckSection", () => ({
+ PlanCheckSection: (props: {
+ onRun: () => Promise<void>;
+ trailingSummary?: ReactNode;
+ }) => {
+ mocks.section = props;
+ return <div>{props.trailingSummary}</div>;
+ },
+}));
+
+vi.mock("@/lib/plan/check", () => ({
+ getPlanCheckSummaryWithFallback: () => ({ total: 1 }),
+}));
+
+vi.mock("../hooks/usePlanCheckActions", () => ({
+ usePlanCheckActions: () => ({
+ allowRunChecks: true,
+ isRunningChecks: false,
+ refreshChecks: vi.fn(),
+ runChecks: mocks.runChecks,
+ }),
+}));
+
+vi.mock("../hooks/useSqlReviewV2", () => ({
+ useSqlReviewV2: () => mocks.sqlReview,
+}));
+
+vi.mock("../shell/PlanDetailContext", () => ({
+ usePlanDetailContext: () => mocks.page,
+}));
+
+vi.mock("./PlanDetailRuleReviewSummary", () => ({
+ PlanDetailRuleReviewSummary: () => <span>rule review summary</span>,
+}));
+
+vi.mock("./PlanTargetDisplay", () => ({ PlanTargetDisplay: () => null }));
+
+import { PlanDetailAggregateChecks } from "./PlanDetailAggregateChecks";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.page = { plan: { name: "projects/foo/plans/7" }, planCheckRuns: [] };
+ mocks.runChecks.mockResolvedValue(undefined);
+ mocks.reload.mockResolvedValue(undefined);
+ mocks.sqlReview = {
+ unresolvedThreads: 0,
+ ruleReview: {
+ loadFailed: false,
+ openFindings: 0,
+ reload: mocks.reload,
+ run: null,
+ stale: false,
+ },
+ };
+});
+
+test("joins the rule review to the checks under SQL Review V2", async () => {
+ const { getByText } = render(<PlanDetailAggregateChecks />);
+ expect(getByText("rule review summary")).toBeInTheDocument();
+
+ await act(async () => {
+ await mocks.section.onRun?.();
+ });
+ expect(mocks.runChecks).toHaveBeenCalledTimes(1);
+ expect(mocks.reload).toHaveBeenCalledTimes(1);
+});
+
+test.each([
+ ["SQL Review V2 is off", undefined],
+ ["the review cannot be read", { unresolvedThreads: 0 }],
+])("leaves the rule review out when %s", async (_, sqlReview) => {
+ mocks.sqlReview = sqlReview;
+ const { queryByText } = render(<PlanDetailAggregateChecks />);
+ expect(queryByText("rule review summary")).not.toBeInTheDocument();
+
+ await act(async () => {
+ await mocks.section.onRun?.();
+ });
+ expect(mocks.runChecks).toHaveBeenCalledTimes(1);
+ expect(mocks.reload).not.toHaveBeenCalled();
+});
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.tsx
index bd60f91cda..162b3bde51 100644
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.tsx
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.tsx
@@ -2,7 +2,9 @@ import { useMemo } from "react";
import { PlanCheckSection } from "@/components/plan-check/PlanCheckSection";
import { getPlanCheckSummaryWithFallback } from "@/lib/plan/check";
import { usePlanCheckActions } from "../hooks/usePlanCheckActions";
+import { useSqlReviewV2 } from "../hooks/useSqlReviewV2";
import { usePlanDetailContext } from "../shell/PlanDetailContext";
+import { PlanDetailRuleReviewSummary } from "./PlanDetailRuleReviewSummary";
import { PlanTargetDisplay } from "./PlanTargetDisplay";
// Plan-wide checks rendered as a verdict-line footer at the bottom of the
@@ -10,11 +12,13 @@ import { PlanTargetDisplay } from "./PlanTargetDisplay";
// every spec without clicking into each tab. Drill-down details still live
// in the PlanCheckSection drawer. Create mode renders nothing here — there
// is no plan yet to aggregate against; per-spec PlanDetailDraftChecks
-// covers that case.
+// covers that case. Under SQL Review V2 the standard rule review replaces the
+// checks' SQL review, so its status joins the verdict line.
export function PlanDetailAggregateChecks() {
const page = usePlanDetailContext();
const { allowRunChecks, isRunningChecks, refreshChecks, runChecks } =
usePlanCheckActions();
+ const ruleReview = useSqlReviewV2()?.ruleReview;
const summary = useMemo(
() =>
getPlanCheckSummaryWithFallback(
@@ -28,6 +32,12 @@ export function PlanDetailAggregateChecks() {
return null;
}
+ // Running the checks also starts the rule review on the server.
+ const runAllChecks = async () => {
+ await runChecks();
+ await ruleReview?.reload();
+ };
+
return (
<div className="border-t px-4 py-4">
<PlanCheckSection
@@ -35,12 +45,15 @@ export function PlanDetailAggregateChecks() {
includeRunFailure
isRunning={isRunningChecks}
onRefreshOnOpen={refreshChecks}
- onRun={runChecks}
+ onRun={runAllChecks}
planCheckRuns={page.planCheckRuns}
renderTarget={(target) => (
<PlanTargetDisplay showEnvironment target={target} />
)}
summaryOverride={summary}
+ trailingSummary={
+ ruleReview && <PlanDetailRuleReviewSummary state={ruleReview} />
+ }
/>
</div>
);
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailDeployFuture.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailDeployFuture.tsx
index aa50fc2452..9e13c105cc 100644
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailDeployFuture.tsx
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailDeployFuture.tsx
@@ -8,12 +8,14 @@ import { Button } from "@/components/ui/button";
import { pushNotification } from "@/stores";
import { State } from "@/types/proto-es/v1/common_pb";
import { CreateRolloutRequestSchema } from "@/types/proto-es/v1/rollout_service_pb";
+import { useSqlReviewV2 } from "../hooks/useSqlReviewV2";
import { usePlanDetailContext } from "../shell/PlanDetailContext";
import { isReleaseBackedPlan } from "../utils/spec";
export function PlanDetailDeployFuture() {
const { t } = useTranslation();
const page = usePlanDetailContext();
+ const sqlReview = useSqlReviewV2();
const [creatingRollout, setCreatingRollout] = useState(false);
const isGitOpsPlan = useMemo(
@@ -60,7 +62,9 @@ export function PlanDetailDeployFuture() {
<p className="text-sm text-control-placeholder">
{isGitOpsPlan
? t("plan.phase.deploy-description-gitops")
- : t("plan.phase.deploy-description")}
+ : sqlReview
+ ? t("plan.phase.deploy-description-v2")
+ : t("plan.phase.deploy-description")}
</p>
{canCreateRollout && (
<div className="mt-3">
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailRuleReviewSummary.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailRuleReviewSummary.test.tsx
new file mode 100644
index 0000000000..1e695adcc8
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailRuleReviewSummary.test.tsx
@@ -0,0 +1,105 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { expect, test, vi } from "vitest";
+import {
+ type ReviewRun,
+ ReviewRun_Status,
+ ReviewRun_Type,
+} from "@/types/proto-es/v1/issue_service_pb";
+import type { RuleReviewRunState } from "../hooks/useRuleReviewRun";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { count?: number }) =>
+ options?.count === undefined ? key : `${key}:${options.count}`,
+ }),
+}));
+
+vi.mock("@/components/HumanizeTs", async () => ({
+ ...(await import("@/test-utils/humanizeTs")).humanizeTsStub(),
+}));
+
+import { PlanDetailRuleReviewSummary } from "./PlanDetailRuleReviewSummary";
+
+const reviewRun = (status: ReviewRun_Status, extra = {}) =>
+ ({
+ name: "projects/foo/issues/7/reviewRuns/rule",
+ type: ReviewRun_Type.RULE,
+ status,
+ error: "",
+ ...extra,
+ }) as ReviewRun;
+
+const renderSummary = (state: Partial<RuleReviewRunState>) =>
+ render(
+ <PlanDetailRuleReviewSummary
+ state={{
+ loadFailed: false,
+ openFindings: 0,
+ reload: vi.fn(),
+ run: undefined,
+ stale: false,
+ ...state,
+ }}
+ />
+ );
+
+test("renders nothing while loading", () => {
+ const { container } = renderSummary({});
+ expect(container).toBeEmptyDOMElement();
+});
+
+test("says the review never ran", () => {
+ renderSummary({ run: null });
+ expect(screen.getByText("plan.rule-review.not-run")).toBeVisible();
+});
+
+test("says the review never ran on the plan's current SQL", () => {
+ renderSummary({
+ run: reviewRun(ReviewRun_Status.DONE, { outdated: true }),
+ });
+ expect(screen.getByText("plan.rule-review.not-run")).toBeVisible();
+});
+
+test.each([
+ [ReviewRun_Status.AVAILABLE, "plan.rule-review.queued"],
+ [ReviewRun_Status.RUNNING, "plan.rule-review.running"],
+])("shows a run in progress", (status, label) => {
+ renderSummary({ run: reviewRun(status) });
+ expect(screen.getByText(label)).toBeVisible();
+});
+
+test("counts the open findings of a completed run", () => {
+ renderSummary({
+ openFindings: 3,
+ run: reviewRun(ReviewRun_Status.DONE, {
+ endTime: { seconds: 5n, nanos: 0 },
+ }),
+ });
+ expect(screen.getByText("plan.rule-review.open-findings:3")).toBeVisible();
+ expect(screen.getByTestId("humanize-ts")).toHaveTextContent("5000");
+});
+
+test("says a completed run found nothing", () => {
+ renderSummary({ run: reviewRun(ReviewRun_Status.DONE) });
+ expect(screen.getByText("plan.rule-review.no-open-findings")).toBeVisible();
+});
+
+test("shows why a run failed", () => {
+ renderSummary({
+ run: reviewRun(ReviewRun_Status.FAILED, {
+ error: "1 of 1 review units failed",
+ }),
+ });
+ expect(screen.getByText("plan.rule-review.failed")).toBeVisible();
+ expect(screen.getByText("1 of 1 review units failed")).toBeVisible();
+});
+
+test("offers a retry when the status could not be read", () => {
+ const reload = vi.fn();
+ renderSummary({ loadFailed: true, reload });
+ expect(screen.getByText("plan.rule-review.load-failed")).toBeVisible();
+ fireEvent.click(
+ screen.getByRole("button", { name: "sql-review.standard-rules.retry" })
+ );
+ expect(reload).toHaveBeenCalledTimes(1);
+});
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailRuleReviewSummary.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailRuleReviewSummary.tsx
new file mode 100644
index 0000000000..1b9ad576cd
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailRuleReviewSummary.tsx
@@ -0,0 +1,82 @@
+import { AlertCircle, CheckCircle, Loader2, XCircle } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { HumanizeTs } from "@/components/HumanizeTs";
+import { Button } from "@/components/ui/button";
+import { ReviewRun_Status } from "@/types/proto-es/v1/issue_service_pb";
+import { getTimeForPbTimestampProtoEs } from "@/types/timestamp";
+import type { RuleReviewRunState } from "../hooks/useRuleReviewRun";
+
+// The standard rule review's part of the Checks summary line.
+export function PlanDetailRuleReviewSummary({
+ state,
+}: {
+ state: RuleReviewRunState;
+}) {
+ const { t } = useTranslation();
+ const { loadFailed, openFindings, run } = state;
+ if (loadFailed) {
+ return (
+ <span className="flex items-center gap-1 text-sm">
+ <span className="text-error">{t("plan.rule-review.load-failed")}</span>
+ <Button appearance="link" onClick={() => void state.reload()} size="xs">
+ {t("sql-review.standard-rules.retry")}
+ </Button>
+ </span>
+ );
+ }
+ if (run === undefined) return null;
+ // An outdated run reviewed earlier SQL: the plan's current SQL has not run.
+ if (run === null || run.outdated) {
+ return (
+ <span className="text-sm text-control-placeholder">
+ {t("plan.rule-review.not-run")}
+ </span>
+ );
+ }
+ switch (run.status) {
+ case ReviewRun_Status.AVAILABLE:
+ case ReviewRun_Status.RUNNING:
+ return (
+ <span className="flex items-center gap-1 text-sm text-control">
+ <Loader2 className="size-4 animate-spin" />
+ {run.status === ReviewRun_Status.AVAILABLE
+ ? t("plan.rule-review.queued")
+ : t("plan.rule-review.running")}
+ </span>
+ );
+ case ReviewRun_Status.DONE:
+ return (
+ <span className="flex items-center gap-x-3 text-sm">
+ {openFindings > 0 ? (
+ <span className="flex items-center gap-1 text-warning">
+ <AlertCircle className="size-4" />
+ {t("plan.rule-review.open-findings", { count: openFindings })}
+ </span>
+ ) : (
+ <span className="flex items-center gap-1 text-success">
+ <CheckCircle className="size-4" />
+ {t("plan.rule-review.no-open-findings")}
+ </span>
+ )}
+ <HumanizeTs
+ className="text-xs text-control-placeholder"
+ tsMs={getTimeForPbTimestampProtoEs(run.endTime)}
+ />
+ </span>
+ );
+ case ReviewRun_Status.FAILED:
+ return (
+ <span className="flex basis-full flex-col gap-y-1 text-sm">
+ <span className="flex items-center gap-1 text-error">
+ <XCircle className="size-4" />
+ {t("plan.rule-review.failed")}
+ </span>
+ <span className="text-xs break-words text-control-light">
+ {run.error}
+ </span>
+ </span>
+ );
+ default:
+ return null;
+ }
+}
diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/PlanStatusAction.tsx b/frontend/src/routes/project/plan-detail/components/lifecycle/PlanStatusAction.tsx
index 0808ca13ec..eed5c70a4c 100644
--- a/frontend/src/routes/project/plan-detail/components/lifecycle/PlanStatusAction.tsx
+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/PlanStatusAction.tsx
@@ -1,8 +1,8 @@
// The header's read-only "Plan status" control, shown when the current user does
// not own the next action (observer, not-your-turn) or the plan is in a pre-deploy
// blocker state. The trigger names the blocker; clicking opens a details panel
-// styled after GitHub's merge box — two collapsible gate rows (Review, Plan
-// checks), each a status icon + headline + subtext. The detail is ours: Review
+// styled after GitHub's merge box — gate rows (Review, Plan checks, and under
+// SQL Review V2 the open threads), each a status icon + headline + subtext. The detail is ours: Review
// expands to the (compact) approval flow; Plan checks expands to a severity
// breakdown with a "View Details" link into the existing plan-check drawer. The
// footer shows at most one state-dependent action: re-request review when
@@ -16,6 +16,7 @@ import {
CircleX,
Clock3,
Loader2,
+ MessagesSquare,
} from "lucide-react";
import { type ReactNode, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -37,6 +38,7 @@ import { userNamePrefix } from "@/stores/modules/v1/common";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import { RequestIssueRequestSchema } from "@/types/proto-es/v1/issue_service_pb";
+import { useSqlReviewV2 } from "../../hooks/useSqlReviewV2";
import { usePlanDetailContext } from "../../shell/PlanDetailContext";
import type { PlanCheckSummary } from "../../utils/phaseSummary";
import { BypassAndDeploySheet, useBypassDeploy } from "../review/bypassDeploy";
@@ -61,6 +63,7 @@ export function PlanStatusAction({
const [open, setOpen] = useState(false);
const [checksDrawerOpen, setChecksDrawerOpen] = useState(false);
const bypass = useBypassDeploy(issue, page.plan);
+ const sqlReview = useSqlReviewV2();
const tone = getPlanStatusTone(reason);
// Only the Review gate expands (to the approval flow); Checks is a static row
// with a View Details link. Open Review by default when it is the active gate.
@@ -81,6 +84,10 @@ export function PlanStatusAction({
return t("plan.lifecycle.rejected");
case "checks-failing":
return t("plan.lifecycle.checks-failing");
+ case "threads-open":
+ return t("plan.summary.n-unresolved-threads", {
+ count: bypass.unresolvedThreads,
+ });
}
})();
@@ -120,6 +127,9 @@ export function PlanStatusAction({
}}
summary={bypass.planCheckSummary}
/>
+ {sqlReview && (
+ <ThreadsGateRow count={sqlReview.unresolvedThreads} />
+ )}
</div>
<PlanStatusFooter
bypass={bypass}
@@ -444,3 +454,27 @@ function BypassAction({
</Button>
);
}
+
+/* -------------------------- threads gate (ours) ------------------------- */
+
+// Under SQL Review V2 every open thread holds the automatic rollout.
+function ThreadsGateRow({ count }: { count: number }) {
+ const { t } = useTranslation();
+ return (
+ <div className="flex items-center gap-3 px-4 py-3">
+ {count > 0 ? (
+ <MessagesSquare className="size-5 shrink-0 text-warning" />
+ ) : (
+ <CircleCheck className="size-5 shrink-0 text-success" />
+ )}
+ <GateLabel
+ subtitle={count > 0 ? t("plan.lifecycle.gate-threads-open-sub") : ""}
+ title={
+ count > 0
+ ? t("plan.lifecycle.gate-threads-open", { count })
+ : t("plan.lifecycle.gate-threads-resolved")
+ }
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.ts b/frontend/src/routes/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.ts
index e55463e338..c3a0a1a4f9 100644
--- a/frontend/src/routes/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.ts
+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.ts
@@ -39,6 +39,7 @@ const base: PlanLifecycleResolverInput = {
canCurrentUserApprove: false,
isCurrentUserReviewCandidate: false,
checks: checks(),
+ unresolvedThreads: 0,
hasRollout: false,
rollout: undefined,
};
@@ -190,6 +191,29 @@ describe("resolvePlanLifecycleHeaderState — pre-deploy gates", () => {
expect(state).toMatchObject({ kind: "plan-status", reason: "checking" });
});
+ test("approved + checks passed + open threads -> threads-open", () => {
+ const state = resolve({
+ approvalStatus: ApprovalStatus.APPROVED,
+ unresolvedThreads: 2,
+ });
+ expect(state).toMatchObject({
+ kind: "plan-status",
+ reason: "threads-open",
+ });
+ });
+
+ test("approved + checks failing outranks open threads", () => {
+ const state = resolve({
+ approvalStatus: ApprovalStatus.APPROVED,
+ checks: checks(1),
+ unresolvedThreads: 2,
+ });
+ expect(state).toMatchObject({
+ kind: "plan-status",
+ reason: "checks-failing",
+ });
+ });
+
test("approved + all gates passed, no rollout yet -> preparing-rollout", () => {
expect(resolve({ approvalStatus: ApprovalStatus.APPROVED }).kind).toBe(
"preparing-rollout"
diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/planLifecycleHeaderState.ts b/frontend/src/routes/project/plan-detail/components/lifecycle/planLifecycleHeaderState.ts
index aa41ef795c..0f202f8baa 100644
--- a/frontend/src/routes/project/plan-detail/components/lifecycle/planLifecycleHeaderState.ts
+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/planLifecycleHeaderState.ts
@@ -27,7 +27,8 @@ export type PlanStatusReason =
| "checking" // approved, plan checks still running
| "in-review" // review pending (the active gate)
| "rejected" // review rejected
- | "checks-failing"; // review approved, but plan checks failed
+ | "checks-failing" // review approved, but plan checks failed
+ | "threads-open"; // approved and checks passed, but threads hold the rollout
export type PlanLifecycleHeaderState =
// Nothing safe to surface (GitOps with no rollout, inconsistent backend
@@ -66,6 +67,8 @@ export interface PlanLifecycleResolverInput {
isCurrentUserReviewCandidate: boolean;
checks: PlanCheckSummary;
+ // Open threads hold the rollout under SQL Review V2; zero elsewhere.
+ unresolvedThreads: number;
hasRollout: boolean;
rollout: Rollout | undefined;
@@ -160,6 +163,9 @@ export function resolvePlanLifecycleHeaderState(
if (input.checks.running > 0) {
return { kind: "plan-status", reason: "checking" };
}
+ if (input.unresolvedThreads > 0) {
+ return { kind: "plan-status", reason: "threads-open" };
+ }
// All required gates passed; the backend auto-creates the rollout. Show a
// transient progress state until it arrives, then resolveDeploy takes over.
return { kind: "preparing-rollout" };
diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/planStatusLabel.test.ts b/frontend/src/routes/project/plan-detail/components/lifecycle/planStatusLabel.test.ts
index 72cb505f5f..0a109b572b 100644
--- a/frontend/src/routes/project/plan-detail/components/lifecycle/planStatusLabel.test.ts
+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/planStatusLabel.test.ts
@@ -3,9 +3,10 @@ import { describe, expect, test } from "vitest";
import { getPlanStatusTone } from "./planStatusLabel";
describe("getPlanStatusTone", () => {
- test("checking / in-review are neutral", () => {
+ test("checking / in-review / threads-open are neutral", () => {
expect(getPlanStatusTone("checking")).toBe("neutral");
expect(getPlanStatusTone("in-review")).toBe("neutral");
+ expect(getPlanStatusTone("threads-open")).toBe("neutral");
});
test("rejected / checks-failing are errors (hard blockers)", () => {
diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/planStatusLabel.ts b/frontend/src/routes/project/plan-detail/components/lifecycle/planStatusLabel.ts
index d597589174..b3618678bb 100644
--- a/frontend/src/routes/project/plan-detail/components/lifecycle/planStatusLabel.ts
+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/planStatusLabel.ts
@@ -9,6 +9,7 @@ export function getPlanStatusTone(reason: PlanStatusReason): PlanStatusTone {
switch (reason) {
case "checking":
case "in-review":
+ case "threads-open":
return "neutral";
case "rejected":
case "checks-failing":
diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts b/frontend/src/routes/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts
index 40443659bd..e2828b4f24 100644
--- a/frontend/src/routes/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts
+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts
@@ -8,6 +8,7 @@ import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import { IssueSchema } from "@/types/proto-es/v1/issue_service_pb";
import { useApprovalCandidates } from "../../../useApprovalCandidates";
+import { useSqlReviewV2, withRuleReview } from "../../hooks/useSqlReviewV2";
import type { PlanDetailPageState } from "../../shell/hooks/types";
import { getPlanCheckSummary } from "../../utils/phaseSummary";
import { isReleaseBackedPlan } from "../../utils/spec";
@@ -45,7 +46,13 @@ export function usePlanLifecycleHeader(
() => isReleaseBackedPlan(page.plan.specs),
[page.plan.specs]
);
- const checks = useMemo(() => getPlanCheckSummary(page.plan), [page.plan]);
+ const sqlReview = useSqlReviewV2();
+ const ruleReviewRun = sqlReview?.ruleReview?.run;
+ const checks = useMemo(
+ () => withRuleReview(getPlanCheckSummary(page.plan), ruleReviewRun),
+ [page.plan, ruleReviewRun]
+ );
+ const unresolvedThreads = sqlReview?.unresolvedThreads ?? 0;
// Depend on the primitives the resolver actually reads, not the whole
// `issue` object — polling replaces `page.issue` with a fresh reference every
@@ -72,6 +79,7 @@ export function usePlanLifecycleHeader(
canCurrentUserApprove,
isCurrentUserReviewCandidate,
checks,
+ unresolvedThreads,
hasRollout: !!page.rollout,
rollout: page.rollout,
}),
@@ -89,6 +97,7 @@ export function usePlanLifecycleHeader(
page.plan.state,
page.readonly,
page.rollout,
+ unresolvedThreads,
]
);
}
diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewReadinessFooter.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewReadinessFooter.tsx
index 471ec3413d..8df4e0c24d 100644
--- a/frontend/src/routes/project/plan-detail/components/review/ReviewReadinessFooter.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewReadinessFooter.tsx
@@ -1,4 +1,11 @@
-import { Ban, CircleCheck, CircleX, Clock3, Loader2 } from "lucide-react";
+import {
+ Ban,
+ CircleCheck,
+ CircleX,
+ Clock3,
+ Loader2,
+ MessagesSquare,
+} from "lucide-react";
import { Fragment, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
@@ -52,7 +59,8 @@ export function ReviewReadinessFooter({
return (
<div
className={
- state.kind === "approved-checks-failed"
+ state.kind === "approved-checks-failed" ||
+ state.kind === "approved-threads-open"
? "flex flex-wrap items-center gap-x-2 gap-y-1 border-t px-4 py-2.5"
: "flex flex-wrap items-center gap-x-2 gap-y-1 border-t px-4 py-2.5 text-sm text-control-placeholder"
}
@@ -101,6 +109,21 @@ export function ReviewReadinessFooter({
</div>
</>
)}
+ {state.kind === "approved-threads-open" && (
+ <>
+ <MessagesSquare className="size-6 shrink-0 text-warning" />
+ <div className="min-w-0 flex-1">
+ <div className="text-sm font-semibold text-main">
+ {t("plan.review.footer.approved-but-threads-open")}
+ </div>
+ <div className="text-xs text-control-placeholder">
+ {t("plan.review.footer.threads-open-not-created", {
+ count: bypass.unresolvedThreads,
+ })}
+ </div>
+ </div>
+ </>
+ )}
{state.kind === "rejected" && (
<>
<Ban className="size-4 shrink-0" />
diff --git a/frontend/src/routes/project/plan-detail/components/review/bypassDeploy.test.tsx b/frontend/src/routes/project/plan-detail/components/review/bypassDeploy.test.tsx
new file mode 100644
index 0000000000..810c0a8f60
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/components/review/bypassDeploy.test.tsx
@@ -0,0 +1,225 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, expect, test, vi } from "vitest";
+import { ApprovalStatus, IssueStatus } from "@/types/proto-es/v1/common_pb";
+import {
+ type Issue,
+ ReviewRun_Status,
+} from "@/types/proto-es/v1/issue_service_pb";
+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+
+const mocks = vi.hoisted(() => ({
+ createRollout: vi.fn(),
+ page: {} as Record<string, unknown>,
+ sqlReview: undefined as unknown,
+}));
+
+vi.mock("react-i18next", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("react-i18next")>()),
+ useTranslation: () => ({
+ t: (key: string, options?: { count?: number }) =>
+ options?.count === undefined ? key : `${key}:${options.count}`,
+ }),
+}));
+
+vi.mock("@/api", () => ({
+ rolloutServiceClientConnect: { createRollout: mocks.createRollout },
+}));
+
+vi.mock("@/stores", () => ({ pushNotification: vi.fn() }));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: (
+ selector: (state: {
+ dbGroupsByName: Record<string, unknown>;
+ dbGroupViewByName: Record<string, unknown>;
+ }) => unknown
+ ) => selector({ dbGroupsByName: {}, dbGroupViewByName: {} }),
+}));
+
+vi.mock("../../hooks/useSqlReviewV2", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../hooks/useSqlReviewV2")>()),
+ useSqlReviewV2: () => mocks.sqlReview,
+}));
+
+vi.mock("../../shell/focusPhase", () => ({ focusPlanPhase: vi.fn() }));
+
+vi.mock("../../shell/PlanDetailContext", () => ({
+ usePlanDetailContext: () => mocks.page,
+}));
+
+import { useBypassDeploy } from "./bypassDeploy";
+
+const issue = {
+ approvalStatus: ApprovalStatus.APPROVED,
+ status: IssueStatus.OPEN,
+} as Issue;
+const planOf = (change: { targets: string[]; release: string }) =>
+ ({
+ hasRollout: false,
+ name: "projects/foo/plans/7",
+ planCheckRunStatusCount: { SUCCESS: 1 },
+ specs: [{ config: { case: "changeDatabaseConfig", value: change } }],
+ }) as unknown as Plan;
+const plan = planOf({ targets: ["instances/prod/databases/app"], release: "" });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.createRollout.mockResolvedValue({});
+ mocks.page = {
+ expandPhase: vi.fn(),
+ planCheckRuns: [],
+ projectCanCreateRollout: true,
+ projectRequireIssueApproval: false,
+ projectRequirePlanCheckNoError: false,
+ readonly: false,
+ refreshState: vi.fn().mockResolvedValue(undefined),
+ };
+});
+
+test("asks to acknowledge open threads before deploying past them", async () => {
+ mocks.sqlReview = {
+ unresolvedThreads: 2,
+ threadsLoaded: true,
+ ruleReview: {
+ run: { status: ReviewRun_Status.DONE },
+ stale: false,
+ loadFailed: false,
+ },
+ };
+ const { result } = renderHook(() => useBypassDeploy(issue, plan));
+ expect(result.current.state.kind).toBe("approved-threads-open");
+ expect(result.current.weight).toBe("link");
+ expect(result.current.warnings).toContain(
+ "plan.review.footer.confirm-unresolved-threads:2"
+ );
+ expect(result.current.confirmDisabled).toBe(true);
+
+ act(() => result.current.triggerDeploy());
+ expect(result.current.confirmOpen).toBe(true);
+ expect(mocks.createRollout).not.toHaveBeenCalled();
+
+ act(() => result.current.setAcknowledge(true));
+ expect(result.current.confirmDisabled).toBe(false);
+});
+
+test("counts a failed rule review as a failed check", () => {
+ mocks.sqlReview = {
+ unresolvedThreads: 0,
+ threadsLoaded: true,
+ ruleReview: { run: { status: ReviewRun_Status.FAILED } },
+ };
+ const { result } = renderHook(() => useBypassDeploy(issue, plan));
+ expect(result.current.state.kind).toBe("approved-checks-failed");
+ expect(result.current.checks.error).toBe(1);
+});
+
+test.each([
+ ["without permission to read it", undefined],
+ ["while it loads", { run: undefined, stale: true, loadFailed: false }],
+ [
+ "when it fails to load",
+ { run: { status: ReviewRun_Status.DONE }, stale: false, loadFailed: true },
+ ],
+ [
+ "before it reads the plan's latest change",
+ { run: { status: ReviewRun_Status.DONE }, stale: true, loadFailed: false },
+ ],
+])("asks to confirm deploying past a rule review it cannot read %s", (_, ruleReview) => {
+ mocks.sqlReview = { unresolvedThreads: 0, threadsLoaded: true, ruleReview };
+ const { result } = renderHook(() => useBypassDeploy(issue, plan));
+ expect(result.current.state.kind).toBe("all-gates-passed");
+ expect(result.current.warnings).toEqual([
+ "plan.review.footer.confirm-rule-review-unknown",
+ ]);
+
+ act(() => result.current.triggerDeploy());
+ expect(result.current.confirmOpen).toBe(true);
+ expect(mocks.createRollout).not.toHaveBeenCalled();
+});
+
+test("asks to confirm deploying past a rule review that never ran on the SQL", () => {
+ mocks.sqlReview = {
+ unresolvedThreads: 0,
+ threadsLoaded: true,
+ ruleReview: { run: null, stale: false, loadFailed: false },
+ };
+ const { result } = renderHook(() => useBypassDeploy(issue, plan));
+ expect(result.current.warnings).toEqual([
+ "plan.review.footer.confirm-rule-review-unknown",
+ ]);
+
+ act(() => result.current.triggerDeploy());
+ expect(result.current.confirmOpen).toBe(true);
+ expect(mocks.createRollout).not.toHaveBeenCalled();
+});
+
+test("deploys at once where the plan has no SQL to review", async () => {
+ mocks.sqlReview = {
+ unresolvedThreads: 0,
+ threadsLoaded: true,
+ ruleReview: { run: null, stale: false, loadFailed: false },
+ };
+ const releasePlan = planOf({
+ targets: ["instances/prod/databases/app"],
+ release: "projects/foo/releases/1",
+ });
+ const { result } = renderHook(() => useBypassDeploy(issue, releasePlan));
+ expect(result.current.warnings).toEqual([]);
+
+ await act(async () => {
+ result.current.triggerDeploy();
+ });
+ expect(mocks.createRollout).toHaveBeenCalledTimes(1);
+});
+
+test("asks to confirm deploying before the threads have loaded", () => {
+ mocks.sqlReview = {
+ unresolvedThreads: 0,
+ threadsLoaded: false,
+ ruleReview: {
+ run: { status: ReviewRun_Status.DONE },
+ stale: false,
+ loadFailed: false,
+ },
+ };
+ const { result } = renderHook(() => useBypassDeploy(issue, plan));
+ expect(result.current.state.kind).toBe("all-gates-passed");
+ expect(result.current.warnings).toEqual([
+ "plan.review.footer.confirm-threads-unknown",
+ ]);
+
+ act(() => result.current.triggerDeploy());
+ expect(result.current.confirmOpen).toBe(true);
+ expect(mocks.createRollout).not.toHaveBeenCalled();
+});
+
+test("deploys at once after the rule review is done", async () => {
+ mocks.sqlReview = {
+ unresolvedThreads: 0,
+ threadsLoaded: true,
+ ruleReview: {
+ run: { status: ReviewRun_Status.DONE },
+ stale: false,
+ loadFailed: false,
+ },
+ };
+ const { result } = renderHook(() => useBypassDeploy(issue, plan));
+ expect(result.current.warnings).toEqual([]);
+
+ await act(async () => {
+ result.current.triggerDeploy();
+ });
+ expect(mocks.createRollout).toHaveBeenCalledTimes(1);
+});
+
+test("deploys at once where SQL Review V2 is off", async () => {
+ mocks.sqlReview = undefined;
+ const { result } = renderHook(() => useBypassDeploy(issue, plan));
+ expect(result.current.state.kind).toBe("all-gates-passed");
+ expect(result.current.warnings).toEqual([]);
+
+ await act(async () => {
+ result.current.triggerDeploy();
+ });
+ expect(mocks.createRollout).toHaveBeenCalledTimes(1);
+});
diff --git a/frontend/src/routes/project/plan-detail/components/review/bypassDeploy.tsx b/frontend/src/routes/project/plan-detail/components/review/bypassDeploy.tsx
index 7562b63f98..74f788e8b7 100644
--- a/frontend/src/routes/project/plan-detail/components/review/bypassDeploy.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/bypassDeploy.tsx
@@ -23,11 +23,17 @@ import {
} from "@/components/ui/sheet";
import { getPlanCheckSummaryWithFallback } from "@/lib/plan/check";
import { pushNotification } from "@/stores";
+import { useAppStore } from "@/stores/app";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
import { CreateRolloutRequestSchema } from "@/types/proto-es/v1/rollout_service_pb";
+import { useSqlReviewV2, withRuleReview } from "../../hooks/useSqlReviewV2";
import { focusPlanPhase } from "../../shell/focusPhase";
import { usePlanDetailContext } from "../../shell/PlanDetailContext";
+import {
+ hasReviewableSQL,
+ loadedMatchedDatabaseCount,
+} from "../../utils/aiReviewRun";
import type { PlanCheckSummary } from "../../utils/phaseSummary";
import { getPlanCheckSummary } from "../../utils/phaseSummary";
import { ReviewApprovalFlow } from "./ReviewApprovalFlow";
@@ -51,6 +57,7 @@ export interface BypassDeploy {
setAcknowledge: (value: boolean) => void;
gates: { label: string; met: boolean }[];
gatesBlocked: boolean;
+ unresolvedThreads: number;
warnings: string[];
needAck: boolean;
confirmDisabled: boolean;
@@ -64,7 +71,32 @@ export function useBypassDeploy(issue: Issue, plan: Plan): BypassDeploy {
const [confirmOpen, setConfirmOpen] = useState(false);
const [acknowledge, setAcknowledge] = useState(false);
- const checks = useMemo(() => getPlanCheckSummary(plan), [plan]);
+ const sqlReview = useSqlReviewV2();
+ const ruleReview = sqlReview?.ruleReview;
+ const ruleReviewRun = ruleReview?.run;
+ const dbGroupsByName = useAppStore((state) => state.dbGroupsByName);
+ const dbGroupViewByName = useAppStore((state) => state.dbGroupViewByName);
+ const reviewsSQL = hasReviewableSQL(
+ plan,
+ loadedMatchedDatabaseCount({ dbGroupsByName, dbGroupViewByName })
+ );
+ // The rule review is unknown when this page cannot read it (still loading,
+ // failed to load, no permission, or not read since the plan changed), or
+ // when it never ran on a plan with SQL to review: the server may still be
+ // running it, or start it before an automatic rollout.
+ const ruleReviewUnknown =
+ !!sqlReview &&
+ (!ruleReview ||
+ ruleReview.run === undefined ||
+ (ruleReview.run === null && reviewsSQL) ||
+ ruleReview.loadFailed ||
+ ruleReview.stale);
+ const unresolvedThreads = sqlReview?.unresolvedThreads ?? 0;
+ const threadsUnknown = !!sqlReview && !sqlReview.threadsLoaded;
+ const checks = useMemo(
+ () => withRuleReview(getPlanCheckSummary(plan), ruleReviewRun),
+ [plan, ruleReviewRun]
+ );
const state = useMemo(
() =>
computeReadinessFooterState({
@@ -72,8 +104,15 @@ export function useBypassDeploy(issue: Issue, plan: Plan): BypassDeploy {
issueStatus: issue.status,
approvalStatus: issue.approvalStatus,
checks,
+ unresolvedThreads,
}),
- [checks, issue.approvalStatus, issue.status, plan.hasRollout]
+ [
+ checks,
+ issue.approvalStatus,
+ issue.status,
+ plan.hasRollout,
+ unresolvedThreads,
+ ]
);
const weight = computeBypassActionWeight({
state: state.kind,
@@ -82,11 +121,14 @@ export function useBypassDeploy(issue: Issue, plan: Plan): BypassDeploy {
});
const planCheckSummary = useMemo(
() =>
- getPlanCheckSummaryWithFallback(
- page.planCheckRuns,
- plan.planCheckRunStatusCount
+ withRuleReview(
+ getPlanCheckSummaryWithFallback(
+ page.planCheckRuns,
+ plan.planCheckRunStatusCount
+ ),
+ ruleReviewRun
),
- [page.planCheckRuns, plan.planCheckRunStatusCount]
+ [page.planCheckRuns, plan.planCheckRunStatusCount, ruleReviewRun]
);
const openConfirm = () => {
@@ -98,7 +140,12 @@ export function useBypassDeploy(issue: Issue, plan: Plan): BypassDeploy {
// bypass or confirm — deploy straight away. Any other case (failed/running
// checks, or bypassing review) opens the confirm sheet.
const triggerDeploy = () => {
- if (state.kind === "all-gates-passed" && checks.running === 0) {
+ if (
+ state.kind === "all-gates-passed" &&
+ checks.running === 0 &&
+ !ruleReviewUnknown &&
+ !threadsUnknown
+ ) {
void createRollout();
} else {
openConfirm();
@@ -133,7 +180,8 @@ export function useBypassDeploy(issue: Issue, plan: Plan): BypassDeploy {
// only bypass the project's *optional* requirements, never its mandatory ones.
const reviewApproved =
state.kind === "all-gates-passed" ||
- state.kind === "approved-checks-failed";
+ state.kind === "approved-checks-failed" ||
+ state.kind === "approved-threads-open";
const gates: { label: string; met: boolean }[] = [];
if (page.projectRequireIssueApproval) {
gates.push({
@@ -167,6 +215,19 @@ export function useBypassDeploy(issue: Issue, plan: Plan): BypassDeploy {
if (checks.running > 0) {
warnings.push(t("plan.review.footer.confirm-checks-running"));
}
+ if (ruleReviewUnknown) {
+ warnings.push(t("plan.review.footer.confirm-rule-review-unknown"));
+ }
+ if (unresolvedThreads > 0) {
+ warnings.push(
+ t("plan.review.footer.confirm-unresolved-threads", {
+ count: unresolvedThreads,
+ })
+ );
+ }
+ if (threadsUnknown) {
+ warnings.push(t("plan.review.footer.confirm-threads-unknown"));
+ }
const needAck = warnings.length > 0;
const confirmDisabled = creating || gatesBlocked || (needAck && !acknowledge);
@@ -183,6 +244,7 @@ export function useBypassDeploy(issue: Issue, plan: Plan): BypassDeploy {
setAcknowledge,
gates,
gatesBlocked,
+ unresolvedThreads,
warnings,
needAck,
confirmDisabled,
diff --git a/frontend/src/routes/project/plan-detail/components/review/readinessFooterState.test.ts b/frontend/src/routes/project/plan-detail/components/review/readinessFooterState.test.ts
index 33b5c58ba3..0248b28c16 100644
--- a/frontend/src/routes/project/plan-detail/components/review/readinessFooterState.test.ts
+++ b/frontend/src/routes/project/plan-detail/components/review/readinessFooterState.test.ts
@@ -18,6 +18,7 @@ const base = {
hasRollout: false,
issueStatus: IssueStatus.OPEN,
checks: checks(),
+ unresolvedThreads: 0,
};
describe("computeReadinessFooterState", () => {
@@ -78,6 +79,27 @@ describe("computeReadinessFooterState", () => {
).toBe("approved-checks-failed");
});
+ test("approved with open threads -> approved-threads-open", () => {
+ expect(
+ computeReadinessFooterState({
+ ...base,
+ approvalStatus: ApprovalStatus.APPROVED,
+ unresolvedThreads: 3,
+ }).kind
+ ).toBe("approved-threads-open");
+ });
+
+ test("failed checks outrank open threads", () => {
+ expect(
+ computeReadinessFooterState({
+ ...base,
+ approvalStatus: ApprovalStatus.APPROVED,
+ checks: checks(1),
+ unresolvedThreads: 3,
+ }).kind
+ ).toBe("approved-checks-failed");
+ });
+
test("rejected -> rejected", () => {
expect(
computeReadinessFooterState({
@@ -94,6 +116,12 @@ describe("computeBypassActionWeight", () => {
requireIssueApproval: false,
};
+ test("muted link when review passed but threads are open", () => {
+ expect(
+ computeBypassActionWeight({ ...allowed, state: "approved-threads-open" })
+ ).toBe("link");
+ });
+
test("primary button when review passed but checks failed", () => {
expect(
computeBypassActionWeight({ ...allowed, state: "approved-checks-failed" })
diff --git a/frontend/src/routes/project/plan-detail/components/review/readinessFooterState.ts b/frontend/src/routes/project/plan-detail/components/review/readinessFooterState.ts
index b7b89a6f80..0bc1f2c150 100644
--- a/frontend/src/routes/project/plan-detail/components/review/readinessFooterState.ts
+++ b/frontend/src/routes/project/plan-detail/components/review/readinessFooterState.ts
@@ -11,6 +11,7 @@ export type ReadinessFooterStateKind =
| "waiting-review"
| "all-gates-passed"
| "approved-checks-failed"
+ | "approved-threads-open"
| "rejected";
export interface ReadinessFooterState {
@@ -23,6 +24,8 @@ export function computeReadinessFooterState(input: {
issueStatus: IssueStatus | undefined;
approvalStatus: ApprovalStatus;
checks: PlanCheckSummary;
+ // Open threads hold the rollout under SQL Review V2; zero elsewhere.
+ unresolvedThreads: number;
}): ReadinessFooterState {
const { checks } = input;
if (input.hasRollout || input.issueStatus !== IssueStatus.OPEN) {
@@ -35,10 +38,13 @@ export function computeReadinessFooterState(input: {
input.approvalStatus === ApprovalStatus.APPROVED ||
input.approvalStatus === ApprovalStatus.SKIPPED
) {
- return {
- kind: checks.error > 0 ? "approved-checks-failed" : "all-gates-passed",
- checks,
- };
+ if (checks.error > 0) {
+ return { kind: "approved-checks-failed", checks };
+ }
+ if (input.unresolvedThreads > 0) {
+ return { kind: "approved-threads-open", checks };
+ }
+ return { kind: "all-gates-passed", checks };
}
return { kind: "waiting-review", checks };
}
@@ -68,6 +74,10 @@ export function computeBypassActionWeight(input: {
if (input.state === "waiting-review") {
return input.requireIssueApproval ? "none" : "link";
}
+ // Open threads are meant to be resolved, so the override stays a muted link.
+ if (input.state === "approved-threads-open") {
+ return "link";
+ }
// Review passed (approved/skipped): always offer a manual deploy when the user
// can create a rollout, regardless of plan-check state. Prominent button when
// checks failed (the call to action), muted link otherwise. The confirm sheet
diff --git a/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.test.tsx b/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.test.tsx
index bbb3c6b0ad..a7b0424fda 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.test.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.test.tsx
@@ -2,6 +2,7 @@ import { create } from "@bufbuild/protobuf";
import { cleanup, fireEvent, render } from "@testing-library/react";
import { afterEach, describe, expect, test, vi } from "vitest";
import { IssueComment_ReviewMetadata_Priority } from "@/types/proto-es/v1/issue_service_pb";
+import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
import {
Plan_ChangeDatabaseConfigSchema,
Plan_SpecSchema,
@@ -25,7 +26,11 @@ vi.mock("../PlanTargetDisplay", () => ({
),
}));
-import { ReviewPriorityBadge, ReviewTargets } from "./ReviewResult";
+import {
+ ReviewPriorityBadge,
+ ReviewRule,
+ ReviewTargets,
+} from "./ReviewResult";
afterEach(cleanup);
@@ -72,6 +77,26 @@ describe("ReviewPriorityBadge", () => {
});
});
+describe("ReviewRule", () => {
+ test("names the standard rule in the reader's language", () => {
+ const { getByTestId } = render(
+ <ReviewRule ruleType={ReviewRuleType.REQUIRE_WHERE} />
+ );
+ const rule = getByTestId("review-rule");
+ expect(rule.firstElementChild?.textContent).toBe("plan.review.thread.rule");
+ expect(rule.lastElementChild?.textContent).toBe(
+ "sql-review.standard-rules.rule.require-where.title"
+ );
+ });
+
+ test("shows nothing for an unspecified rule", () => {
+ const { container } = render(
+ <ReviewRule ruleType={ReviewRuleType.REVIEW_RULE_TYPE_UNSPECIFIED} />
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+});
+
describe("ReviewTargets", () => {
test("shows a short list whole", () => {
const { container, queryByRole } = render(
diff --git a/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.tsx b/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.tsx
index 61a5c0b686..4f41845cb0 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.tsx
@@ -2,9 +2,11 @@ import type { TFunction } from "i18next";
import { Bot, ListChecks } from "lucide-react";
import { type ReactNode, useState } from "react";
import { useTranslation } from "react-i18next";
+import { standardRuleText } from "@/components/sql-review/standardRules";
import { UserAvatar } from "@/components/UserAvatar";
import { Badge, type BadgeProps, badgeVariants } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
import { useUserByIdentifier } from "@/hooks/useAppState";
import { cn } from "@/lib/utils";
import { isValidDatabaseName, unknownUser } from "@/types";
@@ -14,6 +16,7 @@ import {
ReviewRun_Type,
} from "@/types/proto-es/v1/issue_service_pb";
import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
import { extractDatabaseResourceName } from "@/utils/v1/database";
import { PlanTargetDisplay } from "../PlanTargetDisplay";
@@ -119,6 +122,30 @@ function priorityStyle(
}
}
+// The standard rule a rule review result reports, in the reader's language,
+// with what the rule checks on hover. An AI result names its rule in its text.
+export function ReviewRule({ ruleType }: { ruleType: ReviewRuleType }) {
+ const { t } = useTranslation();
+ if (ruleType === ReviewRuleType.REVIEW_RULE_TYPE_UNSPECIFIED) return null;
+ const { title, description } = standardRuleText(t, ruleType);
+ return (
+ <div
+ className="flex min-w-0 items-baseline gap-x-2 text-xs"
+ data-testid="review-rule"
+ >
+ <span className="shrink-0 text-control-light">
+ {t("plan.review.thread.rule")}
+ </span>
+ <Tooltip
+ content={description}
+ render={<span className="min-w-0 text-control" tabIndex={0} />}
+ >
+ {title}
+ </Tooltip>
+ </div>
+ );
+}
+
// The databases a review result applies to. A result without targets has
// nothing to list. A result for exactly the databases of its spec says
// nothing the spec does not, so the row is left out then too, but only when
diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementAnchorContext.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementAnchorContext.tsx
index 437546759c..715bf24933 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/StatementAnchorContext.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementAnchorContext.tsx
@@ -13,10 +13,9 @@ import type { StatementAnchor } from "@/types/proto-es/v1/issue_service_pb";
import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
import { tokenizeLines } from "./placement/lineTokens";
-import type { Placement } from "./placement/place";
+import { anchorLineRange, type Placement } from "./placement/place";
import {
type AnchorState,
- anchorLineRange,
completePreviewLineCount,
excerptLines,
type LineRange,
diff --git a/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.test.tsx b/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.test.tsx
index b5cf53c6eb..cc9a9bd75e 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.test.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.test.tsx
@@ -15,6 +15,7 @@ import {
Plan_SpecSchema,
} from "@/types/proto-es/v1/plan_service_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
+import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
vi.mock("react-i18next", () => ({
initReactI18next: { type: "3rdParty", init: () => {} },
@@ -164,6 +165,25 @@ describe("ThreadComment", () => {
}
);
+ test("names the standard rule of a RULE result, and no rule for an AI result", () => {
+ const rule = reviewResult(
+ "DELETE FROM employee has no WHERE clause",
+ ReviewRun_Type.RULE,
+ IssueComment_ReviewMetadata_Priority.P1
+ );
+ if (rule.reviewMetadata) {
+ rule.reviewMetadata.ruleType = ReviewRuleType.REQUIRE_WHERE;
+ }
+ const { getByTestId } = renderComment(rule);
+ expect(getByTestId("review-rule").textContent).toContain(
+ "sql-review.standard-rules.rule.require-where.title"
+ );
+ cleanup();
+
+ const { container } = renderComment(reviewResult("Missing WHERE clause."));
+ expect(container.querySelector("[data-testid='review-rule']")).toBeNull();
+ });
+
test("shows a user comment as its author with no review details", () => {
const { container, getByTitle } = renderComment(
userComment("Looks good ![screenshot](https://example.com/s.png)")
diff --git a/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.tsx b/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.tsx
index 2c10d3ad6e..415e043504 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/ThreadComment.tsx
@@ -8,10 +8,12 @@ import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { getTimeForPbTimestampProtoEs } from "@/types";
import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";
+import { ReviewRun_Type } from "@/types/proto-es/v1/issue_service_pb";
import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
import {
ReviewPriorityBadge,
+ ReviewRule,
ReviewTargets,
useCommentAuthor,
} from "./ReviewResult";
@@ -170,6 +172,9 @@ export function ThreadComment({
</div>
)
)}
+ {review?.runType === ReviewRun_Type.RULE && (
+ <ReviewRule ruleType={review.ruleType} />
+ )}
</div>
</div>
);
diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/place.test.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/place.test.ts
index 4ed0c4210d..c1ceba62b0 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/placement/place.test.ts
+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/place.test.ts
@@ -1,12 +1,17 @@
+import { create } from "@bufbuild/protobuf";
import { describe, expect, it } from "vitest";
+import { PositionSchema } from "@/types/proto-es/v1/common_pb";
+import { StatementAnchorSchema } from "@/types/proto-es/v1/issue_service_pb";
import { SHEET_PREVIEW_CHARACTER_LIMIT } from "@/utils/v1/sheet";
import {
+ anchorLineRange,
current,
diffPair,
OUTDATED,
placeOnPair,
placeWithHunks,
tokenizeSheet,
+ trivialPlacement,
UNAVAILABLE,
UNAVAILABLE_SIZE_LIMIT,
} from "./place";
@@ -226,3 +231,72 @@ describe("place: invalid input and limits", () => {
).toEqual(UNAVAILABLE_SIZE_LIMIT);
});
});
+
+const anchorAt = (
+ start: [line: number, column: number],
+ end: [line: number, column: number],
+ sheetSha256 = ""
+) =>
+ create(StatementAnchorSchema, {
+ sheetSha256,
+ startPosition: create(PositionSchema, { line: start[0], column: start[1] }),
+ endPosition: create(PositionSchema, { line: end[0], column: end[1] }),
+ });
+
+describe("anchorLineRange", () => {
+ it("includes the end line of a whole-line anchor", () => {
+ expect(anchorLineRange(anchorAt([8, 0], [10, 0]))).toEqual({
+ startLine: 8,
+ endLine: 10,
+ });
+ });
+
+ it("covers the lines of a code-point range", () => {
+ expect(anchorLineRange(anchorAt([2, 1], [2, 21]))).toEqual({
+ startLine: 2,
+ endLine: 2,
+ });
+ expect(anchorLineRange(anchorAt([3, 2], [4, 7]))).toEqual({
+ startLine: 3,
+ endLine: 4,
+ });
+ });
+
+ it("stops a code-point range ending at column 1 on the previous line", () => {
+ expect(anchorLineRange(anchorAt([3, 2], [5, 1]))).toEqual({
+ startLine: 3,
+ endLine: 4,
+ });
+ });
+
+ it("rejects malformed anchors", () => {
+ expect(anchorLineRange(create(StatementAnchorSchema))).toBeUndefined();
+ expect(anchorLineRange(anchorAt([0, 0], [1, 0]))).toBeUndefined();
+ expect(anchorLineRange(anchorAt([5, 0], [2, 0]))).toBeUndefined();
+ });
+});
+
+describe("trivialPlacement", () => {
+ const SHA = "a".repeat(64);
+
+ it("places a code-point anchor on its own sheet at its covered lines", () => {
+ expect(trivialPlacement(anchorAt([4, 1], [4, 52], SHA), SHA)).toEqual(
+ current(4, 4)
+ );
+ });
+
+ it("leaves an anchor on another sheet to the diff", () => {
+ expect(
+ trivialPlacement(anchorAt([4, 1], [4, 52], SHA), "b".repeat(64))
+ ).toBeUndefined();
+ });
+
+ it("is UNAVAILABLE without a target or with a malformed anchor", () => {
+ expect(trivialPlacement(anchorAt([4, 1], [4, 52], SHA), undefined)).toBe(
+ UNAVAILABLE
+ );
+ expect(trivialPlacement(anchorAt([0, 0], [0, 0], SHA), SHA)).toBe(
+ UNAVAILABLE
+ );
+ });
+});
diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/place.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/place.ts
index 63a753f66d..1ff3c96a16 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/placement/place.ts
+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/place.ts
@@ -11,8 +11,8 @@ export interface LineRange {
}
// Where an anchored comment shows for the spec's current statement. CURRENT
-// carries the range in the current sheet; the text there is byte for byte
-// what the reviewer selected. OUTDATED means the selected lines changed.
+// carries the range in the current sheet; the lines there are byte for byte
+// the lines the anchor covers. OUTDATED means those lines changed.
// UNAVAILABLE means the inputs were missing or invalid, or a limit was hit.
export type Placement =
| { readonly state: "CURRENT"; readonly range: LineRange }
@@ -40,22 +40,29 @@ export interface PairAnchor extends LineRange {
export const anchorId = (range: LineRange): string =>
`${range.startLine}-${range.endLine}`;
-// This version supports whole-line anchors only: both columns zero, one-based
-// lines, and an inclusive end at or after the start.
-export function wholeLineRange(
+// The one-based lines an anchor covers, which placement maps. A whole-line
+// anchor has zero columns and an inclusive end line. A code-point range, such
+// as a rule review finding's, is end-exclusive, so an end at column 1 of a
+// later line covers nothing on that line.
+export function anchorLineRange(
anchor: Pick<StatementAnchor, "startPosition" | "endPosition">
): LineRange | undefined {
const start = anchor.startPosition;
const end = anchor.endPosition;
- if (!start || !end) return undefined;
- if (start.column !== 0 || end.column !== 0) return undefined;
- if (start.line < 1 || end.line < start.line) return undefined;
- return { startLine: start.line, endLine: end.line };
+ if (!start || !end || start.line < 1 || end.line < start.line) {
+ return undefined;
+ }
+ const wholeLine = start.column === 0 && end.column === 0;
+ const endLine =
+ !wholeLine && end.column === 1 && end.line > start.line
+ ? end.line - 1
+ : end.line;
+ return { startLine: start.line, endLine };
}
// The part of the placement rule that needs no diff, shared by the planner
// and by every consumer that shows a comment before a run has settled it:
-// an unsupported anchor is UNAVAILABLE, no target (spec gone or without a
+// a malformed anchor is UNAVAILABLE, no target (spec gone or without a
// statement) is UNAVAILABLE, and an anchor on the target sheet itself is
// CURRENT at its own lines. Undefined means the diff has to decide.
export function trivialPlacement(
@@ -65,7 +72,7 @@ export function trivialPlacement(
>,
targetSha256: string | undefined
): Placement | undefined {
- const range = wholeLineRange(anchor);
+ const range = anchorLineRange(anchor);
if (!range || !targetSha256) return UNAVAILABLE;
if (targetSha256 === anchor.sheetSha256) {
return current(range.startLine, range.endLine);
diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.test.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.test.ts
index dfe636ad6f..f81195a4dd 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.test.ts
+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.test.ts
@@ -15,7 +15,6 @@ import {
OUTDATED,
UNAVAILABLE,
UNAVAILABLE_SIZE_LIMIT,
- wholeLineRange,
} from "./place";
import {
type PlacementPlanInput,
@@ -94,46 +93,37 @@ const plan = (
});
};
-describe("wholeLineRange", () => {
- test("accepts zero-column ranges and rejects anything else", () => {
- expect(wholeLineRange(anchor(SHA_A, 2, 4))).toEqual({
- startLine: 2,
- endLine: 4,
- });
- expect(wholeLineRange(anchor(SHA_A, 2))).toEqual({
- startLine: 2,
- endLine: 2,
- });
- expect(
- wholeLineRange(anchor(SHA_A, 2, 4, { columns: [1, 1] }))
- ).toBeUndefined();
- expect(
- wholeLineRange(anchor(SHA_A, 2, 4, { columns: [0, 3] }))
- ).toBeUndefined();
- expect(wholeLineRange(anchor(SHA_A, 0, 1))).toBeUndefined();
- expect(wholeLineRange(anchor(SHA_A, 3, 2))).toBeUndefined();
- });
-});
-
describe("planPlacements", () => {
test("ignores unanchored comments and settles trivial cases without fetching", () => {
const result = plan({
comments: [
comment("plain"),
comment("same", anchor(SHA_B, 3, 5)),
- comment("columns", anchor(SHA_A, 1, 1, { columns: [1, 4] })),
+ comment("columns", anchor(SHA_B, 2, 3, { columns: [5, 1] })),
comment("no-spec", anchor(SHA_A, 1, 1, { spec: "gone" })),
],
specs: [spec("spec-1", SHA_B), spec("other", SHA_C)],
});
expect(result.settled.has(nameOf("plain"))).toBe(false);
expect(result.settled.get(nameOf("same"))).toEqual(current(3, 5));
- expect(result.settled.get(nameOf("columns"))).toEqual(UNAVAILABLE);
+ expect(result.settled.get(nameOf("columns"))).toEqual(current(2, 2));
expect(result.settled.get(nameOf("no-spec"))).toEqual(UNAVAILABLE);
expect(result.pairs).toEqual([]);
expect(result.fetches).toEqual([]);
});
+ test("diffs a code-point anchor on an earlier sheet by its covered lines", () => {
+ const result = plan({
+ comments: [comment("finding", anchor(SHA_A, 2, 2, { columns: [1, 21] }))],
+ sizes: { [sheet(SHA_A)]: 100, [sheet(SHA_B)]: 200 },
+ });
+ expect(result.settled.size).toBe(0);
+ expect(result.pairs).toHaveLength(1);
+ expect(result.pairs[0].anchors).toEqual([
+ { id: "2-2", startLine: 2, endLine: 2 },
+ ]);
+ });
+
test("settles UNAVAILABLE when the spec has no statement", () => {
const result = plan({
comments: [comment("c", anchor(SHA_A, 1))],
diff --git a/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.ts b/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.ts
index dc9552cd22..8f536e1fa9 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.ts
+++ b/frontend/src/routes/project/plan-detail/components/threads/placement/placementPlan.ts
@@ -8,12 +8,12 @@ import {
import type { PlacementBudgets } from "./budgets";
import {
anchorId,
+ anchorLineRange,
type PairAnchor,
type Placement,
trivialPlacement,
UNAVAILABLE,
UNAVAILABLE_SIZE_LIMIT,
- wholeLineRange,
} from "./place";
// One saved/current sheet pair to diff, with the anchors that map through it.
@@ -105,7 +105,7 @@ export function planPlacements(input: PlacementPlanInput): PlacementPlan {
return;
}
// `trivialPlacement` returned undefined, so both are present.
- const range = wholeLineRange(anchor);
+ const range = anchorLineRange(anchor);
if (!range || !targetSha256) return;
const key = pairKey(anchor.spec, anchor.sheetSha256, targetSha256);
let candidate = candidates.get(key);
diff --git a/frontend/src/routes/project/plan-detail/components/threads/threadModel.test.ts b/frontend/src/routes/project/plan-detail/components/threads/threadModel.test.ts
index 333b0e6161..c807cb7a76 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/threadModel.test.ts
+++ b/frontend/src/routes/project/plan-detail/components/threads/threadModel.test.ts
@@ -3,8 +3,10 @@ import { TimestampSchema } from "@bufbuild/protobuf/wkt";
import { describe, expect, test } from "vitest";
import { PositionSchema } from "@/types/proto-es/v1/common_pb";
import {
+ IssueComment_ReviewMetadataSchema,
IssueComment_ThreadState,
IssueCommentSchema,
+ ReviewRun_Type,
StatementAnchorSchema,
} from "@/types/proto-es/v1/issue_service_pb";
import {
@@ -14,7 +16,6 @@ import {
} from "@/types/proto-es/v1/plan_service_pb";
import { current, OUTDATED, UNAVAILABLE } from "./placement/place";
import {
- anchorLineRange,
buildWholeLineAnchor,
completePreviewLineCount,
countPlacedUnresolvedBySpec,
@@ -203,28 +204,6 @@ describe("resolveAnchorState", () => {
});
});
-describe("anchorLineRange", () => {
- test("whole-line anchors include the end line", () => {
- expect(anchorLineRange(anchor(8, 10))).toEqual({
- startLine: 8,
- endLine: 10,
- });
- });
-
- test("code-point ranges ending at column 1 stop on the previous line", () => {
- const precise = create(StatementAnchorSchema, {
- startPosition: create(PositionSchema, { line: 3, column: 2 }),
- endPosition: create(PositionSchema, { line: 5, column: 1 }),
- });
- expect(anchorLineRange(precise)).toEqual({ startLine: 3, endLine: 4 });
- });
-
- test("rejects malformed anchors", () => {
- expect(anchorLineRange(create(StatementAnchorSchema))).toBeUndefined();
- expect(anchorLineRange(anchor(5, 2))).toBeUndefined();
- });
-});
-
describe("buildWholeLineAnchor", () => {
test("orders the lines and uses zero columns", () => {
const built = buildWholeLineAnchor({
@@ -315,6 +294,59 @@ describe("editor placement", () => {
});
});
+describe("editor placement of review results", () => {
+ const result = (
+ id: string,
+ runType: ReviewRun_Type,
+ opts: { superseded?: boolean; resolved?: boolean } = {}
+ ) => {
+ const comment = root(id, { anchor: anchor(2, 2), resolved: opts.resolved });
+ comment.reviewMetadata = create(IssueComment_ReviewMetadataSchema, {
+ runType,
+ superseded: opts.superseded ?? false,
+ });
+ return comment;
+ };
+ const placedNames = (comments: ReturnType<typeof root>[]) =>
+ selectEditorThreads(groupThreads(comments), {
+ specId: "spec-1",
+ sheetSha256: SHA,
+ }).map((entry) => entry.thread.root.comment);
+
+ test("shows the latest standard rule review, resolved or not", () => {
+ expect(
+ placedNames([
+ result("latest-open", ReviewRun_Type.RULE),
+ result("latest-resolved", ReviewRun_Type.RULE, { resolved: true }),
+ result("earlier", ReviewRun_Type.RULE, {
+ superseded: true,
+ resolved: true,
+ }),
+ ])
+ ).toEqual(["root latest-open", "root latest-resolved"]);
+ });
+
+ test("keeps a superseded result someone reopened, since it holds the rollout", () => {
+ expect(
+ placedNames([
+ result("reopened", ReviewRun_Type.RULE, { superseded: true }),
+ ])
+ ).toEqual(["root reopened"]);
+ });
+
+ test("leaves AI results and human threads as they are", () => {
+ expect(
+ placedNames([
+ result("ai-earlier", ReviewRun_Type.AI, {
+ superseded: true,
+ resolved: true,
+ }),
+ root("human", { anchor: anchor(2, 2), resolved: true }),
+ ])
+ ).toEqual(["root ai-earlier", "root human"]);
+ });
+});
+
describe("excerpt and labels", () => {
test("slices the anchored lines regardless of line endings", () => {
expect(excerptLines("a\r\nb\nc\rd", { startLine: 2, endLine: 3 })).toEqual([
diff --git a/frontend/src/routes/project/plan-detail/components/threads/threadModel.ts b/frontend/src/routes/project/plan-detail/components/threads/threadModel.ts
index ce95ef3159..f591c2b913 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/threadModel.ts
+++ b/frontend/src/routes/project/plan-detail/components/threads/threadModel.ts
@@ -10,6 +10,7 @@ import { PositionSchema } from "@/types/proto-es/v1/common_pb";
import {
type IssueComment,
IssueComment_ThreadState,
+ ReviewRun_Type,
type StatementAnchor,
StatementAnchorSchema,
} from "@/types/proto-es/v1/issue_service_pb";
@@ -125,25 +126,6 @@ export function resolveAnchorState(
return trivialPlacement(anchor, targetSha256OfSpec(spec))?.state ?? "PENDING";
}
-// Whole-line anchors use zero columns and an inclusive end line. A
-// code-point range is end-exclusive, so an end at column 1 of a later line
-// covers nothing on that line.
-export function anchorLineRange(
- anchor: StatementAnchor
-): LineRange | undefined {
- const start = anchor.startPosition;
- const end = anchor.endPosition;
- if (!start || !end || start.line < 1 || end.line < start.line) {
- return undefined;
- }
- const wholeLine = start.column === 0 && end.column === 0;
- const endLine =
- !wholeLine && end.column === 1 && end.line > start.line
- ? end.line - 1
- : end.line;
- return { startLine: start.line, endLine: Math.max(endLine, start.line) };
-}
-
// A truncated preview may end in the middle of a line, including the empty
// line after a trailing newline. Only preceding lines have complete content.
export const completePreviewLineCount = (
@@ -211,6 +193,14 @@ const compareEditorThreads = (a: EditorThread, b: EditorThread): number =>
a.range.endLine - b.range.endLine ||
compareByCreateTime(a.thread.root, b.thread.root);
+// The statement shows only the latest standard rule review. A result a later
+// run superseded stays in the timeline, unless someone reopened it, since an
+// open thread holds the rollout.
+const isSupersededRuleResult = (root: IssueComment): boolean =>
+ root.reviewMetadata?.runType === ReviewRun_Type.RULE &&
+ root.reviewMetadata.superseded &&
+ root.threadState !== IssueComment_ThreadState.OPEN;
+
// Threads shown in the displayed statement, ordered by start line, then
// oldest first. A computed placement decides: CURRENT threads sit at their
// mapped range, which may differ from the anchor's when edits above shifted
@@ -228,6 +218,7 @@ export function selectEditorThreads(
const anchor = thread.root.statementAnchor;
if (!anchor) continue;
if (anchor.spec !== target.specId) continue;
+ if (isSupersededRuleResult(thread.root)) continue;
const placement =
placements.get(thread.root.name) ??
trivialPlacement(anchor, target.sheetSha256);
diff --git a/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.test.ts b/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.test.ts
new file mode 100644
index 0000000000..7aee48b3cc
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.test.ts
@@ -0,0 +1,36 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, expect, test, vi } from "vitest";
+
+const ISSUE = "projects/foo/issues/7";
+
+const mocks = vi.hoisted(() => ({
+ issueCommentsByIssue: {} as Record<string, unknown[]>,
+}));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: (
+ selector: (state: {
+ issueCommentsByIssue: Record<string, unknown[]>;
+ }) => unknown
+ ) => selector({ issueCommentsByIssue: mocks.issueCommentsByIssue }),
+}));
+
+import { useIssueThreadsLoaded } from "./useUnresolvedThreadCounts";
+
+beforeEach(() => {
+ mocks.issueCommentsByIssue = {};
+});
+
+test("reports the threads unloaded until the issue's comments load", () => {
+ const { result, rerender } = renderHook(() => useIssueThreadsLoaded(ISSUE));
+ expect(result.current).toBe(false);
+
+ mocks.issueCommentsByIssue = { [ISSUE]: [] };
+ rerender();
+ expect(result.current).toBe(true);
+});
+
+test("reports the threads loaded before an issue exists", () => {
+ const { result } = renderHook(() => useIssueThreadsLoaded(undefined));
+ expect(result.current).toBe(true);
+});
diff --git a/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.ts b/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.ts
index 71d133b8db..fa1ce47b06 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.ts
+++ b/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.ts
@@ -24,12 +24,21 @@ const useIssueThreads = (issueName: string | undefined) => {
return useMemo(() => groupThreads(comments), [comments]);
};
-// Every unresolved thread on the issue; zero before an issue exists.
+// Every unresolved thread on the issue; zero before an issue exists, and
+// before its comments have loaded.
export function useUnresolvedThreadTotal(issueName: string | undefined) {
const threads = useIssueThreads(issueName);
return useMemo(() => countUnresolvedThreads(threads), [threads]);
}
+// Whether the issue's comments have loaded at least once. A failed load leaves
+// it false.
+export function useIssueThreadsLoaded(issueName: string | undefined) {
+ return useAppStore(
+ (state) => !issueName || state.issueCommentsByIssue[issueName] !== undefined
+ );
+}
+
// Unresolved threads the statement editor shows for each of `specs`, so a
// change tab and its editor walker agree.
export function usePlacedUnresolvedThreadCounts(
diff --git a/frontend/src/routes/project/plan-detail/hooks/useRuleReviewRun.test.ts b/frontend/src/routes/project/plan-detail/hooks/useRuleReviewRun.test.ts
new file mode 100644
index 0000000000..5c65606326
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/hooks/useRuleReviewRun.test.ts
@@ -0,0 +1,285 @@
+import { Code, ConnectError } from "@connectrpc/connect";
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import {
+ IssueComment_ThreadState,
+ ReviewRun_Status,
+ ReviewRun_Type,
+} from "@/types/proto-es/v1/issue_service_pb";
+
+const ISSUE = "projects/foo/issues/7";
+const RULE_RUN = `${ISSUE}/reviewRuns/rule`;
+
+const mocks = vi.hoisted(() => ({
+ comments: [] as unknown[],
+ fetchIssueCommentThreads: vi.fn(),
+ getReviewRun: vi.fn(),
+}));
+
+vi.mock("@/api", () => ({
+ issueServiceClientConnect: { getReviewRun: mocks.getReviewRun },
+}));
+
+vi.mock("@/stores/app", () => {
+ const state = {
+ fetchIssueCommentThreads: mocks.fetchIssueCommentThreads,
+ getIssueComments: () => mocks.comments,
+ };
+ return {
+ useAppStore: Object.assign(
+ (selector: (s: typeof state) => unknown) => selector(state),
+ { getState: () => state }
+ ),
+ };
+});
+
+import { useRuleReviewRun } from "./useRuleReviewRun";
+
+const reviewRun = (status: ReviewRun_Status) => ({
+ name: RULE_RUN,
+ type: ReviewRun_Type.RULE,
+ status,
+ error: "",
+});
+
+const finding = (
+ runType: ReviewRun_Type,
+ threadState: IssueComment_ThreadState
+) => ({ reviewMetadata: { runType }, threadState });
+
+const flush = () =>
+ act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ mocks.getReviewRun.mockReset();
+ mocks.comments = [];
+ mocks.fetchIssueCommentThreads.mockResolvedValue(undefined);
+ mocks.getReviewRun.mockRejectedValue(
+ new ConnectError("not found", Code.NotFound)
+ );
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+test("reads nothing while disabled", async () => {
+ const { result } = renderHook(() =>
+ useRuleReviewRun({ enabled: false, issueName: ISSUE, reloadKey: "1" })
+ );
+ await flush();
+ expect(mocks.getReviewRun).not.toHaveBeenCalled();
+ expect(result.current.run).toBeUndefined();
+});
+
+test("reports a review that never ran", async () => {
+ const { result } = renderHook(() =>
+ useRuleReviewRun({ enabled: true, issueName: ISSUE, reloadKey: "1" })
+ );
+ await flush();
+ expect(mocks.getReviewRun).toHaveBeenCalledWith(
+ expect.objectContaining({ name: RULE_RUN }),
+ expect.anything()
+ );
+ expect(result.current.run).toBeNull();
+ expect(result.current.loadFailed).toBe(false);
+});
+
+test("polls an active run and reloads the threads when it completes", async () => {
+ mocks.comments = [
+ finding(ReviewRun_Type.RULE, IssueComment_ThreadState.OPEN),
+ finding(ReviewRun_Type.RULE, IssueComment_ThreadState.OPEN),
+ finding(ReviewRun_Type.RULE, IssueComment_ThreadState.RESOLVED),
+ finding(ReviewRun_Type.AI, IssueComment_ThreadState.OPEN),
+ ];
+ mocks.getReviewRun
+ .mockResolvedValueOnce(reviewRun(ReviewRun_Status.RUNNING))
+ .mockResolvedValueOnce(reviewRun(ReviewRun_Status.DONE));
+ const { result } = renderHook(() =>
+ useRuleReviewRun({ enabled: true, issueName: ISSUE, reloadKey: "1" })
+ );
+ await flush();
+ expect(result.current.run?.status).toBe(ReviewRun_Status.RUNNING);
+ expect(mocks.fetchIssueCommentThreads).not.toHaveBeenCalled();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+ expect(result.current.run?.status).toBe(ReviewRun_Status.DONE);
+ expect(result.current.openFindings).toBe(2);
+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledWith({
+ parent: ISSUE,
+ });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10_000);
+ });
+ expect(mocks.getReviewRun).toHaveBeenCalledTimes(2);
+});
+
+test("reads the run again when the reload key changes", async () => {
+ mocks.getReviewRun.mockResolvedValue(reviewRun(ReviewRun_Status.DONE));
+ const { rerender } = renderHook(
+ ({ reloadKey }) =>
+ useRuleReviewRun({ enabled: true, issueName: ISSUE, reloadKey }),
+ { initialProps: { reloadKey: "1" } }
+ );
+ await flush();
+ expect(mocks.getReviewRun).toHaveBeenCalledTimes(1);
+
+ rerender({ reloadKey: "2" });
+ await flush();
+ expect(mocks.getReviewRun).toHaveBeenCalledTimes(2);
+});
+
+test("reports a failed read", async () => {
+ mocks.getReviewRun.mockRejectedValue(
+ new ConnectError("boom", Code.Unavailable)
+ );
+ const { result } = renderHook(() =>
+ useRuleReviewRun({ enabled: true, issueName: ISSUE, reloadKey: "1" })
+ );
+ await flush();
+ expect(result.current.loadFailed).toBe(true);
+});
+
+const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+};
+
+test("marks the run stale until the plan's new run is read", async () => {
+ const next = deferred<ReturnType<typeof reviewRun>>();
+ mocks.getReviewRun
+ .mockResolvedValueOnce(reviewRun(ReviewRun_Status.DONE))
+ .mockReturnValueOnce(next.promise);
+ const { result, rerender } = renderHook(
+ ({ reloadKey }) =>
+ useRuleReviewRun({ enabled: true, issueName: ISSUE, reloadKey }),
+ { initialProps: { reloadKey: "1" } }
+ );
+ await flush();
+ expect(result.current.stale).toBe(false);
+
+ rerender({ reloadKey: "2" });
+ expect(result.current.run?.status).toBe(ReviewRun_Status.DONE);
+ expect(result.current.stale).toBe(true);
+
+ next.resolve(reviewRun(ReviewRun_Status.AVAILABLE));
+ await flush();
+ expect(result.current.run?.status).toBe(ReviewRun_Status.AVAILABLE);
+ expect(result.current.stale).toBe(false);
+});
+
+test("keeps the latest read when an earlier one answers last", async () => {
+ const earlier = deferred<ReturnType<typeof reviewRun>>();
+ mocks.getReviewRun
+ .mockReturnValueOnce(earlier.promise)
+ .mockResolvedValueOnce(reviewRun(ReviewRun_Status.AVAILABLE));
+ const { result } = renderHook(() =>
+ useRuleReviewRun({ enabled: true, issueName: ISSUE, reloadKey: "1" })
+ );
+ await act(async () => {
+ void result.current.reload();
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(result.current.run?.status).toBe(ReviewRun_Status.AVAILABLE);
+
+ earlier.resolve(reviewRun(ReviewRun_Status.DONE));
+ await flush();
+ expect(result.current.run?.status).toBe(ReviewRun_Status.AVAILABLE);
+});
+
+test("keeps a completed run stale until its findings are listed", async () => {
+ const listed = deferred<undefined>();
+ mocks.fetchIssueCommentThreads.mockReturnValueOnce(listed.promise);
+ mocks.getReviewRun
+ .mockResolvedValueOnce(reviewRun(ReviewRun_Status.RUNNING))
+ .mockResolvedValueOnce(reviewRun(ReviewRun_Status.DONE));
+ const { result } = renderHook(() =>
+ useRuleReviewRun({ enabled: true, issueName: ISSUE, reloadKey: "1" })
+ );
+ await flush();
+ expect(result.current.stale).toBe(false);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+ expect(result.current.run?.status).toBe(ReviewRun_Status.DONE);
+ expect(result.current.stale).toBe(true);
+
+ listed.resolve(undefined);
+ await flush();
+ expect(result.current.stale).toBe(false);
+});
+
+test("keeps a completed run stale when its findings fail to list", async () => {
+ mocks.fetchIssueCommentThreads.mockRejectedValueOnce(new Error("boom"));
+ mocks.getReviewRun
+ .mockResolvedValueOnce(reviewRun(ReviewRun_Status.RUNNING))
+ .mockResolvedValueOnce(reviewRun(ReviewRun_Status.DONE));
+ const { result } = renderHook(() =>
+ useRuleReviewRun({ enabled: true, issueName: ISSUE, reloadKey: "1" })
+ );
+ await flush();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(1);
+ expect(result.current.stale).toBe(true);
+});
+
+test("lists the findings of a run first read as done", async () => {
+ const listed = deferred<undefined>();
+ mocks.fetchIssueCommentThreads.mockReturnValueOnce(listed.promise);
+ mocks.getReviewRun.mockResolvedValue(reviewRun(ReviewRun_Status.DONE));
+ const { result, rerender } = renderHook(
+ ({ reloadKey }) =>
+ useRuleReviewRun({ enabled: true, issueName: ISSUE, reloadKey }),
+ { initialProps: { reloadKey: "1" } }
+ );
+ await flush();
+ expect(result.current.run?.status).toBe(ReviewRun_Status.DONE);
+ expect(result.current.stale).toBe(true);
+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(1);
+
+ listed.resolve(undefined);
+ await flush();
+ expect(result.current.stale).toBe(false);
+
+ // Reading the same execution again lists nothing.
+ rerender({ reloadKey: "2" });
+ await flush();
+ expect(mocks.getReviewRun).toHaveBeenCalledTimes(2);
+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(1);
+ expect(result.current.stale).toBe(false);
+});
+
+test("keeps an outdated run stale and polls it until its replacement starts", async () => {
+ mocks.getReviewRun
+ .mockResolvedValueOnce({
+ ...reviewRun(ReviewRun_Status.DONE),
+ outdated: true,
+ })
+ .mockResolvedValueOnce(reviewRun(ReviewRun_Status.AVAILABLE));
+ const { result } = renderHook(() =>
+ useRuleReviewRun({ enabled: true, issueName: ISSUE, reloadKey: "1" })
+ );
+ await flush();
+ expect(result.current.run?.status).toBe(ReviewRun_Status.DONE);
+ expect(result.current.stale).toBe(true);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+ expect(mocks.getReviewRun).toHaveBeenCalledTimes(2);
+ expect(result.current.run?.status).toBe(ReviewRun_Status.AVAILABLE);
+ expect(result.current.stale).toBe(false);
+});
diff --git a/frontend/src/routes/project/plan-detail/hooks/useRuleReviewRun.ts b/frontend/src/routes/project/plan-detail/hooks/useRuleReviewRun.ts
new file mode 100644
index 0000000000..d647b1fc41
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/hooks/useRuleReviewRun.ts
@@ -0,0 +1,163 @@
+import { create } from "@bufbuild/protobuf";
+import type { Timestamp } from "@bufbuild/protobuf/wkt";
+import { Code, ConnectError, createContextValues } from "@connectrpc/connect";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { issueServiceClientConnect } from "@/api";
+import { silentContextKey } from "@/api/context-key";
+import { useAppStore } from "@/stores/app";
+import {
+ GetReviewRunRequestSchema,
+ IssueComment_ThreadState,
+ type ReviewRun,
+ ReviewRun_Status,
+ ReviewRun_Type,
+} from "@/types/proto-es/v1/issue_service_pb";
+
+const POLL_INTERVAL_MS = 2000;
+const EMPTY_ISSUE = "";
+
+const isActive = (run: ReviewRun | null | undefined) =>
+ run?.status === ReviewRun_Status.AVAILABLE ||
+ run?.status === ReviewRun_Status.RUNNING;
+
+const sameTime = (a: Timestamp | undefined, b: Timestamp | undefined) =>
+ a?.seconds === b?.seconds && a?.nanos === b?.nanos;
+
+// Whether two reads show the same execution in the same status. The slot
+// restarts its create time on every reset and stamps an end time on every
+// completion.
+const sameExecution = (a: ReviewRun | null | undefined, b: ReviewRun) =>
+ !!a &&
+ a.status === b.status &&
+ sameTime(a.createTime, b.createTime) &&
+ sameTime(a.endTime, b.endTime);
+
+export type RuleReviewRunState = {
+ // undefined while loading; null when the review never ran on the issue.
+ run: ReviewRun | null | undefined;
+ // True while `run` may not match the plan's SQL: the plan changed after it
+ // was read, the server reports it outdated, or it shows a completion whose
+ // findings are not yet listed.
+ stale: boolean;
+ loadFailed: boolean;
+ openFindings: number;
+ reload: () => Promise<void>;
+};
+
+// The issue's standard rule review run, read again whenever `reloadKey`
+// changes and polled while it is queued or running. The server starts the
+// review wherever it runs the plan checks, so the caller keys a reload on the
+// same events.
+export function useRuleReviewRun({
+ enabled,
+ issueName,
+ reloadKey,
+}: {
+ enabled: boolean;
+ issueName: string | undefined;
+ reloadKey: string;
+}): RuleReviewRunState {
+ const reviewRunName =
+ enabled && issueName ? `${issueName}/reviewRuns/rule` : undefined;
+ const [run, setRun] = useState<ReviewRun | null | undefined>(undefined);
+ const [readKey, setReadKey] = useState<string | undefined>(undefined);
+ const [loadFailed, setLoadFailed] = useState(false);
+ const [findingsPending, setFindingsPending] = useState(false);
+ // Only the latest read lands: one it overtook would bring back an older run.
+ const latestRead = useRef(0);
+ const lastRun = useRef<ReviewRun | null | undefined>(undefined);
+
+ const reload = useCallback(async () => {
+ if (!reviewRunName) return;
+ const read = ++latestRead.current;
+ try {
+ const resp = await issueServiceClientConnect.getReviewRun(
+ create(GetReviewRunRequestSchema, { name: reviewRunName }),
+ { contextValues: createContextValues().set(silentContextKey, true) }
+ );
+ if (read !== latestRead.current) return;
+ // A run posts its findings with its DONE, so a DONE execution this hook
+ // has not seen may come with comments the page has not listed, even on
+ // the first read: the page's comment load may predate the completion.
+ // Set with the run, so no render shows it completed with old findings.
+ if (
+ resp.status === ReviewRun_Status.DONE &&
+ !sameExecution(lastRun.current, resp)
+ ) {
+ setFindingsPending(true);
+ }
+ lastRun.current = resp;
+ setRun(resp);
+ setReadKey(reloadKey);
+ setLoadFailed(false);
+ } catch (error) {
+ if (read !== latestRead.current) return;
+ if (ConnectError.from(error).code === Code.NotFound) {
+ lastRun.current = null;
+ setRun(null);
+ setReadKey(reloadKey);
+ setLoadFailed(false);
+ } else {
+ setLoadFailed(true);
+ }
+ }
+ }, [reloadKey, reviewRunName]);
+
+ useEffect(() => {
+ latestRead.current++;
+ lastRun.current = undefined;
+ setRun(undefined);
+ setReadKey(undefined);
+ setLoadFailed(false);
+ setFindingsPending(false);
+ }, [reviewRunName]);
+
+ useEffect(() => {
+ void reload();
+ }, [reload]);
+
+ // Each poll stores a new run object, which schedules the next poll. An
+ // outdated run is polled too, until the server starts its replacement.
+ useEffect(() => {
+ if (!isActive(run) && !run?.outdated) return;
+ const timer = window.setTimeout(() => void reload(), POLL_INTERVAL_MS);
+ return () => window.clearTimeout(timer);
+ }, [reload, run]);
+
+ // A run posts its findings as comments when it completes; re-list them then
+ // so they appear without waiting for the page's thread refresh. A failed
+ // re-list leaves the findings pending.
+ useEffect(() => {
+ if (!findingsPending || !issueName) return;
+ let current = true;
+ void useAppStore
+ .getState()
+ .fetchIssueCommentThreads({ parent: issueName })
+ .then(() => {
+ if (current) setFindingsPending(false);
+ })
+ .catch(() => undefined);
+ return () => {
+ current = false;
+ };
+ }, [findingsPending, issueName]);
+
+ const comments = useAppStore((state) =>
+ state.getIssueComments(issueName ?? EMPTY_ISSUE)
+ );
+ const openFindings = useMemo(
+ () =>
+ comments.filter(
+ (comment) =>
+ comment.reviewMetadata?.runType === ReviewRun_Type.RULE &&
+ comment.threadState === IssueComment_ThreadState.OPEN
+ ).length,
+ [comments]
+ );
+
+ const stale = readKey !== reloadKey || findingsPending || !!run?.outdated;
+ return useMemo(
+ () => ({ run, stale, loadFailed, openFindings, reload }),
+ [loadFailed, openFindings, reload, run, stale]
+ );
+}
diff --git a/frontend/src/routes/project/plan-detail/hooks/useSqlReviewV2.test.tsx b/frontend/src/routes/project/plan-detail/hooks/useSqlReviewV2.test.tsx
new file mode 100644
index 0000000000..f8d2ecd659
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/hooks/useSqlReviewV2.test.tsx
@@ -0,0 +1,153 @@
+import { renderHook } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ type ReviewRun,
+ ReviewRun_Status,
+} from "@/types/proto-es/v1/issue_service_pb";
+
+const mocks = vi.hoisted(() => ({
+ gate: true,
+ page: {} as Record<string, unknown>,
+ permissions: new Set<string>(),
+ ruleReview: {
+ run: null,
+ stale: false,
+ loadFailed: false,
+ openFindings: 0,
+ } as unknown,
+ threadsLoaded: true,
+ unresolvedThreads: 2,
+ useRuleReviewRun: vi.fn(),
+}));
+
+vi.mock("@/hooks/useProjectByName", () => ({
+ useProjectByName: () => ({ name: "projects/foo" }),
+}));
+
+vi.mock("@/utils", () => ({
+ hasProjectPermissionV2: (_project: unknown, permission: string) =>
+ mocks.permissions.has(permission),
+}));
+
+vi.mock("@/utils/featureGates", () => ({
+ sqlReviewV2Enabled: () => mocks.gate,
+}));
+
+vi.mock("../components/threads/useUnresolvedThreadCounts", () => ({
+ useIssueThreadsLoaded: () => mocks.threadsLoaded,
+ useUnresolvedThreadTotal: () => mocks.unresolvedThreads,
+}));
+
+vi.mock("../shell/PlanDetailContext", () => ({
+ usePlanDetailContext: () => mocks.page,
+}));
+
+vi.mock("./useRuleReviewRun", () => ({
+ useRuleReviewRun: mocks.useRuleReviewRun,
+}));
+
+import {
+ SqlReviewV2Provider,
+ useSqlReviewV2,
+ withRuleReview,
+} from "./useSqlReviewV2";
+
+const wrapper = ({ children }: { children: ReactNode }) => (
+ <SqlReviewV2Provider>{children}</SqlReviewV2Provider>
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.gate = true;
+ mocks.permissions = new Set(["bb.reviewRuns.get"]);
+ mocks.threadsLoaded = true;
+ mocks.page = {
+ issue: { name: "projects/foo/issues/7" },
+ plan: { updateTime: { seconds: 9n, nanos: 1 } },
+ projectId: "foo",
+ };
+ mocks.useRuleReviewRun.mockReturnValue(mocks.ruleReview);
+});
+
+describe("SqlReviewV2Provider", () => {
+ test("provides the open threads and the rule review", () => {
+ const { result } = renderHook(() => useSqlReviewV2(), { wrapper });
+ expect(result.current).toEqual({
+ unresolvedThreads: 2,
+ threadsLoaded: true,
+ ruleReview: mocks.ruleReview,
+ });
+ expect(mocks.useRuleReviewRun).toHaveBeenCalledWith({
+ enabled: true,
+ issueName: "projects/foo/issues/7",
+ reloadKey: "9:1",
+ });
+ });
+
+ test("still counts threads without permission to read the review", () => {
+ mocks.permissions.clear();
+ const { result } = renderHook(() => useSqlReviewV2(), { wrapper });
+ expect(result.current).toEqual({
+ unresolvedThreads: 2,
+ threadsLoaded: true,
+ });
+ expect(mocks.useRuleReviewRun).toHaveBeenCalledWith(
+ expect.objectContaining({ enabled: false })
+ );
+ });
+
+ test("says when the threads have not loaded", () => {
+ mocks.threadsLoaded = false;
+ const { result } = renderHook(() => useSqlReviewV2(), { wrapper });
+ expect(result.current?.threadsLoaded).toBe(false);
+ });
+
+ test.each([
+ [
+ "SQL Review V2 is off",
+ () => {
+ mocks.gate = false;
+ },
+ ],
+ [
+ "the plan has no issue",
+ () => {
+ mocks.page.issue = undefined;
+ },
+ ],
+ ])("provides nothing when %s", (_, arrange) => {
+ arrange();
+ const { result } = renderHook(() => useSqlReviewV2(), { wrapper });
+ expect(result.current).toBeUndefined();
+ });
+});
+
+describe("withRuleReview", () => {
+ const checks = { error: 0, running: 0, success: 1, total: 1, warning: 0 };
+ const run = (status: ReviewRun_Status) => ({ status }) as ReviewRun;
+
+ test("counts a queued or running review as a running check", () => {
+ for (const status of [ReviewRun_Status.AVAILABLE, ReviewRun_Status.RUNNING]) {
+ expect(withRuleReview(checks, run(status))).toEqual({
+ ...checks,
+ running: 1,
+ total: 2,
+ });
+ }
+ });
+
+ test("counts a failed review as a failed check", () => {
+ expect(withRuleReview(checks, run(ReviewRun_Status.FAILED))).toEqual({
+ ...checks,
+ error: 1,
+ total: 2,
+ });
+ });
+
+ test("leaves the checks alone for a completed or absent review", () => {
+ expect(withRuleReview(checks, run(ReviewRun_Status.DONE))).toBe(checks);
+ expect(withRuleReview(checks, null)).toBe(checks);
+ expect(withRuleReview(checks, undefined)).toBe(checks);
+ });
+});
diff --git a/frontend/src/routes/project/plan-detail/hooks/useSqlReviewV2.tsx b/frontend/src/routes/project/plan-detail/hooks/useSqlReviewV2.tsx
new file mode 100644
index 0000000000..bc89acd1a0
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/hooks/useSqlReviewV2.tsx
@@ -0,0 +1,91 @@
+import { createContext, type ReactNode, useContext, useMemo } from "react";
+import { useProjectByName } from "@/hooks/useProjectByName";
+import type { PlanCheckSummary } from "@/lib/plan/check";
+import {
+ type ReviewRun,
+ ReviewRun_Status,
+} from "@/types/proto-es/v1/issue_service_pb";
+import { hasProjectPermissionV2 } from "@/utils";
+import { sqlReviewV2Enabled } from "@/utils/featureGates";
+import {
+ useIssueThreadsLoaded,
+ useUnresolvedThreadTotal,
+} from "../components/threads/useUnresolvedThreadCounts";
+import { PROJECT_NAME_PREFIX } from "../shell/constants";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
+import { type RuleReviewRunState, useRuleReviewRun } from "./useRuleReviewRun";
+
+// What SQL Review V2 changes on the plan page: the standard rule review is one
+// of the checks, and every open thread holds the automatic rollout, as the
+// server's rollout creator does.
+export type SqlReviewV2State = {
+ unresolvedThreads: number;
+ // False until the issue's threads have loaded; `unresolvedThreads` reads
+ // zero until then.
+ threadsLoaded: boolean;
+ // Undefined without permission to read the review run.
+ ruleReview?: RuleReviewRunState;
+};
+
+const SqlReviewV2Context = createContext<SqlReviewV2State | undefined>(
+ undefined
+);
+
+// Provides one rule review poll for the whole page. The value is undefined
+// where SQL Review V2 is off or before the plan has an issue.
+export function SqlReviewV2Provider({ children }: { children: ReactNode }) {
+ const page = usePlanDetailContext();
+ const project = useProjectByName(`${PROJECT_NAME_PREFIX}${page.projectId}`);
+ const enabled = sqlReviewV2Enabled() && !!page.issue;
+ const canReadReview =
+ enabled && hasProjectPermissionV2(project, "bb.reviewRuns.get");
+ const updateTime = page.plan.updateTime;
+ // The server starts the rule review whenever the plan's SQL changes.
+ const ruleReview = useRuleReviewRun({
+ enabled: canReadReview,
+ issueName: page.issue?.name,
+ reloadKey: `${updateTime?.seconds ?? ""}:${updateTime?.nanos ?? ""}`,
+ });
+ const unresolvedThreads = useUnresolvedThreadTotal(page.issue?.name);
+ const threadsLoaded = useIssueThreadsLoaded(page.issue?.name);
+ const value = useMemo(
+ () =>
+ enabled
+ ? {
+ unresolvedThreads,
+ threadsLoaded,
+ ruleReview: canReadReview ? ruleReview : undefined,
+ }
+ : undefined,
+ [canReadReview, enabled, ruleReview, threadsLoaded, unresolvedThreads]
+ );
+ return (
+ <SqlReviewV2Context.Provider value={value}>
+ {children}
+ </SqlReviewV2Context.Provider>
+ );
+}
+
+export const useSqlReviewV2 = (): SqlReviewV2State | undefined =>
+ useContext(SqlReviewV2Context);
+
+// The plan checks with the rule review counted among them: a queued or running
+// review is a running check, and a failed one a failed check.
+export function withRuleReview(
+ checks: PlanCheckSummary,
+ run: ReviewRun | null | undefined
+): PlanCheckSummary {
+ switch (run?.status) {
+ case ReviewRun_Status.AVAILABLE:
+ case ReviewRun_Status.RUNNING:
+ return {
+ ...checks,
+ total: checks.total + 1,
+ running: checks.running + 1,
+ };
+ case ReviewRun_Status.FAILED:
+ return { ...checks, total: checks.total + 1, error: checks.error + 1 };
+ default:
+ return checks;
+ }
+}
diff --git a/frontend/src/types/proto-es/v1/issue_service_pb.d.ts b/frontend/src/types/proto-es/v1/issue_service_pb.d.ts
index 2cf09982e1..e35304fec7 100644
--- a/frontend/src/types/proto-es/v1/issue_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/issue_service_pb.d.ts
@@ -1091,6 +1091,14 @@ export declare type IssueComment_ReviewMetadata = Message<"bytebase.v1.IssueComm
* @generated from field: repeated string targets = 4;
*/
targets: string[];
+
+ /**
+ * A later run of the same reviewer has completed, so the result is not
+ * from the latest review, whatever its thread state.
+ *
+ * @generated from field: bool superseded = 5;
+ */
+ superseded: boolean;
};
/**
@@ -1405,6 +1413,15 @@ export declare type ReviewRun = Message<"bytebase.v1.ReviewRun"> & {
* @generated from field: string error = 6;
*/
error: string;
+
+ /**
+ * Whether the plan's SQL changed after this run started, so the run
+ * reviews an earlier version of it. The server starts a new run before it
+ * creates the rollout automatically.
+ *
+ * @generated from field: bool outdated = 7;
+ */
+ outdated: boolean;
};
/**
diff --git a/frontend/src/types/proto-es/v1/issue_service_pb.js b/frontend/src/types/proto-es/v1/issue_service_pb.js
index 57c7f467a0..3dc73647e7 100644
--- a/frontend/src/types/proto-es/v1/issue_service_pb.js
+++ b/frontend/src/types/proto-es/v1/issue_service_pb.js
@@ -19,7 +19,7 @@ import { file_v1_review_rule } from "./review_rule_pb";
* Describes the file v1/issue_service.proto.
*/
export const file_v1_issue_service = /*@__PURE__*/
- fileDesc("ChZ2MS9pc3N1ZV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSJKCg9HZXRJc3N1ZVJlcXVlc3QSKAoEbmFtZRgBIAEoCUIa4EEC+kEUChJieXRlYmFzZS5jb20vSXNzdWUSDQoFZm9yY2UYAiABKAgiagoSQ3JlYXRlSXNzdWVSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBImCgVpc3N1ZRgCIAEoCzISLmJ5dGViYXNlLnYxLklzc3VlQgPgQQIimQEKEUxpc3RJc3N1ZXNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkSDQoFcXVlcnkYBSABKAkSEAoIb3JkZXJfYnkYBiABKAkiUQoSTGlzdElzc3Vlc1Jlc3BvbnNlEiIKBmlzc3VlcxgBIAMoCzISLmJ5dGViYXNlLnYxLklzc3VlEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSKCAQoTU2VhcmNoSXNzdWVzUmVxdWVzdBITCgZwYXJlbnQYASABKAlCA+BBAhIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkSDQoFcXVlcnkYBSABKAkSEAoIb3JkZXJfYnkYBiABKAkiUwoUU2VhcmNoSXNzdWV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J5QXBwcm92YWwSoQEKDEdldFJldmlld1J1bhIgLmJ5dGViYXNlLnYxLkdldFJldmlld1J1blJlcXVlc3QaFi5ieXRlYmFzZS52MS5SZXZpZXdSdW4iV9pBBG5hbWWK6jARYmIucmV2aWV3UnVucy5nZXSQ6jABoOowAYLT5JMCLRIrL3YxL3tuYW1lPXByb2plY3RzLyovaXNzdWVzLyovcmV2aWV3UnVucy8qfRKmAQoJUnVuUmV2aWV3Eh0uYnl0ZWJhc2UudjEuUnVuUmV2aWV3UmVxdWVzdBoWLmJ5dGViYXNlLnYxLlJldmlld1J1biJi2kEEbmFtZYrqMBFiYi5yZXZpZXdSdW5zLnJ1bpDqMAGY6jABoOowAoLT5JMCNDoBKiIvL3YxL3tuYW1lPXByb2plY3RzLyovaXNzdWVzLyovcmV2aWV3UnVucy8qfTpydW5CpwEKD2NvbS5ieXRlYmFzZS52MUIRSXNzdWVTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_google_type_expr, file_v1_annotation, file_v1_common, file_v1_plan_service, file_v1_review_rule]);
+ fileDesc("ChZ2MS9pc3N1ZV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSJKCg9HZXRJc3N1ZVJlcXVlc3QSKAoEbmFtZRgBIAEoCUIa4EEC+kEUChJieXRlYmFzZS5jb20vSXNzdWUSDQoFZm9yY2UYAiABKAgiagoSQ3JlYXRlSXNzdWVSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXR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cm9qZWN0cy8qL2lzc3Vlcy8qL3Jldmlld1J1bnMvKn06cnVuQqcBCg9jb20uYnl0ZWJhc2UudjFCEUlzc3VlU2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_google_type_expr, file_v1_annotation, file_v1_common, file_v1_plan_service, file_v1_review_rule]);
/**
* Describes the message bytebase.v1.GetIssueRequest.
diff --git a/frontend/src/utils/featureGates.ts b/frontend/src/utils/featureGates.ts
index a337e3bddf..b58801e311 100644
--- a/frontend/src/utils/featureGates.ts
+++ b/frontend/src/utils/featureGates.ts
@@ -1,12 +1,13 @@
import { isDev } from "./util";
-// SQL Review V2 is dark-launched: nothing triggers review runs yet and their
-// results do not render, so its settings stay on the Vite dev server only. The
-// review rule policy API stays live.
+// SQL Review V2 is dark-launched: its settings and the standard rule review in
+// the plan page's Checks row stay on the Vite dev server only. The review rule
+// policy API stays live. On the server, the profile's SQLReviewV2 is the same
+// switch, on only in a dev build.
//
// `isDev()` is a build-time constant, so a release bundle folds every call to
-// `false` and drops the UI rather than hiding it. Flipping this to `true` is
-// the whole un-gate.
+// `false` and drops the UI rather than hiding it. Un-gating flips this and the
+// server switch together.
export const sqlReviewV2Enabled = (): boolean => isDev();
export const isSaaSOrDev = (isSaaSMode: boolean): boolean =>
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index 6ba5fadd27..62849a7933 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -22658,6 +22658,12 @@ components:
description: |-
Every database the result applies to, sorted.
Format: instances/{instance}/databases/{database}
+ superseded:
+ type: boolean
+ title: superseded
+ description: |-
+ A later run of the same reviewer has completed, so the result is not
+ from the latest review, whatever its thread state.
title: ReviewMetadata
additionalProperties: false
description: What a review result carries beyond its text.
@@ -27061,6 +27067,14 @@ components:
failed to execute (a platform problem, never the SQL — SQL problems are
review results on a DONE run).
readOnly: true
+ outdated:
+ type: boolean
+ title: outdated
+ description: |-
+ Whether the plan's SQL changed after this run started, so the run
+ reviews an earlier version of it. The server starts a new run before it
+ creates the rollout automatically.
+ readOnly: true
title: ReviewRun
additionalProperties: false
bytebase.v1.ReviewRun.Status:
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index 9e604f04d6..99326f17f4 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -2163,6 +2163,7 @@ issue. Results live in issue comments; the run carries none.
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
| error | [string](#string) | | Fatal execution error for the FAILED status, e.g. &#34;metadata not synced: instances/prod/databases/db1, db2, db3 (&#43;497 more)&#34;. Written by the executor or by the reaper. |
+| approval_input_version | [int64](#int64) | | The plan&#39;s PlanConfig.approval_input_version when the slot was reset: the version of the plan&#39;s SQL this run reviews. Completion keeps it. |
@@ -2299,7 +2300,8 @@ ReviewMetadata is what a review result carries beyond its text: which
reviewer posted it, what it was judged against, its priority, and the
databases it applies to. Results from the same reviewer are superseded
together: when a run completes, it resolves every OPEN root of its type
-in the transaction that posts the new results.
+and marks every earlier root of its type superseded, in the transaction
+that posts the new results.
| Field | Type | Label | Description |
@@ -2308,6 +2310,7 @@ in the transaction that posts the new results.
| rule_type | [ReviewRuleType](#bytebase-store-ReviewRuleType) | | The rule judged against. Set if and only if run_type is RULE. |
| priority | [IssueCommentPayload.ReviewMetadata.Priority](#bytebase-store-IssueCommentPayload-ReviewMetadata-Priority) | | A result merged across databases carries the highest priority among them. |
| targets | [string](#string) | repeated | Every database the result applies to, sorted. Always complete; the renderer collapses it when it equals the spec&#39;s target set. Format: instances/{instance}/databases/{database} |
+| superseded | [bool](#bool) | | A later run of the same reviewer has completed, so the result is not from the latest review. Set by that run whatever the thread state, and never cleared. |
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index 052a8522be..4f8f6aac7a 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -6254,6 +6254,14 @@ instances/prod/databases/db1, db2, db3 (&#43;497 more)&#34;. Written by the
executor or by the reaper. </p></td>
</tr>
+ <tr>
+ <td>approval_input_version</td>
+ <td><a href="#int64">int64</a></td>
+ <td></td>
+ <td><p>The plan&#39;s PlanConfig.approval_input_version when the slot was reset: the
+version of the plan&#39;s SQL this run reviews. Completion keeps it. </p></td>
+ </tr>
+
</tbody>
</table>
@@ -6545,7 +6553,7 @@ change. </p></td>
<h3 id="bytebase.store.IssueCommentPayload.ReviewMetadata">IssueCommentPayload.ReviewMetadata</h3>
- <p>ReviewMetadata is what a review result carries beyond its text: which</p><p>reviewer posted it, what it was judged against, its priority, and the</p><p>databases it applies to. Results from the same reviewer are superseded</p><p>together: when a run completes, it resolves every OPEN root of its type</p><p>in the transaction that posts the new results.</p>
+ <p>ReviewMetadata is what a review result carries beyond its text: which</p><p>reviewer posted it, what it was judged against, its priority, and the</p><p>databases it applies to. Results from the same reviewer are superseded</p><p>together: when a run completes, it resolves every OPEN root of its type</p><p>and marks every earlier root of its type superseded, in the transaction</p><p>that posts the new results.</p>
<table class="field-table">
@@ -6586,6 +6594,15 @@ renderer collapses it when it equals the spec&#39;s target set.
Format: instances/{instance}/databases/{database} </p></td>
</tr>
+ <tr>
+ <td>superseded</td>
+ <td><a href="#bool">bool</a></td>
+ <td></td>
+ <td><p>A later run of the same reviewer has completed, so the result is not
+from the latest review. Set by that run whatever the thread state, and
+never cleared. </p></td>
+ </tr>
+
</tbody>
</table>
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index 482a8bf3ab..1aaf3124d7 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -3687,6 +3687,7 @@ What a review result carries beyond its text.
| rule_type | [ReviewRuleType](#bytebase-v1-ReviewRuleType) | | The rule judged against. Set if and only if run_type is RULE. |
| priority | [IssueComment.ReviewMetadata.Priority](#bytebase-v1-IssueComment-ReviewMetadata-Priority) | | |
| targets | [string](#string) | repeated | Every database the result applies to, sorted. Format: instances/{instance}/databases/{database} |
+| superseded | [bool](#bool) | | A later run of the same reviewer has completed, so the result is not from the latest review, whatever its thread state. |
@@ -3842,6 +3843,7 @@ For example: creator == &#34;users/[email protected]&#34; &amp;&amp; status in [&#
| create_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | When the current run was triggered. Reset on every re-run. |
| end_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | When the run reached a terminal status. Unset while AVAILABLE or RUNNING. |
| error | [string](#string) | | Fatal execution error, set if and only if status is FAILED: the review failed to execute (a platform problem, never the SQL — SQL problems are review results on a DONE run). |
+| outdated | [bool](#bool) | | Whether the plan&#39;s SQL changed after this run started, so the run reviews an earlier version of it. The server starts a new run before it creates the rollout automatically. |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index 3256e2936a..c118ffcc75 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -11199,6 +11199,14 @@ Never accepted on create or update. </p></td>
Format: instances/{instance}/databases/{database} </p></td>
</tr>
+ <tr>
+ <td>superseded</td>
+ <td><a href="#bool">bool</a></td>
+ <td></td>
+ <td><p>A later run of the same reviewer has completed, so the result is not
+from the latest review, whatever its thread state. </p></td>
+ </tr>
+
</tbody>
</table>
@@ -11570,6 +11578,15 @@ failed to execute (a platform problem, never the SQL — SQL problems are
review results on a DONE run). </p></td>
</tr>
+ <tr>
+ <td>outdated</td>
+ <td><a href="#bool">bool</a></td>
+ <td></td>
+ <td><p>Whether the plan&#39;s SQL changed after this run started, so the run
+reviews an earlier version of it. The server starts a new run before it
+creates the rollout automatically. </p></td>
+ </tr>
+
</tbody>
</table>
diff --git a/proto/store/store/issue_comment.proto b/proto/store/store/issue_comment.proto
index 4a51548c53..0a06fce318 100644
--- a/proto/store/store/issue_comment.proto
+++ b/proto/store/store/issue_comment.proto
@@ -63,7 +63,8 @@ message IssueCommentPayload {
// reviewer posted it, what it was judged against, its priority, and the
// databases it applies to. Results from the same reviewer are superseded
// together: when a run completes, it resolves every OPEN root of its type
- // in the transaction that posts the new results.
+ // and marks every earlier root of its type superseded, in the transaction
+ // that posts the new results.
message ReviewMetadata {
// Priority says what resolving the thread means. It has no bearing on
// blocking: an OPEN root thread blocks whatever its priority, and a
@@ -91,6 +92,10 @@ message IssueCommentPayload {
// renderer collapses it when it equals the spec's target set.
// Format: instances/{instance}/databases/{database}
repeated string targets = 4;
+ // A later run of the same reviewer has completed, so the result is not
+ // from the latest review. Set by that run whatever the thread state, and
+ // never cleared.
+ bool superseded = 5;
}
// StatementAnchor records the anchored statement revision and range.
diff --git a/proto/store/store/review_run.proto b/proto/store/store/review_run.proto
index 16d1f37ec1..9ede9aae2c 100644
--- a/proto/store/store/review_run.proto
+++ b/proto/store/store/review_run.proto
@@ -34,4 +34,8 @@ message ReviewRunPayload {
// instances/prod/databases/db1, db2, db3 (+497 more)". Written by the
// executor or by the reaper.
string error = 1;
+
+ // The plan's PlanConfig.approval_input_version when the slot was reset: the
+ // version of the plan's SQL this run reviews. Completion keeps it.
+ int64 approval_input_version = 2;
}
diff --git a/proto/v1/v1/issue_service.proto b/proto/v1/v1/issue_service.proto
index ee639f5743..bb0e83e844 100644
--- a/proto/v1/v1/issue_service.proto
+++ b/proto/v1/v1/issue_service.proto
@@ -707,6 +707,9 @@ message IssueComment {
// Every database the result applies to, sorted.
// Format: instances/{instance}/databases/{database}
repeated string targets = 4;
+ // A later run of the same reviewer has completed, so the result is not
+ // from the latest review, whatever its thread state.
+ bool superseded = 5;
}
enum ThreadState {
@@ -836,6 +839,11 @@ message ReviewRun {
// failed to execute (a platform problem, never the SQL — SQL problems are
// review results on a DONE run).
string error = 6 [(google.api.field_behavior) = OUTPUT_ONLY];
+
+ // Whether the plan's SQL changed after this run started, so the run
+ // reviews an earlier version of it. The server starts a new run before it
+ // creates the rollout automatically.
+ bool outdated = 7 [(google.api.field_behavior) = OUTPUT_ONLY];
}
message GetReviewRunRequest {