Skip to content

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

feat: event-driven automatic rollout creation (#18644)

Danny Xu0e6bc61e13ea
diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.go
index 8d77c8a3d7..e361967410 100644
--- a/backend/api/v1/issue_service.go
+++ b/backend/api/v1/issue_service.go
@@ -818,6 +818,14 @@ func (s *IssueService) ApproveIssue(ctx context.Context, req *connect.Request[v1
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to convert to issue, error: %v", err))
}
+
+ // Auto-create rollout if this approval completes the approval flow
+ if issueV1.ApprovalStatus == v1pb.Issue_APPROVED {
+ if issue.PlanUID != nil {
+ s.stateCfg.RolloutCreationChan <- *issue.PlanUID
+ }
+ }
+
return connect.NewResponse(issueV1), nil
}
diff --git a/backend/component/state/state.go b/backend/component/state/state.go
index 50bb315ba8..b4462982fe 100644
--- a/backend/component/state/state.go
+++ b/backend/component/state/state.go
@@ -43,6 +43,9 @@ type State struct {
// TaskRunTickleChan is the tickler for task run scheduler.
TaskRunTickleChan chan int
+ // RolloutCreationChan is the channel for automatic rollout creation.
+ RolloutCreationChan chan int64
+
ExpireCache *lru.Cache[string, bool]
}
@@ -57,6 +60,7 @@ func New() (*State, error) {
TaskSkippedOrDoneChan: make(chan int, 1000),
PlanCheckTickleChan: make(chan int, 1000),
TaskRunTickleChan: make(chan int, 1000),
+ RolloutCreationChan: make(chan int64, 100),
ExpireCache: expireCache,
}, nil
}
diff --git a/backend/runner/plancheck/scheduler.go b/backend/runner/plancheck/scheduler.go
index 4b5d724de2..78c3f486ad 100644
--- a/backend/runner/plancheck/scheduler.go
+++ b/backend/runner/plancheck/scheduler.go
@@ -123,6 +123,19 @@ func (s *Scheduler) markPlanCheckRunDone(ctx context.Context, planCheckRun *stor
planCheckRun.UID,
); err != nil {
slog.Error("failed to mark plan check run done", log.BBError(err))
+ return
+ }
+
+ // Auto-create rollout if plan checks pass
+ issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{PlanUID: &planCheckRun.PlanUID})
+ if err != nil {
+ slog.Error("failed to get issue for rollout creation after plan check",
+ slog.Int("plan_id", int(planCheckRun.PlanUID)),
+ log.BBError(err))
+ return
+ }
+ if issue != nil && issue.PlanUID != nil {
+ s.stateCfg.RolloutCreationChan <- planCheckRun.PlanUID
}
}
diff --git a/backend/runner/taskrun/rollout_creator.go b/backend/runner/taskrun/rollout_creator.go
new file mode 100644
index 0000000000..e0e627080f
--- /dev/null
+++ b/backend/runner/taskrun/rollout_creator.go
@@ -0,0 +1,186 @@
+package taskrun
+
+import (
+ "context"
+ "log/slog"
+ "sync"
+ "time"
+
+ "google.golang.org/protobuf/proto"
+
+ apiv1 "github.com/bytebase/bytebase/backend/api/v1"
+ "github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/component/dbfactory"
+ "github.com/bytebase/bytebase/backend/component/state"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
+ "github.com/bytebase/bytebase/backend/utils"
+)
+
+// RolloutCreator handles automatic rollout creation.
+// nolint:revive
+type RolloutCreator struct {
+ store *store.Store
+ stateCfg *state.State
+ dbFactory *dbfactory.DBFactory
+}
+
+// NewRolloutCreator creates a new rollout creator.
+func NewRolloutCreator(store *store.Store, stateCfg *state.State, dbFactory *dbfactory.DBFactory) *RolloutCreator {
+ return &RolloutCreator{
+ store: store,
+ stateCfg: stateCfg,
+ dbFactory: dbFactory,
+ }
+}
+
+// Run starts the rollout creator listening to the channel.
+func (rc *RolloutCreator) Run(ctx context.Context, wg *sync.WaitGroup, rolloutCreationChan chan int64) {
+ defer wg.Done()
+ slog.Debug("Rollout creator started")
+
+ for {
+ select {
+ case planID := <-rolloutCreationChan:
+ rc.tryCreateRollout(ctx, planID)
+ case <-ctx.Done():
+ slog.Debug("Rollout creator stopped")
+ return
+ }
+ }
+}
+
+// tryCreateRollout attempts to create a rollout for the given plan.
+func (rc *RolloutCreator) tryCreateRollout(_ context.Context, planID int64) {
+ // Use background context with timeout to avoid being affected by request cancellation
+ rolloutCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ plan, err := rc.store.GetPlan(rolloutCtx, &store.FindPlanMessage{UID: &planID})
+ if err != nil {
+ slog.Error("failed to get plan for rollout creation",
+ slog.Int("plan_id", int(planID)),
+ log.BBError(err))
+ return
+ }
+ if plan == nil {
+ slog.Debug("plan not found for rollout creation", slog.Int("plan_id", int(planID)))
+ return
+ }
+
+ // Idempotency: skip if rollout already exists
+ if plan.Config != nil && plan.Config.HasRollout {
+ slog.Debug("rollout already exists, skipping creation",
+ slog.Int("plan_id", int(planID)))
+ return
+ }
+
+ issue, err := rc.store.GetIssue(rolloutCtx, &store.FindIssueMessage{PlanUID: &planID})
+ if err != nil {
+ slog.Error("failed to get issue for rollout creation",
+ slog.Int("plan_id", int(planID)),
+ log.BBError(err))
+ return
+ }
+ if issue == nil {
+ slog.Debug("issue not found for rollout creation", slog.Int("plan_id", int(planID)))
+ return
+ }
+
+ project, err := rc.store.GetProject(rolloutCtx, &store.FindProjectMessage{ResourceID: &plan.ProjectID})
+ if err != nil {
+ slog.Error("failed to get project for rollout creation",
+ slog.String("project_id", plan.ProjectID),
+ log.BBError(err))
+ return
+ }
+ if project == nil {
+ slog.Error("project not found for rollout creation", slog.String("project_id", plan.ProjectID))
+ return
+ }
+
+ // Check approval status (must be approved)
+ approved, err := utils.CheckIssueApproved(issue)
+ if err != nil {
+ slog.Error("failed to check if the issue is approved",
+ slog.Int("plan_id", int(planID)),
+ log.BBError(err))
+ return
+ }
+ if !approved {
+ slog.Debug("issue not approved, skipping rollout creation",
+ slog.Int("plan_id", int(planID)))
+ return
+ }
+
+ // Check plan check status (must have no errors)
+ planCheckRun, err := rc.store.GetPlanCheckRun(rolloutCtx, planID)
+ if err != nil {
+ slog.Error("failed to get plan check run for rollout creation",
+ slog.Int("plan_id", int(planID)),
+ log.BBError(err))
+ return
+ }
+
+ // If plan checks exist, they must be DONE with no errors
+ if planCheckRun != nil {
+ // Check if plan checks are in DONE status
+ if planCheckRun.Status != store.PlanCheckRunStatusDone {
+ slog.Debug("plan checks not in DONE status, skipping rollout creation",
+ slog.Int("plan_id", int(planID)),
+ slog.String("status", string(planCheckRun.Status)))
+ return
+ }
+
+ // Check for ERROR-level results
+ if planCheckRun.Result != nil {
+ for _, result := range planCheckRun.Result.Results {
+ if result.Status == storepb.Advice_ERROR {
+ slog.Debug("plan checks have errors, skipping rollout creation",
+ slog.Int("plan_id", int(planID)))
+ return
+ }
+ }
+ }
+ }
+
+ // All conditions met - create the rollout
+ slog.Info("auto-creating rollout", slog.Int("plan_id", int(planID)))
+
+ // Get pipeline create (tasks to create)
+ pipelineCreate, err := apiv1.GetPipelineCreate(rolloutCtx, rc.store, rc.dbFactory, plan.Config.GetSpecs(), project.ResourceID)
+ if err != nil {
+ slog.Error("failed to get pipeline create for rollout creation",
+ slog.Int("plan_id", int(planID)),
+ log.BBError(err))
+ return
+ }
+
+ // Create rollout tasks
+ _, err = rc.store.CreateRolloutTasks(rolloutCtx, planID, pipelineCreate)
+ if err != nil {
+ slog.Error("failed to create rollout tasks",
+ slog.Int("plan_id", int(planID)),
+ log.BBError(err))
+ return
+ }
+
+ // Update plan to set hasRollout to true
+ config := proto.CloneOf(plan.Config)
+ config.HasRollout = true
+ _, err = rc.store.UpdatePlan(rolloutCtx, &store.UpdatePlanMessage{
+ UID: planID,
+ Config: config,
+ })
+ if err != nil {
+ slog.Error("failed to update plan hasRollout",
+ slog.Int("plan_id", int(planID)),
+ log.BBError(err))
+ return
+ }
+
+ // Tickle task run scheduler
+ rc.stateCfg.TaskRunTickleChan <- 0
+
+ slog.Info("successfully auto-created rollout", slog.Int("plan_id", int(planID)))
+}
diff --git a/backend/runner/taskrun/scheduler.go b/backend/runner/taskrun/scheduler.go
index b203d83a91..3e2a345580 100644
--- a/backend/runner/taskrun/scheduler.go
+++ b/backend/runner/taskrun/scheduler.go
@@ -11,6 +11,7 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/component/config"
+ "github.com/bytebase/bytebase/backend/component/dbfactory"
"github.com/bytebase/bytebase/backend/component/state"
"github.com/bytebase/bytebase/backend/component/webhook"
"github.com/bytebase/bytebase/backend/enterprise"
@@ -34,6 +35,7 @@ type Scheduler struct {
executorMap map[storepb.Task_Type]Executor
profile *config.Profile
licenseService *enterprise.LicenseService
+ dbFactory *dbfactory.DBFactory
}
// NewScheduler will create a new scheduler.
@@ -43,6 +45,7 @@ func NewScheduler(
webhookManager *webhook.Manager,
profile *config.Profile,
licenseService *enterprise.LicenseService,
+ dbFactory *dbfactory.DBFactory,
) *Scheduler {
return &Scheduler{
store: store,
@@ -51,6 +54,7 @@ func NewScheduler(
profile: profile,
executorMap: map[storepb.Task_Type]Executor{},
licenseService: licenseService,
+ dbFactory: dbFactory,
}
}
@@ -71,6 +75,11 @@ func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
go s.ListenTaskSkippedOrDone(ctx)
+ // Start rollout creator component
+ rolloutCreator := NewRolloutCreator(s.store, s.stateCfg, s.dbFactory)
+ wg.Add(1)
+ go rolloutCreator.Run(ctx, wg, s.stateCfg.RolloutCreationChan)
+
// Start three independent schedulers
wg.Add(3)
go s.runAutoRolloutScheduler(ctx, wg)
diff --git a/backend/server/server.go b/backend/server/server.go
index cf29f8760f..1eaba5236c 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -187,7 +187,7 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
s.schemaSyncer = schemasync.NewSyncer(stores, s.dbFactory, s.profile, s.stateCfg, s.licenseService)
s.approvalRunner = approval.NewRunner(stores, sheetManager, s.dbFactory, s.stateCfg, s.webhookManager, s.licenseService)
- s.taskScheduler = taskrun.NewScheduler(stores, s.stateCfg, s.webhookManager, profile, s.licenseService)
+ s.taskScheduler = taskrun.NewScheduler(stores, s.stateCfg, s.webhookManager, profile, s.licenseService, s.dbFactory)
s.taskScheduler.Register(storepb.Task_DATABASE_CREATE, taskrun.NewDatabaseCreateExecutor(stores, s.dbFactory, s.schemaSyncer, s.stateCfg, profile))
s.taskScheduler.Register(storepb.Task_DATABASE_MIGRATE, taskrun.NewDatabaseMigrateExecutor(stores, s.dbFactory, s.licenseService, s.stateCfg, s.schemaSyncer, profile))
s.taskScheduler.Register(storepb.Task_DATABASE_EXPORT, taskrun.NewDataExportExecutor(stores, s.dbFactory, s.licenseService, s.stateCfg, s.schemaSyncer, profile))
diff --git a/docs/plans/2025-12-25-event-driven-rollout-creation-design.md b/docs/plans/2025-12-25-event-driven-rollout-creation-design.md
new file mode 100644
index 0000000000..6fc25e28a8
--- /dev/null
+++ b/docs/plans/2025-12-25-event-driven-rollout-creation-design.md
@@ -0,0 +1,276 @@
+# Event-Driven Rollout Creation Design
+
+**Date:** 2025-12-25
+**Status:** Approved
+
+## Overview
+
+This design replaces the polling-based auto-rollout scheduler with an event-driven architecture. Rollouts will be created automatically and instantly when approval and plan check conditions are met, eliminating both the 5-second polling delay and the need for users to manually click "Create Rollout".
+
+## Motivation
+
+**Current Problems:**
+- 5-second polling delay before rollouts are created
+- Users must manually click "Create Rollout" button even when conditions are met
+- Periodic scheduler wastes resources checking issues that haven't changed
+
+**Goals:**
+- Instant rollout creation when conditions are met
+- Better user experience (no manual button click needed)
+- Cleaner event-driven architecture
+- Lower resource usage
+
+**Scope:**
+- Backend-only changes
+- Frontend continues to work as-is (button stays as fallback)
+
+## Current State
+
+**Auto-Rollout Scheduler:**
+- Location: `backend/runner/auto_rollout/scheduler.go`
+- Runs every 5 seconds
+- Checks all open issues with plans for:
+ - Approval status (if `project.RequireIssueApproval == true`)
+ - Plan check status (if `project.RequirePlanCheckNoError == true`)
+- Calls `CreateRollout()` when conditions are met
+
+**Manual Button:**
+- Location: `frontend/src/components/Plan/components/HeaderSection/Actions/registry/actions/rollout.ts`
+- Shows "Create Rollout" button when `!plan.hasRollout` and preconditions met
+- Calls `CreateRollout()` RPC
+
+**CreateRollout():**
+- Location: `backend/api/v1/rollout_service.go`
+- Converts plan specs to tasks
+- Sets `plan.Config.HasRollout = true` to prevent further spec modifications
+
+## Design
+
+### Architecture
+
+**Event-Driven Flow:**
+
+```
+┌─────────────────┐ ┌──────────────────┐
+│ ApproveIssue() │────────▶│ TryCreateRollout │
+│ (all approved) │ │ (Issue ID) │
+└─────────────────┘ └──────────────────┘
+ │
+ ▼
+┌─────────────────┐ ┌──────────────────┐
+│ PlanCheckRunner │────────▶│ Check all │
+│ (status = DONE) │ │ conditions │
+└─────────────────┘ └──────────────────┘
+ │
+ ▼
+ ┌──────────────────┐
+ │ CreateRollout() │
+ │ (if ready) │
+ └──────────────────┘
+```
+
+**Components to Remove:**
+- `backend/runner/auto_rollout/scheduler.go` - Entire scheduler
+- Auto-rollout scheduler registration in server startup
+
+**Components to Add:**
+- `TryCreateRollout(ctx, issueID)` - Centralized condition checking
+
+**Components to Modify:**
+- `CreateRollout()` - Add idempotency check
+- `ApproveIssue()` - Call TryCreateRollout when fully approved
+- Plan check executor - Call TryCreateRollout when status = DONE
+
+### Core Function: TryCreateRollout()
+
+**Location:** `backend/api/v1/rollout_service.go`
+
+**Signature:**
+```go
+func (s *RolloutService) TryCreateRollout(ctx context.Context, issueID int) error
+```
+
+**Logic Flow:**
+1. Fetch issue by ID (include plan, project)
+2. Early return if issue is nil or plan is nil
+3. **Idempotency check:** Early return if `plan.Config.HasRollout == true`
+4. **Check approval condition:**
+ - If `project.RequireIssueApproval == true`:
+ - Verify `issue.approvalStatus == APPROVED`
+ - Else: approval condition passes
+5. **Check plan check condition:**
+ - If `project.RequirePlanCheckNoError == true`:
+ - Fetch all plan check runs for the plan
+ - Verify no ERROR-level results exist
+ - Verify no RUNNING plan checks exist
+ - Else: plan check condition passes
+ - **Edge case:** Treat "no plan checks" as passing (same as old scheduler)
+6. If BOTH conditions pass:
+ - Call `CreateRollout()` with plan
+7. **Error handling:** Log errors but don't propagate (fire-and-forget)
+
+**Characteristics:**
+- Non-blocking (called in goroutine)
+- Idempotent (safe to call multiple times)
+- Best-effort (errors logged but not returned)
+
+### CreateRollout() Idempotency
+
+**Add at the beginning of CreateRollout():**
+
+```go
+// Idempotency check
+if plan.Config.HasRollout {
+ return nil, status.Errorf(codes.AlreadyExists, "rollout already exists for plan")
+}
+```
+
+This ensures:
+- Race conditions between events are handled safely
+- Manual button click after auto-creation returns graceful error
+- Database transaction provides additional safety
+
+### Trigger Point 1: Approval
+
+**Location:** `backend/api/v1/issue_service.go` in `ApproveIssue()`
+
+**When to trigger:**
+- After updating `issue.approvers` in database
+- Only when `issue.approvalStatus` becomes `APPROVED` (all approvers stamped)
+- Not after each individual approval, only when fully approved
+
+**Implementation:**
+```go
+// After database update
+if issue.approvalStatus == Issue_ApprovalStatus_APPROVED {
+ go func() {
+ if err := s.rolloutService.TryCreateRollout(ctx, issueID); err != nil {
+ slog.Error("failed to auto-create rollout after approval",
+ log.BBError(err),
+ slog.Int("issue_id", issueID))
+ }
+ }()
+}
+```
+
+### Trigger Point 2: Plan Check Completion
+
+**Location:** `backend/runner/plancheck/executor.go` (or wherever plan_check_run status is updated to DONE)
+
+**When to trigger:**
+- After updating `plan_check_run.status = DONE` in database
+- Only for status `DONE` (success)
+- Not for `FAILED` or `CANCELED`
+
+**Implementation:**
+```go
+// After updating plan check run to DONE
+if planCheckRun.Status == PlanCheckRun_Status_DONE {
+ // Get issue from plan
+ issueID := getIssueIDFromPlan(plan)
+ if issueID > 0 {
+ go func() {
+ if err := rolloutService.TryCreateRollout(ctx, issueID); err != nil {
+ slog.Error("failed to auto-create rollout after plan check",
+ log.BBError(err),
+ slog.Int("issue_id", issueID))
+ }
+ }()
+ }
+}
+```
+
+### Edge Cases
+
+1. **Race condition between events:**
+ - Both approval and plan check complete simultaneously
+ - Both call `TryCreateRollout()`
+ - **Solution:** Idempotent check on `HasRollout` + database transaction in CreateRollout()
+
+2. **No plan checks exist:**
+ - Some plans may not have plan checks (freemium users, simple changes)
+ - **Solution:** Treat "no plan checks" as passing (same behavior as old scheduler)
+
+3. **Approval template discovery incomplete:**
+ - Template discovery runs async (every 1 second)
+ - If approval required but template not found, status stays PENDING_APPROVAL
+ - **Solution:** No special handling - TryCreateRollout only triggers on APPROVED status
+
+4. **Manual button after auto-creation:**
+ - User clicks button after auto-creation happens
+ - **Solution:** CreateRollout() returns AlreadyExists error, frontend handles gracefully
+
+5. **Plan specs change after approval:**
+ - If `plan.Config.HasRollout == true`, specs can't be modified (existing validation)
+ - **Solution:** No special handling needed
+
+## Testing Strategy
+
+### Unit Tests
+
+1. **TryCreateRollout() tests:**
+ - Approval required + plan checks required → both must pass
+ - Approval skipped + plan checks required → only plan checks matter
+ - Approval required + no plan check enforcement → only approval matters
+ - Idempotency: calling twice returns early on second call
+ - Plan checks with ERROR results → rollout not created
+ - Plan checks still RUNNING → rollout not created
+ - No plan checks exist → treated as passing
+
+2. **CreateRollout() idempotency:**
+ - Calling CreateRollout on plan with HasRollout=true returns AlreadyExists error
+
+### Integration Tests
+
+1. **Approval flow:**
+ - Create issue requiring 2 approvals + plan checks passing
+ - Approve with first user → no rollout created
+ - Approve with second user → rollout created automatically
+
+2. **Plan check flow:**
+ - Create issue with approval passed + plan checks running
+ - Complete plan checks with DONE status → rollout created automatically
+
+3. **Race condition:**
+ - Approval and plan check complete simultaneously
+ - Verify only one rollout created
+ - Verify no errors in logs
+
+## Rollout Plan
+
+1. **Code changes:**
+ - Add TryCreateRollout() function
+ - Add idempotency check to CreateRollout()
+ - Hook approval trigger in ApproveIssue()
+ - Hook plan check trigger in plan check executor
+ - Remove auto_rollout scheduler initialization
+
+2. **Testing:**
+ - Run unit tests
+ - Run integration tests
+ - Manual testing in development environment
+
+3. **Deployment:**
+ - Deploy to staging
+ - Verify auto-creation works
+ - Verify manual button still works as fallback
+ - Deploy to production
+
+4. **Monitoring:**
+ - Log every TryCreateRollout call (issue ID, rollout created or not)
+ - Log any errors in TryCreateRollout
+ - Alert if CreateRollout returns AlreadyExists frequently (indicates race conditions)
+
+## Success Metrics
+
+- Rollouts created instantly when conditions met (vs 0-5 second delay)
+- Zero manual "Create Rollout" button clicks needed in normal flow
+- No errors or race conditions in production logs
+- Manual button still works as fallback for edge cases
+
+## Rollback Plan
+
+If issues are discovered:
+1. Re-enable auto_rollout_scheduler
+2. Remove event triggers from ApproveIssue and plan check executor
+3. Keep idempotency check in CreateRollout (harmless safety measure)
diff --git a/docs/plans/2025-12-25-event-driven-rollout-creation.md b/docs/plans/2025-12-25-event-driven-rollout-creation.md
new file mode 100644
index 0000000000..a2a591b12f
--- /dev/null
+++ b/docs/plans/2025-12-25-event-driven-rollout-creation.md
@@ -0,0 +1,555 @@
+# Event-Driven Rollout Creation Implementation Plan
+
+> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
+
+**Goal:** Replace manual "Create Rollout" button with event-driven auto-creation when approval and plan checks complete.
+
+**Architecture:** Add centralized `TryCreateRollout()` function that checks conditions (approval + plan checks). Hook into `ApproveIssue()` and plan check completion to call `TryCreateRollout()`. Make `CreateRollout()` idempotent to handle race conditions.
+
+**Tech Stack:** Go, gRPC/Connect, PostgreSQL
+
+---
+
+### Task 1: Add Idempotency Check to CreateRollout
+
+**Files:**
+- Modify: `backend/api/v1/rollout_service.go:203-332`
+
+**Step 1: Read current CreateRollout implementation**
+
+Read `backend/api/v1/rollout_service.go` lines 203-234 to understand the current flow.
+
+**Step 2: Add idempotency check**
+
+Add this check immediately after fetching the plan (after line 233):
+
+```go
+// Idempotency check: prevent duplicate rollout creation
+if plan.Config != nil && plan.Config.HasRollout {
+ return nil, connect.NewError(connect.CodeAlreadyExists, errors.Errorf("rollout already exists for plan %s", request.GetRollout().GetPlan()))
+}
+```
+
+**Step 3: Test manually**
+
+Run: `go build -o ./bytebase-build/bytebase ./backend/bin/server/main.go`
+Expected: Builds successfully
+
+**Step 4: Commit**
+
+```bash
+git add backend/api/v1/rollout_service.go
+git commit -m "feat: add idempotency check to CreateRollout
+
+Prevent duplicate rollout creation by checking HasRollout flag.
+Returns AlreadyExists error if rollout already exists.
+
+🤖 Generated with [Claude Code](https://claude.com/claude-code)
+
+Co-Authored-By: Claude Sonnet 4.5 <[email protected]>"
+```
+
+---
+
+### Task 2: Implement TryCreateRollout Function
+
+**Files:**
+- Modify: `backend/api/v1/rollout_service.go` (add new function after CreateRollout)
+
+**Step 1: Add TryCreateRollout function**
+
+Add this function after the `CreateRollout()` function (after line 332):
+
+```go
+// TryCreateRollout attempts to create a rollout if all conditions are met.
+// This function is called asynchronously after approval or plan check completion.
+// It checks approval and plan check conditions before calling CreateRollout.
+func (s *RolloutService) TryCreateRollout(ctx context.Context, issueID int) {
+ issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{UID: &issueID})
+ if err != nil {
+ slog.Error("failed to get issue for rollout creation",
+ slog.Int("issue_id", issueID),
+ log.BBError(err))
+ return
+ }
+ if issue == nil {
+ slog.Debug("issue not found for rollout creation", slog.Int("issue_id", issueID))
+ return
+ }
+
+ if issue.PlanUID == nil {
+ slog.Debug("issue has no plan, skipping rollout creation", slog.Int("issue_id", issueID))
+ return
+ }
+
+ plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{UID: issue.PlanUID})
+ if err != nil {
+ slog.Error("failed to get plan for rollout creation",
+ slog.Int("plan_id", int(*issue.PlanUID)),
+ log.BBError(err))
+ return
+ }
+ if plan == nil {
+ slog.Debug("plan not found for rollout creation", slog.Int("plan_id", int(*issue.PlanUID)))
+ return
+ }
+
+ // Idempotency: skip if rollout already exists
+ if plan.Config != nil && plan.Config.HasRollout {
+ slog.Debug("rollout already exists, skipping creation",
+ slog.Int("issue_id", issueID),
+ slog.Int("plan_id", int(*issue.PlanUID)))
+ return
+ }
+
+ project, err := s.store.GetProject(ctx, &store.FindProjectMessage{ResourceID: &plan.ProjectID})
+ if err != nil {
+ slog.Error("failed to get project for rollout creation",
+ slog.String("project_id", plan.ProjectID),
+ log.BBError(err))
+ return
+ }
+ if project == nil {
+ slog.Error("project not found for rollout creation", slog.String("project_id", plan.ProjectID))
+ return
+ }
+
+ // Check approval condition
+ if project.Setting != nil && project.Setting.RequireIssueApproval {
+ if issue.ApprovalStatus != storepb.Issue_APPROVED {
+ slog.Debug("issue not approved yet, skipping rollout creation",
+ slog.Int("issue_id", issueID),
+ slog.String("approval_status", issue.ApprovalStatus.String()))
+ return
+ }
+ }
+
+ // Check plan check condition
+ if project.Setting != nil && project.Setting.RequirePlanCheckNoError {
+ planCheckRun, err := s.store.GetPlanCheckRun(ctx, *issue.PlanUID)
+ if err != nil {
+ slog.Error("failed to get plan check run for rollout creation",
+ slog.Int("plan_id", int(*issue.PlanUID)),
+ log.BBError(err))
+ return
+ }
+
+ // If no plan checks exist, treat as passing (same as old behavior)
+ if planCheckRun != nil {
+ // Check if plan checks are still running
+ if planCheckRun.Status == store.PlanCheckRunStatusRunning {
+ slog.Debug("plan checks still running, skipping rollout creation",
+ slog.Int("issue_id", issueID))
+ return
+ }
+
+ // Check for ERROR-level results
+ if planCheckRun.Result != nil {
+ for _, result := range planCheckRun.Result.Results {
+ if result.Status == storepb.Advice_ERROR {
+ slog.Debug("plan checks have errors, skipping rollout creation",
+ slog.Int("issue_id", issueID))
+ return
+ }
+ }
+ }
+ }
+ }
+
+ // All conditions met - create the rollout
+ slog.Info("auto-creating rollout",
+ slog.Int("issue_id", issueID),
+ slog.Int("plan_id", int(*issue.PlanUID)))
+
+ projectID := common.FormatProject(plan.ProjectID)
+ planName := common.FormatPlan(project.Name, *issue.PlanUID)
+
+ _, err = s.CreateRollout(ctx, connect.NewRequest(&v1pb.CreateRolloutRequest{
+ Parent: projectID,
+ Rollout: &v1pb.Rollout{
+ Plan: planName,
+ },
+ }))
+
+ if err != nil {
+ // If rollout already exists, this is not an error (race condition handled)
+ if connect.CodeOf(err) == connect.CodeAlreadyExists {
+ slog.Debug("rollout already exists (race condition), ignoring",
+ slog.Int("issue_id", issueID))
+ return
+ }
+ slog.Error("failed to auto-create rollout",
+ slog.Int("issue_id", issueID),
+ slog.Int("plan_id", int(*issue.PlanUID)),
+ log.BBError(err))
+ return
+ }
+
+ slog.Info("successfully auto-created rollout",
+ slog.Int("issue_id", issueID),
+ slog.Int("plan_id", int(*issue.PlanUID)))
+}
+```
+
+**Step 2: Add required imports**
+
+Add to imports at the top if not already present:
+```go
+"github.com/bytebase/bytebase/backend/common"
+```
+
+**Step 3: Build and verify**
+
+Run: `go build -o ./bytebase-build/bytebase ./backend/bin/server/main.go`
+Expected: Builds successfully
+
+**Step 4: Commit**
+
+```bash
+git add backend/api/v1/rollout_service.go
+git commit -m "feat: implement TryCreateRollout function
+
+Add centralized function that checks all conditions (approval + plan
+checks) and creates rollout if ready. Designed to be called
+asynchronously from event handlers.
+
+🤖 Generated with [Claude Code](https://claude.com/claude-code)
+
+Co-Authored-By: Claude Sonnet 4.5 <[email protected]>"
+```
+
+---
+
+### Task 3: Hook TryCreateRollout into ApproveIssue
+
+**Files:**
+- Modify: `backend/api/v1/issue_service.go:32-40` (add rolloutService field)
+- Modify: `backend/api/v1/issue_service.go:49-60` (update NewIssueService)
+- Modify: `backend/api/v1/issue_service.go:634-822` (add trigger in ApproveIssue)
+
+**Step 1: Add rolloutService field to IssueService struct**
+
+Modify the IssueService struct (around line 32-40):
+
+```go
+// IssueService implements the issue service.
+type IssueService struct {
+ v1connect.UnimplementedIssueServiceHandler
+ store *store.Store
+ webhookManager *webhook.Manager
+ stateCfg *state.State
+ licenseService *enterprise.LicenseService
+ profile *config.Profile
+ iamManager *iam.Manager
+ rolloutService *RolloutService // Add this line
+}
+```
+
+**Step 2: Update NewIssueService constructor**
+
+Find the NewIssueService function and:
+1. Add `rolloutService *RolloutService` parameter
+2. Add `rolloutService: rolloutService` to the returned struct
+
+**Step 3: Find where ApproveIssue function is defined**
+
+Run: `grep -n "func.*ApproveIssue" backend/api/v1/issue_service.go`
+Expected: Shows line number (around 634)
+
+**Step 4: Read ApproveIssue to find where approval status changes**
+
+Read lines 634-822 to find where the issue is updated with new approval status.
+
+**Step 5: Add TryCreateRollout trigger after approval**
+
+After the issue is updated and approval status becomes APPROVED, add:
+
+```go
+// Auto-create rollout if this approval completes the approval flow
+if updatedIssue.ApprovalStatus == storepb.Issue_APPROVED {
+ go func() {
+ s.rolloutService.TryCreateRollout(ctx, updatedIssue.UID)
+ }()
+}
+```
+
+**Step 6: Build and verify**
+
+Run: `go build -o ./bytebase-build/bytebase ./backend/bin/server/main.go`
+Expected: May fail due to NewIssueService call sites not updated yet
+
+**Step 7: Find all NewIssueService call sites**
+
+Run: `grep -rn "NewIssueService" backend/ --include="*.go"`
+Expected: Shows all places where NewIssueService is called
+
+**Step 8: Update all NewIssueService call sites to pass rolloutService**
+
+Update each call site to pass the rolloutService parameter.
+
+**Step 9: Build and verify**
+
+Run: `go build -o ./bytebase-build/bytebase ./backend/bin/server/main.go`
+Expected: Builds successfully
+
+**Step 10: Commit**
+
+```bash
+git add backend/api/v1/issue_service.go
+git add <other files with NewIssueService calls>
+git commit -m "feat: trigger rollout creation on approval
+
+Call TryCreateRollout when issue becomes fully approved.
+Add rolloutService dependency to IssueService.
+
+🤖 Generated with [Claude Code](https://claude.com/claude-code)
+
+Co-Authored-By: Claude Sonnet 4.5 <[email protected]>"
+```
+
+---
+
+### Task 4: Hook TryCreateRollout into Plan Check Completion
+
+**Files:**
+- Modify: `backend/runner/plancheck/scheduler.go:24-32` (add rolloutService field to Scheduler)
+- Modify: `backend/runner/plancheck/scheduler.go:116-127` (add trigger in markPlanCheckRunDone)
+
+**Step 1: Add rolloutService to plan check Scheduler**
+
+Modify the Scheduler struct around line 34-40:
+
+```go
+// Scheduler is the plan check run scheduler.
+type Scheduler struct {
+ store *store.Store
+ licenseService *enterprise.LicenseService
+ stateCfg *state.State
+ executor *CombinedExecutor
+ rolloutService interface { // Add this field
+ TryCreateRollout(ctx context.Context, issueID int)
+ }
+}
+```
+
+**Step 2: Update NewScheduler function**
+
+Modify NewScheduler (around line 25-32):
+
+```go
+// NewScheduler creates a new plan check scheduler.
+func NewScheduler(s *store.Store, licenseService *enterprise.LicenseService, stateCfg *state.State, executor *CombinedExecutor, rolloutService interface {
+ TryCreateRollout(ctx context.Context, issueID int)
+}) *Scheduler {
+ return &Scheduler{
+ store: s,
+ licenseService: licenseService,
+ stateCfg: stateCfg,
+ executor: executor,
+ rolloutService: rolloutService,
+ }
+}
+```
+
+**Step 3: Add TryCreateRollout trigger in markPlanCheckRunDone**
+
+Modify markPlanCheckRunDone function (around line 116-127):
+
+```go
+func (s *Scheduler) markPlanCheckRunDone(ctx context.Context, planCheckRun *store.PlanCheckRunMessage, results []*storepb.PlanCheckRunResult_Result) {
+ result := &storepb.PlanCheckRunResult{
+ Results: results,
+ }
+ if err := s.store.UpdatePlanCheckRun(ctx,
+ store.PlanCheckRunStatusDone,
+ result,
+ planCheckRun.UID,
+ ); err != nil {
+ slog.Error("failed to mark plan check run done", log.BBError(err))
+ return // Add return here
+ }
+
+ // Auto-create rollout if plan checks pass
+ issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{PlanUID: &planCheckRun.PlanUID})
+ if err != nil {
+ slog.Error("failed to get issue for rollout creation after plan check",
+ slog.Int("plan_id", int(planCheckRun.PlanUID)),
+ log.BBError(err))
+ return
+ }
+ if issue != nil {
+ go func() {
+ s.rolloutService.TryCreateRollout(ctx, issue.UID)
+ }()
+ }
+}
+```
+
+**Step 4: Add required imports**
+
+Add to imports at top:
+```go
+"log/slog"
+"github.com/bytebase/bytebase/backend/common/log"
+```
+
+**Step 5: Find all NewScheduler call sites**
+
+Run: `grep -rn "plancheck.NewScheduler" backend/ --include="*.go"`
+Expected: Shows where plancheck.NewScheduler is called
+
+**Step 6: Update NewScheduler call sites to pass rolloutService**
+
+Update each call site to pass the rolloutService parameter.
+
+**Step 7: Build and verify**
+
+Run: `go build -o ./bytebase-build/bytebase ./backend/bin/server/main.go`
+Expected: Builds successfully
+
+**Step 8: Commit**
+
+```bash
+git add backend/runner/plancheck/scheduler.go
+git add <other files with NewScheduler calls>
+git commit -m "feat: trigger rollout creation on plan check completion
+
+Call TryCreateRollout when plan checks complete with DONE status.
+Add rolloutService dependency to plan check Scheduler.
+
+🤖 Generated with [Claude Code](https://claude.com/claude-code)
+
+Co-Authored-By: Claude Sonnet 4.5 <[email protected]>"
+```
+
+---
+
+### Task 5: Run Tests and Lint
+
+**Step 1: Run Go linter**
+
+Run: `golangci-lint run --allow-parallel-runners`
+Expected: No errors (or fixable errors)
+
+**Step 2: Auto-fix linter issues**
+
+Run: `golangci-lint run --fix --allow-parallel-runners`
+Expected: Auto-fixes issues
+
+**Step 3: Re-run linter until clean**
+
+Run: `golangci-lint run --allow-parallel-runners`
+Repeat until: No errors
+
+**Step 4: Format Go code**
+
+Run: `gofmt -w backend/api/v1/rollout_service.go backend/api/v1/issue_service.go backend/runner/plancheck/scheduler.go`
+Expected: Files formatted
+
+**Step 5: Run relevant tests**
+
+Run: `go test -v -count=1 github.com/bytebase/bytebase/backend/api/v1 -run CreateRollout`
+Expected: Tests pass
+
+**Step 6: Build final binary**
+
+Run: `go build -ldflags "-w -s" -p=16 -o ./bytebase-build/bytebase ./backend/bin/server/main.go`
+Expected: Builds successfully
+
+**Step 7: Commit any fixes**
+
+```bash
+git add .
+git commit -m "chore: fix linting and formatting issues
+
+🤖 Generated with [Claude Code](https://claude.com/claude-code)
+
+Co-Authored-By: Claude Sonnet 4.5 <[email protected]>"
+```
+
+---
+
+### Task 6: Manual Integration Testing
+
+**Step 1: Start development server**
+
+Run: `PG_URL=postgresql://bbdev@localhost/bbdev ./bytebase-build/bytebase --port 8080 --data . --debug`
+Expected: Server starts
+
+**Step 2: Create test issue with approval required**
+
+1. Create a project with `RequireIssueApproval = true`
+2. Create a plan with database change
+3. Create an issue from the plan
+4. Verify no rollout exists yet
+
+**Step 3: Approve the issue**
+
+1. Approve the issue (if plan checks also configured, they should be passing)
+2. Verify rollout is created automatically
+3. Check logs for "auto-creating rollout" message
+
+**Step 4: Test plan check trigger**
+
+1. Create another issue with approval already done
+2. Wait for plan checks to complete
+3. Verify rollout is created automatically
+4. Check logs for "auto-creating rollout" message
+
+**Step 5: Test idempotency**
+
+1. Try to manually create rollout again via UI button
+2. Verify AlreadyExists error is returned
+3. Verify no duplicate rollouts created
+
+**Step 6: Test race condition**
+
+1. Create issue where approval and plan checks complete simultaneously
+2. Verify only one rollout is created
+3. Check logs for any race condition messages
+
+**Step 7: Document test results**
+
+Create a test results document:
+
+```markdown
+# Event-Driven Rollout Testing Results
+
+## Test 1: Approval Trigger
+- Status: PASS/FAIL
+- Notes: ...
+
+## Test 2: Plan Check Trigger
+- Status: PASS/FAIL
+- Notes: ...
+
+## Test 3: Idempotency
+- Status: PASS/FAIL
+- Notes: ...
+
+## Test 4: Race Condition
+- Status: PASS/FAIL
+- Notes: ...
+```
+
+---
+
+## Completion Checklist
+
+- [ ] Task 1: Idempotency check added to CreateRollout
+- [ ] Task 2: TryCreateRollout function implemented
+- [ ] Task 3: ApproveIssue hook added
+- [ ] Task 4: Plan check completion hook added
+- [ ] Task 5: Tests and linting pass
+- [ ] Task 6: Manual integration tests complete
+- [ ] All code formatted with gofmt
+- [ ] All linter issues resolved
+- [ ] Build succeeds
+- [ ] Feature tested in development environment
+
+## Notes
+
+- The manual "Create Rollout" button in the UI remains functional as a fallback
+- No frontend changes are required
+- All errors in TryCreateRollout are logged but not propagated (fire-and-forget design)
+- Race conditions are handled via idempotency check and database transactions