Skip to content

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

feat(review): add a workspace switch for the AI SQL review (#21589)

h3n4lc8b2de1d27bc
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yaml
index c0cbbdcfa2..0a88f2aede 100644
--- a/backend/api/mcp/gen/openapi.yaml
+++ b/backend/api/mcp/gen/openapi.yaml
@@ -9218,6 +9218,14 @@ components:
version:
type: string
title: version
+ sqlReviewEnabled:
+ type: boolean
+ title: sql_review_enabled
+ description: |-
+ Whether the AI SQL review may run. It is off by default and is a consent
+ of its own beside `enabled`: a review sends the statements of a change to
+ the provider, and can send the schema of its target databases and their
+ table statistics.
title: AISetting
additionalProperties: false
bytebase.v1.AISetting.Provider:
@@ -9484,6 +9492,13 @@ components:
title: ai_enabled
description: Whether the workspace AI setting enables the AI agent.
readOnly: true
+ aiSqlReviewEnabled:
+ type: boolean
+ title: ai_sql_review_enabled
+ description: |-
+ Whether the workspace AI setting switches the AI SQL review on. A review
+ also needs `ai_enabled`.
+ readOnly: true
title: ActuatorInfo
additionalProperties: false
description: |-
diff --git a/backend/api/v1/actuator_service.go b/backend/api/v1/actuator_service.go
index c1f5161e15..539eeacb54 100644
--- a/backend/api/v1/actuator_service.go
+++ b/backend/api/v1/actuator_service.go
@@ -100,6 +100,10 @@ func actuatorAIEnabled(setting *storepb.AISetting, err error) bool {
return err == nil && setting != nil && setting.Enabled
}
+func actuatorAISQLReviewEnabled(setting *storepb.AISetting, err error) bool {
+ return err == nil && setting != nil && setting.SqlReviewEnabled
+}
+
func (s *ActuatorService) getServerInfo(ctx context.Context, workspaceID string) (*v1pb.ActuatorInfo, error) {
serverInfo := v1pb.ActuatorInfo{
Version: s.profile.Version,
@@ -115,11 +119,14 @@ func (s *ActuatorService) getServerInfo(ctx context.Context, workspaceID string)
if workspaceID != "" {
serverInfo.Workspace = common.FormatWorkspace(workspaceID)
serverInfo.McpSetting = actuatorMCPSetting(ctx, s.store, workspaceID)
- aiSetting, err := s.store.GetAISetting(ctx, workspaceID)
+ // Read past the setting cache like the review gates, so the switch shown
+ // to users without bb.settings.get matches what the review enforces.
+ aiSetting, err := s.store.GetAISettingUncached(ctx, workspaceID)
if err != nil {
slog.Error("failed to read the AI setting", slog.String("workspace", workspaceID), log.BBError(err))
}
serverInfo.AiEnabled = actuatorAIEnabled(aiSetting, err)
+ serverInfo.AiSqlReviewEnabled = actuatorAISQLReviewEnabled(aiSetting, err)
if s.sampleManager != nil {
serverInfo.Sample.Available = s.sampleManager.CheckAvailable(ctx) == nil
instances, err := s.sampleManager.ListInstances(ctx, workspaceID)
diff --git a/backend/api/v1/actuator_service_test.go b/backend/api/v1/actuator_service_test.go
index 9b0fb68172..1eab9e57fe 100644
--- a/backend/api/v1/actuator_service_test.go
+++ b/backend/api/v1/actuator_service_test.go
@@ -86,3 +86,21 @@ func TestActuatorAIEnabled(t *testing.T) {
})
}
}
+
+func TestActuatorAISQLReviewEnabled(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ setting *storepb.AISetting
+ err error
+ want bool
+ }{
+ {name: "absent setting"},
+ {name: "AI on without the review", setting: &storepb.AISetting{Enabled: true}},
+ {name: "the review switched on", setting: &storepb.AISetting{Enabled: true, SqlReviewEnabled: true}, want: true},
+ {name: "unreadable setting", setting: &storepb.AISetting{SqlReviewEnabled: true}, err: errors.New("read failed")},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ require.Equal(t, tc.want, actuatorAISQLReviewEnabled(tc.setting, tc.err))
+ })
+ }
+}
diff --git a/backend/api/v1/issue_service_review_run.go b/backend/api/v1/issue_service_review_run.go
index 35523c83a7..59d617a30b 100644
--- a/backend/api/v1/issue_service_review_run.go
+++ b/backend/api/v1/issue_service_review_run.go
@@ -10,6 +10,7 @@ import (
"github.com/bytebase/bytebase/backend/common"
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"
"github.com/bytebase/bytebase/backend/runner/plancheck"
"github.com/bytebase/bytebase/backend/store"
)
@@ -104,12 +105,12 @@ func (s *IssueService) RunReview(ctx context.Context, req *connect.Request[v1pb.
return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("the plan has no reviewable SQL"))
}
if reviewType == store.ReviewRunTypeAI {
- aiSetting, err := s.store.GetAISetting(ctx, common.GetWorkspaceIDFromContext(ctx))
+ aiSetting, err := s.store.GetAISettingUncached(ctx, common.GetWorkspaceIDFromContext(ctx))
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get AI setting"))
}
- if !aiSetting.Enabled {
- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("AI review requires AI to be enabled in the workspace setting"))
+ if err := aireview.CheckSetting(aiSetting); err != nil {
+ return nil, connect.NewError(connect.CodeFailedPrecondition, err)
}
}
diff --git a/backend/api/v1/issue_service_review_run_test.go b/backend/api/v1/issue_service_review_run_test.go
index 4ca35cf23d..f6ff19d533 100644
--- a/backend/api/v1/issue_service_review_run_test.go
+++ b/backend/api/v1/issue_service_review_run_test.go
@@ -181,3 +181,45 @@ func createReviewRunIssue(ctx context.Context, t *testing.T, stores *store.Store
require.NoError(t, err)
return issue
}
+
+func TestRunReviewRefusesAIReviewWhileItsSwitchIsOff(t *testing.T) {
+ t.Parallel()
+ ctx := issueServiceTestContext()
+ stores := setupIssueServiceTestStore(ctx, t)
+ _, issue := createIssueServiceApprovalIssue(ctx, t, stores)
+ service := newIssueServiceForTest(t, stores)
+
+ setAISetting := func(setting *storepb.AISetting) {
+ t.Helper()
+ _, err := stores.UpsertSetting(ctx, &store.SettingMessage{
+ Name: storepb.SettingName_AI,
+ Workspace: "default",
+ Value: setting,
+ })
+ require.NoError(t, err)
+ }
+ runAIReview := func() (*connect.Response[v1pb.ReviewRun], error) {
+ return service.RunReview(ctx, connect.NewRequest(&v1pb.RunReviewRequest{
+ Name: fmt.Sprintf("projects/project-a/issues/%d/reviewRuns/ai", issue.UID),
+ }))
+ }
+
+ setAISetting(&storepb.AISetting{Enabled: true})
+ _, err := runAIReview()
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))
+ require.ErrorContains(t, err, "AI SQL review is not enabled")
+ claimed, err := stores.ClaimAvailableReviewRuns(ctx, "replica")
+ require.NoError(t, err)
+ require.Empty(t, claimed, "a refused review creates no run")
+
+ setAISetting(&storepb.AISetting{Enabled: true, SqlReviewEnabled: true})
+ resp, err := runAIReview()
+ require.NoError(t, err)
+ require.Equal(t, v1pb.ReviewRun_AI, resp.Msg.Type)
+ require.Equal(t, v1pb.ReviewRun_AVAILABLE, resp.Msg.Status)
+
+ setAISetting(&storepb.AISetting{SqlReviewEnabled: true})
+ _, err = runAIReview()
+ require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))
+ require.ErrorContains(t, err, "AI is not enabled")
+}
diff --git a/backend/api/v1/setting_service.go b/backend/api/v1/setting_service.go
index 6e8e58fd1d..df7a7a3751 100644
--- a/backend/api/v1/setting_service.go
+++ b/backend/api/v1/setting_service.go
@@ -317,47 +317,7 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *connect.Req
}
storeSettingValue = storeSemanticTypeSetting
case storepb.SettingName_AI:
- if s.profile.SaaS {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("the AI setting cannot be changed in SaaS mode"))
- }
- if request.Msg.UpdateMask == nil {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("update mask is required"))
- }
- payload := convertAISetting(request.Msg.Setting.Value.GetAi())
- oldAISetting, err := s.store.GetAISetting(ctx, workspaceID)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to find AI setting: %v", err))
- }
- // Clone to avoid mutating the cached store object if validation fails later.
- oldAISetting = proto.CloneOf(oldAISetting)
-
- for _, path := range request.Msg.UpdateMask.Paths {
- switch path {
- case "value.ai.enabled":
- oldAISetting.Enabled = payload.Enabled
- case "value.ai.provider":
- oldAISetting.Provider = storepb.AISetting_Provider(payload.Provider)
- case "value.ai.endpoint":
- oldAISetting.Endpoint = payload.Endpoint
- case "value.ai.api_key":
- oldAISetting.ApiKey = payload.ApiKey
- case "value.ai.model":
- oldAISetting.Model = payload.Model
- default:
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid update mask path %v", path))
- }
- }
-
- if oldAISetting.Enabled {
- if oldAISetting.Endpoint == "" || oldAISetting.Model == "" {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("API endpoint and model are required"))
- }
- if oldAISetting.ApiKey == "" {
- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("API key is required"))
- }
- }
-
- storeSettingValue = oldAISetting
+ return s.updateAISetting(ctx, request, workspaceID)
case storepb.SettingName_ENVIRONMENT:
if serr := s.validateEnvironments(ctx, workspaceID, request.Msg.Setting.Value.GetEnvironment().GetEnvironments()); serr != nil {
return nil, serr
@@ -503,6 +463,113 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *connect.Req
return connect.NewResponse(settingMessage), nil
}
+// updateAISetting merges the update mask onto the locked AI setting row, so a
+// save cannot restore a field outside its mask from a stale read, such as
+// turning AI or the AI SQL review back on after another admin turned it off.
+// Workspace creation does not seed this row, so a missing row starts empty.
+func (s *SettingService) updateAISetting(ctx context.Context, request *connect.Request[v1pb.UpdateSettingRequest], workspaceID string) (*connect.Response[v1pb.Setting], error) {
+ if s.profile.SaaS {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("the AI setting cannot be changed in SaaS mode"))
+ }
+ if request.Msg.UpdateMask == nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("update mask is required"))
+ }
+ payload := convertAISetting(request.Msg.Setting.Value.GetAi())
+ paths := request.Msg.UpdateMask.Paths
+
+ if request.Msg.ValidateOnly {
+ stored, err := s.store.GetAISettingUncached(ctx, workspaceID)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to find AI setting: %v", err))
+ }
+ if _, err := mergeAISetting(stored, payload, paths); err != nil {
+ return nil, err
+ }
+ return connect.NewResponse(&v1pb.Setting{
+ Name: request.Msg.Setting.Name,
+ Value: request.Msg.Setting.Value,
+ }), nil
+ }
+
+ var lockedBefore *storepb.AISetting
+ setting, err := s.store.UpsertSettingAtomic(ctx, workspaceID, storepb.SettingName_AI, func(current proto.Message, existed bool) (proto.Message, error) {
+ stored, ok := current.(*storepb.AISetting)
+ if !ok {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("invalid setting value type for %s", storepb.SettingName_AI))
+ }
+ // A setting that did not exist has no before-image.
+ if existed {
+ lockedBefore = stored
+ }
+ return mergeAISetting(stored, payload, paths)
+ }, nil)
+
+ // Re-capture the audit before-image from the locked row the merge ran
+ // against, overwriting UpdateSetting's earlier pre-lock snapshot. A save
+ // that fails validation is audited too, so this runs before the error check.
+ if setServiceData, ok := getSetServiceDataFromContext(ctx); ok && lockedBefore != nil {
+ v1pbSetting, err := convertToSettingMessage(&store.SettingMessage{
+ Name: storepb.SettingName_AI,
+ Workspace: workspaceID,
+ Value: lockedBefore,
+ })
+ if err != nil {
+ slog.Warn("audit: failed to convert to v1.Setting", log.BBError(err))
+ }
+ p, err := anypb.New(v1pbSetting)
+ if err != nil {
+ slog.Warn("audit: failed to convert to anypb.Any", log.BBError(err))
+ }
+ setServiceData(p)
+ }
+ if err != nil {
+ var connectErr *connect.Error
+ if errors.As(err, &connectErr) {
+ return nil, err
+ }
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to set setting: %v", err))
+ }
+
+ settingMessage, err := convertToSettingMessage(setting)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to convert setting message: %v", err))
+ }
+ return connect.NewResponse(settingMessage), nil
+}
+
+// mergeAISetting applies the update mask to a copy of stored and validates
+// the result.
+func mergeAISetting(stored, payload *storepb.AISetting, paths []string) (*storepb.AISetting, error) {
+ merged := proto.CloneOf(stored)
+ for _, path := range paths {
+ switch path {
+ case "value.ai.enabled":
+ merged.Enabled = payload.GetEnabled()
+ case "value.ai.provider":
+ merged.Provider = payload.GetProvider()
+ case "value.ai.endpoint":
+ merged.Endpoint = payload.GetEndpoint()
+ case "value.ai.api_key":
+ merged.ApiKey = payload.GetApiKey()
+ case "value.ai.model":
+ merged.Model = payload.GetModel()
+ case "value.ai.sql_review_enabled":
+ merged.SqlReviewEnabled = payload.GetSqlReviewEnabled()
+ default:
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid update mask path %v", path))
+ }
+ }
+ if merged.Enabled {
+ if merged.Endpoint == "" || merged.Model == "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("API endpoint and model are required"))
+ }
+ if merged.ApiKey == "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("API key is required"))
+ }
+ }
+ return merged, nil
+}
+
// appIMSettingMaskPath maps each accepted APP_IM mask path to the provider it
// addresses. The paths do not name real proto fields — AppIMSetting holds one
// repeated `settings`, and AIP-161 does not let a mask address a repeated
diff --git a/backend/api/v1/setting_service_converter.go b/backend/api/v1/setting_service_converter.go
index 572184c9fd..1de6adc1c6 100644
--- a/backend/api/v1/setting_service_converter.go
+++ b/backend/api/v1/setting_service_converter.go
@@ -842,12 +842,13 @@ func convertAISetting(v1Setting *v1pb.AISetting) *storepb.AISetting {
}
return &storepb.AISetting{
- Enabled: v1Setting.Enabled,
- Provider: storepb.AISetting_Provider(v1Setting.Provider),
- Endpoint: v1Setting.Endpoint,
- ApiKey: v1Setting.ApiKey,
- Model: v1Setting.Model,
- Version: v1Setting.Version,
+ Enabled: v1Setting.Enabled,
+ Provider: storepb.AISetting_Provider(v1Setting.Provider),
+ Endpoint: v1Setting.Endpoint,
+ ApiKey: v1Setting.ApiKey,
+ Model: v1Setting.Model,
+ Version: v1Setting.Version,
+ SqlReviewEnabled: v1Setting.SqlReviewEnabled,
}
}
@@ -861,9 +862,10 @@ func convertToAISetting(storeSetting *storepb.AISetting) *v1pb.AISetting {
Provider: v1pb.AISetting_Provider(storeSetting.Provider),
Endpoint: storeSetting.Endpoint,
// Do not return the API key for security reasons.
- ApiKey: "",
- Model: storeSetting.Model,
- Version: storeSetting.Version,
+ ApiKey: "",
+ Model: storeSetting.Model,
+ Version: storeSetting.Version,
+ SqlReviewEnabled: storeSetting.SqlReviewEnabled,
}
}
diff --git a/backend/api/v1/setting_service_converter_test.go b/backend/api/v1/setting_service_converter_test.go
new file mode 100644
index 0000000000..30ebaaa5e7
--- /dev/null
+++ b/backend/api/v1/setting_service_converter_test.go
@@ -0,0 +1,40 @@
+package v1
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+func TestConvertAISetting(t *testing.T) {
+ t.Parallel()
+
+ stored := convertAISetting(&v1pb.AISetting{
+ Enabled: true,
+ Provider: v1pb.AISetting_CLAUDE,
+ Endpoint: "https://api.anthropic.com/v1/messages",
+ ApiKey: "key",
+ Model: "claude-sonnet-5-5",
+ Version: "2023-06-01",
+ SqlReviewEnabled: true,
+ })
+ require.Equal(t, &storepb.AISetting{
+ Enabled: true,
+ Provider: storepb.AISetting_CLAUDE,
+ Endpoint: "https://api.anthropic.com/v1/messages",
+ ApiKey: "key",
+ Model: "claude-sonnet-5-5",
+ Version: "2023-06-01",
+ SqlReviewEnabled: true,
+ }, stored)
+
+ returned := convertToAISetting(stored)
+ require.Empty(t, returned.ApiKey, "the key is never returned")
+ require.True(t, returned.SqlReviewEnabled)
+ require.True(t, returned.Enabled)
+
+ require.False(t, convertToAISetting(&storepb.AISetting{Enabled: true}).SqlReviewEnabled, "the review is off until it is switched on")
+}
diff --git a/backend/api/v1/setting_service_test.go b/backend/api/v1/setting_service_test.go
index d9aee70135..9c86f9e4be 100644
--- a/backend/api/v1/setting_service_test.go
+++ b/backend/api/v1/setting_service_test.go
@@ -348,3 +348,44 @@ func TestMergeAppIMSetting(t *testing.T) {
require.Equal(t, "feishu-secret", feishuSecret(before))
})
}
+
+func TestMergeAISetting(t *testing.T) {
+ stored := func() *storepb.AISetting {
+ return &storepb.AISetting{
+ Enabled: true,
+ Provider: storepb.AISetting_OPEN_AI,
+ Endpoint: "https://api.openai.com/v1",
+ ApiKey: "stored-key",
+ Model: "gpt-4o",
+ }
+ }
+
+ t.Run("a masked field changes and the rest stay", func(t *testing.T) {
+ before := stored()
+ merged, err := mergeAISetting(before, &storepb.AISetting{SqlReviewEnabled: true}, []string{"value.ai.sql_review_enabled"})
+ require.NoError(t, err)
+ want := stored()
+ want.SqlReviewEnabled = true
+ require.Equal(t, want.String(), merged.String())
+ require.False(t, before.SqlReviewEnabled)
+ })
+
+ t.Run("an enabled setting needs its endpoint, model and key", func(t *testing.T) {
+ _, err := mergeAISetting(stored(), &storepb.AISetting{}, []string{"value.ai.api_key"})
+ require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
+ _, err = mergeAISetting(&storepb.AISetting{}, &storepb.AISetting{Enabled: true}, []string{"value.ai.enabled"})
+ require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
+ })
+
+ t.Run("an unknown path is refused", func(t *testing.T) {
+ _, err := mergeAISetting(stored(), &storepb.AISetting{}, []string{"value.ai.version"})
+ require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
+ })
+
+ t.Run("a missing payload clears the masked fields", func(t *testing.T) {
+ merged, err := mergeAISetting(stored(), nil, []string{"value.ai.enabled", "value.ai.sql_review_enabled"})
+ require.NoError(t, err)
+ require.False(t, merged.Enabled)
+ require.Equal(t, "stored-key", merged.ApiKey)
+ })
+}
diff --git a/backend/generated-go/store/setting.pb.go b/backend/generated-go/store/setting.pb.go
index 685dd5dd24..95ba380434 100644
--- a/backend/generated-go/store/setting.pb.go
+++ b/backend/generated-go/store/setting.pb.go
@@ -1243,15 +1243,19 @@ func (x *AppIMSetting) GetSettings() []*AppIMSetting_IMSetting {
}
type AISetting struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"`
- Provider AISetting_Provider `protobuf:"varint,2,opt,name=provider,proto3,enum=bytebase.store.AISetting_Provider" json:"provider,omitempty"`
- Endpoint string `protobuf:"bytes,3,opt,name=endpoint,proto3" json:"endpoint,omitempty"`
- ApiKey string `protobuf:"bytes,4,opt,name=api_key,json=apiKey,proto3" json:"api_key,omitempty"`
- Model string `protobuf:"bytes,5,opt,name=model,proto3" json:"model,omitempty"`
- Version string `protobuf:"bytes,6,opt,name=version,proto3" json:"version,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"`
+ Provider AISetting_Provider `protobuf:"varint,2,opt,name=provider,proto3,enum=bytebase.store.AISetting_Provider" json:"provider,omitempty"`
+ Endpoint string `protobuf:"bytes,3,opt,name=endpoint,proto3" json:"endpoint,omitempty"`
+ ApiKey string `protobuf:"bytes,4,opt,name=api_key,json=apiKey,proto3" json:"api_key,omitempty"`
+ Model string `protobuf:"bytes,5,opt,name=model,proto3" json:"model,omitempty"`
+ Version string `protobuf:"bytes,6,opt,name=version,proto3" json:"version,omitempty"`
+ // Whether the AI SQL review may run. It is a consent of its own beside
+ // `enabled`, because a review sends the statements of a change to the
+ // provider and can send the schema of its target databases.
+ SqlReviewEnabled bool `protobuf:"varint,7,opt,name=sql_review_enabled,json=sqlReviewEnabled,proto3" json:"sql_review_enabled,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *AISetting) Reset() {
@@ -1326,6 +1330,13 @@ func (x *AISetting) GetVersion() string {
return ""
}
+func (x *AISetting) GetSqlReviewEnabled() bool {
+ if x != nil {
+ return x.SqlReviewEnabled
+ }
+ return false
+}
+
type EnvironmentSetting struct {
state protoimpl.MessageState `protogen:"open.v1"`
Environments []*EnvironmentSetting_Environment `protobuf:"bytes,1,rep,name=environments,proto3" json:"environments,omitempty"`
@@ -3101,14 +3112,15 @@ const file_store_setting_proto_rawDesc = "" +
"\x04lark\x18\x05 \x01(\v2!.bytebase.store.AppIMSetting.LarkH\x00R\x04lark\x12C\n" +
"\bdingtalk\x18\x06 \x01(\v2%.bytebase.store.AppIMSetting.DingTalkH\x00R\bdingtalk\x12:\n" +
"\x05teams\x18\a \x01(\v2\".bytebase.store.AppIMSetting.TeamsH\x00R\x05teamsB\t\n" +
- "\apayload\"\xa7\x02\n" +
+ "\apayload\"\xd5\x02\n" +
"\tAISetting\x12\x18\n" +
"\aenabled\x18\x01 \x01(\bR\aenabled\x12>\n" +
"\bprovider\x18\x02 \x01(\x0e2\".bytebase.store.AISetting.ProviderR\bprovider\x12\x1a\n" +
"\bendpoint\x18\x03 \x01(\tR\bendpoint\x12\x17\n" +
"\aapi_key\x18\x04 \x01(\tR\x06apiKey\x12\x14\n" +
"\x05model\x18\x05 \x01(\tR\x05model\x12\x18\n" +
- "\aversion\x18\x06 \x01(\tR\aversion\"[\n" +
+ "\aversion\x18\x06 \x01(\tR\aversion\x12,\n" +
+ "\x12sql_review_enabled\x18\a \x01(\bR\x10sqlReviewEnabled\"[\n" +
"\bProvider\x12\x18\n" +
"\x14PROVIDER_UNSPECIFIED\x10\x00\x12\v\n" +
"\aOPEN_AI\x10\x01\x12\n" +
diff --git a/backend/generated-go/store/setting_equal.pb.go b/backend/generated-go/store/setting_equal.pb.go
index c21664d13a..079cbfc9df 100644
--- a/backend/generated-go/store/setting_equal.pb.go
+++ b/backend/generated-go/store/setting_equal.pb.go
@@ -679,6 +679,9 @@ func (x *AISetting) Equal(y *AISetting) bool {
if x.Version != y.Version {
return false
}
+ if x.SqlReviewEnabled != y.SqlReviewEnabled {
+ return false
+ }
return true
}
diff --git a/backend/generated-go/v1/actuator_service.pb.go b/backend/generated-go/v1/actuator_service.pb.go
index 0ae5f8a3ee..d23d033c3d 100644
--- a/backend/generated-go/v1/actuator_service.pb.go
+++ b/backend/generated-go/v1/actuator_service.pb.go
@@ -154,9 +154,12 @@ type ActuatorInfo struct {
// The MCP (Model Context Protocol) setting in the current workspace.
McpSetting *MCPSetting `protobuf:"bytes,30,opt,name=mcp_setting,json=mcpSetting,proto3" json:"mcp_setting,omitempty"`
// Whether the workspace AI setting enables the AI agent.
- AiEnabled bool `protobuf:"varint,31,opt,name=ai_enabled,json=aiEnabled,proto3" json:"ai_enabled,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ AiEnabled bool `protobuf:"varint,31,opt,name=ai_enabled,json=aiEnabled,proto3" json:"ai_enabled,omitempty"`
+ // Whether the workspace AI setting switches the AI SQL review on. A review
+ // also needs `ai_enabled`.
+ AiSqlReviewEnabled bool `protobuf:"varint,32,opt,name=ai_sql_review_enabled,json=aiSqlReviewEnabled,proto3" json:"ai_sql_review_enabled,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *ActuatorInfo) Reset() {
@@ -308,6 +311,13 @@ func (x *ActuatorInfo) GetAiEnabled() bool {
return false
}
+func (x *ActuatorInfo) GetAiSqlReviewEnabled() bool {
+ if x != nil {
+ return x.AiSqlReviewEnabled
+ }
+ return false
+}
+
// Instance describes one provisioned sample instance.
type SampleInfo_Instance struct {
state protoimpl.MessageState `protogen:"open.v1"`
@@ -378,7 +388,7 @@ const file_v1_actuator_service_proto_rawDesc = "" +
"\binstance\x18\x01 \x01(\tB\x1d\xe0A\x03\xfaA\x17\n" +
"\x15bytebase.com/InstanceR\binstance\x12@\n" +
"\vexpire_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampB\x03\xe0A\x03R\n" +
- "expireTime\"\xf5\x06\n" +
+ "expireTime\"\xad\a\n" +
"\fActuatorInfo\x12\x1d\n" +
"\aversion\x18\x01 \x01(\tB\x03\xe0A\x03R\aversion\x12\"\n" +
"\n" +
@@ -399,7 +409,8 @@ const file_v1_actuator_service_proto_rawDesc = "" +
"\vmcp_setting\x18\x1e \x01(\v2\x17.bytebase.v1.MCPSettingB\x03\xe0A\x03R\n" +
"mcpSetting\x12\"\n" +
"\n" +
- "ai_enabled\x18\x1f \x01(\bB\x03\xe0A\x03R\taiEnabledJ\x04\b\x03\x10\x04J\x04\b\x05\x10\bJ\x04\b\t\x10\n" +
+ "ai_enabled\x18\x1f \x01(\bB\x03\xe0A\x03R\taiEnabled\x126\n" +
+ "\x15ai_sql_review_enabled\x18 \x01(\bB\x03\xe0A\x03R\x12aiSqlReviewEnabledJ\x04\b\x03\x10\x04J\x04\b\x05\x10\bJ\x04\b\t\x10\n" +
"J\x04\b\n" +
"\x10\vJ\x04\b\f\x10\rJ\x04\b\x0e\x10\x0fJ\x04\b\x10\x10\x14J\x04\b\x16\x10\x17J\x04\b\x19\x10\x1a2\x86\x01\n" +
"\x0fActuatorService\x12s\n" +
diff --git a/backend/generated-go/v1/actuator_service_equal.pb.go b/backend/generated-go/v1/actuator_service_equal.pb.go
index 8834faf945..cfa91f898f 100644
--- a/backend/generated-go/v1/actuator_service_equal.pb.go
+++ b/backend/generated-go/v1/actuator_service_equal.pb.go
@@ -113,5 +113,8 @@ func (x *ActuatorInfo) Equal(y *ActuatorInfo) bool {
if x.AiEnabled != y.AiEnabled {
return false
}
+ if x.AiSqlReviewEnabled != y.AiSqlReviewEnabled {
+ return false
+ }
return true
}
diff --git a/backend/generated-go/v1/setting_service.pb.go b/backend/generated-go/v1/setting_service.pb.go
index f90666acb2..6734895430 100644
--- a/backend/generated-go/v1/setting_service.pb.go
+++ b/backend/generated-go/v1/setting_service.pb.go
@@ -1755,15 +1755,20 @@ func (*Algorithm_Md5Mask) isAlgorithm_Mask() {}
func (*Algorithm_InnerOuterMask_) isAlgorithm_Mask() {}
type AISetting struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"`
- Provider AISetting_Provider `protobuf:"varint,2,opt,name=provider,proto3,enum=bytebase.v1.AISetting_Provider" json:"provider,omitempty"`
- Endpoint string `protobuf:"bytes,3,opt,name=endpoint,proto3" json:"endpoint,omitempty"`
- ApiKey string `protobuf:"bytes,4,opt,name=api_key,json=apiKey,proto3" json:"api_key,omitempty"`
- Model string `protobuf:"bytes,5,opt,name=model,proto3" json:"model,omitempty"`
- Version string `protobuf:"bytes,6,opt,name=version,proto3" json:"version,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled,omitempty"`
+ Provider AISetting_Provider `protobuf:"varint,2,opt,name=provider,proto3,enum=bytebase.v1.AISetting_Provider" json:"provider,omitempty"`
+ Endpoint string `protobuf:"bytes,3,opt,name=endpoint,proto3" json:"endpoint,omitempty"`
+ ApiKey string `protobuf:"bytes,4,opt,name=api_key,json=apiKey,proto3" json:"api_key,omitempty"`
+ Model string `protobuf:"bytes,5,opt,name=model,proto3" json:"model,omitempty"`
+ Version string `protobuf:"bytes,6,opt,name=version,proto3" json:"version,omitempty"`
+ // Whether the AI SQL review may run. It is off by default and is a consent
+ // of its own beside `enabled`: a review sends the statements of a change to
+ // the provider, and can send the schema of its target databases and their
+ // table statistics.
+ SqlReviewEnabled bool `protobuf:"varint,7,opt,name=sql_review_enabled,json=sqlReviewEnabled,proto3" json:"sql_review_enabled,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *AISetting) Reset() {
@@ -1838,6 +1843,13 @@ func (x *AISetting) GetVersion() string {
return ""
}
+func (x *AISetting) GetSqlReviewEnabled() bool {
+ if x != nil {
+ return x.SqlReviewEnabled
+ }
+ return false
+}
+
type EnvironmentSetting struct {
state protoimpl.MessageState `protogen:"open.v1"`
Environments []*EnvironmentSetting_Environment `protobuf:"bytes,1,rep,name=environments,proto3" json:"environments,omitempty"`
@@ -3723,14 +3735,15 @@ const file_v1_setting_service_proto_rawDesc = "" +
"\x15MASK_TYPE_UNSPECIFIED\x10\x00\x12\t\n" +
"\x05INNER\x10\x01\x12\t\n" +
"\x05OUTER\x10\x02B\x06\n" +
- "\x04mask\"\xaa\x02\n" +
+ "\x04mask\"\xd8\x02\n" +
"\tAISetting\x12\x18\n" +
"\aenabled\x18\x01 \x01(\bR\aenabled\x12;\n" +
"\bprovider\x18\x02 \x01(\x0e2\x1f.bytebase.v1.AISetting.ProviderR\bprovider\x12\x1a\n" +
"\bendpoint\x18\x03 \x01(\tR\bendpoint\x12\x1d\n" +
"\aapi_key\x18\x04 \x01(\tB\x04\xd0\xea0\x01R\x06apiKey\x12\x14\n" +
"\x05model\x18\x05 \x01(\tR\x05model\x12\x18\n" +
- "\aversion\x18\x06 \x01(\tR\aversion\"[\n" +
+ "\aversion\x18\x06 \x01(\tR\aversion\x12,\n" +
+ "\x12sql_review_enabled\x18\a \x01(\bR\x10sqlReviewEnabled\"[\n" +
"\bProvider\x12\x18\n" +
"\x14PROVIDER_UNSPECIFIED\x10\x00\x12\v\n" +
"\aOPEN_AI\x10\x01\x12\n" +
diff --git a/backend/generated-go/v1/setting_service_equal.pb.go b/backend/generated-go/v1/setting_service_equal.pb.go
index 885e1780f6..da32756ca9 100644
--- a/backend/generated-go/v1/setting_service_equal.pb.go
+++ b/backend/generated-go/v1/setting_service_equal.pb.go
@@ -800,6 +800,9 @@ func (x *AISetting) Equal(y *AISetting) bool {
if x.Version != y.Version {
return false
}
+ if x.SqlReviewEnabled != y.SqlReviewEnabled {
+ return false
+ }
return true
}
diff --git a/backend/plugin/aireview/model_ai.go b/backend/plugin/aireview/model_ai.go
index 5fffb24c7b..d15df6190f 100644
--- a/backend/plugin/aireview/model_ai.go
+++ b/backend/plugin/aireview/model_ai.go
@@ -28,20 +28,43 @@ const (
type settingModel struct {
setting *storepb.AISetting
+ // beforeCall runs before every provider call, the retries included.
+ beforeCall func(ctx context.Context) error
// sleep waits for the duration, or returns the context's error as soon as
// the context ends. Tests replace it so that a retry takes no time.
sleep func(ctx context.Context, wait time.Duration) error
}
+// ModelOption configures the Model that NewModel returns.
+type ModelOption func(*settingModel)
+
+// CheckBeforeEachCall runs check before every provider call, the retries of a
+// failed call included, and fails the call with its error. It is for a
+// condition that can change while a failed call waits to be sent again.
+func CheckBeforeEachCall(check func(ctx context.Context) error) ModelOption {
+ return func(m *settingModel) {
+ m.beforeCall = check
+ }
+}
+
// NewModel returns the Model behind the workspace AI setting.
-func NewModel(setting *storepb.AISetting) Model {
- return &settingModel{setting: setting, sleep: sleepContext}
+func NewModel(setting *storepb.AISetting, options ...ModelOption) Model {
+ m := &settingModel{setting: setting, sleep: sleepContext}
+ for _, option := range options {
+ option(m)
+ }
+ return m
}
// Chat sends the request again after a transient provider failure, so the
// review loop sees one model call however many attempts it takes.
func (m *settingModel) Chat(ctx context.Context, request *v1pb.AIChatRequest) (*v1pb.AIChatResponse, error) {
for retry := 0; ; retry++ {
+ if m.beforeCall != nil {
+ if err := m.beforeCall(ctx); err != nil {
+ return nil, err
+ }
+ }
response, err := ai.Chat(ctx, m.setting, request, ai.WithMaxOutputTokens(maxOutputTokens))
if err == nil {
return response, nil
diff --git a/backend/plugin/aireview/model_ai_retry_test.go b/backend/plugin/aireview/model_ai_retry_test.go
index c4e8b629f9..b75182986c 100644
--- a/backend/plugin/aireview/model_ai_retry_test.go
+++ b/backend/plugin/aireview/model_ai_retry_test.go
@@ -16,6 +16,7 @@ import (
"testing/synctest"
"time"
+ "github.com/pkg/errors"
"github.com/stretchr/testify/require"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
@@ -662,3 +663,45 @@ func TestSleepContext(t *testing.T) {
})
})
}
+
+func TestSettingModelChecksBeforeEveryAttempt(t *testing.T) {
+ t.Parallel()
+
+ refusal := errors.New("AI SQL review is not enabled in the workspace AI setting")
+
+ t.Run("a refusal before the first call", func(t *testing.T) {
+ t.Parallel()
+ provider := newScriptedProvider(t, providerReply{status: http.StatusOK, body: geminiOK})
+ model := NewModel(
+ &storepb.AISetting{Provider: storepb.AISetting_GEMINI, Endpoint: provider.url, Model: "test-model", ApiKey: testAPIKey},
+ CheckBeforeEachCall(func(context.Context) error { return refusal }),
+ )
+ _, err := model.Chat(context.Background(), chatRequest())
+ require.ErrorIs(t, err, refusal)
+ require.Zero(t, provider.requests.Load())
+ })
+
+ t.Run("a refusal while a failed call waits to retry", func(t *testing.T) {
+ t.Parallel()
+ provider := newScriptedProvider(t,
+ providerReply{status: http.StatusServiceUnavailable, body: geminiUnavailable},
+ providerReply{status: http.StatusOK, body: geminiOK},
+ )
+ model, recorder := newRetryModel(storepb.AISetting_GEMINI, provider.url)
+ var refused atomic.Bool
+ CheckBeforeEachCall(func(context.Context) error {
+ if refused.Load() {
+ return refusal
+ }
+ return nil
+ })(model)
+ model.sleep = func(ctx context.Context, wait time.Duration) error {
+ refused.Store(true)
+ return recorder.sleep(ctx, wait)
+ }
+
+ _, err := model.Chat(context.Background(), chatRequest())
+ require.ErrorIs(t, err, refusal)
+ require.Equal(t, int32(1), provider.requests.Load(), "no retry reaches the provider after the check refuses")
+ })
+}
diff --git a/backend/plugin/aireview/setting.go b/backend/plugin/aireview/setting.go
new file mode 100644
index 0000000000..5a979fc1a6
--- /dev/null
+++ b/backend/plugin/aireview/setting.go
@@ -0,0 +1,21 @@
+package aireview
+
+import (
+ "github.com/pkg/errors"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+// CheckSetting reports why the workspace AI setting does not allow an AI SQL
+// review, or nil when it does. The review has a switch of its own because it
+// sends the statements of a change to the provider and can send the schema of
+// its targets, which turning AI on for the SQL editor does not agree to.
+func CheckSetting(setting *storepb.AISetting) error {
+ if !setting.GetEnabled() {
+ return errors.New("AI is not enabled in the workspace setting")
+ }
+ if !setting.GetSqlReviewEnabled() {
+ return errors.New("AI SQL review is not enabled in the workspace AI setting")
+ }
+ return nil
+}
diff --git a/backend/plugin/aireview/setting_test.go b/backend/plugin/aireview/setting_test.go
new file mode 100644
index 0000000000..c2ba72e654
--- /dev/null
+++ b/backend/plugin/aireview/setting_test.go
@@ -0,0 +1,36 @@
+package aireview
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+func TestCheckSetting(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ setting *storepb.AISetting
+ want string
+ }{
+ {name: "no setting", setting: nil, want: "AI is not enabled"},
+ {name: "a new workspace", setting: &storepb.AISetting{}, want: "AI is not enabled"},
+ {name: "AI on for the SQL editor only", setting: &storepb.AISetting{Enabled: true}, want: "AI SQL review is not enabled"},
+ {name: "the switch on while AI is off", setting: &storepb.AISetting{SqlReviewEnabled: true}, want: "AI is not enabled"},
+ {name: "both on", setting: &storepb.AISetting{Enabled: true, SqlReviewEnabled: true}},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+ err := CheckSetting(test.setting)
+ if test.want == "" {
+ require.NoError(t, err)
+ return
+ }
+ require.ErrorContains(t, err, test.want)
+ })
+ }
+}
diff --git a/backend/runner/reviewrun/ai_review_executor.go b/backend/runner/reviewrun/ai_review_executor.go
index 3843f9694c..531723ac38 100644
--- a/backend/runner/reviewrun/ai_review_executor.go
+++ b/backend/runner/reviewrun/ai_review_executor.go
@@ -20,7 +20,7 @@ import (
// concurrently under aiReviewRunConcurrency.
type AIReviewExecutor struct {
store *store.Store
- newModel func(*storepb.AISetting) aireview.Model
+ newModel func(*storepb.AISetting, ...aireview.ModelOption) aireview.Model
// slots bounds the reviews in flight across every run of the executor.
slots reviewSlots
}
@@ -43,12 +43,11 @@ func (e *AIReviewExecutor) RunOnce(ctx context.Context, projectID string, issueU
if err != nil {
return nil, err
}
- aiSetting, err := e.store.GetAISetting(ctx, project.Workspace)
+ // A run created while the review was allowed must not reach the provider
+ // after it is switched off.
+ aiSetting, err := e.checkAISetting(ctx, project.Workspace)
if err != nil {
- return nil, errors.Wrapf(err, "failed to get AI setting")
- }
- if !aiSetting.GetEnabled() {
- return nil, errors.New("AI is not enabled in the workspace setting")
+ return nil, err
}
policy, err := e.store.GetEffectiveReviewAIPolicy(ctx, project.Workspace, projectID)
if err != nil {
@@ -83,7 +82,12 @@ func (e *AIReviewExecutor) RunOnce(ctx context.Context, projectID string, issueU
units = append(units, &aiReviewUnit{Check: checkTarget, Statement: statement})
}
- reviewer := aireview.NewReviewer(e.newModel(aiSetting))
+ // The setting is read again before every provider call, retries included,
+ // so switching the review off stops a run in flight at its next call.
+ reviewer := aireview.NewReviewer(e.newModel(aiSetting, aireview.CheckBeforeEachCall(func(ctx context.Context) error {
+ _, err := e.checkAISetting(ctx, project.Workspace)
+ return err
+ })))
results, reviewErrs := reviewUnits(ctx, e.slots, units, func(ctx context.Context, unit *aiReviewUnit) (*aireview.Result, error) {
// The schema is loaded once the unit holds its slot and dropped when
// the review ends, so the runs together hold at most one schema per
@@ -131,6 +135,20 @@ func (e *AIReviewExecutor) RunOnce(ctx context.Context, projectID string, issueU
return aiReviewComments(projectID, issueUID, results), nil
}
+// checkAISetting returns the workspace AI setting if it allows the review. It
+// reads past the setting cache, which only this process's writes refresh, so
+// a switch-off written anywhere else stops the review too.
+func (e *AIReviewExecutor) checkAISetting(ctx context.Context, workspace string) (*storepb.AISetting, error) {
+ setting, err := e.store.GetAISettingUncached(ctx, workspace)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get AI setting")
+ }
+ if err := aireview.CheckSetting(setting); err != nil {
+ return nil, err
+ }
+ return setting, nil
+}
+
// sheetStatement returns the sheet text, loaded once per run, and refuses a
// sheet over maxAIReviewSheetBytes.
func (e *AIReviewExecutor) sheetStatement(ctx context.Context, sheets map[string]string, sha256 string) (string, error) {
diff --git a/backend/runner/reviewrun/ai_review_executor_test.go b/backend/runner/reviewrun/ai_review_executor_test.go
index 6aeb391471..9d1cf521e9 100644
--- a/backend/runner/reviewrun/ai_review_executor_test.go
+++ b/backend/runner/reviewrun/ai_review_executor_test.go
@@ -37,7 +37,7 @@ func TestCISampleBoundsOnlyTheAIReview(t *testing.T) {
model := &findingModel{}
executor := &AIReviewExecutor{
store: stores,
- newModel: func(*storepb.AISetting) aireview.Model { return model },
+ newModel: func(*storepb.AISetting, ...aireview.ModelOption) aireview.Model { return model },
slots: semaphore.NewWeighted(aiReviewServerConcurrency),
}
reviewedDatabases := func() []string {
@@ -79,7 +79,7 @@ func TestAIReviewRunsShareTheServerLimit(t *testing.T) {
slots := &observedSlots{Weighted: semaphore.NewWeighted(limit), waiting: make(chan struct{}, total)}
executor := &AIReviewExecutor{
store: stores,
- newModel: func(*storepb.AISetting) aireview.Model { return model },
+ newModel: func(*storepb.AISetting, ...aireview.ModelOption) aireview.Model { return model },
slots: slots,
}
@@ -130,7 +130,7 @@ func setupReviewFixture(ctx context.Context, t *testing.T, issueCount int) (*sto
INSERT INTO project (resource_id, workspace, name) VALUES ('p', 'ws', 'P');
`)
require.NoError(t, err)
- _, err = stores.UpsertSetting(ctx, &store.SettingMessage{Name: storepb.SettingName_AI, Workspace: "ws", Value: &storepb.AISetting{Enabled: true}})
+ _, err = stores.UpsertSetting(ctx, &store.SettingMessage{Name: storepb.SettingName_AI, Workspace: "ws", Value: &storepb.AISetting{Enabled: true, SqlReviewEnabled: true}})
require.NoError(t, err)
rules, err := protojson.Marshal(&storepb.ReviewRulePolicy{Rules: []storepb.ReviewRuleType{storepb.ReviewRuleType_SYNTAX}})
require.NoError(t, err)
@@ -290,3 +290,71 @@ func send(t *testing.T, ch chan<- struct{}) {
t.Fatal("timed out waiting for a model call to release")
}
}
+
+func TestAIReviewExecutorChecksTheSettingAgain(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ db, stores, _ := testcontainer.NewMetadataDBWithCache(t, true)
+ _, 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)
+
+ 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/missing/databases/app"},
+ },
+ },
+ }},
+ },
+ 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)
+
+ setAISetting := func(setting *storepb.AISetting) {
+ t.Helper()
+ _, err := stores.UpsertSetting(ctx, &store.SettingMessage{
+ Name: storepb.SettingName_AI,
+ Workspace: "ws",
+ Value: setting,
+ })
+ require.NoError(t, err)
+ }
+ executor := NewAIReviewExecutor(stores)
+
+ setAISetting(&storepb.AISetting{Enabled: true})
+ _, err = executor.RunOnce(ctx, "p", issue.UID)
+ require.ErrorContains(t, err, "AI SQL review is not enabled")
+
+ // With the switch on the executor goes on to the target, which does not
+ // exist in this fixture.
+ setAISetting(&storepb.AISetting{Enabled: true, SqlReviewEnabled: true})
+ _, err = executor.RunOnce(ctx, "p", issue.UID)
+ require.Error(t, err)
+ require.NotContains(t, err.Error(), "is not enabled")
+
+ // A switch-off written outside this process leaves the cached copy on.
+ _, err = db.ExecContext(ctx, `UPDATE setting SET value = '{"enabled": true}' WHERE workspace = 'ws' AND name = 'AI'`)
+ require.NoError(t, err)
+ cached, err := stores.GetAISetting(ctx, "ws")
+ require.NoError(t, err)
+ require.True(t, cached.SqlReviewEnabled)
+ _, err = executor.RunOnce(ctx, "p", issue.UID)
+ require.ErrorContains(t, err, "AI SQL review is not enabled")
+}
diff --git a/backend/store/setting.go b/backend/store/setting.go
index d4730934c8..4c25c23a84 100644
--- a/backend/store/setting.go
+++ b/backend/store/setting.go
@@ -225,6 +225,20 @@ func (s *Store) GetAISetting(ctx context.Context, workspaceID string) (*storepb.
if err != nil {
return nil, err
}
+ return aiSettingValue(setting)
+}
+
+// GetAISettingUncached is GetAISetting past the setting cache, for a gate that
+// must see a write from outside this process.
+func (s *Store) GetAISettingUncached(ctx context.Context, workspaceID string) (*storepb.AISetting, error) {
+ setting, err := s.GetSettingUncached(ctx, workspaceID, storepb.SettingName_AI)
+ if err != nil {
+ return nil, err
+ }
+ return aiSettingValue(setting)
+}
+
+func aiSettingValue(setting *SettingMessage) (*storepb.AISetting, error) {
if setting == nil {
return &storepb.AISetting{}, nil
}
@@ -380,7 +394,7 @@ func (s *Store) ListSettings(ctx context.Context, find *FindSettingMessage) ([]*
// mutex (GetSettingUncached callers hit it on every read), and an
// unordered fill could pin a pre-commit snapshot over a newer published
// value. Publication happens only in GetSetting's fill, UpsertSetting,
- // and UpdateSettingAtomic — all ordered by settingPublishMu.
+ // and the atomic updates — all ordered by settingPublishMu.
return settingMessages, nil
}
@@ -405,27 +419,51 @@ func (s *Store) ListSettings(ctx context.Context, find *FindSettingMessage) ([]*
// caller that sets one field on current and returns it (RotateDirectorySyncToken)
// would erase everything else the row held.
func (s *Store) UpdateSettingAtomic(ctx context.Context, workspace string, name storepb.SettingName, apply func(current proto.Message) (proto.Message, error), postCommit func(current *SettingMessage)) (*SettingMessage, error) {
- return s.writeSettingAtomic(ctx, workspace, name, func(raw string) (proto.Message, error) {
- current, err := getSettingMessage(name)
- if err != nil {
- return nil, err
- }
- if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(raw), current); err != nil {
- return nil, errors.Wrapf(err, "failed to unmarshal setting %s", name)
- }
+ return s.writeSettingAtomic(ctx, workspace, name, false, func(current proto.Message, _ bool) (proto.Message, error) {
return apply(current)
}, postCommit)
}
-// writeSettingAtomic locks the row, asks next for the value to store, and
-// writes it in the same transaction.
-func (s *Store) writeSettingAtomic(ctx context.Context, workspace string, name storepb.SettingName, next func(raw string) (proto.Message, error), postCommit func(current *SettingMessage)) (*SettingMessage, error) {
+// UpsertSettingAtomic is UpdateSettingAtomic for a setting that workspace
+// creation does not seed: a missing row is inserted with the zero value in the
+// same transaction, so apply always merges onto the locked row. existed is
+// false only when this call inserted the row; a caller that raced the insert
+// waits for it to commit and gets the committed row with existed true.
+func (s *Store) UpsertSettingAtomic(ctx context.Context, workspace string, name storepb.SettingName, apply func(current proto.Message, existed bool) (proto.Message, error), postCommit func(current *SettingMessage)) (*SettingMessage, error) {
+ return s.writeSettingAtomic(ctx, workspace, name, true, apply, postCommit)
+}
+
+// writeSettingAtomic locks the row, asks apply for the value to store, and
+// writes it in the same transaction. With insertMissing, a missing row is
+// inserted first.
+func (s *Store) writeSettingAtomic(ctx context.Context, workspace string, name storepb.SettingName, insertMissing bool, apply func(current proto.Message, existed bool) (proto.Message, error), postCommit func(current *SettingMessage)) (*SettingMessage, error) {
tx, err := s.GetDB().BeginTx(ctx, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to begin transaction")
}
defer tx.Rollback()
+ existed := true
+ if insertMissing {
+ q := qb.Q().Space(`
+ INSERT INTO setting (name, workspace, value) VALUES (?, ?, '{}')
+ ON CONFLICT (workspace, name) DO NOTHING
+ `, name.String(), workspace)
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to build sql")
+ }
+ result, err := tx.ExecContext(ctx, query, args...)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to insert setting %s", name)
+ }
+ inserted, err := result.RowsAffected()
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to insert setting %s", name)
+ }
+ existed = inserted == 0
+ }
+
q := qb.Q().Space(`
SELECT value FROM setting WHERE workspace = ? AND name = ? FOR UPDATE
`, workspace, name.String())
@@ -440,7 +478,14 @@ func (s *Store) writeSettingAtomic(ctx context.Context, workspace string, name s
}
return nil, errors.Wrapf(err, "failed to lock setting %s", name)
}
- value, err := next(valueString)
+ current, err := getSettingMessage(name)
+ if err != nil {
+ return nil, err
+ }
+ if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(valueString), current); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal setting %s", name)
+ }
+ value, err := apply(current, existed)
if err != nil {
return nil, err
}
diff --git a/backend/store/setting_atomic_test.go b/backend/store/setting_atomic_test.go
index 95dd0abcc9..32f9bb6c30 100644
--- a/backend/store/setting_atomic_test.go
+++ b/backend/store/setting_atomic_test.go
@@ -189,6 +189,83 @@ func TestUpdateSettingAtomicMissingRow(t *testing.T) {
require.Contains(t, err.Error(), "not found")
}
+func TestUpsertSettingAtomicMergesConcurrentWritesOnAMissingRow(t *testing.T) {
+ t.Parallel()
+ ctx, db, s := newSettingAtomicFixture(t)
+
+ upsertAI := func(wantExisted bool, set func(*storepb.AISetting), before func()) error {
+ _, err := s.UpsertSettingAtomic(ctx, "default", storepb.SettingName_AI,
+ func(current proto.Message, existed bool) (proto.Message, error) {
+ setting, ok := current.(*storepb.AISetting)
+ if !ok {
+ return nil, errors.Errorf("unexpected type %T", current)
+ }
+ if existed != wantExisted {
+ return nil, errors.Errorf("existed is %t, want %t", existed, wantExisted)
+ }
+ set(setting)
+ before()
+ return setting, nil
+ }, nil)
+ return err
+ }
+
+ entered := make(chan struct{})
+ release := make(chan struct{})
+ firstResult := make(chan error, 1)
+ go func() {
+ firstResult <- upsertAI(false, func(setting *storepb.AISetting) { setting.SqlReviewEnabled = true }, func() {
+ close(entered)
+ <-release
+ })
+ }()
+ select {
+ case <-entered:
+ case <-time.After(15 * time.Second):
+ t.Fatal("first upsert never reached its apply callback")
+ }
+
+ secondResult := make(chan error, 1)
+ go func() {
+ secondResult <- upsertAI(true, func(setting *storepb.AISetting) { setting.Model = "second" }, func() {})
+ }()
+ // The second insert waits on the first's uncommitted row.
+ require.Eventually(t, func() bool {
+ var waiting bool
+ err := db.QueryRowContext(ctx, `
+ SELECT EXISTS (
+ SELECT 1
+ FROM pg_stat_activity
+ WHERE datname = current_database()
+ AND cardinality(pg_blocking_pids(pid)) > 0
+ AND query LIKE '%INSERT INTO setting%ON CONFLICT%'
+ )
+ `).Scan(&waiting)
+ return err == nil && waiting
+ }, 10*time.Second, 10*time.Millisecond)
+
+ close(release)
+ for _, result := range []chan error{firstResult, secondResult} {
+ select {
+ case err := <-result:
+ require.NoError(t, err)
+ case <-time.After(15 * time.Second):
+ t.Fatal("upsert did not complete; possible deadlock")
+ }
+ }
+
+ fresh, err := s.GetSettingUncached(ctx, "default", storepb.SettingName_AI)
+ require.NoError(t, err)
+ setting, ok := fresh.Value.(*storepb.AISetting)
+ require.True(t, ok)
+ require.True(t, setting.SqlReviewEnabled)
+ require.Equal(t, "second", setting.Model)
+ cached, err := s.GetAISetting(ctx, "default")
+ require.NoError(t, err)
+ require.True(t, cached.SqlReviewEnabled)
+ require.Equal(t, "second", cached.Model)
+}
+
// TestUpdateSettingAtomicPublishOrder pins that the setting cache is published
// in commit order: while one update is paused between its commit and its cache
// publish (test hook), a later update must not be able to commit and publish —
diff --git a/backend/tests/review_run_lifecycle_test.go b/backend/tests/review_run_lifecycle_test.go
index bf12b5b937..722ef09aa2 100644
--- a/backend/tests/review_run_lifecycle_test.go
+++ b/backend/tests/review_run_lifecycle_test.go
@@ -9,6 +9,7 @@ import (
"net/http/httptest"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -121,13 +122,29 @@ func TestCollision_RunReviewLifecycle(t *testing.T) {
afterB := listReviewRuns(ctx, t, ctl, projectBID)
a.Equal(beforeB, afterB, "project B review_run rows must be untouched by A's re-run")
- // With AI enabled but the model failing, the AI slot is created, claimed,
- // and fails honestly with the model's error.
brokenModel := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, `{"error": {"message": "quota exceeded"}}`, http.StatusServiceUnavailable)
}))
defer brokenModel.Close()
- setAISetting(ctx, t, ctl, brokenModel.URL)
+
+ setting := setAISetting(ctx, t, ctl, brokenModel.URL, false)
+ a.False(setting.GetValue().GetAi().GetSqlReviewEnabled())
+ _, err = runReview(ctx, ctl, issueA.Name, "ai")
+ a.Equal(connect.CodeFailedPrecondition, connect.CodeOf(err))
+ a.ErrorContains(err, "AI SQL review is not enabled")
+
+ // With the review switched on but the model failing, the AI slot is
+ // created, claimed, and fails honestly with the model's error.
+ setting = setAISetting(ctx, t, ctl, brokenModel.URL, true)
+ a.True(setting.GetValue().GetAi().GetSqlReviewEnabled())
+
+ // The server info follows a switch written outside the server too.
+ a.True(actuatorAISQLReviewEnabled(ctx, t, ctl))
+ setStoredAISQLReviewEnabled(ctx, t, ctl, false)
+ a.False(actuatorAISQLReviewEnabled(ctx, t, ctl))
+ setStoredAISQLReviewEnabled(ctx, t, ctl, true)
+ a.True(actuatorAISQLReviewEnabled(ctx, t, ctl))
+
aiRun, err := runReview(ctx, ctl, issueA.Name, "ai")
a.NoError(err)
a.Equal(v1pb.ReviewRun_AI, aiRun.Type)
@@ -181,7 +198,7 @@ func TestCollision_RunReviewLifecycle(t *testing.T) {
_, _ = w.Write([]byte(reply))
}))
defer model.Close()
- setAISetting(ctx, t, ctl, model.URL)
+ setAISetting(ctx, t, ctl, model.URL, true)
aiRun, err = runReview(ctx, ctl, issueA.Name, "ai")
a.NoError(err)
a.Equal(v1pb.ReviewRun_AVAILABLE, aiRun.Status)
@@ -208,31 +225,93 @@ func TestCollision_RunReviewLifecycle(t *testing.T) {
a.True(strings.HasSuffix(result.GetReviewMetadata().GetTargets()[0], fixture.DatabaseA.Name), "target %q", result.GetReviewMetadata().GetTargets()[0])
a.Equal(int32(1), result.GetStatementAnchor().GetStartPosition().GetLine())
a.Equal(v1pb.IssueComment_OPEN, result.GetThreadState())
+
+ // Switching the review off stops a run in flight at its next model call.
+ // This model answers its first call with a tool call, which asks for a
+ // second call, and the review is switched off in between.
+ var modelCalls atomic.Int32
+ switchedOff := make(chan error, 1)
+ switchingModel := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ if modelCalls.Add(1) == 1 {
+ _, err := ctl.settingServiceClient.UpdateSetting(ctx, connect.NewRequest(&v1pb.UpdateSettingRequest{
+ Setting: &v1pb.Setting{
+ Name: "settings/" + v1pb.Setting_AI.String(),
+ Value: &v1pb.SettingValue{Value: &v1pb.SettingValue_Ai{Ai: &v1pb.AISetting{}}},
+ },
+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"value.ai.sql_review_enabled"}},
+ }))
+ switchedOff <- err
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"candidates": [{"content": {"parts": [{"functionCall": {"name": "read", "args": {}}}]}}], "usageMetadata": {"totalTokenCount": 10}}`))
+ }))
+ defer switchingModel.Close()
+ setAISetting(ctx, t, ctl, switchingModel.URL, true)
+ _, err = runReview(ctx, ctl, issueA.Name, "ai")
+ a.NoError(err)
+ stoppedRow := waitReviewRunTerminal(ctx, t, ctl, projectAID, issueAUID, "AI")
+ select {
+ case err := <-switchedOff:
+ a.NoError(err)
+ default:
+ a.Fail("the model was never called")
+ }
+ a.Equal("FAILED", stoppedRow.Status, "payload %s", stoppedRow.Payload)
+ a.Contains(stoppedRow.Payload, "AI SQL review is not enabled")
+ a.Equal(int32(1), modelCalls.Load(), "no call reaches the model after the review is switched off")
}
// setAISetting enables AI in the test workspace with a Gemini model served at
-// endpoint.
-func setAISetting(ctx context.Context, t *testing.T, ctl *controller, endpoint string) {
+// endpoint, and switches the AI SQL review on or off.
+func setAISetting(ctx context.Context, t *testing.T, ctl *controller, endpoint string, sqlReviewEnabled bool) *v1pb.Setting {
t.Helper()
- _, err := ctl.settingServiceClient.UpdateSetting(ctx, connect.NewRequest(&v1pb.UpdateSettingRequest{
+ resp, err := ctl.settingServiceClient.UpdateSetting(ctx, connect.NewRequest(&v1pb.UpdateSettingRequest{
AllowMissing: true,
Setting: &v1pb.Setting{
Name: "settings/" + v1pb.Setting_AI.String(),
Value: &v1pb.SettingValue{
Value: &v1pb.SettingValue_Ai{
Ai: &v1pb.AISetting{
- Enabled: true,
- Provider: v1pb.AISetting_GEMINI,
- Endpoint: endpoint,
- ApiKey: "unused",
- Model: "unused",
+ Enabled: true,
+ Provider: v1pb.AISetting_GEMINI,
+ Endpoint: endpoint,
+ ApiKey: "unused",
+ Model: "unused",
+ SqlReviewEnabled: sqlReviewEnabled,
},
},
},
},
UpdateMask: &fieldmaskpb.FieldMask{
- Paths: []string{"value.ai.enabled", "value.ai.provider", "value.ai.endpoint", "value.ai.api_key", "value.ai.model"},
+ Paths: []string{"value.ai.enabled", "value.ai.provider", "value.ai.endpoint", "value.ai.api_key", "value.ai.model", "value.ai.sql_review_enabled"},
},
}))
require.NoError(t, err)
+ return resp.Msg
+}
+
+func actuatorAISQLReviewEnabled(ctx context.Context, t *testing.T, ctl *controller) bool {
+ t.Helper()
+ info, err := ctl.actuatorServiceClient.GetActuatorInfo(ctx, connect.NewRequest(&v1pb.GetActuatorInfoRequest{}))
+ require.NoError(t, err)
+ return info.Msg.AiSqlReviewEnabled
+}
+
+// setStoredAISQLReviewEnabled writes the switch straight into the metadata
+// database, past the server and its setting cache.
+func setStoredAISQLReviewEnabled(ctx context.Context, t *testing.T, ctl *controller, enabled bool) {
+ t.Helper()
+ workspace, err := ctl.workspaceServiceClient.GetWorkspace(ctx, connect.NewRequest(&v1pb.GetWorkspaceRequest{Name: "workspaces/-"}))
+ require.NoError(t, err)
+ db, err := sql.Open("pgx", ctl.profile.PgURL)
+ require.NoError(t, err)
+ defer db.Close()
+ result, err := db.ExecContext(ctx, `
+ UPDATE setting SET value = jsonb_set(value, '{sqlReviewEnabled}', to_jsonb($2::boolean))
+ WHERE workspace = $1 AND name = 'AI'
+ `, strings.TrimPrefix(workspace.Msg.Name, "workspaces/"), enabled)
+ require.NoError(t, err)
+ affected, err := result.RowsAffected()
+ require.NoError(t, err)
+ require.Equal(t, int64(1), affected)
}
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index bebcf76beb..a88feb900d 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -1,6 +1,19 @@
{
"add-or-remove-rules": "Add or remove rules",
"add-rules": "Add rules",
+ "ai-review": {
+ "ai-off": "AI is off for the workspace, so no AI review runs.",
+ "description": "An AI model that reviews the SQL of an issue for risks the standard rules cannot see. It applies to every project in the workspace.",
+ "enable": {
+ "description": "Each review sends the statements as written to the AI provider, and can send the schema of the target databases and their table statistics. It reads no rows from the databases.",
+ "self": "Review changes with AI"
+ },
+ "project-description": "An AI model that reviews the SQL of an issue for risks the standard rules cannot see.",
+ "self": "AI review",
+ "set-for-workspace": "Set for the whole workspace.",
+ "turn-on-ai": "Turn on AI",
+ "view-workspace-setting": "View workspace setting"
+ },
"attach-resource": {
"change-resources": "Change attached resources",
"label": "You can apply the SQL review policy to environments or projects. The database will use the project-level policy if it exists, or fallback to the environment-level policy.",
diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.json
index 48024d3072..23387cb563 100644
--- a/frontend/src/locales/sql-review/es-ES.json
+++ b/frontend/src/locales/sql-review/es-ES.json
@@ -1,6 +1,19 @@
{
"add-or-remove-rules": "Agregar o eliminar reglas",
"add-rules": "Agregar reglas",
+ "ai-review": {
+ "ai-off": "La IA está desactivada en el espacio de trabajo, por lo que no se ejecuta ninguna revisión con IA.",
+ "description": "Un modelo de IA que revisa el SQL de un issue en busca de riesgos que las reglas estándar no pueden ver. Se aplica a todos los proyectos del espacio de trabajo.",
+ "enable": {
+ "description": "Cada revisión envía al proveedor de IA las sentencias tal como están escritas, y puede enviar el esquema de las bases de datos de destino y las estadísticas de sus tablas. No lee ninguna fila de las bases de datos.",
+ "self": "Revisar los cambios con IA"
+ },
+ "project-description": "Un modelo de IA que revisa el SQL de un issue en busca de riesgos que las reglas estándar no pueden ver.",
+ "self": "Revisión con IA",
+ "set-for-workspace": "Se establece para todo el espacio de trabajo.",
+ "turn-on-ai": "Activar la IA",
+ "view-workspace-setting": "Ver la configuración del espacio de trabajo"
+ },
"attach-resource": {
"change-resources": "Cambiar recursos adjuntos",
"label": "Puede aplicar la política de revisión a entornos o proyectos. Un recurso sólo puede vincular una política. La base de datos utilizará la política de revisión de SQL adjunta al proyecto; de lo contrario, recurrirá a la política de entorno.",
diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.json
index 5f9f87c37f..307d63b89f 100644
--- a/frontend/src/locales/sql-review/ja-JP.json
+++ b/frontend/src/locales/sql-review/ja-JP.json
@@ -1,6 +1,19 @@
{
"add-or-remove-rules": "ルールを追加または削除する",
"add-rules": "ルールを追加する",
+ "ai-review": {
+ "ai-off": "ワークスペースで AI が無効になっているため、AI レビューは実行されません。",
+ "description": "AI モデルが Issue の SQL をレビューし、標準ルールでは検出できないリスクを見つけます。ワークスペース内のすべてのプロジェクトに適用されます。",
+ "enable": {
+ "description": "レビューのたびにステートメントの原文が AI プロバイダーに送信され、対象データベースのスキーマとテーブルの統計情報も送信される場合があります。データベースの行は読み取りません。",
+ "self": "AI で変更をレビューする"
+ },
+ "project-description": "AI モデルが Issue の SQL をレビューし、標準ルールでは検出できないリスクを見つけます。",
+ "self": "AI レビュー",
+ "set-for-workspace": "ワークスペース全体で設定されます。",
+ "turn-on-ai": "AI を有効にする",
+ "view-workspace-setting": "ワークスペースの設定を表示"
+ },
"attach-resource": {
"change-resources": "バインドされたリソースを変更する",
"label": "SQL レビューポリシーは環境リソースまたはプロジェクト リソースにバインドする必要があり、対応するリソースの下にあるすべてのデータベースに影響します。データベースがプロジェクト レベルと環境レベルの両方のポリシーの影響を受ける場合、プロジェクト レベルのポリシーのみが有効になります。",
diff --git a/frontend/src/locales/sql-review/vi-VN.json b/frontend/src/locales/sql-review/vi-VN.json
index bde7a63846..aa895c4f0a 100644
--- a/frontend/src/locales/sql-review/vi-VN.json
+++ b/frontend/src/locales/sql-review/vi-VN.json
@@ -1,6 +1,19 @@
{
"add-or-remove-rules": "Thêm hoặc xóa quy tắc",
"add-rules": "Thêm quy tắc",
+ "ai-review": {
+ "ai-off": "AI đang tắt trong không gian làm việc nên không có lần đánh giá bằng AI nào được chạy.",
+ "description": "Một mô hình AI đánh giá SQL của issue để tìm các rủi ro mà quy tắc tiêu chuẩn không phát hiện được. Áp dụng cho mọi dự án trong không gian làm việc.",
+ "enable": {
+ "description": "Mỗi lần đánh giá sẽ gửi nguyên văn các câu lệnh tới nhà cung cấp AI, và có thể gửi lược đồ của các cơ sở dữ liệu đích cùng số liệu thống kê bảng của chúng. Tính năng này không đọc bất kỳ hàng dữ liệu nào trong cơ sở dữ liệu.",
+ "self": "Đánh giá thay đổi bằng AI"
+ },
+ "project-description": "Một mô hình AI đánh giá SQL của issue để tìm các rủi ro mà quy tắc tiêu chuẩn không phát hiện được.",
+ "self": "Đánh giá bằng AI",
+ "set-for-workspace": "Được thiết lập cho toàn bộ không gian làm việc.",
+ "turn-on-ai": "Bật AI",
+ "view-workspace-setting": "Xem thiết lập của không gian làm việc"
+ },
"attach-resource": {
"change-resources": "Thay đổi tài nguyên đính kèm",
"label": "Bạn có thể áp dụng chính sách đánh giá SQL cho môi trường hoặc dự án. Cơ sở dữ liệu sẽ sử dụng chính sách cấp dự án nếu có, hoặc quay lại chính sách cấp môi trường.",
diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.json
index acf49f6c1c..dda8cde57e 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -1,6 +1,19 @@
{
"add-or-remove-rules": "添加或删除规则",
"add-rules": "添加规则",
+ "ai-review": {
+ "ai-off": "工作空间尚未启用 AI,因此不会运行 AI 审核。",
+ "description": "由 AI 模型审核工单中的 SQL,发现标准规则无法识别的风险。对工作空间内的所有项目生效。",
+ "enable": {
+ "description": "每次审核会将语句原文发送给 AI 提供方,并可能发送目标数据库的 Schema 及其表的统计信息,但不会读取数据库中的任何数据行。",
+ "self": "使用 AI 审核变更"
+ },
+ "project-description": "由 AI 模型审核工单中的 SQL,发现标准规则无法识别的风险。",
+ "self": "AI 审核",
+ "set-for-workspace": "由工作空间统一设置。",
+ "turn-on-ai": "启用 AI",
+ "view-workspace-setting": "查看工作空间设置"
+ },
"attach-resource": {
"change-resources": "更改绑定的资源",
"label": "审核策略需要绑定到环境资源或项目资源上,并影响对应资源下所有数据库。若一个数据库同时受到项目级别与环境级别策略影响,则只有项目级别策略生效。",
diff --git a/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx b/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
index 6688b2e602..8046a78f88 100644
--- a/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
+++ b/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
@@ -1,5 +1,11 @@
import { create } from "@bufbuild/protobuf";
-import { act, fireEvent, render, screen } from "@testing-library/react";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from "@testing-library/react";
import type { ReactNode } from "react";
import { beforeEach, describe, expect, test, vi } from "vitest";
import {
@@ -71,6 +77,7 @@ vi.mock("@/stores/app", async () => {
type StorePolicy = import("@/types/proto-es/v1/org_policy_service_pb").Policy;
const useAppStore = createStore<{
policies: Record<string, StorePolicy>;
+ serverInfo?: { aiEnabled: boolean; aiSqlReviewEnabled: boolean };
getPolicyByParentAndType: (params: {
parentPath: string;
}) => StorePolicy | undefined;
@@ -141,6 +148,15 @@ const seedPolicies = (policies: Record<string, Policy>) =>
setState: (state: { policies: Record<string, Policy> }) => void;
}
).setState({ policies });
+const seedServerInfo = (serverInfo?: {
+ aiEnabled: boolean;
+ aiSqlReviewEnabled: boolean;
+}) =>
+ (
+ useAppStore as unknown as {
+ setState: (state: { serverInfo: typeof serverInfo }) => void;
+ }
+ ).setState({ serverInfo });
const { ProjectSQLReviewPage } = await import("./ProjectSQLReviewPage");
const reviewRulePolicy = (
@@ -200,6 +216,53 @@ describe("ProjectSQLReviewPage", () => {
mocks.fetchPolicy.mockReset();
mocks.pushNotification.mockReset();
seedPolicies({ [WORKSPACE]: workspacePolicy() });
+ seedServerInfo(undefined);
+ });
+
+ // The row of the AI review: its title, its description, and its state.
+ const aiReviewRow = () =>
+ within(
+ screen.getByText("sql-review.ai-review.enable.self").parentElement!
+ .parentElement!
+ );
+
+ test("shows the AI review as on when the workspace has it on and AI is on", async () => {
+ seedServerInfo({ aiEnabled: true, aiSqlReviewEnabled: true });
+ await renderLoaded();
+
+ expect(
+ aiReviewRow().getByText("sql-review.standard-rules.on")
+ ).toBeInTheDocument();
+ expect(
+ aiReviewRow().getByText("sql-review.ai-review.set-for-workspace", {
+ exact: false,
+ })
+ ).toBeInTheDocument();
+ expect(
+ aiReviewRow().getByRole("link", {
+ name: "sql-review.ai-review.view-workspace-setting",
+ })
+ ).toBeInTheDocument();
+ expect(aiReviewRow().queryByRole("switch")).not.toBeInTheDocument();
+ });
+
+ test.each([
+ ["the workspace has it off", { aiEnabled: true, aiSqlReviewEnabled: false }],
+ ["AI is off for the workspace", { aiEnabled: false, aiSqlReviewEnabled: true }],
+ ])("shows the AI review as off when %s", async (_name, serverInfo) => {
+ seedServerInfo(serverInfo);
+ await renderLoaded();
+
+ expect(
+ aiReviewRow().getByText("sql-review.standard-rules.off")
+ ).toBeInTheDocument();
+ });
+
+ test("the workspace setting link of the AI review needs the workspace policy read", async () => {
+ mocks.workspacePermissions["bb.policies.get"] = false;
+ await renderLoaded();
+
+ expect(aiReviewRow().queryByRole("link")).not.toBeInTheDocument();
});
test("a project without its own policy shows the workspace rules as text", async () => {
@@ -209,8 +272,9 @@ describe("ProjectSQLReviewPage", () => {
// Only the customize control is a switch; the rules are read-only.
expect(screen.getAllByRole("switch")).toHaveLength(1);
expect(screen.getAllByText("sql-review.standard-rules.on")).toHaveLength(2);
+ // Nine rules, and the AI review row below them.
expect(screen.getAllByText("sql-review.standard-rules.off")).toHaveLength(
- 9
+ 10
);
expect(
screen.getByText("sql-review.standard-rules.running")
diff --git a/frontend/src/routes/project/ProjectSQLReviewPage.tsx b/frontend/src/routes/project/ProjectSQLReviewPage.tsx
index 3dbdf28b38..6014282081 100644
--- a/frontend/src/routes/project/ProjectSQLReviewPage.tsx
+++ b/frontend/src/routes/project/ProjectSQLReviewPage.tsx
@@ -222,6 +222,13 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {
: !standardRules.storedCustomized && !canSave;
// The V2 workspace route needs only the policy read.
const canViewWorkspaceRules = hasWorkspacePermissionV2("bb.policies.get");
+ // The AI review is switched for the whole workspace, and it runs only
+ // while AI itself is on.
+ const aiReviewOn = useAppStore(
+ (state) =>
+ state.serverInfo?.aiEnabled === true &&
+ state.serverInfo?.aiSqlReviewEnabled === true
+ );
return (
<ProjectPageLayout>
@@ -295,6 +302,37 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {
)}
</>
)}
+ <div className="flex flex-col gap-y-2 pt-8">
+ <h1 className="text-2xl font-bold text-main">
+ {t("sql-review.ai-review.self")}
+ </h1>
+ <p className="text-sm text-control-light">
+ {t("sql-review.ai-review.project-description")}
+ </p>
+ </div>
+ <SwitchRow
+ className="rounded-sm border border-block-border px-4 py-3"
+ title={t("sql-review.ai-review.enable.self")}
+ description={
+ <>
+ {t("sql-review.ai-review.set-for-workspace")}
+ {canViewWorkspaceRules && (
+ <>
+ {" "}
+ <RouterLink
+ to={{ name: WORKSPACE_ROUTE_SQL_REVIEW }}
+ className="text-accent hover:underline"
+ >
+ {t("sql-review.ai-review.view-workspace-setting")}
+ </RouterLink>
+ </>
+ )}
+ </>
+ }
+ checked={aiReviewOn}
+ onCheckedChange={() => {}}
+ readOnly
+ />
</div>
{standardRules.isDirty && (
diff --git a/frontend/src/routes/workspace/SQLReviewAIReviewSection.test.tsx b/frontend/src/routes/workspace/SQLReviewAIReviewSection.test.tsx
new file mode 100644
index 0000000000..63edca90eb
--- /dev/null
+++ b/frontend/src/routes/workspace/SQLReviewAIReviewSection.test.tsx
@@ -0,0 +1,229 @@
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { type ReactNode, useState } from "react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
+
+const SWITCH = { name: "sql-review.ai-review.enable.self" };
+
+const mocks = vi.hoisted(() => ({
+ permissions: {} as Record<string, boolean>,
+ saas: { value: false },
+ upsertSetting: vi.fn(),
+ pushNotification: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/hooks/useAppState", () => ({
+ useServerState: () => ({ isSaaSMode: mocks.saas.value }),
+}));
+
+vi.mock("@/utils", () => ({
+ hasWorkspacePermissionV2: (permission: string) =>
+ mocks.permissions[permission] ?? true,
+}));
+
+vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));
+
+vi.mock("@/components/RouterLink", () => ({
+ RouterLink: ({ children }: { children: ReactNode }) => (
+ <a href="/">{children}</a>
+ ),
+}));
+
+// Mirrors the real store: a saved AI setting updates the server info.
+vi.mock("@/stores/app", async () => {
+ const { create: createStore } = await import("zustand");
+ type ServerInfo = { aiEnabled: boolean; aiSqlReviewEnabled: boolean };
+ type Saved = {
+ value: { value: { value: { sqlReviewEnabled: boolean } } };
+ };
+ const useAppStore = createStore<{
+ serverInfo: ServerInfo;
+ upsertSetting: (params: Saved) => Promise<void>;
+ }>()((set) => ({
+ serverInfo: { aiEnabled: true, aiSqlReviewEnabled: false },
+ upsertSetting: async (params) => {
+ await mocks.upsertSetting(params);
+ set((state) => ({
+ serverInfo: {
+ ...state.serverInfo,
+ aiSqlReviewEnabled: params.value.value.value.sqlReviewEnabled,
+ },
+ }));
+ },
+ }));
+ return { useAppStore };
+});
+
+const { useAppStore } = await import("@/stores/app");
+const seedServerInfo = (serverInfo: {
+ aiEnabled: boolean;
+ aiSqlReviewEnabled: boolean;
+}) =>
+ (
+ useAppStore as unknown as {
+ setState: (state: { serverInfo: typeof serverInfo }) => void;
+ }
+ ).setState({ serverInfo });
+
+const { SQLReviewAIReviewSection, useWorkspaceAIReview } = await import(
+ "./SQLReviewAIReviewSection"
+);
+
+function Harness() {
+ const aiReview = useWorkspaceAIReview();
+ const [saved, setSaved] = useState<boolean>();
+ return (
+ <>
+ <SQLReviewAIReviewSection aiReview={aiReview} />
+ <output>{aiReview.isDirty ? "dirty" : "clean"}</output>
+ <output>{`saved: ${saved}`}</output>
+ <button
+ type="button"
+ onClick={() => void aiReview.save().then(setSaved)}
+ >
+ save
+ </button>
+ <button type="button" onClick={aiReview.revert}>
+ revert
+ </button>
+ </>
+ );
+}
+
+const save = () =>
+ act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "save" }));
+ });
+
+describe("SQLReviewAIReviewSection", () => {
+ beforeEach(() => {
+ mocks.permissions = {};
+ mocks.saas.value = false;
+ mocks.upsertSetting.mockReset();
+ mocks.pushNotification.mockReset();
+ seedServerInfo({ aiEnabled: true, aiSqlReviewEnabled: false });
+ });
+
+ test("saves the switch under its own mask path", async () => {
+ render(<Harness />);
+ expect(screen.getByRole("switch", SWITCH)).toHaveAttribute(
+ "aria-checked",
+ "false"
+ );
+ expect(screen.getByText("clean")).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("switch", SWITCH));
+ expect(screen.getByText("dirty")).toBeInTheDocument();
+ await save();
+
+ expect(mocks.upsertSetting).toHaveBeenCalledOnce();
+ const saved = mocks.upsertSetting.mock.calls[0][0];
+ expect(saved.name).toBe(Setting_SettingName.AI);
+ expect(saved.updateMask.paths).toEqual(["value.ai.sql_review_enabled"]);
+ expect(saved.value.value.value.sqlReviewEnabled).toBe(true);
+ expect(screen.getByRole("switch", SWITCH)).toHaveAttribute(
+ "aria-checked",
+ "true"
+ );
+ expect(screen.getByText("clean")).toBeInTheDocument();
+ expect(screen.getByText("saved: true")).toBeInTheDocument();
+ // The page reports the update, once for everything the click saved.
+ expect(mocks.pushNotification).not.toHaveBeenCalled();
+ });
+
+ test("reverting drops the unsaved choice", () => {
+ seedServerInfo({ aiEnabled: true, aiSqlReviewEnabled: true });
+ render(<Harness />);
+
+ fireEvent.click(screen.getByRole("switch", SWITCH));
+ expect(screen.getByRole("switch", SWITCH)).toHaveAttribute(
+ "aria-checked",
+ "false"
+ );
+ fireEvent.click(screen.getByRole("button", { name: "revert" }));
+
+ expect(screen.getByRole("switch", SWITCH)).toHaveAttribute(
+ "aria-checked",
+ "true"
+ );
+ expect(screen.getByText("clean")).toBeInTheDocument();
+ });
+
+ test("a failed save keeps the unsaved choice", async () => {
+ mocks.upsertSetting.mockRejectedValueOnce(new Error("save failed"));
+ render(<Harness />);
+
+ fireEvent.click(screen.getByRole("switch", SWITCH));
+ await save();
+
+ expect(screen.getByRole("switch", SWITCH)).toHaveAttribute(
+ "aria-checked",
+ "true"
+ );
+ expect(screen.getByText("dirty")).toBeInTheDocument();
+ expect(screen.getByText("saved: false")).toBeInTheDocument();
+ expect(mocks.pushNotification).not.toHaveBeenCalled();
+ });
+
+ test("shows the state as text without bb.settings.set", () => {
+ mocks.permissions["bb.settings.set"] = false;
+ seedServerInfo({ aiEnabled: true, aiSqlReviewEnabled: true });
+ render(<Harness />);
+
+ expect(screen.queryByRole("switch")).not.toBeInTheDocument();
+ expect(screen.getByText("sql-review.standard-rules.on")).toBeInTheDocument();
+ });
+
+ test("shows the state as text in SaaS mode, where the AI setting is read only", () => {
+ mocks.saas.value = true;
+ render(<Harness />);
+
+ expect(screen.queryByRole("switch")).not.toBeInTheDocument();
+ expect(
+ screen.getByText("sql-review.standard-rules.off")
+ ).toBeInTheDocument();
+ });
+
+ test("warns while AI is off for the workspace, with a link to turn it on", () => {
+ seedServerInfo({ aiEnabled: false, aiSqlReviewEnabled: true });
+ render(<Harness />);
+
+ expect(
+ screen.getByText("sql-review.ai-review.ai-off")
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("link", { name: "sql-review.ai-review.turn-on-ai" })
+ ).toBeInTheDocument();
+ });
+
+ test.each([
+ ["without bb.settings.set", () => (mocks.permissions["bb.settings.set"] = false)],
+ ["without bb.settings.get", () => (mocks.permissions["bb.settings.get"] = false)],
+ [
+ "without bb.settings.getWorkspaceProfile",
+ () => (mocks.permissions["bb.settings.getWorkspaceProfile"] = false),
+ ],
+ ["in SaaS mode", () => (mocks.saas.value = true)],
+ ])("warns without the link %s, where the user cannot turn AI on", (_name, arrange) => {
+ arrange();
+ seedServerInfo({ aiEnabled: false, aiSqlReviewEnabled: false });
+ render(<Harness />);
+
+ expect(
+ screen.getByText("sql-review.ai-review.ai-off")
+ ).toBeInTheDocument();
+ expect(screen.queryByRole("link")).not.toBeInTheDocument();
+ });
+
+ test("shows no warning while AI is on", () => {
+ render(<Harness />);
+
+ expect(
+ screen.queryByText("sql-review.ai-review.ai-off")
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/routes/workspace/SQLReviewAIReviewSection.tsx b/frontend/src/routes/workspace/SQLReviewAIReviewSection.tsx
new file mode 100644
index 0000000000..156cc52e4c
--- /dev/null
+++ b/frontend/src/routes/workspace/SQLReviewAIReviewSection.tsx
@@ -0,0 +1,147 @@
+import { create } from "@bufbuild/protobuf";
+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/app/router/handles";
+import { RouterLink } from "@/components/RouterLink";
+import { SwitchRow } from "@/components/sql-review/SwitchRow";
+import { Alert } from "@/components/ui/alert";
+import { useServerState } from "@/hooks/useAppState";
+import { useAppStore } from "@/stores/app";
+import {
+ AISettingSchema,
+ Setting_SettingName,
+ SettingValueSchema,
+} from "@/types/proto-es/v1/setting_service_pb";
+import { hasWorkspacePermissionV2 } from "@/utils";
+
+export interface WorkspaceAIReview {
+ // Whether the review is switched on, or the unsaved choice.
+ enabled: boolean;
+ // Whether AI is on for the workspace. While it is off no review runs,
+ // whatever the switch says.
+ aiEnabled: boolean;
+ // The switch is a field of the AI setting, which SaaS keeps read only.
+ canEdit: boolean;
+ setEnabled: (enabled: boolean) => void;
+ isDirty: boolean;
+ saving: boolean;
+ revert: () => void;
+ // Resolves whether the switch saved. The page reports the update; a failure
+ // is reported by the response middleware and keeps the draft.
+ save: () => Promise<boolean>;
+}
+
+// The page owns the draft so the switch saves with the standard rules, from
+// the one sticky footer.
+export function useWorkspaceAIReview(): WorkspaceAIReview {
+ const { isSaaSMode } = useServerState();
+ // The server info carries both flags, so a user who cannot read the AI
+ // setting still sees whether the review is on.
+ const stored = useAppStore(
+ (state) => state.serverInfo?.aiSqlReviewEnabled === true
+ );
+ const aiEnabled = useAppStore(
+ (state) => state.serverInfo?.aiEnabled === true
+ );
+ const [draft, setDraft] = useState<boolean>();
+ const [saving, setSaving] = useState(false);
+ const isDirty = draft !== undefined && draft !== stored;
+
+ const save = async () => {
+ if (draft === undefined) return true;
+ setSaving(true);
+ try {
+ await useAppStore.getState().upsertSetting({
+ name: Setting_SettingName.AI,
+ value: create(SettingValueSchema, {
+ value: {
+ case: "ai",
+ value: create(AISettingSchema, { sqlReviewEnabled: draft }),
+ },
+ }),
+ // The mask leaves the provider, the key, and the model as stored.
+ updateMask: create(FieldMaskSchema, {
+ paths: ["value.ai.sql_review_enabled"],
+ }),
+ });
+ setDraft(undefined);
+ return true;
+ } catch {
+ return false;
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return {
+ enabled: draft ?? stored,
+ aiEnabled,
+ canEdit: hasWorkspacePermissionV2("bb.settings.set") && !isSaaSMode,
+ setEnabled: setDraft,
+ isDirty,
+ saving,
+ revert: () => setDraft(undefined),
+ save,
+ };
+}
+
+export function SQLReviewAIReviewSection({
+ aiReview,
+}: {
+ aiReview: WorkspaceAIReview;
+}) {
+ const { t } = useTranslation();
+ // AI is turned on in the general settings, whose AI section shows its
+ // controls only to a user who can open that page and read the AI setting.
+ const canTurnOnAI =
+ aiReview.canEdit &&
+ hasWorkspacePermissionV2("bb.settings.get") &&
+ hasWorkspacePermissionV2("bb.settings.getWorkspaceProfile");
+
+ return (
+ <section className="flex flex-col gap-y-6 pt-8">
+ <div className="flex flex-col gap-y-2">
+ <h1 className="text-2xl font-bold text-main">
+ {t("sql-review.ai-review.self")}
+ </h1>
+ <p className="text-sm text-control-light">
+ {t("sql-review.ai-review.description")}
+ </p>
+ </div>
+ {!aiReview.aiEnabled && (
+ <Alert
+ variant="warning"
+ description={
+ <>
+ {t("sql-review.ai-review.ai-off")}
+ {canTurnOnAI && (
+ <>
+ {" "}
+ <RouterLink
+ to={{
+ name: SETTING_ROUTE_WORKSPACE_GENERAL,
+ hash: "#ai-assistant",
+ }}
+ className="text-accent hover:underline"
+ >
+ {t("sql-review.ai-review.turn-on-ai")}
+ </RouterLink>
+ </>
+ )}
+ </>
+ }
+ />
+ )}
+ <SwitchRow
+ className="rounded-sm border border-block-border px-4 py-3"
+ title={t("sql-review.ai-review.enable.self")}
+ description={t("sql-review.ai-review.enable.description")}
+ checked={aiReview.enabled}
+ onCheckedChange={aiReview.setEnabled}
+ disabled={aiReview.saving}
+ readOnly={!aiReview.canEdit}
+ />
+ </section>
+ );
+}
diff --git a/frontend/src/routes/workspace/SQLReviewPage.test.tsx b/frontend/src/routes/workspace/SQLReviewPage.test.tsx
index 07e1ed0127..450dc993f1 100644
--- a/frontend/src/routes/workspace/SQLReviewPage.test.tsx
+++ b/frontend/src/routes/workspace/SQLReviewPage.test.tsx
@@ -1,10 +1,20 @@
-import { render, screen } from "@testing-library/react";
+import { act, fireEvent, render, screen } from "@testing-library/react";
import type { ReactNode } from "react";
import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
sqlReviewV2: { value: true },
fetchReviewPolicyList: vi.fn(),
+ standardRules: {
+ rules: [],
+ setRules: vi.fn(),
+ isDirty: false,
+ saving: false,
+ revert: vi.fn(),
+ save: vi.fn(),
+ },
+ aiReview: { isDirty: false, saving: false, revert: vi.fn(), save: vi.fn() },
+ pushNotification: vi.fn(),
}));
vi.mock("react-i18next", () => ({
@@ -17,14 +27,12 @@ vi.mock("@/utils/featureGates", () => ({
vi.mock("./SQLReviewStandardRulesSection", () => ({
SQLReviewStandardRulesSection: () => <div>standard-rules-section</div>,
- useWorkspaceStandardRules: () => ({
- rules: [],
- setRules: vi.fn(),
- isDirty: false,
- saving: false,
- revert: vi.fn(),
- save: vi.fn(),
- }),
+ useWorkspaceStandardRules: () => mocks.standardRules,
+}));
+
+vi.mock("./SQLReviewAIReviewSection", () => ({
+ SQLReviewAIReviewSection: () => <div>ai-review-section</div>,
+ useWorkspaceAIReview: () => mocks.aiReview,
}));
vi.mock("@/stores/sqlReview", () => {
@@ -47,7 +55,7 @@ vi.mock("@/components/LearnMoreLink", () => ({
vi.mock("@/hooks/useUnsavedChangesGuard", () => ({
useUnsavedChangesGuard: vi.fn(),
}));
-vi.mock("@/stores", () => ({ pushNotification: vi.fn() }));
+vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));
vi.mock("@/utils", () => ({
hasWorkspacePermissionV2: () => true,
sqlReviewPolicySlug: () => "slug",
@@ -55,16 +63,32 @@ vi.mock("@/utils", () => ({
const { SQLReviewPage } = await import("./SQLReviewPage");
+const update = () =>
+ act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "common.update" }));
+ });
+
describe("SQLReviewPage", () => {
beforeEach(() => {
mocks.fetchReviewPolicyList.mockReset();
+ for (const part of [mocks.standardRules, mocks.aiReview]) {
+ part.isDirty = false;
+ part.saving = false;
+ part.revert.mockReset();
+ part.save.mockReset().mockResolvedValue(true);
+ }
+ mocks.pushNotification.mockReset();
});
- test("shows only the standard rules under SQL Review V2", () => {
+ test("shows the standard rules and the AI review under SQL Review V2", () => {
mocks.sqlReviewV2.value = true;
render(<SQLReviewPage />);
expect(screen.getByText("standard-rules-section")).toBeInTheDocument();
+ expect(screen.getByText("ai-review-section")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "common.update" })
+ ).not.toBeInTheDocument();
expect(screen.queryByText("sql-review.description")).not.toBeInTheDocument();
expect(screen.queryByText("common.create")).not.toBeInTheDocument();
expect(mocks.fetchReviewPolicyList).not.toHaveBeenCalled();
@@ -77,8 +101,72 @@ describe("SQLReviewPage", () => {
expect(
screen.queryByText("standard-rules-section")
).not.toBeInTheDocument();
+ expect(screen.queryByText("ai-review-section")).not.toBeInTheDocument();
expect(screen.getByText("sql-review.description")).toBeInTheDocument();
expect(screen.getAllByText("common.create").length).toBeGreaterThan(0);
expect(mocks.fetchReviewPolicyList).toHaveBeenCalledTimes(1);
});
+
+ test("the footer saves only the part that changed", async () => {
+ mocks.sqlReviewV2.value = true;
+ mocks.aiReview.isDirty = true;
+ render(<SQLReviewPage />);
+
+ await update();
+
+ expect(mocks.aiReview.save).toHaveBeenCalledOnce();
+ expect(mocks.standardRules.save).not.toHaveBeenCalled();
+ expect(mocks.pushNotification).toHaveBeenCalledOnce();
+ });
+
+ test("the footer saves both parts when both changed, and reports one update", async () => {
+ mocks.sqlReviewV2.value = true;
+ mocks.aiReview.isDirty = true;
+ mocks.standardRules.isDirty = true;
+ render(<SQLReviewPage />);
+
+ await update();
+
+ expect(mocks.aiReview.save).toHaveBeenCalledOnce();
+ expect(mocks.standardRules.save).toHaveBeenCalledOnce();
+ expect(mocks.pushNotification).toHaveBeenCalledOnce();
+ });
+
+ test.each([
+ ["the AI review", mocks.aiReview],
+ ["the standard rules", mocks.standardRules],
+ ])("reports no update when %s fails to save", async (_, failing) => {
+ mocks.sqlReviewV2.value = true;
+ mocks.aiReview.isDirty = true;
+ mocks.standardRules.isDirty = true;
+ render(<SQLReviewPage />);
+ failing.save.mockResolvedValue(false);
+
+ await update();
+
+ expect(mocks.aiReview.save).toHaveBeenCalledOnce();
+ expect(mocks.standardRules.save).toHaveBeenCalledOnce();
+ expect(mocks.pushNotification).not.toHaveBeenCalled();
+ });
+
+ test("cancel reverts both parts", () => {
+ mocks.sqlReviewV2.value = true;
+ mocks.standardRules.isDirty = true;
+ render(<SQLReviewPage />);
+
+ fireEvent.click(screen.getByRole("button", { name: "common.cancel" }));
+
+ expect(mocks.standardRules.revert).toHaveBeenCalledOnce();
+ expect(mocks.aiReview.revert).toHaveBeenCalledOnce();
+ });
+
+ test("the footer waits while either part is saving", () => {
+ mocks.sqlReviewV2.value = true;
+ mocks.standardRules.isDirty = true;
+ mocks.aiReview.saving = true;
+ render(<SQLReviewPage />);
+
+ expect(screen.getByRole("button", { name: "common.update" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "common.cancel" })).toBeDisabled();
+ });
});
diff --git a/frontend/src/routes/workspace/SQLReviewPage.tsx b/frontend/src/routes/workspace/SQLReviewPage.tsx
index 41e9989e82..b7f1e363e8 100644
--- a/frontend/src/routes/workspace/SQLReviewPage.tsx
+++ b/frontend/src/routes/workspace/SQLReviewPage.tsx
@@ -34,6 +34,10 @@ import { useSQLReviewStore } from "@/stores/sqlReview";
import type { SQLReviewPolicy } from "@/types";
import { hasWorkspacePermissionV2, sqlReviewPolicySlug } from "@/utils";
import { sqlReviewV2Enabled } from "@/utils/featureGates";
+import {
+ SQLReviewAIReviewSection,
+ useWorkspaceAIReview,
+} from "./SQLReviewAIReviewSection";
import {
SQLReviewStandardRulesSection,
useWorkspaceStandardRules,
@@ -263,7 +267,10 @@ export function SQLReviewPage() {
// With SQL Review V2 the standard rules replace the v1 review policies.
const sqlReviewV2 = sqlReviewV2Enabled();
const standardRules = useWorkspaceStandardRules(sqlReviewV2);
- useUnsavedChangesGuard(standardRules.isDirty);
+ const aiReview = useWorkspaceAIReview();
+ const isDirty = standardRules.isDirty || aiReview.isDirty;
+ const saving = standardRules.saving || aiReview.saving;
+ useUnsavedChangesGuard(isDirty);
useEffect(() => {
if (sqlReviewV2) return;
@@ -303,6 +310,7 @@ export function SQLReviewPage() {
{sqlReviewV2 ? (
<div className={STANDARD_RULES_COLUMN}>
<SQLReviewStandardRulesSection standardRules={standardRules} />
+ <SQLReviewAIReviewSection aiReview={aiReview} />
</div>
) : (
<>
@@ -345,23 +353,39 @@ export function SQLReviewPage() {
</>
)}
- {standardRules.isDirty && (
+ {isDirty && (
<StickyActionFooter
contentPadding={false}
contentClassName={STANDARD_RULES_COLUMN}
left={
<Button
appearance="outline"
- disabled={standardRules.saving}
- onClick={standardRules.revert}
+ disabled={saving}
+ onClick={() => {
+ standardRules.revert();
+ aiReview.revert();
+ }}
>
{t("common.cancel")}
</Button>
}
right={
<Button
- disabled={standardRules.saving}
- onClick={() => void standardRules.save()}
+ disabled={saving}
+ onClick={async () => {
+ const saves: Promise<boolean>[] = [];
+ if (standardRules.isDirty) saves.push(standardRules.save());
+ if (aiReview.isDirty) saves.push(aiReview.save());
+ // One click reports one update, and only when every changed
+ // part saved.
+ if ((await Promise.all(saves)).every(Boolean)) {
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ }
+ }}
>
{t("common.update")}
</Button>
diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
index 45dd2eef2f..a9409301e0 100644
--- a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
@@ -1,5 +1,6 @@
import { create } from "@bufbuild/protobuf";
import { act, fireEvent, render, screen } from "@testing-library/react";
+import { useState } from "react";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { STANDARD_RULE_TYPES } from "@/components/sql-review/standardRules";
import {
@@ -98,11 +99,16 @@ const reviewRulePolicy = (
function Harness() {
const standardRules = useWorkspaceStandardRules(true);
+ const [saved, setSaved] = useState<boolean>();
return (
<>
<SQLReviewStandardRulesSection standardRules={standardRules} />
<output data-testid="dirty">{String(standardRules.isDirty)}</output>
- <button type="button" onClick={() => void standardRules.save()}>
+ <output data-testid="saved">{String(saved)}</output>
+ <button
+ type="button"
+ onClick={() => void standardRules.save().then(setSaved)}
+ >
save
</button>
<button type="button" onClick={standardRules.revert}>
@@ -154,10 +160,13 @@ describe("SQLReviewStandardRulesSection", () => {
)
);
expect(screen.getByTestId("dirty")).toHaveTextContent("false");
+ expect(screen.getByTestId("saved")).toHaveTextContent("true");
expect(ruleSwitch("disallow-truncate")).toHaveAttribute(
"aria-checked",
"false"
);
+ // The page reports the update, once for everything the click saved.
+ expect(mocks.pushNotification).not.toHaveBeenCalled();
});
test("switching a rule back is not a change, and revert drops the draft", async () => {
@@ -186,6 +195,7 @@ describe("SQLReviewStandardRulesSection", () => {
});
expect(screen.getByTestId("dirty")).toHaveTextContent("true");
+ expect(screen.getByTestId("saved")).toHaveTextContent("false");
expect(mocks.pushNotification).not.toHaveBeenCalled();
});
diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
index f647b09884..10a6e55990 100644
--- a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
@@ -9,7 +9,6 @@ import {
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { useWorkspaceResourceName } from "@/hooks/useAppState";
-import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import {
PolicyResourceType,
@@ -31,7 +30,9 @@ export interface WorkspaceStandardRules {
isDirty: boolean;
saving: boolean;
revert: () => void;
- save: () => Promise<void>;
+ // Resolves whether the rules saved. The page reports the update; a failure
+ // is reported by the response middleware and keeps the draft.
+ save: () => Promise<boolean>;
}
// The page owns the draft so its sticky footer can sit at the end of the page,
@@ -39,7 +40,6 @@ export interface WorkspaceStandardRules {
export function useWorkspaceStandardRules(
enabled: boolean
): WorkspaceStandardRules {
- const { t } = useTranslation();
const workspace = useWorkspaceResourceName();
const policy = useAppStore((state) =>
state.getPolicyByParentAndType({
@@ -78,7 +78,7 @@ export function useWorkspaceStandardRules(
!sameStandardRules(draft, stored);
const save = async () => {
- if (!draft) return;
+ if (!draft) return true;
setSaving(true);
try {
await useAppStore.getState().upsertPolicy({
@@ -94,14 +94,9 @@ export function useWorkspaceStandardRules(
},
});
setDraft(undefined);
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.updated"),
- });
+ return true;
} catch {
- // The response middleware reports the failure; the draft stays for a
- // retry.
+ return false;
} finally {
setSaving(false);
}
diff --git a/frontend/src/stores/app/workspace.test.ts b/frontend/src/stores/app/workspace.test.ts
index 1a595bcef4..d52a90bd15 100644
--- a/frontend/src/stores/app/workspace.test.ts
+++ b/frontend/src/stores/app/workspace.test.ts
@@ -37,13 +37,13 @@ const createStore = () => {
return state as ReturnType<typeof createWorkspaceSlice>;
};
-const aiSetting = (enabled: boolean) =>
+const aiSetting = (enabled: boolean, sqlReviewEnabled = false) =>
create(SettingSchema, {
name: "settings/AI",
value: create(SettingValueSchema, {
value: {
case: "ai",
- value: create(AISettingSchema, { enabled }),
+ value: create(AISettingSchema, { enabled, sqlReviewEnabled }),
},
}),
});
@@ -73,6 +73,27 @@ describe("workspace AI setting cache", () => {
expect(store.serverInfo?.aiEnabled).toBe(false);
});
+ test("updates the AI SQL review switch from a successful setting response", async () => {
+ const store = createStore();
+ const switchedOn = aiSetting(true, true);
+ mocks.updateSetting.mockResolvedValueOnce(switchedOn);
+
+ await store.upsertSetting({
+ name: Setting_SettingName.AI,
+ value: switchedOn.value!,
+ });
+ expect(store.serverInfo?.aiSqlReviewEnabled).toBe(true);
+
+ const switchedOff = aiSetting(true, false);
+ mocks.updateSetting.mockResolvedValueOnce(switchedOff);
+ await store.upsertSetting({
+ name: Setting_SettingName.AI,
+ value: switchedOff.value!,
+ });
+ expect(store.serverInfo?.aiSqlReviewEnabled).toBe(false);
+ expect(store.serverInfo?.aiEnabled).toBe(true);
+ });
+
test("does not change Ask AI availability when the setting save fails", async () => {
const store = createStore();
mocks.updateSetting.mockRejectedValueOnce(new Error("save failed"));
diff --git a/frontend/src/stores/app/workspace.ts b/frontend/src/stores/app/workspace.ts
index 91f49ba191..0f92fd80bb 100644
--- a/frontend/src/stores/app/workspace.ts
+++ b/frontend/src/stores/app/workspace.ts
@@ -445,6 +445,7 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
serverInfo: state.serverInfo && {
...state.serverInfo,
aiEnabled: settingValue.value.enabled,
+ aiSqlReviewEnabled: settingValue.value.sqlReviewEnabled,
},
}));
}
diff --git a/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts b/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts
index 0ac62fe99c..f902b1a0ef 100644
--- a/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts
@@ -208,6 +208,14 @@ export declare type ActuatorInfo = Message<"bytebase.v1.ActuatorInfo"> & {
* @generated from field: bool ai_enabled = 31;
*/
aiEnabled: boolean;
+
+ /**
+ * Whether the workspace AI setting switches the AI SQL review on. A review
+ * also needs `ai_enabled`.
+ *
+ * @generated from field: bool ai_sql_review_enabled = 32;
+ */
+ aiSqlReviewEnabled: boolean;
};
/**
diff --git a/frontend/src/types/proto-es/v1/actuator_service_pb.js b/frontend/src/types/proto-es/v1/actuator_service_pb.js
index c99f855950..6773cd1841 100644
--- a/frontend/src/types/proto-es/v1/actuator_service_pb.js
+++ b/frontend/src/types/proto-es/v1/actuator_service_pb.js
@@ -15,7 +15,7 @@ import { file_v1_setting_service } from "./setting_service_pb";
* Describes the file v1/actuator_service.proto.
*/
export const file_v1_actuator_service = /*@__PURE__*/
- fileDesc("Chl2MS9hY3R1YXRvcl9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSIYChZHZXRBY3R1YXRvckluZm9SZXF1ZXN0ItEBCgpTYW1wbGVJbmZvEhYKCWF2YWlsYWJsZRgBIAEoCEID4EEDEjg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aMoYBCg9BY3R1YXRvclNlcnZpY2UScwoPR2V0QWN0dWF0b3JJbmZvEiMuYnl0ZWJhc2UudjEuR2V0QWN0dWF0b3JJbmZvUmVxdWVzdBoZLmJ5dGViYXNlLnYxLkFjdHVhdG9ySW5mbyIg2kEAoOowAYLT5JMCExIRL3YxL2FjdHVhdG9yL2luZm9CqgEKD2NvbS5ieXRlYmFzZS52MUIUQWN0dWF0b3JTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_timestamp, file_v1_annotation, file_v1_setting_service]);
+ fileDesc("Chl2MS9hY3R1YXRvcl9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSIYChZHZXRBY3R1YXRvckluZm9SZXF1ZXN0ItEBCgpTYW1wbGVJbmZvEhYKCWF2YWlsYWJsZRgBIAEoCEID4EEDEjgKCWluc3RhbmNlcxgCIAMoCzIgLmJ5dGViYXNlLnYxLlNhbXBsZUluZm8uSW5zdGFuY2VCA+BBAxpxCghJbnN0YW5jZRIvCghpbnN0YW5jZRgBIAEoCUId4EED+kEXChVieXRlYmFzZS5jb20vSW5zdGFuY2USNAoLZXhwaXJlX3RpbWUYAiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wQgPgQQMioQUKDEFjdHVhdG9ySW5mbxIUCgd2ZXJzaW9uGAEgASgJQgPgQQMSFwoKZ2l0X2NvbW1pdBgCIAEoCUID4EEDEhEKBHNhYXMYBCABKAhCA+BBAxIZCgxleHRlcm5hbF91cmwYCCABKAlCA+BBAxI5ChBsYXN0X2FjdGl2ZV90aW1lGAsgASg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hc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_timestamp, file_v1_annotation, file_v1_setting_service]);
/**
* Describes the message bytebase.v1.GetActuatorInfoRequest.
diff --git a/frontend/src/types/proto-es/v1/setting_service_pb.d.ts b/frontend/src/types/proto-es/v1/setting_service_pb.d.ts
index 9009713dd7..c51ee58a3e 100644
--- a/frontend/src/types/proto-es/v1/setting_service_pb.d.ts
+++ b/frontend/src/types/proto-es/v1/setting_service_pb.d.ts
@@ -1394,6 +1394,16 @@ export declare type AISetting = Message<"bytebase.v1.AISetting"> & {
* @generated from field: string version = 6;
*/
version: string;
+
+ /**
+ * Whether the AI SQL review may run. It is off by default and is a consent
+ * of its own beside `enabled`: a review sends the statements of a change to
+ * the provider, and can send the schema of its target databases and their
+ * table statistics.
+ *
+ * @generated from field: bool sql_review_enabled = 7;
+ */
+ sqlReviewEnabled: boolean;
};
/**
diff --git a/frontend/src/types/proto-es/v1/setting_service_pb.js b/frontend/src/types/proto-es/v1/setting_service_pb.js
index 7b66542aef..5d388ff6f2 100644
--- a/frontend/src/types/proto-es/v1/setting_service_pb.js
+++ b/frontend/src/types/proto-es/v1/setting_service_pb.js
@@ -18,7 +18,7 @@ import { file_v1_issue_service } from "./issue_service_pb";
* Describes the file v1/setting_service.proto.
*/
export const file_v1_setting_service = /*@__PURE__*/
- fileDesc("Chh2MS9zZXR0aW5nX3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIhUKE0xpc3RTZXR0aW5nc1JlcXVlc3QiPgoUTGlzdFNldHRpbmdzUmVzcG9uc2USJgoIc2V0dGluZ3MYASADKAsyFC5ieXRlYmFzZS52MS5TZXR0aW5nIj8KEUdldFNldHRpbmdSZXF1ZXN0EioKBG5hbWUYASABKAlCHOBBAvpBFgoUYnl0ZWJhc2UuY29tL1NldHRpbmciO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N9pBAIrqMBBiYi5zZXR0aW5ncy5saXN0kOowAaDqMASo6jAJgtPkkwIOEgwvdjEvc2V0dGluZ3MShwEKCkdldFNldHRpbmcSHi5ieXRlYmFzZS52MS5HZXRTZXR0aW5nUmVxdWVzdBoULmJ5dGViYXNlLnYxLlNldHRpbmciQ9pBBG5hbWWK6jAPYmIuc2V0dGluZ3MuZ2V0kOowAqDqMASo6jAJgtPkkwIXEhUvdjEve25hbWU9c2V0dGluZ3MvKn0SmwEKDVVwZGF0ZVNldHRpbmcSIS5ieXRlYmFzZS52MS5VcGRhdGVTZXR0aW5nUmVxdWVzdBoULmJ5dGViYXNlLnYxLlNldHRpbmciUYrqMA9iYi5zZXR0aW5ncy5zZXSQ6jACmOowAaDqMAOo6jAHgtPkkwIoOgdzZXR0aW5nMh0vdjEve3NldHRpbmcubmFtZT1zZXR0aW5ncy8qfRK4AQoQVGVzdEVtYWlsU2V0dGluZxIkLmJ5dGViYXNlLnYxLlRlc3RFbWFpbFNldHRpbmdSZXF1ZXN0GiUuYnl0ZWJhc2UudjEuVGVzdEVtYWlsU2V0dGluZ1Jlc3BvbnNlIleK6jAPYmIuc2V0dGluZ3Muc2V0kOowAaDqMAOo6jAGgtPkkwIyOgEqIi0vdjEve3BhcmVudD13b3Jrc3BhY2VzLyp9L3NldHRpbmdzL0VNQUlMOnRlc3RCqQEKD2NvbS5ieXRlYmFzZS52MUITU2V0dGluZ1NlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [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_type_color, file_google_type_expr, file_v1_annotation, file_v1_common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dTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [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_type_color, file_google_type_expr, file_v1_annotation, file_v1_common, file_v1_issue_service]);
/**
* Describes the message bytebase.v1.ListSettingsRequest.
diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yaml
index 5a258d9d56..cec8e98fac 100644
--- a/proto/gen/grpc-doc/openapi.yaml
+++ b/proto/gen/grpc-doc/openapi.yaml
@@ -16716,6 +16716,14 @@ components:
version:
type: string
title: version
+ sqlReviewEnabled:
+ type: boolean
+ title: sql_review_enabled
+ description: |-
+ Whether the AI SQL review may run. It is off by default and is a consent
+ of its own beside `enabled`: a review sends the statements of a change to
+ the provider, and can send the schema of its target databases and their
+ table statistics.
title: AISetting
additionalProperties: false
bytebase.v1.AISetting.Provider:
@@ -16982,6 +16990,13 @@ components:
title: ai_enabled
description: Whether the workspace AI setting enables the AI agent.
readOnly: true
+ aiSqlReviewEnabled:
+ type: boolean
+ title: ai_sql_review_enabled
+ description: |-
+ Whether the workspace AI setting switches the AI SQL review on. A review
+ also needs `ai_enabled`.
+ readOnly: true
title: ActuatorInfo
additionalProperties: false
description: |-
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index 9bd0747a25..9e604f04d6 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -3654,6 +3654,7 @@ All other settings live in per-workspace WORKSPACE_PROFILE.
| api_key | [string](#string) | | |
| model | [string](#string) | | |
| version | [string](#string) | | |
+| sql_review_enabled | [bool](#bool) | | Whether the AI SQL review may run. It is a consent of its own beside `enabled`, because a review sends the statements of a change to the provider and can send the schema of its target databases. |
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index 4d8e0597ac..052a8522be 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -9696,6 +9696,15 @@ is deleted or transferred, degrading to &#34;no database&#34; in the UI. </p></t
<td><p> </p></td>
</tr>
+ <tr>
+ <td>sql_review_enabled</td>
+ <td><a href="#bool">bool</a></td>
+ <td></td>
+ <td><p>Whether the AI SQL review may run. It is a consent of its own beside
+`enabled`, because a review sends the statements of a change to the
+provider and can send the schema of its target databases. </p></td>
+ </tr>
+
</tbody>
</table>
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index 585586940a..e6d7218a5e 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -4130,6 +4130,7 @@ IssueService manages issues for tracking database changes and tasks.
| api_key | [string](#string) | | |
| model | [string](#string) | | |
| version | [string](#string) | | |
+| sql_review_enabled | [bool](#bool) | | Whether the AI SQL review may run. It is off by default and is a consent of its own beside `enabled`: a review sends the statements of a change to the provider, and can send the schema of its target databases and their table statistics. |
@@ -5087,6 +5088,7 @@ Actuator concept is similar to the Spring Boot Actuator.
| sample | [SampleInfo](#bytebase-v1-SampleInfo) | | Sample setup availability and provisioned resources. |
| mcp_setting | [MCPSetting](#bytebase-v1-MCPSetting) | | The MCP (Model Context Protocol) setting in the current workspace. |
| ai_enabled | [bool](#bool) | | Whether the workspace AI setting enables the AI agent. |
+| ai_sql_review_enabled | [bool](#bool) | | Whether the workspace AI setting switches the AI SQL review on. A review also needs `ai_enabled`. |
diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.html
index 0267e336f1..542f1e2dea 100644
--- a/proto/gen/grpc-doc/v1/index.html
+++ b/proto/gen/grpc-doc/v1/index.html
@@ -12516,6 +12516,16 @@ Permissions required: bb.reviewRuns.run</p></td>
<td><p> </p></td>
</tr>
+ <tr>
+ <td>sql_review_enabled</td>
+ <td><a href="#bool">bool</a></td>
+ <td></td>
+ <td><p>Whether the AI SQL review may run. It is off by default and is a consent
+of its own beside `enabled`: a review sends the statements of a change to
+the provider, and can send the schema of its target databases and their
+table statistics. </p></td>
+ </tr>
+
</tbody>
</table>
@@ -14906,6 +14916,14 @@ Format: projects/{id} </p></td>
<td><p>Whether the workspace AI setting enables the AI agent. </p></td>
</tr>
+ <tr>
+ <td>ai_sql_review_enabled</td>
+ <td><a href="#bool">bool</a></td>
+ <td></td>
+ <td><p>Whether the workspace AI setting switches the AI SQL review on. A review
+also needs `ai_enabled`. </p></td>
+ </tr>
+
</tbody>
</table>
diff --git a/proto/store/store/setting.proto b/proto/store/store/setting.proto
index 32fe6d6a34..0da85ee4fb 100644
--- a/proto/store/store/setting.proto
+++ b/proto/store/store/setting.proto
@@ -387,6 +387,10 @@ message AISetting {
string api_key = 4;
string model = 5;
string version = 6;
+ // Whether the AI SQL review may run. It is a consent of its own beside
+ // `enabled`, because a review sends the statements of a change to the
+ // provider and can send the schema of its target databases.
+ bool sql_review_enabled = 7;
}
message EnvironmentSetting {
diff --git a/proto/v1/v1/actuator_service.proto b/proto/v1/v1/actuator_service.proto
index 56ebf6ea0c..c76a59ea92 100644
--- a/proto/v1/v1/actuator_service.proto
+++ b/proto/v1/v1/actuator_service.proto
@@ -106,4 +106,8 @@ message ActuatorInfo {
// Whether the workspace AI setting enables the AI agent.
bool ai_enabled = 31 [(google.api.field_behavior) = OUTPUT_ONLY];
+
+ // Whether the workspace AI setting switches the AI SQL review on. A review
+ // also needs `ai_enabled`.
+ bool ai_sql_review_enabled = 32 [(google.api.field_behavior) = OUTPUT_ONLY];
}
diff --git a/proto/v1/v1/setting_service.proto b/proto/v1/v1/setting_service.proto
index 4eb26fdee3..dca9569c11 100644
--- a/proto/v1/v1/setting_service.proto
+++ b/proto/v1/v1/setting_service.proto
@@ -547,6 +547,11 @@ message AISetting {
string api_key = 4 [(bytebase.v1.audit_behavior) = SENSITIVE];
string model = 5;
string version = 6;
+ // Whether the AI SQL review may run. It is off by default and is a consent
+ // of its own beside `enabled`: a review sends the statements of a change to
+ // the provider, and can send the schema of its target databases and their
+ // table statistics.
+ bool sql_review_enabled = 7;
}
message EnvironmentSetting {