From e777e0981ee97bec5809453ad8efcd56378448b6 Mon Sep 17 00:00:00 2001 From: Wenting Wu Date: Wed, 11 Nov 2026 13:39:09 -0500 Subject: [PATCH 1/5] fix: upgrade DocumentDB core alongside the main extension Upgrade co-versioned dependencies first in a single transaction and repair existing mismatches when schema upgrades are authorized. Preserve two-phase behavior and leave independently versioned extensions unmanaged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 251a6aad-1c9b-4e75-9768-1d79b8eb8a7f Signed-off-by: Wenting Wu --- docs/designs/product-neutral-core.md | 10 + .../controller/documentdb_controller_test.go | 43 ++--- operator/src/internal/engine/extension.go | 70 ++++++- .../internal/engine/extension_policy_test.go | 171 +++++++++++++++++- operator/src/internal/product/documentdb.go | 3 +- operator/src/internal/product/profile.go | 4 + test/e2e/tests/upgrade/helpers_test.go | 38 +++- .../tests/upgrade/upgrade_schema_auto_test.go | 8 + test/e2e/tests/upgrade/upgrade_schema_test.go | 17 ++ 9 files changed, 330 insertions(+), 34 deletions(-) diff --git a/docs/designs/product-neutral-core.md b/docs/designs/product-neutral-core.md index 8897dfcd0..9622462b3 100644 --- a/docs/designs/product-neutral-core.md +++ b/docs/designs/product-neutral-core.md @@ -99,6 +99,16 @@ whose PostgreSQL extension uses dotted semantic versions set `core.ExtensionVersionSemver`; automatic upgrades, explicit targets, comparison, events, and schema status then use that format without rewriting it. +`PostgresProfile.ExtensionDependencies` lists only dependencies that share the +main extension's version, in upgrade order. The reconciler upgrades them before +the main extension in one transaction, using the same explicit target for all +extensions, including in `auto` mode. DocumentDB configures `documentdb_core`; +independently versioned dependencies such as PostGIS and pg_cron are not +automatically upgraded. With `schemaVersion` set to `auto` or the installed main +extension version, reconciliation also repairs dependencies left behind by an +earlier operator, even if the main extension is already current. An unset +`schemaVersion` still leaves all extension schemas untouched. + The DocumentDB controllers and webhook in `internal/controller` and `internal/webhook` are now thin wrappers over these packages. They keep their types, method names, and `cmd/main.go` wiring. CRD schemas are unchanged; diff --git a/operator/src/internal/controller/documentdb_controller_test.go b/operator/src/internal/controller/documentdb_controller_test.go index c20b606f0..3528fb0c5 100644 --- a/operator/src/internal/controller/documentdb_controller_test.go +++ b/operator/src/internal/controller/documentdb_controller_test.go @@ -840,11 +840,10 @@ var _ = Describe("DocumentDB Controller", func() { Recorder: recorder, SQLExecutor: func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { sqlCalls = append(sqlCalls, sql) - if len(sqlCalls) == 1 { - // First call: version check — installed 0.109-0, default 0.110-0 + if strings.Contains(sql, "pg_available_extensions") { + // Version checks: installed 0.109-0, default 0.110-0 return " default_version | installed_version \n-----------------+-------------------\n 0.110-0 | 0.109-0 \n", nil } - // Second call: ALTER EXTENSION return "ALTER EXTENSION", nil }, } @@ -852,10 +851,11 @@ var _ = Describe("DocumentDB Controller", func() { err := reconciler.handleExtensionUpgrade(ctx, cluster, documentdb) Expect(err).ToNot(HaveOccurred()) - // Verify both SQL calls were made - Expect(sqlCalls).To(HaveLen(2)) + // Check both versions before upgrading core and DocumentDB atomically. + Expect(sqlCalls).To(HaveLen(3)) Expect(sqlCalls[0]).To(ContainSubstring("pg_available_extensions")) - Expect(sqlCalls[1]).To(Equal(`ALTER EXTENSION "documentdb" UPDATE`)) + Expect(sqlCalls[1]).To(ContainSubstring("name = 'documentdb_core'")) + Expect(sqlCalls[2]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '0.110-0'; ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'; COMMIT;`)) // Status should reflect the upgraded version (default version as semver) updatedDB := &dbv1.DocumentDB{} @@ -905,14 +905,12 @@ var _ = Describe("DocumentDB Controller", func() { WithStatusSubresource(&dbv1.DocumentDB{}). Build() - callCount := 0 reconciler := &DocumentDBReconciler{ Client: fakeClient, Scheme: scheme, Recorder: recorder, SQLExecutor: func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { - callCount++ - if callCount == 1 { + if strings.Contains(sql, "pg_available_extensions") { // Version check: upgrade needed return " default_version | installed_version \n-----------------+-------------------\n 0.110-0 | 0.109-0 \n", nil } @@ -1214,7 +1212,7 @@ var _ = Describe("DocumentDB Controller", func() { Recorder: recorder, SQLExecutor: func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { sqlCalls = append(sqlCalls, sql) - if len(sqlCalls) == 1 { + if strings.Contains(sql, "pg_available_extensions") { // default > installed → triggers ALTER EXTENSION return " default_version | installed_version \n-----------------+-------------------\n 0.110-0 | 0.109-0 \n", nil } @@ -1225,7 +1223,7 @@ var _ = Describe("DocumentDB Controller", func() { err := reconciler.handleExtensionUpgrade(ctx, cluster, documentdb) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("failed to update DocumentDB status after schema upgrade")) - Expect(sqlCalls).To(HaveLen(2)) + Expect(sqlCalls).To(HaveLen(3)) }) }) @@ -1349,7 +1347,7 @@ var _ = Describe("DocumentDB Controller", func() { Recorder: recorder, SQLExecutor: func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { sqlCalls = append(sqlCalls, sql) - if len(sqlCalls) == 1 { + if strings.Contains(sql, "pg_available_extensions") { return " default_version | installed_version \n-----------------+-------------------\n 0.110-0 | 0.109-0 \n", nil } return "ALTER EXTENSION", nil @@ -1359,10 +1357,11 @@ var _ = Describe("DocumentDB Controller", func() { err := reconciler.handleExtensionUpgrade(ctx, cluster, documentdb) Expect(err).ToNot(HaveOccurred()) - // Both version-check and ALTER EXTENSION should have been called - Expect(sqlCalls).To(HaveLen(2)) + // Check both versions before running the upgrade transaction. + Expect(sqlCalls).To(HaveLen(3)) Expect(sqlCalls[0]).To(ContainSubstring("pg_available_extensions")) - Expect(sqlCalls[1]).To(Equal(`ALTER EXTENSION "documentdb" UPDATE`)) + Expect(sqlCalls[1]).To(ContainSubstring("name = 'documentdb_core'")) + Expect(sqlCalls[2]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '0.110-0'; ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'; COMMIT;`)) // Status should reflect the upgraded version updatedDB := &dbv1.DocumentDB{} @@ -1420,7 +1419,7 @@ var _ = Describe("DocumentDB Controller", func() { Recorder: recorder, SQLExecutor: func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { sqlCalls = append(sqlCalls, sql) - if len(sqlCalls) == 1 { + if strings.Contains(sql, "pg_available_extensions") { // Binary is 0.110-0, installed is 0.109-0 return " default_version | installed_version \n-----------------+-------------------\n 0.110-0 | 0.109-0 \n", nil } @@ -1431,10 +1430,11 @@ var _ = Describe("DocumentDB Controller", func() { err := reconciler.handleExtensionUpgrade(ctx, cluster, documentdb) Expect(err).ToNot(HaveOccurred()) - // Should run ALTER EXTENSION UPDATE TO specific version - Expect(sqlCalls).To(HaveLen(2)) + // Both extensions must use the requested target version. + Expect(sqlCalls).To(HaveLen(3)) Expect(sqlCalls[0]).To(ContainSubstring("pg_available_extensions")) - Expect(sqlCalls[1]).To(Equal(`ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'`)) + Expect(sqlCalls[1]).To(ContainSubstring("name = 'documentdb_core'")) + Expect(sqlCalls[2]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '0.110-0'; ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'; COMMIT;`)) // Status should reflect the explicit version updatedDB := &dbv1.DocumentDB{} @@ -1570,8 +1570,9 @@ var _ = Describe("DocumentDB Controller", func() { err := reconciler.handleExtensionUpgrade(ctx, cluster, documentdb) Expect(err).ToNot(HaveOccurred()) - // Only version-check SQL should have been called (no ALTER EXTENSION) - Expect(sqlCalls).To(HaveLen(1)) + // Check both extensions, but do not migrate either one. + Expect(sqlCalls).To(HaveLen(2)) + Expect(sqlCalls[1]).To(ContainSubstring("name = 'documentdb_core'")) }) It("should handle unparseable binary version gracefully", func() { diff --git a/operator/src/internal/engine/extension.go b/operator/src/internal/engine/extension.go index 0c794b9c3..0841c7a22 100644 --- a/operator/src/internal/engine/extension.go +++ b/operator/src/internal/engine/extension.go @@ -156,8 +156,10 @@ func (r *ClusterReconciler[T]) HandleExtensionUpgrade(ctx context.Context, curre } } - // If versions match, no upgrade needed - if defaultVersion == installedVersion { + // An up-to-date main extension can still have outdated dependencies left + // by an earlier operator. Check them when schema upgrades are authorized. + if defaultVersion == installedVersion && + (len(r.profile().Postgres.ExtensionDependencies) == 0 || r.Adapter.Spec(obj).SchemaVersion == "") { logger.V(1).Info(name+" extension is up to date", "version", installedVersion) return nil } @@ -195,6 +197,14 @@ func (r *ClusterReconciler[T]) HandleExtensionUpgrade(ctx context.Context, curre return nil } + updateSQL, err = r.extensionUpgradeSQL(ctx, currentCluster, schemaTarget, installedVersion, updateSQL) + if err != nil { + return err + } + if updateSQL == "" { + return nil + } + // Run ALTER EXTENSION to upgrade logger.Info("Upgrading "+name+" extension", "fromVersion", installedVersion, @@ -221,6 +231,58 @@ func (r *ClusterReconciler[T]) HandleExtensionUpgrade(ctx context.Context, curre return nil } +func (r *ClusterReconciler[T]) extensionUpgradeSQL( + ctx context.Context, + cluster *cnpgv1.Cluster, + targetVersion, installedVersion, mainSQL string, +) (string, error) { + dependencies := r.profile().Postgres.ExtensionDependencies + var statements []string + for _, extension := range dependencies { + output, err := r.SQLExecutor(ctx, cluster, cnpg.ExtensionVersionSQL(extension)) + if err != nil { + return "", fmt.Errorf("failed to check %s extension versions: %w", extension, err) + } + defaultVersion, installed, ok := ParseExtensionVersions(output) + if !ok || defaultVersion == "" || installed == "" { + return "", fmt.Errorf("cannot upgrade dependency %s: extension versions missing or invalid: %q", extension, output) + } + binaryCmp, err := r.compareExtensionVersions(targetVersion, defaultVersion) + if err != nil { + return "", fmt.Errorf("failed to compare %s dependency binary version: %w", extension, err) + } + if binaryCmp > 0 { + return "", fmt.Errorf("cannot upgrade dependency %s to %s: binary offers %s", extension, targetVersion, defaultVersion) + } + installedCmp, err := r.compareExtensionVersions(targetVersion, installed) + if err != nil { + return "", fmt.Errorf("failed to compare %s dependency installed version: %w", extension, err) + } + if installedCmp < 0 { + return "", fmt.Errorf("cannot downgrade dependency %s from %s to %s", extension, installed, targetVersion) + } + if installedCmp > 0 { + statements = append(statements, cnpg.ExtensionUpdateSQL(extension, targetVersion)) + } + } + if targetVersion != installedVersion { + if len(dependencies) > 0 { + // Pin auto upgrades too, so every extension uses the same target, + // rather than each extension's potentially different default. + mainSQL = cnpg.ExtensionUpdateSQL(r.extensionName(), targetVersion) + } + statements = append(statements, mainSQL) + } + if len(statements) == 0 { + return "", nil + } + if len(dependencies) == 0 { + return mainSQL, nil + } + // Execute as one SQLExecutor call: separate calls use separate sessions. + return "BEGIN; " + strings.Join(statements, "; ") + "; COMMIT;", nil +} + func (r *ClusterReconciler[T]) setSchemaVersion(obj T, version string) { status := r.Adapter.Status(obj) status.SchemaVersion = version @@ -287,7 +349,7 @@ func (r *ClusterReconciler[T]) DetermineSchemaTarget( return "", "" } - // Check: target must be > installed version (otherwise no-op) + // An equal target can still require repairing outdated dependencies. installedCmp, err := r.compareExtensionVersions(targetPgVersion, installedVersion) if err != nil { logger.Error(err, "Failed to compare target schema version with installed version", @@ -295,7 +357,7 @@ func (r *ClusterReconciler[T]) DetermineSchemaTarget( "installedVersion", installedVersion) return "", "" } - if installedCmp <= 0 { + if installedCmp < 0 || (installedCmp == 0 && len(r.profile().Postgres.ExtensionDependencies) == 0) { logger.V(1).Info("Schema already at or beyond requested version", "requestedVersion", specSchemaVersion, "installedVersion", installedVersion) diff --git a/operator/src/internal/engine/extension_policy_test.go b/operator/src/internal/engine/extension_policy_test.go index a3740d1b0..b2c6d5d91 100644 --- a/operator/src/internal/engine/extension_policy_test.go +++ b/operator/src/internal/engine/extension_policy_test.go @@ -5,17 +5,20 @@ package engine import ( "context" + "fmt" "strings" "testing" cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" + "github.com/documentdb/documentdb-operator/internal/cnpg" "github.com/documentdb/documentdb-operator/internal/product" ) type extensionPolicyAdapter struct { product.DocumentDBAdapter - format product.ExtensionVersionFormat + format product.ExtensionVersionFormat + dependencies []string } func (a extensionPolicyAdapter) Profile() product.ProductProfile { @@ -23,6 +26,7 @@ func (a extensionPolicyAdapter) Profile() product.ProductProfile { p.Name = "Widget" p.Postgres.Extension.Name = "widget" p.Postgres.ExtensionVersionFormat = a.format + p.Postgres.ExtensionDependencies = a.dependencies return p } @@ -30,6 +34,7 @@ func TestHandleExtensionUpgradeVersionPolicy(t *testing.T) { for _, tc := range []struct { name string format product.ExtensionVersionFormat + dependencies []string installed, binary, requested string wantSQL, wantSchema, wantEvent string }{ @@ -94,6 +99,18 @@ func TestHandleExtensionUpgradeVersionPolicy(t *testing.T) { name: "dotted invalid target", format: product.ExtensionVersionSemver, installed: "1.2.3", binary: "1.3.0", requested: "not-a-version", wantSchema: "1.2.3", }, + { + name: "dotted auto with ordered dependencies", format: product.ExtensionVersionSemver, + dependencies: []string{"widget-types", "widget_core"}, + installed: "1.2.3", binary: "1.3.0", requested: "auto", wantSchema: "1.3.0", + wantSQL: `BEGIN; ALTER EXTENSION "widget-types" UPDATE TO '1.3.0'; ALTER EXTENSION "widget_core" UPDATE TO '1.3.0'; ALTER EXTENSION "widget" UPDATE TO '1.3.0'; COMMIT;`, + }, + { + name: "dotted prerelease with ordered dependencies", format: product.ExtensionVersionSemver, + dependencies: []string{"widget-types", "widget_core"}, + installed: "1.2.3", binary: "1.3.0", requested: "1.3.0-rc.1", wantSchema: "1.3.0-rc.1", + wantSQL: `BEGIN; ALTER EXTENSION "widget-types" UPDATE TO '1.3.0-rc.1'; ALTER EXTENSION "widget_core" UPDATE TO '1.3.0-rc.1'; ALTER EXTENSION "widget" UPDATE TO '1.3.0-rc.1'; COMMIT;`, + }, } { t.Run(tc.name, func(t *testing.T) { s := newTestScheme(t) @@ -101,7 +118,7 @@ func TestHandleExtensionUpgradeVersionPolicy(t *testing.T) { db.Spec.SchemaVersion = tc.requested c := newFakeClient(t, s, nil, db) r, rec := newClusterReconciler(c, s, &sqlRecorder{}) - r.Adapter = extensionPolicyAdapter{format: tc.format} + r.Adapter = extensionPolicyAdapter{format: tc.format, dependencies: tc.dependencies} var updates []string r.SQLExecutor = func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { if strings.Contains(sql, "pg_available_extensions") { @@ -133,3 +150,153 @@ func TestHandleExtensionUpgradeVersionPolicy(t *testing.T) { }) } } + +func TestHandleExtensionUpgradeDependencies(t *testing.T) { + const ( + bothSQL = `BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '1.0-0'; ALTER EXTENSION "documentdb" UPDATE TO '1.0-0'; COMMIT;` + coreSQL = `BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '1.0-0'; COMMIT;` + mainSQL = `BEGIN; ALTER EXTENSION "documentdb" UPDATE TO '1.0-0'; COMMIT;` + ) + for _, tc := range []struct { + name, requested, installed, binary string + coreInstalled, coreBinary string + coreOutput, wantSQL, wantErr string + queryErr, updateErr bool + }{ + {name: "auto upgrades core first", requested: "auto", wantSQL: bothSQL}, + {name: "explicit upgrades core first", requested: "1.0.0", wantSQL: bothSQL}, + { + name: "explicit intermediate target does not use dependency default", + requested: "1.0.0", binary: "1.1-0", coreBinary: "1.1-0", wantSQL: bothSQL, + }, + {name: "core already current", requested: "auto", coreInstalled: "1.0-0", wantSQL: mainSQL}, + {name: "repair auto", requested: "auto", installed: "1.0-0", wantSQL: coreSQL}, + {name: "repair explicit", requested: "1.0.0", installed: "1.0-0", wantSQL: coreSQL}, + { + name: "repair explicit below binary", requested: "1.0.0", installed: "1.0-0", + binary: "1.1-0", coreBinary: "1.1-0", wantSQL: coreSQL, + }, + {name: "already current", requested: "auto", installed: "1.0-0", coreInstalled: "1.0-0"}, + {name: "two phase leaves both unchanged"}, + {name: "two phase does not repair without authorization", installed: "1.0-0"}, + {name: "older explicit target does not downgrade", requested: "0.116.0"}, + {name: "invalid explicit target does not repair", requested: "invalid", installed: "1.0-0"}, + {name: "target above binary does not repair", requested: "1.1.0", installed: "1.0-0"}, + {name: "binary rollback does not upgrade dependencies", requested: "auto", installed: "1.1-0"}, + { + name: "dependency downgrade rejected", requested: "auto", + coreInstalled: "1.1-0", coreBinary: "1.1-0", wantErr: "cannot downgrade dependency documentdb_core", + }, + { + name: "dependency binary too old", requested: "auto", + coreBinary: "0.117-0", wantErr: "binary offers 0.117-0", + }, + { + name: "invalid dependency binary", requested: "auto", + coreBinary: "invalid", wantErr: "failed to compare documentdb_core dependency binary version", + }, + { + name: "invalid dependency installed version", requested: "auto", + coreInstalled: "invalid", wantErr: "failed to compare documentdb_core dependency installed version", + }, + { + name: "missing dependency", requested: "auto", + coreOutput: "(0 rows)", wantErr: "extension versions missing or invalid", + }, + { + name: "uninstalled dependency", requested: "auto", + coreOutput: "default_version | installed_version\n---+---\n1.0-0 | \n(1 row)", + wantErr: "extension versions missing or invalid", + }, + { + name: "dependency query failure", requested: "auto", + queryErr: true, wantErr: "failed to check documentdb_core extension versions", + }, + { + name: "transaction failure does not advance schema status", requested: "auto", + updateErr: true, wantSQL: bothSQL, wantErr: "failed to run ALTER EXTENSION documentdb UPDATE", + }, + } { + t.Run(tc.name, func(t *testing.T) { + installed, binary := tc.installed, tc.binary + coreInstalled, coreBinary := tc.coreInstalled, tc.coreBinary + if installed == "" { + installed = "0.117-0" + } + if binary == "" { + binary = "1.0-0" + } + if coreInstalled == "" { + coreInstalled = "0.117-0" + } + if coreBinary == "" { + coreBinary = "1.0-0" + } + versions := func(binary, installed string) string { + return fmt.Sprintf("default_version | installed_version\n---+---\n%s | %s\n(1 row)", binary, installed) + } + s := newTestScheme(t) + db := reconcilableCluster() + db.Spec.SchemaVersion = tc.requested + c := newFakeClient(t, s, nil, db) + r, _ := newClusterReconciler(c, s, &sqlRecorder{}) + var updates []string + r.SQLExecutor = func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { + switch sql { + case cnpg.ExtensionVersionSQL("documentdb"): + return versions(binary, installed), nil + case cnpg.ExtensionVersionSQL("documentdb_core"): + if tc.queryErr { + return "", errInjected + } + if tc.coreOutput != "" { + return tc.coreOutput, nil + } + return versions(coreBinary, coreInstalled), nil + default: + if !strings.HasPrefix(sql, "BEGIN;") { + t.Fatalf("unexpected SQL: %s", sql) + } + updates = append(updates, sql) + if tc.updateErr { + return "", errInjected + } + installed, coreInstalled = "1.0-0", "1.0-0" + return "", nil + } + } + cluster := &cnpgv1.Cluster{Status: cnpgv1.ClusterStatus{ + CurrentPrimary: "db-1", + InstancesStatus: map[cnpgv1.PodStatus][]string{cnpgv1.PodHealthy: {"db-1"}}, + }} + wantSchema := r.extensionVersionToSemver(installed) + err := r.HandleExtensionUpgrade(context.Background(), cluster, db) + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + } else if err != nil { + t.Fatal(err) + } + if tc.wantSQL == "" { + if len(updates) != 0 { + t.Fatalf("unexpected updates: %q", updates) + } + } else if len(updates) != 1 || updates[0] != tc.wantSQL { + t.Fatalf("updates = %q, want %q", updates, tc.wantSQL) + } + if tc.wantSQL != "" && tc.wantErr == "" { + wantSchema = "1.0.0" + if err := r.HandleExtensionUpgrade(context.Background(), cluster, db); err != nil { + t.Fatalf("repeat reconcile: %v", err) + } + if len(updates) != 1 { + t.Fatalf("repeat reconcile ran another upgrade: %q", updates) + } + } + if got := getDocumentDB(t, c).Status.SchemaVersion; got != wantSchema { + t.Errorf("schema status = %q, want %q", got, wantSchema) + } + }) + } +} diff --git a/operator/src/internal/product/documentdb.go b/operator/src/internal/product/documentdb.go index 3212e57dc..18a25eb20 100644 --- a/operator/src/internal/product/documentdb.go +++ b/operator/src/internal/product/documentdb.go @@ -29,7 +29,8 @@ func DocumentDBProfile() ProductProfile { ExtensionControlPath: []string{"share"}, LdLibraryPath: []string{"lib", "system"}, }, - AdditionalLibraries: []string{"pg_cron", "pg_documentdb_core", "pg_documentdb"}, + ExtensionDependencies: []string{"documentdb_core"}, + AdditionalLibraries: []string{"pg_cron", "pg_documentdb_core", "pg_documentdb"}, BootstrapSQL: []string{ "CREATE EXTENSION documentdb CASCADE", "CREATE ROLE documentdb WITH LOGIN PASSWORD 'Admin100'", diff --git a/operator/src/internal/product/profile.go b/operator/src/internal/product/profile.go index 5704b3384..793bf4153 100644 --- a/operator/src/internal/product/profile.go +++ b/operator/src/internal/product/profile.go @@ -99,6 +99,10 @@ type PostgresProfile struct { // ExtensionVersionFormat controls extension comparison and spec/status // conversion. Its zero value preserves DocumentDB's version convention. ExtensionVersionFormat ExtensionVersionFormat + // ExtensionDependencies lists co-versioned extensions to upgrade before + // Extension, in dependency order, to the same target version and in the + // same transaction. Do not include independently versioned dependencies. + ExtensionDependencies []string // AdditionalLibraries are added to shared_preload_libraries. AdditionalLibraries []string // BootstrapSQL runs once at initdb, before any user PostInitSQL. diff --git a/test/e2e/tests/upgrade/helpers_test.go b/test/e2e/tests/upgrade/helpers_test.go index 70a1e5f1f..f2d39c966 100644 --- a/test/e2e/tests/upgrade/helpers_test.go +++ b/test/e2e/tests/upgrade/helpers_test.go @@ -251,8 +251,29 @@ func replicaInstalledSchemaVersion( return agreed, nil } -// podInstalledSchemaVersion execs psql on a single pod and returns the -// installed documentdb extension version normalized to semver. +func primaryInstalledSchemaVersion( + ctx context.Context, + env *environment.TestingEnvironment, + ns, clusterName string, +) (string, error) { + var pods corev1.PodList + if err := env.Client.List(ctx, &pods, + client.InNamespace(ns), + client.MatchingLabels{ + "cnpg.io/cluster": clusterName, + "cnpg.io/instanceRole": "primary", + }, + ); err != nil { + return "", fmt.Errorf("list primary pod for cluster %s/%s: %w", ns, clusterName, err) + } + if len(pods.Items) != 1 { + return "", fmt.Errorf("expected one primary pod for cluster %s/%s, found %d", ns, clusterName, len(pods.Items)) + } + return podInstalledSchemaVersion(ctx, env, pods.Items[0]) +} + +// podInstalledSchemaVersion requires documentdb and documentdb_core to agree +// and returns their installed version normalized to semver. func podInstalledSchemaVersion( ctx context.Context, env *environment.TestingEnvironment, @@ -261,15 +282,20 @@ func podInstalledSchemaVersion( timeout := time.Minute stdout, stderr, err := env.EventuallyExecCommand(ctx, pod, "postgres", &timeout, "psql", "-U", "postgres", "-d", "postgres", "-tAc", - "SELECT extversion FROM pg_extension WHERE extname='documentdb'") + "SELECT extversion FROM pg_extension WHERE extname IN ('documentdb', 'documentdb_core') ORDER BY extname") if err != nil { return "", fmt.Errorf("exec psql on pod %s: %w (stderr: %s)", pod.Name, err, stderr) } - raw := strings.TrimSpace(stdout) - if raw == "" { - return "", fmt.Errorf("documentdb extension not installed on pod %s", pod.Name) + versions := strings.Fields(stdout) + if len(versions) != 2 { + return "", fmt.Errorf("expected documentdb and documentdb_core versions on pod %s, got %q", pod.Name, stdout) + } + if versions[0] != versions[1] { + return "", fmt.Errorf("extension versions differ on pod %s: documentdb=%s, documentdb_core=%s", + pod.Name, versions[0], versions[1]) } + raw := versions[0] // "0.110-0" -> "0.110.0"; a value already in semver form is unchanged. if i := strings.LastIndex(raw, "-"); i >= 0 { raw = raw[:i] + "." + raw[i+1:] diff --git a/test/e2e/tests/upgrade/upgrade_schema_auto_test.go b/test/e2e/tests/upgrade/upgrade_schema_auto_test.go index 41d70bbe4..5983f90d5 100644 --- a/test/e2e/tests/upgrade/upgrade_schema_auto_test.go +++ b/test/e2e/tests/upgrade/upgrade_schema_auto_test.go @@ -159,6 +159,14 @@ var _ = Describe("DocumentDB upgrade — schema (auto mode)", timeouts.PollInterval(timeouts.DocumentDBUpgrade), ).Should(Equal(newVersion), "auto mode should migrate schema to %s in a single step", newVersion) + By("verifying documentdb and documentdb_core both migrated") + Eventually(func() (string, error) { + return primaryInstalledSchemaVersion(ctx, env, ns, ddName) + }, + timeouts.For(timeouts.DocumentDBUpgrade), + timeouts.PollInterval(timeouts.DocumentDBUpgrade), + ).Should(Equal(newVersion), "both extensions must migrate to %s in auto mode", newVersion) + By("verifying seeded data survived the single-step upgrade") handle2, err := e2emongo.NewFromDocumentDB(ctx, env, ns, ddName) Expect(err).NotTo(HaveOccurred(), "reconnect to DocumentDB gateway after single-step upgrade") diff --git a/test/e2e/tests/upgrade/upgrade_schema_test.go b/test/e2e/tests/upgrade/upgrade_schema_test.go index 6348fa9cf..0cc4132a0 100644 --- a/test/e2e/tests/upgrade/upgrade_schema_test.go +++ b/test/e2e/tests/upgrade/upgrade_schema_test.go @@ -144,6 +144,9 @@ var _ = Describe("DocumentDB upgrade — schema", // Consistently below: it caches the last good read so a transient // API error can't fail the Consistently window (see helper doc). schemaVersion := schemaVersionGetter(ctx, c, key) + installedSchemaVersion := func() (string, error) { + return primaryInstalledSchemaVersion(ctx, env, ns, ddName) + } By("waiting for status.schemaVersion to settle on the old version") Eventually(schemaVersion, @@ -151,6 +154,11 @@ var _ = Describe("DocumentDB upgrade — schema", timeouts.PollInterval(timeouts.DocumentDBReady), ).Should(Equal(oldVersion), "initial schema version should be %s", oldVersion) + Eventually(installedSchemaVersion, + timeouts.For(timeouts.DocumentDBReady), + timeouts.PollInterval(timeouts.DocumentDBReady), + ).Should(Equal(oldVersion), "both extensions must start at %s", oldVersion) + By("seeding data on the old schema") docs := seed.SmallDataset() handle, err := e2emongo.NewFromDocumentDB(ctx, env, ns, ddName) @@ -192,6 +200,10 @@ var _ = Describe("DocumentDB upgrade — schema", ).Should(Equal(oldVersion), "schema must remain at %s until spec.schemaVersion is set (two-phase)", oldVersion) + Consistently(installedSchemaVersion, + 15*time.Second, 5*time.Second, + ).Should(Equal(oldVersion), "neither extension may migrate before schema finalization") + By("verifying seeded data survived the binary upgrade") handle2, err := e2emongo.NewFromDocumentDB(ctx, env, ns, ddName) Expect(err).NotTo(HaveOccurred(), "reconnect to DocumentDB gateway after binary upgrade") @@ -214,6 +226,11 @@ var _ = Describe("DocumentDB upgrade — schema", timeouts.PollInterval(timeouts.DocumentDBUpgrade), ).Should(Equal(newVersion), "schema did not migrate to %s after finalize", newVersion) + Eventually(installedSchemaVersion, + timeouts.For(timeouts.DocumentDBUpgrade), + timeouts.PollInterval(timeouts.DocumentDBUpgrade), + ).Should(Equal(newVersion), "both extensions must migrate to %s", newVersion) + Eventually(assertions.AssertDocumentDBReady(ctx, c, key), timeouts.For(timeouts.DocumentDBUpgrade), timeouts.PollInterval(timeouts.DocumentDBUpgrade), From 414e7473bd696d37fa61a5b9e821cf8643b12c39 Mon Sep 17 00:00:00 2001 From: Wenting Wu Date: Wed, 11 Nov 2026 15:48:27 -0500 Subject: [PATCH 2/5] refactor: keep core extension upgrade fix minimal Limit the fix to upgrading documentdb_core before documentdb in the existing upgrade transaction. Remove dependency prechecks and existing-mismatch repair while retaining same-target upgrades, existing schema gates, and focused regression coverage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 251a6aad-1c9b-4e75-9768-1d79b8eb8a7f Signed-off-by: Wenting Wu --- docs/designs/product-neutral-core.md | 14 +- .../controller/documentdb_controller_test.go | 43 +++-- operator/src/internal/engine/extension.go | 77 ++------ .../internal/engine/extension_policy_test.go | 169 ++---------------- test/e2e/tests/upgrade/upgrade_schema_test.go | 9 - 5 files changed, 50 insertions(+), 262 deletions(-) diff --git a/docs/designs/product-neutral-core.md b/docs/designs/product-neutral-core.md index 9622462b3..9fb6fe40e 100644 --- a/docs/designs/product-neutral-core.md +++ b/docs/designs/product-neutral-core.md @@ -99,15 +99,11 @@ whose PostgreSQL extension uses dotted semantic versions set `core.ExtensionVersionSemver`; automatic upgrades, explicit targets, comparison, events, and schema status then use that format without rewriting it. -`PostgresProfile.ExtensionDependencies` lists only dependencies that share the -main extension's version, in upgrade order. The reconciler upgrades them before -the main extension in one transaction, using the same explicit target for all -extensions, including in `auto` mode. DocumentDB configures `documentdb_core`; -independently versioned dependencies such as PostGIS and pg_cron are not -automatically upgraded. With `schemaVersion` set to `auto` or the installed main -extension version, reconciliation also repairs dependencies left behind by an -earlier operator, even if the main extension is already current. An unset -`schemaVersion` still leaves all extension schemas untouched. +`PostgresProfile.ExtensionDependencies` lists co-versioned dependencies to +upgrade before the main extension, to the same target in one transaction. +DocumentDB configures only `documentdb_core`, not independently versioned +dependencies such as PostGIS or pg_cron. This applies when the main extension +is upgraded; it does not repair existing version mismatches. The DocumentDB controllers and webhook in `internal/controller` and `internal/webhook` are now thin wrappers over these packages. They keep their diff --git a/operator/src/internal/controller/documentdb_controller_test.go b/operator/src/internal/controller/documentdb_controller_test.go index 3528fb0c5..d078bd2b7 100644 --- a/operator/src/internal/controller/documentdb_controller_test.go +++ b/operator/src/internal/controller/documentdb_controller_test.go @@ -840,10 +840,11 @@ var _ = Describe("DocumentDB Controller", func() { Recorder: recorder, SQLExecutor: func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { sqlCalls = append(sqlCalls, sql) - if strings.Contains(sql, "pg_available_extensions") { - // Version checks: installed 0.109-0, default 0.110-0 + if len(sqlCalls) == 1 { + // First call: version check — installed 0.109-0, default 0.110-0 return " default_version | installed_version \n-----------------+-------------------\n 0.110-0 | 0.109-0 \n", nil } + // Second call: ALTER EXTENSION return "ALTER EXTENSION", nil }, } @@ -851,11 +852,10 @@ var _ = Describe("DocumentDB Controller", func() { err := reconciler.handleExtensionUpgrade(ctx, cluster, documentdb) Expect(err).ToNot(HaveOccurred()) - // Check both versions before upgrading core and DocumentDB atomically. - Expect(sqlCalls).To(HaveLen(3)) + // Verify both SQL calls were made + Expect(sqlCalls).To(HaveLen(2)) Expect(sqlCalls[0]).To(ContainSubstring("pg_available_extensions")) - Expect(sqlCalls[1]).To(ContainSubstring("name = 'documentdb_core'")) - Expect(sqlCalls[2]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '0.110-0'; ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'; COMMIT;`)) + Expect(sqlCalls[1]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '0.110-0'; ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'; COMMIT;`)) // Status should reflect the upgraded version (default version as semver) updatedDB := &dbv1.DocumentDB{} @@ -905,12 +905,14 @@ var _ = Describe("DocumentDB Controller", func() { WithStatusSubresource(&dbv1.DocumentDB{}). Build() + callCount := 0 reconciler := &DocumentDBReconciler{ Client: fakeClient, Scheme: scheme, Recorder: recorder, SQLExecutor: func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { - if strings.Contains(sql, "pg_available_extensions") { + callCount++ + if callCount == 1 { // Version check: upgrade needed return " default_version | installed_version \n-----------------+-------------------\n 0.110-0 | 0.109-0 \n", nil } @@ -1212,7 +1214,7 @@ var _ = Describe("DocumentDB Controller", func() { Recorder: recorder, SQLExecutor: func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { sqlCalls = append(sqlCalls, sql) - if strings.Contains(sql, "pg_available_extensions") { + if len(sqlCalls) == 1 { // default > installed → triggers ALTER EXTENSION return " default_version | installed_version \n-----------------+-------------------\n 0.110-0 | 0.109-0 \n", nil } @@ -1223,7 +1225,7 @@ var _ = Describe("DocumentDB Controller", func() { err := reconciler.handleExtensionUpgrade(ctx, cluster, documentdb) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("failed to update DocumentDB status after schema upgrade")) - Expect(sqlCalls).To(HaveLen(3)) + Expect(sqlCalls).To(HaveLen(2)) }) }) @@ -1347,7 +1349,7 @@ var _ = Describe("DocumentDB Controller", func() { Recorder: recorder, SQLExecutor: func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { sqlCalls = append(sqlCalls, sql) - if strings.Contains(sql, "pg_available_extensions") { + if len(sqlCalls) == 1 { return " default_version | installed_version \n-----------------+-------------------\n 0.110-0 | 0.109-0 \n", nil } return "ALTER EXTENSION", nil @@ -1357,11 +1359,10 @@ var _ = Describe("DocumentDB Controller", func() { err := reconciler.handleExtensionUpgrade(ctx, cluster, documentdb) Expect(err).ToNot(HaveOccurred()) - // Check both versions before running the upgrade transaction. - Expect(sqlCalls).To(HaveLen(3)) + // Both version-check and ALTER EXTENSION should have been called + Expect(sqlCalls).To(HaveLen(2)) Expect(sqlCalls[0]).To(ContainSubstring("pg_available_extensions")) - Expect(sqlCalls[1]).To(ContainSubstring("name = 'documentdb_core'")) - Expect(sqlCalls[2]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '0.110-0'; ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'; COMMIT;`)) + Expect(sqlCalls[1]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '0.110-0'; ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'; COMMIT;`)) // Status should reflect the upgraded version updatedDB := &dbv1.DocumentDB{} @@ -1419,7 +1420,7 @@ var _ = Describe("DocumentDB Controller", func() { Recorder: recorder, SQLExecutor: func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { sqlCalls = append(sqlCalls, sql) - if strings.Contains(sql, "pg_available_extensions") { + if len(sqlCalls) == 1 { // Binary is 0.110-0, installed is 0.109-0 return " default_version | installed_version \n-----------------+-------------------\n 0.110-0 | 0.109-0 \n", nil } @@ -1430,11 +1431,10 @@ var _ = Describe("DocumentDB Controller", func() { err := reconciler.handleExtensionUpgrade(ctx, cluster, documentdb) Expect(err).ToNot(HaveOccurred()) - // Both extensions must use the requested target version. - Expect(sqlCalls).To(HaveLen(3)) + // Should run ALTER EXTENSION UPDATE TO specific version + Expect(sqlCalls).To(HaveLen(2)) Expect(sqlCalls[0]).To(ContainSubstring("pg_available_extensions")) - Expect(sqlCalls[1]).To(ContainSubstring("name = 'documentdb_core'")) - Expect(sqlCalls[2]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '0.110-0'; ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'; COMMIT;`)) + Expect(sqlCalls[1]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '0.110-0'; ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'; COMMIT;`)) // Status should reflect the explicit version updatedDB := &dbv1.DocumentDB{} @@ -1570,9 +1570,8 @@ var _ = Describe("DocumentDB Controller", func() { err := reconciler.handleExtensionUpgrade(ctx, cluster, documentdb) Expect(err).ToNot(HaveOccurred()) - // Check both extensions, but do not migrate either one. - Expect(sqlCalls).To(HaveLen(2)) - Expect(sqlCalls[1]).To(ContainSubstring("name = 'documentdb_core'")) + // Only version-check SQL should have been called (no ALTER EXTENSION) + Expect(sqlCalls).To(HaveLen(1)) }) It("should handle unparseable binary version gracefully", func() { diff --git a/operator/src/internal/engine/extension.go b/operator/src/internal/engine/extension.go index 0841c7a22..50e5437fb 100644 --- a/operator/src/internal/engine/extension.go +++ b/operator/src/internal/engine/extension.go @@ -156,10 +156,8 @@ func (r *ClusterReconciler[T]) HandleExtensionUpgrade(ctx context.Context, curre } } - // An up-to-date main extension can still have outdated dependencies left - // by an earlier operator. Check them when schema upgrades are authorized. - if defaultVersion == installedVersion && - (len(r.profile().Postgres.ExtensionDependencies) == 0 || r.Adapter.Spec(obj).SchemaVersion == "") { + // If versions match, no upgrade needed + if defaultVersion == installedVersion { logger.V(1).Info(name+" extension is up to date", "version", installedVersion) return nil } @@ -197,12 +195,15 @@ func (r *ClusterReconciler[T]) HandleExtensionUpgrade(ctx context.Context, curre return nil } - updateSQL, err = r.extensionUpgradeSQL(ctx, currentCluster, schemaTarget, installedVersion, updateSQL) - if err != nil { - return err - } - if updateSQL == "" { - return nil + if dependencies := r.profile().Postgres.ExtensionDependencies; len(dependencies) > 0 { + // ALTER EXTENSION does not upgrade dependencies. Use one transaction + // and pin every extension to the same target, including in auto mode. + statements := []string{"BEGIN"} + for _, dependency := range dependencies { + statements = append(statements, cnpg.ExtensionUpdateSQL(dependency, schemaTarget)) + } + statements = append(statements, cnpg.ExtensionUpdateSQL(extension, schemaTarget), "COMMIT") + updateSQL = strings.Join(statements, "; ") + ";" } // Run ALTER EXTENSION to upgrade @@ -231,58 +232,6 @@ func (r *ClusterReconciler[T]) HandleExtensionUpgrade(ctx context.Context, curre return nil } -func (r *ClusterReconciler[T]) extensionUpgradeSQL( - ctx context.Context, - cluster *cnpgv1.Cluster, - targetVersion, installedVersion, mainSQL string, -) (string, error) { - dependencies := r.profile().Postgres.ExtensionDependencies - var statements []string - for _, extension := range dependencies { - output, err := r.SQLExecutor(ctx, cluster, cnpg.ExtensionVersionSQL(extension)) - if err != nil { - return "", fmt.Errorf("failed to check %s extension versions: %w", extension, err) - } - defaultVersion, installed, ok := ParseExtensionVersions(output) - if !ok || defaultVersion == "" || installed == "" { - return "", fmt.Errorf("cannot upgrade dependency %s: extension versions missing or invalid: %q", extension, output) - } - binaryCmp, err := r.compareExtensionVersions(targetVersion, defaultVersion) - if err != nil { - return "", fmt.Errorf("failed to compare %s dependency binary version: %w", extension, err) - } - if binaryCmp > 0 { - return "", fmt.Errorf("cannot upgrade dependency %s to %s: binary offers %s", extension, targetVersion, defaultVersion) - } - installedCmp, err := r.compareExtensionVersions(targetVersion, installed) - if err != nil { - return "", fmt.Errorf("failed to compare %s dependency installed version: %w", extension, err) - } - if installedCmp < 0 { - return "", fmt.Errorf("cannot downgrade dependency %s from %s to %s", extension, installed, targetVersion) - } - if installedCmp > 0 { - statements = append(statements, cnpg.ExtensionUpdateSQL(extension, targetVersion)) - } - } - if targetVersion != installedVersion { - if len(dependencies) > 0 { - // Pin auto upgrades too, so every extension uses the same target, - // rather than each extension's potentially different default. - mainSQL = cnpg.ExtensionUpdateSQL(r.extensionName(), targetVersion) - } - statements = append(statements, mainSQL) - } - if len(statements) == 0 { - return "", nil - } - if len(dependencies) == 0 { - return mainSQL, nil - } - // Execute as one SQLExecutor call: separate calls use separate sessions. - return "BEGIN; " + strings.Join(statements, "; ") + "; COMMIT;", nil -} - func (r *ClusterReconciler[T]) setSchemaVersion(obj T, version string) { status := r.Adapter.Status(obj) status.SchemaVersion = version @@ -349,7 +298,7 @@ func (r *ClusterReconciler[T]) DetermineSchemaTarget( return "", "" } - // An equal target can still require repairing outdated dependencies. + // Check: target must be > installed version (otherwise no-op) installedCmp, err := r.compareExtensionVersions(targetPgVersion, installedVersion) if err != nil { logger.Error(err, "Failed to compare target schema version with installed version", @@ -357,7 +306,7 @@ func (r *ClusterReconciler[T]) DetermineSchemaTarget( "installedVersion", installedVersion) return "", "" } - if installedCmp < 0 || (installedCmp == 0 && len(r.profile().Postgres.ExtensionDependencies) == 0) { + if installedCmp <= 0 { logger.V(1).Info("Schema already at or beyond requested version", "requestedVersion", specSchemaVersion, "installedVersion", installedVersion) diff --git a/operator/src/internal/engine/extension_policy_test.go b/operator/src/internal/engine/extension_policy_test.go index b2c6d5d91..2ea4a3444 100644 --- a/operator/src/internal/engine/extension_policy_test.go +++ b/operator/src/internal/engine/extension_policy_test.go @@ -5,13 +5,11 @@ package engine import ( "context" - "fmt" "strings" "testing" cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" - "github.com/documentdb/documentdb-operator/internal/cnpg" "github.com/documentdb/documentdb-operator/internal/product" ) @@ -100,16 +98,21 @@ func TestHandleExtensionUpgradeVersionPolicy(t *testing.T) { installed: "1.2.3", binary: "1.3.0", requested: "not-a-version", wantSchema: "1.2.3", }, { - name: "dotted auto with ordered dependencies", format: product.ExtensionVersionSemver, - dependencies: []string{"widget-types", "widget_core"}, + name: "dotted auto with dependency", format: product.ExtensionVersionSemver, + dependencies: []string{"widget_core"}, installed: "1.2.3", binary: "1.3.0", requested: "auto", wantSchema: "1.3.0", - wantSQL: `BEGIN; ALTER EXTENSION "widget-types" UPDATE TO '1.3.0'; ALTER EXTENSION "widget_core" UPDATE TO '1.3.0'; ALTER EXTENSION "widget" UPDATE TO '1.3.0'; COMMIT;`, + wantSQL: `BEGIN; ALTER EXTENSION "widget_core" UPDATE TO '1.3.0'; ALTER EXTENSION "widget" UPDATE TO '1.3.0'; COMMIT;`, }, { - name: "dotted prerelease with ordered dependencies", format: product.ExtensionVersionSemver, - dependencies: []string{"widget-types", "widget_core"}, + name: "dotted explicit dependency target below binary", format: product.ExtensionVersionSemver, + dependencies: []string{"widget_core"}, installed: "1.2.3", binary: "1.3.0", requested: "1.3.0-rc.1", wantSchema: "1.3.0-rc.1", - wantSQL: `BEGIN; ALTER EXTENSION "widget-types" UPDATE TO '1.3.0-rc.1'; ALTER EXTENSION "widget_core" UPDATE TO '1.3.0-rc.1'; ALTER EXTENSION "widget" UPDATE TO '1.3.0-rc.1'; COMMIT;`, + wantSQL: `BEGIN; ALTER EXTENSION "widget_core" UPDATE TO '1.3.0-rc.1'; ALTER EXTENSION "widget" UPDATE TO '1.3.0-rc.1'; COMMIT;`, + }, + { + name: "dotted two phase with dependency", format: product.ExtensionVersionSemver, + dependencies: []string{"widget_core"}, + installed: "1.2.3", binary: "1.3.0", wantSchema: "1.2.3", }, } { t.Run(tc.name, func(t *testing.T) { @@ -150,153 +153,3 @@ func TestHandleExtensionUpgradeVersionPolicy(t *testing.T) { }) } } - -func TestHandleExtensionUpgradeDependencies(t *testing.T) { - const ( - bothSQL = `BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '1.0-0'; ALTER EXTENSION "documentdb" UPDATE TO '1.0-0'; COMMIT;` - coreSQL = `BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '1.0-0'; COMMIT;` - mainSQL = `BEGIN; ALTER EXTENSION "documentdb" UPDATE TO '1.0-0'; COMMIT;` - ) - for _, tc := range []struct { - name, requested, installed, binary string - coreInstalled, coreBinary string - coreOutput, wantSQL, wantErr string - queryErr, updateErr bool - }{ - {name: "auto upgrades core first", requested: "auto", wantSQL: bothSQL}, - {name: "explicit upgrades core first", requested: "1.0.0", wantSQL: bothSQL}, - { - name: "explicit intermediate target does not use dependency default", - requested: "1.0.0", binary: "1.1-0", coreBinary: "1.1-0", wantSQL: bothSQL, - }, - {name: "core already current", requested: "auto", coreInstalled: "1.0-0", wantSQL: mainSQL}, - {name: "repair auto", requested: "auto", installed: "1.0-0", wantSQL: coreSQL}, - {name: "repair explicit", requested: "1.0.0", installed: "1.0-0", wantSQL: coreSQL}, - { - name: "repair explicit below binary", requested: "1.0.0", installed: "1.0-0", - binary: "1.1-0", coreBinary: "1.1-0", wantSQL: coreSQL, - }, - {name: "already current", requested: "auto", installed: "1.0-0", coreInstalled: "1.0-0"}, - {name: "two phase leaves both unchanged"}, - {name: "two phase does not repair without authorization", installed: "1.0-0"}, - {name: "older explicit target does not downgrade", requested: "0.116.0"}, - {name: "invalid explicit target does not repair", requested: "invalid", installed: "1.0-0"}, - {name: "target above binary does not repair", requested: "1.1.0", installed: "1.0-0"}, - {name: "binary rollback does not upgrade dependencies", requested: "auto", installed: "1.1-0"}, - { - name: "dependency downgrade rejected", requested: "auto", - coreInstalled: "1.1-0", coreBinary: "1.1-0", wantErr: "cannot downgrade dependency documentdb_core", - }, - { - name: "dependency binary too old", requested: "auto", - coreBinary: "0.117-0", wantErr: "binary offers 0.117-0", - }, - { - name: "invalid dependency binary", requested: "auto", - coreBinary: "invalid", wantErr: "failed to compare documentdb_core dependency binary version", - }, - { - name: "invalid dependency installed version", requested: "auto", - coreInstalled: "invalid", wantErr: "failed to compare documentdb_core dependency installed version", - }, - { - name: "missing dependency", requested: "auto", - coreOutput: "(0 rows)", wantErr: "extension versions missing or invalid", - }, - { - name: "uninstalled dependency", requested: "auto", - coreOutput: "default_version | installed_version\n---+---\n1.0-0 | \n(1 row)", - wantErr: "extension versions missing or invalid", - }, - { - name: "dependency query failure", requested: "auto", - queryErr: true, wantErr: "failed to check documentdb_core extension versions", - }, - { - name: "transaction failure does not advance schema status", requested: "auto", - updateErr: true, wantSQL: bothSQL, wantErr: "failed to run ALTER EXTENSION documentdb UPDATE", - }, - } { - t.Run(tc.name, func(t *testing.T) { - installed, binary := tc.installed, tc.binary - coreInstalled, coreBinary := tc.coreInstalled, tc.coreBinary - if installed == "" { - installed = "0.117-0" - } - if binary == "" { - binary = "1.0-0" - } - if coreInstalled == "" { - coreInstalled = "0.117-0" - } - if coreBinary == "" { - coreBinary = "1.0-0" - } - versions := func(binary, installed string) string { - return fmt.Sprintf("default_version | installed_version\n---+---\n%s | %s\n(1 row)", binary, installed) - } - s := newTestScheme(t) - db := reconcilableCluster() - db.Spec.SchemaVersion = tc.requested - c := newFakeClient(t, s, nil, db) - r, _ := newClusterReconciler(c, s, &sqlRecorder{}) - var updates []string - r.SQLExecutor = func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { - switch sql { - case cnpg.ExtensionVersionSQL("documentdb"): - return versions(binary, installed), nil - case cnpg.ExtensionVersionSQL("documentdb_core"): - if tc.queryErr { - return "", errInjected - } - if tc.coreOutput != "" { - return tc.coreOutput, nil - } - return versions(coreBinary, coreInstalled), nil - default: - if !strings.HasPrefix(sql, "BEGIN;") { - t.Fatalf("unexpected SQL: %s", sql) - } - updates = append(updates, sql) - if tc.updateErr { - return "", errInjected - } - installed, coreInstalled = "1.0-0", "1.0-0" - return "", nil - } - } - cluster := &cnpgv1.Cluster{Status: cnpgv1.ClusterStatus{ - CurrentPrimary: "db-1", - InstancesStatus: map[cnpgv1.PodStatus][]string{cnpgv1.PodHealthy: {"db-1"}}, - }} - wantSchema := r.extensionVersionToSemver(installed) - err := r.HandleExtensionUpgrade(context.Background(), cluster, db) - if tc.wantErr != "" { - if err == nil || !strings.Contains(err.Error(), tc.wantErr) { - t.Fatalf("error = %v, want %q", err, tc.wantErr) - } - } else if err != nil { - t.Fatal(err) - } - if tc.wantSQL == "" { - if len(updates) != 0 { - t.Fatalf("unexpected updates: %q", updates) - } - } else if len(updates) != 1 || updates[0] != tc.wantSQL { - t.Fatalf("updates = %q, want %q", updates, tc.wantSQL) - } - if tc.wantSQL != "" && tc.wantErr == "" { - wantSchema = "1.0.0" - if err := r.HandleExtensionUpgrade(context.Background(), cluster, db); err != nil { - t.Fatalf("repeat reconcile: %v", err) - } - if len(updates) != 1 { - t.Fatalf("repeat reconcile ran another upgrade: %q", updates) - } - } - if got := getDocumentDB(t, c).Status.SchemaVersion; got != wantSchema { - t.Errorf("schema status = %q, want %q", got, wantSchema) - } - }) - } -} diff --git a/test/e2e/tests/upgrade/upgrade_schema_test.go b/test/e2e/tests/upgrade/upgrade_schema_test.go index 0cc4132a0..8a4a8cf22 100644 --- a/test/e2e/tests/upgrade/upgrade_schema_test.go +++ b/test/e2e/tests/upgrade/upgrade_schema_test.go @@ -154,11 +154,6 @@ var _ = Describe("DocumentDB upgrade — schema", timeouts.PollInterval(timeouts.DocumentDBReady), ).Should(Equal(oldVersion), "initial schema version should be %s", oldVersion) - Eventually(installedSchemaVersion, - timeouts.For(timeouts.DocumentDBReady), - timeouts.PollInterval(timeouts.DocumentDBReady), - ).Should(Equal(oldVersion), "both extensions must start at %s", oldVersion) - By("seeding data on the old schema") docs := seed.SmallDataset() handle, err := e2emongo.NewFromDocumentDB(ctx, env, ns, ddName) @@ -200,10 +195,6 @@ var _ = Describe("DocumentDB upgrade — schema", ).Should(Equal(oldVersion), "schema must remain at %s until spec.schemaVersion is set (two-phase)", oldVersion) - Consistently(installedSchemaVersion, - 15*time.Second, 5*time.Second, - ).Should(Equal(oldVersion), "neither extension may migrate before schema finalization") - By("verifying seeded data survived the binary upgrade") handle2, err := e2emongo.NewFromDocumentDB(ctx, env, ns, ddName) Expect(err).NotTo(HaveOccurred(), "reconnect to DocumentDB gateway after binary upgrade") From 78f83388e3a7d24f5415a6754324e8c0dc70bf62 Mon Sep 17 00:00:00 2001 From: Wenting Wu Date: Wed, 11 Nov 2026 15:52:18 -0500 Subject: [PATCH 3/5] refactor: scope core upgrade directly to documentdb Remove ExtensionDependencies and use the fixed documentdb-to-documentdb_core relationship only when the main extension is documentdb. Keep both upgrades in the same transaction and leave other products unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 251a6aad-1c9b-4e75-9768-1d79b8eb8a7f Signed-off-by: Wenting Wu --- docs/designs/product-neutral-core.md | 9 ++++--- .../controller/documentdb_controller_test.go | 6 ++--- operator/src/internal/engine/extension.go | 13 ++++------ .../internal/engine/extension_policy_test.go | 24 ++----------------- operator/src/internal/product/documentdb.go | 6 +++-- operator/src/internal/product/profile.go | 4 ---- 6 files changed, 17 insertions(+), 45 deletions(-) diff --git a/docs/designs/product-neutral-core.md b/docs/designs/product-neutral-core.md index 9fb6fe40e..603cd639c 100644 --- a/docs/designs/product-neutral-core.md +++ b/docs/designs/product-neutral-core.md @@ -99,11 +99,10 @@ whose PostgreSQL extension uses dotted semantic versions set `core.ExtensionVersionSemver`; automatic upgrades, explicit targets, comparison, events, and schema status then use that format without rewriting it. -`PostgresProfile.ExtensionDependencies` lists co-versioned dependencies to -upgrade before the main extension, to the same target in one transaction. -DocumentDB configures only `documentdb_core`, not independently versioned -dependencies such as PostGIS or pg_cron. This applies when the main extension -is upgraded; it does not repair existing version mismatches. +DocumentDB schema upgrades also update `documentdb_core` first, to the same +target in one transaction. This is specific to the `documentdb` extension; +other products and independently versioned dependencies are unchanged. +Existing version mismatches are not repaired. The DocumentDB controllers and webhook in `internal/controller` and `internal/webhook` are now thin wrappers over these packages. They keep their diff --git a/operator/src/internal/controller/documentdb_controller_test.go b/operator/src/internal/controller/documentdb_controller_test.go index d078bd2b7..f5b352901 100644 --- a/operator/src/internal/controller/documentdb_controller_test.go +++ b/operator/src/internal/controller/documentdb_controller_test.go @@ -1396,7 +1396,7 @@ var _ = Describe("DocumentDB Controller", func() { }, } - // Explicit version: update to 0.110.0 (binary is also 0.110-0) + // Explicit version: update both extensions to 0.110.0, below binary 0.111-0. documentdb := &dbv1.DocumentDB{ ObjectMeta: metav1.ObjectMeta{ Name: "test-documentdb", @@ -1421,8 +1421,8 @@ var _ = Describe("DocumentDB Controller", func() { SQLExecutor: func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { sqlCalls = append(sqlCalls, sql) if len(sqlCalls) == 1 { - // Binary is 0.110-0, installed is 0.109-0 - return " default_version | installed_version \n-----------------+-------------------\n 0.110-0 | 0.109-0 \n", nil + // Binary is 0.111-0, installed is 0.109-0. + return " default_version | installed_version \n-----------------+-------------------\n 0.111-0 | 0.109-0 \n", nil } return "ALTER EXTENSION", nil }, diff --git a/operator/src/internal/engine/extension.go b/operator/src/internal/engine/extension.go index 50e5437fb..04227295e 100644 --- a/operator/src/internal/engine/extension.go +++ b/operator/src/internal/engine/extension.go @@ -195,15 +195,10 @@ func (r *ClusterReconciler[T]) HandleExtensionUpgrade(ctx context.Context, curre return nil } - if dependencies := r.profile().Postgres.ExtensionDependencies; len(dependencies) > 0 { - // ALTER EXTENSION does not upgrade dependencies. Use one transaction - // and pin every extension to the same target, including in auto mode. - statements := []string{"BEGIN"} - for _, dependency := range dependencies { - statements = append(statements, cnpg.ExtensionUpdateSQL(dependency, schemaTarget)) - } - statements = append(statements, cnpg.ExtensionUpdateSQL(extension, schemaTarget), "COMMIT") - updateSQL = strings.Join(statements, "; ") + ";" + if extension == product.DocumentDBExtensionName { + // PostgreSQL does not upgrade dependencies, so update core first. + updateSQL = "BEGIN; " + cnpg.ExtensionUpdateSQL(product.DocumentDBCoreExtensionName, schemaTarget) + + "; " + cnpg.ExtensionUpdateSQL(extension, schemaTarget) + "; COMMIT;" } // Run ALTER EXTENSION to upgrade diff --git a/operator/src/internal/engine/extension_policy_test.go b/operator/src/internal/engine/extension_policy_test.go index 2ea4a3444..a3740d1b0 100644 --- a/operator/src/internal/engine/extension_policy_test.go +++ b/operator/src/internal/engine/extension_policy_test.go @@ -15,8 +15,7 @@ import ( type extensionPolicyAdapter struct { product.DocumentDBAdapter - format product.ExtensionVersionFormat - dependencies []string + format product.ExtensionVersionFormat } func (a extensionPolicyAdapter) Profile() product.ProductProfile { @@ -24,7 +23,6 @@ func (a extensionPolicyAdapter) Profile() product.ProductProfile { p.Name = "Widget" p.Postgres.Extension.Name = "widget" p.Postgres.ExtensionVersionFormat = a.format - p.Postgres.ExtensionDependencies = a.dependencies return p } @@ -32,7 +30,6 @@ func TestHandleExtensionUpgradeVersionPolicy(t *testing.T) { for _, tc := range []struct { name string format product.ExtensionVersionFormat - dependencies []string installed, binary, requested string wantSQL, wantSchema, wantEvent string }{ @@ -97,23 +94,6 @@ func TestHandleExtensionUpgradeVersionPolicy(t *testing.T) { name: "dotted invalid target", format: product.ExtensionVersionSemver, installed: "1.2.3", binary: "1.3.0", requested: "not-a-version", wantSchema: "1.2.3", }, - { - name: "dotted auto with dependency", format: product.ExtensionVersionSemver, - dependencies: []string{"widget_core"}, - installed: "1.2.3", binary: "1.3.0", requested: "auto", wantSchema: "1.3.0", - wantSQL: `BEGIN; ALTER EXTENSION "widget_core" UPDATE TO '1.3.0'; ALTER EXTENSION "widget" UPDATE TO '1.3.0'; COMMIT;`, - }, - { - name: "dotted explicit dependency target below binary", format: product.ExtensionVersionSemver, - dependencies: []string{"widget_core"}, - installed: "1.2.3", binary: "1.3.0", requested: "1.3.0-rc.1", wantSchema: "1.3.0-rc.1", - wantSQL: `BEGIN; ALTER EXTENSION "widget_core" UPDATE TO '1.3.0-rc.1'; ALTER EXTENSION "widget" UPDATE TO '1.3.0-rc.1'; COMMIT;`, - }, - { - name: "dotted two phase with dependency", format: product.ExtensionVersionSemver, - dependencies: []string{"widget_core"}, - installed: "1.2.3", binary: "1.3.0", wantSchema: "1.2.3", - }, } { t.Run(tc.name, func(t *testing.T) { s := newTestScheme(t) @@ -121,7 +101,7 @@ func TestHandleExtensionUpgradeVersionPolicy(t *testing.T) { db.Spec.SchemaVersion = tc.requested c := newFakeClient(t, s, nil, db) r, rec := newClusterReconciler(c, s, &sqlRecorder{}) - r.Adapter = extensionPolicyAdapter{format: tc.format, dependencies: tc.dependencies} + r.Adapter = extensionPolicyAdapter{format: tc.format} var updates []string r.SQLExecutor = func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) { if strings.Contains(sql, "pg_available_extensions") { diff --git a/operator/src/internal/product/documentdb.go b/operator/src/internal/product/documentdb.go index 18a25eb20..021997039 100644 --- a/operator/src/internal/product/documentdb.go +++ b/operator/src/internal/product/documentdb.go @@ -29,8 +29,7 @@ func DocumentDBProfile() ProductProfile { ExtensionControlPath: []string{"share"}, LdLibraryPath: []string{"lib", "system"}, }, - ExtensionDependencies: []string{"documentdb_core"}, - AdditionalLibraries: []string{"pg_cron", "pg_documentdb_core", "pg_documentdb"}, + AdditionalLibraries: []string{"pg_cron", "pg_documentdb_core", "pg_documentdb"}, BootstrapSQL: []string{ "CREATE EXTENSION documentdb CASCADE", "CREATE ROLE documentdb WITH LOGIN PASSWORD 'Admin100'", @@ -59,6 +58,9 @@ func DocumentDBProfile() ProductProfile { // DocumentDBExtensionName is the PostgreSQL extension backing DocumentDB. const DocumentDBExtensionName = "documentdb" +// DocumentDBCoreExtensionName is the co-versioned PostgreSQL core extension. +const DocumentDBCoreExtensionName = "documentdb_core" + // DocumentDBAdapter is the first product adapter. It maps the DocumentDB custom // resource onto the product-neutral model consumed by the reconciler. type DocumentDBAdapter struct{} diff --git a/operator/src/internal/product/profile.go b/operator/src/internal/product/profile.go index 793bf4153..5704b3384 100644 --- a/operator/src/internal/product/profile.go +++ b/operator/src/internal/product/profile.go @@ -99,10 +99,6 @@ type PostgresProfile struct { // ExtensionVersionFormat controls extension comparison and spec/status // conversion. Its zero value preserves DocumentDB's version convention. ExtensionVersionFormat ExtensionVersionFormat - // ExtensionDependencies lists co-versioned extensions to upgrade before - // Extension, in dependency order, to the same target version and in the - // same transaction. Do not include independently versioned dependencies. - ExtensionDependencies []string // AdditionalLibraries are added to shared_preload_libraries. AdditionalLibraries []string // BootstrapSQL runs once at initdb, before any user PostInitSQL. From 50c7f0ceead2af172aeb6152b35f7b191430c628 Mon Sep 17 00:00:00 2001 From: Wenting Wu Date: Wed, 11 Nov 2026 15:55:56 -0500 Subject: [PATCH 4/5] test: reuse CNPG primary lookup in upgrade assertions Remove the duplicate primary-pod listing found during self-review and use the existing CNPG helper with explicit missing-primary handling. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 251a6aad-1c9b-4e75-9768-1d79b8eb8a7f Signed-off-by: Wenting Wu --- test/e2e/tests/upgrade/helpers_test.go | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/test/e2e/tests/upgrade/helpers_test.go b/test/e2e/tests/upgrade/helpers_test.go index f2d39c966..c5a59eba7 100644 --- a/test/e2e/tests/upgrade/helpers_test.go +++ b/test/e2e/tests/upgrade/helpers_test.go @@ -12,6 +12,7 @@ import ( . "github.com/onsi/ginkgo/v2" //nolint:revive + cnpgclusterutils "github.com/cloudnative-pg/cloudnative-pg/tests/utils/clusterutils" "github.com/cloudnative-pg/cloudnative-pg/tests/utils/environment" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -256,20 +257,14 @@ func primaryInstalledSchemaVersion( env *environment.TestingEnvironment, ns, clusterName string, ) (string, error) { - var pods corev1.PodList - if err := env.Client.List(ctx, &pods, - client.InNamespace(ns), - client.MatchingLabels{ - "cnpg.io/cluster": clusterName, - "cnpg.io/instanceRole": "primary", - }, - ); err != nil { - return "", fmt.Errorf("list primary pod for cluster %s/%s: %w", ns, clusterName, err) + pod, err := cnpgclusterutils.GetPrimary(ctx, env.Client, ns, clusterName) + if err != nil { + return "", fmt.Errorf("get primary pod for cluster %s/%s: %w", ns, clusterName, err) } - if len(pods.Items) != 1 { - return "", fmt.Errorf("expected one primary pod for cluster %s/%s, found %d", ns, clusterName, len(pods.Items)) + if pod == nil || pod.Name == "" { + return "", fmt.Errorf("no primary pod found for cluster %s/%s", ns, clusterName) } - return podInstalledSchemaVersion(ctx, env, pods.Items[0]) + return podInstalledSchemaVersion(ctx, env, *pod) } // podInstalledSchemaVersion requires documentdb and documentdb_core to agree From a33782717f578ff1015fe847c41de469a10e0e55 Mon Sep 17 00:00:00 2001 From: Wenting Wu Date: Wed, 11 Nov 2026 16:03:56 -0500 Subject: [PATCH 5/5] refactor: build DocumentDB core upgrade in SQL helper Move the fixed core-first transaction into ExtensionUpdateSQL and restore the reconciler unchanged. Auto upgrades use each packaged default; explicit upgrades use the same requested target for both extensions. Preserve standalone SQL for other extensions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 251a6aad-1c9b-4e75-9768-1d79b8eb8a7f Signed-off-by: Wenting Wu --- docs/designs/product-neutral-core.md | 8 ++++---- operator/src/internal/cnpg/extension_sql.go | 17 ++++++++++++----- .../src/internal/cnpg/extension_sql_test.go | 13 ++++++++----- .../controller/documentdb_controller_test.go | 4 ++-- operator/src/internal/engine/extension.go | 6 ------ operator/src/pkg/core/core.go | 3 ++- 6 files changed, 28 insertions(+), 23 deletions(-) diff --git a/docs/designs/product-neutral-core.md b/docs/designs/product-neutral-core.md index 603cd639c..8617efa0a 100644 --- a/docs/designs/product-neutral-core.md +++ b/docs/designs/product-neutral-core.md @@ -99,10 +99,10 @@ whose PostgreSQL extension uses dotted semantic versions set `core.ExtensionVersionSemver`; automatic upgrades, explicit targets, comparison, events, and schema status then use that format without rewriting it. -DocumentDB schema upgrades also update `documentdb_core` first, to the same -target in one transaction. This is specific to the `documentdb` extension; -other products and independently versioned dependencies are unchanged. -Existing version mismatches are not repaired. +`ExtensionUpdateSQL` upgrades `documentdb_core` before `documentdb` in one +transaction. Explicit schema versions apply to both extensions; `auto` uses +each extension's packaged default. Other products and independently versioned +dependencies are unchanged. Existing version mismatches are not repaired. The DocumentDB controllers and webhook in `internal/controller` and `internal/webhook` are now thin wrappers over these packages. They keep their diff --git a/operator/src/internal/cnpg/extension_sql.go b/operator/src/internal/cnpg/extension_sql.go index 61538b19b..0ff0255c3 100644 --- a/operator/src/internal/cnpg/extension_sql.go +++ b/operator/src/internal/cnpg/extension_sql.go @@ -9,6 +9,7 @@ import ( cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1" "github.com/lib/pq" + "github.com/documentdb/documentdb-operator/internal/product" util "github.com/documentdb/documentdb-operator/internal/utils" ) @@ -22,14 +23,20 @@ func ExtensionVersionSQL(extension string) string { return fmt.Sprintf("SELECT default_version, installed_version FROM pg_available_extensions WHERE name = %s", pq.QuoteLiteral(extension)) } -// ExtensionUpdateSQL returns the ALTER EXTENSION statement for the named -// extension. An empty targetVersion updates to the binary's default version. +// ExtensionUpdateSQL returns SQL to upgrade the named extension. DocumentDB +// upgrades documentdb_core first in the same transaction. An empty targetVersion +// updates each extension to its binary's default version. // targetVersion must already be validated (digits, dots, and hyphens only). func ExtensionUpdateSQL(extension, targetVersion string) string { - if targetVersion == "" { - return fmt.Sprintf("ALTER EXTENSION %s UPDATE", pq.QuoteIdentifier(extension)) + updateSQL := fmt.Sprintf("ALTER EXTENSION %s UPDATE", pq.QuoteIdentifier(extension)) + if targetVersion != "" { + updateSQL += " TO " + pq.QuoteLiteral(targetVersion) } - return fmt.Sprintf("ALTER EXTENSION %s UPDATE TO %s", pq.QuoteIdentifier(extension), pq.QuoteLiteral(targetVersion)) + if extension == product.DocumentDBExtensionName { + coreSQL := ExtensionUpdateSQL(product.DocumentDBCoreExtensionName, targetVersion) + return "BEGIN; " + coreSQL + "; " + updateSQL + "; COMMIT;" + } + return updateSQL } // ReplicationRoleCheckSQL returns the query that yields one row when CNPG's diff --git a/operator/src/internal/cnpg/extension_sql_test.go b/operator/src/internal/cnpg/extension_sql_test.go index c0220d71d..dd390346c 100644 --- a/operator/src/internal/cnpg/extension_sql_test.go +++ b/operator/src/internal/cnpg/extension_sql_test.go @@ -14,11 +14,14 @@ import ( func TestExtensionLifecycleSQLUsesProductNames(t *testing.T) { cases := map[string]string{ - ExtensionVersionSQL("pgcosmos"): "SELECT default_version, installed_version FROM pg_available_extensions WHERE name = 'pgcosmos'", - ExtensionUpdateSQL("pgcosmos", ""): `ALTER EXTENSION "pgcosmos" UPDATE`, - ExtensionUpdateSQL("pgcosmos", "1.2-0"): `ALTER EXTENSION "pgcosmos" UPDATE TO '1.2-0'`, - ReplicationRoleCheckSQL("cosmos_admin"): "SELECT 1 FROM pg_roles WHERE rolname = 'streaming_replica' AND pg_has_role('streaming_replica', 'cosmos_admin', 'USAGE');", - ReplicationRoleGrantSQL("cosmos_admin"): `GRANT "cosmos_admin" TO streaming_replica;`, + ExtensionVersionSQL("pgcosmos"): "SELECT default_version, installed_version FROM pg_available_extensions WHERE name = 'pgcosmos'", + ExtensionUpdateSQL("pgcosmos", ""): `ALTER EXTENSION "pgcosmos" UPDATE`, + ExtensionUpdateSQL("pgcosmos", "1.2-0"): `ALTER EXTENSION "pgcosmos" UPDATE TO '1.2-0'`, + ExtensionUpdateSQL("documentdb", ""): `BEGIN; ALTER EXTENSION "documentdb_core" UPDATE; ALTER EXTENSION "documentdb" UPDATE; COMMIT;`, + ExtensionUpdateSQL("documentdb", "1.2-0"): `BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '1.2-0'; ALTER EXTENSION "documentdb" UPDATE TO '1.2-0'; COMMIT;`, + ExtensionUpdateSQL("documentdb_core", ""): `ALTER EXTENSION "documentdb_core" UPDATE`, + ReplicationRoleCheckSQL("cosmos_admin"): "SELECT 1 FROM pg_roles WHERE rolname = 'streaming_replica' AND pg_has_role('streaming_replica', 'cosmos_admin', 'USAGE');", + ReplicationRoleGrantSQL("cosmos_admin"): `GRANT "cosmos_admin" TO streaming_replica;`, } for got, want := range cases { if got != want { diff --git a/operator/src/internal/controller/documentdb_controller_test.go b/operator/src/internal/controller/documentdb_controller_test.go index f5b352901..b108128fe 100644 --- a/operator/src/internal/controller/documentdb_controller_test.go +++ b/operator/src/internal/controller/documentdb_controller_test.go @@ -855,7 +855,7 @@ var _ = Describe("DocumentDB Controller", func() { // Verify both SQL calls were made Expect(sqlCalls).To(HaveLen(2)) Expect(sqlCalls[0]).To(ContainSubstring("pg_available_extensions")) - Expect(sqlCalls[1]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '0.110-0'; ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'; COMMIT;`)) + Expect(sqlCalls[1]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE; ALTER EXTENSION "documentdb" UPDATE; COMMIT;`)) // Status should reflect the upgraded version (default version as semver) updatedDB := &dbv1.DocumentDB{} @@ -1362,7 +1362,7 @@ var _ = Describe("DocumentDB Controller", func() { // Both version-check and ALTER EXTENSION should have been called Expect(sqlCalls).To(HaveLen(2)) Expect(sqlCalls[0]).To(ContainSubstring("pg_available_extensions")) - Expect(sqlCalls[1]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '0.110-0'; ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'; COMMIT;`)) + Expect(sqlCalls[1]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE; ALTER EXTENSION "documentdb" UPDATE; COMMIT;`)) // Status should reflect the upgraded version updatedDB := &dbv1.DocumentDB{} diff --git a/operator/src/internal/engine/extension.go b/operator/src/internal/engine/extension.go index 04227295e..0c794b9c3 100644 --- a/operator/src/internal/engine/extension.go +++ b/operator/src/internal/engine/extension.go @@ -195,12 +195,6 @@ func (r *ClusterReconciler[T]) HandleExtensionUpgrade(ctx context.Context, curre return nil } - if extension == product.DocumentDBExtensionName { - // PostgreSQL does not upgrade dependencies, so update core first. - updateSQL = "BEGIN; " + cnpg.ExtensionUpdateSQL(product.DocumentDBCoreExtensionName, schemaTarget) + - "; " + cnpg.ExtensionUpdateSQL(extension, schemaTarget) + "; COMMIT;" - } - // Run ALTER EXTENSION to upgrade logger.Info("Upgrading "+name+" extension", "fromVersion", installedVersion, diff --git a/operator/src/pkg/core/core.go b/operator/src/pkg/core/core.go index 8ca796194..2269bc509 100644 --- a/operator/src/pkg/core/core.go +++ b/operator/src/pkg/core/core.go @@ -105,7 +105,8 @@ func ValidateResources(res Resources, monitoring bool, base *field.Path, cfg Spl func ExtensionVersionSQL(extension string) string { return cnpg.ExtensionVersionSQL(extension) } // ExtensionUpdateSQL upgrades extension, to targetVersion when set. Pass the -// unquoted extension name; it is quoted as a SQL identifier. +// unquoted extension name; it is quoted as a SQL identifier. For DocumentDB, +// documentdb_core is upgraded first in the same transaction. func ExtensionUpdateSQL(extension, targetVersion string) string { return cnpg.ExtensionUpdateSQL(extension, targetVersion) }