Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
test: add composite-PK collision safety harness (#20040)
zchpeter07335c79c5ae
diff --git a/.gitignore b/.gitignoreindex d62ff5b20b..c56f783a23 100644--- a/.gitignore+++ b/.gitignore@@ -26,8 +26,8 @@ bytebase-build# IntelliJ (Goland, IDEA) folder.idea-# Claude Code configuration-.claude+# Claude Code user-specific configuration+.claude/settings.local.json# Git worktrees.worktrees/diff --git a/AGENTS.md b/AGENTS.mdindex 2af509d2a6..9266c0f671 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -155,6 +155,26 @@ The frontend is migrating from Vue to React. **All new UI code should be written- Use American English- Avoid plurals like "xxxList" for simplicity and to prevent singular/plural ambiguity stemming from poor design+## Composite Primary Keys++Several tables use composite primary keys (e.g., `(project, id)`). Check+`backend/migrator/migration/LATEST.sql` for the full list — any table with a+multi-column PRIMARY KEY.++When writing or modifying queries on these tables:+- Every WHERE, JOIN, USING, DELETE, and UPDATE predicate must include ALL primary key+ columns — never filter by `id` alone+- When adding a new store method touching a composite-PK table, add a corresponding+ `TestCollision_*` test in `backend/tests/`. The existing `setupCollidingProjects`+ fixture and `assertProjectUnchanged` helper cover `plan`, `issue`, `task`, `task_run`,+ and `plan_check_run`. For tables not in that set (e.g., `plan_webhook_delivery`,+ `task_run_log`, `db_group`, `release`), write table-specific seed and assertion+ helpers — or extend the shared helper first+- Collision tests use `setupCollidingProjects` + `fixture.completeRolloutB` for setup+ and `snapshotProject` / `assertProjectUnchanged` for assertions — all going through+ the public gRPC API, no store access. Run with:+ `go test -v -count=1 ./backend/tests/ -run "^(TestClaim|TestCollision)" -timeout 5m`+### Imports- Use organized imports (sorted by the import path)@@ -169,29 +189,12 @@ The frontend is migrating from Vue to React. **All new UI code should be written## Pull Request Guidelines+**Before running `gh pr create`, walk through [`docs/pre-pr-checklist.md`](docs/pre-pr-checklist.md).** It covers the breaking-change review, composite-PK query safety, lint/test gates, and SonarCloud properties — the checks that lint and CI can't catch on their own.+- **Code Review** — Follow [Google's Code Review Guideline](https://google.github.io/eng-practices/)- **Author Responsibility** — Authors are responsible for driving discussions, resolving comments, and promptly merging pull requests- **Description** — Clearly describe what the PR changes and why- **Testing** — Include information about how the changes were tested-- **SonarCloud** — When creating or updating a PR, update `.sonarcloud.properties` to reflect the latest file structure. Use `sonar.exclusions` for generated code, build artifacts, and dependencies (directory paths only). Use `sonar.test.inclusions` for test file patterns (wildcards like `**/*_test.go`). Use `sonar.cpd.exclusions` to skip copy-paste detection on test files--### Breaking Change Check (MANDATORY before `gh pr create`)--**This is a required step in the PR creation workflow. Run `git diff main...HEAD` and check every item below BEFORE writing the `gh pr create` command. This step comes after pushing the branch and before creating the PR.**--1. **API breaking changes** — removed/renamed endpoints, changed request/response formats, removed/renamed query parameters-2. **Database schema breaking changes** — dropped columns/tables, non-backward-compatible migrations-3. **Proto breaking changes** — removed/renamed fields, changed field numbers/types, removed RPCs-4. **Configuration breaking changes** — removed flags, changed default behavior, renamed environment variables-5. **Behavior changes** — changed default values, altered existing workflows, modified permission/access control logic-6. **Webhook/event changes** — renamed/removed events, changed payload formats-7. **UI workflow changes** — redesigned user-facing flows that change how users perform existing tasks (e.g., merging steps, splitting pages, changing navigation)--**If ANY of the above apply:**-1. Add `--label breaking` to the `gh pr create` command-2. Include a `## Breaking Changes` section in the PR description summarizing what changed and what users need to be aware of--Do NOT skip this check. Do NOT assume changes are non-breaking without reviewing the diff.## Common Go Lint Rulesdiff --git a/backend/tests/collision_helper_test.go b/backend/tests/collision_helper_test.gonew file mode 100644index 0000000000..4b0197b631--- /dev/null+++ b/backend/tests/collision_helper_test.go@@ -0,0 +1,695 @@+package tests++import (+ "context"+ "fmt"+ "strings"+ "testing"++ "connectrpc.com/connect"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+ "google.golang.org/protobuf/proto"++ "github.com/bytebase/bytebase/backend/common"+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+)++// collisionFixture holds references to entities created in two projects+// whose composite-PK ids naturally collide.+//+// When created by setupCollidingProjects, both projects share a single+// instance (Instance == InstanceA == InstanceB). When created by+// setupCollidingProjectsSeparateInstances, InstanceA and InstanceB are+// distinct — Instance is unset in that case.+type collisionFixture struct {+ ProjectA *v1pb.Project+ ProjectB *v1pb.Project+ // Instance is set only when both projects share an instance.+ Instance *v1pb.Instance+ InstanceA *v1pb.Instance+ InstanceB *v1pb.Instance++ DatabaseA *v1pb.Database+ DatabaseB *v1pb.Database++ PlanA *v1pb.Plan+ PlanB *v1pb.Plan++ IssueA *v1pb.Issue+ IssueB *v1pb.Issue++ // BaselineA is project A's snapshot captured immediately after A's+ // rollout completes and BEFORE project B's plan/issue are created.+ // Tests should use this as the "before" oracle rather than calling+ // snapshotProject() at the start of the test, because the scheduler+ // may fire cross-project side effects during project B's creation.+ BaselineA *projectSnapshot+}++// setupCollidingProjects creates two projects with naturally colliding ids.+//+// Both projects get a plan → issue → rollout with a DML task targeting+// separate databases on the same SQLite instance. Because nextProjectID+// allocates per-project, the first plan/task/task_run/plan_check_run in+// each project receives the same numeric id.+//+// Project A's rollout is driven to DONE. Project B's rollout is left+// in a state controlled by the caller (default: tasks are NOT_STARTED).+func setupCollidingProjects(+ ctx context.Context,+ t *testing.T,+ ctl *controller,+) *collisionFixture {+ t.Helper()+ a := require.New(t)++ projectA, err := ctl.projectServiceClient.CreateProject(ctx, connect.NewRequest(&v1pb.CreateProjectRequest{+ ProjectId: generateRandomString("col-a"),+ Project: &v1pb.Project{Title: "Collision Project A", AllowSelfApproval: true},+ }))+ a.NoError(err)++ projectB, err := ctl.projectServiceClient.CreateProject(ctx, connect.NewRequest(&v1pb.CreateProjectRequest{+ ProjectId: generateRandomString("col-b"),+ Project: &v1pb.Project{Title: "Collision Project B", AllowSelfApproval: true},+ }))+ a.NoError(err)++ instanceRootDir := t.TempDir()+ instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, "collision-instance")+ a.NoError(err)++ instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{+ InstanceId: generateRandomString("col-inst"),+ Instance: &v1pb.Instance{+ Title: "collision-instance",+ Engine: v1pb.Engine_SQLITE,+ Environment: new("environments/prod"),+ Activation: true,+ DataSources: []*v1pb.DataSource{{Type: v1pb.DataSourceType_ADMIN, Host: instanceDir, Id: "admin"}},+ },+ }))+ a.NoError(err)+ instance := instanceResp.Msg++ dbNameA := "collision_db_a"+ err = ctl.createDatabase(ctx, projectA.Msg, instance, nil, dbNameA, "")+ a.NoError(err)++ dbNameB := "collision_db_b"+ err = ctl.createDatabase(ctx, projectB.Msg, instance, nil, dbNameB, "")+ a.NoError(err)++ dbA, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{+ Name: fmt.Sprintf("%s/databases/%s", instance.Name, dbNameA),+ }))+ a.NoError(err)++ dbB, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{+ Name: fmt.Sprintf("%s/databases/%s", instance.Name, dbNameB),+ }))+ a.NoError(err)++ sheetA, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: projectA.Msg.Name,+ Sheet: &v1pb.Sheet{Content: []byte("SELECT 1;")},+ }))+ a.NoError(err)++ planA, err := ctl.planServiceClient.CreatePlan(ctx, connect.NewRequest(&v1pb.CreatePlanRequest{+ Parent: projectA.Msg.Name,+ Plan: &v1pb.Plan{+ Specs: []*v1pb.Plan_Spec{{+ Id: uuid.NewString(),+ Config: &v1pb.Plan_Spec_ChangeDatabaseConfig{+ ChangeDatabaseConfig: &v1pb.Plan_ChangeDatabaseConfig{+ Targets: []string{dbA.Msg.Name},+ Sheet: sheetA.Msg.Name,+ },+ },+ }},+ },+ }))+ a.NoError(err)++ issueA, err := ctl.issueServiceClient.CreateIssue(ctx, connect.NewRequest(&v1pb.CreateIssueRequest{+ Parent: projectA.Msg.Name,+ Issue: &v1pb.Issue{+ Title: "Collision test A",+ Type: v1pb.Issue_DATABASE_CHANGE,+ Plan: planA.Msg.Name,+ },+ }))+ a.NoError(err)++ rolloutA, err := ctl.rolloutServiceClient.CreateRollout(ctx, connect.NewRequest(&v1pb.CreateRolloutRequest{+ Parent: planA.Msg.Name,+ }))+ a.NoError(err)++ err = ctl.waitRollout(ctx, issueA.Msg.Name, rolloutA.Msg.Name)+ a.NoError(err)++ // Capture project A's baseline BEFORE creating project B's plan. Anything+ // below (CreatePlan, CreateIssue) can tickle the scheduler; a cross-project+ // bug would fire here and corrupt project A. By snapshotting now, tests+ // get a clean oracle that reflects A's true post-rollout state.+ baselineA := snapshotProject(ctx, t, ctl, projectA.Msg)++ sheetB, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: projectB.Msg.Name,+ Sheet: &v1pb.Sheet{Content: []byte("SELECT 1;")},+ }))+ a.NoError(err)++ planB, err := ctl.planServiceClient.CreatePlan(ctx, connect.NewRequest(&v1pb.CreatePlanRequest{+ Parent: projectB.Msg.Name,+ Plan: &v1pb.Plan{+ Specs: []*v1pb.Plan_Spec{{+ Id: uuid.NewString(),+ Config: &v1pb.Plan_Spec_ChangeDatabaseConfig{+ ChangeDatabaseConfig: &v1pb.Plan_ChangeDatabaseConfig{+ Targets: []string{dbB.Msg.Name},+ Sheet: sheetB.Msg.Name,+ },+ },+ }},+ },+ }))+ a.NoError(err)++ issueB, err := ctl.issueServiceClient.CreateIssue(ctx, connect.NewRequest(&v1pb.CreateIssueRequest{+ Parent: projectB.Msg.Name,+ Issue: &v1pb.Issue{+ Title: "Collision test B",+ Type: v1pb.Issue_DATABASE_CHANGE,+ Plan: planB.Msg.Name,+ },+ }))+ a.NoError(err)++ f := &collisionFixture{+ ProjectA: projectA.Msg,+ ProjectB: projectB.Msg,+ Instance: instance,+ InstanceA: instance,+ InstanceB: instance,+ DatabaseA: dbA.Msg,+ DatabaseB: dbB.Msg,+ PlanA: planA.Msg,+ PlanB: planB.Msg,+ IssueA: issueA.Msg,+ IssueB: issueB.Msg,+ BaselineA: baselineA,+ }+ assertFixtureIDsCollide(ctx, t, ctl, f)+ return f+}++// setupCollidingProjectsSeparateInstances is a variant of setupCollidingProjects+// that places each project on its own SQLite instance. Useful for tests that+// need to distinguish correct per-instance cascade from a buggy cross-project+// DELETE USING predicate. Project A's rollout is driven to DONE; project B's+// rollout is left for the caller to trigger.+func setupCollidingProjectsSeparateInstances(+ ctx context.Context,+ t *testing.T,+ ctl *controller,+) *collisionFixture {+ t.Helper()+ a := require.New(t)++ projectA, err := ctl.projectServiceClient.CreateProject(ctx, connect.NewRequest(&v1pb.CreateProjectRequest{+ ProjectId: generateRandomString("col-a"),+ Project: &v1pb.Project{Title: "Collision Project A", AllowSelfApproval: true},+ }))+ a.NoError(err)++ projectB, err := ctl.projectServiceClient.CreateProject(ctx, connect.NewRequest(&v1pb.CreateProjectRequest{+ ProjectId: generateRandomString("col-b"),+ Project: &v1pb.Project{Title: "Collision Project B", AllowSelfApproval: true},+ }))+ a.NoError(err)++ instA := createSQLiteInstance(ctx, t, ctl, "col-inst-a")+ instB := createSQLiteInstance(ctx, t, ctl, "col-inst-b")++ const dbNameA = "collision_db_a"+ a.NoError(ctl.createDatabase(ctx, projectA.Msg, instA, nil, dbNameA, ""))+ dbA, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{+ Name: fmt.Sprintf("%s/databases/%s", instA.Name, dbNameA),+ }))+ a.NoError(err)++ const dbNameB = "collision_db_b"+ a.NoError(ctl.createDatabase(ctx, projectB.Msg, instB, nil, dbNameB, ""))+ dbB, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{+ Name: fmt.Sprintf("%s/databases/%s", instB.Name, dbNameB),+ }))+ a.NoError(err)++ planA, issueA, rolloutA := createPlanIssueRollout(ctx, t, ctl, projectA.Msg, dbA.Msg, "Collision test A")+ a.NoError(ctl.waitRollout(ctx, issueA.Name, rolloutA.Name))++ // Snapshot A BEFORE creating project B's plan — see note in setupCollidingProjects.+ baselineA := snapshotProject(ctx, t, ctl, projectA.Msg)++ planB, issueB := createPlanAndIssue(ctx, t, ctl, projectB.Msg, dbB.Msg, "Collision test B")++ f := &collisionFixture{+ ProjectA: projectA.Msg,+ ProjectB: projectB.Msg,+ InstanceA: instA,+ InstanceB: instB,+ DatabaseA: dbA.Msg,+ DatabaseB: dbB.Msg,+ PlanA: planA,+ PlanB: planB,+ IssueA: issueA,+ IssueB: issueB,+ BaselineA: baselineA,+ }+ assertFixtureIDsCollide(ctx, t, ctl, f)+ return f+}++// assertFixtureIDsCollide verifies that the "colliding IDs" invariant the+// whole harness depends on is actually true. If a future change adds an+// extra project-scoped allocation on either path, the tests would silently+// stop exercising the composite-PK collision case; this assertion fails+// fast in that case.+//+// Coverage matrix (by table):+// - plan — asserted here (both projects have plans at fixture time)+// - issue — asserted here (both projects have issues at fixture time)+// - task — asserted in completeRolloutB (B's rollout required)+// - task_run — asserted in completeRolloutB (B's rollout required)+// - plan_check_run — NOT ASSERTED. The v1 API exposes PCRs via a+// UID-less singleton name, so the UID is not observable from public+// gRPC. nextProjectID is per-table, so task_run collision does NOT+// imply PCR collision. The PCR claim test should be treated as+// belt-and-suspenders for the task_run claim test, not an+// independent regression lock.+func assertFixtureIDsCollide(ctx context.Context, t *testing.T, ctl *controller, f *collisionFixture) {+ t.Helper()+ a := require.New(t)++ aPlans := listPlanUIDs(ctx, t, ctl, f.ProjectA.Name)+ bPlans := listPlanUIDs(ctx, t, ctl, f.ProjectB.Name)+ a.Greater(len(aPlans), 0, "project A should have at least one plan")+ a.Greater(len(bPlans), 0, "project B should have at least one plan")+ assertAtLeastOneUIDCollides(t, aPlans, bPlans, "plan")++ aIssues := listIssueUIDs(ctx, t, ctl, f.ProjectA.Name)+ bIssues := listIssueUIDs(ctx, t, ctl, f.ProjectB.Name)+ a.Greater(len(aIssues), 0, "project A should have at least one issue")+ a.Greater(len(bIssues), 0, "project B should have at least one issue")+ assertAtLeastOneUIDCollides(t, aIssues, bIssues, "issue")+}++// completeRolloutB drives project B's rollout to completion and proves that+// task and task_run ids collide across the two projects. This is the ONLY+// supported way for a collision test to roll out B — every call site gets+// the collision invariants for free, so no test can silently become vacuous+// by forgetting an assertion.+//+// Known coverage gap — plan_check_run:+// The v1 API exposes plan_check_runs via a UID-less singleton name+// ({plan.name}/planCheckRun), so PCR UIDs cannot be observed from public+// gRPC. The store's nextProjectID allocator is keyed per-table per-project,+// so task_run collision is NOT evidence of PCR collision — the two+// sequences can diverge independently. This means+// TestClaimAvailablePlanCheckRunsNoCrossProjectTransition exercises the+// PCR claim SQL path (via the scheduler) but cannot prove its assertions+// fire against a genuinely colliding row. The regression lock for the+// BYT-9259 SQL pattern is TestClaimAvailableTaskRunsNoCrossProjectResurrection,+// which does prove collision. The PCR test is kept as belt-and-suspenders+// coverage; do not read it as an independent guarantee.+//+// Why this method lives here rather than inside setupCollidingProjects:+// the fixture returns before B's rollout fires, so task and task_run don't+// exist yet at fixture-construction time. Tests that don't need B's+// rollout (pure read-isolation tests on plan/issue) don't pay the cost.+func (f *collisionFixture) completeRolloutB(ctx context.Context, t *testing.T, ctl *controller) {+ t.Helper()+ a := require.New(t)++ rolloutB, err := ctl.rolloutServiceClient.CreateRollout(ctx,+ connect.NewRequest(&v1pb.CreateRolloutRequest{+ Parent: f.PlanB.Name,+ }))+ a.NoError(err)+ a.NoError(ctl.waitRollout(ctx, f.IssueB.Name, rolloutB.Msg.Name))++ assertTasksCollide(ctx, t, ctl, f)+ assertTaskRunsCollide(ctx, t, ctl, f)+}++// assertTaskRunsCollide verifies that after both projects have rolled out,+// their task_run ids collide. Call this from tests that run project B's+// rollout and depend on task_run collisions.+//+// Note: nextProjectID allocates per table, so task_run collision does not+// imply plan_check_run collision. Each table needs its own assertion.+func assertTaskRunsCollide(ctx context.Context, t *testing.T, ctl *controller, f *collisionFixture) {+ t.Helper()+ a := require.New(t)++ aTaskRuns, _ := listTaskRunAndTaskUIDs(ctx, t, ctl, f.PlanA.Name)+ bTaskRuns, _ := listTaskRunAndTaskUIDs(ctx, t, ctl, f.PlanB.Name)+ a.Greater(len(aTaskRuns), 0, "project A should have at least one task_run")+ a.Greater(len(bTaskRuns), 0, "project B should have at least one task_run — did you forget to roll out B?")+ assertAtLeastOneUIDCollides(t, aTaskRuns, bTaskRuns, "task_run")+}++// assertTasksCollide verifies that task UIDs collide across projects.+// Task UIDs are embedded in task_run resource names, so we can derive+// them without a separate ListTasks API (which gRPC does not expose).+func assertTasksCollide(ctx context.Context, t *testing.T, ctl *controller, f *collisionFixture) {+ t.Helper()+ a := require.New(t)++ _, aTasks := listTaskRunAndTaskUIDs(ctx, t, ctl, f.PlanA.Name)+ _, bTasks := listTaskRunAndTaskUIDs(ctx, t, ctl, f.PlanB.Name)+ a.Greater(len(aTasks), 0, "project A should have at least one task")+ a.Greater(len(bTasks), 0, "project B should have at least one task — did you forget to roll out B?")+ assertAtLeastOneUIDCollides(t, aTasks, bTasks, "task")+}++func assertAtLeastOneUIDCollides(t *testing.T, aUIDs, bUIDs []int64, label string) {+ t.Helper()+ aSet := make(map[int64]bool, len(aUIDs))+ for _, u := range aUIDs {+ aSet[u] = true+ }+ for _, u := range bUIDs {+ if aSet[u] {+ return+ }+ }+ require.Failf(t, "fixture invariant broken",+ "projects A and B should have at least one %s UID in common. Got A=%v, B=%v", label, aUIDs, bUIDs)+}++// listPlanUIDs returns every plan UID in the project, via the public gRPC+// ListPlans API. UIDs are parsed from the resource names.+func listPlanUIDs(ctx context.Context, t *testing.T, ctl *controller, projectName string) []int64 {+ t.Helper()+ a := require.New(t)+ resp, err := ctl.planServiceClient.ListPlans(ctx, connect.NewRequest(&v1pb.ListPlansRequest{+ Parent: projectName,+ PageSize: 1000,+ }))+ a.NoError(err, "ListPlans(%s)", projectName)+ out := make([]int64, 0, len(resp.Msg.Plans))+ for _, p := range resp.Msg.Plans {+ _, uid, err := common.GetProjectIDPlanID(p.Name)+ a.NoError(err, "parse plan name %q", p.Name)+ out = append(out, uid)+ }+ return out+}++// listIssueUIDs returns every issue UID in the project.+func listIssueUIDs(ctx context.Context, t *testing.T, ctl *controller, projectName string) []int64 {+ t.Helper()+ a := require.New(t)+ resp, err := ctl.issueServiceClient.ListIssues(ctx, connect.NewRequest(&v1pb.ListIssuesRequest{+ Parent: projectName,+ PageSize: 1000,+ }))+ a.NoError(err, "ListIssues(%s)", projectName)+ out := make([]int64, 0, len(resp.Msg.Issues))+ for _, i := range resp.Msg.Issues {+ _, uid, err := common.GetProjectIDIssueUID(i.Name)+ a.NoError(err, "parse issue name %q", i.Name)+ out = append(out, uid)+ }+ return out+}++// listTaskRunAndTaskUIDs returns every task_run UID and the set of task UIDs+// underneath a plan's rollout. Both come from parsing task_run names+// (projects/X/plans/Y/rollout/stages/Z/tasks/{taskUID}/taskRuns/{taskRunUID}),+// so one ListTaskRuns call covers both composite-PK tables without needing+// a separate ListTasks gRPC (which doesn't exist).+func listTaskRunAndTaskUIDs(ctx context.Context, t *testing.T, ctl *controller, planName string) (taskRunUIDs, taskUIDs []int64) {+ t.Helper()+ a := require.New(t)+ resp, err := ctl.rolloutServiceClient.ListTaskRuns(ctx, connect.NewRequest(&v1pb.ListTaskRunsRequest{+ Parent: planName + "/rollout/stages/-/tasks/-",+ }))+ a.NoError(err, "ListTaskRuns(%s)", planName)+ seenTasks := make(map[int64]bool)+ for _, tr := range resp.Msg.TaskRuns {+ _, _, _, taskUID, trUID, err := common.GetProjectIDPlanIDStageIDTaskIDTaskRunID(tr.Name)+ a.NoError(err, "parse task_run name %q", tr.Name)+ taskRunUIDs = append(taskRunUIDs, trUID)+ if !seenTasks[taskUID] {+ seenTasks[taskUID] = true+ taskUIDs = append(taskUIDs, taskUID)+ }+ }+ return taskRunUIDs, taskUIDs+}++// createSQLiteInstance provisions and registers a SQLite instance for test use.+func createSQLiteInstance(ctx context.Context, t *testing.T, ctl *controller, titlePrefix string) *v1pb.Instance {+ t.Helper()+ a := require.New(t)+ instanceDir, err := ctl.provisionSQLiteInstance(t.TempDir(), titlePrefix)+ a.NoError(err)+ resp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{+ InstanceId: generateRandomString(titlePrefix),+ Instance: &v1pb.Instance{+ Title: titlePrefix,+ Engine: v1pb.Engine_SQLITE,+ Environment: new("environments/prod"),+ Activation: true,+ DataSources: []*v1pb.DataSource{{Type: v1pb.DataSourceType_ADMIN, Host: instanceDir, Id: "admin"}},+ },+ }))+ a.NoError(err)+ return resp.Msg+}++// createPlanAndIssue creates a plan + issue for a DML change targeting the given+// database, without triggering a rollout. The caller must create the rollout.+func createPlanAndIssue(ctx context.Context, t *testing.T, ctl *controller, project *v1pb.Project, db *v1pb.Database, title string) (*v1pb.Plan, *v1pb.Issue) {+ t.Helper()+ a := require.New(t)++ sheet, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: project.Name,+ Sheet: &v1pb.Sheet{Content: []byte("SELECT 1;")},+ }))+ a.NoError(err)++ plan, err := ctl.planServiceClient.CreatePlan(ctx, connect.NewRequest(&v1pb.CreatePlanRequest{+ Parent: project.Name,+ Plan: &v1pb.Plan{+ Specs: []*v1pb.Plan_Spec{{+ Id: uuid.NewString(),+ Config: &v1pb.Plan_Spec_ChangeDatabaseConfig{+ ChangeDatabaseConfig: &v1pb.Plan_ChangeDatabaseConfig{+ Targets: []string{db.Name},+ Sheet: sheet.Msg.Name,+ },+ },+ }},+ },+ }))+ a.NoError(err)++ issue, err := ctl.issueServiceClient.CreateIssue(ctx, connect.NewRequest(&v1pb.CreateIssueRequest{+ Parent: project.Name,+ Issue: &v1pb.Issue{+ Title: title,+ Type: v1pb.Issue_DATABASE_CHANGE,+ Plan: plan.Msg.Name,+ },+ }))+ a.NoError(err)++ return plan.Msg, issue.Msg+}++// createPlanIssueRollout wraps createPlanAndIssue and also creates the rollout.+func createPlanIssueRollout(ctx context.Context, t *testing.T, ctl *controller, project *v1pb.Project, db *v1pb.Database, title string) (*v1pb.Plan, *v1pb.Issue, *v1pb.Rollout) {+ t.Helper()+ a := require.New(t)+ plan, issue := createPlanAndIssue(ctx, t, ctl, project, db, title)+ rollout, err := ctl.rolloutServiceClient.CreateRollout(ctx, connect.NewRequest(&v1pb.CreateRolloutRequest{+ Parent: plan.Name,+ }))+ a.NoError(err)+ return plan, issue, rollout.Msg+}++// projectSnapshot captures the state of a project's composite-PK rows as+// observed through the public gRPC API. Each slice's rows are keyed by the+// UID parsed from their resource name.+type projectSnapshot struct {+ Plans []*v1pb.Plan+ Issues []*v1pb.Issue+ TaskRuns []*v1pb.TaskRun+ PlanCheckRuns []*v1pb.PlanCheckRun+}++// snapshotProject captures every plan/issue/task_run/plan_check_run row+// visible to the public gRPC API for the given project. Every read goes+// through the service layer (auth + audit), not the raw store — so a+// read-path regression that leaks cross-project data would also surface in+// these calls.+//+// PlanCheckRuns are fetched via GetPlanCheckRun(planName+"/planCheckRun"),+// which is the single-consolidated-PCR endpoint the UI itself uses. One+// PCR per plan.+func snapshotProject(+ ctx context.Context,+ t *testing.T,+ ctl *controller,+ project *v1pb.Project,+) *projectSnapshot {+ t.Helper()+ a := require.New(t)++ plansResp, err := ctl.planServiceClient.ListPlans(ctx, connect.NewRequest(&v1pb.ListPlansRequest{+ Parent: project.Name,+ PageSize: 1000,+ }))+ a.NoError(err, "ListPlans(%s)", project.Name)+ plans := plansResp.Msg.Plans+ for _, p := range plans {+ a.True(strings.HasPrefix(p.Name, project.Name+"/"),+ "ListPlans(%s) returned %q — read-path leak", project.Name, p.Name)+ }++ issuesResp, err := ctl.issueServiceClient.ListIssues(ctx, connect.NewRequest(&v1pb.ListIssuesRequest{+ Parent: project.Name,+ PageSize: 1000,+ }))+ a.NoError(err, "ListIssues(%s)", project.Name)+ issues := issuesResp.Msg.Issues+ for _, i := range issues {+ a.True(strings.HasPrefix(i.Name, project.Name+"/"),+ "ListIssues(%s) returned %q — read-path leak", project.Name, i.Name)+ }++ var taskRuns []*v1pb.TaskRun+ var planCheckRuns []*v1pb.PlanCheckRun+ for _, p := range plans {+ trResp, err := ctl.rolloutServiceClient.ListTaskRuns(ctx, connect.NewRequest(&v1pb.ListTaskRunsRequest{+ Parent: p.Name + "/rollout/stages/-/tasks/-",+ }))+ a.NoError(err, "ListTaskRuns for plan %s", p.Name)+ for _, tr := range trResp.Msg.TaskRuns {+ a.True(strings.HasPrefix(tr.Name, project.Name+"/"),+ "ListTaskRuns for plan %s returned %q — read-path leak", p.Name, tr.Name)+ }+ taskRuns = append(taskRuns, trResp.Msg.TaskRuns...)++ pcrResp, err := ctl.planServiceClient.GetPlanCheckRun(ctx, connect.NewRequest(&v1pb.GetPlanCheckRunRequest{+ Name: p.Name + "/planCheckRun",+ }))+ // A plan may not have a check run yet; only NotFound is acceptable here.+ // Other codes (Internal, Permission, Unavailable) likely indicate a+ // real regression in the read path and should fail the snapshot.+ switch {+ case err == nil:+ a.True(strings.HasPrefix(pcrResp.Msg.Name, project.Name+"/"),+ "GetPlanCheckRun for plan %s returned %q — read-path leak", p.Name, pcrResp.Msg.Name)+ planCheckRuns = append(planCheckRuns, pcrResp.Msg)+ case connect.CodeOf(err) == connect.CodeNotFound:+ // expected: plan has no PCR yet+ default:+ a.NoError(err, "GetPlanCheckRun for plan %s", p.Name)+ }+ }++ return &projectSnapshot{+ Plans: plans,+ Issues: issues,+ TaskRuns: taskRuns,+ PlanCheckRuns: planCheckRuns,+ }+}++// assertProjectUnchanged fails if any row in the `before` snapshot went+// missing or got mutated in `after`. Keyed by resource name (unique per+// project by construction) so comparison is order-insensitive.+//+// Issue.UpdateTime is deliberately NOT compared — the approval runner+// actively updates open issues in the background, which is expected+// behavior, not a cross-project leak. Title and Status are the fields a+// cross-project corruption would mutate.+func assertProjectUnchanged(+ t *testing.T,+ before, after *projectSnapshot,+ label string,+) {+ t.Helper()+ a := require.New(t)++ assertNoChange(t, before.Plans, after.Plans,+ func(p *v1pb.Plan) string { return p.Name },+ func(b, af *v1pb.Plan) {+ a.True(proto.Equal(b.UpdateTime, af.UpdateTime), "%s: plan %s update_time changed", label, b.Name)+ },+ label, "plan")++ assertNoChange(t, before.Issues, after.Issues,+ func(i *v1pb.Issue) string { return i.Name },+ func(b, af *v1pb.Issue) {+ a.Equal(b.Title, af.Title, "%s: issue %s title changed", label, b.Name)+ a.Equal(b.Status, af.Status, "%s: issue %s status changed", label, b.Name)+ },+ label, "issue")++ assertNoChange(t, before.TaskRuns, after.TaskRuns,+ func(tr *v1pb.TaskRun) string { return tr.Name },+ func(b, af *v1pb.TaskRun) {+ a.Equal(b.Status, af.Status, "%s: task_run %s status changed from %v to %v", label, b.Name, b.Status, af.Status)+ a.True(proto.Equal(b.UpdateTime, af.UpdateTime), "%s: task_run %s update_time changed", label, b.Name)+ },+ label, "task_run")++ assertNoChange(t, before.PlanCheckRuns, after.PlanCheckRuns,+ func(p *v1pb.PlanCheckRun) string { return p.Name },+ func(b, af *v1pb.PlanCheckRun) {+ a.Equal(b.Status, af.Status, "%s: plan_check_run %s status changed from %v to %v", label, b.Name, b.Status, af.Status)+ },+ label, "plan_check_run")+}++// assertNoChange compares two row slices keyed by name, fails if any+// row disappeared, appeared, or duplicated. Per-row equality beyond+// identity is delegated to the caller's `compare` func.+func assertNoChange[T any](+ t *testing.T,+ before, after []T,+ key func(T) string,+ compare func(b, af T),+ label, kind string,+) {+ t.Helper()+ a := require.New(t)+ byKey := make(map[string]T, len(before))+ for _, r := range before {+ _, dup := byKey[key(r)]+ a.False(dup, "%s: duplicate %s %q in before snapshot", label, kind, key(r))+ byKey[key(r)] = r+ }+ a.Equal(len(before), len(after), "%s: %s count changed", label, kind)+ seen := make(map[string]bool, len(after))+ for _, r := range after {+ a.False(seen[key(r)], "%s: duplicate %s %q in after snapshot", label, kind, key(r))+ seen[key(r)] = true+ b, ok := byKey[key(r)]+ a.True(ok, "%s: %s %q appeared after", label, kind, key(r))+ if ok {+ compare(b, r)+ }+ }+}diff --git a/backend/tests/cross_project_claim_test.go b/backend/tests/cross_project_claim_test.gonew file mode 100644index 0000000000..d830685808--- /dev/null+++ b/backend/tests/cross_project_claim_test.go@@ -0,0 +1,83 @@+package tests++import (+ "context"+ "testing"+ "time"++ "github.com/stretchr/testify/require"++ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+)++// TestClaimAvailableTaskRunsNoCrossProjectResurrection verifies that the+// `ClaimAvailableTaskRuns` store query cannot resurrect a DONE task_run in+// another project, even when both projects have the same numeric task_run id.+//+// Design: rather than calling ClaimAvailableTaskRuns directly (which would+// leave rows stuck in RUNNING because the test's replica_id doesn't match+// the scheduler's, so the real scheduler would skip them and waitRollout+// would hang), we let the live scheduler run the claim naturally via+// completeRolloutB. The claim SQL is the same either way — this test's+// regression value is in observing whether project A's DONE rows survive+// the scheduler's claim pass unchanged.+//+// Regression lock for BYT-9259 (customer data loss from silent re-execution).+func TestClaimAvailableTaskRunsNoCrossProjectResurrection(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ fixture := setupCollidingProjects(ctx, t, ctl)++ // fixture.BaselineA was captured inside setupCollidingProjects BEFORE+ // project B's plan was created, so it reflects project A's state+ // uncontaminated by any scheduler side effect on project B.+ a.Greater(len(fixture.BaselineA.TaskRuns), 0, "project A should have task_runs")+ for _, tr := range fixture.BaselineA.TaskRuns {+ a.Equal(v1pb.TaskRun_DONE, tr.Status,+ "project A task_run should be DONE before any project B activity")+ }++ fixture.completeRolloutB(ctx, t, ctl)++ afterA := snapshotProject(ctx, t, ctl, fixture.ProjectA)+ assertProjectUnchanged(t, fixture.BaselineA, afterA, "project A after scheduler claim pass")+}++// TestClaimAvailablePlanCheckRunsNoCrossProjectTransition verifies that the+// `ClaimAvailablePlanCheckRuns` store query cannot transition a terminal+// plan_check_run in another project.+func TestClaimAvailablePlanCheckRunsNoCrossProjectTransition(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ fixture := setupCollidingProjects(ctx, t, ctl)++ // Project A's consolidated plan_check_run must be in a terminal state+ // before B does any work — otherwise a corruption during fixture setup+ // could be baked into the "before" oracle and escape detection.+ a.Greater(len(fixture.BaselineA.PlanCheckRuns), 0, "project A should have plan_check_runs")+ for _, pcr := range fixture.BaselineA.PlanCheckRuns {+ a.NotEqual(v1pb.PlanCheckRun_STATUS_UNSPECIFIED, pcr.Status,+ "project A plan_check_run status should be set at baseline")+ a.NotEqual(v1pb.PlanCheckRun_RUNNING, pcr.Status,+ "project A plan_check_run should not be RUNNING at baseline")+ }++ fixture.completeRolloutB(ctx, t, ctl)++ afterA := snapshotProject(ctx, t, ctl, fixture.ProjectA)+ assertProjectUnchanged(t, fixture.BaselineA, afterA, "project A after scheduler plan_check_run claim pass")+}diff --git a/backend/tests/cross_project_delete_test.go b/backend/tests/cross_project_delete_test.gonew file mode 100644index 0000000000..06d2a43679--- /dev/null+++ b/backend/tests/cross_project_delete_test.go@@ -0,0 +1,182 @@+package tests++import (+ "context"+ "testing"+ "time"++ "connectrpc.com/connect"+ "github.com/stretchr/testify/require"++ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+)++// TestCollisionDeleteProjectCascade verifies that permanently deleting+// project A does not remove or modify any rows belonging to project B,+// even when both projects have colliding composite-PK ids.+//+// Scope: covers plan, issue, task_run, plan_check_run isolation via the+// gRPC snapshot. Tables NOT covered here (currently): task, task_run_log,+// plan_webhook_delivery. Add targeted tests if a future change touches+// their DELETE paths.+func TestCollisionDeleteProjectCascade(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ fixture := setupCollidingProjects(ctx, t, ctl)++ fixture.completeRolloutB(ctx, t, ctl)++ beforeB := snapshotProject(ctx, t, ctl, fixture.ProjectB)+ a.Greater(len(beforeB.TaskRuns), 0, "project B should have task_runs")+ a.Greater(len(beforeB.Plans), 0, "project B should have plans")+ a.Greater(len(beforeB.Issues), 0, "project B should have issues")++ // DeleteProject with Purge=true handles both soft-delete and hard-delete+ // (cascade) in one gRPC call.+ _, err = ctl.projectServiceClient.DeleteProject(ctx,+ connect.NewRequest(&v1pb.DeleteProjectRequest{+ Name: fixture.ProjectA.Name,+ Purge: true,+ }))+ a.NoError(err)++ // Positive check: project A itself must actually be gone. Without this,+ // a regression that turned DeleteProject into a no-op would still pass+ // the project-B-unchanged check below.+ _, err = ctl.projectServiceClient.GetProject(ctx,+ connect.NewRequest(&v1pb.GetProjectRequest{Name: fixture.ProjectA.Name}))+ a.Error(err, "project A should be gone after purge; GetProject should fail")++ afterB := snapshotProject(ctx, t, ctl, fixture.ProjectB)+ assertProjectUnchanged(t, beforeB, afterB, "project B after project A deleted")+}++// TestCollisionDeleteInstanceNoCrossProjectCorruption verifies that deleting+// a shared instance cleans up both projects' instance-scoped rows (task_run)+// via the USING-join DELETE paths in the store, without cross-project+// corruption of project-scoped rows (plan, issue).+//+// Scope note: because setupCollidingProjects places both projects on a+// shared instance, this test cannot distinguish "bug: delete also wiped B's+// rows because it was cross-matching on id alone" from "correct: delete+// wiped B's rows because they were on the deleted instance". It therefore+// focuses on two things the composite-PK bug class can break:+// 1. Symmetric cleanup of instance-scoped rows for both projects.+// 2. Survival of project-scoped rows (plans, issues) for both projects.+//+// TestCollisionDeleteInstanceCrossProjectIsolation (below) covers the+// asymmetric scenario with separate per-project instances.+func TestCollisionDeleteInstanceNoCrossProjectCorruption(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ fixture := setupCollidingProjects(ctx, t, ctl)++ fixture.completeRolloutB(ctx, t, ctl)++ beforeA := snapshotProject(ctx, t, ctl, fixture.ProjectA)+ beforeB := snapshotProject(ctx, t, ctl, fixture.ProjectB)+ a.Greater(len(beforeA.TaskRuns), 0, "project A should have task_runs before instance deletion")+ a.Greater(len(beforeB.TaskRuns), 0, "project B should have task_runs before instance deletion")++ purgeInstance(ctx, t, ctl, fixture.Instance.Name)++ afterA := snapshotProject(ctx, t, ctl, fixture.ProjectA)+ afterB := snapshotProject(ctx, t, ctl, fixture.ProjectB)++ // Instance-scoped rows (task_run) are removed for BOTH projects.+ // Asymmetric counts here would indicate a cross-project bug in the+ // DELETE USING predicates.+ a.Equal(0, len(afterA.TaskRuns), "project A task_runs should be cleaned up")+ a.Equal(0, len(afterB.TaskRuns), "project B task_runs should be cleaned up")++ // Project-scoped rows (plan, issue) are NOT instance-scoped and must+ // survive. Cross-project corruption would shift counts or swap rows.+ assertProjectUnchanged(t, plansIssuesOnly(beforeA), plansIssuesOnly(afterA), "project A plans/issues")+ assertProjectUnchanged(t, plansIssuesOnly(beforeB), plansIssuesOnly(afterB), "project B plans/issues")+}++// TestCollisionDeleteInstanceCrossProjectIsolation is the variant that can+// distinguish correct cascade from cross-project over-delete. Each project+// gets its OWN instance, but composite-PK ids still collide across projects+// via per-project nextProjectID allocation. Deleting instance A must only+// affect project A's rows — project B's task_runs must survive unchanged.+//+// This is the test that catches a buggy `DELETE ... USING` predicate that+// cross-matches rows on `id` alone across projects.+func TestCollisionDeleteInstanceCrossProjectIsolation(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ fixture := setupCollidingProjectsSeparateInstances(ctx, t, ctl)++ fixture.completeRolloutB(ctx, t, ctl)++ beforeA := snapshotProject(ctx, t, ctl, fixture.ProjectA)+ beforeB := snapshotProject(ctx, t, ctl, fixture.ProjectB)+ a.Greater(len(beforeA.TaskRuns), 0, "project A should have task_runs before deletion")+ a.Greater(len(beforeB.TaskRuns), 0, "project B should have task_runs before deletion")++ purgeInstance(ctx, t, ctl, fixture.InstanceA.Name)++ // Positive check: project A's instance-scoped rows must actually be+ // removed. Without this, a no-op DeleteInstance would leave orphaned+ // state and still pass the cross-project isolation check.+ afterA := snapshotProject(ctx, t, ctl, fixture.ProjectA)+ a.Equal(0, len(afterA.TaskRuns),+ "project A task_runs should be cleaned up after its instance is deleted")++ // Isolation check: project B's rows reference instance B and must+ // survive entirely unchanged.+ afterB := snapshotProject(ctx, t, ctl, fixture.ProjectB)+ assertProjectUnchanged(t, beforeB, afterB, "project B after instance A deleted")+}++// purgeInstance soft-deletes (with Force because the instance has attached+// databases) then hard-deletes the instance via the gRPC API. The DeleteInstance+// API requires the instance already be soft-deleted before Purge works.+func purgeInstance(ctx context.Context, t *testing.T, ctl *controller, name string) {+ t.Helper()+ a := require.New(t)+ _, err := ctl.instanceServiceClient.DeleteInstance(ctx,+ connect.NewRequest(&v1pb.DeleteInstanceRequest{+ Name: name,+ Force: true,+ }))+ a.NoError(err, "soft-delete instance %s", name)+ _, err = ctl.instanceServiceClient.DeleteInstance(ctx,+ connect.NewRequest(&v1pb.DeleteInstanceRequest{+ Name: name,+ Purge: true,+ }))+ a.NoError(err, "purge instance %s", name)+}++// plansIssuesOnly returns a snapshot containing only the plan and issue+// slices — used by tests that expect task_run rows to be deleted but+// plan/issue rows to be preserved.+func plansIssuesOnly(s *projectSnapshot) *projectSnapshot {+ return &projectSnapshot{+ Plans: s.Plans,+ Issues: s.Issues,+ }+}diff --git a/backend/tests/cross_project_update_test.go b/backend/tests/cross_project_update_test.gonew file mode 100644index 0000000000..7f7698d6c5--- /dev/null+++ b/backend/tests/cross_project_update_test.go@@ -0,0 +1,209 @@+package tests++import (+ "context"+ "strings"+ "testing"+ "time"++ "connectrpc.com/connect"+ "github.com/stretchr/testify/require"+ "google.golang.org/protobuf/types/known/fieldmaskpb"++ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+)++// TestCollisionUpdateIssueNoCrossProjectEffect verifies that updating+// an issue in project A (a) actually changes A's title and (b) does not+// leak the title/status mutation into project B's same-id issue.+//+// Note on assertion scope: we deliberately avoid a full snapshot comparison+// of project B here. The approval runner actively updates project B's open+// issue in the background (approval template resolution, updated_at) —+// that's expected behavior, not a cross-project leak. Title and Status are+// the fields UpdateIssue(A) could actually cross-corrupt if the WHERE clause+// were broken, so those are what we assert.+func TestCollisionUpdateIssueNoCrossProjectEffect(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ fixture := setupCollidingProjects(ctx, t, ctl)++ issueBBefore, err := ctl.issueServiceClient.GetIssue(ctx,+ connect.NewRequest(&v1pb.GetIssueRequest{Name: fixture.IssueB.Name}))+ a.NoError(err)++ const updatedTitle = "Updated collision test A"+ _, err = ctl.issueServiceClient.UpdateIssue(ctx,+ connect.NewRequest(&v1pb.UpdateIssueRequest{+ Issue: &v1pb.Issue{+ Name: fixture.IssueA.Name,+ Title: updatedTitle,+ },+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"title"}},+ }))+ a.NoError(err)++ // Positive check: confirm project A's issue actually received the update.+ issueAAfter, err := ctl.issueServiceClient.GetIssue(ctx,+ connect.NewRequest(&v1pb.GetIssueRequest{Name: fixture.IssueA.Name}))+ a.NoError(err)+ a.Equal(updatedTitle, issueAAfter.Msg.Title,+ "project A's issue title should have been updated")++ // Isolation check: project B's Title/Status — the fields UpdateIssue can+ // cross-corrupt — must be unchanged.+ issueBAfter, err := ctl.issueServiceClient.GetIssue(ctx,+ connect.NewRequest(&v1pb.GetIssueRequest{Name: fixture.IssueB.Name}))+ a.NoError(err)+ a.Equal(issueBBefore.Msg.Title, issueBAfter.Msg.Title,+ "project B's issue title leaked from project A update")+ a.Equal(issueBBefore.Msg.Status, issueBAfter.Msg.Status,+ "project B's issue status leaked from project A update")+}++// TestCollisionListPlansIsolation verifies that ListPlans scoped to project A+// does not leak project B's plans.+func TestCollisionListPlansIsolation(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ fixture := setupCollidingProjects(ctx, t, ctl)++ resp, err := ctl.planServiceClient.ListPlans(ctx,+ connect.NewRequest(&v1pb.ListPlansRequest{Parent: fixture.ProjectA.Name, PageSize: 100}))+ a.NoError(err)++ // Positive precondition — without this, an over-filtering regression+ // that returned zero rows would silently pass the prefix check below.+ a.Greater(len(resp.Msg.Plans), 0, "project A should have plans (fixture creates them)")++ for _, p := range resp.Msg.Plans {+ a.True(strings.HasPrefix(p.Name, fixture.ProjectA.Name+"/"),+ "ListPlans for project A returned a plan from another project: %s", p.Name)+ }+}++// TestCollisionListTaskRunsIsolation verifies that ListTaskRuns scoped to a+// project A rollout does not leak project B's task_runs, using the wildcard+// parent form that the production API supports.+func TestCollisionListTaskRunsIsolation(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ fixture := setupCollidingProjects(ctx, t, ctl)+ fixture.completeRolloutB(ctx, t, ctl)++ resp, err := ctl.rolloutServiceClient.ListTaskRuns(ctx,+ connect.NewRequest(&v1pb.ListTaskRunsRequest{+ Parent: fixture.PlanA.Name + "/rollout/stages/-/tasks/-",+ }))+ a.NoError(err)++ // Positive precondition: project A's rollout completed during fixture+ // setup, so it must have task_runs. Without this, an over-filtering+ // regression returning zero rows would silently pass the prefix check.+ a.Greater(len(resp.Msg.TaskRuns), 0, "project A should have task_runs after fixture rollout")++ for _, tr := range resp.Msg.TaskRuns {+ a.True(strings.HasPrefix(tr.Name, fixture.ProjectA.Name+"/"),+ "ListTaskRuns for project A returned %s from another project", tr.Name)+ }+}++// TestCollisionGetPlanCheckRunIsolation verifies that GetPlanCheckRun for+// project A's plan returns only project A's check run, even when project B+// has a plan_check_run with the same numeric composite-PK id.+func TestCollisionGetPlanCheckRunIsolation(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ fixture := setupCollidingProjects(ctx, t, ctl)+ fixture.completeRolloutB(ctx, t, ctl)++ resp, err := ctl.planServiceClient.GetPlanCheckRun(ctx,+ connect.NewRequest(&v1pb.GetPlanCheckRunRequest{+ Name: fixture.PlanA.Name + "/planCheckRun",+ }))+ a.NoError(err)+ a.True(strings.HasPrefix(resp.Msg.Name, fixture.ProjectA.Name+"/"),+ "GetPlanCheckRun for plan A returned %s from another project", resp.Msg.Name)+}++// TestCollisionGetIssueIsolation verifies that GetIssue with project A's+// issue name returns project A's issue, not project B's.+func TestCollisionGetIssueIsolation(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ fixture := setupCollidingProjects(ctx, t, ctl)++ issueA, err := ctl.issueServiceClient.GetIssue(ctx,+ connect.NewRequest(&v1pb.GetIssueRequest{Name: fixture.IssueA.Name}))+ a.NoError(err)+ a.Equal(fixture.IssueA.Name, issueA.Msg.Name,+ "GetIssue returned wrong issue")+ a.Equal("Collision test A", issueA.Msg.Title,+ "GetIssue returned project B's issue title instead of project A's")+}++// TestCollisionListIssuesIsolation verifies that ListIssues scoped to+// project A does not return project B's issues.+func TestCollisionListIssuesIsolation(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ fixture := setupCollidingProjects(ctx, t, ctl)++ resp, err := ctl.issueServiceClient.ListIssues(ctx,+ connect.NewRequest(&v1pb.ListIssuesRequest{+ Parent: fixture.ProjectA.Name,+ PageSize: 100,+ }))+ a.NoError(err)++ // Positive precondition — guard against an over-filter regression+ // that would make the prefix check vacuously true.+ a.Greater(len(resp.Msg.Issues), 0, "project A should have issues (fixture creates them)")++ for _, issue := range resp.Msg.Issues {+ a.True(strings.HasPrefix(issue.Name, fixture.ProjectA.Name+"/"),+ "ListIssues for project A returned an issue from another project: %s", issue.Name)+ }+}diff --git a/docs/pre-pr-checklist.md b/docs/pre-pr-checklist.mdnew file mode 100644index 0000000000..3a5f54d85e--- /dev/null+++ b/docs/pre-pr-checklist.md@@ -0,0 +1,194 @@+# Pre-PR Checklist++Run through every section below before creating a pull request. Each section has a+skip condition — check it first to avoid unnecessary work.++## 1. Determine What Changed++```bash+git diff main...HEAD --stat+git diff main...HEAD+```++Use the diff output to decide which sections below apply.++## 2. Breaking Change Check++**Skip if:** diff only touches test files, docs, or comments.++Review the diff against each category. A "breaking change" is anything that could+cause existing users, integrations, or deployments to fail after upgrading.++| # | Category | What to look for |+|---|----------|-----------------|+| 1 | API | Removed/renamed endpoints, changed request/response formats, removed query params |+| 2 | Database schema | Dropped columns/tables, non-backward-compatible migrations |+| 3 | Proto | Removed/renamed fields, changed field numbers/types, removed RPCs |+| 4 | Configuration | Removed flags, changed defaults, renamed env vars |+| 5 | Behavior | Changed default values, altered workflows, modified permission logic |+| 6 | Webhooks/events | Renamed/removed events, changed payload formats |+| 7 | UI workflows | Redesigned user-facing flows that change how users perform existing tasks |+| 8 | Composite-PK migration | Adding a composite PK to an EXISTING table, or changing the PK columns of an existing table. Does NOT apply to: new queries (those are bugs — block via section 3), or new tables with composite PKs (those are additive). |++**If ANY apply:**+- Add `--label breaking` to the `gh pr create` command+- Include a `## Breaking Changes` section in the PR body++**Common NOT-breaking scenarios** (do not add the breaking label):+- A new method/query on a composite-PK table (even if buggy — block via section 3 instead)+- A new table added via migration (even with composite PK — it's additive)+- A bug fix that adds missing PK columns to an existing query (it restores correctness)++## 3. Composite-PK Query Safety++**Skip if:** diff does not touch `backend/store/` or `backend/migrator/`.++Composite primary keys (e.g., `(project, id)`) mean that `id` alone is NOT unique.+Filtering by `id` without `project` causes cross-project data corruption — the exact+bug class behind BYT-9259 (customer data loss from silent task re-execution).++### Step 3a: Identify composite-PK tables in the diff++Read `backend/migrator/migration/LATEST.sql` and find every table with a multi-column+`PRIMARY KEY`. The known project-scoped set (as of April 2026) includes:++- `plan (project, id)`+- `plan_check_run (project, id)`+- `plan_webhook_delivery (project, plan_id)`+- `issue (project, id)`+- `task (project, id)`+- `task_run (project, id)`+- `task_run_log (project, task_run_id, created_at)`+- `db_group (project, resource_id)`+- `release (project, train, iteration)`++Always verify against LATEST.sql — tables may have been added since this list was+last updated. Cross-reference with the tables your diff touches.++### Step 3b: Verify predicates++For every query in the diff that touches a composite-PK table, verify:++- Every `WHERE` clause includes ALL primary key columns+- Every `JOIN ... ON` includes ALL primary key columns+- Every `DELETE ... USING` includes ALL primary key columns+- Every `UPDATE ... FROM` includes ALL primary key columns++**Red flag pattern:** `WHERE id = ?` without `AND project = ?` on any of these tables.++**STOP — do not proceed to PR creation if any predicate is missing a PK column.**+This is the exact bug pattern that caused BYT-9259. Fix the query first.++### Step 3c: Verify collision test coverage++If the diff adds or modifies a store method that touches a composite-PK table:++1. Check if a corresponding `TestCollision*` or `TestClaim*` test exists in `backend/tests/`+2. If not, add one using `setupCollidingProjects` and `assertProjectUnchanged` from+ `backend/tests/collision_helper_test.go`. Note: the shared snapshot currently+ covers `plan`, `issue`, `task`, `task_run`, and `plan_check_run`. For methods+ touching `task_run_log`, `plan_webhook_delivery`, `db_group`, or `release`,+ add table-specific assertions inline — the shared helper is not sufficient+3. If your test needs project B rolled out (to create task/task_run/plan_check_run+ rows that could collide with project A's), call `fixture.completeRolloutB(ctx, t, ctl)`+ — this is the ONLY supported rollout path and it proves `task` and `task_run`+ id collisions automatically. (Plan-check-run id collision is NOT proven —+ the v1 API uses a UID-less name for PCRs, so the collision can't be observed+ from public gRPC. The PCR claim test is belt-and-suspenders coverage; the+ load-bearing regression lock is the task_run claim test.) Do NOT hand-roll+ `CreateRollout` + `waitRollout` — the collision invariant must not be a+ per-test responsibility+4. If testing delete cascades across projects where both projects share an+ instance, also consider adding a variant using `setupCollidingProjectsSeparateInstances`+ to catch cross-project over-delete bugs that shared-instance tests cannot detect+5. **Every cross-project / isolation test must have a positive precondition.**+ `assert(rows belong to project A)` is vacuously true when the list is+ empty. Add `Greater(len, 0, ...)` for the list under test before iterating+ so that an over-filtering regression cannot pass silently.++If the diff adds a NEW composite-PK table via migration:++1. Add collision test coverage for every store method touching the new table+2. Update the table list in step 3a above++**STOP — do not proceed to PR creation until collision tests exist for every new or+modified store method on a composite-PK table.** Write the tests before continuing.++### Step 3d: Run collision tests++Only run after steps 3b and 3c are resolved.++```bash+go test -v -count=1 ./backend/tests/ -run "^(TestClaim|TestCollision)" -timeout 5m+```++All must pass before proceeding.++### Step 3e: Doc-code drift check++**Skip if:** the diff didn't remove or rename any exported symbol or any+documented helper.++If you removed `Server.StoreForTest()`, renamed `assertFooCollide`, etc.,+grep for stale references that would now lie to the reader:++```bash+git diff main...HEAD --name-only -- '*.go' | xargs -I{} grep -l 'OldSymbolName' AGENTS.md docs/ backend/ 2>/dev/null+```++For each match, either delete the prose or update it to reference the+current API. AGENTS.md and `docs/pre-pr-checklist.md` are the highest-leak+spots — they document what helpers exist and what guarantees they make.+Stale references don't break the build but they actively mislead future+contributors and AI agents that read these docs at session start.++## 4. Lint and Format Gate++**Skip if:** no code changes (docs-only PR).++Run the checks relevant to the files you changed:++**Go changes:**+```bash+gofmt -w <changed .go files>+golangci-lint run --allow-parallel-runners+```+Run golangci-lint repeatedly until zero issues (the linter has a max-issues limit).++**Frontend changes:**+```bash+pnpm --dir frontend check+pnpm --dir frontend type-check+```++**Proto changes:**+```bash+buf lint proto+```++## 5. Test Gate++**Skip if:** no code changes.++- Run tests for every changed package+- For store changes touching composite-PK tables, run the collision tests (section 3d)+- For Go changes: `go build -ldflags "-w -s" -p=16 -o ./bytebase-build/bytebase ./backend/bin/server/main.go`+- For new migration files: update `TestLatestVersion` in `backend/migrator/migrator_test.go`++## 6. SonarCloud Properties++**Skip if:** no new files or directories added.++Update `.sonarcloud.properties` to reflect the latest file structure:+- `sonar.exclusions` for generated code, build artifacts, dependencies (directory paths)+- `sonar.test.inclusions` for test file patterns (e.g., `**/*_test.go`)+- `sonar.cpd.exclusions` to skip copy-paste detection on test files++## 7. Final Verification++Before running `gh pr create`:++- [ ] All checks above passed or were correctly skipped+- [ ] PR description clearly describes what changed and why+- [ ] Breaking changes are labeled and documented (if applicable)+- [ ] No unrelated files are staged