Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(approval): preserve per-sheet plan check summaries (#20274)
p0nyf88519fb1619
diff --git a/backend/api/v1/issue_hook.go b/backend/api/v1/issue_hook.goindex bf64ea7fa0..53247037eb 100644--- a/backend/api/v1/issue_hook.go+++ b/backend/api/v1/issue_hook.go@@ -49,7 +49,7 @@ func postCreateIssue(storepb.Issue_ROLE_GRANT,storepb.Issue_DATABASE_EXPORT:- if err := approval.FindAndApplyApprovalTemplate(ctx, stores, webhookManager, licenseService, issue); err != nil {+ if err := approval.FindAndApplyApprovalTemplate(ctx, stores, b, webhookManager, licenseService, issue); err != nil {slog.Error("failed to find approval template",slog.String("project", issue.ProjectID), slog.Int64("issue_uid", issue.UID),slog.String("issue_title", issue.Title),diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.goindex 09f0cb0026..b90bd7bbf4 100644--- a/backend/api/v1/issue_service.go+++ b/backend/api/v1/issue_service.go@@ -885,7 +885,7 @@ func (s *IssueService) RetryIssueApproval(ctx context.Context, req *connect.Requreturn connect.NewResponse(issueV1), nil}- if err := approval.FindAndApplyApprovalTemplate(ctx, s.store, s.webhookManager, s.licenseService, issue); err != nil {+ if err := approval.FindAndApplyApprovalTemplate(ctx, s.store, s.bus, s.webhookManager, s.licenseService, issue); err != nil {// Surface the underlying cause (e.g. CEL error in the workspace// approval rule) so the operator can fix it.return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Wrap(err, "approval finding still failing"))diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.goindex dddf7752f0..1e66865469 100644--- a/backend/api/v1/plan_service.go+++ b/backend/api/v1/plan_service.go@@ -359,7 +359,7 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *connect.Request[v// which will trigger approval finding on completion// DATABASE_EXPORT: Re-run approval finding synchronously (no plan checks for export data)if updatedIssue.Type == storepb.Issue_DATABASE_EXPORT {- if err := approval.FindAndApplyApprovalTemplate(ctx, s.store, s.webhookManager, s.licenseService, updatedIssue); err != nil {+ if err := approval.FindAndApplyApprovalTemplate(ctx, s.store, s.bus, s.webhookManager, s.licenseService, updatedIssue); err != nil {slog.Error("failed to find approval template after plan update",slog.String("project", updatedIssue.ProjectID), slog.Int64("issue_uid", updatedIssue.UID),slog.String("issue_title", updatedIssue.Title),diff --git a/backend/generated-go/store/plan_check_run.pb.go b/backend/generated-go/store/plan_check_run.pb.goindex 3a8c14bfb5..4249f6e2b5 100644--- a/backend/generated-go/store/plan_check_run.pb.go+++ b/backend/generated-go/store/plan_check_run.pb.go@@ -336,6 +336,9 @@ type PlanCheckRunResult_Result struct {// Format: instances/{instance}/databases/{database}Target string `protobuf:"bytes,7,opt,name=target,proto3" json:"target,omitempty"`Type PlanCheckType `protobuf:"varint,8,opt,name=type,proto3,enum=bytebase.store.PlanCheckType" json:"type,omitempty"`+ // sheet_sha256 is the content hash of the SQL sheet used to produce this result.+ // Empty for checks that are not tied to a SQL sheet.+ SheetSha256 string `protobuf:"bytes,9,opt,name=sheet_sha256,json=sheetSha256,proto3" json:"sheet_sha256,omitempty"`// Types that are valid to be assigned to Report://// *PlanCheckRunResult_Result_SqlSummaryReport_@@ -417,6 +420,13 @@ func (x *PlanCheckRunResult_Result) GetType() PlanCheckType {return PlanCheckType_PLAN_CHECK_TYPE_UNSPECIFIED}+func (x *PlanCheckRunResult_Result) GetSheetSha256() string {+ if x != nil {+ return x.SheetSha256+ }+ return ""+}+func (x *PlanCheckRunResult_Result) GetReport() isPlanCheckRunResult_Result_Report {if x != nil {return x.Report@@ -576,17 +586,18 @@ var File_store_plan_check_run_proto protoreflect.FileDescriptorconst file_store_plan_check_run_proto_rawDesc = "" +"\n" +- "\x1astore/plan_check_run.proto\x12\x0ebytebase.store\x1a\x12store/advice.proto\x1a\x12store/common.proto\"\x82\a\n" ++ "\x1astore/plan_check_run.proto\x12\x0ebytebase.store\x1a\x12store/advice.proto\x1a\x12store/common.proto\"\xa5\a\n" +"\x12PlanCheckRunResult\x12C\n" +"\aresults\x18\x01 \x03(\v2).bytebase.store.PlanCheckRunResult.ResultR\aresults\x12\x14\n" +- "\x05error\x18\x02 \x01(\tR\x05error\x1a\x90\x06\n" ++ "\x05error\x18\x02 \x01(\tR\x05error\x1a\xb3\x06\n" +"\x06Result\x125\n" +"\x06status\x18\x01 \x01(\x0e2\x1d.bytebase.store.Advice.StatusR\x06status\x12\x14\n" +"\x05title\x18\x02 \x01(\tR\x05title\x12\x18\n" +"\acontent\x18\x03 \x01(\tR\acontent\x12\x12\n" +"\x04code\x18\x04 \x01(\x05R\x04code\x12\x16\n" +"\x06target\x18\a \x01(\tR\x06target\x121\n" +- "\x04type\x18\b \x01(\x0e2\x1d.bytebase.store.PlanCheckTypeR\x04type\x12j\n" ++ "\x04type\x18\b \x01(\x0e2\x1d.bytebase.store.PlanCheckTypeR\x04type\x12!\n" ++ "\fsheet_sha256\x18\t \x01(\tR\vsheetSha256\x12j\n" +"\x12sql_summary_report\x18\x05 \x01(\v2:.bytebase.store.PlanCheckRunResult.Result.SqlSummaryReportH\x00R\x10sqlSummaryReport\x12g\n" +"\x11sql_review_report\x18\x06 \x01(\v29.bytebase.store.PlanCheckRunResult.Result.SqlReviewReportH\x00R\x0fsqlReviewReport\x1a\xce\x01\n" +"\x10SqlSummaryReport\x12F\n" +diff --git a/backend/generated-go/store/plan_check_run_equal.pb.go b/backend/generated-go/store/plan_check_run_equal.pb.goindex 3309c588f9..d6744b85ba 100644--- a/backend/generated-go/store/plan_check_run_equal.pb.go+++ b/backend/generated-go/store/plan_check_run_equal.pb.go@@ -68,6 +68,9 @@ func (x *PlanCheckRunResult_Result) Equal(y *PlanCheckRunResult_Result) bool {if x.Type != y.Type {return false}+ if x.SheetSha256 != y.SheetSha256 {+ return false+ }if !x.GetSqlSummaryReport().Equal(y.GetSqlSummaryReport()) {return false}diff --git a/backend/runner/approval/runner.go b/backend/runner/approval/runner.goindex 3c336e9a39..b98e56b188 100644--- a/backend/runner/approval/runner.go+++ b/backend/runner/approval/runner.go@@ -63,7 +63,7 @@ func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {// FindAndApplyApprovalTemplate finds and applies the approval template for an issue.// This is a utility function that can be called synchronously (from issue creation)// or asynchronously (from the event handler).-func FindAndApplyApprovalTemplate(ctx context.Context, stores *store.Store, webhookManager *webhook.Manager, licenseService *enterprise.LicenseService, issue *store.IssueMessage) error {+func FindAndApplyApprovalTemplate(ctx context.Context, stores *store.Store, b *bus.Bus, webhookManager *webhook.Manager, licenseService *enterprise.LicenseService, issue *store.IssueMessage) error {project, err := stores.GetProjectByResourceID(ctx, issue.ProjectID)if err != nil {return errors.Wrap(err, "failed to get project")@@ -77,7 +77,7 @@ func FindAndApplyApprovalTemplate(ctx context.Context, stores *store.Store, webh}// Find approval template - errors are logged, not persisted- err = findApprovalTemplateForIssue(ctx, stores, webhookManager, licenseService, issue, approvalSetting)+ err = findApprovalTemplateForIssue(ctx, stores, b, webhookManager, licenseService, issue, approvalSetting)if err != nil {return errors.Wrap(err, "failed to find approval template")}@@ -112,7 +112,7 @@ func (r *Runner) processIssue(ctx context.Context, ref bus.IssueRef) {return}- if err := findApprovalTemplateForIssue(ctx, r.store, r.webhookManager, r.licenseService, issue, approvalSetting); err != nil {+ if err := findApprovalTemplateForIssue(ctx, r.store, r.bus, r.webhookManager, r.licenseService, issue, approvalSetting); err != nil {slog.Error("failed to find approval template",slog.String("project", ref.ProjectID), slog.Int64("issue_uid", ref.UID),slog.String("issue_title", issue.Title),@@ -148,7 +148,7 @@ func (r *Runner) processIssue(ctx context.Context, ref bus.IssueRef) {}}-func findApprovalTemplateForIssue(ctx context.Context, stores *store.Store, webhookManager *webhook.Manager, licenseService *enterprise.LicenseService, issue *store.IssueMessage, approvalSetting *storepb.WorkspaceApprovalSetting) error {+func findApprovalTemplateForIssue(ctx context.Context, stores *store.Store, b *bus.Bus, webhookManager *webhook.Manager, licenseService *enterprise.LicenseService, issue *store.IssueMessage, approvalSetting *storepb.WorkspaceApprovalSetting) error {payload := issue.Payloadif payload.Approval != nil && payload.Approval.ApprovalFindingDone {return nil@@ -180,7 +180,7 @@ func findApprovalTemplateForIssue(ctx context.Context, stores *store.Store, webh}// Step 2: Build CEL variables for evaluation- celVarsList, done, err := buildCELVariablesForIssue(ctx, stores, issue)+ celVarsList, done, err := buildCELVariablesForIssue(ctx, stores, b, issue)if err != nil {return nil, nil, false, errors.Wrap(err, "failed to build CEL variables for issue")}@@ -384,12 +384,12 @@ func buildFallbackCELVars(celVarsList []map[string]any) []map[string]any {// buildCELVariablesForIssue builds the CEL variable maps for evaluating approval rules.// Returns a list of CEL variable maps (one per task/component), done flag, and error.// done=false means the caller should retry later (e.g., waiting for plan check runs).-func buildCELVariablesForIssue(ctx context.Context, stores *store.Store, issue *store.IssueMessage) ([]map[string]any, bool, error) {+func buildCELVariablesForIssue(ctx context.Context, stores *store.Store, b *bus.Bus, issue *store.IssueMessage) ([]map[string]any, bool, error) {switch issue.Type {case storepb.Issue_ROLE_GRANT:return buildCELVariablesForRoleGrant(ctx, stores, issue)case storepb.Issue_DATABASE_CHANGE:- return buildCELVariablesForDatabaseChange(ctx, stores, issue)+ return buildCELVariablesForDatabaseChange(ctx, stores, b, issue)case storepb.Issue_DATABASE_EXPORT:return buildCELVariablesForDataExport(ctx, stores, issue)case storepb.Issue_ACCESS_GRANT:@@ -515,9 +515,101 @@ func unfoldSpecTargets(ctx context.Context, stores *store.Store, specs []*storepreturn targets, nil}+type statementSummaryKey struct {+ InstanceID string+ DatabaseName string+ SheetSHA256 string+}++func buildStatementSummaryResultMap(results []*storepb.PlanCheckRunResult_Result) map[statementSummaryKey]*storepb.PlanCheckRunResult_Result {+ m := map[statementSummaryKey]*storepb.PlanCheckRunResult_Result{}+ for _, result := range results {+ if result.Type != storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT {+ continue+ }+ instanceID, databaseName, err := common.GetInstanceDatabaseID(result.Target)+ if err != nil {+ continue+ }+ m[statementSummaryKey{+ InstanceID: instanceID,+ DatabaseName: databaseName,+ SheetSHA256: result.SheetSha256,+ }] = result+ }+ return m+}++func hasLegacyStatementSummaryResult(planCheckRun *store.PlanCheckRunMessage, targets []specTarget) bool {+ if planCheckRun == nil || planCheckRun.Status != store.PlanCheckRunStatusDone {+ return false+ }++ type databaseKey struct {+ InstanceID string+ DatabaseName string+ }+ sheetBackedTargets := map[databaseKey]struct{}{}+ for _, target := range targets {+ if target.sheetSha256 == "" || target.database == nil {+ continue+ }+ sheetBackedTargets[databaseKey{+ InstanceID: target.database.InstanceID,+ DatabaseName: target.database.DatabaseName,+ }] = struct{}{}+ }+ if len(sheetBackedTargets) == 0 {+ return false+ }++ for _, result := range planCheckRun.Result.GetResults() {+ if result.Type != storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT || result.SheetSha256 != "" {+ continue+ }+ instanceID, databaseName, err := common.GetInstanceDatabaseID(result.Target)+ if err != nil {+ continue+ }+ if _, ok := sheetBackedTargets[databaseKey{InstanceID: instanceID, DatabaseName: databaseName}]; ok {+ return true+ }+ }+ return false+}++func isPlanCheckRunPendingApprovalEvaluation(planCheckRun *store.PlanCheckRunMessage) bool {+ if planCheckRun == nil {+ return false+ }+ return planCheckRun.Status == store.PlanCheckRunStatusAvailable || planCheckRun.Status == store.PlanCheckRunStatusRunning+}++func shouldRerunLegacyStatementSummaryResult(planCheckRun *store.PlanCheckRunMessage, targets []specTarget) bool {+ return hasLegacyStatementSummaryResult(planCheckRun, targets)+}++func rerunPlanChecksForApproval(ctx context.Context, stores *store.Store, b *bus.Bus, plan *store.PlanMessage) error {+ if b == nil {+ return errors.New("approval plan-check rerun requires bus")+ }+ if err := stores.CreatePlanCheckRun(ctx, &store.PlanCheckRunMessage{+ ProjectID: plan.ProjectID,+ PlanUID: plan.UID,+ Result: &storepb.PlanCheckRunResult{},+ }); err != nil {+ return errors.Wrap(err, "failed to create plan check run")+ }+ select {+ case b.PlanCheckTickleChan <- 0:+ default:+ }+ return nil+}+// buildCELVariablesForDatabaseChange builds CEL variables for DATABASE_CHANGE issues.// This includes DDL and DML operations.-func buildCELVariablesForDatabaseChange(ctx context.Context, stores *store.Store, issue *store.IssueMessage) ([]map[string]any, bool, error) {+func buildCELVariablesForDatabaseChange(ctx context.Context, stores *store.Store, b *bus.Bus, issue *store.IssueMessage) ([]map[string]any, bool, error) {if issue.PlanUID == nil {return nil, false, errors.Errorf("expected plan UID in issue %v", issue.UID)}@@ -534,41 +626,29 @@ func buildCELVariablesForDatabaseChange(ctx context.Context, stores *store.Storereturn nil, false, errors.Wrapf(err, "failed to get plan check run for plan %v", plan.UID)}- type Key struct {- InstanceID string- DatabaseName string- }- latestPlanCheckRun := map[Key]*storepb.PlanCheckRunResult_Result{}-- // Wait for plan check to complete if running- if planCheckRun != nil && planCheckRun.Status == store.PlanCheckRunStatusRunning {+ // Wait for plan check to complete if available or running.+ if isPlanCheckRunPendingApprovalEvaluation(planCheckRun) {return nil, false, nil // Not ready yet, retry later}- // Build map from results, filtering for STATEMENT_SUMMARY_REPORT- if planCheckRun != nil {- for _, result := range planCheckRun.Result.Results {- if result.Type != storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT {- continue- }- instanceID, databaseName, err := common.GetInstanceDatabaseID(result.Target)- if err != nil {- continue- }- key := Key{- InstanceID: instanceID,- DatabaseName: databaseName,- }- latestPlanCheckRun[key] = result- }- }-// Unfold database groups and get all targetstargets, err := unfoldSpecTargets(ctx, stores, plan.Config.GetSpecs(), issue.ProjectID)if err != nil {return nil, false, errors.Wrap(err, "failed to unfold spec targets")}+ if shouldRerunLegacyStatementSummaryResult(planCheckRun, targets) {+ if err := rerunPlanChecksForApproval(ctx, stores, b, plan); err != nil {+ return nil, false, err+ }+ return nil, false, nil+ }++ statementSummaryResults := map[statementSummaryKey]*storepb.PlanCheckRunResult_Result{}+ if planCheckRun != nil {+ statementSummaryResults = buildStatementSummaryResultMap(planCheckRun.Result.GetResults())+ }+var celVarsList []map[string]anyfor _, target := range targets {taskStatement := ""@@ -599,9 +679,10 @@ func buildCELVariablesForDatabaseChange(ctx context.Context, stores *store.Store}// Add summary report data if available- result, ok := latestPlanCheckRun[Key{+ result, ok := statementSummaryResults[statementSummaryKey{InstanceID: target.database.InstanceID,DatabaseName: target.database.DatabaseName,+ SheetSHA256: target.sheetSha256,}]if !ok {celVarsList = append(celVarsList, celVars)diff --git a/backend/runner/approval/runner_test.go b/backend/runner/approval/runner_test.goindex 239df85f3d..7f887b58e9 100644--- a/backend/runner/approval/runner_test.go+++ b/backend/runner/approval/runner_test.go@@ -7,6 +7,7 @@ import ("github.com/bytebase/bytebase/backend/common"storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/store")func TestRiskLevelToString(t *testing.T) {@@ -175,3 +176,244 @@ func TestCalculateRiskLevelFromCELVars(t *testing.T) {})}}++func TestBuildStatementSummaryResultMapUsesSheetSHA256(t *testing.T) {+ results := []*storepb.PlanCheckRunResult_Result{+ {+ Target: "instances/prod/databases/app",+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,+ SheetSha256: "sheet-a",+ Report: &storepb.PlanCheckRunResult_Result_SqlSummaryReport_{+ SqlSummaryReport: &storepb.PlanCheckRunResult_Result_SqlSummaryReport{+ AffectedRows: 10,+ },+ },+ },+ {+ Target: "instances/prod/databases/app",+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,+ SheetSha256: "sheet-b",+ Report: &storepb.PlanCheckRunResult_Result_SqlSummaryReport_{+ SqlSummaryReport: &storepb.PlanCheckRunResult_Result_SqlSummaryReport{+ AffectedRows: 20,+ },+ },+ },+ }++ got := buildStatementSummaryResultMap(results)++ require.Equal(t, int64(10), got[statementSummaryKey{+ InstanceID: "prod",+ DatabaseName: "app",+ SheetSHA256: "sheet-a",+ }].GetSqlSummaryReport().GetAffectedRows())+ require.Equal(t, int64(20), got[statementSummaryKey{+ InstanceID: "prod",+ DatabaseName: "app",+ SheetSHA256: "sheet-b",+ }].GetSqlSummaryReport().GetAffectedRows())+}++func TestHasLegacyStatementSummaryResultForSheetTarget(t *testing.T) {+ sheetTargets := []specTarget{+ {+ database: &store.DatabaseMessage{+ InstanceID: "prod",+ DatabaseName: "app",+ },+ sheetSha256: "sheet-a",+ },+ }+ tests := []struct {+ name string+ planCheckRun *store.PlanCheckRunMessage+ targets []specTarget+ want bool+ }{+ {+ name: "legacy summary result for sheet target",+ planCheckRun: &store.PlanCheckRunMessage{+ Status: store.PlanCheckRunStatusDone,+ Result: &storepb.PlanCheckRunResult{+ Results: []*storepb.PlanCheckRunResult_Result{+ {+ Target: "instances/prod/databases/app",+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,+ },+ },+ },+ },+ targets: sheetTargets,+ want: true,+ },+ {+ name: "sheet-tagged result is not legacy",+ planCheckRun: &store.PlanCheckRunMessage{+ Status: store.PlanCheckRunStatusDone,+ Result: &storepb.PlanCheckRunResult{+ Results: []*storepb.PlanCheckRunResult_Result{+ {+ Target: "instances/prod/databases/app",+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,+ SheetSha256: "sheet-a",+ },+ },+ },+ },+ targets: sheetTargets,+ },+ {+ name: "non-sheet target is not legacy",+ planCheckRun: &store.PlanCheckRunMessage{+ Status: store.PlanCheckRunStatusDone,+ Result: &storepb.PlanCheckRunResult{+ Results: []*storepb.PlanCheckRunResult_Result{+ {+ Target: "instances/prod/databases/app",+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,+ },+ },+ },+ },+ targets: []specTarget{+ {+ database: &store.DatabaseMessage{+ InstanceID: "prod",+ DatabaseName: "app",+ },+ },+ },+ },+ {+ name: "non-summary result is not legacy",+ planCheckRun: &store.PlanCheckRunMessage{+ Status: store.PlanCheckRunStatusDone,+ Result: &storepb.PlanCheckRunResult{+ Results: []*storepb.PlanCheckRunResult_Result{+ {+ Target: "instances/prod/databases/app",+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE,+ },+ },+ },+ },+ targets: sheetTargets,+ },+ {+ name: "invalid target is not legacy",+ planCheckRun: &store.PlanCheckRunMessage{+ Status: store.PlanCheckRunStatusDone,+ Result: &storepb.PlanCheckRunResult{+ Results: []*storepb.PlanCheckRunResult_Result{+ {+ Target: "bad-target",+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,+ },+ },+ },+ },+ targets: sheetTargets,+ },+ {+ name: "non-matching target is not legacy",+ planCheckRun: &store.PlanCheckRunMessage{+ Status: store.PlanCheckRunStatusDone,+ Result: &storepb.PlanCheckRunResult{+ Results: []*storepb.PlanCheckRunResult_Result{+ {+ Target: "instances/prod/databases/other",+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,+ },+ },+ },+ },+ targets: sheetTargets,+ },+ {+ name: "non-DONE status is not legacy",+ planCheckRun: &store.PlanCheckRunMessage{+ Status: store.PlanCheckRunStatusAvailable,+ Result: &storepb.PlanCheckRunResult{+ Results: []*storepb.PlanCheckRunResult_Result{+ {+ Target: "instances/prod/databases/app",+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,+ },+ },+ },+ },+ targets: sheetTargets,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ require.Equal(t, tt.want, hasLegacyStatementSummaryResult(tt.planCheckRun, tt.targets))+ })+ }+}++func TestIsPlanCheckRunPendingApprovalEvaluation(t *testing.T) {+ tests := []struct {+ name string+ planCheckRun *store.PlanCheckRunMessage+ want bool+ }{+ {+ name: "nil plan check run is ready to evaluate",+ planCheckRun: nil,+ },+ {+ name: "AVAILABLE is not ready",+ planCheckRun: &store.PlanCheckRunMessage{Status: store.PlanCheckRunStatusAvailable},+ want: true,+ },+ {+ name: "RUNNING is not ready",+ planCheckRun: &store.PlanCheckRunMessage{Status: store.PlanCheckRunStatusRunning},+ want: true,+ },+ {+ name: "DONE is ready",+ planCheckRun: &store.PlanCheckRunMessage{Status: store.PlanCheckRunStatusDone},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ require.Equal(t, tt.want, isPlanCheckRunPendingApprovalEvaluation(tt.planCheckRun))+ })+ }+}++func TestShouldRerunLegacyStatementSummaryResult(t *testing.T) {+ targets := []specTarget{+ {+ database: &store.DatabaseMessage{+ InstanceID: "prod",+ DatabaseName: "app",+ },+ sheetSha256: "sheet-a",+ },+ }+ planCheckRun := &store.PlanCheckRunMessage{+ Status: store.PlanCheckRunStatusDone,+ Result: &storepb.PlanCheckRunResult{+ Results: []*storepb.PlanCheckRunResult_Result{+ {+ Target: "instances/prod/databases/app",+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,+ },+ },+ },+ }++ require.True(t, shouldRerunLegacyStatementSummaryResult(planCheckRun, targets))++ planCheckRun.Result.Results[0].SheetSha256 = "sheet-a"+ require.False(t, shouldRerunLegacyStatementSummaryResult(planCheckRun, targets))++ planCheckRun.Result.Results[0].SheetSha256 = ""+ require.True(t, shouldRerunLegacyStatementSummaryResult(planCheckRun, targets))+}diff --git a/backend/runner/plancheck/executor_combined.go b/backend/runner/plancheck/executor_combined.goindex 85fa09f553..4ff2dbf336 100644--- a/backend/runner/plancheck/executor_combined.go+++ b/backend/runner/plancheck/executor_combined.go@@ -39,12 +39,13 @@ func (e *CombinedExecutor) RunForTarget(ctx context.Context, target *CheckTargetif err != nil {// Add error result for this target/type, continue to nextallResults = append(allResults, &storepb.PlanCheckRunResult_Result{- Status: storepb.Advice_ERROR,- Target: target.Target,- Type: checkType,- Title: "Check failed",- Content: err.Error(),- Code: common.Internal.Int32(),+ Status: storepb.Advice_ERROR,+ Target: target.Target,+ Type: checkType,+ SheetSha256: target.SheetSha256,+ Title: "Check failed",+ Content: err.Error(),+ Code: common.Internal.Int32(),})continue}@@ -52,6 +53,7 @@ func (e *CombinedExecutor) RunForTarget(ctx context.Context, target *CheckTargetfor _, r := range results {r.Target = target.Targetr.Type = checkType+ r.SheetSha256 = target.SheetSha256}allResults = append(allResults, results...)}diff --git a/docs/superpowers/plans/2026-05-09-byt-9422-plan-check-sheet-identity.md b/docs/superpowers/plans/2026-05-09-byt-9422-plan-check-sheet-identity.mdnew file mode 100644index 0000000000..125bc2d69c--- /dev/null+++ b/docs/superpowers/plans/2026-05-09-byt-9422-plan-check-sheet-identity.md@@ -0,0 +1,590 @@+# BYT-9422 Plan Check Sheet Identity Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Persist SQL sheet identity on plan-check results so approval evaluation handles multiple specs targeting the same database without spec-order-dependent governance bypass.++**Architecture:** Add `sheet_sha256` to the stored plan-check result proto, propagate it from `plancheck.CheckTarget`, and use it in approval statement-summary lookup keys. Approval generation will detect legacy completed summary results without sheet identity, recreate the plan-check run, tickle the scheduler, and wait for the normal async completion path.++**Tech Stack:** Go, protobuf, buf, protojson, Bytebase store layer, plancheck runner, approval runner, testify.++---++## File Structure++- Modify `proto/store/store/plan_check_run.proto`: add internal stored result field `sheet_sha256`.+- Modify generated files under `backend/generated-go/store/`: regenerate after the proto change.+- Modify `backend/runner/plancheck/executor_combined.go`: extract result-tagging helper and copy `SheetSha256`.+- Create `backend/runner/plancheck/executor_combined_test.go`: test result tagging without database dependencies.+- Modify `backend/runner/approval/runner.go`: pass the bus into approval finding, detect legacy plan-check results, recreate stale runs, and key summary reports by sheet.+- Extend `backend/runner/approval/runner_test.go`: test summary map matching and legacy stale detection.+- Modify approval call sites in `backend/api/v1/issue_hook.go`, `backend/api/v1/issue_service.go`, and `backend/api/v1/plan_service.go`: pass the service bus to `approval.FindAndApplyApprovalTemplate`.++## Task 1: Add Stored Sheet Identity++**Files:**+- Modify: `proto/store/store/plan_check_run.proto`+- Regenerate: `backend/generated-go/store/plan_check_run.pb.go`+- Regenerate: `backend/generated-go/store/plan_check_run_equal.pb.go`++- [ ] **Step 1: Add the proto field**++Edit `proto/store/store/plan_check_run.proto` inside `message PlanCheckRunResult.Result`:++```proto+ // Target identification for consolidated results+ // Format: instances/{instance}/databases/{database}+ string target = 7;+ PlanCheckType type = 8;++ // sheet_sha256 is the content hash of the SQL sheet used to produce this result.+ // Empty for checks that are not tied to a SQL sheet.+ string sheet_sha256 = 9;+```++- [ ] **Step 2: Format and regenerate protobufs**++Run:++```bash+buf format -w proto+cd proto && buf generate+```++Expected: command exits `0`, and generated store Go files include `SheetSha256 string`.++- [ ] **Step 3: Verify generated field exists**++Run:++```bash+rg -n "SheetSha256|sheet_sha256" backend/generated-go/store/plan_check_run.pb.go backend/generated-go/store/plan_check_run_equal.pb.go+```++Expected: matches in both generated files.++- [ ] **Step 4: Commit proto identity field**++Run:++```bash+git add proto/store/store/plan_check_run.proto backend/generated-go/store/plan_check_run.pb.go backend/generated-go/store/plan_check_run_equal.pb.go+git commit -m "feat(plancheck): persist sheet identity in results"+```++## Task 2: Propagate Sheet Identity From Plan Check Targets++**Files:**+- Modify: `backend/runner/plancheck/executor_combined.go`+- Create: `backend/runner/plancheck/executor_combined_test.go`++- [ ] **Step 1: Write the failing result-tagging test**++Create `backend/runner/plancheck/executor_combined_test.go`:++```go+package plancheck++import (+ "testing"++ "github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+)++func TestTagPlanCheckResultsCopiesTargetMetadata(t *testing.T) {+ results := []*storepb.PlanCheckRunResult_Result{+ {+ Status: storepb.Advice_SUCCESS,+ Title: "ok",+ },+ }+ target := &CheckTarget{+ Target: "instances/prod/databases/app",+ SheetSha256: "abc123",+ }++ tagPlanCheckResults(results, target, storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT)++ require.Len(t, results, 1)+ require.Equal(t, "instances/prod/databases/app", results[0].Target)+ require.Equal(t, "abc123", results[0].SheetSha256)+ require.Equal(t, storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT, results[0].Type)+}+```++- [ ] **Step 2: Run the failing test**++Run:++```bash+go test -v -count=1 ./backend/runner/plancheck -run ^TestTagPlanCheckResultsCopiesTargetMetadata$+```++Expected: FAIL with `undefined: tagPlanCheckResults`.++- [ ] **Step 3: Extract tagging helper and copy sheet identity**++Edit `backend/runner/plancheck/executor_combined.go`:++```go+func (e *CombinedExecutor) RunForTarget(ctx context.Context, target *CheckTarget) ([]*storepb.PlanCheckRunResult_Result, error) {+ var allResults []*storepb.PlanCheckRunResult_Result++ for _, checkType := range target.Types {+ results, err := e.runCheck(ctx, target, checkType)+ if err != nil {+ // Add error result for this target/type, continue to next+ allResults = append(allResults, &storepb.PlanCheckRunResult_Result{+ Status: storepb.Advice_ERROR,+ Target: target.Target,+ Type: checkType,+ SheetSha256: target.SheetSha256,+ Title: "Check failed",+ Content: err.Error(),+ Code: common.Internal.Int32(),+ })+ continue+ }+ tagPlanCheckResults(results, target, checkType)+ allResults = append(allResults, results...)+ }++ return allResults, nil+}++func tagPlanCheckResults(results []*storepb.PlanCheckRunResult_Result, target *CheckTarget, checkType storepb.PlanCheckType) {+ for _, r := range results {+ r.Target = target.Target+ r.Type = checkType+ r.SheetSha256 = target.SheetSha256+ }+}+```++- [ ] **Step 4: Run the plancheck test**++Run:++```bash+go test -v -count=1 ./backend/runner/plancheck -run ^TestTagPlanCheckResultsCopiesTargetMetadata$+```++Expected: PASS.++- [ ] **Step 5: Commit target propagation**++Run:++```bash+gofmt -w backend/runner/plancheck/executor_combined.go backend/runner/plancheck/executor_combined_test.go+git add backend/runner/plancheck/executor_combined.go backend/runner/plancheck/executor_combined_test.go+git commit -m "fix(plancheck): tag results with sheet identity"+```++## Task 3: Match Approval Summaries By Sheet++**Files:**+- Modify: `backend/runner/approval/runner.go`+- Extend: `backend/runner/approval/runner_test.go`++- [ ] **Step 1: Write the failing summary-map test**++Append to `backend/runner/approval/runner_test.go`:++```go+func TestBuildStatementSummaryResultMapUsesSheetSHA256(t *testing.T) {+ results := []*storepb.PlanCheckRunResult_Result{+ {+ Target: "instances/prod/databases/app",+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,+ SheetSha256: "sheet-a",+ Report: &storepb.PlanCheckRunResult_Result_SqlSummaryReport_{+ SqlSummaryReport: &storepb.PlanCheckRunResult_Result_SqlSummaryReport{+ AffectedRows: 10,+ },+ },+ },+ {+ Target: "instances/prod/databases/app",+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,+ SheetSha256: "sheet-b",+ Report: &storepb.PlanCheckRunResult_Result_SqlSummaryReport_{+ SqlSummaryReport: &storepb.PlanCheckRunResult_Result_SqlSummaryReport{+ AffectedRows: 20,+ },+ },+ },+ }++ got := buildStatementSummaryResultMap(results)++ require.Equal(t, int64(10), got[statementSummaryKey{+ InstanceID: "prod",+ DatabaseName: "app",+ SheetSHA256: "sheet-a",+ }].GetSqlSummaryReport().GetAffectedRows())+ require.Equal(t, int64(20), got[statementSummaryKey{+ InstanceID: "prod",+ DatabaseName: "app",+ SheetSHA256: "sheet-b",+ }].GetSqlSummaryReport().GetAffectedRows())+}+```++- [ ] **Step 2: Run the failing summary-map test**++Run:++```bash+go test -v -count=1 ./backend/runner/approval -run ^TestBuildStatementSummaryResultMapUsesSheetSHA256$+```++Expected: FAIL with `undefined: buildStatementSummaryResultMap`.++- [ ] **Step 3: Add the sheet-aware summary map helper**++Edit `backend/runner/approval/runner.go` near `buildCELVariablesForDatabaseChange`:++```go+type statementSummaryKey struct {+ InstanceID string+ DatabaseName string+ SheetSHA256 string+}++func buildStatementSummaryResultMap(results []*storepb.PlanCheckRunResult_Result) map[statementSummaryKey]*storepb.PlanCheckRunResult_Result {+ m := map[statementSummaryKey]*storepb.PlanCheckRunResult_Result{}+ for _, result := range results {+ if result.Type != storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT {+ continue+ }+ instanceID, databaseName, err := common.GetInstanceDatabaseID(result.Target)+ if err != nil {+ continue+ }+ m[statementSummaryKey{+ InstanceID: instanceID,+ DatabaseName: databaseName,+ SheetSHA256: result.SheetSha256,+ }] = result+ }+ return m+}+```++- [ ] **Step 4: Use the helper in database-change CEL generation**++Inside `buildCELVariablesForDatabaseChange`, replace the local `Key` type and `latestPlanCheckRun` construction with:++```go+ statementSummaryResults := map[statementSummaryKey]*storepb.PlanCheckRunResult_Result{}+ if planCheckRun != nil {+ statementSummaryResults = buildStatementSummaryResultMap(planCheckRun.Result.GetResults())+ }+```++Then replace the lookup before `report := result.GetSqlSummaryReport()` with:++```go+ result, ok := statementSummaryResults[statementSummaryKey{+ InstanceID: target.database.InstanceID,+ DatabaseName: target.database.DatabaseName,+ SheetSHA256: target.sheetSha256,+ }]+```++- [ ] **Step 5: Run the summary-map test**++Run:++```bash+gofmt -w backend/runner/approval/runner.go backend/runner/approval/runner_test.go+go test -v -count=1 ./backend/runner/approval -run ^TestBuildStatementSummaryResultMapUsesSheetSHA256$+```++Expected: PASS.++- [ ] **Step 6: Commit sheet-aware approval lookup**++Run:++```bash+git add backend/runner/approval/runner.go backend/runner/approval/runner_test.go+git commit -m "fix(approval): match statement summaries by sheet"+```++## Task 4: Auto-Rerun Legacy Plan Checks During Approval++**Files:**+- Modify: `backend/runner/approval/runner.go`+- Extend: `backend/runner/approval/runner_test.go`+- Modify: `backend/api/v1/issue_hook.go`+- Modify: `backend/api/v1/issue_service.go`+- Modify: `backend/api/v1/plan_service.go`++- [ ] **Step 1: Write the failing legacy detection test**++Append to `backend/runner/approval/runner_test.go`:++```go+func TestHasLegacyStatementSummaryResultForSheetTarget(t *testing.T) {+ targets := []specTarget{+ {+ database: &store.DatabaseMessage{+ InstanceID: "prod",+ DatabaseName: "app",+ },+ sheetSha256: "sheet-a",+ },+ }+ planCheckRun := &store.PlanCheckRunMessage{+ Status: store.PlanCheckRunStatusDone,+ Result: &storepb.PlanCheckRunResult{+ Results: []*storepb.PlanCheckRunResult_Result{+ {+ Target: "instances/prod/databases/app",+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT,+ },+ },+ },+ }++ require.True(t, hasLegacyStatementSummaryResult(planCheckRun, targets))++ planCheckRun.Result.Results[0].SheetSha256 = "sheet-a"+ require.False(t, hasLegacyStatementSummaryResult(planCheckRun, targets))+}+```++Also add the missing store import at the top of `backend/runner/approval/runner_test.go`:++```go+ "github.com/bytebase/bytebase/backend/store"+```++- [ ] **Step 2: Run the failing legacy detection test**++Run:++```bash+go test -v -count=1 ./backend/runner/approval -run ^TestHasLegacyStatementSummaryResultForSheetTarget$+```++Expected: FAIL with `undefined: hasLegacyStatementSummaryResult`.++- [ ] **Step 3: Add legacy detection and rerun helpers**++Add helpers near the statement-summary map helper in `backend/runner/approval/runner.go`. The file already imports `backend/component/bus`, so the new helper can use `*bus.Bus` directly:++```go+func hasLegacyStatementSummaryResult(planCheckRun *store.PlanCheckRunMessage, targets []specTarget) bool {+ if planCheckRun == nil || planCheckRun.Status != store.PlanCheckRunStatusDone {+ return false+ }++ type databaseKey struct {+ InstanceID string+ DatabaseName string+ }+ sheetBackedTargets := map[databaseKey]struct{}{}+ for _, target := range targets {+ if target.sheetSha256 == "" || target.database == nil {+ continue+ }+ sheetBackedTargets[databaseKey{+ InstanceID: target.database.InstanceID,+ DatabaseName: target.database.DatabaseName,+ }] = struct{}{}+ }+ if len(sheetBackedTargets) == 0 {+ return false+ }++ for _, result := range planCheckRun.Result.GetResults() {+ if result.Type != storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_SUMMARY_REPORT || result.SheetSha256 != "" {+ continue+ }+ instanceID, databaseName, err := common.GetInstanceDatabaseID(result.Target)+ if err != nil {+ continue+ }+ if _, ok := sheetBackedTargets[databaseKey{InstanceID: instanceID, DatabaseName: databaseName}]; ok {+ return true+ }+ }+ return false+}++func rerunPlanChecksForApproval(ctx context.Context, stores *store.Store, b *bus.Bus, plan *store.PlanMessage) error {+ if b == nil {+ return errors.New("approval plan-check rerun requires bus")+ }+ if err := stores.CreatePlanCheckRun(ctx, &store.PlanCheckRunMessage{+ ProjectID: plan.ProjectID,+ PlanUID: plan.UID,+ Result: &storepb.PlanCheckRunResult{},+ }); err != nil {+ return errors.Wrap(err, "failed to create plan check run")+ }+ b.PlanCheckTickleChan <- 0+ return nil+}+```++- [ ] **Step 4: Pass bus through approval generation**++Change signatures in `backend/runner/approval/runner.go`:++```go+func FindAndApplyApprovalTemplate(ctx context.Context, stores *store.Store, b *bus.Bus, webhookManager *webhook.Manager, licenseService *enterprise.LicenseService, issue *store.IssueMessage) error+func findApprovalTemplateForIssue(ctx context.Context, stores *store.Store, b *bus.Bus, webhookManager *webhook.Manager, licenseService *enterprise.LicenseService, issue *store.IssueMessage, approvalSetting *storepb.WorkspaceApprovalSetting) error+func buildCELVariablesForIssue(ctx context.Context, stores *store.Store, b *bus.Bus, issue *store.IssueMessage) ([]map[string]any, bool, error)+func buildCELVariablesForDatabaseChange(ctx context.Context, stores *store.Store, b *bus.Bus, issue *store.IssueMessage) ([]map[string]any, bool, error)+```++Update calls inside the same file:++```go+ err = findApprovalTemplateForIssue(ctx, stores, b, webhookManager, licenseService, issue, approvalSetting)+ if err := findApprovalTemplateForIssue(ctx, r.store, r.bus, r.webhookManager, r.licenseService, issue, approvalSetting); err != nil {+ celVarsList, done, err := buildCELVariablesForIssue(ctx, stores, b, issue)+ return buildCELVariablesForDatabaseChange(ctx, stores, b, issue)+```++- [ ] **Step 5: Trigger rerun before building summary map**++In `buildCELVariablesForDatabaseChange`, unfold targets before constructing the statement-summary map. After `targets` is available and after the existing `RUNNING` check, add:++```go+ if hasLegacyStatementSummaryResult(planCheckRun, targets) {+ if err := rerunPlanChecksForApproval(ctx, stores, b, plan); err != nil {+ return nil, false, err+ }+ return nil, false, nil+ }+```++Keep the existing `RUNNING` behavior:++```go+ if planCheckRun != nil && planCheckRun.Status == store.PlanCheckRunStatusRunning {+ return nil, false, nil+ }+```++- [ ] **Step 6: Update API call sites**++In `backend/api/v1/issue_hook.go`, change:++```go+if err := approval.FindAndApplyApprovalTemplate(ctx, stores, b, webhookManager, licenseService, issue); err != nil {+```++In `backend/api/v1/issue_service.go`, change:++```go+if err := approval.FindAndApplyApprovalTemplate(ctx, s.store, s.bus, s.webhookManager, s.licenseService, issue); err != nil {+```++In `backend/api/v1/plan_service.go`, change:++```go+if err := approval.FindAndApplyApprovalTemplate(ctx, s.store, s.bus, s.webhookManager, s.licenseService, updatedIssue); err != nil {+```++- [ ] **Step 7: Run approval tests**++Run:++```bash+gofmt -w backend/runner/approval/runner.go backend/runner/approval/runner_test.go backend/api/v1/issue_hook.go backend/api/v1/issue_service.go backend/api/v1/plan_service.go+go test -v -count=1 ./backend/runner/approval -run '^(TestBuildStatementSummaryResultMapUsesSheetSHA256|TestHasLegacyStatementSummaryResultForSheetTarget)$'+```++Expected: PASS.++- [ ] **Step 8: Commit legacy rerun behavior**++Run:++```bash+git add backend/runner/approval/runner.go backend/runner/approval/runner_test.go backend/api/v1/issue_hook.go backend/api/v1/issue_service.go backend/api/v1/plan_service.go+git commit -m "fix(approval): rerun legacy plan checks before evaluation"+```++## Task 5: Verify Integration Gates++**Files:**+- Verify only.++- [ ] **Step 1: Run focused package tests**++Run:++```bash+go test -v -count=1 ./backend/runner/plancheck ./backend/runner/approval+```++Expected: PASS.++- [ ] **Step 2: Run protobuf formatting and linting**++Run:++```bash+buf format -w proto+buf lint proto+```++Expected: both commands exit `0`.++- [ ] **Step 3: Run Go formatting**++Run:++```bash+gofmt -w backend/runner/plancheck/executor_combined.go backend/runner/plancheck/executor_combined_test.go backend/runner/approval/runner.go backend/runner/approval/runner_test.go backend/api/v1/issue_hook.go backend/api/v1/issue_service.go backend/api/v1/plan_service.go+```++Expected: command exits `0`.++- [ ] **Step 4: Run repository lint**++Run:++```bash+golangci-lint run --allow-parallel-runners+```++Expected: PASS. If the linter reports issues, run:++```bash+golangci-lint run --fix --allow-parallel-runners+golangci-lint run --allow-parallel-runners+```++Expected after fixes: PASS.++- [ ] **Step 5: Run backend build**++Run:++```bash+go build -ldflags "-w -s" -p=16 -o ./bytebase-build/bytebase ./backend/bin/server/main.go+```++Expected: PASS and binary written to `./bytebase-build/bytebase`.++- [ ] **Step 6: Commit verification fixes**++Run:++```bash+git status --short+git add proto/store/store/plan_check_run.proto backend/generated-go/store/plan_check_run.pb.go backend/generated-go/store/plan_check_run_equal.pb.go backend/runner/plancheck/executor_combined.go backend/runner/plancheck/executor_combined_test.go backend/runner/approval/runner.go backend/runner/approval/runner_test.go backend/api/v1/issue_hook.go backend/api/v1/issue_service.go backend/api/v1/plan_service.go+git commit -m "chore: fix plan check sheet identity verification"+```++Expected: create this commit only if verification changed files. If `git status --short` is empty, do not create an empty commit.diff --git a/docs/superpowers/specs/2026-05-09-byt-9422-plan-check-sheet-identity-design.md b/docs/superpowers/specs/2026-05-09-byt-9422-plan-check-sheet-identity-design.mdnew file mode 100644index 0000000000..b64068328d--- /dev/null+++ b/docs/superpowers/specs/2026-05-09-byt-9422-plan-check-sheet-identity-design.md@@ -0,0 +1,91 @@+# BYT-9422 Plan Check Sheet Identity Design++## Problem++Approval rule evaluation for database-change issues can become spec-order dependent when multiple `ChangeDatabaseConfig` specs target the same database.++Plan check target derivation keeps the SQL sheet identity in `CheckTarget.SheetSha256`, but plan-check results persist only the database target and check type. When approval generation later reads `STATEMENT_SUMMARY_REPORT` results, it can key them only by `(instance_id, database_name)`. Multiple specs for the same database overwrite each other, so only one spec's statement summary contributes `resource.table_name`, `statement.affected_rows`, `statement.table_rows`, and `statement.sql_type` to CEL rule evaluation.++This can silently route an issue through a weaker approval rule when the protected spec is not the surviving summary.++## Goals++- Persist enough identity on each plan-check result to match it back to the spec sheet that produced it.+- Preserve per-spec approval evaluation semantics.+- Avoid guessing when existing legacy plan-check results do not contain sheet identity.+- Keep the change scoped to plan-check result identity and approval CEL variable generation.++## Non-Goals++- Do not aggregate statement-summary data across all specs for a database.+- Do not introduce a new persisted plan spec identifier.+- Do not change approval rule matching order or CEL expression behavior.+- Do not add compatibility fallback that maps an ambiguous legacy summary to multiple specs.++## Data Model++Add `sheet_sha256` to `PlanCheckRunResult.Result` in `proto/store/store/plan_check_run.proto`.++`CheckTarget` already carries `SheetSha256`, so `CombinedExecutor.RunForTarget` will copy it to each result while tagging `target` and `type`.++Each plan-check result will then be identifiable by:++```text+target + type + sheet_sha256+```++For non-sheet checks or future checks where sheet identity is irrelevant, the field can remain empty.++## Approval Evaluation++`buildCELVariablesForDatabaseChange` will continue unfolding plan specs into approval targets. For each sheet-backed target, statement-summary lookup will use:++```text+instance_id + database_name + sheet_sha256+```++The matched summary will enrich only that target's CEL variables:++- `statement.text`: the target sheet's SQL.+- `statement.sql_type`: the target sheet's statement types.+- `resource.table_name`: the target sheet's changed tables.+- `statement.affected_rows`: the target sheet's affected rows.+- `statement.table_rows`: the target sheet's table row total.++`expandCELVars` and rule matching stay unchanged. The first approval rule that matches any CEL variable map still wins. The behavioral change is that earlier specs targeting the same database are no longer hidden by later statement-summary results.++## Legacy Plan Check Results++Existing stored plan-check results will have an empty `sheet_sha256`. Approval generation must not silently use those results for sheet-backed database-change specs, because that would preserve the ambiguous behavior BYT-9422 fixes.++When approval generation sees a `DONE` plan-check run for a database-change plan and finds statement-summary results for sheet-backed targets without `sheet_sha256`, it will treat the run as stale. The approval runner will recreate the plan-check run, tickle the plan-check scheduler, and return `done=false`.++The normal async flow then resumes:++```text+approval runner detects legacy result+-> creates a fresh AVAILABLE plan_check_run+-> scheduler runs checks and persists sheet_sha256+-> scheduler triggers approval check+-> approval runner evaluates exact per-sheet summaries+```++Single-spec legacy plans will also rerun. That is intentional: it keeps the compatibility path simple and ensures all approval decisions after this change are based on unambiguous plan-check results.++## Error Handling++If the plan-check run is already `RUNNING`, approval generation keeps the current behavior and returns `done=false`.++If recreating a stale plan-check run fails, approval generation returns an error. The caller already logs approval-generation errors without persisting a partial approval result, and the user can retry by rerunning plan checks.++If a fresh `DONE` plan-check run lacks an exact result for a sheet-backed target, approval generation should not fall back to a database-only result. The target receives only base CEL variables, matching the existing behavior for missing summary data but without consuming ambiguous data.++## Testing++Add coverage for three behaviors:++1. Plan-check result identity propagation: `CombinedExecutor.RunForTarget` copies `CheckTarget.SheetSha256` into tagged results.+2. Approval summary matching: two sheet-backed specs targeting the same database produce CEL variables containing both specs' statement-summary data instead of only one surviving database-level summary.+3. Legacy auto-rerun: a completed plan-check run with statement-summary results missing `sheet_sha256` causes approval generation to recreate/tickle plan checks and return `done=false`, rather than generating an approval template from ambiguous data.++These tests should check behavior through the narrowest practical boundary. Unit-level tests are preferred for result tagging and summary matching; integration-level coverage is acceptable where store and scheduler interactions are required for the rerun path.diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.mdindex 13ccb120dc..9c9fac420d 100644--- a/proto/gen/grpc-doc/store/README.md+++ b/proto/gen/grpc-doc/store/README.md@@ -3144,6 +3144,7 @@ Plan spec update event (tracks sheet changes to plan specs)| code | [int32](#int32) | | || target | [string](#string) | | Target identification for consolidated results Format: instances/{instance}/databases/{database} || type | [PlanCheckType](#bytebase-store-PlanCheckType) | | |+| sheet_sha256 | [string](#string) | | sheet_sha256 is the content hash of the SQL sheet used to produce this result. Empty for checks that are not tied to a SQL sheet. || sql_summary_report | [PlanCheckRunResult.Result.SqlSummaryReport](#bytebase-store-PlanCheckRunResult-Result-SqlSummaryReport) | | || sql_review_report | [PlanCheckRunResult.Result.SqlReviewReport](#bytebase-store-PlanCheckRunResult-Result-SqlReviewReport) | | |diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.htmlindex 72541713c0..fa54df66ba 100644--- a/proto/gen/grpc-doc/store/index.html+++ b/proto/gen/grpc-doc/store/index.html@@ -9147,6 +9147,14 @@ Format: instances/{instance}/databases/{database} </p></td><td><p> </p></td></tr>+ <tr>+ <td>sheet_sha256</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>sheet_sha256 is the content hash of the SQL sheet used to produce this result.+Empty for checks that are not tied to a SQL sheet. </p></td>+ </tr>+<tr><td>sql_summary_report</td><td><a href="#bytebase.store.PlanCheckRunResult.Result.SqlSummaryReport">PlanCheckRunResult.Result.SqlSummaryReport</a></td>diff --git a/proto/store/store/plan_check_run.proto b/proto/store/store/plan_check_run.protoindex 457fb90227..02ad9c8eb2 100644--- a/proto/store/store/plan_check_run.proto+++ b/proto/store/store/plan_check_run.proto@@ -29,6 +29,10 @@ message PlanCheckRunResult {string target = 7;PlanCheckType type = 8;+ // sheet_sha256 is the content hash of the SQL sheet used to produce this result.+ // Empty for checks that are not tied to a SQL sheet.+ string sheet_sha256 = 9;+oneof report {SqlSummaryReport sql_summary_report = 5;SqlReviewReport sql_review_report = 6;