Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
perf(tests): second pass on backend test time, 189 s to 140 s (#21358)
Danny Xu114923e41a4c
diff --git a/.github/workflows/backend-tests.yml b/.github/workflows/backend-tests.ymlindex e619d67e95..501b45ac0e 100644--- a/.github/workflows/backend-tests.yml+++ b/.github/workflows/backend-tests.yml@@ -33,7 +33,10 @@ jobs:go mod tidygit diff --exit-code- name: Run all tests- run: go test -p=8 -timeout 30m -ldflags "-w -s" -v ./backend/... | tee test.log; exit ${PIPESTATUS[0]}+ # go test runs packages in command-line order. backend/tests is the+ # longest package by far, so it goes first instead of after the ~130+ # packages that sort before it alphabetically.+ run: go test -p=8 -timeout 30m -ldflags "-w -s" -v ./backend/tests ./backend/api/v1 ./backend/... | tee test.log; exit ${PIPESTATUS[0]}- name: Pretty print tests running time# grep: filter out lines like "--- PASS: Test (15.04s)"# sed: remove unnecessary charactersdiff --git a/AGENTS.md b/AGENTS.mdindex f5eeb31991..9f907debec 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -48,8 +48,10 @@ those live in `backend/tests`, the only package that may start one; everythingelse asserts in `backend/api/v1` or `backend/store`.A package needing a real metadata Postgres shares one through-`testcontainer.MetadataMain` and `testcontainer.NewMetadataDB`, never its own-container. Prefer needing none: extract the+`testcontainer.Main` and `testcontainer.NewMetadataDB`, never its own+container; a package needing a target engine shares one the same way through+`testcontainer.SharedPgContainer` and its siblings, with `NewPgDatabase` for+a database per test. Prefer needing none: extract thedecide-and-convert half of a handler as functions over plain data, and wherestate is genuinely read declare an interface beside the handler and fake it, as`backend/api/mcp` does with `serverStore` — never one interface over the wholediff --git a/action/command/rollout.go b/action/command/rollout.goindex b467aefd5f..deb3a622b8 100644--- a/action/command/rollout.go+++ b/action/command/rollout.go@@ -265,7 +265,7 @@ func waitForRollout(ctx context.Context, w *world.World, client *client, rolloutreturn errors.Wrapf(err, "failed to batch create tasks")}}- time.Sleep(5 * time.Second)+ time.Sleep(w.RolloutPollInterval)}}diff --git a/action/world/world.go b/action/world/world.goindex e2375c4aab..5f2a085834 100644--- a/action/world/world.go+++ b/action/world/world.go@@ -16,6 +16,9 @@ type World struct {// Whether it is the rollout subcommand.IsRollout bool+ // How long the rollout subcommand waits between status polls. Not a flag:+ // releases keep the default, and the workflow tests shorten it.+ RolloutPollInterval time.Duration// bytebase-action flagsOutput string@@ -62,7 +65,8 @@ type World struct {func NewWorld() *World {return &World{- CurrentTime: time.Now(),- Logger: slog.Default(),+ CurrentTime: time.Now(),+ Logger: slog.Default(),+ RolloutPollInterval: 5 * time.Second,}}diff --git a/backend/api/auth/main_test.go b/backend/api/auth/main_test.goindex da5bfddf51..07c589aaa8 100644--- a/backend/api/auth/main_test.go+++ b/backend/api/auth/main_test.go@@ -6,4 +6,4 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer")-func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/api/lsp/main_test.go b/backend/api/lsp/main_test.goindex c7ff522aab..7213fc0eee 100644--- a/backend/api/lsp/main_test.go+++ b/backend/api/lsp/main_test.go@@ -6,4 +6,4 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer")-func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/api/mcp/main_test.go b/backend/api/mcp/main_test.goindex 74d60b064c..9e05e0b2c7 100644--- a/backend/api/mcp/main_test.go+++ b/backend/api/mcp/main_test.go@@ -6,4 +6,4 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer")-func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/api/oauth2/main_test.go b/backend/api/oauth2/main_test.goindex 386ac75fe8..6dae3c8abd 100644--- a/backend/api/oauth2/main_test.go+++ b/backend/api/oauth2/main_test.go@@ -6,4 +6,4 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer")-func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/api/v1/access_grant_service_test.go b/backend/api/v1/access_grant_service_test.goindex a3f128a068..515103e1be 100644--- a/backend/api/v1/access_grant_service_test.go+++ b/backend/api/v1/access_grant_service_test.go@@ -12,6 +12,7 @@ import ()func TestIsReadOnlyStatementForAccessGrantRejectsDocumentEngineWriteStatements(t *testing.T) {+ t.Parallel()tests := []struct {name stringengine storepb.Engine@@ -41,6 +42,7 @@ func TestIsReadOnlyStatementForAccessGrantRejectsDocumentEngineWriteStatements(tfor _, tc := range tests {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()readOnly, err := isReadOnlyStatementForAccessGrant(context.Background(), tc.engine, tc.statement)require.NoError(t, err)require.False(t, readOnly)@@ -49,6 +51,7 @@ func TestIsReadOnlyStatementForAccessGrantRejectsDocumentEngineWriteStatements(t}func TestIsReadOnlyStatementForAccessGrantAllowsDocumentEngineReadStatements(t *testing.T) {+ t.Parallel()tests := []struct {name stringengine storepb.Engine@@ -68,6 +71,7 @@ func TestIsReadOnlyStatementForAccessGrantAllowsDocumentEngineReadStatements(t *for _, tc := range tests {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()readOnly, err := isReadOnlyStatementForAccessGrant(context.Background(), tc.engine, tc.statement)require.NoError(t, err)require.True(t, readOnly)@@ -76,6 +80,7 @@ func TestIsReadOnlyStatementForAccessGrantAllowsDocumentEngineReadStatements(t *}func TestIsReadOnlyStatementForAccessGrantRejectsDocumentEngineInvalidStatements(t *testing.T) {+ t.Parallel()readOnly, err := isReadOnlyStatementForAccessGrant(context.Background(), storepb.Engine_ELASTICSEARCH, `db.users.find({})`)require.Error(t, err)require.False(t, readOnly)@@ -87,6 +92,7 @@ func TestIsReadOnlyStatementForAccessGrantRejectsDocumentEngineInvalidStatements// frontend tooltips and audit displays that depend on the user-typed// reason silently render empty.func TestConvertToAccessGrantPropagatesPayloadFields(t *testing.T) {+ t.Parallel()expire := time.Date(2026, 6, 30, 12, 0, 0, 0, time.UTC)msg := &store.AccessGrantMessage{ProjectID: "proj",@@ -119,6 +125,7 @@ func TestConvertToAccessGrantPropagatesPayloadFields(t *testing.T) {// TestConvertToAccessGrantNilPayloadIsSafe guards the `if p := msg.Payload; p != nil`// branch — a nil payload must not panic and payload-sourced fields stay zero.func TestConvertToAccessGrantNilPayloadIsSafe(t *testing.T) {+ t.Parallel()msg := &store.AccessGrantMessage{ProjectID: "proj",ID: "ag1",diff --git a/backend/api/v1/account_email_validation_test.go b/backend/api/v1/account_email_validation_test.goindex 6b7a015959..1a3ae39a08 100644--- a/backend/api/v1/account_email_validation_test.go+++ b/backend/api/v1/account_email_validation_test.go@@ -7,6 +7,7 @@ import ()func TestValidateServiceAccountEmail(t *testing.T) {+ t.Parallel()tests := []struct {name stringemail string@@ -31,6 +32,7 @@ func TestValidateServiceAccountEmail(t *testing.T) {for _, test := range tests {t.Run(test.name, func(t *testing.T) {+ t.Parallel()err := validateServiceAccountEmail(test.email)if test.valid {require.NoError(t, err)@@ -42,6 +44,7 @@ func TestValidateServiceAccountEmail(t *testing.T) {}func TestValidateWorkloadIdentityEmail(t *testing.T) {+ t.Parallel()tests := []struct {name stringemail string@@ -66,6 +69,7 @@ func TestValidateWorkloadIdentityEmail(t *testing.T) {for _, test := range tests {t.Run(test.name, func(t *testing.T) {+ t.Parallel()err := validateWorkloadIdentityEmail(test.email)if test.valid {require.NoError(t, err)diff --git a/backend/api/v1/acl_allow_missing_test.go b/backend/api/v1/acl_allow_missing_test.goindex 81abdb63d1..9bd08b5aa9 100644--- a/backend/api/v1/acl_allow_missing_test.go+++ b/backend/api/v1/acl_allow_missing_test.go@@ -75,6 +75,7 @@ type allowMissingCreateCheck struct {// TestAllowMissingCreatePermission fails when an allow_missing create path is// authorized by nobody, or by a permission that cannot deny or cannot grant.func TestAllowMissingCreatePermission(t *testing.T) {+ t.Parallel()found := allowMissingMethods(t)var undeclared []stringdiff --git a/backend/api/v1/acl_test.go b/backend/api/v1/acl_test.goindex e053f1d359..cce5de6bd0 100644--- a/backend/api/v1/acl_test.go+++ b/backend/api/v1/acl_test.go@@ -30,6 +30,7 @@ func TestResourceResolutionConnectError(t *testing.T) {}func TestACLCheckResourceResolutionStatus(t *testing.T) {+ t.Parallel()ctx, stores, _, _, _, _ := setupWorkspaceInstanceDescendantServiceTest(t)interceptor := NewACLInterceptor(stores, "", nil, nil)@@ -50,6 +51,7 @@ func TestACLCheckResourceResolutionStatus(t *testing.T) {},} {t.Run(test.name, func(t *testing.T) {+ t.Parallel()err := interceptor.doACLCheck(authenticatedACLContext(ctx), test.request, v1connect.DatabaseServiceGetDatabaseProcedure)require.Equal(t, test.want, connect.CodeOf(err))})@@ -57,6 +59,7 @@ func TestACLCheckResourceResolutionStatus(t *testing.T) {}func TestACLCheckAuthenticatesBeforeResolvingResources(t *testing.T) {+ t.Parallel()ctx, stores, _, _, _, _ := setupWorkspaceInstanceDescendantServiceTest(t)interceptor := NewACLInterceptor(stores, "", nil, nil)@@ -69,6 +72,7 @@ func TestACLCheckAuthenticatesBeforeResolvingResources(t *testing.T) {}func TestACLCheckPanicPreventsRequestAdmission(t *testing.T) {+ t.Parallel()ctx := authenticatedACLContext(context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default"))interceptor := NewACLInterceptor(nil, "", nil, nil)aclCheckReturnedNil := false@@ -102,6 +106,7 @@ func unauthenticatedACLContext(ctx context.Context) context.Context {}func TestGetResourceRoute(t *testing.T) {+ t.Parallel()tests := []struct {name stringparts []string@@ -186,12 +191,14 @@ func TestGetResourceRoute(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {+ t.Parallel()require.Equal(t, tt.want, getResourceRoute(tt.parts))})}}func TestFindResourceResolver(t *testing.T) {+ t.Parallel()tests := []struct {name stringroute resourceRoute@@ -218,6 +225,7 @@ func TestFindResourceResolver(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {+ t.Parallel()gotRoute, resolver, gotExists := findResourceResolver(tt.route)require.Equal(t, tt.wantExists, gotExists)if !tt.wantExists {@@ -265,6 +273,7 @@ func TestResolveRawResource(t *testing.T) {}func TestResolveRawResourceWorkspaceDatabaseUsesDatabaseProject(t *testing.T) {+ t.Parallel()ctx, stores, instanceID, databaseName, _, _ := setupWorkspaceInstanceDescendantServiceTest(t)resource, err := resolveRawResource(ctx, stores, common.FormatDatabase(instanceID, databaseName)+"/revisions/1")require.NoError(t, err)@@ -272,6 +281,7 @@ func TestResolveRawResourceWorkspaceDatabaseUsesDatabaseProject(t *testing.T) {}func TestPopulateRawResourcesUsesWorkspaceFallback(t *testing.T) {+ t.Parallel()ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")for _, request := range []any{&v1pb.GetInstanceRequest{Name: "projects/-"},@@ -288,6 +298,7 @@ func TestPopulateRawResourcesUsesWorkspaceFallback(t *testing.T) {}func TestPopulateRawResourcesBatchSyncUsesDatabaseProject(t *testing.T) {+ t.Parallel()ctx, stores, instanceID, databaseName, _, _ := setupWorkspaceInstanceDescendantServiceTest(t)resources, err := populateRawResources(ctx,@@ -303,6 +314,7 @@ func TestPopulateRawResourcesBatchSyncUsesDatabaseProject(t *testing.T) {}func TestPopulateRawResourcesAllowsDeletedSampleProjectInstanceProject(t *testing.T) {+ t.Parallel()ctx, stores, projectID, _, _ := setupProjectInstanceLifecycleAPITest(t)workspaceID := common.GetWorkspaceIDFromContext(ctx)_, err := stores.GetDB().ExecContext(ctx, `@@ -323,6 +335,7 @@ func TestPopulateRawResourcesAllowsDeletedSampleProjectInstanceProject(t *testin}func TestGetResourceFromRequest(t *testing.T) {+ t.Parallel()tests := []struct {request anymethod string@@ -679,6 +692,7 @@ func TestGetResourceFromRequest(t *testing.T) {}func TestToSnakeCase(t *testing.T) {+ t.Parallel()tests := []struct {input stringwant string@@ -708,6 +722,7 @@ func TestToSnakeCase(t *testing.T) {}func TestGetPermissionForRequest(t *testing.T) {+ t.Parallel()tests := []struct {name stringrequest any@@ -741,6 +756,7 @@ func TestGetPermissionForRequest(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {+ t.Parallel()got := getPermissionForRequest(tt.request, tt.defaultPermission)require.Equal(t, tt.want, got)})@@ -748,6 +764,7 @@ func TestGetPermissionForRequest(t *testing.T) {}func TestHasAllowMissingEnabled(t *testing.T) {+ t.Parallel()tests := []struct {name stringrequest any@@ -821,6 +838,7 @@ func TestHasAllowMissingEnabled(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {+ t.Parallel()got := hasAllowMissingEnabled(tt.request)require.Equal(t, tt.want, got)})diff --git a/backend/api/v1/actuator_service_test.go b/backend/api/v1/actuator_service_test.goindex 230bcb8af9..1878cb47e4 100644--- a/backend/api/v1/actuator_service_test.go+++ b/backend/api/v1/actuator_service_test.go@@ -26,6 +26,7 @@ import ()func TestAuthenticationInfoAndActuatorBoundary(t *testing.T) {+ t.Parallel()ctx := context.Background()_, stores, pgURL := testcontainer.NewMetadataDB(t)diff --git a/backend/api/v1/audit_log_converter_test.go b/backend/api/v1/audit_log_converter_test.goindex 6810d596c8..1900b6050a 100644--- a/backend/api/v1/audit_log_converter_test.go+++ b/backend/api/v1/audit_log_converter_test.go@@ -13,6 +13,7 @@ import (// The resource name is built from the payload's parent, not the row's// workspace. Split out of the retention test that moved to backend/store.func TestConvertToAuditLogsNamesRowsByPayloadParent(t *testing.T) {+ t.Parallel()logs := convertToAuditLogs([]*store.AuditLog{{ResourceID: "after-cutoff", CreatedAt: time.Unix(2, 0), Payload: &storepb.AuditLog{Parent: "projects/project-a"}},{ResourceID: "at-cutoff", CreatedAt: time.Unix(1, 0), Payload: &storepb.AuditLog{Parent: "projects/project-a"}},diff --git a/backend/api/v1/audit_mcp_provenance_test.go b/backend/api/v1/audit_mcp_provenance_test.goindex 58dbf69950..e47de77947 100644--- a/backend/api/v1/audit_mcp_provenance_test.go+++ b/backend/api/v1/audit_mcp_provenance_test.go@@ -154,6 +154,7 @@ func TestAuditRowCarriesMCPDelegationProvenance(t *testing.T) {// dedup, a single denied batch call naming N items would write N identical// rows.func TestAuditParentsDeduplicated(t *testing.T) {+ t.Parallel()st := newAuditLiveStore(t)in := NewAuditInterceptor(st, "test-secret", &config.Profile{})diff --git a/backend/api/v1/audit_redact_inventory_test.go b/backend/api/v1/audit_redact_inventory_test.goindex 75c4a814e4..1e1ea30d39 100644--- a/backend/api/v1/audit_redact_inventory_test.go+++ b/backend/api/v1/audit_redact_inventory_test.go@@ -48,6 +48,7 @@ import (// leaves the audited surface without anyone deciding what the audit row may// record for it.func TestLintAuditPayloadInventory(t *testing.T) {+ t.Parallel()found := auditRecordedScalarFields(t)recorded := map[string]bool{}@@ -1090,6 +1091,7 @@ var auditRecordedFields = []string{// caller_supplied_user_agent is caller-controlled and the likeliest candidate —// and this fails, because nothing would redact it.func TestAuditRowNeedsNoRedactionBeyondTheAnyPayloads(t *testing.T) {+ t.Parallel()for _, message := range []proto.Message{&storepb.RequestMetadata{}, &storepb.MCPDelegation{}} {descriptor := message.ProtoReflect().Descriptor()require.Nil(t, planFor(descriptor),@@ -1116,6 +1118,7 @@ func TestAuditRowNeedsNoRedactionBeyondTheAnyPayloads(t *testing.T) {// Without it a new Any field would be governed by nothing: the runtime drops// what it cannot place, so the payload would vanish silently.func TestLintAuditAnyFieldsAreRegistered(t *testing.T) {+ t.Parallel()found := auditReachableAnyFields(t)var unregistered []stringdiff --git a/backend/api/v1/audit_redact_test.go b/backend/api/v1/audit_redact_test.goindex bfccc77c64..66a77843f7 100644--- a/backend/api/v1/audit_redact_test.go+++ b/backend/api/v1/audit_redact_test.go@@ -378,6 +378,7 @@ func TestAuditPlanHandlesCyclicDescriptors(t *testing.T) {// sits inside one today — exactly why either bug would go unnoticed until one// did.func TestAuditRedactionFollowsACycleToAnyDepth(t *testing.T) {+ t.Parallel()descriptor := cyclicSensitiveDescriptor(t)secret := descriptor.Fields().ByName("secret")child := descriptor.Fields().ByName("child")@@ -418,6 +419,7 @@ func TestAuditRedactionFollowsACycleToAnyDepth(t *testing.T) {// type with a plan today, so this violation of "redaction does not mutate the// caller's message" would otherwise go uncaught until one appeared.func TestAuditRedactionRebuildsMapsRatherThanSharing(t *testing.T) {+ t.Parallel()descriptor := mapOfSensitiveDescriptor(t)entryValue := dynamicpb.NewMessage(descriptor.Fields().ByName("entries").MapValue().Message())entryValue.Set(entryValue.Descriptor().Fields().ByName("secret"), protoreflect.ValueOfString(secretSentinel))@@ -444,6 +446,7 @@ func TestAuditRedactionRebuildsMapsRatherThanSharing(t *testing.T) {// app_role is a message that would survive as {}, so clearing would make token// auth indistinguishable from unconfigured while AppRole stayed legible.func TestAuditRedactionKeepsSensitiveOneofArmsPresent(t *testing.T) {+ t.Parallel()request := &v1pb.AddDataSourceRequest{DataSource: &v1pb.DataSource{ExternalSecret: &v1pb.DataSourceExternalSecret{Url: "https://vault.example.com",@@ -476,6 +479,7 @@ func TestAuditRedactionKeepsSensitiveOneofArmsPresent(t *testing.T) {// pointer, never copied. A 5 MB sheet inside an audited batch used to be cloned// only to have its content nulled.func TestAuditRedactionSharesUnannotatedSubtrees(t *testing.T) {+ t.Parallel()labels := map[string]string{"env": "prod"}instance := &v1pb.Instance{Name: "instances/instance-a",@@ -585,6 +589,7 @@ func TestAuditRedactsPackedAny(t *testing.T) {// persistence is exercised through the createAuditLogFunc stub, which bypasses// the real path; this one writes a real row and reads it back.func TestStreamingAuditRedactsRows(t *testing.T) {+ t.Parallel()st := newAuditLiveStore(t)t.Cleanup(func() { require.NoError(t, st.Close()) })interceptor := NewAuditInterceptor(st, "test-secret", &config.Profile{})@@ -628,6 +633,7 @@ func TestStreamingAuditRedactsRows(t *testing.T) {// instance at marshal time; it would be a hole if an annotation could ever sit// inside one.func TestNoAnnotationOutsideBytebaseProtos(t *testing.T) {+ t.Parallel()var annotated []stringprotoregistry.GlobalFiles.RangeFiles(func(fd protoreflect.FileDescriptor) bool {if strings.HasPrefix(string(fd.Package()), "bytebase.") {diff --git a/backend/api/v1/audit_test.go b/backend/api/v1/audit_test.goindex f7c1d23fa6..92b93c770a 100644--- a/backend/api/v1/audit_test.go+++ b/backend/api/v1/audit_test.go@@ -17,6 +17,7 @@ import ()func TestFailedLoginWithoutWorkspaceIsSkipped(t *testing.T) {+ t.Parallel()ctx := context.WithValue(context.Background(), common.AuthContextKey, &common.AuthContext{Audit: true})st := newAuditLiveStore(t)t.Cleanup(func() { require.NoError(t, st.Close()) })@@ -41,6 +42,7 @@ func TestFailedLoginWithoutWorkspaceIsSkipped(t *testing.T) {}func TestFailedLoginWithHandlerWorkspaceCreatesSingleAuditRow(t *testing.T) {+ t.Parallel()ctx := context.WithValue(context.Background(), common.AuthContextKey, &common.AuthContext{Audit: true})st := newAuditLiveStore(t)t.Cleanup(func() { require.NoError(t, st.Close()) })@@ -154,6 +156,7 @@ func (c *auditRecorderConn) Send(any) error {}func TestLifecycleAuditResource(t *testing.T) {+ t.Parallel()for _, test := range []struct {name stringrequest any@@ -211,6 +214,7 @@ func TestLifecycleAuditResource(t *testing.T) {{name: "prepare sample project instance", request: &v1pb.PrepareSampleProjectInstanceRequest{Parent: "projects/project-a"}, method: "/bytebase.v1.InstanceService/PrepareSampleProjectInstance", want: "projects/project-a"},} {t.Run(test.name, func(t *testing.T) {+ t.Parallel()require.Equal(t, test.want, getRequestResource(test.request, test.method))})}diff --git a/backend/api/v1/auth_service_lockout_test.go b/backend/api/v1/auth_service_lockout_test.goindex 8d896e9934..856516ea3f 100644--- a/backend/api/v1/auth_service_lockout_test.go+++ b/backend/api/v1/auth_service_lockout_test.go@@ -308,6 +308,7 @@ func TestMFALockoutClaims(t *testing.T) {}func TestSwitchWorkspaceMFAClaims(t *testing.T) {+ t.Parallel()ctx := context.Background()stores := newAuthTestStore(t)const secret = "test-secret"@@ -363,6 +364,7 @@ func TestSwitchWorkspaceMFAClaims(t *testing.T) {// bucket of LDAP user "[email protected]" on IDP "corpldap". ":" is legal in// neither alphabet, so an LDAP identity can never be a valid email.func TestLDAPLoginIdentity(t *testing.T) {+ t.Parallel()// The submitted username is kept verbatim: a case-exact directory// attribute can name two accounts differing only by case, and merging// them would let either lock — or clear — the other.@@ -373,6 +375,7 @@ func TestLDAPLoginIdentity(t *testing.T) {}func TestLDAPLockoutClaims(t *testing.T) {+ t.Parallel()ctx := context.Background()stores := newAuthTestStore(t)service := &AuthService{store: stores, secret: "test-secret", profile: &config.Profile{ExternalURL: "http://localhost"}}@@ -424,6 +427,7 @@ func TestLDAPLockoutClaims(t *testing.T) {// to the lockout window: a retention shorter than the window would delete// still-running locks, silently capping every lockout at the retention.func TestLoginAttemptRetentionOutlivesLockouts(t *testing.T) {+ t.Parallel()require.Greater(t, cleaner.LoginAttemptRetentionPeriod, loginAttemptWindow,"the hourly purge must never delete a still-running lock")}diff --git a/backend/api/v1/auth_service_test.go b/backend/api/v1/auth_service_test.goindex 73fe93d051..0bab06815a 100644--- a/backend/api/v1/auth_service_test.go+++ b/backend/api/v1/auth_service_test.go@@ -106,6 +106,7 @@ func TestLoginAnnouncesPreAuthenticationWorkspace(t *testing.T) {}func TestExtractDomain(t *testing.T) {+ t.Parallel()tests := []struct {domain stringwant string@@ -346,6 +347,7 @@ func TestLoginEnforcesWorkspaceDomains(t *testing.T) {// invisible to the raw-secret extraction the guard used to do (asserted below).// Recognizing only extractable claims would fail OPEN for every MCP session.func TestSwitchWorkspaceMCPRecognition(t *testing.T) {+ t.Parallel()const secret = "test-secret"delegated, err := auth.GenerateInternalMCPToken(auth.DelegatedMCPCredential{@@ -395,6 +397,7 @@ func mustLegacyOAuth2Token(t *testing.T, secret string) string {}func TestLoginAuthMethodRequiresPasswordReset(t *testing.T) {+ t.Parallel()emailCode := "123456"tests := []struct {name string@@ -420,6 +423,7 @@ func TestLoginAuthMethodRequiresPasswordReset(t *testing.T) {for _, test := range tests {t.Run(test.name, func(t *testing.T) {+ t.Parallel()got := loginAuthMethodFromRequest(test.request).requiresPasswordReset()require.Equal(t, test.want, got)})@@ -427,6 +431,7 @@ func TestLoginAuthMethodRequiresPasswordReset(t *testing.T) {}func TestMFATempTokenPreservesLoginAuthMethod(t *testing.T) {+ t.Parallel()const secret = "test-secret"tests := []struct {@@ -451,6 +456,7 @@ func TestMFATempTokenPreservesLoginAuthMethod(t *testing.T) {for _, test := range tests {t.Run(test.name, func(t *testing.T) {+ t.Parallel()token, err := auth.GenerateMFATempTokenWithLoginMethod("[email protected]", string(test.method), secret, time.Minute)require.NoError(t, err)@@ -464,6 +470,7 @@ func TestMFATempTokenPreservesLoginAuthMethod(t *testing.T) {}func TestLegacyMFATempTokenDefaultsToPasswordLoginAuthMethod(t *testing.T) {+ t.Parallel()const secret = "test-secret"token, err := auth.GenerateMFATempToken("[email protected]", secret, time.Minute)@@ -488,6 +495,7 @@ func TestLegacyMFATempTokenDefaultsToPasswordLoginAuthMethod(t *testing.T) {// return before generateLoginToken touches it, so a regression panics rather// than quietly minting a token.func TestSwitchWorkspaceInternalRefusesMCPCaller(t *testing.T) {+ t.Parallel()const secret = "test-secret"s := &AuthService{secret: secret}user := &store.UserMessage{Email: "[email protected]"}diff --git a/backend/api/v1/catalog_masking_cosmosdb_test.go b/backend/api/v1/catalog_masking_cosmosdb_test.goindex c0688c891e..b728b18cf6 100644--- a/backend/api/v1/catalog_masking_cosmosdb_test.go+++ b/backend/api/v1/catalog_masking_cosmosdb_test.go@@ -142,6 +142,7 @@ func maskCosmosDBDoc(t *testing.T, query string, inputJSON string, schema *store// ---------------------------------------------------------------------------func TestCosmosDBMaskingSelectTop(t *testing.T) {+ t.Parallel()// SELECT TOP N should mask sensitive fields just like regular SELECT.query := `SELECT TOP 10 c.name, c.email FROM c`input := `{"name":"Alice","email":"[email protected]"}`@@ -152,6 +153,7 @@ func TestCosmosDBMaskingSelectTop(t *testing.T) {}func TestCosmosDBMaskingSelectStar(t *testing.T) {+ t.Parallel()// SELECT * masks all fields based on schema.query := `SELECT * FROM c`input := `{"name":"Alice","email":"[email protected]","country":"US"}`@@ -162,6 +164,7 @@ func TestCosmosDBMaskingSelectStar(t *testing.T) {}func TestCosmosDBMaskingSelectTopStar(t *testing.T) {+ t.Parallel()// SELECT TOP N * masks like SELECT *.query := `SELECT TOP 5 * FROM c`input := `{"name":"Alice","email":"[email protected]"}`@@ -172,6 +175,7 @@ func TestCosmosDBMaskingSelectTopStar(t *testing.T) {}func TestCosmosDBMaskingFunctionsInSelect(t *testing.T) {+ t.Parallel()// Functions in SELECT produce computed values. The function result column// (aliased) shouldn't match any schema field, so it should pass through unmasked.// Direct field references should still be masked.@@ -184,6 +188,7 @@ func TestCosmosDBMaskingFunctionsInSelect(t *testing.T) {}func TestCosmosDBMaskingAggregation(t *testing.T) {+ t.Parallel()// Aggregation result: COUNT(1) AS totalRecords.// The result is a computed value, not a direct field reference.query := `SELECT COUNT(1) AS totalRecords FROM c`@@ -195,6 +200,7 @@ func TestCosmosDBMaskingAggregation(t *testing.T) {}func TestCosmosDBMaskingGroupBy(t *testing.T) {+ t.Parallel()// GROUP BY with aggregation. Direct field (country) + function result (cnt).query := `SELECT c.country, COUNT(1) AS cnt FROM c GROUP BY c.country`input := `{"country":"US","cnt":5}`@@ -205,6 +211,7 @@ func TestCosmosDBMaskingGroupBy(t *testing.T) {}func TestCosmosDBMaskingOrderBy(t *testing.T) {+ t.Parallel()// ORDER BY doesn't affect masking.query := `SELECT c.name, c.email FROM c ORDER BY c.name ASC`input := `{"name":"Alice","email":"[email protected]"}`@@ -215,6 +222,7 @@ func TestCosmosDBMaskingOrderBy(t *testing.T) {}func TestCosmosDBMaskingOffsetLimit(t *testing.T) {+ t.Parallel()// OFFSET LIMIT doesn't affect masking.query := `SELECT c.name, c.email FROM c ORDER BY c.name OFFSET 0 LIMIT 10`input := `{"name":"Alice","email":"[email protected]"}`@@ -225,6 +233,7 @@ func TestCosmosDBMaskingOffsetLimit(t *testing.T) {}func TestCosmosDBMaskingStringFunctions(t *testing.T) {+ t.Parallel()// String functions in SELECT: UPPER, LOWER, LENGTH.query := `SELECT UPPER(c.name) AS upperName, LOWER(c.country) AS lowerCountry, LENGTH(c.name) AS nameLen FROM c`input := `{"upperName":"ALICE","lowerCountry":"us","nameLen":5}`@@ -235,6 +244,7 @@ func TestCosmosDBMaskingStringFunctions(t *testing.T) {}func TestCosmosDBMaskingMathFunctions(t *testing.T) {+ t.Parallel()// Math functions in SELECT.query := `SELECT c.name, ROUND(c.score) AS roundedScore FROM c`input := `{"name":"Alice","roundedScore":95}`@@ -245,6 +255,7 @@ func TestCosmosDBMaskingMathFunctions(t *testing.T) {}func TestCosmosDBMaskingTypeCheckFunctions(t *testing.T) {+ t.Parallel()// Type-check functions in SELECT.query := `SELECT c.name, IS_STRING(c.name) AS isStr, IS_NUMBER(c.population) AS isNum FROM c`input := `{"name":"Alice","isStr":true,"isNum":true}`@@ -255,6 +266,7 @@ func TestCosmosDBMaskingTypeCheckFunctions(t *testing.T) {}func TestCosmosDBMaskingUnderscoreFields(t *testing.T) {+ t.Parallel()// Underscore-prefixed fields like _ts, _etag should work with the new IDENTIFIER rule.query := `SELECT c._ts, c._etag, c.name FROM c`input := `{"_ts":1743702439,"_etag":"abc123","name":"Alice"}`@@ -265,6 +277,7 @@ func TestCosmosDBMaskingUnderscoreFields(t *testing.T) {}func TestCosmosDBMaskingNestedFieldProjection(t *testing.T) {+ t.Parallel()// Projecting nested sensitive field.query := `SELECT c.name, c.contact.phone AS phone FROM c`input := `{"name":"Alice","phone":"123-456"}`@@ -275,6 +288,7 @@ func TestCosmosDBMaskingNestedFieldProjection(t *testing.T) {}func TestCosmosDBMaskingDistinctValue(t *testing.T) {+ t.Parallel()// SELECT DISTINCT VALUE returns scalar values, not objects.// The result is just a plain value like "US" instead of {"country":"US"}.// CosmosDB returns each value as a single-field JSON, but the masking@@ -288,6 +302,7 @@ func TestCosmosDBMaskingDistinctValue(t *testing.T) {}func TestCosmosDBMaskingDistinctValueSensitive(t *testing.T) {+ t.Parallel()// SELECT DISTINCT VALUE on a sensitive field.query := `SELECT DISTINCT VALUE c.email FROM c`input := `{"email":"[email protected]"}`@@ -298,6 +313,7 @@ func TestCosmosDBMaskingDistinctValueSensitive(t *testing.T) {}func TestCosmosDBMaskingGeospatial(t *testing.T) {+ t.Parallel()// Geospatial function with JSON object literal where source field IS sensitive.// ST_DISTANCE(c.location, ...) -- c.location is tagged with bb.default.// The distance result must be masked because it derives from sensitive location data.@@ -310,6 +326,7 @@ func TestCosmosDBMaskingGeospatial(t *testing.T) {}func TestCosmosDBMaskingValueSensitive(t *testing.T) {+ t.Parallel()// SELECT VALUE c.email returns scalar values from CosmosDB, not objects.// The driver returns each result as a raw JSON string (e.g., "\"[email protected]\"").// maskResults must handle non-object JSON values for VALUE queries.@@ -336,6 +353,7 @@ func TestCosmosDBMaskingValueSensitive(t *testing.T) {}func TestCosmosDBMaskingValueNonSensitive(t *testing.T) {+ t.Parallel()// SELECT VALUE c.name returns scalar values; c.name is not sensitive.schema := cosmosDBTestSchema()maskers := cosmosDBMaskers()@@ -359,6 +377,7 @@ func TestCosmosDBMaskingValueNonSensitive(t *testing.T) {}func TestCosmosDBMaskingValueCount(t *testing.T) {+ t.Parallel()// SELECT VALUE COUNT(1) returns a number. No source field, not masked.schema := cosmosDBTestSchema()maskers := cosmosDBMaskers()@@ -382,6 +401,7 @@ func TestCosmosDBMaskingValueCount(t *testing.T) {}func TestCosmosDBMaskingValueConcatSensitive(t *testing.T) {+ t.Parallel()// SELECT VALUE CONCAT(c.name, " <", c.email, ">") -- no alias, expression has sensitive c.email.// The expression has no output name, but source paths must still be tracked so// findMaskerForScalarValue can detect that c.email is sensitive and mask the result.@@ -407,6 +427,7 @@ func TestCosmosDBMaskingValueConcatSensitive(t *testing.T) {}func TestCosmosDBMaskingValueConcatNonSensitive(t *testing.T) {+ t.Parallel()// SELECT VALUE CONCAT(c.name, " - ", c.country) -- no alias, no sensitive fields.schema := cosmosDBTestSchema()maskers := cosmosDBMaskers()@@ -434,6 +455,7 @@ func TestCosmosDBMaskingValueConcatNonSensitive(t *testing.T) {// ---------------------------------------------------------------------------func TestCosmosDBMaskingArithmeticProjection(t *testing.T) {+ t.Parallel()// Arithmetic expression: c.population / 1000 AS popK.// Expression path is nil, alias "popK" not in schema, so not masked.query := `SELECT c.name, c.population / 1000 AS popK FROM c`@@ -445,6 +467,7 @@ func TestCosmosDBMaskingArithmeticProjection(t *testing.T) {}func TestCosmosDBMaskingStringConcatProjection(t *testing.T) {+ t.Parallel()// String concatenation of non-sensitive fields: c.name || " - " || c.country AS label.// Source fields (name, country) are not sensitive, so result is not masked.query := `SELECT c.name || " - " || c.country AS label FROM c`@@ -456,6 +479,7 @@ func TestCosmosDBMaskingStringConcatProjection(t *testing.T) {}func TestCosmosDBMaskingStringConcatWithSensitiveField(t *testing.T) {+ t.Parallel()// String concatenation that includes a sensitive field.// c.name || " - " || c.email AS label -- c.email is sensitive.// Result must be masked because it derives from sensitive data.@@ -468,6 +492,7 @@ func TestCosmosDBMaskingStringConcatWithSensitiveField(t *testing.T) {}func TestCosmosDBMaskingNestedFunctionProjection(t *testing.T) {+ t.Parallel()// Nested function calls: ROUND(StringToNumber(c.population)).// Expression path is nil, computed value not masked.query := `SELECT c.name, ROUND(StringToNumber(c.population)) AS rounded FROM c`@@ -479,6 +504,7 @@ func TestCosmosDBMaskingNestedFunctionProjection(t *testing.T) {}func TestCosmosDBMaskingArithmeticOnFunctionProjection(t *testing.T) {+ t.Parallel()// Arithmetic on function result: StringToNumber(c.population) / 1000.// Expression path is nil, alias not in schema, not masked.query := `SELECT CONCAT(c.name, " - ", c.country) AS label, StringToNumber(c.population) / 1000 AS populationInThousands FROM c`@@ -490,6 +516,7 @@ func TestCosmosDBMaskingArithmeticOnFunctionProjection(t *testing.T) {}func TestCosmosDBMaskingExprWithSensitiveFieldAlias(t *testing.T) {+ t.Parallel()// Expression alias matches a sensitive schema field name.// UPPER(c.name) AS email -- source field c.name is NOT sensitive.// Even though alias "email" is sensitive in the schema, the masking@@ -504,6 +531,7 @@ func TestCosmosDBMaskingExprWithSensitiveFieldAlias(t *testing.T) {}func TestCosmosDBMaskingExprMixedWithDirectFields(t *testing.T) {+ t.Parallel()// Mix of direct field references and expressions.// Direct sensitive field (email) should be masked.// Expression results from non-sensitive fields (upperName, popK) should not be masked.@@ -516,6 +544,7 @@ func TestCosmosDBMaskingExprMixedWithDirectFields(t *testing.T) {}func TestCosmosDBMaskingExprOnSensitiveFieldNonMatchingAlias(t *testing.T) {+ t.Parallel()// Function wrapping a sensitive field with a non-matching alias.// UPPER(c.email) AS upperEmail -- c.email IS sensitive.// The result must be masked because it derives from sensitive data,@@ -529,6 +558,7 @@ func TestCosmosDBMaskingExprOnSensitiveFieldNonMatchingAlias(t *testing.T) {}func TestCosmosDBMaskingConcatWithSensitiveArg(t *testing.T) {+ t.Parallel()// CONCAT with a sensitive field argument.// CONCAT(c.name, " <", c.email, ">") AS display -- c.email is sensitive.// Result must be masked because it contains sensitive data.@@ -545,6 +575,7 @@ func TestCosmosDBMaskingConcatWithSensitiveArg(t *testing.T) {// ---------------------------------------------------------------------------func TestCosmosDBPredicateNotEqual(t *testing.T) {+ t.Parallel()// WHERE with != on a sensitive field should be detected.query := `SELECT * FROM c WHERE c.email != "[email protected]"`span := getCosmosDBQuerySpan(t, query)@@ -558,6 +589,7 @@ func TestCosmosDBPredicateNotEqual(t *testing.T) {}func TestCosmosDBPredicateIn(t *testing.T) {+ t.Parallel()// WHERE with IN on a sensitive field should be detected.query := `SELECT * FROM c WHERE c.email IN ("[email protected]", "[email protected]")`span := getCosmosDBQuerySpan(t, query)@@ -571,6 +603,7 @@ func TestCosmosDBPredicateIn(t *testing.T) {}func TestCosmosDBPredicateBetween(t *testing.T) {+ t.Parallel()// WHERE with BETWEEN on a non-sensitive field should NOT be blocked.query := `SELECT * FROM c WHERE c.age BETWEEN 18 AND 65`span := getCosmosDBQuerySpan(t, query)@@ -584,6 +617,7 @@ func TestCosmosDBPredicateBetween(t *testing.T) {}func TestCosmosDBPredicateInNonSensitive(t *testing.T) {+ t.Parallel()// WHERE with IN on a non-sensitive field should NOT be blocked.query := `SELECT * FROM c WHERE c.country IN ("US", "UK", "CA")`span := getCosmosDBQuerySpan(t, query)@@ -597,6 +631,7 @@ func TestCosmosDBPredicateInNonSensitive(t *testing.T) {}func TestCosmosDBPredicateNotEqualNonSensitive(t *testing.T) {+ t.Parallel()// WHERE with != on a non-sensitive field should NOT be blocked.query := `SELECT * FROM c WHERE c.status != "inactive"`span := getCosmosDBQuerySpan(t, query)@@ -610,6 +645,7 @@ func TestCosmosDBPredicateNotEqualNonSensitive(t *testing.T) {}func TestCosmosDBPredicateNestedSensitive(t *testing.T) {+ t.Parallel()// WHERE with nested sensitive field c.contact.phone.query := `SELECT * FROM c WHERE c.contact.phone = "123-456"`span := getCosmosDBQuerySpan(t, query)@@ -623,6 +659,7 @@ func TestCosmosDBPredicateNestedSensitive(t *testing.T) {}func TestCosmosDBPredicateFunctionInWhere(t *testing.T) {+ t.Parallel()// Function used in WHERE clause should extract fields from arguments.query := `SELECT * FROM c WHERE CONTAINS(c.email, "example")`span := getCosmosDBQuerySpan(t, query)@@ -636,6 +673,7 @@ func TestCosmosDBPredicateFunctionInWhere(t *testing.T) {}func TestCosmosDBPredicateCompoundWhere(t *testing.T) {+ t.Parallel()// Compound WHERE with multiple operators including new ones.query := `SELECT * FROM c WHERE c.country != "US" AND c._ts > 1743702439`span := getCosmosDBQuerySpan(t, query)diff --git a/backend/api/v1/catalog_masking_elasticsearch_test.go b/backend/api/v1/catalog_masking_elasticsearch_test.goindex 120f193b1c..472b0ac217 100644--- a/backend/api/v1/catalog_masking_elasticsearch_test.go+++ b/backend/api/v1/catalog_masking_elasticsearch_test.go@@ -126,12 +126,14 @@ func TestLookupSemanticTypeByDotPath(t *testing.T) {}func TestMaskElasticsearchHitsColumn(t *testing.T) {+ t.Parallel()td := loadElasticsearchTestData(t)schema := testElasticsearchObjectSchema()maskers := testElasticsearchMaskerMap()for _, tc := range td.MaskHitsColumn {t.Run(tc.Description, func(t *testing.T) {+ t.Parallel()result, err := maskElasticsearchHitsColumn(tc.Input, tc.SortFields, schema, maskers)require.NoError(t, err)requireJSONEqual(t, tc.Want, result)@@ -140,12 +142,14 @@ func TestMaskElasticsearchHitsColumn(t *testing.T) {}func TestMaskElasticsearchDocSource(t *testing.T) {+ t.Parallel()td := loadElasticsearchTestData(t)schema := testElasticsearchObjectSchema()maskers := testElasticsearchMaskerMap()for _, tc := range td.MaskDocSource {t.Run(tc.Description, func(t *testing.T) {+ t.Parallel()result, err := maskDocumentString(tc.Input, schema, maskers)require.NoError(t, err)requireJSONEqual(t, tc.Want, result)@@ -154,12 +158,14 @@ func TestMaskElasticsearchDocSource(t *testing.T) {}func TestMaskElasticsearchGetSourceColumn(t *testing.T) {+ t.Parallel()td := loadElasticsearchTestData(t)schema := testElasticsearchObjectSchema()maskers := testElasticsearchMaskerMap()for _, tc := range td.MaskGetSourceColumn {t.Run(tc.Description, func(t *testing.T) {+ t.Parallel()result, err := maskElasticsearchGetSourceColumn(tc.FieldName, tc.Input, schema, maskers)require.NoError(t, err)requireJSONEqual(t, tc.Want, result)@@ -168,12 +174,14 @@ func TestMaskElasticsearchGetSourceColumn(t *testing.T) {}func TestMaskElasticsearchMGetSource(t *testing.T) {+ t.Parallel()td := loadElasticsearchTestData(t)schema := testElasticsearchObjectSchema()maskers := testElasticsearchMaskerMap()for _, tc := range td.MaskMGetSource {t.Run(tc.Description, func(t *testing.T) {+ t.Parallel()result, err := maskElasticsearchMGetSource(tc.Input, schema, maskers)require.NoError(t, err)requireJSONEqual(t, tc.Want, result)@@ -182,12 +190,14 @@ func TestMaskElasticsearchMGetSource(t *testing.T) {}func TestMaskElasticsearchInnerHits(t *testing.T) {+ t.Parallel()td := loadElasticsearchTestData(t)schema := testElasticsearchObjectSchema()maskers := testElasticsearchMaskerMap()for _, tc := range td.MaskInnerHits {t.Run(tc.Description, func(t *testing.T) {+ t.Parallel()result, err := maskElasticsearchHitsColumn(tc.Input, tc.SortFields, schema, maskers)require.NoError(t, err)requireJSONEqual(t, tc.Want, result)@@ -196,12 +206,14 @@ func TestMaskElasticsearchInnerHits(t *testing.T) {}func TestMaskElasticsearchMSearchResponses(t *testing.T) {+ t.Parallel()td := loadElasticsearchTestData(t)schema := testElasticsearchObjectSchema()maskers := testElasticsearchMaskerMap()for _, tc := range td.MaskMSearchResponses {t.Run(tc.Description, func(t *testing.T) {+ t.Parallel()result, err := maskElasticsearchMSearchResponses(tc.Input, tc.SortFields, schema, maskers)require.NoError(t, err)requireJSONEqual(t, tc.Want, result)@@ -210,6 +222,7 @@ func TestMaskElasticsearchMSearchResponses(t *testing.T) {}func TestMaskElasticsearchSourceObjectDirectReplacement(t *testing.T) {+ t.Parallel()maskers := map[string]masker.Masker{"bb.default": masker.NewDefaultFullMasker(),}@@ -283,6 +296,7 @@ func TestMaskElasticsearchSourceObjectDirectReplacement(t *testing.T) {for _, tc := range tests {t.Run(tc.description, func(t *testing.T) {+ t.Parallel()masked, err := walkAndMaskJSONRecursive(tc.input, tc.schema, maskers)require.NoError(t, err)got, ok := masked.(map[string]any)@@ -293,10 +307,12 @@ func TestMaskElasticsearchSourceObjectDirectReplacement(t *testing.T) {}func TestCheckElasticsearchRequestBlocked(t *testing.T) {+ t.Parallel()td := loadElasticsearchTestData(t)for _, tc := range td.CheckBlocked {t.Run(tc.Description, func(t *testing.T) {+ t.Parallel()analysis := &esparser.RequestAnalysis{API: tc.API,Index: tc.Index,diff --git a/backend/api/v1/catalog_masking_mongodb_test.go b/backend/api/v1/catalog_masking_mongodb_test.goindex 940b7d97a1..a018bd4c5d 100644--- a/backend/api/v1/catalog_masking_mongodb_test.go+++ b/backend/api/v1/catalog_masking_mongodb_test.go@@ -260,6 +260,7 @@ func mustMaskableAPI(t *testing.T, api string) mongoparser.MaskableAPI {}func TestMaskMongoDBDocumentString(t *testing.T) {+ t.Parallel()td := loadMongoDBMaskingTestData(t)maskers := map[string]masker.Masker{"bb.default": masker.NewDefaultFullMasker(),@@ -267,6 +268,7 @@ func TestMaskMongoDBDocumentString(t *testing.T) {for _, tc := range td.MaskDocument {t.Run(tc.Description, func(t *testing.T) {+ t.Parallel()schema := mustMongoSchema(t, tc.Schema)got, err := maskDocumentString(tc.Input, schema, maskers)require.NoError(t, err)@@ -276,10 +278,12 @@ func TestMaskMongoDBDocumentString(t *testing.T) {}func TestCheckMongoDBRequestBlocked(t *testing.T) {+ t.Parallel()td := loadMongoDBMaskingTestData(t)for _, tc := range td.CheckBlocked {t.Run(tc.Description, func(t *testing.T) {+ t.Parallel()var analysis *mongoparser.MaskingAnalysisif !tc.AnalysisNil {analysis = &mongoparser.MaskingAnalysis{diff --git a/backend/api/v1/catalog_masking_test.go b/backend/api/v1/catalog_masking_test.goindex 852e088a62..4a85f0acd8 100644--- a/backend/api/v1/catalog_masking_test.go+++ b/backend/api/v1/catalog_masking_test.go@@ -12,6 +12,7 @@ import ()func TestGetFirstSemanticTypeInPath(t *testing.T) {+ t.Parallel()containerName := "container"containerNode := base.NewItemSelector(containerName)@@ -135,6 +136,7 @@ func TestGetFirstSemanticTypeInPath(t *testing.T) {}func TestWalkAndMaskJSON(t *testing.T) {+ t.Parallel()innerMasker, err := masker.NewInnerOuterMasker(storepb.Algorithm_InnerOuterMask_INNER, 1, 1, "*")require.NoError(t, err)@@ -468,6 +470,7 @@ func TestWalkAndMaskJSON(t *testing.T) {}func TestWalkAndMaskJSONRecursiveSemanticTypeMasksJSONContainerAsString(t *testing.T) {+ t.Parallel()innerMasker, err := masker.NewInnerOuterMasker(storepb.Algorithm_InnerOuterMask_INNER, 1, 1, "*")require.NoError(t, err)diff --git a/backend/api/v1/common_test.go b/backend/api/v1/common_test.goindex 9b97d1cce0..5105c437e6 100644--- a/backend/api/v1/common_test.go+++ b/backend/api/v1/common_test.go@@ -9,6 +9,7 @@ import ()func TestIsValidResourceID(t *testing.T) {+ t.Parallel()tests := []struct {resourceID stringwant bool@@ -42,6 +43,7 @@ func TestIsValidResourceID(t *testing.T) {}func TestParseFilter(t *testing.T) {+ t.Parallel()testCases := []struct {input stringwant []Expression@@ -91,6 +93,7 @@ func TestParseFilter(t *testing.T) {}func TestIsValidateOnlyRequest(t *testing.T) {+ t.Parallel()tests := []struct {name stringrequest any@@ -152,6 +155,7 @@ func TestIsValidateOnlyRequest(t *testing.T) {for _, test := range tests {t.Run(test.name, func(t *testing.T) {+ t.Parallel()got := isValidateOnlyRequest(test.request)require.Equal(t, test.want, got)})diff --git a/backend/api/v1/database_catalog_service_test.go b/backend/api/v1/database_catalog_service_test.goindex b0f77a1901..b83a73f37a 100644--- a/backend/api/v1/database_catalog_service_test.go+++ b/backend/api/v1/database_catalog_service_test.go@@ -9,6 +9,7 @@ import ()func TestValidateCatalogSchemaNames(t *testing.T) {+ t.Parallel()tests := []struct {name stringconfig *storepb.DatabaseConfig@@ -61,6 +62,7 @@ func TestValidateCatalogSchemaNames(t *testing.T) {for _, tc := range tests {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()err := validateCatalogSchemaNames(tc.config, tc.metadata)if tc.wantErr {require.Error(t, err)@@ -72,6 +74,7 @@ func TestValidateCatalogSchemaNames(t *testing.T) {}func TestValidateCatalogSemanticTypeIDs(t *testing.T) {+ t.Parallel()tests := []struct {name stringconfig *storepb.DatabaseConfig@@ -154,6 +157,7 @@ func TestValidateCatalogSemanticTypeIDs(t *testing.T) {for _, tc := range tests {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()err := validateCatalogSemanticTypeIDs(tc.config, tc.setting)if tc.wantErr != "" {require.EqualError(t, err, tc.wantErr)diff --git a/backend/api/v1/database_converter_test.go b/backend/api/v1/database_converter_test.goindex 73de62eaa4..785739a49d 100644--- a/backend/api/v1/database_converter_test.go+++ b/backend/api/v1/database_converter_test.go@@ -82,6 +82,7 @@ func TestConvertColumnMetadataSRIDInvisibleRoundTrip(t *testing.T) {// SRID/INVISIBLE fields must not be stripped by the v1->store conversion, so the diff shows// only the intended change and never a spurious spatial/visibility MODIFY.func TestDiffMetadataPreservesSRIDInvisible(t *testing.T) {+ t.Parallel()mkV1 := func(noteComment string) *v1pb.DatabaseMetadata {return &v1pb.DatabaseMetadata{Schemas: []*v1pb.SchemaMetadata{{diff --git a/backend/api/v1/database_service_test.go b/backend/api/v1/database_service_test.goindex 23bd82644e..f4a4bb782f 100644--- a/backend/api/v1/database_service_test.go+++ b/backend/api/v1/database_service_test.go@@ -14,6 +14,7 @@ import ()func TestShouldDiffSchemaViaSDL(t *testing.T) {+ t.Parallel()tests := []struct {name stringengine storepb.Engine@@ -93,12 +94,14 @@ func TestShouldDiffSchemaViaSDL(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {+ t.Parallel()require.Equal(t, tt.want, shouldDiffSchemaViaSDL(tt.engine, tt.req))})}}func TestFormatDatabaseResourceName(t *testing.T) {+ t.Parallel()database := &store.DatabaseMessage{InstanceID: "instance-a", DatabaseName: "app"}require.Equal(t, "instances/instance-a/databases/app", formatDatabaseResourceName(&store.InstanceMessage{ResourceID: "instance-a"}, database))projectID := "project-a"@@ -109,6 +112,7 @@ func TestFormatDatabaseResourceName(t *testing.T) {}func TestListDatabaseFilter(t *testing.T) {+ t.Parallel()testCases := []struct {input stringwantSQL string@@ -181,6 +185,7 @@ func TestListDatabaseFilter(t *testing.T) {}func TestGetDatabaseMetadataFilter(t *testing.T) {+ t.Parallel()testCases := []struct {name stringinput string@@ -211,6 +216,7 @@ func TestGetDatabaseMetadataFilter(t *testing.T) {for _, tc := range testCases {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()filter, err := getDatabaseMetadataFilter(tc.input)if tc.errContains != "" {require.Error(t, err)@@ -233,6 +239,7 @@ func TestGetDatabaseMetadataFilter(t *testing.T) {}func TestGetDatabaseMetadataFilterRedactsSyntaxError(t *testing.T) {+ t.Parallel()_, err := getDatabaseMetadataFilter(`table == "sensitive SQL" &&`)require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))require.ErrorContains(t, err, "invalid filter expression")diff --git a/backend/api/v1/document_masking_test.go b/backend/api/v1/document_masking_test.goindex ffc0f3eb4f..1d7917d832 100644--- a/backend/api/v1/document_masking_test.go+++ b/backend/api/v1/document_masking_test.go@@ -17,6 +17,7 @@ import (// engine in both sets would take the document path and never be column-masked// there. Nothing else asserts this; the branch order alone decides it.func TestMaskersAreDisjoint(t *testing.T) {+ t.Parallel()values := storepb.Engine(0).Descriptor().Values()document := 0for i := range values.Len() {diff --git a/backend/api/v1/iam_policy_etag_test.go b/backend/api/v1/iam_policy_etag_test.goindex 3caa7bd911..76d2576b0b 100644--- a/backend/api/v1/iam_policy_etag_test.go+++ b/backend/api/v1/iam_policy_etag_test.go@@ -72,6 +72,7 @@ func TestRequestedIamPolicyEtag(t *testing.T) {// somewhere else would attribute a real permission change to the wrong// workspace, so the two have to agree.func TestWorkspaceResourceMatches(t *testing.T) {+ t.Parallel()testCases := []struct {name stringresource string@@ -86,6 +87,7 @@ func TestWorkspaceResourceMatches(t *testing.T) {for _, tc := range testCases {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()require.Equal(t, tc.want, workspaceResourceMatches(tc.resource, "ws-a"))})}diff --git a/backend/api/v1/instance_descendant_service_test.go b/backend/api/v1/instance_descendant_service_test.goindex 7355b44525..3fa70d6aa8 100644--- a/backend/api/v1/instance_descendant_service_test.go+++ b/backend/api/v1/instance_descendant_service_test.go@@ -16,6 +16,7 @@ import ()func TestProjectInstanceDescendantServicesUseCanonicalNames(t *testing.T) {+ t.Parallel()ctx, stores, instanceID, databaseName, changelogID, revisionID := setupProjectInstanceDescendantServiceTest(t)projectID := "project-a"parent := common.FormatProjectDatabase(projectID, instanceID, databaseName)@@ -49,6 +50,7 @@ func TestProjectInstanceDescendantServicesUseCanonicalNames(t *testing.T) {}func TestProjectInstanceDescendantServicesRejectWrongScopeParents(t *testing.T) {+ t.Parallel()ctx, stores, instanceID, databaseName, changelogID, revisionID := setupProjectInstanceDescendantServiceTest(t)workspaceParent := common.FormatDatabase(instanceID, databaseName)wrongProjectID := "project-b"@@ -80,6 +82,7 @@ func TestProjectInstanceDescendantServicesRejectWrongScopeParents(t *testing.T)}func TestWorkspaceInstanceDescendantServicesKeepWorkspaceNames(t *testing.T) {+ t.Parallel()ctx, stores, instanceID, databaseName, changelogID, revisionID := setupWorkspaceInstanceDescendantServiceTest(t)parent := common.FormatDatabase(instanceID, databaseName)diff --git a/backend/api/v1/instance_service_converter_test.go b/backend/api/v1/instance_service_converter_test.goindex 3cec259f4b..2917c4961a 100644--- a/backend/api/v1/instance_service_converter_test.go+++ b/backend/api/v1/instance_service_converter_test.go@@ -17,6 +17,7 @@ import ()func TestConvertToV1InstanceUsesOwningProjectName(t *testing.T) {+ t.Parallel()projectID := "project-a"instance := &store.InstanceMessage{ResourceID: "instance-a",@@ -35,6 +36,7 @@ func TestConvertToV1InstanceUsesOwningProjectName(t *testing.T) {}func TestConvertDataSourceCloudSQLIPType(t *testing.T) {+ t.Parallel()tests := []struct {name stringv1 v1pb.DataSource_CloudSQLIPType@@ -47,6 +49,7 @@ func TestConvertDataSourceCloudSQLIPType(t *testing.T) {}for _, tc := range tests {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()// v1 -> storestoreDS, err := convertV1DataSource(&v1pb.DataSource{Type: v1pb.DataSourceType_ADMIN,@@ -65,6 +68,7 @@ func TestConvertDataSourceCloudSQLIPType(t *testing.T) {}func TestNormalizeGCPDataSources(t *testing.T) {+ t.Parallel()tests := []struct {name stringengine storepb.Engine@@ -127,6 +131,7 @@ func TestNormalizeGCPDataSources(t *testing.T) {}for _, tc := range tests {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()normalizeGCPDataSources(tc.engine, []*storepb.DataSource{tc.in})require.Equal(t, tc.wantProjectID, tc.in.GetProjectId())require.Equal(t, tc.wantInstanceID, tc.in.GetInstanceId())@@ -136,6 +141,7 @@ func TestNormalizeGCPDataSources(t *testing.T) {}func TestConvertDataSourceGCPFields(t *testing.T) {+ t.Parallel()storeDS, err := convertV1DataSource(&v1pb.DataSource{Type: v1pb.DataSourceType_ADMIN,ProjectId: "my-proj",@@ -156,6 +162,7 @@ func TestConvertDataSourceGCPFields(t *testing.T) {}func TestConvertDataSourceSaslConfigNeverReturnsKeytab(t *testing.T) {+ t.Parallel()got := convertDataSourceSaslConfig(&storepb.SASLConfig{Mechanism: &storepb.SASLConfig_KrbConfig{KrbConfig: &storepb.KerberosConfig{@@ -203,6 +210,7 @@ func krbDataSource(id, host, keytab string) *storepb.DataSource {}func TestRetainStoredKeytabOnEmptyUpdate(t *testing.T) {+ t.Parallel()const storedHost = "hive.internal.example.com"stored := krbDataSource("admin", storedHost, "stored-keytab")@@ -325,6 +333,7 @@ func TestRetainStoredKeytabRefusesANewDestination(t *testing.T) {// field is named in one list or the other, which is the point: the choice gets// made by whoever adds it rather than defaulted.func TestDataSourceDestinationClassifiesEveryField(t *testing.T) {+ t.Parallel()// Fields the caller supplies an address through. Keep in step with// dataSourceDestination.inDestination := []string{@@ -409,6 +418,7 @@ func TestDataSourceDestinationClassifiesEveryField(t *testing.T) {}func TestRetainStoredKeytabs(t *testing.T) {+ t.Parallel()const storedHost = "hive.internal.example.com"stored := []*storepb.DataSource{krbDataSource("admin", storedHost, "admin-keytab"),@@ -510,6 +520,7 @@ func isInputOnly(field protoreflect.FieldDescriptor) bool {// audit-side leak this design opens with was the request path, and the read// path staying clean is what lets the annotation be SENSITIVE rather than OMIT.func TestConvertInstanceRolesBlanksEveryWriteOnlyField(t *testing.T) {+ t.Parallel()instance := &store.InstanceMessage{ResourceID: "instance-a"}roles := []*storepb.InstanceRole{{Name: "admin", Attribute: proto.String("SUPERUSER"), ConnectionLimit: proto.Int32(10)},@@ -524,6 +535,7 @@ func TestConvertInstanceRolesBlanksEveryWriteOnlyField(t *testing.T) {}func TestConvertDataSourcesBlanksEveryWriteOnlyField(t *testing.T) {+ t.Parallel()// One store data source per authentication/secret shape, each with every// secret populated, so the INPUT_ONLY walk covers all converter branches.dataSources := []*storepb.DataSource{diff --git a/backend/api/v1/instance_service_test.go b/backend/api/v1/instance_service_test.goindex 270c4c6703..b36f56db21 100644--- a/backend/api/v1/instance_service_test.go+++ b/backend/api/v1/instance_service_test.go@@ -22,6 +22,7 @@ import ()func TestPrepareSampleProjectInstanceValidatesParentAndManager(t *testing.T) {+ t.Parallel()service := &InstanceService{}_, err := service.PrepareSampleProjectInstance(context.Background(), connect.NewRequest(&v1pb.PrepareSampleProjectInstanceRequest{}))require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))@@ -37,7 +38,9 @@ func TestPrepareSampleProjectInstanceValidatesParentAndManager(t *testing.T) {require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))}+//nolint:tparallel // Subtests share the parent's fixture.func TestPrepareSampleProjectInstanceUsesConfiguredManagerInBothDeployments(t *testing.T) {+ t.Parallel()ctx, stores, projectID, _, _ := setupProjectInstanceLifecycleAPITest(t)for _, saas := range []bool{false, true} {t.Run(fmt.Sprintf("saas=%t", saas), func(t *testing.T) {@@ -65,6 +68,7 @@ func TestPrepareSampleProjectInstanceUsesConfiguredManagerInBothDeployments(t *t}func TestPrepareSampleProjectInstanceChecksManagerAvailability(t *testing.T) {+ t.Parallel()ctx, stores, projectID, _, _ := setupProjectInstanceLifecycleAPITest(t)manager := &sampleManagerStub{checkAvailableErr: sample.NewFailure(sample.FailureUnavailable, errors.New("sample target unavailable")),@@ -84,6 +88,7 @@ func TestPrepareSampleProjectInstanceChecksManagerAvailability(t *testing.T) {}func TestSampleInstanceLifecycleHooksWrapMetadataUpdate(t *testing.T) {+ t.Parallel()ctx, stores, projectID, instanceID, _ := setupProjectInstanceLifecycleAPITest(t)_, err := stores.UpdateInstance(ctx, &store.UpdateInstanceMessage{ResourceID: &instanceID,@@ -126,6 +131,7 @@ func TestSampleInstanceLifecycleHooksWrapMetadataUpdate(t *testing.T) {}func TestPrepareSampleProjectInstanceRejectsConsumedEntitlementAfterProjectDeletion(t *testing.T) {+ t.Parallel()ctx, stores, projectID, _, _ := setupProjectInstanceLifecycleAPITest(t)workspaceID := common.GetWorkspaceIDFromContext(ctx)payload, err := protojson.Marshal(&storepb.SaaSSampleInstanceSetupPayload{@@ -162,11 +168,13 @@ func TestPrepareSampleProjectInstanceRejectsConsumedEntitlementAfterProjectDelet}func TestSampleProjectInstanceConnectErrorMapsUnknownFailure(t *testing.T) {+ t.Parallel()err := sampleProjectInstanceConnectError(errors.New("unexpected manager failure"))require.Equal(t, connect.CodeInternal, connect.CodeOf(err))}func TestSampleProjectInstanceCapacityGuardMapsCapacityDenial(t *testing.T) {+ t.Parallel()ctx, stores, projectID, _, _ := setupProjectInstanceLifecycleAPITest(t)for i := 0; i < 9; i++ {_, err := stores.CreateInstance(ctx, &store.InstanceMessage{@@ -189,6 +197,7 @@ func TestSampleProjectInstanceCapacityGuardMapsCapacityDenial(t *testing.T) {}func TestSampleProjectInstanceCapacityGuardDoesNotConsumeActivationQuota(t *testing.T) {+ t.Parallel()ctx, stores, _, _, _ := setupProjectInstanceLifecycleAPITest(t)service := &InstanceService{store: stores,@@ -366,6 +375,7 @@ func TestValidateIAMCredentialForSaaS(t *testing.T) {}func TestValidateExtraConnectionParametersRejectsTiDBAllowAllFiles(t *testing.T) {+ t.Parallel()err := validateExtraConnectionParameters(storepb.Engine_TIDB, map[string]string{"allowAllFiles": "true",})@@ -374,6 +384,7 @@ func TestValidateExtraConnectionParametersRejectsTiDBAllowAllFiles(t *testing.T)}func TestValidateProjectInstanceListFilter(t *testing.T) {+ t.Parallel()projectID := "project-a"tests := []struct {name string@@ -392,6 +403,7 @@ func TestValidateProjectInstanceListFilter(t *testing.T) {}for _, test := range tests {t.Run(test.name, func(t *testing.T) {+ t.Parallel()err := validateProjectInstanceListFilter(test.parent, test.filter)if test.wantErr {require.Error(t, err)@@ -403,6 +415,7 @@ func TestValidateProjectInstanceListFilter(t *testing.T) {}func TestClassifyConnectionFailure(t *testing.T) {+ t.Parallel()connectErr := connect.NewError(connect.CodeInvalidArgument, errors.New("generic connect error"))connectErr.Meta().Set(connectionCategoryHeader, connectionCategoryAuthFailed)var typedNilConnectErr *connect.Error@@ -429,6 +442,7 @@ func TestClassifyConnectionFailure(t *testing.T) {}func TestBuildInstanceConnectionLogAttrs(t *testing.T) {+ t.Parallel()instance := &store.InstanceMessage{Metadata: &storepb.Instance{Engine: storepb.Engine_POSTGRES,diff --git a/backend/api/v1/instance_service_tls_test.go b/backend/api/v1/instance_service_tls_test.goindex 6c0e33920b..01fa1c8ff3 100644--- a/backend/api/v1/instance_service_tls_test.go+++ b/backend/api/v1/instance_service_tls_test.go@@ -63,6 +63,7 @@ ZboOWVe3icTy64BT3OQhmg==-----END RSA PRIVATE KEY-----`func TestValidateAndSanitizeDataSourceTLSRejectsSameSlotMixedMaterial(t *testing.T) {+ t.Parallel()tests := []struct {name stringds *storepb.DataSource@@ -86,6 +87,7 @@ func TestValidateAndSanitizeDataSourceTLSRejectsSameSlotMixedMaterial(t *testing}for _, tc := range tests {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()err := validateAndSanitizeDataSourceTLS(tc.ds)require.Error(t, err)require.Contains(t, err.Error(), tc.want)@@ -94,6 +96,7 @@ func TestValidateAndSanitizeDataSourceTLSRejectsSameSlotMixedMaterial(t *testing}func TestValidateAndSanitizeDataSourceTLSRejectsMergedSameSlotMixedMaterial(t *testing.T) {+ t.Parallel()ds := &storepb.DataSource{UseSsl: true, SslCa: "inline-ca", SslCaPath: "/tmp/ca.pem"}err := validateAndSanitizeDataSourceTLS(ds)@@ -102,17 +105,20 @@ func TestValidateAndSanitizeDataSourceTLSRejectsMergedSameSlotMixedMaterial(t *t}func TestValidateAndSanitizeDataSourceTLSAllowsCrossSlotMixedMaterial(t *testing.T) {+ t.Parallel()err := validateAndSanitizeDataSourceTLS(&storepb.DataSource{UseSsl: true, SslCa: validCAPEM, SslCertPath: "/tmp/cert.pem", SslKeyPath: "/tmp/key.pem"})require.NoError(t, err)}func TestValidateAndSanitizeDataSourceTLSMatchesRuntimeCAPoolParsing(t *testing.T) {+ t.Parallel()caBundle := validKeyPEM + "\n" + validCAPEMerr := validateAndSanitizeDataSourceTLS(&storepb.DataSource{UseSsl: true, SslCa: caBundle})require.NoError(t, err)}func TestValidateAndSanitizeDataSourceTLSRejectsSourceSwitchWithoutClearingOldField(t *testing.T) {+ t.Parallel()ds := &storepb.DataSource{UseSsl: true, SslCa: validCAPEM, SslCaPath: "/tmp/ca.pem"}err := validateAndSanitizeDataSourceTLS(ds)@@ -122,6 +128,7 @@ func TestValidateAndSanitizeDataSourceTLSRejectsSourceSwitchWithoutClearingOldFi}func TestValidateAndSanitizeDataSourceTLSAllowsSourceSwitchWithExplicitOldFieldClear(t *testing.T) {+ t.Parallel()ds := &storepb.DataSource{UseSsl: true, SslCaPath: "/tmp/ca.pem"}err := validateAndSanitizeDataSourceTLS(ds)@@ -129,6 +136,7 @@ func TestValidateAndSanitizeDataSourceTLSAllowsSourceSwitchWithExplicitOldFieldC}func TestValidateAndSanitizeDataSourceTLSRejectsPathToInlineSwitchWithoutClearingOldField(t *testing.T) {+ t.Parallel()ds := &storepb.DataSource{UseSsl: true, SslCa: validCAPEM, SslCaPath: "/tmp/ca.pem"}err := validateAndSanitizeDataSourceTLS(ds)@@ -138,40 +146,47 @@ func TestValidateAndSanitizeDataSourceTLSRejectsPathToInlineSwitchWithoutClearin}func TestValidateAndSanitizeDataSourceTLSAllowsCertPathAndInlineKey(t *testing.T) {+ t.Parallel()err := validateAndSanitizeDataSourceTLS(&storepb.DataSource{UseSsl: true, SslCertPath: "/tmp/cert.pem", SslKey: validKeyPEM})require.NoError(t, err)}func TestValidateAndSanitizeDataSourceTLSAllowsCertInlineAndKeyPath(t *testing.T) {+ t.Parallel()err := validateAndSanitizeDataSourceTLS(&storepb.DataSource{UseSsl: true, SslCert: validCAPEM, SslKeyPath: "/tmp/key.pem"})require.NoError(t, err)}func TestValidateAndSanitizeDataSourceTLSMatchesRuntimeCertPEMScanning(t *testing.T) {+ t.Parallel()certBundle := validKeyPEM + "\n" + validCAPEMerr := validateAndSanitizeDataSourceTLS(&storepb.DataSource{UseSsl: true, SslCert: certBundle, SslKeyPath: "/tmp/key.pem"})require.NoError(t, err)}func TestValidateAndSanitizeDataSourceTLSRejectsMalformedInlineCertWithKeyPath(t *testing.T) {+ t.Parallel()err := validateAndSanitizeDataSourceTLS(&storepb.DataSource{UseSsl: true, SslCert: "not-a-cert", SslKeyPath: "/tmp/key.pem"})require.Error(t, err)require.Contains(t, err.Error(), "invalid ssl_cert PEM")}func TestValidateAndSanitizeDataSourceTLSRejectsMalformedInlineKeyWithCertPath(t *testing.T) {+ t.Parallel()err := validateAndSanitizeDataSourceTLS(&storepb.DataSource{UseSsl: true, SslCertPath: "/tmp/cert.pem", SslKey: "not-a-key"})require.Error(t, err)require.Contains(t, err.Error(), "invalid ssl_key PEM")}func TestValidateAndSanitizeDataSourceTLSMatchesRuntimeKeyPEMScanning(t *testing.T) {+ t.Parallel()keyBundle := validCAPEM + "\n" + validKeyPEMerr := validateAndSanitizeDataSourceTLS(&storepb.DataSource{UseSsl: true, SslCertPath: "/tmp/cert.pem", SslKey: keyBundle})require.NoError(t, err)}func TestValidateAndSanitizeDataSourceTLSAllowsEd25519PrivateKey(t *testing.T) {+ t.Parallel()keyPEM := generateEd25519KeyPEM(t)err := validateAndSanitizeDataSourceTLS(&storepb.DataSource{UseSsl: true, SslCertPath: "/tmp/cert.pem", SslKey: keyPEM})require.NoError(t, err)@@ -188,6 +203,7 @@ func generateEd25519KeyPEM(t *testing.T) string {}func TestValidateAndSanitizeDataSourceTLSRejectsRelativePath(t *testing.T) {+ t.Parallel()ds := &storepb.DataSource{UseSsl: true, SslCaPath: "ca.pem"}err := validateAndSanitizeDataSourceTLS(ds)@@ -196,6 +212,7 @@ func TestValidateAndSanitizeDataSourceTLSRejectsRelativePath(t *testing.T) {}func TestValidateAndSanitizeDataSourceTLSRejectsIncompleteCertPath(t *testing.T) {+ t.Parallel()ds := &storepb.DataSource{UseSsl: true, SslCertPath: "/tmp/cert.pem"}err := validateAndSanitizeDataSourceTLS(ds)@@ -204,6 +221,7 @@ func TestValidateAndSanitizeDataSourceTLSRejectsIncompleteCertPath(t *testing.T)}func TestValidateAndSanitizeDataSourceTLSAllowsValidPathOnlyCert(t *testing.T) {+ t.Parallel()ds := &storepb.DataSource{UseSsl: true, SslCertPath: "/tmp/cert.pem", SslKeyPath: "/tmp/key.pem"}err := validateAndSanitizeDataSourceTLS(ds)@@ -211,6 +229,7 @@ func TestValidateAndSanitizeDataSourceTLSAllowsValidPathOnlyCert(t *testing.T) {}func TestValidateAndSanitizeDataSourceTLSClearsAllWhenDisabled(t *testing.T) {+ t.Parallel()ds := &storepb.DataSource{UseSsl: false,SslCa: "inline-ca",diff --git a/backend/api/v1/interactive_project_database_test.go b/backend/api/v1/interactive_project_database_test.goindex 5af82936c9..78be1becbc 100644--- a/backend/api/v1/interactive_project_database_test.go+++ b/backend/api/v1/interactive_project_database_test.go@@ -18,6 +18,7 @@ import ()func TestBOT36SQLPrepareRelatedMessageRequiresCanonicalActiveOwner(t *testing.T) {+ t.Parallel()ctx, stores, projectID, instanceID, databaseName := setupBOT36ProjectDatabase(t)service := NewSQLService(stores, nil, nil, nil, nil, nil)@@ -42,6 +43,7 @@ func TestBOT36SQLPrepareRelatedMessageRequiresCanonicalActiveOwner(t *testing.T)}func TestBOT36SavedQueryDatabasesUseCanonicalOwningProjectNames(t *testing.T) {+ t.Parallel()ctx, stores, projectID, instanceID, databaseName := setupBOT36ProjectDatabase(t)service := NewSavedQueryService(stores, nil)@@ -70,6 +72,7 @@ func TestBOT36SavedQueryDatabasesUseCanonicalOwningProjectNames(t *testing.T) {}func TestUpdateSavedQueryKeepsDanglingDatabaseReference(t *testing.T) {+ t.Parallel()ctx, stores, projectID, _, _ := setupBOT36ProjectDatabase(t)service := NewSavedQueryService(stores, nil)@@ -110,6 +113,7 @@ func TestUpdateSavedQueryKeepsDanglingDatabaseReference(t *testing.T) {}func TestBOT36AccessGrantTargetsRequireCanonicalOwningProject(t *testing.T) {+ t.Parallel()ctx, stores, projectID, instanceID, databaseName := setupBOT36ProjectDatabase(t)service := NewAccessGrantService(stores, nil, nil, nil)diff --git a/backend/api/v1/issue_service_test.go b/backend/api/v1/issue_service_test.goindex 1683ff4703..e6e6cbb5ed 100644--- a/backend/api/v1/issue_service_test.go+++ b/backend/api/v1/issue_service_test.go@@ -27,6 +27,7 @@ import ()func TestUpdateIssueCommentRejectsEmptyComment(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -64,6 +65,7 @@ func TestUpdateIssueCommentRejectsEmptyComment(t *testing.T) {// and root comments: the v1 message cannot represent a reply, so a reply must// neither render as a top-level row nor consume a page slot.func TestListIssueCommentsExcludesReplies(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -108,6 +110,7 @@ func TestListIssueCommentsExcludesReplies(t *testing.T) {}func TestUpdateIssueLabelsResetsApprovalBeforeRollout(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -122,6 +125,7 @@ func TestUpdateIssueLabelsResetsApprovalBeforeRollout(t *testing.T) {}func TestUpdateIssueLabelsClearedBeforeRolloutResetsApproval(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -137,6 +141,7 @@ func TestUpdateIssueLabelsClearedBeforeRolloutResetsApproval(t *testing.T) {}func TestUpdateIssueLabelsDoesNotResetApprovalAfterRollout(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -162,6 +167,7 @@ func TestUpdateIssueLabelsDoesNotResetApprovalAfterRollout(t *testing.T) {}func TestMixedIssuePatchCommitsWithAuditComments(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -215,6 +221,7 @@ func TestMixedIssuePatchCommitsWithAuditComments(t *testing.T) {}func TestIssueMetadataNoopDoesNotCreateAuditComments(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -244,6 +251,7 @@ func TestIssueMetadataNoopDoesNotCreateAuditComments(t *testing.T) {}func TestApproveIssueFailsClosedWhenIAMLookupFails(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -268,6 +276,7 @@ func TestApproveIssueFailsClosedWhenIAMLookupFails(t *testing.T) {}func TestCreateRolloutAndPendingTasksAllowsUnapprovedIssueWhenApprovalNotRequired(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)plan, issue := createIssueServiceApprovalIssue(ctx, t, stores)@@ -305,6 +314,7 @@ func TestCreateRolloutAndPendingTasksAllowsUnapprovedIssueWhenApprovalNotRequire}func TestCreateRolloutAndPendingTasksClassifiesApprovalRaceAsStale(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)require.NoError(t, stores.UpdateProjects(ctx, &store.UpdateProjectMessage{@@ -337,6 +347,7 @@ func TestCreateRolloutAndPendingTasksClassifiesApprovalRaceAsStale(t *testing.T)}func TestCreateRolloutAndPendingTasksRejectsDraft(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)plan, issue := createIssueServiceApprovalIssue(ctx, t, stores)@@ -368,6 +379,7 @@ func TestCreateRolloutAndPendingTasksRejectsDraft(t *testing.T) {}func TestCreateRolloutAndPendingTasksRejectsPersistedDraftWithStaleIssueSnapshot(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)plan, issue := createIssueServiceApprovalIssue(ctx, t, stores)@@ -395,6 +407,7 @@ func TestCreateRolloutAndPendingTasksRejectsPersistedDraftWithStaleIssueSnapshot}func TestCreateDraftIssueRejectedAfterRollout(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -436,6 +449,7 @@ func TestCreateDraftIssueRejectedAfterRollout(t *testing.T) {}func TestUpdateIssueLabelsNoopDoesNotResetApproval(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -451,6 +465,7 @@ func TestUpdateIssueLabelsNoopDoesNotResetApproval(t *testing.T) {}func TestUpdateIssueLabelsDoesNotResetCreateDatabaseApproval(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -466,6 +481,7 @@ func TestUpdateIssueLabelsDoesNotResetCreateDatabaseApproval(t *testing.T) {}func TestUpdateIssueLabelsOnDraftPreservesApproval(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -488,6 +504,7 @@ func TestUpdateIssueLabelsOnDraftPreservesApproval(t *testing.T) {}func TestRetryIssueApprovalRejectsDraft(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -511,6 +528,7 @@ func TestRetryIssueApprovalRejectsDraft(t *testing.T) {}func TestDraftIssueApprovalActionsRejectedBeforeApprovalValidation(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)@@ -543,6 +561,7 @@ func TestDraftIssueApprovalActionsRejectedBeforeApprovalValidation(t *testing.T)for _, test := range tests {t.Run(test.name, func(t *testing.T) {+ t.Parallel()service := newIssueServiceForTest(t, stores)plan, err := stores.CreatePlan(ctx, &store.PlanMessage{ProjectID: "project-a",@@ -574,6 +593,7 @@ func TestDraftIssueApprovalActionsRejectedBeforeApprovalValidation(t *testing.T)}func TestStaleReviewRequestDispatchesNoPostCommitEffects(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -611,6 +631,7 @@ func TestStaleReviewRequestDispatchesNoPostCommitEffects(t *testing.T) {}func TestCreateDraftIssue(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -702,6 +723,7 @@ func TestCreateDraftIssue(t *testing.T) {}func TestCreateDraftIssueDoesNotExposeAnotherCreatorsDraft(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -753,6 +775,7 @@ func TestCreateDraftIssueDoesNotExposeAnotherCreatorsDraft(t *testing.T) {}func TestCreateSubmittedIssueBlockedByExistingDraft(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -814,6 +837,7 @@ func TestCreateSubmittedIssueBlockedByExistingDraft(t *testing.T) {}func TestCreateDraftIssueBlockedByExistingNonDraftIssue(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -975,6 +999,7 @@ func TestCreateDraftIssueRejectsUnsupportedWorkflows(t *testing.T) {// TestCreateIssueRejectsRetiredExportType pins the retired DATABASE_EXPORT// issue type: legacy clients still sending wire value 3 get InvalidArgument.func TestCreateIssueRejectsRetiredExportType(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -990,6 +1015,7 @@ func TestCreateIssueRejectsRetiredExportType(t *testing.T) {}func TestIssueListsHideDraftIssues(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)@@ -1270,6 +1296,7 @@ func issueApprover(status storepb.IssuePayloadApproval_Approver_Status) *storepb// filtering the default My Issues view answered with an empty page and a live// next page token underneath it.func TestIssueApprovalStatusFilterMatchesConverter(t *testing.T) {+ t.Parallel()ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)service := newIssueServiceForTest(t, stores)diff --git a/backend/api/v1/main_test.go b/backend/api/v1/main_test.goindex d23326da80..c06e292744 100644--- a/backend/api/v1/main_test.go+++ b/backend/api/v1/main_test.go@@ -6,4 +6,4 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer")-func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/api/v1/masking_evaluator_test.go b/backend/api/v1/masking_evaluator_test.goindex 1164772404..72a2a732c3 100644--- a/backend/api/v1/masking_evaluator_test.go+++ b/backend/api/v1/masking_evaluator_test.go@@ -12,6 +12,7 @@ import ()func TestEvalMaskingLevelOfColumn(t *testing.T) {+ t.Parallel()environment := "prod"defaultDatabaseMessage := &store.DatabaseMessage{EffectiveEnvironmentID: &environment,diff --git a/backend/api/v1/mcp_gate_test.go b/backend/api/v1/mcp_gate_test.goindex 6081f68677..af983f6855 100644--- a/backend/api/v1/mcp_gate_test.go+++ b/backend/api/v1/mcp_gate_test.go@@ -97,6 +97,7 @@ func forbiddenProceduresFromDescriptors(t *testing.T) map[string]v1pb.MCPDenialR// Membership is a security decision, so adding or removing one has to be// deliberate: this list is the second signature on that decision.func TestForbiddenClassMembership(t *testing.T) {+ t.Parallel()want := []string{v1connect.AuthServiceLoginProcedure,v1connect.AuthServiceSignupProcedure,@@ -349,10 +350,12 @@ func checkEveryClassHasAServingDecision(}func TestLintEveryMethodIsClassified(t *testing.T) {+ t.Parallel()require.Empty(t, checkEveryMethodIsClassified(mcpClassificationsFromDescriptors(t)))}func TestLintReasonsMatchTheClass(t *testing.T) {+ t.Parallel()require.Empty(t, checkReasonsMatchTheClass(mcpClassificationsFromDescriptors(t), mcpDenialReasons))}@@ -366,6 +369,7 @@ func mcpEnums(t *testing.T) (classes, modes protoreflect.EnumDescriptor) {}func TestLintEveryClassHasAServingDecision(t *testing.T) {+ t.Parallel()classes, modes := mcpEnums(t)require.Empty(t, checkEveryClassHasAServingDecision(mcpClassificationsFromDescriptors(t), mcpServingClasses, mcpDeniedClasses, classes, modes))@@ -379,6 +383,7 @@ func TestLintEveryClassHasAServingDecision(t *testing.T) {// serving a class cannot leave discovery hiding it — or the reverse, which is// the one that would offer an agent work it can never do.func TestLintRefusedClassesMatchTheServingTable(t *testing.T) {+ t.Parallel()served := map[v1pb.MCPMethodClass]bool{}for _, classes := range mcpServingClasses {for _, class := range classes {@@ -400,6 +405,7 @@ func TestLintRefusedClassesMatchTheServingTable(t *testing.T) {// that serves no class cannot start admitting sessions — or the reverse, which// would refuse a connection whose methods the gate is ready to serve.func TestLintCeilingAdmissionMatchesTheServingTable(t *testing.T) {+ t.Parallel()values := storepb.MCPSetting_Capability(0).Descriptor().Values()for i := range values.Len() {capability := storepb.MCPSetting_Capability(values.Get(i).Number())@@ -424,6 +430,7 @@ func TestLintCeilingAdmissionMatchesTheServingTable(t *testing.T) {// something else entirely, and every serving decision above would be about the// wrong vocabulary.func TestMCPCapabilityEnumsAgree(t *testing.T) {+ t.Parallel()v1Values := v1pb.MCPSetting_Capability(0).Descriptor().Values()storeValues := storepb.MCPSetting_Capability(0).Descriptor().Values()@@ -573,6 +580,7 @@ func TestLintClausesFireWhenBroken(t *testing.T) {// so forbidding it would cost an agent legitimate work while protecting nothing// an anonymous client could not already read.func TestForbiddenClassLeavesReadsAlone(t *testing.T) {+ t.Parallel()got := forbiddenProceduresFromDescriptors(t)for _, procedure := range []string{v1connect.IdentityProviderServiceGetIdentityProviderProcedure,@@ -631,6 +639,7 @@ func TestForbiddenClassLeavesReadsAlone(t *testing.T) {// of UpdateUser does not. UpdateUser is FORBIDDEN either way, so that// response is not a surface an agent reaches.func TestExcludedOnlyForALeak(t *testing.T) {+ t.Parallel()var got []stringfor _, row := range mcpClassificationsFromDescriptors(t) {if row.reason == v1pb.MCPDenialReason_RETURNS_A_STORED_SECRET {@@ -656,6 +665,7 @@ func TestExcludedOnlyForALeak(t *testing.T) {// regression coming back — an MCP session unable to name a project or an// instance, and so unable to reach a database at all.func TestTheLeakingReadsAreServed(t *testing.T) {+ t.Parallel()class := map[string]v1pb.MCPMethodClass{}for _, row := range mcpClassificationsFromDescriptors(t) {class[row.procedure] = row.class@@ -701,6 +711,7 @@ func TestTheLeakingReadsAreServed(t *testing.T) {// resolves them by operation ID. An alias classified more permissively than the// method it forwards to is a straight bypass of that method's classification.func TestDeprecatedSQLServiceAliasesMatchTheirCanonicalMethod(t *testing.T) {+ t.Parallel()class := map[string]v1pb.MCPMethodClass{}for _, row := range mcpClassificationsFromDescriptors(t) {class[row.procedure] = row.class@@ -777,6 +788,7 @@ func renderMCPInventory(rows []mcpClassification) string {// annotations. It fails on a stale file rather than regenerating silently, so a// classification change shows up in the diff a reviewer reads.func TestMCPClassificationInventory(t *testing.T) {+ t.Parallel()rendered := renderMCPInventory(mcpClassificationsFromDescriptors(t))if os.Getenv("MCP_INVENTORY") == "write" {require.NoError(t, os.WriteFile(mcpInventoryPath, []byte(rendered), 0o600))@@ -1004,6 +1016,7 @@ func TestMCPGateFailsClosedOnTheCeiling(t *testing.T) {// lint fails the build on one, and if a build ever ships past that, the method// is refused rather than served.func TestMCPGateFailsClosedOnAnUnclassifiedMethod(t *testing.T) {+ t.Parallel()got := invokeMCPGate(t, readWriteCeiling(), classContext(v1pb.MCPMethodClass_MCP_METHOD_CLASS_UNSPECIFIED),"/bytebase.v1.NewService/NewMethod", connect.NewRequest(&v1pb.GetUserRequest{}))require.Error(t, got.err)@@ -1041,6 +1054,7 @@ func TestMCPGateFallsBackToGenericWording(t *testing.T) {// TestMCPGateFailsClosedWithoutAnAuthContext pins that the gate does not guess.func TestMCPGateFailsClosedWithoutAnAuthContext(t *testing.T) {+ t.Parallel()got := invokeMCPGate(t, readWriteCeiling(), nil,v1connect.AuthServiceLoginProcedure, connect.NewRequest(&v1pb.LoginRequest{}))require.Error(t, got.err, "without a resolved classification the interceptor must not guess")@@ -1166,7 +1180,10 @@ func TestMCPGateRefusesGrantIssues(t *testing.T) {// rows are checked for what they wrote as well as that they wrote. The gate// refuses before dispatch, so nothing in them was ever used — recording one// verbatim would turn a silent denial into a worse one.+//+//nolint:tparallel // Subtests share the parent's fixture.func TestMCPGateDenialIsAuditedWithoutAnAuditAnnotation(t *testing.T) {+ t.Parallel()st := newAuditLiveStore(t)auditIn := NewAuditInterceptor(st, "test-secret", &config.Profile{})gate := NewInternalMCPGateInterceptor(readWriteCeiling())@@ -1511,6 +1528,7 @@ func mcpRequestFieldNeedsReview(field protoreflect.FieldDescriptor) bool {// message-typed fields the inventory's scalar scope does not — DiffMetadata's// target_metadata is a whole schema, and no string field names it.func TestLintDenialRequestsAreReviewedForRedaction(t *testing.T) {+ t.Parallel()needsReview := map[string][]string{}for _, row := range mcpClassificationsFromDescriptors(t) {if row.audit {diff --git a/backend/api/v1/mcp_masking_test.go b/backend/api/v1/mcp_masking_test.goindex eadbc979de..1e4844e38e 100644--- a/backend/api/v1/mcp_masking_test.go+++ b/backend/api/v1/mcp_masking_test.go@@ -183,6 +183,7 @@ func TestMaskedWriteGuardRefusesTheSentinel(t *testing.T) {// in this file rather than anything about the caller — and a refusal path that// meets a bug refuses.func TestMaskedWriteGuardFailsClosedOnAWiringBug(t *testing.T) {+ t.Parallel()forced := withMCPSettings(contextWithAuth(&common.AuthContext{DelegatedGrant: &common.DelegatedGrant{}}),maskingSettings(true))@@ -259,6 +260,7 @@ func TestMaskedWriteGuardIsWiredIntoTheGate(t *testing.T) {// it, and it authorizes DML per statement — under READ_WRITE an agent can// overwrite the column it just read masked without proposing anything.func TestMaskedWriteGuardCoversTheExecutionDoor(t *testing.T) {+ t.Parallel()masked := "UPDATE employee SET secret = '" + masker.DefaultFullMaskSubstitution + "' WHERE id = 1"got := invokeMCPGate(t,diff --git a/backend/api/v1/plan_service_test.go b/backend/api/v1/plan_service_test.goindex 597973cebb..da16c55788 100644--- a/backend/api/v1/plan_service_test.go+++ b/backend/api/v1/plan_service_test.go@@ -19,6 +19,7 @@ import ()func TestPlanServiceListPlansHidesMalformedUIPlans(t *testing.T) {+ t.Parallel()ctx := context.Background()stores := setupPlanServiceTestStore(ctx, t)service := NewPlanService(stores, nil, nil, nil, nil)@@ -133,6 +134,7 @@ func TestPlanServiceCreatePlanRecordsAuthenticatedPrincipalAsLastEditor(t *testi}func TestPlanServiceReleaseBackedPlanKeepsCreatorAsLastEditor(t *testing.T) {+ t.Parallel()ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")ctx = context.WithValue(ctx, common.UserContextKey, &store.UserMessage{Email: "[email protected]", Name: "creator"})stores := setupPlanServiceTestStore(ctx, t)@@ -171,6 +173,7 @@ func TestPlanServiceReleaseBackedPlanKeepsCreatorAsLastEditor(t *testing.T) {}func TestPlanServiceListPlansIncludesIssueStatus(t *testing.T) {+ t.Parallel()ctx := context.Background()stores := setupPlanServiceTestStore(ctx, t)service := NewPlanService(stores, nil, nil, nil, nil)@@ -248,6 +251,7 @@ func TestPlanServiceListPlansIncludesIssueStatus(t *testing.T) {}func TestConvertToPlansScopesIssueStatusByProject(t *testing.T) {+ t.Parallel()ctx := context.Background()stores := setupPlanServiceTestStore(ctx, t)_, err := stores.GetDB().ExecContext(ctx, `@@ -296,6 +300,7 @@ func TestConvertToPlansScopesIssueStatusByProject(t *testing.T) {}func TestPlanServiceCreatePlanRejectsMixedDatabaseSpecs(t *testing.T) {+ t.Parallel()ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")ctx = context.WithValue(ctx, common.UserContextKey, &store.UserMessage{Email: "[email protected]",@@ -331,6 +336,7 @@ func TestPlanServiceCreatePlanRejectsMixedDatabaseSpecs(t *testing.T) {// spec: a legacy client sending the removed field decodes to a spec with no// config, which creation must reject.func TestCreatePlanRejectsSpecsWithoutConfig(t *testing.T) {+ t.Parallel()ctx := context.Background()ctx = context.WithValue(ctx, common.WorkspaceIDContextKey, "default")ctx = context.WithValue(ctx, common.UserContextKey, &store.UserMessage{Email: "[email protected]", Name: "creator"})diff --git a/backend/api/v1/project_instance_lifecycle_api_test.go b/backend/api/v1/project_instance_lifecycle_api_test.goindex 7f0401a8df..8dfb2045ad 100644--- a/backend/api/v1/project_instance_lifecycle_api_test.go+++ b/backend/api/v1/project_instance_lifecycle_api_test.go@@ -26,6 +26,7 @@ import ()func TestProjectInstanceLifecycleAPIGatesArchivedProjectDescendants(t *testing.T) {+ t.Parallel()ctx, stores, projectID, instanceID, databaseName := setupProjectInstanceLifecycleAPITest(t)_, err := stores.UpdateInstance(ctx, &store.UpdateInstanceMessage{ResourceID: &instanceID,@@ -90,6 +91,7 @@ func TestProjectInstanceLifecycleAPIGatesArchivedProjectDescendants(t *testing.T}func TestProjectPurgeCleansSampleBeforeDeletingMetadata(t *testing.T) {+ t.Parallel()ctx, stores, projectID, instanceID, _ := setupProjectInstanceLifecycleAPITest(t)manager := &sampleManagerStub{}cleanupErr := errors.New("sample cleanup failed")@@ -138,6 +140,7 @@ func TestProjectPurgeCleansSampleBeforeDeletingMetadata(t *testing.T) {}func TestProjectPurgeRemovesSelfHostSample(t *testing.T) {+ t.Parallel()ctx, stores, projectID, instanceID, databaseName := setupProjectInstanceLifecycleAPITest(t)payload, err := protojson.Marshal(&storepb.SelfHostSampleInstanceSetupPayload{Instances: []*storepb.SelfHostSampleInstanceSetupPayload_Instance{{@@ -193,6 +196,7 @@ func TestProjectPurgeRemovesSelfHostSample(t *testing.T) {}func TestBatchSyncDatabasesValidatesAllTargetsBeforeScheduling(t *testing.T) {+ t.Parallel()ctx, stores, projectID, instanceID, databaseName := setupProjectInstanceLifecycleAPITest(t)licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")require.NoError(t, err)@@ -209,6 +213,7 @@ func TestBatchSyncDatabasesValidatesAllTargetsBeforeScheduling(t *testing.T) {}func TestUndeleteProjectInstanceChecksActivationLimit(t *testing.T) {+ t.Parallel()ctx, stores, projectID, instanceID, _ := setupProjectInstanceLifecycleAPITest(t)licenseService := newInstanceServiceTestLicenseService(t, stores)instanceService := &InstanceService{store: stores, licenseService: licenseService}diff --git a/backend/api/v1/project_instance_release_check_test.go b/backend/api/v1/project_instance_release_check_test.goindex 0cbaa93561..757658a106 100644--- a/backend/api/v1/project_instance_release_check_test.go+++ b/backend/api/v1/project_instance_release_check_test.go@@ -18,6 +18,7 @@ import ()func TestCheckReleaseDatabaseTargetsKeepCanonicalNames(t *testing.T) {+ t.Parallel()ctx, stores, instanceID, databaseName := setupProjectInstanceReleaseCheckTest(t)projectID := "project-a"projectTarget := common.FormatProjectDatabase(projectID, instanceID, databaseName)@@ -41,6 +42,7 @@ func TestCheckReleaseDatabaseTargetsKeepCanonicalNames(t *testing.T) {}func TestCheckReleaseRejectsCrossProjectTargets(t *testing.T) {+ t.Parallel()ctx, stores, instanceID, databaseName := setupProjectInstanceReleaseCheckTest(t)service := NewReleaseService(stores, sheet.NewManager(), nil, nil)request := func(target string) *connect.Request[v1pb.CheckReleaseRequest] {@@ -61,6 +63,7 @@ func TestCheckReleaseRejectsCrossProjectTargets(t *testing.T) {}func TestCheckReleaseHidesDatabasesOutsideProject(t *testing.T) {+ t.Parallel()ctx, stores, _, _ := setupProjectInstanceReleaseCheckTest(t)sharedInstanceID := "shared-instance"_, err := stores.CreateInstance(ctx, &store.InstanceMessage{@@ -100,6 +103,7 @@ func TestCheckReleaseHidesDatabasesOutsideProject(t *testing.T) {}func TestCheckReleaseRejectsArchivedProject(t *testing.T) {+ t.Parallel()ctx, stores, instanceID, databaseName := setupProjectInstanceReleaseCheckTest(t)archived := truerequire.NoError(t, stores.UpdateProjects(ctx, &store.UpdateProjectMessage{diff --git a/backend/api/v1/project_service_converter_webhook_test.go b/backend/api/v1/project_service_converter_webhook_test.goindex a21a3b2a63..a7a6c9a883 100644--- a/backend/api/v1/project_service_converter_webhook_test.go+++ b/backend/api/v1/project_service_converter_webhook_test.go@@ -10,6 +10,7 @@ import ()func TestConvertWebhookTypeGoogleChat(t *testing.T) {+ t.Parallel()a := require.New(t)storeType, err := convertToStoreWebhookType(v1pb.WebhookType_GOOGLE_CHAT)diff --git a/backend/api/v1/project_service_test.go b/backend/api/v1/project_service_test.goindex 64383a049d..d5d7d33446 100644--- a/backend/api/v1/project_service_test.go+++ b/backend/api/v1/project_service_test.go@@ -21,6 +21,7 @@ import ()func TestValidateMembers(t *testing.T) {+ t.Parallel()tests := []struct {member stringwantErr bool@@ -83,6 +84,7 @@ func TestValidateMembers(t *testing.T) {}func TestValidateBindings(t *testing.T) {+ t.Parallel()tests := []struct {bindings []*v1pb.Bindingroles []*store.RoleMessage@@ -257,6 +259,7 @@ func TestValidateBindings(t *testing.T) {}func TestValidateIAMPolicyExpression(t *testing.T) {+ t.Parallel()timeNow := time.Now()thirtyDays := &durationpb.Duration{Seconds: 60 * 60 * 24 * 30}withinCap := fmt.Sprintf("request.time < timestamp(\"%s\")", timeNow.AddDate(0, 0, 15).Format(time.RFC3339))@@ -307,6 +310,7 @@ func TestValidateIAMPolicyExpression(t *testing.T) {}func TestFindIamPolicyDeltas(t *testing.T) {+ t.Parallel()tests := []struct {oldPolicy *storepb.IamPolicynewIamPolicy *storepb.IamPolicy@@ -520,6 +524,7 @@ func TestValidateLabels(t *testing.T) {}func TestValidateIssueLabelsColor(t *testing.T) {+ t.Parallel()tests := []struct {name stringlabels []*v1pb.Label@@ -561,6 +566,7 @@ func TestValidateIssueLabelsColor(t *testing.T) {for _, tc := range tests {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()err := validateIssueLabels(tc.labels)if tc.wantErr {require.Error(t, err)diff --git a/backend/api/v1/read_redaction_test.go b/backend/api/v1/read_redaction_test.goindex 17e4128ac2..298aed989c 100644--- a/backend/api/v1/read_redaction_test.go+++ b/backend/api/v1/read_redaction_test.go@@ -114,6 +114,7 @@ func TestRedactRoleAttributeMasksTheCredential(t *testing.T) {// alone: the response is a copy, and a converter that masked in place would// corrupt the cached instance for everything else reading it.func TestConvertInstanceRolesRedactsOnTheReadPath(t *testing.T) {+ t.Parallel()leaking := "GRANT ALL PRIVILEGES ON *.* TO `root`@`%` IDENTIFIED BY PASSWORD '*3D3B92F242033365AE5BC6A8E6FC3E1679F4140A' WITH GRANT OPTION"stored := []*storepb.InstanceRole{{Name: "root", Attribute: &leaking},@@ -141,6 +142,7 @@ func TestConvertInstanceRolesRedactsOnTheReadPath(t *testing.T) {// are configuration, not a credential, and a client still has to be able to// list what is configured and edit it.func TestConvertToProjectWithholdsTheWebhookURL(t *testing.T) {+ t.Parallel()const storedURL = "https://hooks.slack.com/services/fixture-not-a-real-token"project := convertToProject(&store.ProjectMessage{ResourceID: "chat",diff --git a/backend/api/v1/release_service_check_mysql_test.go b/backend/api/v1/release_service_check_mysql_test.goindex 6322386271..298eb1bc2f 100644--- a/backend/api/v1/release_service_check_mysql_test.go+++ b/backend/api/v1/release_service_check_mysql_test.go@@ -15,6 +15,7 @@ import (// TestEngineSupportsDeclarativeRelease asserts MySQL is admitted into the declarative// release gating alongside PostgreSQL, and that engines without SDL support are excluded.func TestEngineSupportsDeclarativeRelease(t *testing.T) {+ t.Parallel()require.True(t, engineSupportsDeclarativeRelease(storepb.Engine_POSTGRES), "postgres must be admitted")require.True(t, engineSupportsDeclarativeRelease(storepb.Engine_MYSQL), "mysql must be admitted")require.False(t, engineSupportsDeclarativeRelease(storepb.Engine_ORACLE), "oracle must not be admitted")@@ -24,6 +25,7 @@ func TestEngineSupportsDeclarativeRelease(t *testing.T) {// TestGetStatementTypesWithPositionsForEngineMySQL proves the MySQL case of the gating// statement-type extractor classifies SDL statements and carries position info.func TestGetStatementTypesWithPositionsForEngineMySQL(t *testing.T) {+ t.Parallel()sql := "CREATE TABLE t (id INT PRIMARY KEY);\nDROP TABLE old;\n"stmts, err := base.ParseStatements(storepb.Engine_MYSQL, sql)require.NoError(t, err)@@ -46,6 +48,7 @@ func TestGetStatementTypesWithPositionsForEngineMySQL(t *testing.T) {// MySQL-only overlay (no PostgreSQL analog); mutating statements and unclassified// (UNSPECIFIED) statements are rejected for every engine — fail closed.func TestIsAllowedInSDL(t *testing.T) {+ t.Parallel()commonAllowed := []storepb.StatementType{storepb.StatementType_CREATE_TABLE,storepb.StatementType_CREATE_VIEW,@@ -95,6 +98,7 @@ func TestIsAllowedInSDL(t *testing.T) {// rejected — dropping it would let arbitrary unclassified statements bypass the SDL// allowlist entirely.func TestMySQLSDLGateFailsClosedOnUnclassifiedStatement(t *testing.T) {+ t.Parallel()sql := "CREATE TABLE t (id INT PRIMARY KEY);\nGRANT SELECT ON *.* TO 'x'@'%';\n"stmts, err := base.ParseStatements(storepb.Engine_MYSQL, sql)require.NoError(t, err, "omni must parse the GRANT for this gate to be reachable")diff --git a/backend/api/v1/release_service_test.go b/backend/api/v1/release_service_test.goindex cc678e80a4..aadcdfda5e 100644--- a/backend/api/v1/release_service_test.go+++ b/backend/api/v1/release_service_test.go@@ -8,6 +8,7 @@ import ()func TestRenderTrain(t *testing.T) {+ t.Parallel()// Fixed time for deterministic tests: 2026-01-15 14:30:45 UTCtestTime := time.Date(2026, 1, 15, 14, 30, 45, 0, time.UTC)@@ -114,6 +115,7 @@ func TestRenderTrain(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {+ t.Parallel()got, err := renderTrain(tt.template, tt.timezone, tt.time)if tt.wantError {require.Error(t, err)@@ -126,6 +128,7 @@ func TestRenderTrain(t *testing.T) {}func TestRenderTrainTimezoneConversion(t *testing.T) {+ t.Parallel()// Test edge case: date change across timezones// 2026-01-15 23:30:00 UTCtestTime := time.Date(2026, 1, 15, 23, 30, 0, 0, time.UTC)@@ -164,6 +167,7 @@ func TestRenderTrainTimezoneConversion(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {+ t.Parallel()template := "release_{date}_{time}-RC{iteration}"got, err := renderTrain(template, tt.timezone, testTime)require.NoError(t, err)@@ -174,6 +178,7 @@ func TestRenderTrainTimezoneConversion(t *testing.T) {}func TestValidateTemplate(t *testing.T) {+ t.Parallel()tests := []struct {name stringtemplate string@@ -251,6 +256,7 @@ func TestValidateTemplate(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {+ t.Parallel()err := validateTemplate(tt.template)if tt.wantError {require.Error(t, err)diff --git a/backend/api/v1/resource_id_test.go b/backend/api/v1/resource_id_test.goindex fbd36591a6..8bbc1992ec 100644--- a/backend/api/v1/resource_id_test.go+++ b/backend/api/v1/resource_id_test.go@@ -7,6 +7,7 @@ import ()func TestValidateResourceID(t *testing.T) {+ t.Parallel()a := require.New(t)testCases := []struct {diff --git a/backend/api/v1/review_config_service_test.go b/backend/api/v1/review_config_service_test.goindex 6d0a785db4..14d2fecd1f 100644--- a/backend/api/v1/review_config_service_test.go+++ b/backend/api/v1/review_config_service_test.go@@ -9,6 +9,7 @@ import ()func TestValidateSQLReviewRules(t *testing.T) {+ t.Parallel()tests := []struct {name stringrules []*v1pb.SQLReviewRule@@ -131,6 +132,7 @@ func TestValidateSQLReviewRules(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {+ t.Parallel()err := validateSQLReviewRules(tt.rules)if tt.wantErr {require.Error(t, err)diff --git a/backend/api/v1/rollout_service_converter_test.go b/backend/api/v1/rollout_service_converter_test.goindex 94b400bd94..69ea92246e 100644--- a/backend/api/v1/rollout_service_converter_test.go+++ b/backend/api/v1/rollout_service_converter_test.go@@ -13,6 +13,7 @@ import ()func TestConvertToTaskRunStatus(t *testing.T) {+ t.Parallel()tests := []struct {storeStatus storepb.TaskRun_Statuswant v1pb.TaskRun_Status@@ -28,12 +29,14 @@ func TestConvertToTaskRunStatus(t *testing.T) {for _, test := range tests {t.Run(test.storeStatus.String(), func(t *testing.T) {+ t.Parallel()require.Equal(t, test.want, convertToTaskRunStatus(test.storeStatus))})}}func TestConvertToTaskRunLogEntries_GhostMigration(t *testing.T) {+ t.Parallel()start := time.Date(2026, 5, 8, 10, 0, 0, 0, time.UTC)end := start.Add(3 * time.Second)diff --git a/backend/api/v1/sample_project_instance_integration_test.go b/backend/api/v1/sample_project_instance_integration_test.goindex cd64cb6ad0..8a0b104193 100644--- a/backend/api/v1/sample_project_instance_integration_test.go+++ b/backend/api/v1/sample_project_instance_integration_test.go@@ -39,6 +39,7 @@ import ()func TestPrepareSampleProjectInstanceLifecycle(t *testing.T) {+ t.Parallel()now := time.Date(2026, time.August, 17, 12, 0, 0, 0, time.UTC)ctx, fixture := newSampleProjectInstanceFixture(t, func() time.Time { return now })runner := samplerunner.NewRunner(fixture.manager)@@ -149,6 +150,7 @@ func TestPrepareSampleProjectInstanceLifecycle(t *testing.T) {}func TestSampleProjectPurgeRejectsPendingReservation(t *testing.T) {+ t.Parallel()ctx, fixture := newSampleProjectInstanceFixture(t, time.Now)payload := &storepb.SaaSSampleInstanceSetupPayload{ProjectId: fixture.projectID,@@ -177,7 +179,9 @@ func TestSampleProjectPurgeRejectsPendingReservation(t *testing.T) {require.Nil(t, setup.DeletedAt)}+//nolint:tparallel // Subtests share the parent's fixture.func TestPrepareSampleProjectInstanceAdditionalLifecycleCoverage(t *testing.T) {+ t.Parallel()now := time.Date(2026, time.August, 17, 12, 0, 0, 0, time.UTC)ctx, fixture := newSampleProjectInstanceFixture(t, func() time.Time { return now })runner := samplerunner.NewRunner(fixture.manager)diff --git a/backend/api/v1/setting_service_directory_sync_test.go b/backend/api/v1/setting_service_directory_sync_test.goindex 58f9fd8cdb..a07ee2904d 100644--- a/backend/api/v1/setting_service_directory_sync_test.go+++ b/backend/api/v1/setting_service_directory_sync_test.go@@ -17,6 +17,7 @@ import (// may ever be converted into it. The directory sync token used to be, which is// how it leaked to every member.func TestWorkspaceProfileNeverExposesDirectorySyncToken(t *testing.T) {+ t.Parallel()const tokenHash = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"got := convertToWorkspaceProfileSetting(&storepb.WorkspaceProfileSetting{@@ -78,6 +79,7 @@ func TestRotateDirectorySyncTokenRejectsMalformedNames(t *testing.T) {// before it is written — otherwise anyone with audit-log read access gets a// working SCIM credential.func TestRotateDirectorySyncTokenResponseIsRedactedForAudit(t *testing.T) {+ t.Parallel()const token = "b17c0d9e-2222-4000-8000-fedcbafedcba"got := marshalAuditPayload(&v1pb.RotateDirectorySyncTokenResponse{Token: token})@@ -87,6 +89,7 @@ func TestRotateDirectorySyncTokenResponseIsRedactedForAudit(t *testing.T) {// Guard against the next secret being dropped into this member-readable blob.// If this fails, either redact the new field or move it out of WORKSPACE_PROFILE.func TestWorkspaceProfileHasNoSecretShapedFields(t *testing.T) {+ t.Parallel()// Only string/bytes fields can carry a credential. Booleans like// disallow_password_signin and durations like refresh_token_duration name a// policy, not a secret, so restricting by kind keeps this guard free of andiff --git a/backend/api/v1/setting_service_test.go b/backend/api/v1/setting_service_test.goindex 74da75976e..d9aee70135 100644--- a/backend/api/v1/setting_service_test.go+++ b/backend/api/v1/setting_service_test.go@@ -16,6 +16,7 @@ import ()func TestValidateDomains(t *testing.T) {+ t.Parallel()a := require.New(t)testCases := []struct {@@ -63,6 +64,7 @@ func TestValidateDomains(t *testing.T) {}func TestValidateApprovalTemplate(t *testing.T) {+ t.Parallel()cases := []struct {name stringtemplate *v1pb.ApprovalTemplate@@ -107,6 +109,7 @@ func TestValidateApprovalTemplate(t *testing.T) {for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()err := validateApprovalTemplate(tc.template)if tc.wantErr {require.Error(t, err)@@ -175,6 +178,7 @@ func colorWithAlpha(red, green, blue, alpha float32) *colorpb.Color {}func TestValidateAnnouncementTheme(t *testing.T) {+ t.Parallel()cases := []struct {name stringtheme *storepb.WorkspaceProfileSetting_Announcement_AnnouncementTheme@@ -189,6 +193,7 @@ func TestValidateAnnouncementTheme(t *testing.T) {}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()err := validateAnnouncementTheme(tc.theme)if tc.wantErr {require.Error(t, err)@@ -200,6 +205,7 @@ func TestValidateAnnouncementTheme(t *testing.T) {}func TestValidateMCPCapability(t *testing.T) {+ t.Parallel()cases := []struct {name stringcapability storepb.MCPSetting_Capability@@ -214,6 +220,7 @@ func TestValidateMCPCapability(t *testing.T) {}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()err := validateMCPCapability(tc.capability)if tc.wantErr {require.Error(t, err)@@ -261,6 +268,7 @@ func TestValidateEnvironmentsColor(t *testing.T) {// stdout) are rejected in SaaS mode: on a shared replica they would let one// workspace admin change process-wide behavior affecting other workspaces.func TestPreflightWorkspaceProfileSaaSRestrictedPaths(t *testing.T) {+ t.Parallel()newRequest := func(path string) *connect.Request[v1pb.UpdateSettingRequest] {return connect.NewRequest(&v1pb.UpdateSettingRequest{UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{path}},diff --git a/backend/api/v1/sheet_test.go b/backend/api/v1/sheet_test.goindex 0eebcd9802..983fcc6320 100644--- a/backend/api/v1/sheet_test.go+++ b/backend/api/v1/sheet_test.go@@ -18,6 +18,7 @@ import (// split is otherwise compiler-enforced — the raw batch getters and the ref// filter are unexported from the store.func TestSheetContentGetterConfinement(t *testing.T) {+ t.Parallel()forbidden := map[string]bool{"GetSheetFull": true,}diff --git a/backend/api/v1/sql_service_schema_resolution_test.go b/backend/api/v1/sql_service_schema_resolution_test.goindex 22cdb95bba..8af2e4ea0c 100644--- a/backend/api/v1/sql_service_schema_resolution_test.go+++ b/backend/api/v1/sql_service_schema_resolution_test.go@@ -14,6 +14,7 @@ import (// sentinel when that can't be determined ahead of execution (so resource.schema_name is// omitted and schema-scoped grants fail closed). See SUP-222 / BYT-9698.func TestSchemaForWriteTargetResolution(t *testing.T) {+ t.Parallel()const dbName = "ORADB"tests := []struct {name string@@ -37,6 +38,7 @@ func TestSchemaForWriteTargetResolution(t *testing.T) {}for _, tc := range tests {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()require.Equal(t, tc.want, schemaForWriteTargetResolution(tc.engine, dbName, tc.requestSchema))})}@@ -70,5 +72,6 @@ func TestPostgresWriteTargetSchemaForRequest(t *testing.T) {// TestUnresolvedSchemaSentinelIsImpossible guards that the sentinel can never collide with a// real schema: a NUL byte is not representable in a PostgreSQL/MSSQL identifier.func TestUnresolvedSchemaSentinelIsImpossible(t *testing.T) {+ t.Parallel()require.Contains(t, unresolvedSchemaSentinel, "\x00")}diff --git a/backend/api/v1/sql_service_test.go b/backend/api/v1/sql_service_test.goindex f4b0af3135..a9ecec36e5 100644--- a/backend/api/v1/sql_service_test.go+++ b/backend/api/v1/sql_service_test.go@@ -14,6 +14,7 @@ import ()func TestSQLIAMDatabaseResourceUsesCanonicalInstanceScope(t *testing.T) {+ t.Parallel()projectID := "project-a"projectInstance := &store.InstanceMessage{ResourceID: "instance-a", ProjectID: &projectID}workspaceInstance := &store.InstanceMessage{ResourceID: "instance-b"}@@ -55,6 +56,7 @@ func TestSQLIAMDatabaseResourceUsesCanonicalInstanceScope(t *testing.T) {// rollout/stage names must fail name parsing with InvalidArgument, not fall// through as 500s.func TestExportRejectsRetiredRolloutNames(t *testing.T) {+ t.Parallel()ctx := context.WithValue(context.Background(), common.UserContextKey, &store.UserMessage{Email: "[email protected]"})s := &SQLService{}for _, name := range []string{@@ -156,6 +158,7 @@ func TestBuildExportQueryContextPropagatesSkipMasking(t *testing.T) {// TestBuildExportQueryContextPropagatesOtherFields guards against accidental// drops of the surrounding fields if buildExportQueryContext is edited.func TestBuildExportQueryContextPropagatesOtherFields(t *testing.T) {+ t.Parallel()schema := "public"restriction := &store.EffectiveQueryDataPolicy{MaximumResultRows: 500,@@ -178,6 +181,7 @@ func TestBuildExportQueryContextPropagatesOtherFields(t *testing.T) {// MaxQueryTimeoutInSeconds doesn't leak a zero-Duration timeout into the// query context (which the driver layer treats differently from "no timeout").func TestBuildExportQueryContextOmitsTimeoutWhenZero(t *testing.T) {+ t.Parallel()restriction := &store.EffectiveQueryDataPolicy{MaximumResultRows: 100,MaximumResultSize: 1 << 20,@@ -189,6 +193,7 @@ func TestBuildExportQueryContextOmitsTimeoutWhenZero(t *testing.T) {}func TestResolveDataSourceIDUsesAdminForNonReadOnlyAutomaticQueryWhenAllowed(t *testing.T) {+ t.Parallel()instance := &store.InstanceMessage{Metadata: &storepb.Instance{Engine: storepb.Engine_MYSQL,@@ -205,6 +210,7 @@ func TestResolveDataSourceIDUsesAdminForNonReadOnlyAutomaticQueryWhenAllowed(t *}func TestResolveDataSourceIDKeepsReadOnlyForReadOnlyAutomaticQueryWhenAllowed(t *testing.T) {+ t.Parallel()instance := &store.InstanceMessage{Metadata: &storepb.Instance{Engine: storepb.Engine_MYSQL,@@ -221,6 +227,7 @@ func TestResolveDataSourceIDKeepsReadOnlyForReadOnlyAutomaticQueryWhenAllowed(t}func TestResolveDataSourceIDKeepsReadOnlyForNonReadOnlyAutomaticQueryWhenAdminDisallowed(t *testing.T) {+ t.Parallel()instance := &store.InstanceMessage{Metadata: &storepb.Instance{Engine: storepb.Engine_MYSQL,@@ -237,6 +244,7 @@ func TestResolveDataSourceIDKeepsReadOnlyForNonReadOnlyAutomaticQueryWhenAdminDi}func TestResolveDataSourceIDUsesAdminForDocumentEngineAutomaticWriteQueryWhenAllowed(t *testing.T) {+ t.Parallel()tests := []struct {name stringengine storepb.Engine@@ -266,6 +274,7 @@ func TestResolveDataSourceIDUsesAdminForDocumentEngineAutomaticWriteQueryWhenAllfor _, tc := range tests {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()instance := &store.InstanceMessage{Metadata: &storepb.Instance{Engine: tc.engine,@@ -284,6 +293,7 @@ func TestResolveDataSourceIDUsesAdminForDocumentEngineAutomaticWriteQueryWhenAll}func TestResolveDataSourceIDKeepsReadOnlyForDocumentEngineAutomaticReadQueryWhenAllowed(t *testing.T) {+ t.Parallel()tests := []struct {name stringengine storepb.Engine@@ -303,6 +313,7 @@ func TestResolveDataSourceIDKeepsReadOnlyForDocumentEngineAutomaticReadQueryWhenfor _, tc := range tests {t.Run(tc.name, func(t *testing.T) {+ t.Parallel()instance := &store.InstanceMessage{Metadata: &storepb.Instance{Engine: tc.engine,diff --git a/backend/api/v1/user_service_credential_test.go b/backend/api/v1/user_service_credential_test.goindex 1538747e4f..ab33f25307 100644--- a/backend/api/v1/user_service_credential_test.go+++ b/backend/api/v1/user_service_credential_test.go@@ -18,6 +18,7 @@ import (// password instead — and never against a live MFA factor. The SaaS side has// no e2e harness, so the rule is pinned here.func TestEmailCodeEligibility(t *testing.T) {+ t.Parallel()userWith := func(otpSecret string, lastChangePassword bool) *store.UserMessage {profile := &storepb.UserProfile{}if lastChangePassword {@@ -61,6 +62,7 @@ func TestEmailCodeEligibility(t *testing.T) {// SSO-provisioned account holds a random password nobody was told, and the// server cannot tell it apart from one whose owner simply did not type it.func TestFirstTimeEnrollmentCredentialShape(t *testing.T) {+ t.Parallel()saas := &UserService{profile: &config.Profile{SaaS: true}}selfHosted := &UserService{profile: &config.Profile{SaaS: false}}enrolling := &store.UserMessage{diff --git a/backend/api/v1/workload_identity_service_test.go b/backend/api/v1/workload_identity_service_test.goindex 31fff0c26c..78d67e687e 100644--- a/backend/api/v1/workload_identity_service_test.go+++ b/backend/api/v1/workload_identity_service_test.go@@ -9,6 +9,7 @@ import ()func TestValidateWorkloadIdentityConfig(t *testing.T) {+ t.Parallel()tests := []struct {name stringconfig *v1pb.WorkloadIdentityConfig@@ -124,6 +125,7 @@ func TestValidateWorkloadIdentityConfig(t *testing.T) {for _, test := range tests {t.Run(test.name, func(t *testing.T) {+ t.Parallel()err := validateWorkloadIdentityConfig(test.config)if test.wantErr == "" {require.NoError(t, err)@@ -135,6 +137,7 @@ func TestValidateWorkloadIdentityConfig(t *testing.T) {}func TestConvertToStoreWorkloadIdentityConfigNormalizesOIDCValues(t *testing.T) {+ t.Parallel()config := &v1pb.WorkloadIdentityConfig{ProviderType: v1pb.WorkloadIdentityConfig_OIDC,IssuerUrl: " https://nomad.example.com ",diff --git a/backend/common/testcontainer/metadata.go b/backend/common/testcontainer/metadata.goindex 0af47604d9..b1e5d54080 100644--- a/backend/common/testcontainer/metadata.go+++ b/backend/common/testcontainer/metadata.go@@ -1,10 +1,8 @@-// Shared metadata Postgres: one container for a whole test package instead of-// one per test. A package opts in with three lines:+// Shared metadata Postgres: the package's shared container carries a template+// database migrated once, and each test calls NewMetadataDB for a copy of it.+// A copy costs 44ms against a container start. The package opts in with//-// func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }-//-// and each test calls NewMetadataDB for its own copy of a template database-// migrated once. A copy costs 44ms against a 4.3s container.+// func TestMain(m *testing.M) { testcontainer.Main(m) }package testcontainer@@ -29,37 +27,17 @@ var (metaAdminDB *sql.DBmetaDatabaseSeq atomic.Int64metaOnce sync.Once- metaContainer *ContainermetaErr error)-// MetadataMain runs the package's tests and takes the shared Postgres down-// afterwards. Call it from the package's TestMain. Nothing starts until a test-// actually asks for a database, so `go test -run` over tests that need none-// still costs nothing and still works without Docker.-func MetadataMain(m *testing.M) {- defer func() {- if metaContainer != nil {- metaContainer.Close(context.Background())- }- }()- m.Run()-}--// startMetadata brings up the container and template on first use.+// startMetadata migrates the template on the shared container on first use.func startMetadata(t *testing.T) {t.Helper()+ container := SharedPgContainer(t)metaOnce.Do(func() {- ctx := context.Background()- container, err := GetPgContainer(ctx)- if err != nil {- metaErr = err- return- }- metaContainer = containermetaHost, metaPort = container.GetHost(), container.GetPort()metaAdminDB = container.GetDB()- metaErr = migrateTemplate(ctx)+ metaErr = migrateTemplate(context.Background())})require.NoError(t, metaErr)}diff --git a/backend/common/testcontainer/shared.go b/backend/common/testcontainer/shared.gonew file mode 100644index 0000000000..8cef2393fe--- /dev/null+++ b/backend/common/testcontainer/shared.go@@ -0,0 +1,92 @@+package testcontainer++import (+ "context"+ "database/sql"+ "fmt"+ "sync"+ "sync/atomic"+ "testing"++ "github.com/stretchr/testify/require"+)++// One container per test package, started on first use and stopped by Main.+// A test binary is its own process, so package-level state here is per+// package. Starting lazily is what keeps `go test -run` over the tests that+// need no engine from paying for a container they never open.+var (+ sharedPg = startOnce(GetPgContainer)+ sharedMySQL = startOnce(GetTestMySQLContainer)+ sharedOracle = startOnce(GetOracleContainer)+ sharedMSSQL = startOnce(GetMSSQLContainer)+ sharedTiDB = startOnce(GetTiDBContainer)++ startedMu sync.Mutex+ started []*Container++ pgDatabaseSeq atomic.Int64+)++func startOnce(start func(context.Context) (*Container, error)) func() (*Container, error) {+ return sync.OnceValues(func() (*Container, error) {+ c, err := start(context.Background())+ if err == nil {+ startedMu.Lock()+ started = append(started, c)+ startedMu.Unlock()+ }+ return c, err+ })+}++func shared(t testing.TB, start func() (*Container, error)) *Container {+ t.Helper()+ c, err := start()+ require.NoError(t, err, "start the shared container")+ return c+}++// Main runs the package's tests and stops the containers they shared:+//+// func TestMain(m *testing.M) { testcontainer.Main(m) }+func Main(m *testing.M) {+ defer func() {+ for _, c := range started {+ c.Close(context.Background())+ }+ }()+ m.Run()+}++// SharedPgContainer returns the package's PostgreSQL container, starting it on+// the first call. Tests isolate themselves with NewPgDatabase or NewMetadataDB.+func SharedPgContainer(t testing.TB) *Container { return shared(t, sharedPg) }++// SharedMySQLContainer is SharedPgContainer for MySQL; tests take a database each.+func SharedMySQLContainer(t testing.TB) *Container { return shared(t, sharedMySQL) }++// SharedOracleContainer is SharedPgContainer for Oracle; tests take a user each.+func SharedOracleContainer(t testing.TB) *Container { return shared(t, sharedOracle) }++// SharedMSSQLContainer is SharedPgContainer for SQL Server; tests take a database each.+func SharedMSSQLContainer(t testing.TB) *Container { return shared(t, sharedMSSQL) }++// SharedTiDBContainer is SharedPgContainer for TiDB; tests take a database each.+func SharedTiDBContainer(t testing.TB) *Container { return shared(t, sharedTiDB) }++// NewPgDatabase creates an empty database for the test on the shared+// PostgreSQL container and returns its name with a superuser handle to it.+// Anything cluster-wide the test creates, such as a role, should be named+// after the database so that parallel tests cannot collide.+func NewPgDatabase(t testing.TB) (string, *sql.DB) {+ t.Helper()+ container := SharedPgContainer(t)+ name := fmt.Sprintf("test_%d", pgDatabaseSeq.Add(1))+ _, err := container.GetDB().Exec("CREATE DATABASE " + name)+ require.NoError(t, err)+ db, err := sql.Open("pgx", fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=%s", container.GetHost(), container.GetPort(), name))+ require.NoError(t, err)+ t.Cleanup(func() { require.NoError(t, db.Close()) })+ return name, db+}diff --git a/backend/common/testcontainer/testcontainer.go b/backend/common/testcontainer/testcontainer.goindex 11115a18c8..62a6d40bcf 100644--- a/backend/common/testcontainer/testcontainer.go+++ b/backend/common/testcontainer/testcontainer.go@@ -336,26 +336,26 @@ func createPostgreSQLTLSMaterial() (string, string, []byte, []byte, error) {return tlsDir, caPath, certificate, key, nil}+// waitDBPing returns once the database accepts a connection. The container's+// log wait has already passed by the time this runs, so the first ping nearly+// always succeeds; the poll only covers the gap between "ready" in the log and+// the listener. A 3 s ticker here used to add 3 s to every container start.func waitDBPing(ctx context.Context, db *sql.DB) error {- started := time.Now()- ticker := time.NewTicker(3 * time.Second)+ ticker := time.NewTicker(100 * time.Millisecond)defer ticker.Stop()timeout := time.After(10 * time.Minute)-outerLoop:for {+ if err := db.PingContext(ctx); err == nil {+ return nil+ }select {case <-ticker.C:- if err := db.PingContext(ctx); err == nil {- if time.Since(started) > 1*time.Minute {- fmt.Printf("Total wait time: %s\n", time.Since(started))- }- break outerLoop- }case <-timeout:return errors.Errorf("start container timeout reached")+ case <-ctx.Done():+ return ctx.Err()}}- return nil}// GetTestPgContainer is a helper function for tests that creates a PostgreSQL containerdiff --git a/backend/component/recovery/main_test.go b/backend/component/recovery/main_test.goindex da9528e851..329fad9c56 100644--- a/backend/component/recovery/main_test.go+++ b/backend/component/recovery/main_test.go@@ -6,4 +6,4 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer")-func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/component/review/main_test.go b/backend/component/review/main_test.goindex 71d4b3dddf..c44ea2fdc0 100644--- a/backend/component/review/main_test.go+++ b/backend/component/review/main_test.go@@ -6,4 +6,4 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer")-func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/enterprise/main_test.go b/backend/enterprise/main_test.goindex f9224c3090..fe85868621 100644--- a/backend/enterprise/main_test.go+++ b/backend/enterprise/main_test.go@@ -6,4 +6,4 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer")-func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/plugin/db/pg/main_test.go b/backend/plugin/db/pg/main_test.gonew file mode 100644index 0000000000..12b1b9272c--- /dev/null+++ b/backend/plugin/db/pg/main_test.go@@ -0,0 +1,9 @@+package pg++import (+ "testing"++ "github.com/bytebase/bytebase/backend/common/testcontainer"+)++func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/plugin/db/pg/query_merge_cte_test.go b/backend/plugin/db/pg/query_merge_cte_test.goindex 60cec3e685..bbf7e8277a 100644--- a/backend/plugin/db/pg/query_merge_cte_test.go+++ b/backend/plugin/db/pg/query_merge_cte_test.go@@ -28,6 +28,7 @@ import (// security-relevant outcome at the driver boundary: the MERGE-CTE must NOT return// the secret value as data rows. MERGE ... RETURNING requires PostgreSQL 17.func TestQueryConnMergeCTEDoesNotLeakRows(t *testing.T) {+ t.Parallel()ctx := context.Background()pgContainer := testcontainer.GetTestPg17Container(ctx, t)diff --git a/backend/plugin/db/pg/query_search_path_test.go b/backend/plugin/db/pg/query_search_path_test.goindex 141d0aee9f..b9fce07b8e 100644--- a/backend/plugin/db/pg/query_search_path_test.go+++ b/backend/plugin/db/pg/query_search_path_test.go@@ -13,13 +13,11 @@ import ()func TestQueryConnSearchPathIncludesPublicAfterSelectedSchema(t *testing.T) {+ t.Parallel()ctx := context.Background()- pgContainer := testcontainer.GetTestPgContainer(ctx, t)- defer pgContainer.Close(ctx)-- rawDB := pgContainer.GetDB()- require.NoError(t, rawDB.Ping())+ pgContainer := testcontainer.SharedPgContainer(t)+ dbName, rawDB := testcontainer.NewPgDatabase(t)_, err := rawDB.ExecContext(ctx, `CREATE SCHEMA app;CREATE TABLE public.lookup_precedence (marker text);@@ -46,7 +44,7 @@ func TestQueryConnSearchPathIncludesPublicAfterSelectedSchema(t *testing.T) {Username: "postgres",},Password: "root-password",- ConnectionContext: db.ConnectionContext{DatabaseName: "postgres"},+ ConnectionContext: db.ConnectionContext{DatabaseName: dbName},})require.NoError(t, err)defer driver.Close(ctx)@@ -70,13 +68,11 @@ func TestQueryConnSearchPathIncludesPublicAfterSelectedSchema(t *testing.T) {}func TestQueryConnSearchPathEscapesSelectedSchemaName(t *testing.T) {+ t.Parallel()ctx := context.Background()- pgContainer := testcontainer.GetTestPgContainer(ctx, t)- defer pgContainer.Close(ctx)-- rawDB := pgContainer.GetDB()- require.NoError(t, rawDB.Ping())+ pgContainer := testcontainer.SharedPgContainer(t)+ dbName, rawDB := testcontainer.NewPgDatabase(t)_, err := rawDB.ExecContext(ctx, `CREATE SCHEMA "app""schema";CREATE TABLE "app""schema".lookup_precedence (marker text);@@ -91,7 +87,7 @@ func TestQueryConnSearchPathEscapesSelectedSchemaName(t *testing.T) {Username: "postgres",},Password: "root-password",- ConnectionContext: db.ConnectionContext{DatabaseName: "postgres"},+ ConnectionContext: db.ConnectionContext{DatabaseName: dbName},})require.NoError(t, err)defer driver.Close(ctx)diff --git a/backend/plugin/db/pg/sync_column_default_test.go b/backend/plugin/db/pg/sync_column_default_test.goindex d7dfd1eb64..be8bd920f8 100644--- a/backend/plugin/db/pg/sync_column_default_test.go+++ b/backend/plugin/db/pg/sync_column_default_test.go@@ -12,15 +12,11 @@ import ()func TestSync_ColumnDefaultSchemaQualification(t *testing.T) {+ t.Parallel()ctx := context.Background()- // Use the centralized testcontainer helper- pgContainer := testcontainer.GetTestPgContainer(ctx, t)- defer pgContainer.Close(ctx)-- // Get database connection- pgDB := pgContainer.GetDB()- require.NoError(t, pgDB.Ping())+ pgContainer := testcontainer.SharedPgContainer(t)+ dbName, pgDB := testcontainer.NewPgDatabase(t)// Set up test schema with various default value scenariossetupSQL := `@@ -88,18 +84,18 @@ COMMENT ON TABLE test_defaults IS 'Test table for column default schema qualificUsername: "postgres",Host: pgContainer.GetHost(),Port: pgContainer.GetPort(),- Database: "postgres",+ Database: dbName,},Password: "root-password",ConnectionContext: db.ConnectionContext{EngineVersion: "16.0",- DatabaseName: "postgres",+ DatabaseName: dbName,},}openedDriver, err := driver.Open(ctx, storepb.Engine_POSTGRES, config)require.NoError(t, err)- defer openedDriver.Close(ctx)+ t.Cleanup(func() { require.NoError(t, openedDriver.Close(ctx)) })pgDriver, ok := openedDriver.(*Driver)require.True(t, ok)@@ -200,6 +196,7 @@ COMMENT ON TABLE test_defaults IS 'Test table for column default schema qualific// Verify each test casefor _, tc := range testCases {t.Run(tc.columnName, func(t *testing.T) {+ t.Parallel()column, exists := columnMap[tc.columnName]require.True(t, exists, "Column %s should exist", tc.columnName)@@ -227,15 +224,11 @@ COMMENT ON TABLE test_defaults IS 'Test table for column default schema qualific}func TestSync_ColumnDefaultCrossSchemaQualification(t *testing.T) {+ t.Parallel()ctx := context.Background()- // Use the centralized testcontainer helper- pgContainer := testcontainer.GetTestPgContainer(ctx, t)- defer pgContainer.Close(ctx)-- // Get database connection- pgDB := pgContainer.GetDB()- require.NoError(t, pgDB.Ping())+ pgContainer := testcontainer.SharedPgContainer(t)+ dbName, pgDB := testcontainer.NewPgDatabase(t)// Create schema with cross-schema referencessetupSQL := `@@ -280,12 +273,12 @@ CREATE TABLE critical_test (Username: "postgres",Host: pgContainer.GetHost(),Port: pgContainer.GetPort(),- Database: "postgres",+ Database: dbName,},Password: "root-password",ConnectionContext: db.ConnectionContext{EngineVersion: "16.0",- DatabaseName: "postgres",+ DatabaseName: dbName,},}diff --git a/backend/plugin/db/pg/sync_column_test.go b/backend/plugin/db/pg/sync_column_test.goindex f440bfb6dc..3ffc0ed27f 100644--- a/backend/plugin/db/pg/sync_column_test.go+++ b/backend/plugin/db/pg/sync_column_test.go@@ -116,13 +116,9 @@ func queryColumnRows(t *testing.T, txn *sql.Tx, query string) []columnQueryRow {// rendering contract: the Go-side formatting in getTableColumns depends on the exact// data_type / precision / udt values that information_schema used to produce.func TestListColumnQueryMatchesInformationSchema(t *testing.T) {- ctx := context.Background()-- pgContainer := testcontainer.GetTestPgContainer(ctx, t)- defer pgContainer.Close(ctx)+ t.Parallel()- pgDB := pgContainer.GetDB()- require.NoError(t, pgDB.Ping())+ _, pgDB := testcontainer.NewPgDatabase(t)setupSQL := `CREATE SCHEMA app;@@ -228,13 +224,11 @@ CREATE TABLE public.plain (a serial, b text);// constraints (read from pg_catalog) but zero columns. The pg_catalog-based column query// must return the columns regardless.func TestSyncColumnsWithoutTablePrivilege(t *testing.T) {+ t.Parallel()ctx := context.Background()- pgContainer := testcontainer.GetTestPgContainer(ctx, t)- defer pgContainer.Close(ctx)-- pgDB := pgContainer.GetDB()- require.NoError(t, pgDB.Ping())+ pgContainer := testcontainer.SharedPgContainer(t)+ dbName, pgDB := testcontainer.NewPgDatabase(t)setupSQL := `CREATE SCHEMA restricted;@@ -245,15 +239,17 @@ CREATE TABLE restricted.secret_table (CONSTRAINT positive_amount CHECK (amount >= 0));CREATE INDEX idx_secret_name ON restricted.secret_table (name);-CREATE USER limited_user WITH LOGIN PASSWORD 'limited-password';--- pg_read_all_stats lets the sync read pg_table_size/pg_indexes_size; it grants no--- table or column privileges, so information_schema.columns still hides the table.-GRANT pg_read_all_stats TO limited_user;`_, err := pgDB.Exec(setupSQL)require.NoError(t, err)- limitedDB, err := sql.Open("pgx", fmt.Sprintf("host=%s port=%s user=limited_user password=limited-password database=postgres", pgContainer.GetHost(), pgContainer.GetPort()))+ // pg_read_all_stats lets the sync read pg_table_size/pg_indexes_size; it grants no+ // table or column privileges, so information_schema.columns still hides the table.+ limitedUser := "limited_" + dbName+ _, err = pgDB.Exec(fmt.Sprintf("CREATE USER %s WITH LOGIN PASSWORD 'limited-password'; GRANT pg_read_all_stats TO %s;", limitedUser, limitedUser))+ require.NoError(t, err)++ limitedDB, err := sql.Open("pgx", fmt.Sprintf("host=%s port=%s user=%s password=limited-password database=%s", pgContainer.GetHost(), pgContainer.GetPort(), limitedUser, dbName))require.NoError(t, err)defer limitedDB.Close()require.NoError(t, limitedDB.Ping())@@ -270,15 +266,15 @@ GRANT pg_read_all_stats TO limited_user;config := db.ConnectionConfig{DataSource: &storepb.DataSource{Type: storepb.DataSourceType_ADMIN,- Username: "limited_user",+ Username: limitedUser,Host: pgContainer.GetHost(),Port: pgContainer.GetPort(),- Database: "postgres",+ Database: dbName,},Password: "limited-password",ConnectionContext: db.ConnectionContext{EngineVersion: "16.0",- DatabaseName: "postgres",+ DatabaseName: dbName,},}diff --git a/backend/plugin/db/pg/sync_foreign_table_test.go b/backend/plugin/db/pg/sync_foreign_table_test.goindex f126b8f9b8..bb93fefed8 100644--- a/backend/plugin/db/pg/sync_foreign_table_test.go+++ b/backend/plugin/db/pg/sync_foreign_table_test.go@@ -57,13 +57,9 @@ func queryForeignTableRows(t *testing.T, conn *sql.DB, query string) [][4]string// foreign table query produces exactly the same rows as the previous// information_schema.foreign_tables-based query for a privileged user.func TestListForeignTableQueryMatchesInformationSchema(t *testing.T) {- ctx := context.Background()-- pgContainer := testcontainer.GetTestPgContainer(ctx, t)- defer pgContainer.Close(ctx)+ t.Parallel()- pgDB := pgContainer.GetDB()- require.NoError(t, pgDB.Ping())+ _, pgDB := testcontainer.NewPgDatabase(t)_, err := pgDB.Exec(foreignTableSetupSQL)require.NoError(t, err)@@ -80,26 +76,22 @@ func TestListForeignTableQueryMatchesInformationSchema(t *testing.T) {// privilege-filters its rows, so a sync user without privileges on a foreign table used// to silently lose the whole table from the synced metadata.func TestSyncForeignTablesWithoutTablePrivilege(t *testing.T) {+ t.Parallel()ctx := context.Background()- pgContainer := testcontainer.GetTestPgContainer(ctx, t)- defer pgContainer.Close(ctx)-- pgDB := pgContainer.GetDB()- require.NoError(t, pgDB.Ping())+ pgContainer := testcontainer.SharedPgContainer(t)+ dbName, pgDB := testcontainer.NewPgDatabase(t)_, err := pgDB.Exec(foreignTableSetupSQL)require.NoError(t, err)// pg_read_all_stats lets the sync read pg_table_size/pg_indexes_size; it grants no// table or column privileges, so information_schema.foreign_tables still filters.- _, err = pgDB.Exec(`-CREATE USER limited_user WITH LOGIN PASSWORD 'limited-password';-GRANT pg_read_all_stats TO limited_user;-`)+ limitedUser := "limited_" + dbName+ _, err = pgDB.Exec(fmt.Sprintf("CREATE USER %s WITH LOGIN PASSWORD 'limited-password'; GRANT pg_read_all_stats TO %s;", limitedUser, limitedUser))require.NoError(t, err)- limitedDB, err := sql.Open("pgx", fmt.Sprintf("host=%s port=%s user=limited_user password=limited-password database=postgres", pgContainer.GetHost(), pgContainer.GetPort()))+ limitedDB, err := sql.Open("pgx", fmt.Sprintf("host=%s port=%s user=%s password=limited-password database=%s", pgContainer.GetHost(), pgContainer.GetPort(), limitedUser, dbName))require.NoError(t, err)defer limitedDB.Close()require.NoError(t, limitedDB.Ping())@@ -114,15 +106,15 @@ GRANT pg_read_all_stats TO limited_user;config := db.ConnectionConfig{DataSource: &storepb.DataSource{Type: storepb.DataSourceType_ADMIN,- Username: "limited_user",+ Username: limitedUser,Host: pgContainer.GetHost(),Port: pgContainer.GetPort(),- Database: "postgres",+ Database: dbName,},Password: "limited-password",ConnectionContext: db.ConnectionContext{EngineVersion: "16.0",- DatabaseName: "postgres",+ DatabaseName: dbName,},}@@ -149,7 +141,7 @@ GRANT pg_read_all_stats TO limited_user;remoteOrders := fdwSchema.ExternalTables[0]require.Equal(t, "remote_orders", remoteOrders.Name)require.Equal(t, "loopback_server", remoteOrders.ExternalServerName)- require.Equal(t, "postgres", remoteOrders.ExternalDatabaseName)+ require.Equal(t, dbName, remoteOrders.ExternalDatabaseName)// Columns of foreign tables come from the privilege-independent column sync.require.Len(t, remoteOrders.Columns, 2)diff --git a/backend/plugin/schema/mssql/generate_migration_testcontainer_test.go b/backend/plugin/schema/mssql/generate_migration_testcontainer_test.goindex b4ce4fb165..58b288d404 100644--- a/backend/plugin/schema/mssql/generate_migration_testcontainer_test.go+++ b/backend/plugin/schema/mssql/generate_migration_testcontainer_test.go@@ -15,6 +15,7 @@ import ("github.com/stretchr/testify/require""google.golang.org/protobuf/testing/protocmp"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/schema""github.com/bytebase/bytebase/backend/store/model"@@ -32,7 +33,7 @@ func TestGenerateMigrationWithTestcontainer(t *testing.T) {ctx := context.Background()// Start shared MSSQL container for all subtests- container := sharedMSSQLContainer(t)+ container := testcontainer.SharedMSSQLContainer(t)// Test cases with various schema changestestCases := []struct {diff --git a/backend/plugin/schema/mssql/get_database_definition_testcontainer_test.go b/backend/plugin/schema/mssql/get_database_definition_testcontainer_test.goindex 4e96ffb547..6dc57d8d8b 100644--- a/backend/plugin/schema/mssql/get_database_definition_testcontainer_test.go+++ b/backend/plugin/schema/mssql/get_database_definition_testcontainer_test.go@@ -10,6 +10,7 @@ import (_ "github.com/microsoft/go-mssqldb""github.com/stretchr/testify/require"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/schema")@@ -17,7 +18,7 @@ import (//nolint:tparallelfunc TestGetDatabaseDefinitionWithTestcontainer(t *testing.T) {ctx := context.Background()- container := sharedMSSQLContainer(t)+ container := testcontainer.SharedMSSQLContainer(t)testCases := []struct {name stringdiff --git a/backend/plugin/schema/mssql/get_database_metadata_testcontainer_test.go b/backend/plugin/schema/mssql/get_database_metadata_testcontainer_test.goindex 29b780d403..ce5d4309dd 100644--- a/backend/plugin/schema/mssql/get_database_metadata_testcontainer_test.go+++ b/backend/plugin/schema/mssql/get_database_metadata_testcontainer_test.go@@ -10,13 +10,14 @@ import (_ "github.com/microsoft/go-mssqldb""github.com/stretchr/testify/require"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store")//nolint:tparallelfunc TestGetDatabaseMetadataWithTestcontainer(t *testing.T) {ctx := context.Background()- container := sharedMSSQLContainer(t)+ container := testcontainer.SharedMSSQLContainer(t)testCases := []struct {name stringdiff --git a/backend/plugin/schema/mssql/main_test.go b/backend/plugin/schema/mssql/main_test.goindex 7b4de34681..aae886b962 100644--- a/backend/plugin/schema/mssql/main_test.go+++ b/backend/plugin/schema/mssql/main_test.go@@ -1,50 +1,9 @@package mssqlimport (- "context"- "sync""testing""github.com/bytebase/bytebase/backend/common/testcontainer")-// The package shares one SQL Server container, started on first use.-//-// Sharing it is worth a container start, and this package took three of them.-// Starting it lazily is what keeps that saving from turning into a tax on the-// tests that need no engine at all, which would otherwise pay for a container-// they never open.-var (- mssqlOnce sync.Once- mssqlContainer *testcontainer.Container- mssqlErr error-)--func TestMain(m *testing.M) {- defer func() {- if mssqlContainer != nil {- mssqlContainer.Close(context.Background())- }- }()- m.Run()-}--// sharedMSSQLContainer returns the package's SQL Server container, starting it on-// the first call. Tests keep isolating themselves with a per-test database,-// which is what makes one container enough.-func sharedMSSQLContainer(t *testing.T) *testcontainer.Container {- t.Helper()-- mssqlOnce.Do(func() {- container, err := testcontainer.GetMSSQLContainer(context.Background())- if err != nil {- mssqlErr = err- return- }- mssqlContainer = container- })- if mssqlErr != nil {- t.Fatalf("failed to start the shared SQL Server container: %v", mssqlErr)- }- return mssqlContainer-}+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go b/backend/plugin/schema/mysql/generate_migration_testcontainer_test.goindex df8e9dcceb..127a1a99e5 100644--- a/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go+++ b/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go@@ -14,6 +14,7 @@ import ("github.com/stretchr/testify/require""google.golang.org/protobuf/testing/protocmp"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/schema"@@ -32,7 +33,7 @@ func TestGenerateMigrationWithTestcontainer(t *testing.T) {ctx := context.Background()// Start shared MySQL container for all subtests- container := sharedMySQLContainer(t)+ container := testcontainer.SharedMySQLContainer(t)// Test cases with various schema changestestCases := []struct {diff --git a/backend/plugin/schema/mysql/get_database_definition_testcontainer_test.go b/backend/plugin/schema/mysql/get_database_definition_testcontainer_test.goindex 8efb7e1c2a..aeb828e5c1 100644--- a/backend/plugin/schema/mysql/get_database_definition_testcontainer_test.go+++ b/backend/plugin/schema/mysql/get_database_definition_testcontainer_test.go@@ -13,6 +13,7 @@ import ("github.com/stretchr/testify/require""google.golang.org/protobuf/testing/protocmp"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/schema"@@ -27,7 +28,7 @@ func TestGetDatabaseDefinition(t *testing.T) {ctx := context.Background()// Start shared MySQL container for all subtests- container := sharedMySQLContainer(t)+ container := testcontainer.SharedMySQLContainer(t)type testCase struct {description string@@ -470,7 +471,7 @@ CREATE TABLE project_member (ctx := context.Background()// Start MySQL container- container := sharedMySQLContainer(t)+ container := testcontainer.SharedMySQLContainer(t)// Create test database_, err := container.GetDB().Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s`", databaseName))diff --git a/backend/plugin/schema/mysql/get_database_metadata_testcontainer_test.go b/backend/plugin/schema/mysql/get_database_metadata_testcontainer_test.goindex 775bfd0382..da0dbcf912 100644--- a/backend/plugin/schema/mysql/get_database_metadata_testcontainer_test.go+++ b/backend/plugin/schema/mysql/get_database_metadata_testcontainer_test.go@@ -11,6 +11,7 @@ import ("github.com/google/uuid""github.com/stretchr/testify/require"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/db")@@ -23,7 +24,7 @@ func TestGetDatabaseMetadataWithTestcontainer(t *testing.T) {ctx := context.Background()// Start shared MySQL container for all subtests- container := sharedMySQLContainer(t)+ container := testcontainer.SharedMySQLContainer(t)// Test cases with various MySQL featurestestCases := []struct {diff --git a/backend/plugin/schema/mysql/main_test.go b/backend/plugin/schema/mysql/main_test.goindex 225e382bb7..0a9c4993be 100644--- a/backend/plugin/schema/mysql/main_test.go+++ b/backend/plugin/schema/mysql/main_test.go@@ -1,50 +1,9 @@package mysqlimport (- "context"- "sync""testing""github.com/bytebase/bytebase/backend/common/testcontainer")-// The package shares one MySQL container, started on first use.-//-// Sharing it is worth a container start, and this package took three of them.-// Starting it lazily is what keeps that saving from turning into a tax on the-// tests that need no engine at all, which would otherwise pay for a container-// they never open.-var (- mysqlOnce sync.Once- mysqlContainer *testcontainer.Container- mysqlErr error-)--func TestMain(m *testing.M) {- defer func() {- if mysqlContainer != nil {- mysqlContainer.Close(context.Background())- }- }()- m.Run()-}--// sharedMySQLContainer returns the package's MySQL container, starting it on-// the first call. Tests keep isolating themselves with a per-test database,-// which is what makes one container enough.-func sharedMySQLContainer(t *testing.T) *testcontainer.Container {- t.Helper()-- mysqlOnce.Do(func() {- container, err := testcontainer.GetTestMySQLContainer(context.Background())- if err != nil {- mysqlErr = err- return- }- mysqlContainer = container- })- if mysqlErr != nil {- t.Fatalf("failed to start the shared MySQL container: %v", mysqlErr)- }- return mysqlContainer-}+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/plugin/schema/oracle/generate_migration_record_test.go b/backend/plugin/schema/oracle/generate_migration_record_test.goindex 43b086ca43..c337eafe4d 100644--- a/backend/plugin/schema/oracle/generate_migration_record_test.go+++ b/backend/plugin/schema/oracle/generate_migration_record_test.go@@ -35,6 +35,7 @@ import ("google.golang.org/protobuf/encoding/protojson""google.golang.org/protobuf/testing/protocmp"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/schema"@@ -56,7 +57,7 @@ var oracleGeneratedName = regexp.MustCompile(`ISEQ\$\$_[0-9]+|SYS_C[0-9]+`)func TestRecordGenerateMigrationFixtures(t *testing.T) {ctx := context.Background()- container := sharedOracleContainer(t)+ container := testcontainer.SharedOracleContainer(t)systemDB := container.GetDB()require.NoError(t, os.MkdirAll(generateMigrationFixtureDir, 0o755))diff --git a/backend/plugin/schema/oracle/get_database_definition_testcontainer_test.go b/backend/plugin/schema/oracle/get_database_definition_testcontainer_test.goindex 4063c5a98e..1698abe2ae 100644--- a/backend/plugin/schema/oracle/get_database_definition_testcontainer_test.go+++ b/backend/plugin/schema/oracle/get_database_definition_testcontainer_test.go@@ -11,6 +11,7 @@ import ("github.com/stretchr/testify/require""google.golang.org/protobuf/testing/protocmp"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/schema")@@ -27,7 +28,7 @@ func TestGetDatabaseDefinitionWithTestcontainer(t *testing.T) {ctx := context.Background()- container := sharedOracleContainer(t)+ container := testcontainer.SharedOracleContainer(t)// Get SYSTEM database connection for user managementsystemDB := container.GetDB()diff --git a/backend/plugin/schema/oracle/get_database_metadata_test.go b/backend/plugin/schema/oracle/get_database_metadata_test.goindex be7baf4a57..578557ccfd 100644--- a/backend/plugin/schema/oracle/get_database_metadata_test.go+++ b/backend/plugin/schema/oracle/get_database_metadata_test.go@@ -9,6 +9,7 @@ import ("github.com/google/uuid""github.com/stretchr/testify/require"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/db")@@ -743,7 +744,7 @@ COMMENT ON COLUMN ORDER_LINE_ITEMS.FULFILLMENT_STATUS IS 'Status: PENDING, PICKEfunc TestGetDatabaseMetadataWithTestcontainer(t *testing.T) {ctx := context.Background()- container := sharedOracleContainer(t)+ container := testcontainer.SharedOracleContainer(t)host := container.GetHost()port := container.GetPort()diff --git a/backend/plugin/schema/oracle/main_test.go b/backend/plugin/schema/oracle/main_test.goindex 4c22b3453d..e8a5706f97 100644--- a/backend/plugin/schema/oracle/main_test.go+++ b/backend/plugin/schema/oracle/main_test.go@@ -1,52 +1,9 @@package oracleimport (- "context"- "sync""testing""github.com/bytebase/bytebase/backend/common/testcontainer")-// The package shares one Oracle container, started on first use.-//-// Sharing it is worth a container start: the metadata and definition tests took-// one each, and an Oracle Free start is around 12 s. Starting it lazily is what-// keeps that saving from turning into a tax on everything else -- the-// generate-migration goldens, the omni parser cases and the topological-order-// cases need no engine at all, and a package-wide eager start would have made-// `go test -run TestGenerateMigration` pay 12 s for a container it never opens.-var (- oracleOnce sync.Once- oracleContainer *testcontainer.Container- oracleErr error-)--func TestMain(m *testing.M) {- defer func() {- if oracleContainer != nil {- oracleContainer.Close(context.Background())- }- }()- m.Run()-}--// sharedOracleContainer returns the package's Oracle container, starting it on-// the first call. Tests keep isolating themselves with a per-test Oracle user,-// which is what makes one container enough.-func sharedOracleContainer(t *testing.T) *testcontainer.Container {- t.Helper()-- oracleOnce.Do(func() {- container, err := testcontainer.GetOracleContainer(context.Background())- if err != nil {- oracleErr = err- return- }- oracleContainer = container- })- if oracleErr != nil {- t.Fatalf("failed to start the shared Oracle container: %v", oracleErr)- }- return oracleContainer-}+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/plugin/schema/pg/get_database_definition_testcontainer_test.go b/backend/plugin/schema/pg/get_database_definition_testcontainer_test.goindex c706663e13..bf1772d4b4 100644--- a/backend/plugin/schema/pg/get_database_definition_testcontainer_test.go+++ b/backend/plugin/schema/pg/get_database_definition_testcontainer_test.go@@ -9,6 +9,7 @@ import ("github.com/google/uuid""github.com/stretchr/testify/require"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/schema")@@ -22,7 +23,7 @@ func TestGetDatabaseDefinitionWithTestcontainer(t *testing.T) {ctx := context.Background()// Get PostgreSQL container from testcontainer.go- pgContainer := sharedPgContainer(t)+ pgContainer := testcontainer.SharedPgContainer(t)// Test cases with various PostgreSQL featurestestCases := []struct {@@ -912,7 +913,7 @@ func compareEnumsDef(t *testing.T, enumsA, enumsB []*storepb.EnumTypeMetadata) {func TestSyncCompositeTypesWithTestcontainer(t *testing.T) {ctx := context.Background()- pgContainer := sharedPgContainer(t)+ pgContainer := testcontainer.SharedPgContainer(t)dbName := fmt.Sprintf("test_sync_composite_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))_, err := pgContainer.GetDB().Exec(fmt.Sprintf("CREATE DATABASE %s", dbName))diff --git a/backend/plugin/schema/pg/main_test.go b/backend/plugin/schema/pg/main_test.goindex 96f755297b..12b1b9272c 100644--- a/backend/plugin/schema/pg/main_test.go+++ b/backend/plugin/schema/pg/main_test.go@@ -1,50 +1,9 @@package pgimport (- "context"- "sync""testing""github.com/bytebase/bytebase/backend/common/testcontainer")-// The package shares one PostgreSQL container, started on first use.-//-// Sharing it is worth a container start, and this package took two of them.-// Starting it lazily is what keeps that saving from turning into a tax on the-// tests that need no engine at all, which would otherwise pay for a container-// they never open.-var (- pgOnce sync.Once- pgContainer *testcontainer.Container- pgErr error-)--func TestMain(m *testing.M) {- defer func() {- if pgContainer != nil {- pgContainer.Close(context.Background())- }- }()- m.Run()-}--// sharedPgContainer returns the package's PostgreSQL container, starting it on-// the first call. Tests keep isolating themselves with a per-test database,-// which is what makes one container enough.-func sharedPgContainer(t *testing.T) *testcontainer.Container {- t.Helper()-- pgOnce.Do(func() {- container, err := testcontainer.GetPgContainer(context.Background())- if err != nil {- pgErr = err- return- }- pgContainer = container- })- if pgErr != nil {- t.Fatalf("failed to start the shared PostgreSQL container: %v", pgErr)- }- return pgContainer-}+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/plugin/schema/tidb/generate_migration_testcontainer_test.go b/backend/plugin/schema/tidb/generate_migration_testcontainer_test.goindex 20bcf697c3..775993d21a 100644--- a/backend/plugin/schema/tidb/generate_migration_testcontainer_test.go+++ b/backend/plugin/schema/tidb/generate_migration_testcontainer_test.go@@ -14,6 +14,7 @@ import ("github.com/stretchr/testify/require""google.golang.org/protobuf/testing/protocmp"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/schema""github.com/bytebase/bytebase/backend/store/model"@@ -29,7 +30,7 @@ func TestGenerateMigrationWithTestcontainer(t *testing.T) {}ctx := context.Background()- container := sharedTiDBContainer(t)+ container := testcontainer.SharedTiDBContainer(t)// Test cases with various schema changestestCases := []struct {diff --git a/backend/plugin/schema/tidb/get_database_definition_testcontainer_test.go b/backend/plugin/schema/tidb/get_database_definition_testcontainer_test.goindex f38401c112..238af74cb9 100644--- a/backend/plugin/schema/tidb/get_database_definition_testcontainer_test.go+++ b/backend/plugin/schema/tidb/get_database_definition_testcontainer_test.go@@ -13,6 +13,7 @@ import ("github.com/stretchr/testify/require""google.golang.org/protobuf/testing/protocmp"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/schema")@@ -25,7 +26,7 @@ func TestGetDatabaseDefinition(t *testing.T) {}ctx := context.Background()- container := sharedTiDBContainer(t)+ container := testcontainer.SharedTiDBContainer(t)type testCase struct {description string@@ -242,7 +243,7 @@ func TestGetDatabaseDefinitionWithConnectedDeps(t *testing.T) {}ctx := context.Background()- container := sharedTiDBContainer(t)+ container := testcontainer.SharedTiDBContainer(t)// Create unique test database using UUIDtestDB := fmt.Sprintf("test_%s", strings.ReplaceAll(uuid.New().String(), "-", "_"))diff --git a/backend/plugin/schema/tidb/get_database_metadata_testcontainer_test.go b/backend/plugin/schema/tidb/get_database_metadata_testcontainer_test.goindex 34bffc033d..6ba7ac8da7 100644--- a/backend/plugin/schema/tidb/get_database_metadata_testcontainer_test.go+++ b/backend/plugin/schema/tidb/get_database_metadata_testcontainer_test.go@@ -9,6 +9,7 @@ import ("github.com/google/uuid""github.com/stretchr/testify/require"+ "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store")@@ -22,7 +23,7 @@ func TestGetDatabaseMetadataWithTestcontainer(t *testing.T) {}ctx := context.Background()- container := sharedTiDBContainer(t)+ container := testcontainer.SharedTiDBContainer(t)// Test cases with various TiDB featurestestCases := []struct {diff --git a/backend/plugin/schema/tidb/main_test.go b/backend/plugin/schema/tidb/main_test.goindex 2609d8a0e9..ff37c2c076 100644--- a/backend/plugin/schema/tidb/main_test.go+++ b/backend/plugin/schema/tidb/main_test.go@@ -1,50 +1,9 @@package tidbimport (- "context"- "sync""testing""github.com/bytebase/bytebase/backend/common/testcontainer")-// The package shares one TiDB container, started on first use.-//-// Sharing it is worth a container start, and this package took four of them.-// Starting it lazily is what keeps that saving from turning into a tax on the-// tests that need no engine at all, which would otherwise pay for a container-// they never open.-var (- tidbOnce sync.Once- tidbContainer *testcontainer.Container- tidbErr error-)--func TestMain(m *testing.M) {- defer func() {- if tidbContainer != nil {- tidbContainer.Close(context.Background())- }- }()- m.Run()-}--// sharedTiDBContainer returns the package's TiDB container, starting it on-// the first call. Tests keep isolating themselves with a per-test database,-// which is what makes one container enough.-func sharedTiDBContainer(t *testing.T) *testcontainer.Container {- t.Helper()-- tidbOnce.Do(func() {- container, err := testcontainer.GetTiDBContainer(context.Background())- if err != nil {- tidbErr = err- return- }- tidbContainer = container- })- if tidbErr != nil {- t.Fatalf("failed to start the shared TiDB container: %v", tidbErr)- }- return tidbContainer-}+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/runner/plancheck/main_test.go b/backend/runner/plancheck/main_test.goindex b449e74fd2..4642ca71a5 100644--- a/backend/runner/plancheck/main_test.go+++ b/backend/runner/plancheck/main_test.go@@ -6,4 +6,4 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer")-func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/runner/schemasync/main_test.go b/backend/runner/schemasync/main_test.goindex 3df9c1015e..fca1ece9c2 100644--- a/backend/runner/schemasync/main_test.go+++ b/backend/runner/schemasync/main_test.go@@ -6,4 +6,4 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer")-func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/runner/taskrun/main_test.go b/backend/runner/taskrun/main_test.goindex 3988cbbe54..0a54580059 100644--- a/backend/runner/taskrun/main_test.go+++ b/backend/runner/taskrun/main_test.go@@ -6,4 +6,4 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer")-func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/server/main_test.go b/backend/server/main_test.goindex 4a1c42c9b2..abcc2705b4 100644--- a/backend/server/main_test.go+++ b/backend/server/main_test.go@@ -6,4 +6,4 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer")-func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/store/main_test.go b/backend/store/main_test.goindex 44e7949164..b7efaa7c4e 100644--- a/backend/store/main_test.go+++ b/backend/store/main_test.go@@ -6,4 +6,4 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer")-func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+func TestMain(m *testing.M) { testcontainer.Main(m) }diff --git a/backend/tests/action_test.go b/backend/tests/action_test.goindex f09e341497..4835ab688a 100644--- a/backend/tests/action_test.go+++ b/backend/tests/action_test.go@@ -8,6 +8,7 @@ import ("os""path/filepath""testing"+ "time""connectrpc.com/connect""github.com/stretchr/testify/require"@@ -18,459 +19,455 @@ import (v1pb "github.com/bytebase/bytebase/backend/generated-go/v1")-func TestActionCheckCommand(t *testing.T) {+func TestActionCheckCommand_ValidMigrations(t *testing.T) {t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- t.Run("ValidMigrations", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}-- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create test instance and database- database := ctl.createTestDatabase(ctx, t)+ // Create test instance and database+ database := ctl.createTestDatabase(ctx, t)- // Create test data directory- testDataDir := t.TempDir()- validMigrationsDir := filepath.Join(testDataDir, "valid-migrations")- err = os.MkdirAll(validMigrationsDir, 0755)- a.NoError(err)+ // Create test data directory+ testDataDir := t.TempDir()+ validMigrationsDir := filepath.Join(testDataDir, "valid-migrations")+ err = os.MkdirAll(validMigrationsDir, 0755)+ a.NoError(err)- // Create a valid migration file- migrationContent := `CREATE TABLE users (+ // Create a valid migration file+ migrationContent := `CREATE TABLE users (id SERIAL PRIMARY KEY,username TEXT NOT NULL UNIQUE,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`- err = os.WriteFile(filepath.Join(validMigrationsDir, "00001_create_users.sql"), []byte(migrationContent), 0644)- a.NoError(err)+ err = os.WriteFile(filepath.Join(validMigrationsDir, "00001_create_users.sql"), []byte(migrationContent), 0644)+ a.NoError(err)- // Execute check command using backend test credentials- result, err := executeActionCommand(ctx,- "check",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", filepath.Join(validMigrationsDir, "*.sql"),- "--check-release", "FAIL_ON_ERROR",- )-- a.NoError(err, "Check command should succeed for valid migrations")-- // E2E Verification for check command:- // The key expectation is that check validates files without modifying target databases-- // Verify database was NOT modified (this is the critical check)- // Query database to ensure no tables were created- metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{- Name: database.Name + "/metadata",- }))- a.NoError(err)- // Verify no user tables exist- for _, schema := range metadata.Msg.Schemas {- for _, table := range schema.Tables {- a.NotEqual("users", table.Name, "Check command should not create tables")- }+ // Execute check command using backend test credentials+ result, err := executeActionCommand(ctx,+ "check",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", filepath.Join(validMigrationsDir, "*.sql"),+ "--check-release", "FAIL_ON_ERROR",+ )++ a.NoError(err, "Check command should succeed for valid migrations")++ // E2E Verification for check command:+ // The key expectation is that check validates files without modifying target databases++ // Verify database was NOT modified (this is the critical check)+ // Query database to ensure no tables were created+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{+ Name: database.Name + "/metadata",+ }))+ a.NoError(err)+ // Verify no user tables exist+ for _, schema := range metadata.Msg.Schemas {+ for _, table := range schema.Tables {+ a.NotEqual("users", table.Name, "Check command should not create tables")}+ }++ // 4. Verify command succeeded with proper exit code+ a.Contains(result.Stdout, "", "Check should complete without errors")+}- // 4. Verify command succeeded with proper exit code- a.Contains(result.Stdout, "", "Check should complete without errors")- })+func TestActionCheckCommand_ValidMigrationsForDatabaseGroup(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- t.Run("ValidMigrationsForDatabaseGroup", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)-- // Create test instance and database- database := ctl.createTestDatabase(ctx, t)-- databaseGroup, err := ctl.databaseGroupServiceClient.CreateDatabaseGroup(ctx, connect.NewRequest(&v1pb.CreateDatabaseGroupRequest{- Parent: ctl.project.Name,- DatabaseGroupId: "test-database-group",- DatabaseGroup: &v1pb.DatabaseGroup{- Title: "test database group",- DatabaseExpr: &expr.Expr{Expression: "true"},- },- }))- a.NoError(err)+ // Create test instance and database+ database := ctl.createTestDatabase(ctx, t)- // Create test data directory- testDataDir := t.TempDir()- validMigrationsDir := filepath.Join(testDataDir, "valid-migrations")- err = os.MkdirAll(validMigrationsDir, 0755)- a.NoError(err)+ databaseGroup, err := ctl.databaseGroupServiceClient.CreateDatabaseGroup(ctx, connect.NewRequest(&v1pb.CreateDatabaseGroupRequest{+ Parent: ctl.project.Name,+ DatabaseGroupId: "test-database-group",+ DatabaseGroup: &v1pb.DatabaseGroup{+ Title: "test database group",+ DatabaseExpr: &expr.Expr{Expression: "true"},+ },+ }))+ a.NoError(err)- // Create a valid migration file- migrationContent := `CREATE TABLE users (+ // Create test data directory+ testDataDir := t.TempDir()+ validMigrationsDir := filepath.Join(testDataDir, "valid-migrations")+ err = os.MkdirAll(validMigrationsDir, 0755)+ a.NoError(err)++ // Create a valid migration file+ migrationContent := `CREATE TABLE users (id SERIAL PRIMARY KEY,username TEXT NOT NULL UNIQUE,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`- err = os.WriteFile(filepath.Join(validMigrationsDir, "00001_create_users.sql"), []byte(migrationContent), 0644)- a.NoError(err)+ err = os.WriteFile(filepath.Join(validMigrationsDir, "00001_create_users.sql"), []byte(migrationContent), 0644)+ a.NoError(err)- // Execute check command using backend test credentials- result, err := executeActionCommand(ctx,- "check",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", databaseGroup.Msg.Name,- "--file-pattern", filepath.Join(validMigrationsDir, "*.sql"),- "--check-release", "FAIL_ON_ERROR",- )-- a.NoError(err, "Check command should succeed for valid migrations")-- // E2E Verification for check command:- // The key expectation is that check validates files without modifying target databases-- // Verify database was NOT modified (this is the critical check)- // Query database to ensure no tables were created- metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{- Name: database.Name + "/metadata",- }))- a.NoError(err)- // Verify no user tables exist- for _, schema := range metadata.Msg.Schemas {- for _, table := range schema.Tables {- a.NotEqual("users", table.Name, "Check command should not create tables")- }+ // Execute check command using backend test credentials+ result, err := executeActionCommand(ctx,+ "check",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", databaseGroup.Msg.Name,+ "--file-pattern", filepath.Join(validMigrationsDir, "*.sql"),+ "--check-release", "FAIL_ON_ERROR",+ )++ a.NoError(err, "Check command should succeed for valid migrations")++ // E2E Verification for check command:+ // The key expectation is that check validates files without modifying target databases++ // Verify database was NOT modified (this is the critical check)+ // Query database to ensure no tables were created+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{+ Name: database.Name + "/metadata",+ }))+ a.NoError(err)+ // Verify no user tables exist+ for _, schema := range metadata.Msg.Schemas {+ for _, table := range schema.Tables {+ a.NotEqual("users", table.Name, "Check command should not create tables")}+ }- // 4. Verify command succeeded with proper exit code- a.Contains(result.Stdout, "", "Check should complete without errors")- })+ // 4. Verify command succeeded with proper exit code+ a.Contains(result.Stdout, "", "Check should complete without errors")+}- t.Run("PolicyViolations", func(t *testing.T) {- t.Skip("Skipping policy violations test - SQL review policies not configured in test environment")- })+func TestActionCheckCommand_PolicyViolations(t *testing.T) {+ t.Skip("Skipping policy violations test - SQL review policies not configured in test environment")+}- t.Run("SyntaxErrors", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}+func TestActionCheckCommand_SyntaxErrors(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create test database- database := ctl.createTestDatabase(ctx, t)+ // Create test database+ database := ctl.createTestDatabase(ctx, t)- // Create test data directory with syntax error migration- testDataDir := t.TempDir()- err = os.MkdirAll(testDataDir, 0755)- a.NoError(err)+ // Create test data directory with syntax error migration+ testDataDir := t.TempDir()+ err = os.MkdirAll(testDataDir, 0755)+ a.NoError(err)- // Create a migration file with obvious syntax errors- migrationContent := `INVALID SQL SYNTAX THIS IS NOT VALID SQL AT ALL!!!`- err = os.WriteFile(filepath.Join(testDataDir, "00001_syntax_error.sql"), []byte(migrationContent), 0644)- a.NoError(err)+ // Create a migration file with obvious syntax errors+ migrationContent := `INVALID SQL SYNTAX THIS IS NOT VALID SQL AT ALL!!!`+ err = os.WriteFile(filepath.Join(testDataDir, "00001_syntax_error.sql"), []byte(migrationContent), 0644)+ a.NoError(err)- // Execute check with file that has syntax errors- _, err = executeActionCommand(ctx,- "check",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", filepath.Join(testDataDir, "00001_syntax_error.sql"),- "--check-release", "FAIL_ON_ERROR",- )-- // Postgres parses the statement, so the release check reports the syntax- // error and FAIL_ON_ERROR makes the command exit with an error.- a.Error(err)- a.Contains(err.Error(), "error(s) in release check")-- // Verify NO database changes occurred- metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{- Name: database.Name + "/metadata",- }))- a.NoError(err)- // Ensure no tables were created- for _, schema := range metadata.Msg.Schemas {- for _, table := range schema.Tables {- a.NotEqual("invalid", table.Name, "Check should not create tables with syntax errors")- }+ // Execute check with file that has syntax errors+ _, err = executeActionCommand(ctx,+ "check",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", filepath.Join(testDataDir, "00001_syntax_error.sql"),+ "--check-release", "FAIL_ON_ERROR",+ )++ // Postgres parses the statement, so the release check reports the syntax+ // error and FAIL_ON_ERROR makes the command exit with an error.+ a.Error(err)+ a.Contains(err.Error(), "error(s) in release check")++ // Verify NO database changes occurred+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{+ Name: database.Name + "/metadata",+ }))+ a.NoError(err)+ // Ensure no tables were created+ for _, schema := range metadata.Msg.Schemas {+ for _, table := range schema.Tables {+ a.NotEqual("invalid", table.Name, "Check should not create tables with syntax errors")}- })+ }+}- t.Run("MultipleTargets", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}+func TestActionCheckCommand_MultipleTargets(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create multiple test databases- database1 := ctl.createTestDatabase(ctx, t)- database2 := ctl.createTestDatabase(ctx, t)+ // Create multiple test databases+ database1 := ctl.createTestDatabase(ctx, t)+ database2 := ctl.createTestDatabase(ctx, t)- // Create test data directory- testDataDir := t.TempDir()- err = os.MkdirAll(testDataDir, 0755)- a.NoError(err)+ // Create test data directory+ testDataDir := t.TempDir()+ err = os.MkdirAll(testDataDir, 0755)+ a.NoError(err)- // Create a valid migration file- migrationContent := `CREATE TABLE users (+ // Create a valid migration file+ migrationContent := `CREATE TABLE users (id SERIAL PRIMARY KEY,email VARCHAR(255) NOT NULL UNIQUE,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`- err = os.WriteFile(filepath.Join(testDataDir, "00001_create_users.sql"), []byte(migrationContent), 0644)- a.NoError(err)+ err = os.WriteFile(filepath.Join(testDataDir, "00001_create_users.sql"), []byte(migrationContent), 0644)+ a.NoError(err)- // Execute check command with multiple targets- result, err := executeActionCommand(ctx,- "check",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", fmt.Sprintf("%s,%s", database1.Name, database2.Name),- "--file-pattern", filepath.Join(testDataDir, "00001_create_users.sql"),- "--check-release", "FAIL_ON_ERROR",- )-- a.NoError(err, "Check command should succeed for multiple valid targets")-- // E2E Verification for check command with multiple targets:- // The check should validate all targets without modifying any databases-- // Verify both databases were NOT modified- for _, db := range []*v1pb.Database{database1, database2} {- metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{- Name: db.Name + "/metadata",- }))- a.NoError(err)- // Verify no user tables exist- for _, schema := range metadata.Msg.Schemas {- for _, table := range schema.Tables {- a.NotEqual("users", table.Name, "Check command should not create tables")- }+ // Execute check command with multiple targets+ result, err := executeActionCommand(ctx,+ "check",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", fmt.Sprintf("%s,%s", database1.Name, database2.Name),+ "--file-pattern", filepath.Join(testDataDir, "00001_create_users.sql"),+ "--check-release", "FAIL_ON_ERROR",+ )++ a.NoError(err, "Check command should succeed for multiple valid targets")++ // E2E Verification for check command with multiple targets:+ // The check should validate all targets without modifying any databases++ // Verify both databases were NOT modified+ for _, db := range []*v1pb.Database{database1, database2} {+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{+ Name: db.Name + "/metadata",+ }))+ a.NoError(err)+ // Verify no user tables exist+ for _, schema := range metadata.Msg.Schemas {+ for _, table := range schema.Tables {+ a.NotEqual("users", table.Name, "Check command should not create tables")}}+ }- // 4. Verify command succeeded- a.NotContains(result.Stderr, "error", "Check should complete without errors")- })+ // 4. Verify command succeeded+ a.NotContains(result.Stderr, "error", "Check should complete without errors")+}- t.Run("DeclarativeCheckValidSchema", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}+func TestActionCheckCommand_DeclarativeCheckValidSchema(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create PostgreSQL test database- database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)- defer pgContainer.Close(ctx)+ // Create PostgreSQL test database+ database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)+ defer pgContainer.Close(ctx)- // Create test data directory and schema.sql file- testDataDir := t.TempDir()- schemaContent := `CREATE TABLE public.users (+ // Create test data directory and schema.sql file+ testDataDir := t.TempDir()+ schemaContent := `CREATE TABLE public.users (id SERIAL NOT NULL,username VARCHAR(255) NOT NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,CONSTRAINT pk_users PRIMARY KEY (id),CONSTRAINT uk_users_username UNIQUE (username));`- schemaFile := filepath.Join(testDataDir, "schema.sql")- err = os.WriteFile(schemaFile, []byte(schemaContent), 0644)- a.NoError(err)+ schemaFile := filepath.Join(testDataDir, "schema.sql")+ err = os.WriteFile(schemaFile, []byte(schemaContent), 0644)+ a.NoError(err)- // Execute declarative check command- _, err = executeActionCommand(ctx,- "check",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", schemaFile,- "--check-release", "FAIL_ON_ERROR",- "--declarative",- )-- a.NoError(err, "Declarative check command should succeed for valid schema")- })-- t.Run("DeclarativeCheckMultipleFiles", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}-- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ // Execute declarative check command+ _, err = executeActionCommand(ctx,+ "check",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", schemaFile,+ "--check-release", "FAIL_ON_ERROR",+ "--declarative",+ )++ a.NoError(err, "Declarative check command should succeed for valid schema")+}- // Create PostgreSQL test database- database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)- defer pgContainer.Close(ctx)+func TestActionCheckCommand_DeclarativeCheckMultipleFiles(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- // Create test data directory with multiple SQL files- testDataDir := t.TempDir()+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create users.sql- usersContent := `CREATE TABLE public.users (+ // Create PostgreSQL test database+ database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)+ defer pgContainer.Close(ctx)++ // Create test data directory with multiple SQL files+ testDataDir := t.TempDir()++ // Create users.sql+ usersContent := `CREATE TABLE public.users (id SERIAL NOT NULL,username VARCHAR(255) NOT NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,CONSTRAINT pk_users PRIMARY KEY (id),CONSTRAINT uk_users_username UNIQUE (username));`- usersFile := filepath.Join(testDataDir, "users.sql")- err = os.WriteFile(usersFile, []byte(usersContent), 0644)- a.NoError(err)+ usersFile := filepath.Join(testDataDir, "users.sql")+ err = os.WriteFile(usersFile, []byte(usersContent), 0644)+ a.NoError(err)- // Create products.sql- productsContent := `CREATE TABLE public.products (+ // Create products.sql+ productsContent := `CREATE TABLE public.products (id SERIAL NOT NULL,name VARCHAR(255) NOT NULL,price DECIMAL(10,2),CONSTRAINT pk_products PRIMARY KEY (id));`- productsFile := filepath.Join(testDataDir, "products.sql")- err = os.WriteFile(productsFile, []byte(productsContent), 0644)- a.NoError(err)+ productsFile := filepath.Join(testDataDir, "products.sql")+ err = os.WriteFile(productsFile, []byte(productsContent), 0644)+ a.NoError(err)- // Execute declarative check command with multiple files- _, err = executeActionCommand(ctx,- "check",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", filepath.Join(testDataDir, "*.sql"),- "--check-release", "FAIL_ON_ERROR",- "--declarative",- )-- a.NoError(err, "Declarative check command should succeed with multiple files")- })-- t.Run("DeclarativeCheckWithDatabaseGroup", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}-- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)-- // Keeps MySQL. Porting this to Postgres was tried and reverted: the- // declarative release check returns three errors against the same schema- // on Postgres, so the engine changes the result here rather than being- // incidental, and what those errors are is its own question.- _, mysqlContainer := ctl.createTestMySQLDatabase(ctx, t)- defer mysqlContainer.Close(ctx)-- // Create database group- databaseGroup, err := ctl.databaseGroupServiceClient.CreateDatabaseGroup(ctx, connect.NewRequest(&v1pb.CreateDatabaseGroupRequest{- Parent: ctl.project.Name,- DatabaseGroupId: "test-declarative-check-group",- DatabaseGroup: &v1pb.DatabaseGroup{- Title: "Test Declarative Check Group",- DatabaseExpr: &expr.Expr{Expression: "true"},- },- }))- a.NoError(err)+ // Execute declarative check command with multiple files+ _, err = executeActionCommand(ctx,+ "check",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", filepath.Join(testDataDir, "*.sql"),+ "--check-release", "FAIL_ON_ERROR",+ "--declarative",+ )++ a.NoError(err, "Declarative check command should succeed with multiple files")+}- // Create test data directory and schema.sql file- testDataDir := t.TempDir()- schemaContent := `CREATE TABLE users (+func TestActionCheckCommand_DeclarativeCheckWithDatabaseGroup(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}++ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ // Keeps MySQL. Porting this to Postgres was tried and reverted: the+ // declarative release check returns three errors against the same schema+ // on Postgres, so the engine changes the result here rather than being+ // incidental, and what those errors are is its own question.+ _, mysqlContainer := ctl.createTestMySQLDatabase(ctx, t)+ defer mysqlContainer.Close(ctx)++ // Create database group+ databaseGroup, err := ctl.databaseGroupServiceClient.CreateDatabaseGroup(ctx, connect.NewRequest(&v1pb.CreateDatabaseGroupRequest{+ Parent: ctl.project.Name,+ DatabaseGroupId: "test-declarative-check-group",+ DatabaseGroup: &v1pb.DatabaseGroup{+ Title: "Test Declarative Check Group",+ DatabaseExpr: &expr.Expr{Expression: "true"},+ },+ }))+ a.NoError(err)++ // Create test data directory and schema.sql file+ testDataDir := t.TempDir()+ schemaContent := `CREATE TABLE users (id SERIAL PRIMARY KEY,username VARCHAR(255) NOT NULL UNIQUE,email VARCHAR(255));`- schemaFile := filepath.Join(testDataDir, "schema.sql")- err = os.WriteFile(schemaFile, []byte(schemaContent), 0644)- a.NoError(err)+ schemaFile := filepath.Join(testDataDir, "schema.sql")+ err = os.WriteFile(schemaFile, []byte(schemaContent), 0644)+ a.NoError(err)- // Execute declarative check command with database group- _, err = executeActionCommand(ctx,- "check",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", databaseGroup.Msg.Name,- "--file-pattern", schemaFile,- "--check-release", "FAIL_ON_ERROR",- "--declarative",- )-- a.NoError(err, "Declarative check command should succeed with database group")- })-- t.Run("DeclarativeCheckSyntaxErrors", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}-- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ // Execute declarative check command with database group+ _, err = executeActionCommand(ctx,+ "check",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", databaseGroup.Msg.Name,+ "--file-pattern", schemaFile,+ "--check-release", "FAIL_ON_ERROR",+ "--declarative",+ )++ a.NoError(err, "Declarative check command should succeed with database group")+}++func TestActionCheckCommand_DeclarativeCheckSyntaxErrors(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}++ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create PostgreSQL test database- database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)- defer pgContainer.Close(ctx)+ // Create PostgreSQL test database+ database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)+ defer pgContainer.Close(ctx)- // Create test data directory with invalid SQL- testDataDir := t.TempDir()- invalidSchemaContent := `CREATE TABLE users (+ // Create test data directory with invalid SQL+ testDataDir := t.TempDir()+ invalidSchemaContent := `CREATE TABLE users (id SERIAL PRIMARY KEY,username VARCHAR(255) NOT NULL UNIQUEemail VARCHAR(255) -- Missing comma after previous column);`- schemaFile := filepath.Join(testDataDir, "schema.sql")- err = os.WriteFile(schemaFile, []byte(invalidSchemaContent), 0644)- a.NoError(err)+ schemaFile := filepath.Join(testDataDir, "schema.sql")+ err = os.WriteFile(schemaFile, []byte(invalidSchemaContent), 0644)+ a.NoError(err)- // Execute declarative check command with syntax error- _, err = executeActionCommand(ctx,- "check",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", schemaFile,- "--check-release", "FAIL_ON_ERROR",- "--declarative",- )-- // The command may complete but should report the syntax issue- a.Error(err, "should error")- a.Contains(err.Error(), "found 1 error(s) in release check. view on Bytebase")- })+ // Execute declarative check command with syntax error+ _, err = executeActionCommand(ctx,+ "check",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", schemaFile,+ "--check-release", "FAIL_ON_ERROR",+ "--declarative",+ )++ // The command may complete but should report the syntax issue+ a.Error(err, "should error")+ a.Contains(err.Error(), "found 1 error(s) in release check. view on Bytebase")}// ActionResult holds the result of executing an action command@@ -486,6 +483,9 @@ func executeActionCommand(ctx context.Context, args ...string) (*ActionResult, e// Create new world instance for test isolationw := world.NewWorld()w.Platform = world.LocalPlatform+ // The release default of 5 s between rollout status polls was most of+ // these tests' time; a rollout here finishes in well under a second.+ w.RolloutPollInterval = 300 * time.Millisecond// Create new command instance using the factory functioncmd := command.NewRootCommand(w)@@ -647,1113 +647,1101 @@ func (ctl *controller) createTestPostgreSQLDatabase(ctx context.Context, t *testreturn databaseResp.Msg, pgContainer}-func TestActionRolloutCommand(t *testing.T) {+func TestActionRolloutCommand_BasicRollout(t *testing.T) {t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- t.Run("BasicRollout", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}-- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create test database- database := ctl.createTestDatabase(ctx, t)+ // Create test database+ database := ctl.createTestDatabase(ctx, t)- // Create test data directory and migration file- testDataDir := t.TempDir()- migrationContent := `CREATE TABLE users (+ // Create test data directory and migration file+ testDataDir := t.TempDir()+ migrationContent := `CREATE TABLE users (id SERIAL PRIMARY KEY,username TEXT NOT NULL UNIQUE,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`- migrationFile := filepath.Join(testDataDir, "00001_create_users.sql")- err = os.WriteFile(migrationFile, []byte(migrationContent), 0644)- a.NoError(err)+ migrationFile := filepath.Join(testDataDir, "00001_create_users.sql")+ err = os.WriteFile(migrationFile, []byte(migrationContent), 0644)+ a.NoError(err)- // Create output file- outputFile := filepath.Join(t.TempDir(), "rollout-output.json")-- // Execute rollout- result, err := executeActionCommand(ctx,- "rollout",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", migrationFile,- "--target-stage", "environments/prod",- "--output", outputFile,- )-- a.NoError(err, "Rollout command should succeed")-- // E2E Verification: Check server state for complete rollout lifecycle-- // 1. Verify plan was created- plans, err := ctl.planServiceClient.ListPlans(ctx, connect.NewRequest(&v1pb.ListPlansRequest{- Parent: ctl.project.Name,- }))- a.NoError(err)- a.NotEmpty(plans.Msg.Plans, "Expected plan to be created")- plan := plans.Msg.Plans[0]+ // Create output file+ outputFile := filepath.Join(t.TempDir(), "rollout-output.json")++ // Execute rollout+ result, err := executeActionCommand(ctx,+ "rollout",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", migrationFile,+ "--target-stage", "environments/prod",+ "--output", outputFile,+ )++ a.NoError(err, "Rollout command should succeed")++ // E2E Verification: Check server state for complete rollout lifecycle++ // 1. Verify plan was created+ plans, err := ctl.planServiceClient.ListPlans(ctx, connect.NewRequest(&v1pb.ListPlansRequest{+ Parent: ctl.project.Name,+ }))+ a.NoError(err)+ a.NotEmpty(plans.Msg.Plans, "Expected plan to be created")+ plan := plans.Msg.Plans[0]- // 2. Verify release was created with correct title- releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{- Parent: ctl.project.Name,- }))- a.NoError(err)- a.Len(releases.Msg.Releases, 1, "Expected exactly one release")- release := releases.Msg.Releases[0]+ // 2. Verify release was created with correct title+ releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{+ Parent: ctl.project.Name,+ }))+ a.NoError(err)+ a.Len(releases.Msg.Releases, 1, "Expected exactly one release")+ release := releases.Msg.Releases[0]- // 3. Verify rollout was created and completed- rollouts, err := ctl.rolloutServiceClient.ListRollouts(ctx, connect.NewRequest(&v1pb.ListRolloutsRequest{- Parent: ctl.project.Name,- }))- a.NoError(err)- a.NotEmpty(rollouts.Msg.Rollouts, "Expected rollout to be created")- rollout := rollouts.Msg.Rollouts[0]- a.Equal(rollout.Name, result.OutputJSON["rollout"])-- // Verify rollout completed by checking all task statuses- for _, stage := range rollout.Stages {- for _, task := range stage.Tasks {- a.True(task.Status == v1pb.Task_DONE || task.Status == v1pb.Task_SKIPPED,- "Task %s should be completed (DONE or SKIPPED), got %s", task.Name, task.Status.String())- }+ // 3. Verify rollout was created and completed+ rollouts, err := ctl.rolloutServiceClient.ListRollouts(ctx, connect.NewRequest(&v1pb.ListRolloutsRequest{+ Parent: ctl.project.Name,+ }))+ a.NoError(err)+ a.NotEmpty(rollouts.Msg.Rollouts, "Expected rollout to be created")+ rollout := rollouts.Msg.Rollouts[0]+ a.Equal(rollout.Name, result.OutputJSON["rollout"])++ // Verify rollout completed by checking all task statuses+ for _, stage := range rollout.Stages {+ for _, task := range stage.Tasks {+ a.True(task.Status == v1pb.Task_DONE || task.Status == v1pb.Task_SKIPPED,+ "Task %s should be completed (DONE or SKIPPED), got %s", task.Name, task.Status.String())}+ }- // 4. Verify database schema was actually changed- metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{- Name: database.Name + "/metadata",- }))- a.NoError(err)- // Find the users table in metadata if schema sync worked- foundUsersTable := false- for _, schema := range metadata.Msg.Schemas {- for _, table := range schema.Tables {- if table.Name == "users" {- foundUsersTable = true- // Verify table structure- a.GreaterOrEqual(len(table.Columns), 2, "Expected at least 2 columns")- }+ // 4. Verify database schema was actually changed+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{+ Name: database.Name + "/metadata",+ }))+ a.NoError(err)+ // Find the users table in metadata if schema sync worked+ foundUsersTable := false+ for _, schema := range metadata.Msg.Schemas {+ for _, table := range schema.Tables {+ if table.Name == "users" {+ foundUsersTable = true+ // Verify table structure+ a.GreaterOrEqual(len(table.Columns), 2, "Expected at least 2 columns")}}- a.True(foundUsersTable, "Users table not found in metadata, but rollout completed successfully")+ }+ a.True(foundUsersTable, "Users table not found in metadata, but rollout completed successfully")- // 5. Verify database revision was updated- updatedDatabase, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{- Name: database.Name,- }))- a.NoError(err)- a.NotEmpty(updatedDatabase.Msg.Release, "Database release not set, but rollout completed successfully")- a.Equal(release.Name, updatedDatabase.Msg.Release, "Database release should match the applied release")+ // 5. Verify database revision was updated+ updatedDatabase, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{+ Name: database.Name,+ }))+ a.NoError(err)+ a.NotEmpty(updatedDatabase.Msg.Release, "Database release not set, but rollout completed successfully")+ a.Equal(release.Name, updatedDatabase.Msg.Release, "Database release should match the applied release")- // 6. Verify change history was recorded- changelogs, err := ctl.changelogServiceClient.ListChangelogs(ctx, connect.NewRequest(&v1pb.ListChangelogsRequest{- Parent: database.Name,- }))- a.NoError(err)- a.NotEmpty(changelogs.Msg.Changelogs, "No change history found, but rollout completed successfully")+ // 6. Verify change history was recorded+ changelogs, err := ctl.changelogServiceClient.ListChangelogs(ctx, connect.NewRequest(&v1pb.ListChangelogsRequest{+ Parent: database.Name,+ }))+ a.NoError(err)+ a.NotEmpty(changelogs.Msg.Changelogs, "No change history found, but rollout completed successfully")- revisions, err := ctl.revisionServiceClient.ListRevisions(ctx, connect.NewRequest(&v1pb.ListRevisionsRequest{- Parent: database.Name,- }))- a.NoError(err)- a.NotEmpty(revisions.Msg.Revisions, "No revision found, but rollout completed successfully")- a.Len(revisions.Msg.Revisions, 1, "Expected exactly one revision")- revision := revisions.Msg.Revisions[0]- a.Equal("00001", revision.Version)-- // 7. Verify output file contains server resource names- var output map[string]string- data, err := os.ReadFile(outputFile)- a.NoError(err)- err = json.Unmarshal(data, &output)- a.NoError(err)+ revisions, err := ctl.revisionServiceClient.ListRevisions(ctx, connect.NewRequest(&v1pb.ListRevisionsRequest{+ Parent: database.Name,+ }))+ a.NoError(err)+ a.NotEmpty(revisions.Msg.Revisions, "No revision found, but rollout completed successfully")+ a.Len(revisions.Msg.Revisions, 1, "Expected exactly one revision")+ revision := revisions.Msg.Revisions[0]+ a.Equal("00001", revision.Version)++ // 7. Verify output file contains server resource names+ var output map[string]string+ data, err := os.ReadFile(outputFile)+ a.NoError(err)+ err = json.Unmarshal(data, &output)+ a.NoError(err)- a.Equal(release.Name, output["release"], "Output should contain actual release name")- a.Equal(plan.Name, output["plan"], "Output should contain actual plan name")- a.Equal(rollout.Name, output["rollout"], "Output should contain actual rollout name")+ a.Equal(release.Name, output["release"], "Output should contain actual release name")+ a.Equal(plan.Name, output["plan"], "Output should contain actual plan name")+ a.Equal(rollout.Name, output["rollout"], "Output should contain actual rollout name")- // 8. Verify command output- a.NotContains(result.Stderr, "error", "Rollout should complete without errors")- })+ // 8. Verify command output+ a.NotContains(result.Stderr, "error", "Rollout should complete without errors")+}- t.Run("MultipleFiles", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}+func TestActionRolloutCommand_MultipleFiles(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create test database- database := ctl.createTestDatabase(ctx, t)+ // Create test database+ database := ctl.createTestDatabase(ctx, t)- // Create test data directory and multiple migration files- testDataDir := t.TempDir()+ // Create test data directory and multiple migration files+ testDataDir := t.TempDir()- // Create 00001_create_users.sql- migrationContent1 := `CREATE TABLE users (+ // Create 00001_create_users.sql+ migrationContent1 := `CREATE TABLE users (id SERIAL PRIMARY KEY,username TEXT NOT NULL UNIQUE,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`- err = os.WriteFile(filepath.Join(testDataDir, "00001_create_users.sql"), []byte(migrationContent1), 0644)- a.NoError(err)+ err = os.WriteFile(filepath.Join(testDataDir, "00001_create_users.sql"), []byte(migrationContent1), 0644)+ a.NoError(err)- // Create 00002_add_email.sql- migrationContent2 := `ALTER TABLE users ADD COLUMN email TEXT;`- err = os.WriteFile(filepath.Join(testDataDir, "00002_add_email.sql"), []byte(migrationContent2), 0644)- a.NoError(err)+ // Create 00002_add_email.sql+ migrationContent2 := `ALTER TABLE users ADD COLUMN email TEXT;`+ err = os.WriteFile(filepath.Join(testDataDir, "00002_add_email.sql"), []byte(migrationContent2), 0644)+ a.NoError(err)- // Create 00003_create_index.sql- migrationContent3 := `CREATE INDEX idx_users_username ON users(username);`- err = os.WriteFile(filepath.Join(testDataDir, "00003_create_index.sql"), []byte(migrationContent3), 0644)- a.NoError(err)+ // Create 00003_create_index.sql+ migrationContent3 := `CREATE INDEX idx_users_username ON users(username);`+ err = os.WriteFile(filepath.Join(testDataDir, "00003_create_index.sql"), []byte(migrationContent3), 0644)+ a.NoError(err)- // Create output file- outputFile := filepath.Join(t.TempDir(), "rollout-output.json")-- // Execute rollout with multiple migration files- result, err := executeActionCommand(ctx,- "rollout",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", filepath.Join(testDataDir, "0000*.sql"),- "--target-stage", "environments/prod",- "--output", outputFile,- )-- a.NoError(err, "Rollout command should succeed with multiple files")-- // E2E Verification: Check server state for complete rollout lifecycle-- // 1. Verify plan was created- plans, err := ctl.planServiceClient.ListPlans(ctx, connect.NewRequest(&v1pb.ListPlansRequest{- Parent: ctl.project.Name,- }))- a.NoError(err)- a.NotEmpty(plans.Msg.Plans, "Expected plan to be created")- plan := plans.Msg.Plans[0]+ // Create output file+ outputFile := filepath.Join(t.TempDir(), "rollout-output.json")++ // Execute rollout with multiple migration files+ result, err := executeActionCommand(ctx,+ "rollout",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", filepath.Join(testDataDir, "0000*.sql"),+ "--target-stage", "environments/prod",+ "--output", outputFile,+ )++ a.NoError(err, "Rollout command should succeed with multiple files")++ // E2E Verification: Check server state for complete rollout lifecycle++ // 1. Verify plan was created+ plans, err := ctl.planServiceClient.ListPlans(ctx, connect.NewRequest(&v1pb.ListPlansRequest{+ Parent: ctl.project.Name,+ }))+ a.NoError(err)+ a.NotEmpty(plans.Msg.Plans, "Expected plan to be created")+ plan := plans.Msg.Plans[0]- // 2. Verify release was created with correct title- releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{- Parent: ctl.project.Name,+ // 2. Verify release was created with correct title+ releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{+ Parent: ctl.project.Name,+ }))+ a.NoError(err)+ a.Len(releases.Msg.Releases, 1, "Expected exactly one release")+ release := releases.Msg.Releases[0]++ // Verify release files+ a.Len(release.Files, 3, "Expected exactly 3 files in release")+ // Verify each file has correct version and path+ for _, f := range release.Files {+ a.Contains(f.Path, f.Version, "File path %s should contain version %s", f.Path, f.Version)+ }+ // Verify specific files exist+ fileVersions := make(map[string]string)+ for _, f := range release.Files {+ fileVersions[f.Version] = f.Path+ }+ a.Contains(fileVersions, "00001", "Should have file with version 00001")+ a.Contains(fileVersions["00001"], "00001_create_users.sql", "File 00001 should be create_users")+ a.Contains(fileVersions, "00002", "Should have file with version 00002")+ a.Contains(fileVersions["00002"], "00002_add_email.sql", "File 00002 should be add_email")+ a.Contains(fileVersions, "00003", "Should have file with version 00003")+ a.Contains(fileVersions["00003"], "00003_create_index.sql", "File 00003 should be create_index")++ // Verify release file contents match original files+ expectedContents := map[string]string{+ "00001": migrationContent1,+ "00002": migrationContent2,+ "00003": migrationContent3,+ }+ for _, f := range release.Files {+ a.NotEmpty(f.Sheet, "File %s should have a sheet", f.Path)+ sheet, err := ctl.sheetServiceClient.GetSheet(ctx, connect.NewRequest(&v1pb.GetSheetRequest{+ Name: f.Sheet,+ Raw: true,}))a.NoError(err)- a.Len(releases.Msg.Releases, 1, "Expected exactly one release")- release := releases.Msg.Releases[0]-- // Verify release files- a.Len(release.Files, 3, "Expected exactly 3 files in release")- // Verify each file has correct version and path- for _, f := range release.Files {- a.Contains(f.Path, f.Version, "File path %s should contain version %s", f.Path, f.Version)- }- // Verify specific files exist- fileVersions := make(map[string]string)- for _, f := range release.Files {- fileVersions[f.Version] = f.Path- }- a.Contains(fileVersions, "00001", "Should have file with version 00001")- a.Contains(fileVersions["00001"], "00001_create_users.sql", "File 00001 should be create_users")- a.Contains(fileVersions, "00002", "Should have file with version 00002")- a.Contains(fileVersions["00002"], "00002_add_email.sql", "File 00002 should be add_email")- a.Contains(fileVersions, "00003", "Should have file with version 00003")- a.Contains(fileVersions["00003"], "00003_create_index.sql", "File 00003 should be create_index")-- // Verify release file contents match original files- expectedContents := map[string]string{- "00001": migrationContent1,- "00002": migrationContent2,- "00003": migrationContent3,- }- for _, f := range release.Files {- a.NotEmpty(f.Sheet, "File %s should have a sheet", f.Path)- sheet, err := ctl.sheetServiceClient.GetSheet(ctx, connect.NewRequest(&v1pb.GetSheetRequest{- Name: f.Sheet,- Raw: true,- }))- a.NoError(err)- expectedContent, ok := expectedContents[f.Version]- a.True(ok, "Unexpected version %s", f.Version)- a.Equal(expectedContent, string(sheet.Msg.Content), "File %s content should match original", f.Path)- }+ expectedContent, ok := expectedContents[f.Version]+ a.True(ok, "Unexpected version %s", f.Version)+ a.Equal(expectedContent, string(sheet.Msg.Content), "File %s content should match original", f.Path)+ }- // 3. Verify rollout was created and completed- rollouts, err := ctl.rolloutServiceClient.ListRollouts(ctx, connect.NewRequest(&v1pb.ListRolloutsRequest{- Parent: ctl.project.Name,- }))- a.NoError(err)- a.NotEmpty(rollouts.Msg.Rollouts, "Expected rollout to be created")- rollout := rollouts.Msg.Rollouts[0]- a.Equal(rollout.Name, result.OutputJSON["rollout"])-- // Verify rollout completed by checking all task statuses- for _, stage := range rollout.Stages {- for _, task := range stage.Tasks {- a.True(task.Status == v1pb.Task_DONE || task.Status == v1pb.Task_SKIPPED,- "Task %s should be completed (DONE or SKIPPED), got %s", task.Name, task.Status.String())- }+ // 3. Verify rollout was created and completed+ rollouts, err := ctl.rolloutServiceClient.ListRollouts(ctx, connect.NewRequest(&v1pb.ListRolloutsRequest{+ Parent: ctl.project.Name,+ }))+ a.NoError(err)+ a.NotEmpty(rollouts.Msg.Rollouts, "Expected rollout to be created")+ rollout := rollouts.Msg.Rollouts[0]+ a.Equal(rollout.Name, result.OutputJSON["rollout"])++ // Verify rollout completed by checking all task statuses+ for _, stage := range rollout.Stages {+ for _, task := range stage.Tasks {+ a.True(task.Status == v1pb.Task_DONE || task.Status == v1pb.Task_SKIPPED,+ "Task %s should be completed (DONE or SKIPPED), got %s", task.Name, task.Status.String())}+ }- // 4. Verify database schema was actually changed- metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{- Name: database.Name + "/metadata",- }))- a.NoError(err)-- // Check for users table (from 00001_create_users.sql)- foundUsersTable := false- foundEmailColumn := false- foundUsernameIndex := false+ // 4. Verify database schema was actually changed+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{+ Name: database.Name + "/metadata",+ }))+ a.NoError(err)- for _, schema := range metadata.Msg.Schemas {- for _, table := range schema.Tables {- if table.Name == "users" {- foundUsersTable = true- // Check for email column (from 00002_add_email.sql)- for _, col := range table.Columns {- if col.Name == "email" {- foundEmailColumn = true- }+ // Check for users table (from 00001_create_users.sql)+ foundUsersTable := false+ foundEmailColumn := false+ foundUsernameIndex := false++ for _, schema := range metadata.Msg.Schemas {+ for _, table := range schema.Tables {+ if table.Name == "users" {+ foundUsersTable = true+ // Check for email column (from 00002_add_email.sql)+ for _, col := range table.Columns {+ if col.Name == "email" {+ foundEmailColumn = true}- // Check for index (from 00003_create_index.sql)- for _, index := range table.Indexes {- if index.Name == "idx_users_username" {- foundUsernameIndex = true- }+ }+ // Check for index (from 00003_create_index.sql)+ for _, index := range table.Indexes {+ if index.Name == "idx_users_username" {+ foundUsernameIndex = true}}}}+ }- a.True(foundUsersTable, "Users table should exist after rollout")- a.True(foundEmailColumn, "Email column should exist after rollout")- a.True(foundUsernameIndex, "Username index should exist after rollout")+ a.True(foundUsersTable, "Users table should exist after rollout")+ a.True(foundEmailColumn, "Email column should exist after rollout")+ a.True(foundUsernameIndex, "Username index should exist after rollout")- // 5. Verify database revision was updated- updatedDatabase, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{- Name: database.Name,- }))- a.NoError(err)- a.NotEmpty(updatedDatabase.Msg.Release, "Database release not set, but rollout completed successfully")- a.Equal(release.Name, updatedDatabase.Msg.Release, "Database release should match the applied release")-- // 6. Verify change history was recorded- // Note: Versioned releases create one MIGRATE changelog for the entire release (not per file)- // Plus a BASELINE changelog if this is the first migration for the database- changelogs, err := ctl.changelogServiceClient.ListChangelogs(ctx, connect.NewRequest(&v1pb.ListChangelogsRequest{- Parent: database.Name,- }))- a.NoError(err)- // Expect at least 1 changelog for the versioned release- a.GreaterOrEqual(len(changelogs.Msg.Changelogs), 1, "Expected at least 1 changelog for the versioned release")+ // 5. Verify database revision was updated+ updatedDatabase, err := ctl.databaseServiceClient.GetDatabase(ctx, connect.NewRequest(&v1pb.GetDatabaseRequest{+ Name: database.Name,+ }))+ a.NoError(err)+ a.NotEmpty(updatedDatabase.Msg.Release, "Database release not set, but rollout completed successfully")+ a.Equal(release.Name, updatedDatabase.Msg.Release, "Database release should match the applied release")++ // 6. Verify change history was recorded+ // Note: Versioned releases create one MIGRATE changelog for the entire release (not per file)+ // Plus a BASELINE changelog if this is the first migration for the database+ changelogs, err := ctl.changelogServiceClient.ListChangelogs(ctx, connect.NewRequest(&v1pb.ListChangelogsRequest{+ Parent: database.Name,+ }))+ a.NoError(err)+ // Expect at least 1 changelog for the versioned release+ a.GreaterOrEqual(len(changelogs.Msg.Changelogs), 1, "Expected at least 1 changelog for the versioned release")- revisions, err := ctl.revisionServiceClient.ListRevisions(ctx, connect.NewRequest(&v1pb.ListRevisionsRequest{- Parent: database.Name,- }))- a.NoError(err)- a.NotEmpty(revisions.Msg.Revisions, "No revision found, but rollout completed successfully")- a.Len(revisions.Msg.Revisions, 3, "Expected exactly three revisions")- // Check last revision version. Revisions are ordered by version desc- lastRevision := revisions.Msg.Revisions[0]- a.Equal("00003", lastRevision.Version)-- // 7. Verify output file contains server resource names- var output map[string]string- data, err := os.ReadFile(outputFile)- a.NoError(err)- err = json.Unmarshal(data, &output)- a.NoError(err)+ revisions, err := ctl.revisionServiceClient.ListRevisions(ctx, connect.NewRequest(&v1pb.ListRevisionsRequest{+ Parent: database.Name,+ }))+ a.NoError(err)+ a.NotEmpty(revisions.Msg.Revisions, "No revision found, but rollout completed successfully")+ a.Len(revisions.Msg.Revisions, 3, "Expected exactly three revisions")+ // Check last revision version. Revisions are ordered by version desc+ lastRevision := revisions.Msg.Revisions[0]+ a.Equal("00003", lastRevision.Version)++ // 7. Verify output file contains server resource names+ var output map[string]string+ data, err := os.ReadFile(outputFile)+ a.NoError(err)+ err = json.Unmarshal(data, &output)+ a.NoError(err)++ a.Equal(release.Name, output["release"], "Output should contain actual release name")+ a.Equal(plan.Name, output["plan"], "Output should contain actual plan name")+ a.Equal(rollout.Name, output["rollout"], "Output should contain actual rollout name")- a.Equal(release.Name, output["release"], "Output should contain actual release name")- a.Equal(plan.Name, output["plan"], "Output should contain actual plan name")- a.Equal(rollout.Name, output["rollout"], "Output should contain actual rollout name")+ // 8. Verify command output+ a.NotContains(result.Stderr, "error", "Multi-file rollout should complete without errors")+}- // 8. Verify command output- a.NotContains(result.Stderr, "error", "Multi-file rollout should complete without errors")- })+func TestActionRolloutCommand_FileContentVersionMatch(t *testing.T) {+ // This test verifies that file content matches the correct version+ // when lexicographical order differs from version order+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- t.Run("FileContentVersionMatch", func(t *testing.T) {- // This test verifies that file content matches the correct version- // when lexicographical order differs from version order- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ // Create test database+ database := ctl.createTestDatabase(ctx, t)- // Create test database- database := ctl.createTestDatabase(ctx, t)+ // Create test data directory with files where lex order != version order+ testDataDir := t.TempDir()- // Create test data directory with files where lex order != version order- testDataDir := t.TempDir()+ // Lexicographical order: v1, v10, v2+ // Version numeric order: 1, 2, 10+ migrationContent1 := `CREATE TABLE first_table (id INTEGER);`+ migrationContent2 := `CREATE TABLE second_table (id INTEGER);`+ migrationContent10 := `CREATE TABLE tenth_table (id INTEGER);`- // Lexicographical order: v1, v10, v2- // Version numeric order: 1, 2, 10- migrationContent1 := `CREATE TABLE first_table (id INTEGER);`- migrationContent2 := `CREATE TABLE second_table (id INTEGER);`- migrationContent10 := `CREATE TABLE tenth_table (id INTEGER);`+ err = os.WriteFile(filepath.Join(testDataDir, "v1_first.sql"), []byte(migrationContent1), 0644)+ a.NoError(err)+ err = os.WriteFile(filepath.Join(testDataDir, "v2_second.sql"), []byte(migrationContent2), 0644)+ a.NoError(err)+ err = os.WriteFile(filepath.Join(testDataDir, "v10_tenth.sql"), []byte(migrationContent10), 0644)+ a.NoError(err)- err = os.WriteFile(filepath.Join(testDataDir, "v1_first.sql"), []byte(migrationContent1), 0644)- a.NoError(err)- err = os.WriteFile(filepath.Join(testDataDir, "v2_second.sql"), []byte(migrationContent2), 0644)- a.NoError(err)- err = os.WriteFile(filepath.Join(testDataDir, "v10_tenth.sql"), []byte(migrationContent10), 0644)- a.NoError(err)+ // Execute rollout+ _, err = executeActionCommand(ctx,+ "rollout",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", filepath.Join(testDataDir, "v*.sql"),+ "--target-stage", "environments/prod",+ )+ a.NoError(err, "Rollout command should succeed")++ // Verify release files have correct content for each version+ releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{+ Parent: ctl.project.Name,+ }))+ a.NoError(err)+ a.Len(releases.Msg.Releases, 1, "Expected exactly one release")+ release := releases.Msg.Releases[0]+ a.Len(release.Files, 3, "Expected exactly 3 files in release")++ // Build expected content map by version+ expectedContents := map[string]string{+ "1": migrationContent1,+ "2": migrationContent2,+ "10": migrationContent10,+ }- // Execute rollout- _, err = executeActionCommand(ctx,- "rollout",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", filepath.Join(testDataDir, "v*.sql"),- "--target-stage", "environments/prod",- )- a.NoError(err, "Rollout command should succeed")-- // Verify release files have correct content for each version- releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{- Parent: ctl.project.Name,+ // Verify each file's content matches its version+ for _, f := range release.Files {+ a.NotEmpty(f.Sheet, "File %s should have a sheet", f.Path)+ sheet, err := ctl.sheetServiceClient.GetSheet(ctx, connect.NewRequest(&v1pb.GetSheetRequest{+ Name: f.Sheet,+ Raw: true,}))a.NoError(err)- a.Len(releases.Msg.Releases, 1, "Expected exactly one release")- release := releases.Msg.Releases[0]- a.Len(release.Files, 3, "Expected exactly 3 files in release")-- // Build expected content map by version- expectedContents := map[string]string{- "1": migrationContent1,- "2": migrationContent2,- "10": migrationContent10,- }-- // Verify each file's content matches its version- for _, f := range release.Files {- a.NotEmpty(f.Sheet, "File %s should have a sheet", f.Path)- sheet, err := ctl.sheetServiceClient.GetSheet(ctx, connect.NewRequest(&v1pb.GetSheetRequest{- Name: f.Sheet,- Raw: true,- }))- a.NoError(err)- expectedContent, ok := expectedContents[f.Version]- a.True(ok, "Unexpected version %s", f.Version)- a.Equal(expectedContent, string(sheet.Msg.Content),- "File %s with version %s should contain '%s' but got '%s'",- f.Path, f.Version, expectedContent, string(sheet.Msg.Content))- }- })+ expectedContent, ok := expectedContents[f.Version]+ a.True(ok, "Unexpected version %s", f.Version)+ a.Equal(expectedContent, string(sheet.Msg.Content),+ "File %s with version %s should contain '%s' but got '%s'",+ f.Path, f.Version, expectedContent, string(sheet.Msg.Content))+ }}-func TestActionRolloutDeclarativeMode(t *testing.T) {+func TestActionRolloutDeclarativeMode_BasicDeclarativeRollout(t *testing.T) {t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- t.Run("BasicDeclarativeRollout", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}-- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create PostgreSQL test database- database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)- defer pgContainer.Close(ctx)+ // Create PostgreSQL test database+ database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)+ defer pgContainer.Close(ctx)- // Create test data directory and schema.sql file- testDataDir := t.TempDir()- migrationContent1 := `CREATE TABLE users (+ // Create test data directory and schema.sql file+ testDataDir := t.TempDir()+ migrationContent1 := `CREATE TABLE users (id SERIAL,username VARCHAR(255) NOT NULL UNIQUE);`- schemaFile := filepath.Join(testDataDir, "schema.sql")- err = os.WriteFile(schemaFile, []byte(migrationContent1), 0644)- a.NoError(err)+ schemaFile := filepath.Join(testDataDir, "schema.sql")+ err = os.WriteFile(schemaFile, []byte(migrationContent1), 0644)+ a.NoError(err)- // Create output file- outputFile := filepath.Join(t.TempDir(), "rollout-output.json")-- // Execute declarative rollout- result, err := executeActionCommand(ctx,- "rollout",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", schemaFile,- "--target-stage", "environments/prod",- "--output", outputFile,- "--declarative",- )-- a.NoError(err, "Declarative rollout command should succeed")-- // Verify release was created- releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{- Parent: ctl.project.Name,- }))- a.NoError(err)- a.Len(releases.Msg.Releases, 1, "Expected exactly one release")+ // Create output file+ outputFile := filepath.Join(t.TempDir(), "rollout-output.json")++ // Execute declarative rollout+ result, err := executeActionCommand(ctx,+ "rollout",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", schemaFile,+ "--target-stage", "environments/prod",+ "--output", outputFile,+ "--declarative",+ )++ a.NoError(err, "Declarative rollout command should succeed")++ // Verify release was created+ releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{+ Parent: ctl.project.Name,+ }))+ a.NoError(err)+ a.Len(releases.Msg.Releases, 1, "Expected exactly one release")- // Verify database schema was created- metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{- Name: database.Name + "/metadata",- }))- a.NoError(err)- foundUsersTable := false- for _, schema := range metadata.Msg.Schemas {- for _, table := range schema.Tables {- if table.Name == "users" {- foundUsersTable = true- a.Equal(2, len(table.Columns), "Expected 2 columns (id, username)")- }+ // Verify database schema was created+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{+ Name: database.Name + "/metadata",+ }))+ a.NoError(err)+ foundUsersTable := false+ for _, schema := range metadata.Msg.Schemas {+ for _, table := range schema.Tables {+ if table.Name == "users" {+ foundUsersTable = true+ a.Equal(2, len(table.Columns), "Expected 2 columns (id, username)")}}- a.True(foundUsersTable, "Users table should exist after declarative rollout")+ }+ a.True(foundUsersTable, "Users table should exist after declarative rollout")- // Verify command output- a.NotContains(result.Stderr, "error", "Declarative rollout should complete without errors")- })+ // Verify command output+ a.NotContains(result.Stderr, "error", "Declarative rollout should complete without errors")+}- t.Run("DeclarativeSchemaEvolution", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}+func TestActionRolloutDeclarativeMode_DeclarativeSchemaEvolution(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create PostgreSQL test database- database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)- defer pgContainer.Close(ctx)+ // Create PostgreSQL test database+ database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)+ defer pgContainer.Close(ctx)- // Create test data directory- testDataDir := t.TempDir()- schemaFile := filepath.Join(testDataDir, "schema.sql")+ // Create test data directory+ testDataDir := t.TempDir()+ schemaFile := filepath.Join(testDataDir, "schema.sql")- // First version of schema- migrationContent1 := `CREATE TABLE users (+ // First version of schema+ migrationContent1 := `CREATE TABLE users (id SERIAL,username VARCHAR(255) NOT NULL UNIQUE);`- err = os.WriteFile(schemaFile, []byte(migrationContent1), 0644)- a.NoError(err)+ err = os.WriteFile(schemaFile, []byte(migrationContent1), 0644)+ a.NoError(err)- // Execute first declarative rollout- result1, err := executeActionCommand(ctx,- "rollout",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", schemaFile,- "--target-stage", "environments/prod",- "--declarative",- )- a.NoError(err, "First declarative rollout should succeed")-- // Verify initial schema- metadata1, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{- Name: database.Name + "/metadata",- }))- a.NoError(err)- foundTable1 := false- for _, schema := range metadata1.Msg.Schemas {- for _, table := range schema.Tables {- if table.Name == "users" {- foundTable1 = true- a.Equal(2, len(table.Columns), "Initial schema should have 2 columns")- }+ // Execute first declarative rollout+ result1, err := executeActionCommand(ctx,+ "rollout",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", schemaFile,+ "--target-stage", "environments/prod",+ "--declarative",+ )+ a.NoError(err, "First declarative rollout should succeed")++ // Verify initial schema+ metadata1, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{+ Name: database.Name + "/metadata",+ }))+ a.NoError(err)+ foundTable1 := false+ for _, schema := range metadata1.Msg.Schemas {+ for _, table := range schema.Tables {+ if table.Name == "users" {+ foundTable1 = true+ a.Equal(2, len(table.Columns), "Initial schema should have 2 columns")}}- a.True(foundTable1, "Users table should exist after first rollout")+ }+ a.True(foundTable1, "Users table should exist after first rollout")- // Update schema.sql with evolved schema (second version)- migrationContent2 := `CREATE TABLE users (+ // Update schema.sql with evolved schema (second version)+ migrationContent2 := `CREATE TABLE users (id SERIAL,username VARCHAR(255) NOT NULL UNIQUE,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`- err = os.WriteFile(schemaFile, []byte(migrationContent2), 0644)- a.NoError(err)+ err = os.WriteFile(schemaFile, []byte(migrationContent2), 0644)+ a.NoError(err)- // Execute second declarative rollout with evolved schema- result2, err := executeActionCommand(ctx,- "rollout",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", schemaFile,- "--target-stage", "environments/prod",- "--declarative",- )- a.NoError(err, "Second declarative rollout should succeed")-- // Verify evolved schema- metadata2, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{- Name: database.Name + "/metadata",- }))- a.NoError(err)- foundTable2 := false- hasCreatedAt := false- for _, schema := range metadata2.Msg.Schemas {- for _, table := range schema.Tables {- if table.Name == "users" {- foundTable2 = true- a.Equal(3, len(table.Columns), "Evolved schema should have 3 columns")- for _, col := range table.Columns {- if col.Name == "created_at" {- hasCreatedAt = true- }+ // Execute second declarative rollout with evolved schema+ result2, err := executeActionCommand(ctx,+ "rollout",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", schemaFile,+ "--target-stage", "environments/prod",+ "--declarative",+ )+ a.NoError(err, "Second declarative rollout should succeed")++ // Verify evolved schema+ metadata2, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{+ Name: database.Name + "/metadata",+ }))+ a.NoError(err)+ foundTable2 := false+ hasCreatedAt := false+ for _, schema := range metadata2.Msg.Schemas {+ for _, table := range schema.Tables {+ if table.Name == "users" {+ foundTable2 = true+ a.Equal(3, len(table.Columns), "Evolved schema should have 3 columns")+ for _, col := range table.Columns {+ if col.Name == "created_at" {+ hasCreatedAt = true}}}}- a.True(foundTable2, "Users table should still exist after evolution")- a.True(hasCreatedAt, "created_at column should be added")+ }+ a.True(foundTable2, "Users table should still exist after evolution")+ a.True(hasCreatedAt, "created_at column should be added")- // Verify no errors- a.NotContains(result1.Stderr, "error", "First rollout should complete without errors")- a.NotContains(result2.Stderr, "error", "Second rollout should complete without errors")- })+ // Verify no errors+ a.NotContains(result1.Stderr, "error", "First rollout should complete without errors")+ a.NotContains(result2.Stderr, "error", "Second rollout should complete without errors")+}- t.Run("DeclarativeIdempotency", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}+func TestActionRolloutDeclarativeMode_DeclarativeIdempotency(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create PostgreSQL test database- database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)- defer pgContainer.Close(ctx)+ // Create PostgreSQL test database+ database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)+ defer pgContainer.Close(ctx)- // Create test data directory and schema.sql file- testDataDir := t.TempDir()- migrationContent := `CREATE TABLE users (+ // Create test data directory and schema.sql file+ testDataDir := t.TempDir()+ migrationContent := `CREATE TABLE users (id SERIAL,username VARCHAR(255) NOT NULL UNIQUE,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`- schemaFile := filepath.Join(testDataDir, "schema.sql")- err = os.WriteFile(schemaFile, []byte(migrationContent), 0644)- a.NoError(err)+ schemaFile := filepath.Join(testDataDir, "schema.sql")+ err = os.WriteFile(schemaFile, []byte(migrationContent), 0644)+ a.NoError(err)- // Create output files- outputFile1 := filepath.Join(t.TempDir(), "rollout-output1.json")- outputFile2 := filepath.Join(t.TempDir(), "rollout-output2.json")- outputFile3 := filepath.Join(t.TempDir(), "rollout-output3.json")-- // Execute first declarative rollout- result1, err := executeActionCommand(ctx,- "rollout",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", schemaFile,- "--target-stage", "environments/prod",- "--output", outputFile1,- "--declarative",- )- a.NoError(err, "First declarative rollout should succeed")-- // Read first output- var output1 map[string]string- data1, err := os.ReadFile(outputFile1)- a.NoError(err)- err = json.Unmarshal(data1, &output1)- a.NoError(err)+ // Create output files+ outputFile1 := filepath.Join(t.TempDir(), "rollout-output1.json")+ outputFile2 := filepath.Join(t.TempDir(), "rollout-output2.json")+ outputFile3 := filepath.Join(t.TempDir(), "rollout-output3.json")++ // Execute first declarative rollout+ result1, err := executeActionCommand(ctx,+ "rollout",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", schemaFile,+ "--target-stage", "environments/prod",+ "--output", outputFile1,+ "--declarative",+ )+ a.NoError(err, "First declarative rollout should succeed")++ // Read first output+ var output1 map[string]string+ data1, err := os.ReadFile(outputFile1)+ a.NoError(err)+ err = json.Unmarshal(data1, &output1)+ a.NoError(err)- // Execute second declarative rollout with same schema (should succeed with task as no-op)- result2, err := executeActionCommand(ctx,- "rollout",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", schemaFile,- "--target-stage", "environments/prod",- "--output", outputFile2,- "--declarative",- )- // Second rollout should succeed (SDL diff detects no changes, executes as no-op)- a.NoError(err, "Second declarative rollout should succeed")-- // Read second output- var output2 map[string]string- data2, err := os.ReadFile(outputFile2)- a.NoError(err)- err = json.Unmarshal(data2, &output2)- a.NoError(err)+ // Execute second declarative rollout with same schema (should succeed with task as no-op)+ result2, err := executeActionCommand(ctx,+ "rollout",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", schemaFile,+ "--target-stage", "environments/prod",+ "--output", outputFile2,+ "--declarative",+ )+ // Second rollout should succeed (SDL diff detects no changes, executes as no-op)+ a.NoError(err, "Second declarative rollout should succeed")++ // Read second output+ var output2 map[string]string+ data2, err := os.ReadFile(outputFile2)+ a.NoError(err)+ err = json.Unmarshal(data2, &output2)+ a.NoError(err)- // Rollout should be created for second execution- rolloutName := output2["rollout"]- a.NotEmpty(rolloutName, "Rollout should be created for second execution")-- // Execute third declarative rollout with same schema (should also succeed with task as no-op)- result3, err := executeActionCommand(ctx,- "rollout",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", schemaFile,- "--target-stage", "environments/prod",- "--output", outputFile3,- "--declarative",- )- // Third rollout should also succeed (SDL diff detects no changes, executes as no-op)- a.NoError(err, "Third declarative rollout should succeed")-- // Read third output- var output3 map[string]string- data3, err := os.ReadFile(outputFile3)- a.NoError(err)- err = json.Unmarshal(data3, &output3)- a.NoError(err)+ // Rollout should be created for second execution+ rolloutName := output2["rollout"]+ a.NotEmpty(rolloutName, "Rollout should be created for second execution")++ // Execute third declarative rollout with same schema (should also succeed with task as no-op)+ result3, err := executeActionCommand(ctx,+ "rollout",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", schemaFile,+ "--target-stage", "environments/prod",+ "--output", outputFile3,+ "--declarative",+ )+ // Third rollout should also succeed (SDL diff detects no changes, executes as no-op)+ a.NoError(err, "Third declarative rollout should succeed")++ // Read third output+ var output3 map[string]string+ data3, err := os.ReadFile(outputFile3)+ a.NoError(err)+ err = json.Unmarshal(data3, &output3)+ a.NoError(err)- // Verify that each rollout creates a separate release (no deduplication)- releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{- Parent: ctl.project.Name,- }))- a.NoError(err)- a.Len(releases.Msg.Releases, 3, "Should have three separate releases (no deduplication)")+ // Verify that each rollout creates a separate release (no deduplication)+ releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{+ Parent: ctl.project.Name,+ }))+ a.NoError(err)+ a.Len(releases.Msg.Releases, 3, "Should have three separate releases (no deduplication)")- // Verify each rollout has its own release- a.NotEqual(output1["release"], output2["release"], "Second rollout should create a new release")- a.NotEqual(output1["release"], output3["release"], "Third rollout should create a new release")- a.NotEqual(output2["release"], output3["release"], "Each rollout should have a unique release")+ // Verify each rollout has its own release+ a.NotEqual(output1["release"], output2["release"], "Second rollout should create a new release")+ a.NotEqual(output1["release"], output3["release"], "Third rollout should create a new release")+ a.NotEqual(output2["release"], output3["release"], "Each rollout should have a unique release")- // Verify schema remains consistent (only one table created)- metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{- Name: database.Name + "/metadata",- }))- a.NoError(err)+ // Verify schema remains consistent (only one table created)+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{+ Name: database.Name + "/metadata",+ }))+ a.NoError(err)- tableCount := 0- for _, schema := range metadata.Msg.Schemas {- for _, table := range schema.Tables {- if table.Name == "users" {- tableCount++- a.Equal(3, len(table.Columns), "Table should have consistent columns")- }+ tableCount := 0+ for _, schema := range metadata.Msg.Schemas {+ for _, table := range schema.Tables {+ if table.Name == "users" {+ tableCount+++ a.Equal(3, len(table.Columns), "Table should have consistent columns")}}- a.Equal(1, tableCount, "Should have exactly one users table (idempotent)")+ }+ a.Equal(1, tableCount, "Should have exactly one users table (idempotent)")- // Verify all rollouts succeeded- a.NotContains(result1.Stderr, "error", "first rollout should complete without errors")- a.NotContains(result2.Stderr, "error", "second rollout should complete without errors")- a.NotContains(result3.Stderr, "error", "third rollout should complete without errors")+ // Verify all rollouts succeeded+ a.NotContains(result1.Stderr, "error", "first rollout should complete without errors")+ a.NotContains(result2.Stderr, "error", "second rollout should complete without errors")+ a.NotContains(result3.Stderr, "error", "third rollout should complete without errors")- // Verify that second rollout has 1 task (idempotency handled by SDL diff at execution)- rollout2, err := ctl.rolloutServiceClient.GetRollout(ctx, connect.NewRequest(&v1pb.GetRolloutRequest{- Name: rolloutName,- }))- a.NoError(err)- // Check that rollout has 1 task (executes as no-op when schema matches)- totalTasks := 0- for _, stage := range rollout2.Msg.Stages {- totalTasks += len(stage.Tasks)- }- a.Equal(1, totalTasks, "Second rollout should have 1 task")- a.Len(rollout2.Msg.Stages, 1, "Second rollout should have 1 stage")+ // Verify that second rollout has 1 task (idempotency handled by SDL diff at execution)+ rollout2, err := ctl.rolloutServiceClient.GetRollout(ctx, connect.NewRequest(&v1pb.GetRolloutRequest{+ Name: rolloutName,+ }))+ a.NoError(err)+ // Check that rollout has 1 task (executes as no-op when schema matches)+ totalTasks := 0+ for _, stage := range rollout2.Msg.Stages {+ totalTasks += len(stage.Tasks)+ }+ a.Equal(1, totalTasks, "Second rollout should have 1 task")+ a.Len(rollout2.Msg.Stages, 1, "Second rollout should have 1 stage")- // Verify third rollout also has 1 task- rolloutName3 := output3["rollout"]- a.NotEmpty(rolloutName3, "Rollout should be created for third execution")+ // Verify third rollout also has 1 task+ rolloutName3 := output3["rollout"]+ a.NotEmpty(rolloutName3, "Rollout should be created for third execution")- rollout3, err := ctl.rolloutServiceClient.GetRollout(ctx, connect.NewRequest(&v1pb.GetRolloutRequest{- Name: rolloutName3,- }))- a.NoError(err)- // Check that rollout has 1 task (executes as no-op when schema matches)- totalTasks = 0- for _, stage := range rollout3.Msg.Stages {- totalTasks += len(stage.Tasks)- }- a.Equal(1, totalTasks, "Third rollout should have 1 task")- a.Len(rollout3.Msg.Stages, 1, "Third rollout should have 1 stage")- })+ rollout3, err := ctl.rolloutServiceClient.GetRollout(ctx, connect.NewRequest(&v1pb.GetRolloutRequest{+ Name: rolloutName3,+ }))+ a.NoError(err)+ // Check that rollout has 1 task (executes as no-op when schema matches)+ totalTasks = 0+ for _, stage := range rollout3.Msg.Stages {+ totalTasks += len(stage.Tasks)+ }+ a.Equal(1, totalTasks, "Third rollout should have 1 task")+ a.Len(rollout3.Msg.Stages, 1, "Third rollout should have 1 stage")+}- t.Run("DeclarativeMultipleDatabases", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}+func TestActionRolloutDeclarativeMode_DeclarativeMultipleDatabases(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create multiple PostgreSQL test databases- database1, pgContainer1 := ctl.createTestPostgreSQLDatabase(ctx, t)- defer pgContainer1.Close(ctx)- database2, pgContainer2 := ctl.createTestPostgreSQLDatabase(ctx, t)- defer pgContainer2.Close(ctx)+ // Create multiple PostgreSQL test databases+ database1, pgContainer1 := ctl.createTestPostgreSQLDatabase(ctx, t)+ defer pgContainer1.Close(ctx)+ database2, pgContainer2 := ctl.createTestPostgreSQLDatabase(ctx, t)+ defer pgContainer2.Close(ctx)- // Create test data directory and schema.sql file- testDataDir := t.TempDir()- migrationContent := `CREATE TABLE users (+ // Create test data directory and schema.sql file+ testDataDir := t.TempDir()+ migrationContent := `CREATE TABLE users (id SERIAL,username VARCHAR(255) NOT NULL UNIQUE,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`- schemaFile := filepath.Join(testDataDir, "schema.sql")- err = os.WriteFile(schemaFile, []byte(migrationContent), 0644)+ schemaFile := filepath.Join(testDataDir, "schema.sql")+ err = os.WriteFile(schemaFile, []byte(migrationContent), 0644)+ a.NoError(err)++ // Execute declarative rollout to multiple databases+ result, err := executeActionCommand(ctx,+ "rollout",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", fmt.Sprintf("%s,%s", database1.Name, database2.Name),+ "--file-pattern", schemaFile,+ "--target-stage", "environments/prod",+ "--declarative",+ )+ a.NoError(err, "Declarative rollout to multiple databases should succeed")++ // Verify schema was applied to both databases+ for _, db := range []*v1pb.Database{database1, database2} {+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{+ Name: db.Name + "/metadata",+ }))a.NoError(err)- // Execute declarative rollout to multiple databases- result, err := executeActionCommand(ctx,- "rollout",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", fmt.Sprintf("%s,%s", database1.Name, database2.Name),- "--file-pattern", schemaFile,- "--target-stage", "environments/prod",- "--declarative",- )- a.NoError(err, "Declarative rollout to multiple databases should succeed")-- // Verify schema was applied to both databases- for _, db := range []*v1pb.Database{database1, database2} {- metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{- Name: db.Name + "/metadata",- }))- a.NoError(err)-- foundUsersTable := false- for _, schema := range metadata.Msg.Schemas {- for _, table := range schema.Tables {- if table.Name == "users" {- foundUsersTable = true- a.Equal(3, len(table.Columns), "Table should have 3 columns in "+db.Name)- }+ foundUsersTable := false+ for _, schema := range metadata.Msg.Schemas {+ for _, table := range schema.Tables {+ if table.Name == "users" {+ foundUsersTable = true+ a.Equal(3, len(table.Columns), "Table should have 3 columns in "+db.Name)}}- a.True(foundUsersTable, "Users table should exist in "+db.Name)}+ a.True(foundUsersTable, "Users table should exist in "+db.Name)+ }- // Verify command output- a.NotContains(result.Stderr, "error", "Multi-database declarative rollout should complete without errors")- })+ // Verify command output+ a.NotContains(result.Stderr, "error", "Multi-database declarative rollout should complete without errors")+}- t.Run("DeclarativeWithDatabaseGroup", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}+func TestActionRolloutDeclarativeMode_DeclarativeWithDatabaseGroup(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)-- // Create PostgreSQL test database- database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)- defer pgContainer.Close(ctx)-- // Create database group- databaseGroup, err := ctl.databaseGroupServiceClient.CreateDatabaseGroup(ctx, connect.NewRequest(&v1pb.CreateDatabaseGroupRequest{- Parent: ctl.project.Name,- DatabaseGroupId: "test-declarative-group",- DatabaseGroup: &v1pb.DatabaseGroup{- Title: "Test Declarative Group",- DatabaseExpr: &expr.Expr{Expression: "true"},- },- }))- a.NoError(err)+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ // Create PostgreSQL test database+ database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)+ defer pgContainer.Close(ctx)++ // Create database group+ databaseGroup, err := ctl.databaseGroupServiceClient.CreateDatabaseGroup(ctx, connect.NewRequest(&v1pb.CreateDatabaseGroupRequest{+ Parent: ctl.project.Name,+ DatabaseGroupId: "test-declarative-group",+ DatabaseGroup: &v1pb.DatabaseGroup{+ Title: "Test Declarative Group",+ DatabaseExpr: &expr.Expr{Expression: "true"},+ },+ }))+ a.NoError(err)- // Create test data directory and schema.sql file- testDataDir := t.TempDir()- migrationContent := `CREATE TABLE users (+ // Create test data directory and schema.sql file+ testDataDir := t.TempDir()+ migrationContent := `CREATE TABLE users (id SERIAL,username VARCHAR(255) NOT NULL UNIQUE,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`- schemaFile := filepath.Join(testDataDir, "schema.sql")- err = os.WriteFile(schemaFile, []byte(migrationContent), 0644)- a.NoError(err)+ schemaFile := filepath.Join(testDataDir, "schema.sql")+ err = os.WriteFile(schemaFile, []byte(migrationContent), 0644)+ a.NoError(err)- // Execute declarative rollout with database group- result, err := executeActionCommand(ctx,- "rollout",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", databaseGroup.Msg.Name,- "--file-pattern", schemaFile,- "--target-stage", "environments/prod",- "--declarative",- )- a.NoError(err, "Declarative rollout with database group should succeed")-- // Verify schema was applied- metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{- Name: database.Name + "/metadata",- }))- a.NoError(err)+ // Execute declarative rollout with database group+ result, err := executeActionCommand(ctx,+ "rollout",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", databaseGroup.Msg.Name,+ "--file-pattern", schemaFile,+ "--target-stage", "environments/prod",+ "--declarative",+ )+ a.NoError(err, "Declarative rollout with database group should succeed")++ // Verify schema was applied+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{+ Name: database.Name + "/metadata",+ }))+ a.NoError(err)- foundUsersTable := false- for _, schema := range metadata.Msg.Schemas {- for _, table := range schema.Tables {- if table.Name == "users" {- foundUsersTable = true- a.Equal(3, len(table.Columns), "Table should have 3 columns")- }+ foundUsersTable := false+ for _, schema := range metadata.Msg.Schemas {+ for _, table := range schema.Tables {+ if table.Name == "users" {+ foundUsersTable = true+ a.Equal(3, len(table.Columns), "Table should have 3 columns")}}- a.True(foundUsersTable, "Users table should exist after declarative rollout with database group")+ }+ a.True(foundUsersTable, "Users table should exist after declarative rollout with database group")- // Verify command output- a.NotContains(result.Stderr, "error", "Declarative rollout with database group should complete without errors")- })+ // Verify command output+ a.NotContains(result.Stderr, "error", "Declarative rollout with database group should complete without errors")+}- t.Run("DeclarativeMultipleFilesMerged", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}+func TestActionRolloutDeclarativeMode_DeclarativeMultipleFilesMerged(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create PostgreSQL test database- database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)- defer pgContainer.Close(ctx)+ // Create PostgreSQL test database+ database, pgContainer := ctl.createTestPostgreSQLDatabase(ctx, t)+ defer pgContainer.Close(ctx)- // Create test data directory with multiple SQL files- testDataDir := t.TempDir()+ // Create test data directory with multiple SQL files+ testDataDir := t.TempDir()- // Create users.sql- usersContent := `CREATE TABLE users (+ // Create users.sql+ usersContent := `CREATE TABLE users (id SERIAL PRIMARY KEY,username VARCHAR(255) NOT NULL UNIQUE,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`- usersFile := filepath.Join(testDataDir, "users.sql")- err = os.WriteFile(usersFile, []byte(usersContent), 0644)- a.NoError(err)+ usersFile := filepath.Join(testDataDir, "users.sql")+ err = os.WriteFile(usersFile, []byte(usersContent), 0644)+ a.NoError(err)- // Create names.sql- namesContent := `CREATE TABLE names (+ // Create names.sql+ namesContent := `CREATE TABLE names (id SERIAL PRIMARY KEY,first_name VARCHAR(100) NOT NULL,last_name VARCHAR(100) NOT NULL);`- namesFile := filepath.Join(testDataDir, "names.sql")- err = os.WriteFile(namesFile, []byte(namesContent), 0644)- a.NoError(err)+ namesFile := filepath.Join(testDataDir, "names.sql")+ err = os.WriteFile(namesFile, []byte(namesContent), 0644)+ a.NoError(err)- // Execute declarative rollout with multiple files (should succeed - files are merged)- result, err := executeActionCommand(ctx,- "rollout",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", filepath.Join(testDataDir, "*.sql"),- "--target-stage", "environments/prod",- "--declarative",- )-- // This should succeed because bytebase-action merges multiple declarative files- a.NoError(err, "Declarative rollout with multiple files should succeed (files are merged)")-- // Verify the release was created with exactly one merged file- releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{- Parent: ctl.project.Name,- }))- a.NoError(err)- a.Len(releases.Msg.Releases, 1, "Expected exactly one release")- release := releases.Msg.Releases[0]+ // Execute declarative rollout with multiple files (should succeed - files are merged)+ result, err := executeActionCommand(ctx,+ "rollout",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", filepath.Join(testDataDir, "*.sql"),+ "--target-stage", "environments/prod",+ "--declarative",+ )++ // This should succeed because bytebase-action merges multiple declarative files+ a.NoError(err, "Declarative rollout with multiple files should succeed (files are merged)")++ // Verify the release was created with exactly one merged file+ releases, err := ctl.releaseServiceClient.ListReleases(ctx, connect.NewRequest(&v1pb.ListReleasesRequest{+ Parent: ctl.project.Name,+ }))+ a.NoError(err)+ a.Len(releases.Msg.Releases, 1, "Expected exactly one release")+ release := releases.Msg.Releases[0]- // Verify the release contains exactly one file (the merged result)- a.Len(release.Files, 1, "Release should contain exactly one merged file")- mergedFile := release.Files[0]+ // Verify the release contains exactly one file (the merged result)+ a.Len(release.Files, 1, "Release should contain exactly one merged file")+ mergedFile := release.Files[0]- // Verify the merged file contains both table definitions via Sheet- a.NotNil(mergedFile.Sheet, "File should have a Sheet")+ // Verify the merged file contains both table definitions via Sheet+ a.NotNil(mergedFile.Sheet, "File should have a Sheet")- sheet, err := ctl.sheetServiceClient.GetSheet(ctx, connect.NewRequest(&v1pb.GetSheetRequest{- Name: mergedFile.Sheet,- Raw: true,- }))- a.NoError(err)+ sheet, err := ctl.sheetServiceClient.GetSheet(ctx, connect.NewRequest(&v1pb.GetSheetRequest{+ Name: mergedFile.Sheet,+ Raw: true,+ }))+ a.NoError(err)- a.Contains(string(sheet.Msg.Content), "CREATE TABLE users", "Merged file should contain users table definition")- a.Contains(string(sheet.Msg.Content), "CREATE TABLE names", "Merged file should contain names table definition")+ a.Contains(string(sheet.Msg.Content), "CREATE TABLE users", "Merged file should contain users table definition")+ a.Contains(string(sheet.Msg.Content), "CREATE TABLE names", "Merged file should contain names table definition")- // Verify both tables were created from the merged files- metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{- Name: database.Name + "/metadata",- }))- a.NoError(err)+ // Verify both tables were created from the merged files+ metadata, err := ctl.databaseServiceClient.GetDatabaseMetadata(ctx, connect.NewRequest(&v1pb.GetDatabaseMetadataRequest{+ Name: database.Name + "/metadata",+ }))+ a.NoError(err)- // Verify both users and names tables were created- foundUsersTable := false- foundNamesTable := false- for _, schema := range metadata.Msg.Schemas {- for _, table := range schema.Tables {- if table.Name == "users" {- foundUsersTable = true- a.Equal(3, len(table.Columns), "Users table should have 3 columns")- }- if table.Name == "names" {- foundNamesTable = true- a.Equal(3, len(table.Columns), "Names table should have 3 columns")- }+ // Verify both users and names tables were created+ foundUsersTable := false+ foundNamesTable := false+ for _, schema := range metadata.Msg.Schemas {+ for _, table := range schema.Tables {+ if table.Name == "users" {+ foundUsersTable = true+ a.Equal(3, len(table.Columns), "Users table should have 3 columns")+ }+ if table.Name == "names" {+ foundNamesTable = true+ a.Equal(3, len(table.Columns), "Names table should have 3 columns")}}- a.True(foundUsersTable, "Users table should exist after merged declarative rollout")- a.True(foundNamesTable, "Names table should exist after merged declarative rollout")+ }+ a.True(foundUsersTable, "Users table should exist after merged declarative rollout")+ a.True(foundNamesTable, "Names table should exist after merged declarative rollout")- // Verify command output- a.NotContains(result.Stderr, "error", "Merged declarative rollout should complete without errors")- })+ // Verify command output+ a.NotContains(result.Stderr, "error", "Merged declarative rollout should complete without errors")}-func TestActionErrorScenarios(t *testing.T) {+func TestActionErrorScenarios_InvalidServiceAccountSecret(t *testing.T) {t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}- t.Run("InvalidServiceAccountSecret", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}-- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)- // Create test database- database := ctl.createTestDatabase(ctx, t)+ // Create test database+ database := ctl.createTestDatabase(ctx, t)- // Create test data directory and migration file- testDataDir := t.TempDir()- migrationContent := `CREATE TABLE users (+ // Create test data directory and migration file+ testDataDir := t.TempDir()+ migrationContent := `CREATE TABLE users (id SERIAL PRIMARY KEY,username TEXT NOT NULL UNIQUE,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`- err = os.WriteFile(filepath.Join(testDataDir, "00001_create_users.sql"), []byte(migrationContent), 0644)- a.NoError(err)+ err = os.WriteFile(filepath.Join(testDataDir, "00001_create_users.sql"), []byte(migrationContent), 0644)+ a.NoError(err)- // Execute command with invalid credentials- result, err := executeActionCommand(ctx,- "check",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "invalid-secret",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", filepath.Join(testDataDir, "*.sql"),- )-- a.Error(err, "Command should fail with invalid service account secret")- a.Contains(result.Stderr, "failed to login", "Expected authentication error in stderr")- })-- t.Run("NonExistentDatabase", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}-- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)+ // Execute command with invalid credentials+ result, err := executeActionCommand(ctx,+ "check",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "invalid-secret",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", filepath.Join(testDataDir, "*.sql"),+ )++ a.Error(err, "Command should fail with invalid service account secret")+ a.Contains(result.Stderr, "failed to login", "Expected authentication error in stderr")+}- // Create test data directory and migration file- testDataDir := t.TempDir()- migrationContent := `CREATE TABLE users (+func TestActionErrorScenarios_NonExistentDatabase(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}++ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ // Create test data directory and migration file+ testDataDir := t.TempDir()+ migrationContent := `CREATE TABLE users (id SERIAL PRIMARY KEY,username TEXT NOT NULL UNIQUE,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`- err = os.WriteFile(filepath.Join(testDataDir, "00001_create_users.sql"), []byte(migrationContent), 0644)- a.NoError(err)+ err = os.WriteFile(filepath.Join(testDataDir, "00001_create_users.sql"), []byte(migrationContent), 0644)+ a.NoError(err)- // Try to target a database that doesn't exist- result, err := executeActionCommand(ctx,- "check",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", "instances/fake/databases/nonexistent",- "--file-pattern", filepath.Join(testDataDir, "*.sql"),- )-- a.Error(err, "Command should fail with non-existent database")- a.Contains(result.Stderr, "database instances/fake/databases/nonexistent not found", "Expected not found error in stderr")- })-- t.Run("EmptyFilePattern", func(t *testing.T) {- t.Parallel()- a := require.New(t)- ctx := context.Background()- ctl := &controller{}-- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer ctl.Close(ctx)-- database := ctl.createTestDatabase(ctx, t)-- // Create test data directory (but don't create any files)- testDataDir := t.TempDir()-- // Use a pattern that matches no files- _, err = executeActionCommand(ctx,- "rollout",- "--url", ctl.rootURL,- "--service-account", "[email protected]",- "--service-account-secret", "1024bytebase",- "--project", ctl.project.Name,- "--targets", database.Name,- "--file-pattern", filepath.Join(testDataDir, "*.nonexistent"),- "--target-stage", "environments/prod",- )-- a.Error(err, "Command should fail with empty file pattern")- a.ErrorContains(err, "no files found for pattern")- })+ // Try to target a database that doesn't exist+ result, err := executeActionCommand(ctx,+ "check",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", "instances/fake/databases/nonexistent",+ "--file-pattern", filepath.Join(testDataDir, "*.sql"),+ )++ a.Error(err, "Command should fail with non-existent database")+ a.Contains(result.Stderr, "database instances/fake/databases/nonexistent not found", "Expected not found error in stderr")+}++func TestActionErrorScenarios_EmptyFilePattern(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}++ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer ctl.Close(ctx)++ database := ctl.createTestDatabase(ctx, t)++ // Create test data directory (but don't create any files)+ testDataDir := t.TempDir()++ // Use a pattern that matches no files+ _, err = executeActionCommand(ctx,+ "rollout",+ "--url", ctl.rootURL,+ "--service-account", "[email protected]",+ "--service-account-secret", "1024bytebase",+ "--project", ctl.project.Name,+ "--targets", database.Name,+ "--file-pattern", filepath.Join(testDataDir, "*.nonexistent"),+ "--target-stage", "environments/prod",+ )++ a.Error(err, "Command should fail with empty file pattern")+ a.ErrorContains(err, "no files found for pattern")}diff --git a/backend/tests/grouping_change_test.go b/backend/tests/grouping_change_test.goindex f27f3236c2..9490c881a0 100644--- a/backend/tests/grouping_change_test.go+++ b/backend/tests/grouping_change_test.go@@ -13,171 +13,178 @@ import (v1pb "github.com/bytebase/bytebase/backend/generated-go/v1")-// TestCreateDatabaseGroup tests creating database and verify the grouping result.-// For each test case:-// 1. The test provides a number of Postgres instances equal to the number of prepareInstances and creates the specified matchDatabase and unmatchedDatabase in the corresponding instances.-// 2. The database group is then created with the specified expr.-// 3. The results obtained are compared with the results given in prepareInstance and they should be consistent.-func TestCreateDatabaseGroup(t *testing.T) {- t.Parallel()- type testCasePrepareInstance struct {- instanceTitle string- matchedDatabasesName map[string]any+type createDatabaseGroupInstance struct {+ instanceTitle string+ matchedDatabasesName map[string]any+}++type createDatabaseGroupCase struct {+ databaseGroupPlaceholder string+ databaseGroupExpr string+ prepareInstances []createDatabaseGroupInstance+}++// testCreateDatabaseGroup creates databases and verifies the grouping result:+// 1. It provisions one Postgres instance per prepareInstances entry and creates the listed databases on it.+// 2. It creates the database group with the given expr.+// 3. It compares the matched databases against prepareInstances; they should be consistent.+//+// The cases are top-level tests rather than subtests so that they enter the+// package's parallel queue with everything else. Parallel subtests only get a+// slot once every top-level test has started, which put these 17 s cases at+// the very end of the package.+func testCreateDatabaseGroup(t *testing.T, tc createDatabaseGroupCase) {+ a := require.New(t)+ ctl := &controller{}+ ctx := context.Background()+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ a.NoError(err)+ defer func() {+ _ = ctl.Close(ctx)+ }()++ instanceResourceID2InstanceTitle := make(map[string]string)+ for _, prepareInstance := range tc.prepareInstances {+ pgContainer, err := provisionPgInstance(ctx, t)+ a.NoError(err)+ instanceResourceID := generateRandomString("instance")+ instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{+ InstanceId: instanceResourceID,+ Instance: &v1pb.Instance{+ Title: prepareInstance.instanceTitle,+ Engine: v1pb.Engine_POSTGRES,+ Environment: new("environments/prod"),+ DataSources: []*v1pb.DataSource{pgContainer.adminDataSource()},+ Activation: true,+ },+ }))+ a.NoError(err)+ instance := instanceResp.Msg+ instanceResourceID2InstanceTitle[instanceResourceID] = instance.Title+ for preCreateDatabase := range prepareInstance.matchedDatabasesName {+ err = ctl.createDatabase(ctx, ctl.project, instance, nil, preCreateDatabase, "")+ a.NoError(err)+ }}- testCases := []struct {- name string- databaseGroupPlaceholder string- databaseGroupExpr string- prepareInstances []testCasePrepareInstance- }{- {- name: "all-matched-one-instance",- databaseGroupPlaceholder: "all-matched-one-instance",- databaseGroupExpr: `(resource.database_name.startsWith("employee_"))`,- prepareInstances: []testCasePrepareInstance{- {- instanceTitle: "TestCreateDatabaseGroups_AllMatched_OneInstance",- matchedDatabasesName: map[string]any{- "employee_01": nil,- "employee_02": nil,- },- },+ databaseGroupResp, err := ctl.databaseGroupServiceClient.CreateDatabaseGroup(ctx, connect.NewRequest(&v1pb.CreateDatabaseGroupRequest{+ Parent: ctl.project.Name,+ DatabaseGroupId: tc.databaseGroupPlaceholder,+ DatabaseGroup: &v1pb.DatabaseGroup{+ Title: tc.databaseGroupPlaceholder,+ DatabaseExpr: &expr.Expr{+ Expression: fmt.Sprintf(`(resource.environment_id == "prod" && (%s))`, tc.databaseGroupExpr),},},- {- name: "partial-matched-one-instance",- databaseGroupPlaceholder: "partial-matched-one-instance",- databaseGroupExpr: `(resource.database_name.startsWith("employee_"))`,- prepareInstances: []testCasePrepareInstance{- {- instanceTitle: "TestCreateDatabaseGroups_PartialMatched_OneInstance",- matchedDatabasesName: map[string]any{- "employee_01": nil,- "employee_02": nil,- },+ }))+ a.NoError(err)+ databaseGroup := databaseGroupResp.Msg+ databaseGroupResp, err = ctl.databaseGroupServiceClient.GetDatabaseGroup(ctx, connect.NewRequest(&v1pb.GetDatabaseGroupRequest{+ Name: databaseGroup.Name,+ View: v1pb.DatabaseGroupView_DATABASE_GROUP_VIEW_FULL,+ }))+ a.NoError(err)+ databaseGroup = databaseGroupResp.Msg++ gotInstanceTitleToMatchedDatabases := make(map[string][]string)++ for _, matchedDatabase := range databaseGroup.MatchedDatabases {+ instanceResourceID := strings.Split(matchedDatabase.Name, "/")[1]+ instanceTitle := instanceResourceID2InstanceTitle[instanceResourceID]+ a.NotEmpty(instanceTitle)++ databaseName := strings.Split(matchedDatabase.Name, "/")[3]+ gotInstanceTitleToMatchedDatabases[instanceTitle] = append(gotInstanceTitleToMatchedDatabases[instanceTitle], databaseName)+ }++ for _, prepareInstance := range tc.prepareInstances {+ gotMatchedDatabases := gotInstanceTitleToMatchedDatabases[prepareInstance.instanceTitle]+ a.Equal(len(gotMatchedDatabases), len(prepareInstance.matchedDatabasesName))+ for wantMatchedDatabase := range prepareInstance.matchedDatabasesName {+ a.Contains(gotMatchedDatabases, wantMatchedDatabase)+ }+ }+}++func TestCreateDatabaseGroup_AllMatchedOneInstance(t *testing.T) {+ t.Parallel()+ testCreateDatabaseGroup(t, createDatabaseGroupCase{+ databaseGroupPlaceholder: "all-matched-one-instance",+ databaseGroupExpr: `(resource.database_name.startsWith("employee_"))`,+ prepareInstances: []createDatabaseGroupInstance{+ {+ instanceTitle: "TestCreateDatabaseGroups_AllMatched_OneInstance",+ matchedDatabasesName: map[string]any{+ "employee_01": nil,+ "employee_02": nil,},},},- {- name: "all-matched-many-instances",- databaseGroupPlaceholder: "all-matched-many-instances",- databaseGroupExpr: `(resource.database_name.startsWith("employee_"))`,- prepareInstances: []testCasePrepareInstance{- {- instanceTitle: "TestCreateDatabaseGroups_AllMatched_ManyInstances_01",- matchedDatabasesName: map[string]any{- "employee_01": nil,- "employee_02": nil,- },- },- {- instanceTitle: "TestCreateDatabaseGroups_AllMatched_ManyInstances_02",- matchedDatabasesName: map[string]any{- "employee_02": nil,- "employee_03": nil,- "employee_04": nil,- },+ })+}++func TestCreateDatabaseGroup_PartialMatchedOneInstance(t *testing.T) {+ t.Parallel()+ testCreateDatabaseGroup(t, createDatabaseGroupCase{+ databaseGroupPlaceholder: "partial-matched-one-instance",+ databaseGroupExpr: `(resource.database_name.startsWith("employee_"))`,+ prepareInstances: []createDatabaseGroupInstance{+ {+ instanceTitle: "TestCreateDatabaseGroups_PartialMatched_OneInstance",+ matchedDatabasesName: map[string]any{+ "employee_01": nil,+ "employee_02": nil,},},},- {- name: "partial-matched-many-instances",- databaseGroupPlaceholder: "partial-matched-many-instances",- databaseGroupExpr: `(resource.database_name.startsWith("employee_"))`,- prepareInstances: []testCasePrepareInstance{- {- instanceTitle: "TestCreateDatabaseGroups_PartialMatched_ManyInstances_01",- matchedDatabasesName: map[string]any{- "employee_01": nil,- "employee_02": nil,- },+ })+}++func TestCreateDatabaseGroup_AllMatchedManyInstances(t *testing.T) {+ t.Parallel()+ testCreateDatabaseGroup(t, createDatabaseGroupCase{+ databaseGroupPlaceholder: "all-matched-many-instances",+ databaseGroupExpr: `(resource.database_name.startsWith("employee_"))`,+ prepareInstances: []createDatabaseGroupInstance{+ {+ instanceTitle: "TestCreateDatabaseGroups_AllMatched_ManyInstances_01",+ matchedDatabasesName: map[string]any{+ "employee_01": nil,+ "employee_02": nil,},- {- instanceTitle: "TestCreateDatabaseGroups_PartialMatched_ManyInstances_02",- matchedDatabasesName: map[string]any{- "employee_02": nil,- "employee_03": nil,- "employee_04": nil,- },+ },+ {+ instanceTitle: "TestCreateDatabaseGroups_AllMatched_ManyInstances_02",+ matchedDatabasesName: map[string]any{+ "employee_02": nil,+ "employee_03": nil,+ "employee_04": nil,},},},- }-- a := require.New(t)-- for _, tc := range testCases {- tc := tc- t.Run(tc.name, func(t *testing.T) {- t.Parallel()- ctl := &controller{}- ctx := context.Background()- ctx, err := ctl.StartServerWithExternalPg(ctx)- a.NoError(err)- defer func() {- _ = ctl.Close(ctx)- }()+ })+}- instanceResourceID2InstanceTitle := make(map[string]string)- for _, prepareInstance := range tc.prepareInstances {- pgContainer, err := provisionPgInstance(ctx, t)- a.NoError(err)- instanceResourceID := generateRandomString("instance")- instanceResp, err := ctl.instanceServiceClient.CreateInstance(ctx, connect.NewRequest(&v1pb.CreateInstanceRequest{- InstanceId: instanceResourceID,- Instance: &v1pb.Instance{- Title: prepareInstance.instanceTitle,- Engine: v1pb.Engine_POSTGRES,- Environment: new("environments/prod"),- DataSources: []*v1pb.DataSource{pgContainer.adminDataSource()},- Activation: true,- },- }))- a.NoError(err)- instance := instanceResp.Msg- instanceResourceID2InstanceTitle[instanceResourceID] = instance.Title- for preCreateDatabase := range prepareInstance.matchedDatabasesName {- err = ctl.createDatabase(ctx, ctl.project, instance, nil, preCreateDatabase, "")- a.NoError(err)- }- }- databaseGroupResp, err := ctl.databaseGroupServiceClient.CreateDatabaseGroup(ctx, connect.NewRequest(&v1pb.CreateDatabaseGroupRequest{- Parent: ctl.project.Name,- DatabaseGroupId: tc.databaseGroupPlaceholder,- DatabaseGroup: &v1pb.DatabaseGroup{- Title: tc.databaseGroupPlaceholder,- DatabaseExpr: &expr.Expr{- Expression: fmt.Sprintf(`(resource.environment_id == "prod" && (%s))`, tc.databaseGroupExpr),- },+func TestCreateDatabaseGroup_PartialMatchedManyInstances(t *testing.T) {+ t.Parallel()+ testCreateDatabaseGroup(t, createDatabaseGroupCase{+ databaseGroupPlaceholder: "partial-matched-many-instances",+ databaseGroupExpr: `(resource.database_name.startsWith("employee_"))`,+ prepareInstances: []createDatabaseGroupInstance{+ {+ instanceTitle: "TestCreateDatabaseGroups_PartialMatched_ManyInstances_01",+ matchedDatabasesName: map[string]any{+ "employee_01": nil,+ "employee_02": nil,},- }))- a.NoError(err)- databaseGroup := databaseGroupResp.Msg- databaseGroupResp, err = ctl.databaseGroupServiceClient.GetDatabaseGroup(ctx, connect.NewRequest(&v1pb.GetDatabaseGroupRequest{- Name: databaseGroup.Name,- View: v1pb.DatabaseGroupView_DATABASE_GROUP_VIEW_FULL,- }))- a.NoError(err)- databaseGroup = databaseGroupResp.Msg-- gotInstanceTitleToMatchedDatabases := make(map[string][]string)-- for _, matchedDatabase := range databaseGroup.MatchedDatabases {- instanceResourceID := strings.Split(matchedDatabase.Name, "/")[1]- instanceTitle := instanceResourceID2InstanceTitle[instanceResourceID]- a.NotEmpty(instanceTitle)-- databaseName := strings.Split(matchedDatabase.Name, "/")[3]- gotInstanceTitleToMatchedDatabases[instanceTitle] = append(gotInstanceTitleToMatchedDatabases[instanceTitle], databaseName)- }-- for _, prepareInstance := range tc.prepareInstances {- gotMatchedDatabases := gotInstanceTitleToMatchedDatabases[prepareInstance.instanceTitle]- a.Equal(len(gotMatchedDatabases), len(prepareInstance.matchedDatabasesName))- for wantMatchedDatabase := range prepareInstance.matchedDatabasesName {- a.Contains(gotMatchedDatabases, wantMatchedDatabase)- }- }- })- }+ },+ {+ instanceTitle: "TestCreateDatabaseGroups_PartialMatched_ManyInstances_02",+ matchedDatabasesName: map[string]any{+ "employee_02": nil,+ "employee_03": nil,+ "employee_04": nil,+ },+ },+ },+ })}diff --git a/backend/tests/webhook_helpers_test.go b/backend/tests/webhook_helpers_test.goindex 1fc8eba047..24f8512371 100644--- a/backend/tests/webhook_helpers_test.go+++ b/backend/tests/webhook_helpers_test.go@@ -97,6 +97,25 @@ func waitForWebhookCount(t *testing.T, c *webhookCollector, projectName, eventTi}}+// createDatabasesFlushingCompletion registers a PIPELINE_FAILED and+// PIPELINE_COMPLETED webhook, provisions the databases, then waits for the+// completion each creation rollout fires and discards it. Registering the+// webhook after creation is not enough: the scheduler marks the task DONE,+// which is what createDatabase waits on, before it emits the completion event,+// so a webhook added in that gap still receives it and a later assertion of+// zero completions fails.+func createDatabasesFlushingCompletion(ctx context.Context, t *testing.T, ctl *controller, c *webhookCollector, project *v1pb.Project, instance *v1pb.Instance, url string, databases ...string) {+ t.Helper()+ addWebhookForEvents(ctx, t, ctl, project, url, []v1pb.Activity_Type{+ v1pb.Activity_PIPELINE_FAILED, v1pb.Activity_PIPELINE_COMPLETED,+ })+ for _, database := range databases {+ require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, database, ""))+ }+ waitForWebhookCount(t, c, project.Name, "Rollout completed", len(databases))+ c.reset()+}+// requireWebhookCount asserts the exact count of webhooks for (project, eventTitle).func requireWebhookCount(t *testing.T, c *webhookCollector, projectName, eventTitle string, n int, resources ...string) {t.Helper()diff --git a/backend/tests/webhook_test.go b/backend/tests/webhook_test.goindex 1e04eb5bb2..fadc453d16 100644--- a/backend/tests/webhook_test.go+++ b/backend/tests/webhook_test.go@@ -428,19 +428,7 @@ func TestWebhookIntegration(t *testing.T) {project := ctl.createTestProject(ctx, t, "byt9398-c4")- // Create databases before registering the webhook so the implicit- // PIPELINE_COMPLETED events fired by createDatabase (which internally- // runs a createDatabaseConfig plan) do not pollute the collector.- err := ctl.createDatabase(ctx, project, instance, nil, "byt9398_c4_pass", "")- require.NoError(t, err)- err = ctl.createDatabase(ctx, project, instance, nil, "byt9398_c4_fail", "")- require.NoError(t, err)-- collector.reset()- addWebhookForEvents(ctx, t, ctl, project, webhookServer.URL, []v1pb.Activity_Type{- v1pb.Activity_PIPELINE_FAILED,- v1pb.Activity_PIPELINE_COMPLETED,- })+ createDatabasesFlushingCompletion(ctx, t, ctl, collector, project, instance, webhookServer.URL, "byt9398_c4_pass", "byt9398_c4_fail")plan := createPlanWithSpecs(ctx, t, ctl, project, []taskSpec{{seedPassingSheet(ctx, t, ctl, project), dbTargetName(instance, "byt9398_c4_pass")},@@ -462,12 +450,7 @@ func TestWebhookIntegration(t *testing.T) {t.Run("PipelineCompleted_AllTasksDone", func(t *testing.T) {collector.reset()project := ctl.createTestProject(ctx, t, "byt9398-c1")- require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, "byt9398_c1_a", ""))- require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, "byt9398_c1_b", ""))- collector.reset() // flush any PIPELINE_COMPLETED from database creation- addWebhookForEvents(ctx, t, ctl, project, webhookServer.URL, []v1pb.Activity_Type{- v1pb.Activity_PIPELINE_FAILED, v1pb.Activity_PIPELINE_COMPLETED,- })+ createDatabasesFlushingCompletion(ctx, t, ctl, collector, project, instance, webhookServer.URL, "byt9398_c1_a", "byt9398_c1_b")plan := createPlanWithSpecs(ctx, t, ctl, project, []taskSpec{{seedPassingSheet(ctx, t, ctl, project), dbTargetName(instance, "byt9398_c1_a")},@@ -482,12 +465,7 @@ func TestWebhookIntegration(t *testing.T) {t.Run("PipelineCompleted_DoneAndSkipped", func(t *testing.T) {collector.reset()project := ctl.createTestProject(ctx, t, "byt9398-c2")- require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, "byt9398_c2_a", ""))- require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, "byt9398_c2_b", ""))- collector.reset() // flush any PIPELINE_COMPLETED from database creation- addWebhookForEvents(ctx, t, ctl, project, webhookServer.URL, []v1pb.Activity_Type{- v1pb.Activity_PIPELINE_FAILED, v1pb.Activity_PIPELINE_COMPLETED,- })+ createDatabasesFlushingCompletion(ctx, t, ctl, collector, project, instance, webhookServer.URL, "byt9398_c2_a", "byt9398_c2_b")plan := createPlanWithSpecs(ctx, t, ctl, project, []taskSpec{{seedPassingSheet(ctx, t, ctl, project), dbTargetName(instance, "byt9398_c2_a")},@@ -504,12 +482,7 @@ func TestWebhookIntegration(t *testing.T) {t.Run("PipelineCompleted_AllSkipped", func(t *testing.T) {collector.reset()project := ctl.createTestProject(ctx, t, "byt9398-c5")- require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, "byt9398_c5_a", ""))- require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, "byt9398_c5_b", ""))- collector.reset() // flush any PIPELINE_COMPLETED from database creation- addWebhookForEvents(ctx, t, ctl, project, webhookServer.URL, []v1pb.Activity_Type{- v1pb.Activity_PIPELINE_FAILED, v1pb.Activity_PIPELINE_COMPLETED,- })+ createDatabasesFlushingCompletion(ctx, t, ctl, collector, project, instance, webhookServer.URL, "byt9398_c5_a", "byt9398_c5_b")plan := createPlanWithSpecs(ctx, t, ctl, project, []taskSpec{{seedPassingSheet(ctx, t, ctl, project), dbTargetName(instance, "byt9398_c5_a")},@@ -525,12 +498,7 @@ func TestWebhookIntegration(t *testing.T) {t.Run("PipelineCompleted_DoneAndFailedThenRetriedDone", func(t *testing.T) {collector.reset()project := ctl.createTestProject(ctx, t, "byt9398-c3")- require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, "byt9398_c3_pass", ""))- require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, "byt9398_c3_fail", ""))- collector.reset() // flush any PIPELINE_COMPLETED from database creation- addWebhookForEvents(ctx, t, ctl, project, webhookServer.URL, []v1pb.Activity_Type{- v1pb.Activity_PIPELINE_FAILED, v1pb.Activity_PIPELINE_COMPLETED,- })+ createDatabasesFlushingCompletion(ctx, t, ctl, collector, project, instance, webhookServer.URL, "byt9398_c3_pass", "byt9398_c3_fail")plan := createPlanWithSpecs(ctx, t, ctl, project, []taskSpec{{seedPassingSheet(ctx, t, ctl, project), dbTargetName(instance, "byt9398_c3_pass")},@@ -552,12 +520,7 @@ func TestWebhookIntegration(t *testing.T) {t.Run("PipelineCompleted_AllFailedThenAllSkipped", func(t *testing.T) {collector.reset()project := ctl.createTestProject(ctx, t, "byt9398-c6")- require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, "byt9398_c6_a", ""))- require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, "byt9398_c6_b", ""))- collector.reset() // flush any PIPELINE_COMPLETED from database creation- addWebhookForEvents(ctx, t, ctl, project, webhookServer.URL, []v1pb.Activity_Type{- v1pb.Activity_PIPELINE_FAILED, v1pb.Activity_PIPELINE_COMPLETED,- })+ createDatabasesFlushingCompletion(ctx, t, ctl, collector, project, instance, webhookServer.URL, "byt9398_c6_a", "byt9398_c6_b")plan := createPlanWithSpecs(ctx, t, ctl, project, []taskSpec{{seedFailingSheet(ctx, t, ctl, project), dbTargetName(instance, "byt9398_c6_a")},@@ -576,13 +539,7 @@ func TestWebhookIntegration(t *testing.T) {t.Run("PipelineCompleted_MixedRecovery", func(t *testing.T) {collector.reset()project := ctl.createTestProject(ctx, t, "byt9398-c7")- for _, n := range []string{"byt9398_c7_done", "byt9398_c7_skip", "byt9398_c7_retry", "byt9398_c7_skipfailed"} {- require.NoError(t, ctl.createDatabase(ctx, project, instance, nil, n, ""))- }- collector.reset() // flush any PIPELINE_COMPLETED from database creation- addWebhookForEvents(ctx, t, ctl, project, webhookServer.URL, []v1pb.Activity_Type{- v1pb.Activity_PIPELINE_FAILED, v1pb.Activity_PIPELINE_COMPLETED,- })+ createDatabasesFlushingCompletion(ctx, t, ctl, collector, project, instance, webhookServer.URL, "byt9398_c7_done", "byt9398_c7_skip", "byt9398_c7_retry", "byt9398_c7_skipfailed")plan := createPlanWithSpecs(ctx, t, ctl, project, []taskSpec{{seedPassingSheet(ctx, t, ctl, project), dbTargetName(instance, "byt9398_c7_done")},diff --git a/docs/design/backend-test-execution-time.md b/docs/design/backend-test-execution-time.mdindex 35ac660e28..1b2ae7fd25 100644--- a/docs/design/backend-test-execution-time.md+++ b/docs/design/backend-test-execution-time.md@@ -85,6 +85,67 @@ there is now about what the tests say, not what they cost. And`plugin/schema/*` as a whole went from 475 s to 164 s, `plugin/db/*` from 339 sto 145 s, which shrinks effort 7 from the largest item here to a middling one.+### Second pass: 189 s to 152 s++Same command, same box, measured again on 2026-09-06 after everything above+had landed: **189 s**, package walls summing to 620 s and overlapping 3.3×.+Five changes later it is **152 s**, walls summing to 654 s and overlapping 4.3×.+Every package passes, `api/v1` also under `-race`.++What the measurement found, what changed, and what it bought:++| Finding | Change | Measured |+| --- | --- | --- |+| `backend/tests` was scheduled last. `./backend/...` expands alphabetically, so it got its first `-p=8` slot at +93 s and ran alone from +125 s. | CI lists `./backend/tests ./backend/api/v1` ahead of `./backend/...`; `go test` keeps command-line order and drops duplicates. | 189 s → 147 s on a cold cache, before any other change. |+| `waitDBPing` waited on a 3 s ticker before its first ping, and a container is pingable 13 ms after `GenericContainer` returns. | Ping first, then poll every 100 ms. | Postgres start 4.33 s → 1.33 s; `backend/tests` alone 97 s → 79 s, its summed test time 1215 s → 953 s. |+| Parallel subtests only get a slot once every top-level test has started, so the action command cases and the database group cases ran last, at one to eight concurrency, for the package's final 25 s. | Flattened into top-level tests. | The tail is gone; `TestWebhookIntegration`, 43 s from a first slot at about +18 s, is now the package floor. |+| `plugin/db/pg` started nine containers, serially. | One shared container, a database per test with roles named after it, `t.Parallel()`. | 53 s → 7 s. |+| `api/v1` ran 336 tests serially, and four of them were 27 s of its 38 s. | `t.Parallel()` on 263 tests: 217 without subtests, 46 table-driven ones at both levels, 3 slow parents under `//nolint:tparallel`. Six stay serial for `t.Setenv`, 62 with sequential subtests stay serial. | 41 s → 25 s inside the full run. |++Two suspects were measured and cleared. The 5 s tickers in the plan check, task+run and review run schedulers all have tickle channels that the API fires, and+forcing them to 300 ms made `backend/tests` slower, 79 s → 84 s, from sixty+schedulers polling Postgres. And `TestWebhookIntegration` is the longest test at+43 s but no longer the tail; it is the floor of a package whose other 225 tests+now fit around it.++What is left of a Postgres start is `initdb`, about 1.25 s, and `backend/tests`+still pays it 161 times. An image with the data directory already initialized+was tried: a container answered in 0.18 s and the run came in at 140 s, but a+`docker build` inside the test helper is more machinery than the 12 s it+bought, and it is not in. The way to take those starts out is the one+`plugin/db/pg` and the metadata packages use, one container per package and a+database per test, with one caveat: a Bytebase instance syncs every database on+its server, so the tests that assert on an instance's database list keep a+server of their own.++Measured standalone after all of it, `backend/tests` is **75.2 s** against+97.1 s, with 1139 s of summed test time against 1215 s.++**The gate has moved again.** With `backend/tests` finishing at +122 s, the+run's last 30 s are `plugin/schema/oracle` alone. It still sorts into the+alphabetical part of the list, starts at +74 s and takes 77 s under contention:+13 subtests of 4.4 s of Oracle work each, on an engine capped at two threads,+so Go-side parallelism buys at most 2×. Listing it ahead of `./backend/...` as+well takes that tail off the run; shrinking the package is effort 7's business.++One race surfaced under the heavier overlap, in `TestWebhookIntegration`'s+completion cases. They provisioned databases, reset the collector, and only+then registered the PIPELINE_COMPLETED webhook, trusting that the creation+rollouts' completions had already been delivered. They had not necessarily:+the running scheduler marks the task DONE, which is what `createDatabase`+waits on, before it emits the completion event, so a webhook registered in that+gap still received it and the assertion of zero completions failed once in+about ten runs. `createDatabasesFlushingCompletion` now registers the webhook+first, waits for one completion per database, and discards them.++One hazard to know about. Two back-to-back heavy runs failed container starts+with `failed to bind host port 0.0.0.0:49xxx/tcp: address already in use`.+Docker publishes ports from the same 32768–60999 range the kernel hands to+outgoing connections, and twenty servers' clients hold many of those. It shows+in none of the CI logs checked, but it scales with throughput; a runner that+starts seeing it should move one of the two ranges apart.+### The floor`backend/plugin/...` cost 866 s across 69 packages at the start, and split by@@ -399,8 +460,8 @@ Sorting the expensive tests by that rule gave four outcomes rather than one:- **Engine is the workflow.** `TestGhostSchemaUpdate` and`TestGitOpsRolloutGhostDirective` keep MySQL, and now say why in a comment:- gh-ost is MySQL-only. `TestActionCheckCommand`'s database-group subtest keeps it- too — the port was tried and reverted, because the declarative check returns+ gh-ost is MySQL-only. `TestActionCheckCommand_DeclarativeCheckWithDatabaseGroup`+ keeps it too — the port was tried and reverted, because the declarative check returnsthree errors against the same schema on Postgres. Worth chasing separately.MySQL in `backend/tests` is now those three tests and nothing else.@@ -421,7 +482,8 @@ in the words "test API and workflow behavior against Postgres only".`docker events` recorded 11 MySQL containers from `backend/tests` when this waswritten. Each of those twelve candidate tests is accounted for above; the one-that is not is `TestActionCheckCommand`, which keeps its container.+that is not is `TestActionCheckCommand_DeclarativeCheckWithDatabaseGroup`, which+keeps its container.The original plan here said "where a Postgres equivalent proves the sameworkflow, delete the MySQL copy". That held for `TestSyncerForMySQL`, whose twin@@ -435,7 +497,7 @@ calling a test a duplicate.****Re-sized: the seconds are already gone, the argument is not.** This sectionwas written against 822 s of wall clock, 611 s of it container starts. #21349then gave `api/v1`, `component/review`, `auth`, `oauth2`, `lsp` and `mcp` a-shared Postgres through `testcontainer.MetadataMain`, and those two packages+shared Postgres through `testcontainer.NewMetadataDB`, and those two packageswent to 43 s and 17 s without a single fake being written. All six now sit withina couple of seconds of the 6.9 s floor that a package holding one containercannot go below, and `api/v1` is 43 s of which about 36 s is its own tests.