From cb6f57161a3ea6792a303be74777f0635a9c593e Mon Sep 17 00:00:00 2001 From: woblerr Date: Sun, 22 Nov 2026 00:21:08 +0300 Subject: [PATCH 1/7] Fix backup consistency after concurrent TRUNCATE. A concurrent TRUNCATE can replace table storage after the backup snapshot but before table locks are acquired. Backup and restore can then report success while restoring an empty table. On Cloudberry, validate storage and table identity after locking, including descendant partitions. Add --snapshot-attempts (default 3) to retry with a fresh shared snapshot, rebuild filters, and discard heap file hashes. Fail the backup when the limit is reached. --- backup/backup.go | 3 +- backup/global_variables.go | 1 + backup/queries_relations.go | 7 +- backup/snapshot.go | 120 +++++++++++++++ backup/snapshot_internal_test.go | 224 +++++++++++++++++++++++++++ backup/validate.go | 3 + backup/validate_test.go | 4 + backup/wrappers.go | 43 ++++-- end_to_end/snapshot_retry_test.go | 238 +++++++++++++++++++++++++++++ integration/snapshot_test.go | 241 ++++++++++++++++++++++++++++++ integration/wrappers_test.go | 2 +- options/flag.go | 2 + options/options.go | 14 +- options/options_test.go | 43 ++++++ 14 files changed, 924 insertions(+), 21 deletions(-) create mode 100644 backup/snapshot_internal_test.go create mode 100644 end_to_end/snapshot_retry_test.go diff --git a/backup/backup.go b/backup/backup.go index ddbcc197..3fb618dc 100644 --- a/backup/backup.go +++ b/backup/backup.go @@ -65,6 +65,7 @@ func DoSetup() { gplog.Info("Starting backup of database %s", MustGetFlagString(options.DBNAME)) opts, err := options.NewOptions(cmdFlags) gplog.FatalOnError(err) + backupOptions = opts ValidateAndProcessFilterLists(opts) includeOids := GetOidsFromRelationList(IncludedRelationFqns) @@ -143,7 +144,7 @@ func DoBackup() { } gplog.Info("Gathering table state information") - metadataTables, dataTables := RetrieveAndProcessTables() + metadataTables, dataTables := RetrieveAndProcessTables(backupOptions) dataTables, numExtOrForeignTables := GetBackupDataSet(dataTables) if len(dataTables) == 0 && !backupReport.MetadataOnly { gplog.Warn("No tables in backup set contain data. Performing metadata-only backup instead.") diff --git a/backup/global_variables.go b/backup/global_variables.go index 01233617..881da88e 100644 --- a/backup/global_variables.go +++ b/backup/global_variables.go @@ -49,6 +49,7 @@ var ( quotedRoleNames map[string]string backupSnapshot string heapFileHashes map[uint32]string + backupOptions *options.Options /* * Used for synchronizing DoCleanup. In DoInit() we increment the group * and then wait for at least one DoCleanup to finish, either in DoTeardown diff --git a/backup/queries_relations.go b/backup/queries_relations.go index 6bc297fb..a658e7f1 100644 --- a/backup/queries_relations.go +++ b/backup/queries_relations.go @@ -550,11 +550,12 @@ func GetAllViews(connectionPool *dbconn.DBConn) []View { // dumping part but it also makes the main worker thread (worker 0) the // most resilient for the later data dumping logic. Locks will still be // taken for --data-only calls. -func LockTables(connectionPool *dbconn.DBConn, tables []Relation) { +func LockTables(connectionPool *dbconn.DBConn, tables []Relation) error { gplog.Info("Acquiring ACCESS SHARE locks on tables") progressBar := utils.NewProgressBar(len(tables), "Locks acquired: ", utils.PB_VERBOSE) progressBar.Start() + defer progressBar.Finish() var lockMode string const batchSize = 100 lastBatchSize := len(tables) % batchSize @@ -583,7 +584,7 @@ func LockTables(connectionPool *dbconn.DBConn, tables []Relation) { gplog.Warn("Interrupt received while acquiring ACCESS SHARE locks on tables") select {} // wait for cleanup thread to exit gpbackup } else { - gplog.FatalOnError(err) + return fmt.Errorf("locking tables %s: %w", currentBatch, err) } } if i == len(tableBatches)-1 && lastBatchSize > 0 { @@ -592,7 +593,7 @@ func LockTables(connectionPool *dbconn.DBConn, tables []Relation) { progressBar.Add(currentBatchSize) } - progressBar.Finish() + return nil } // GenerateTableBatches batches tables to reduce network congestion and diff --git a/backup/snapshot.go b/backup/snapshot.go index 145954f7..8cfbd205 100644 --- a/backup/snapshot.go +++ b/backup/snapshot.go @@ -5,12 +5,132 @@ package backup */ import ( + "database/sql" + "errors" "fmt" + "sort" + "strconv" + "strings" + "github.com/apache/cloudberry-backup/options" "github.com/apache/cloudberry-go-libs/dbconn" "github.com/apache/cloudberry-go-libs/gplog" + "github.com/jackc/pgx/v5/pgconn" ) +// CheckSnapshotTables compares the Cloudberry MVCC catalog with the current relation cache +// after ACCESS SHARE locks have been acquired. A rewrite can commit while LOCK +// waits, leaving the snapshot's old storage inaccessible. Catalog functions use +// current identity, as pg_relation_filepath does for incremental heap hashes. +func CheckSnapshotTables(conn *dbconn.DBConn, tables []Relation) ([]string, error) { + if len(tables) == 0 { + return nil, nil + } + oids := make([]string, len(tables)) + for i, table := range tables { + oids[i] = strconv.FormatUint(uint64(table.Oid), 10) + } + // Include descendants even when COPY reads their data through a parent. + query := fmt.Sprintf(`WITH RECURSIVE relations(oid) AS ( + SELECT oid FROM pg_catalog.pg_class WHERE oid IN (%s) + UNION + SELECT i.inhrelid FROM pg_catalog.pg_inherits i JOIN relations r ON i.inhparent = r.oid + ) + SELECT quote_ident(n.nspname) || '.' || quote_ident(c.relname) AS fqn, + c.oid AS oid, c.relfilenode AS snapshotnode, + pg_catalog.pg_relation_filenode(c.oid) AS currentnode, + pg_catalog.to_regclass(quote_ident(n.nspname) || '.' || quote_ident(c.relname))::oid AS currentoid + FROM relations r JOIN pg_catalog.pg_class c ON c.oid = r.oid + JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace`, strings.Join(oids, ",")) + var rows []struct { + FQN string + Oid uint32 + SnapshotNode uint32 + CurrentNode sql.NullInt64 + CurrentOid sql.NullInt64 + } + if err := conn.Select(&rows, query); err != nil { + return nil, fmt.Errorf("checking table storage against backup snapshot: %w", err) + } + conflicts := make(map[string]bool) + for _, row := range rows { + var reason string + switch { + case !row.CurrentOid.Valid || row.CurrentOid.Int64 != int64(row.Oid): + reason = "table name no longer identifies the snapshot OID" + case row.SnapshotNode != 0 && !row.CurrentNode.Valid: + reason = "table storage disappeared" + case row.SnapshotNode != 0 && row.CurrentNode.Int64 != int64(row.SnapshotNode): + reason = "table storage changed after the snapshot" + } + if reason != "" { + conflicts[fmt.Sprintf("%s (%s)", row.FQN, reason)] = true + } + } + result := make([]string, 0, len(conflicts)) + for conflict := range conflicts { + result = append(result, conflict) + } + sort.Strings(result) + return result, nil +} + +func prepareSnapshotTables(opts *options.Options) ([]Relation, error) { + maxAttempts := MustGetFlagInt(options.SNAPSHOT_ATTEMPTS) + checkSnapshot := connectionPool.Version.IsCBDB() && !MustGetFlagBool(options.METADATA_ONLY) + for attempt := 1; ; attempt++ { + tables := ConvertRelationsOptionsToBackup(GetIncludedUserTableRelations(connectionPool, IncludedRelationFqns)) + lockErr := LockTables(connectionPool, tables) + var conflicts []string + if lockErr != nil { + var pgErr *pgconn.PgError + if !checkSnapshot || !errors.As(lockErr, &pgErr) || (pgErr.Code != "42P01" && pgErr.Code != "3F000") { + return nil, lockErr + } + conflicts = []string{lockErr.Error()} + } else if checkSnapshot { + var err error + conflicts, err = CheckSnapshotTables(connectionPool, tables) + if err != nil { + return nil, err + } + } + if len(conflicts) == 0 { + return tables, nil + } + if attempt >= maxAttempts { + return nil, fmt.Errorf("could not obtain a consistent backup snapshot after %d attempt(s): %s", attempt, strings.Join(conflicts, "; ")) + } + gplog.Warn("Backup snapshot conflict: %s. Starting snapshot attempt %d of %d", strings.Join(conflicts, "; "), attempt+1, maxAttempts) + if attempt == 1 { + heapFileHashes = nil + if MustGetFlagBool(options.HEAP_FILE_HASH) { + gplog.Warn("Snapshot retry disables heap file hashes for this backup; all heap table data will be included and the backup may be larger") + } + } + if err := restartBackupTransactions(); err != nil { + return nil, err + } + if err := opts.ResetTableFilters(cmdFlags); err != nil { + return nil, err + } + filterRelationClause = "" + ValidateAndProcessFilterLists(opts) + if err := ExpandIncludesForPartitions(connectionPool, opts, GetOidsFromRelationList(IncludedRelationFqns), cmdFlags); err != nil { + return nil, err + } + } +} + +func restartBackupTransactions() error { + for connNum := 0; connNum < connectionPool.NumConns; connNum++ { + if err := connectionPool.Rollback(connNum); err != nil { + return fmt.Errorf("rolling back backup connection %d for snapshot retry: %w", connNum, err) + } + } + return initializeBackupTransactions(globalFPInfo.Timestamp) +} + const ( SNAPSHOT_GPDB_MIN_VERSION = "6.21.0" ) diff --git a/backup/snapshot_internal_test.go b/backup/snapshot_internal_test.go new file mode 100644 index 00000000..43875f7b --- /dev/null +++ b/backup/snapshot_internal_test.go @@ -0,0 +1,224 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ + +package backup + +import ( + "database/sql/driver" + "errors" + "fmt" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/apache/cloudberry-backup/options" + "github.com/apache/cloudberry-go-libs/dbconn" + "github.com/apache/cloudberry-go-libs/testhelper" + "github.com/jackc/pgx/v5/pgconn" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/spf13/pflag" +) + +var _ = Describe("snapshot preparation", func() { + var mock sqlmock.Sqlmock + var opts *options.Options + columns := []string{"fqn", "oid", "snapshotnode", "currentnode", "currentoid"} + table := Relation{Oid: 10, Schema: "public", Name: "t"} + BeforeEach(func() { + connectionPool, mock, _, _, _ = testhelper.SetupTestEnvironment() + connectionPool.Version = dbconn.NewVersion("2.999.0") + connectionPool.Version.Type = dbconn.CBDB + SetCmdFlags(pflag.NewFlagSet("snapshot", pflag.ContinueOnError)) + var err error + opts, err = options.NewOptions(cmdFlags) + Expect(err).NotTo(HaveOccurred()) + filterRelationClause = "" + IncludedRelationFqns = nil + ExcludedRelationFqns = nil + heapFileHashes = nil + backupSnapshot = "" + }) + AfterEach(func() { + Expect(mock.ExpectationsWereMet()).To(Succeed()) + connectionPool.Close() + backupSnapshot = "" + heapFileHashes = nil + }) + + DescribeTable("storage and identity conflicts", func(node, oid driver.Value, oldNode int, reason string) { + mock.ExpectQuery("WITH RECURSIVE").WillReturnRows(sqlmock.NewRows(columns).AddRow("public.t", 10, oldNode, node, oid)) + conflicts, err := CheckSnapshotTables(connectionPool, []Relation{table}) + Expect(err).NotTo(HaveOccurred()) + if reason == "" { + Expect(conflicts).To(BeEmpty()) + } else { + Expect(conflicts).To(ConsistOf(ContainSubstring(reason))) + } + }, + Entry("unchanged", 20, 10, 20, ""), + Entry("rewritten", 21, 10, 20, "storage changed"), + Entry("missing storage", nil, 10, 20, "storage disappeared"), + Entry("replaced OID", 20, 11, 20, "snapshot OID"), + Entry("missing name", 20, nil, 20, "snapshot OID"), + Entry("no own storage", nil, 10, 0, ""), + ) + It("does not query for an empty table set", func() { + conflicts, err := CheckSnapshotTables(connectionPool, nil) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(BeEmpty()) + }) + It("reports nested descendants only once", func() { + mock.ExpectQuery("WITH RECURSIVE.*JOIN relations").WillReturnRows(sqlmock.NewRows(columns). + AddRow("public.root", 10, 0, nil, 10). + AddRow("public.leaf", 11, 20, 21, 11). + AddRow("public.leaf", 11, 20, 21, 11)) + conflicts, err := CheckSnapshotTables(connectionPool, []Relation{table}) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(HaveLen(1)) + Expect(conflicts[0]).To(ContainSubstring("public.leaf")) + }) + It("fails closed on a check error", func() { + mock.ExpectQuery("WITH RECURSIVE").WillReturnError(errors.New("catalog failure")) + _, err := CheckSnapshotTables(connectionPool, []Relation{table}) + Expect(err).To(MatchError(ContainSubstring("catalog failure"))) + }) + + begin := func() { + mock.ExpectBegin() + mock.ExpectExec("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE").WillReturnResult(sqlmock.NewResult(0, 0)) + } + session := func() { + for _, query := range []string{"SET search_path", "SET statement_timeout", "SET DATESTYLE", "SET enable_mergejoin", "SELECT set_config", "SET synchronize_seqscans", "SET INTERVALSTYLE", "SET lock_timeout", "SET idle_in_transaction_session_timeout"} { + mock.ExpectExec(query).WillReturnResult(sqlmock.NewResult(0, 0)) + } + } + restart := func() { + mock.ExpectRollback() + mock.ExpectExec("SET application_name").WillReturnResult(sqlmock.NewResult(0, 0)) + begin() + mock.ExpectQuery("SELECT pg_catalog.pg_export_snapshot").WillReturnRows(sqlmock.NewRows([]string{"snapshot"}).AddRow("new-snapshot")) + session() + } + tables := func(lockErr error, changed bool) { + mock.ExpectQuery("SELECT n.oid AS schemaoid").WillReturnRows(sqlmock.NewRows([]string{"schemaoid", "oid", "schema", "name"}).AddRow(1, 10, "public", "t")) + lock := mock.ExpectExec("LOCK TABLE public.t") + if lockErr != nil { + lock.WillReturnError(lockErr) + return + } + lock.WillReturnResult(sqlmock.NewResult(0, 0)) + node := 20 + if changed { + node = 21 + } + mock.ExpectQuery("WITH RECURSIVE").WillReturnRows(sqlmock.NewRows(columns).AddRow("public.t", 10, 20, node, 10)) + } + It("exports before any worker imports and applies session queries afterwards", func() { + // Two mock connections share expectations, so ordering verifies import precedes queries. + connectionPool.ConnPool[0].SetMaxOpenConns(2) + connectionPool.ConnPool = append(connectionPool.ConnPool, connectionPool.ConnPool[0]) + connectionPool.Tx = append(connectionPool.Tx, nil) + connectionPool.NumConns = 2 + for i := 0; i < 2; i++ { + mock.ExpectExec("SET application_name").WillReturnResult(sqlmock.NewResult(0, 0)) + begin() + if i == 0 { + mock.ExpectQuery("SELECT pg_catalog.pg_export_snapshot").WillReturnRows(sqlmock.NewRows([]string{"snapshot"}).AddRow("new-snapshot")) + } else { + mock.ExpectExec("SET TRANSACTION SNAPSHOT 'new-snapshot'").WillReturnResult(sqlmock.NewResult(0, 0)) + } + session() + } + Expect(initializeBackupTransactions("20261120000000")).To(Succeed()) + Expect(backupSnapshot).To(Equal("new-snapshot")) + }) + DescribeTable("honors the attempt budget", func(limit int) { + Expect(cmdFlags.Set(options.SNAPSHOT_ATTEMPTS, fmt.Sprint(limit))).To(Succeed()) + begin() + connectionPool.MustBegin() + for i := 1; i <= limit; i++ { + tables(nil, true) + if i < limit { + restart() + } + } + _, err := prepareSnapshotTables(opts) + Expect(err).To(MatchError(ContainSubstring(fmt.Sprintf("after %d attempt(s): public.t", limit)))) + }, Entry("one", 1), Entry("three", 3)) + It("discards heap hashes and accepts the new snapshot", func() { + begin() + connectionPool.MustBegin() + heapFileHashes = map[uint32]string{10: "old"} + tables(nil, true) + restart() + tables(nil, false) + result, err := prepareSnapshotTables(opts) + Expect(err).NotTo(HaveOccurred()) + Expect(result).To(Equal([]Relation{{SchemaOid: 1, Oid: 10, Schema: "public", Name: "t"}})) + Expect(heapFileHashes).To(BeNil()) + Expect(backupSnapshot).To(Equal("new-snapshot")) + }) + It("does not retry unrelated SQL errors", func() { + tables(&pgconn.PgError{Code: "42501", Message: "permission denied"}, false) + _, err := prepareSnapshotTables(opts) + Expect(err).To(MatchError(ContainSubstring("permission denied"))) + }) + DescribeTable("retries missing names", func(code string) { + begin() + connectionPool.MustBegin() + tables(&pgconn.PgError{Code: code, Message: "disappeared"}, false) + restart() + tables(nil, false) + _, err := prepareSnapshotTables(opts) + Expect(err).NotTo(HaveOccurred()) + }, Entry("table", "42P01"), Entry("schema", "3F000")) + It("does not validate physical storage for metadata-only backups", func() { + Expect(cmdFlags.Set(options.METADATA_ONLY, "true")).To(Succeed()) + mock.ExpectQuery("SELECT n.oid AS schemaoid").WillReturnRows(sqlmock.NewRows([]string{"schemaoid", "oid", "schema", "name"}).AddRow(1, 10, "public", "t")) + mock.ExpectExec("LOCK TABLE public.t").WillReturnResult(sqlmock.NewResult(0, 0)) + result, err := prepareSnapshotTables(opts) + Expect(err).NotTo(HaveOccurred()) + Expect(result).To(HaveLen(1)) + }) + + It("does not retry a storage validation query failure", func() { + mock.ExpectQuery("SELECT n.oid AS schemaoid").WillReturnRows(sqlmock.NewRows([]string{"schemaoid", "oid", "schema", "name"}).AddRow(1, 10, "public", "t")) + mock.ExpectExec("LOCK TABLE public.t").WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectQuery("WITH RECURSIVE").WillReturnError(errors.New("check failed")) + _, err := prepareSnapshotTables(opts) + Expect(err).To(MatchError(ContainSubstring("check failed"))) + }) + + It("stops on rollback failure", func() { + begin() + connectionPool.MustBegin() + tables(nil, true) + mock.ExpectRollback().WillReturnError(errors.New("rollback failure")) + _, err := prepareSnapshotTables(opts) + Expect(err).To(MatchError(ContainSubstring("rollback failure"))) + }) + It("stops on snapshot preparation failure", func() { + begin() + connectionPool.MustBegin() + tables(nil, true) + mock.ExpectRollback() + mock.ExpectExec("SET application_name").WillReturnError(errors.New("session failure")) + _, err := prepareSnapshotTables(opts) + Expect(err).To(MatchError("session failure")) + }) +}) diff --git a/backup/validate.go b/backup/validate.go index a4f84229..70f5adc4 100644 --- a/backup/validate.go +++ b/backup/validate.go @@ -168,6 +168,9 @@ func validateFlagCombinations(flags *pflag.FlagSet) { } func validateFlagValues() { + if MustGetFlagInt(options.SNAPSHOT_ATTEMPTS) < 1 { + gplog.Fatal(errors.New("--snapshot-attempts must be an integer of at least 1"), "") + } timeoutSeconds := MustGetFlagInt(options.HISTORY_SYNC_STANDBY_TIMEOUT) if timeoutSeconds <= 0 || timeoutSeconds > maxHistorySyncStandbyTimeoutSeconds { gplog.Fatal(errors.Errorf("--%s must be between 1 and %d seconds", options.HISTORY_SYNC_STANDBY_TIMEOUT, maxHistorySyncStandbyTimeoutSeconds), "") diff --git a/backup/validate_test.go b/backup/validate_test.go index 82678257..2e4b0741 100644 --- a/backup/validate_test.go +++ b/backup/validate_test.go @@ -214,6 +214,10 @@ var _ = Describe("backup/validate tests", func() { Fail("Valid flag combination failed validation check") } }, + Entry("snapshot attempts accepts one", "--snapshot-attempts 1", true), + Entry("snapshot attempts accepts larger values", "--snapshot-attempts 5", true), + Entry("snapshot attempts rejects zero", "--snapshot-attempts 0", false), + Entry("snapshot attempts rejects negative values", "--snapshot-attempts -2", false), Entry("--backup-dir combo", "--backup-dir /tmp --plugin-config /tmp/config", false), Entry("standby history sync timeout must be positive", "--history-sync-standby-timeout 0", false), Entry("standby history sync timeout must not be negative", "--history-sync-standby-timeout -1", false), diff --git a/backup/wrappers.go b/backup/wrappers.go index 30e33096..55631b5d 100644 --- a/backup/wrappers.go +++ b/backup/wrappers.go @@ -45,7 +45,6 @@ func SetLoggerVerbosity() { func initializeConnectionPool(timestamp string) { var numConns int - var err error connectionPool = dbconn.NewDBConnFromEnvironment(MustGetFlagString(options.DBNAME)) /* * The additional connection is used to hold the locks and process any deferred @@ -68,20 +67,36 @@ func initializeConnectionPool(timestamp string) { utils.ValidateGPDBVersionCompatibility(connectionPool) InitializeMetadataParams(connectionPool) - // Begin transactions, initialize the synchronized snapshot, and set session GUCs + gplog.FatalOnError(initializeBackupTransactions(timestamp)) +} + +// On Cloudberry, import the snapshot before session queries establish a worker snapshot. +// application_name is set outside the transaction so rollback preserves cleanup's identity. +func initializeBackupTransactions(timestamp string) error { + backupSnapshot = "" for connNum := 0; connNum < connectionPool.NumConns; connNum++ { - connectionPool.MustExec(fmt.Sprintf("SET application_name TO 'gpbackup_%s'", timestamp), connNum) - // Begins transaction in repeatable read - connectionPool.MustBegin(connNum) - if ((connectionPool.Version.IsGPDB() && connectionPool.Version.AtLeast(SNAPSHOT_GPDB_MIN_VERSION)) || connectionPool.Version.IsCBDB()) && backupSnapshot == "" { - backupSnapshot, err = GetSynchronizedSnapshot(connectionPool) - if err != nil { - gplog.FatalOnError(err) + if _, err := connectionPool.Exec(fmt.Sprintf("SET application_name TO 'gpbackup_%s'", timestamp), connNum); err != nil { + return err + } + if err := connectionPool.Begin(connNum); err != nil { + return err + } + if connectionPool.Version.IsCBDB() || (connectionPool.Version.IsGPDB() && connectionPool.Version.AtLeast(SNAPSHOT_GPDB_MIN_VERSION)) { + if connNum == 0 { + var err error + backupSnapshot, err = GetSynchronizedSnapshot(connectionPool) + if err != nil { + return err + } + } else if connectionPool.Version.IsCBDB() { + if err := SetSynchronizedSnapshot(connectionPool, connNum, backupSnapshot); err != nil { + return err + } } } - SetSessionGUCs(connNum) } + return nil } func SetSessionGUCs(connNum int) { @@ -203,11 +218,9 @@ func createBackupDirectoriesOnAllHosts() { * Metadata retrieval wrapper functions */ -func RetrieveAndProcessTables() ([]Table, []Table) { - includedRelations := GetIncludedUserTableRelations(connectionPool, IncludedRelationFqns) - tableRelations := ConvertRelationsOptionsToBackup(includedRelations) - - LockTables(connectionPool, tableRelations) +func RetrieveAndProcessTables(opts *options.Options) ([]Table, []Table) { + tableRelations, err := prepareSnapshotTables(opts) + gplog.FatalOnError(err) if (connectionPool.Version.IsGPDB() && connectionPool.Version.AtLeast("6")) || connectionPool.Version.IsCBDB() { tableRelations = append(tableRelations, GetForeignTableRelations(connectionPool)...) diff --git a/end_to_end/snapshot_retry_test.go b/end_to_end/snapshot_retry_test.go new file mode 100644 index 00000000..7a7a9231 --- /dev/null +++ b/end_to_end/snapshot_retry_test.go @@ -0,0 +1,238 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ + +package end_to_end_test + +import ( + "fmt" + "os" + "os/exec" + "syscall" + "time" + + "github.com/apache/cloudberry-backup/testutils" + "github.com/apache/cloudberry-go-libs/dbconn" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + . "github.com/onsi/gomega/gexec" +) + +// Wait for this backup's lock request, never a fixed sleep or another client's lock. +func waitForSnapshotBackupLock(relation string) { + query := fmt.Sprintf(`SELECT count(*) FROM pg_locks l JOIN pg_stat_activity a ON a.pid=l.pid + WHERE l.relation='%s'::regclass AND NOT l.granted AND l.mode='AccessShareLock' + AND a.datname=current_database() AND a.application_name LIKE 'gpbackup_%%' AND a.query LIKE 'LOCK TABLE%%'`, relation) + Eventually(func() (int, error) { var count int; err := backupConn.Get(&count, query); return count, err }, 30*time.Second, 100*time.Millisecond).Should(BeNumerically(">", 0)) +} + +func startSnapshotBackup(args ...string) *Session { + args = append([]string{"--dbname", "testdb", "--backup-dir", backupDir, "--verbose", "--no-history-sync-standby"}, args...) + session, err := Start(exec.Command(gpbackupPath, args...), GinkgoWriter, GinkgoWriter) + Expect(err).NotTo(HaveOccurred()) + DeferCleanup(func() { + if session.ExitCode() == -1 { + session.Terminate() + Eventually(session, 30*time.Second).Should(Exit()) + } + }) + return session +} + +func snapshotRetryRows(conn *dbconn.DBConn) []int { + var rows []int + Expect(conn.Select(&rows, "SELECT id FROM snapshot_retry.t ORDER BY id")).To(Succeed()) + return rows +} + +// Server backend removal from pg_stat_activity can lag the client process exit. +func waitForSnapshotBackupSessionsToClose() { + Eventually(func() (int, error) { + var count int + err := backupConn.Get(&count, "SELECT count(*) FROM pg_stat_activity WHERE datname=current_database() AND application_name LIKE 'gpbackup_%'") + return count, err + }, 10*time.Second, 100*time.Millisecond).Should(BeZero()) +} + +var _ = Describe("snapshot lock retry", func() { + BeforeEach(func() { + if useOldBackupVersion || !backupConn.Version.IsCBDB() { + Skip("snapshot retries require Cloudberry and current gpbackup") + } + end_to_end_setup() + backupConn.MustExec("CREATE SCHEMA snapshot_retry") + }) + AfterEach(func() { + backupConn.MustExec("DROP SCHEMA IF EXISTS snapshot_retry CASCADE") + restoreConn.MustExec("DROP SCHEMA IF EXISTS snapshot_retry CASCADE") + end_to_end_teardown() + }) + + createTable := func(am string, partitioned bool) { + if partitioned { + backupConn.MustExec(fmt.Sprintf(`CREATE TABLE snapshot_retry.t(id int) USING %s DISTRIBUTED BY(id) PARTITION BY RANGE(id); + CREATE TABLE snapshot_retry.middle PARTITION OF snapshot_retry.t FOR VALUES FROM(0) TO(10) PARTITION BY RANGE(id); + CREATE TABLE snapshot_retry.leaf PARTITION OF snapshot_retry.middle FOR VALUES FROM(0) TO(10) USING %s`, am, am)) + } else { + backupConn.MustExec(fmt.Sprintf("CREATE TABLE snapshot_retry.t(id int) USING %s DISTRIBUTED BY(id)", am)) + } + backupConn.MustExec("INSERT INTO snapshot_retry.t VALUES(1),(2),(3)") + } + truncateDuringBackup := func(partitioned bool, args ...string) *Session { + writer := testutils.SetupTestDbConn("testdb") + defer writer.Close() + writer.MustBegin() + defer func() { + if writer.Tx[0] != nil { + writer.MustRollback() + } + }() + relation := "snapshot_retry.t" + if partitioned { + relation = "snapshot_retry.leaf" + } + writer.MustExec("TRUNCATE " + relation) + writer.MustExec("INSERT INTO " + relation + " VALUES(4),(5),(6)") + session := startSnapshotBackup(args...) + waitForSnapshotBackupLock(relation) + writer.MustCommit() + Eventually(session, 90*time.Second).Should(Exit()) + return session + } + restore := func(session *Session) { + Expect(session.ExitCode()).To(Equal(0)) + Expect(string(session.Out.Contents())).To(ContainSubstring("Starting snapshot attempt 2 of 3")) + ts := getBackupTimestamp(string(session.Out.Contents())) + gprestore(gprestorePath, restoreHelperPath, ts, "--backup-dir", backupDir, "--redirect-db", "restoredb") + Expect(snapshotRetryRows(backupConn)).To(Equal([]int{4, 5, 6})) + Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{4, 5, 6})) + } + for _, am := range []string{"heap", "ao_row", "ao_column", "pax"} { + for _, shape := range []string{"plain", "nested root data", "nested leaf data"} { + am, shape := am, shape + It(fmt.Sprintf("restores concurrent TRUNCATE for %s %s", am, shape), func() { + if am == "pax" && dbconn.MustSelectString(backupConn, "SELECT count(*) AS string FROM pg_am WHERE amname='pax'") == "0" { + Skip("PAX unavailable") + } + partitioned := shape != "plain" + createTable(am, partitioned) + args := []string{"--include-schema", "snapshot_retry", "--jobs", "2"} + if shape == "nested leaf data" { + args = append(args, "--leaf-partition-data") + } + restore(truncateDuringBackup(partitioned, args...)) + }) + } + } + It("retries with single data file and a table filter file", func() { + createTable("heap", true) + file, err := os.CreateTemp("", "snapshot-include") + Expect(err).NotTo(HaveOccurred()) + defer os.Remove(file.Name()) + _, err = file.WriteString("snapshot_retry.t\n") + Expect(err).NotTo(HaveOccurred()) + Expect(file.Close()).To(Succeed()) + restoreConn.MustExec("CREATE SCHEMA snapshot_retry") + restore(truncateDuringBackup(true, "--include-table-file", file.Name(), "--single-data-file", "--leaf-partition-data")) + }) + It("fails the entire backup when only one attempt is allowed", func() { + createTable("heap", false) + session := truncateDuringBackup(false, "--include-schema", "snapshot_retry", "--snapshot-attempts", "1") + Expect(session.ExitCode()).NotTo(Equal(0)) + Expect(string(session.Out.Contents())).To(ContainSubstring("after 1 attempt(s): snapshot_retry.t")) + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Backup completed successfully")) + }) + It("fails after two consecutive storage conflicts", func() { + createTable("heap", false) + first := testutils.SetupTestDbConn("testdb") + defer first.Close() + first.MustBegin() + defer func() { + if first.Tx[0] != nil { + first.MustRollback() + } + }() + first.MustExec("TRUNCATE snapshot_retry.t; INSERT INTO snapshot_retry.t VALUES(4),(5),(6)") + session := startSnapshotBackup("--include-schema", "snapshot_retry", "--snapshot-attempts", "2") + waitForSnapshotBackupLock("snapshot_retry.t") + second := testutils.SetupTestDbConn("testdb") + defer second.Close() + var pid int + Expect(second.Get(&pid, "SELECT pg_backend_pid()")).To(Succeed()) + second.MustBegin() + defer func() { + if second.Tx[0] != nil { + second.MustRollback() + } + }() + defer func() { + if first.Tx[0] != nil { + first.MustRollback() + } + }() + ready := make(chan error, 1) + go func() { + _, err := second.Exec("TRUNCATE snapshot_retry.t") + if err == nil { + _, err = second.Exec("INSERT INTO snapshot_retry.t VALUES(7),(8),(9)") + } + ready <- err + }() + Eventually(func() (int, error) { + var count int + err := backupConn.Get(&count, fmt.Sprintf("SELECT count(*) FROM pg_locks WHERE pid=%d AND NOT granted AND relation='snapshot_retry.t'::regclass", pid)) + return count, err + }, 30*time.Second, 100*time.Millisecond).Should(BeNumerically(">", 0)) + first.MustCommit() + Eventually(ready, 30*time.Second).Should(Receive(BeNil())) + waitForSnapshotBackupLock("snapshot_retry.t") + second.MustCommit() + Eventually(session, 90*time.Second).Should(Exit()) + Expect(session.ExitCode()).NotTo(Equal(0)) + Expect(string(session.Out.Contents())).To(ContainSubstring("after 2 attempt(s): snapshot_retry.t")) + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Backup completed successfully")) + waitForSnapshotBackupSessionsToClose() + }) + + It("restores full then incremental after a retry with heap file hashes", func() { + createTable("heap", false) + full := gpbackup(gpbackupPath, backupHelperPath, "--backup-dir", backupDir, "--include-schema", "snapshot_retry", "--leaf-partition-data", "--heap-file-hash") + fullTS := getBackupTimestamp(string(full)) + session := truncateDuringBackup(false, "--include-schema", "snapshot_retry", "--leaf-partition-data", "--heap-file-hash", "--incremental", "--from-timestamp", fullTS) + Expect(session.ExitCode()).To(Equal(0)) + Expect(string(session.Out.Contents())).To(ContainSubstring("Snapshot retry disables heap file hashes")) + ts := getBackupTimestamp(string(session.Out.Contents())) + gprestore(gprestorePath, restoreHelperPath, ts, "--backup-dir", backupDir, "--redirect-db", "restoredb") + Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{4, 5, 6})) + }) + It("cancels blocked locks and leaves no backup sessions after interruption", func() { + createTable("heap", false) + writer := testutils.SetupTestDbConn("testdb") + defer writer.Close() + writer.MustBegin() + defer writer.MustRollback() + writer.MustExec("TRUNCATE snapshot_retry.t") + session := startSnapshotBackup("--include-schema", "snapshot_retry") + waitForSnapshotBackupLock("snapshot_retry.t") + session.Signal(syscall.SIGINT) + Eventually(session, 30*time.Second).Should(Exit()) + Expect(session.ExitCode()).NotTo(Equal(0)) + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Backup completed successfully")) + waitForSnapshotBackupSessionsToClose() + }) +}) diff --git a/integration/snapshot_test.go b/integration/snapshot_test.go index 503ab2a7..56231f61 100644 --- a/integration/snapshot_test.go +++ b/integration/snapshot_test.go @@ -4,7 +4,10 @@ import ( "fmt" "github.com/apache/cloudberry-backup/backup" + "github.com/apache/cloudberry-backup/options" "github.com/apache/cloudberry-backup/testutils" + "github.com/apache/cloudberry-go-libs/dbconn" + "github.com/spf13/cobra" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -219,3 +222,241 @@ var _ = Describe("synchronized snapshot integration tests", func() { }) }) }) + +var _ = Describe("snapshot storage validation", func() { + BeforeEach(func() { + if !connectionPool.Version.IsCBDB() { + Skip("snapshot storage validation is supported only on Cloudberry") + } + connectionPool.MustExec("CREATE TABLE public.snapshot_storage (id int) DISTRIBUTED BY (id); INSERT INTO public.snapshot_storage VALUES (1),(2),(3)") + }) + AfterEach(func() { connectionPool.MustExec("DROP TABLE public.snapshot_storage") }) + It("detects a committed rewrite and accepts a fresh shared snapshot", func() { + reader := testutils.SetupTestDbConn("testdb") + reader.MustExec("SET search_path TO pg_catalog") + defer reader.Close() + worker := testutils.SetupTestDbConn("testdb") + defer worker.Close() + reader.MustBegin() + _, err := backup.GetSynchronizedSnapshot(reader) + Expect(err).NotTo(HaveOccurred()) + var oid uint32 + Expect(reader.Get(&oid, "SELECT 'public.snapshot_storage'::regclass::oid")).To(Succeed()) + tables := []backup.Relation{{Oid: oid, Schema: "public", Name: "snapshot_storage"}} + var before, after []string + query := "SELECT gp_segment_id::text || ':' || relfilenode::text FROM gp_dist_random('pg_class') WHERE oid='public.snapshot_storage'::regclass ORDER BY gp_segment_id" + Expect(connectionPool.Select(&before, query)).To(Succeed()) + connectionPool.MustExec("TRUNCATE public.snapshot_storage; INSERT INTO public.snapshot_storage VALUES (4),(5),(6)") + Expect(connectionPool.Select(&after, query)).To(Succeed()) + Expect(after).NotTo(Equal(before)) + Expect(backup.LockTables(reader, tables)).To(Succeed()) + conflicts, err := backup.CheckSnapshotTables(reader, tables) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(ConsistOf(ContainSubstring("storage changed"))) + reader.MustRollback() + reader.MustBegin() + snapshot, err := backup.GetSynchronizedSnapshot(reader) + Expect(err).NotTo(HaveOccurred()) + Expect(backup.SetSynchronizedSnapshot(worker, 0, snapshot)).To(Succeed()) + Expect(backup.LockTables(reader, tables)).To(Succeed()) + conflicts, err = backup.CheckSnapshotTables(reader, tables) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(BeEmpty()) + for _, conn := range []*dbconn.DBConn{reader, worker} { + var rows []int + Expect(conn.Select(&rows, "SELECT id FROM public.snapshot_storage ORDER BY id")).To(Succeed()) + Expect(rows).To(Equal([]int{4, 5, 6})) + conn.MustRollback() + } + }) + It("does not reject ordinary concurrent DML", func() { + reader := testutils.SetupTestDbConn("testdb") + reader.MustExec("SET search_path TO pg_catalog") + defer reader.Close() + reader.MustBegin() + defer reader.MustRollback() + _, err := backup.GetSynchronizedSnapshot(reader) + Expect(err).NotTo(HaveOccurred()) + var oid uint32 + Expect(reader.Get(&oid, "SELECT 'public.snapshot_storage'::regclass::oid")).To(Succeed()) + connectionPool.MustExec("INSERT INTO public.snapshot_storage VALUES (4); UPDATE public.snapshot_storage SET id=8 WHERE id=2; DELETE FROM public.snapshot_storage WHERE id=3") + tables := []backup.Relation{{Oid: oid, Schema: "public", Name: "snapshot_storage"}} + Expect(backup.LockTables(reader, tables)).To(Succeed()) + conflicts, err := backup.CheckSnapshotTables(reader, tables) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(BeEmpty()) + var rows []int + Expect(reader.Select(&rows, "SELECT id FROM public.snapshot_storage ORDER BY id")).To(Succeed()) + Expect(rows).To(Equal([]int{1, 2, 3})) + }) + It("detects a renamed table replaced under its old name", func() { + defer connectionPool.MustExec("DROP TABLE IF EXISTS public.snapshot_old") + reader := testutils.SetupTestDbConn("testdb") + reader.MustExec("SET search_path TO pg_catalog") + defer reader.Close() + reader.MustBegin() + defer reader.MustRollback() + _, err := backup.GetSynchronizedSnapshot(reader) + Expect(err).NotTo(HaveOccurred()) + var oid uint32 + Expect(reader.Get(&oid, "SELECT oid FROM pg_class WHERE relname='snapshot_storage'")).To(Succeed()) + connectionPool.MustExec("ALTER TABLE public.snapshot_storage RENAME TO snapshot_old; CREATE TABLE public.snapshot_storage (id int) DISTRIBUTED BY (id)") + tables := []backup.Relation{{Oid: oid, Schema: "public", Name: "snapshot_storage"}} + Expect(backup.LockTables(reader, tables)).To(Succeed()) + conflicts, err := backup.CheckSnapshotTables(reader, tables) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(ConsistOf(ContainSubstring("snapshot OID"))) + }) + It("checks a nested leaf when only the root is supplied", func() { + connectionPool.MustExec(`CREATE TABLE public.snapshot_root (id int) PARTITION BY RANGE(id) DISTRIBUTED BY(id); + CREATE TABLE public.snapshot_middle PARTITION OF public.snapshot_root FOR VALUES FROM (0) TO (10) PARTITION BY RANGE(id); + CREATE TABLE public.snapshot_leaf PARTITION OF public.snapshot_middle FOR VALUES FROM (0) TO (10); + INSERT INTO public.snapshot_root VALUES(1),(2),(3)`) + defer connectionPool.MustExec("DROP TABLE public.snapshot_root") + reader := testutils.SetupTestDbConn("testdb") + reader.MustExec("SET search_path TO pg_catalog") + defer reader.Close() + reader.MustBegin() + defer reader.MustRollback() + _, err := backup.GetSynchronizedSnapshot(reader) + Expect(err).NotTo(HaveOccurred()) + var oid uint32 + Expect(reader.Get(&oid, "SELECT oid FROM pg_class WHERE relname='snapshot_root'")).To(Succeed()) + connectionPool.MustExec("TRUNCATE public.snapshot_leaf; INSERT INTO public.snapshot_leaf VALUES(4),(5),(6)") + tables := []backup.Relation{{Oid: oid, Schema: "public", Name: "snapshot_root"}} + Expect(backup.LockTables(reader, tables)).To(Succeed()) + conflicts, err := backup.CheckSnapshotTables(reader, tables) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(ConsistOf(ContainSubstring("public.snapshot_leaf"))) + }) +}) + +var _ = Describe("snapshot retry filter resolution", func() { + BeforeEach(func() { + if !connectionPool.Version.IsCBDB() { + Skip("snapshot retries are supported only on Cloudberry") + } + }) + It("resolves a replacement OID and restores session settings and worker snapshots", func() { + connectionPool.MustExec("CREATE TABLE public.retry_filter(id int) DISTRIBUTED BY(id); INSERT INTO public.retry_filter VALUES(1)") + defer connectionPool.MustExec("DROP TABLE public.retry_filter; DROP TABLE public.retry_filter_old") + reader := dbconn.NewDBConnFromEnvironment("testdb") + reader.MustConnect(2) + defer reader.Close() + defer func() { + backup.SetConnection(connectionPool) + backup.InitializeMetadataParams(connectionPool) + backup.SetBackupSnapshot("") + }() + cmd := &cobra.Command{} + backup.DoInit(cmd) + backup.SetConnection(reader) + backup.InitializeMetadataParams(reader) + Expect(cmd.Flags().Set(options.INCLUDE_RELATION, "public.retry_filter")).To(Succeed()) + opts, err := options.NewOptions(cmd.Flags()) + Expect(err).NotTo(HaveOccurred()) + reader.MustBegin(0) + reader.MustBegin(1) + snapshot, err := backup.GetSynchronizedSnapshot(reader) + Expect(err).NotTo(HaveOccurred()) + backup.SetBackupSnapshot(snapshot) + Expect(backup.SetSynchronizedSnapshot(reader, 1, snapshot)).To(Succeed()) + backup.ValidateAndProcessFilterLists(opts) + oldOid := backup.IncludedRelationFqns[0].Oid + connectionPool.MustExec("ALTER TABLE public.retry_filter RENAME TO retry_filter_old; CREATE TABLE public.retry_filter(id int) DISTRIBUTED BY(id); INSERT INTO public.retry_filter VALUES(4),(5),(6)") + _, data := backup.RetrieveAndProcessTables(opts) + Expect(data).To(HaveLen(1)) + Expect(data[0].Oid).NotTo(Equal(oldOid)) + Expect(backup.IncludedRelationFqns[0].Oid).To(Equal(data[0].Oid)) + connectionPool.MustExec("INSERT INTO public.retry_filter VALUES(7)") + for i := 0; i < 2; i++ { + var rows []int + Expect(reader.Select(&rows, "SELECT id FROM public.retry_filter ORDER BY id", i)).To(Succeed()) + Expect(rows).To(Equal([]int{4, 5, 6})) + var searchPath, appName, timeout string + Expect(reader.Get(&searchPath, "SHOW search_path", i)).To(Succeed()) + Expect(searchPath).To(Equal("pg_catalog")) + Expect(reader.Get(&timeout, "SHOW statement_timeout", i)).To(Succeed()) + Expect(timeout).To(Equal("0")) + Expect(reader.Get(&appName, "SHOW application_name", i)).To(Succeed()) + Expect(appName).To(HavePrefix("gpbackup_")) + reader.MustRollback(i) + } + }) + It("rejects an explicitly included table that disappeared before retry", func() { + connectionPool.MustExec("CREATE TABLE public.retry_missing(id int) DISTRIBUTED BY(id)") + defer connectionPool.MustExec("DROP TABLE public.retry_missing_old") + reader := dbconn.NewDBConnFromEnvironment("testdb") + reader.MustConnect(2) + defer reader.Close() + defer func() { + backup.SetConnection(connectionPool) + backup.InitializeMetadataParams(connectionPool) + backup.SetBackupSnapshot("") + }() + cmd := &cobra.Command{} + backup.DoInit(cmd) + backup.SetConnection(reader) + backup.InitializeMetadataParams(reader) + Expect(cmd.Flags().Set(options.INCLUDE_RELATION, "public.retry_missing")).To(Succeed()) + opts, err := options.NewOptions(cmd.Flags()) + Expect(err).NotTo(HaveOccurred()) + reader.MustBegin(0) + reader.MustBegin(1) + defer func() { + for i := 0; i < 2; i++ { + if reader.Tx[i] != nil { + reader.MustRollback(i) + } + } + }() + snapshot, err := backup.GetSynchronizedSnapshot(reader) + Expect(err).NotTo(HaveOccurred()) + backup.SetBackupSnapshot(snapshot) + Expect(backup.SetSynchronizedSnapshot(reader, 1, snapshot)).To(Succeed()) + backup.ValidateAndProcessFilterLists(opts) + connectionPool.MustExec("ALTER TABLE public.retry_missing RENAME TO retry_missing_old") + Expect(func() { backup.RetrieveAndProcessTables(opts) }).To(PanicWith(MatchRegexp("Table public.retry_missing does not exist"))) + }) + + It("discards expanded old partitions and discovers new ones after retry", func() { + connectionPool.MustExec(`CREATE TABLE public.retry_root(id int) DISTRIBUTED BY(id) PARTITION BY RANGE(id); + CREATE TABLE public.retry_old_leaf PARTITION OF public.retry_root FOR VALUES FROM(0) TO(10)`) + defer connectionPool.MustExec("DROP TABLE public.retry_root") + reader := dbconn.NewDBConnFromEnvironment("testdb") + reader.MustConnect(2) + defer reader.Close() + defer func() { + backup.SetConnection(connectionPool) + backup.InitializeMetadataParams(connectionPool) + backup.SetBackupSnapshot("") + }() + cmd := &cobra.Command{} + backup.DoInit(cmd) + backup.SetConnection(reader) + backup.InitializeMetadataParams(reader) + Expect(cmd.Flags().Set(options.INCLUDE_RELATION, "public.retry_root")).To(Succeed()) + Expect(cmd.Flags().Set(options.LEAF_PARTITION_DATA, "true")).To(Succeed()) + opts, err := options.NewOptions(cmd.Flags()) + Expect(err).NotTo(HaveOccurred()) + reader.MustBegin(0) + reader.MustBegin(1) + snapshot, err := backup.GetSynchronizedSnapshot(reader) + Expect(err).NotTo(HaveOccurred()) + backup.SetBackupSnapshot(snapshot) + Expect(backup.SetSynchronizedSnapshot(reader, 1, snapshot)).To(Succeed()) + backup.ValidateAndProcessFilterLists(opts) + Expect(backup.ExpandIncludesForPartitions(reader, opts, backup.GetOidsFromRelationList(backup.IncludedRelationFqns), cmd.Flags())).To(Succeed()) + Expect(opts.GetIncludedTables()).To(ContainElement("public.retry_old_leaf")) + connectionPool.MustExec(`ALTER TABLE public.retry_root DETACH PARTITION public.retry_old_leaf; DROP TABLE public.retry_old_leaf; + CREATE TABLE public.retry_new_leaf PARTITION OF public.retry_root FOR VALUES FROM(0) TO(10); INSERT INTO public.retry_root VALUES(4),(5),(6)`) + _, data := backup.RetrieveAndProcessTables(opts) + Expect(data).To(HaveLen(1)) + Expect(data[0].Name).To(Equal("retry_new_leaf")) + Expect(opts.GetIncludedTables()).NotTo(ContainElement("public.retry_old_leaf")) + Expect(opts.GetIncludedTables()).To(ContainElement("public.retry_new_leaf")) + for i := 0; i < 2; i++ { + reader.MustRollback(i) + } + }) +}) diff --git a/integration/wrappers_test.go b/integration/wrappers_test.go index cb64c3f2..e39a2983 100644 --- a/integration/wrappers_test.go +++ b/integration/wrappers_test.go @@ -35,7 +35,7 @@ var _ = Describe("Wrappers Integration", func() { connectionPool.MustBegin(0) defer connectionPool.MustCommit(0) - _, dataTables := backup.RetrieveAndProcessTables() + _, dataTables := backup.RetrieveAndProcessTables(subject) Expect(len(dataTables)).To(Equal(2)) Expect(dataTables[0].Name).To(Equal("foo")) Expect(dataTables[1].Name).To(Equal(`"BAR"`)) diff --git a/options/flag.go b/options/flag.go index dad5ea76..76bcba06 100644 --- a/options/flag.go +++ b/options/flag.go @@ -57,6 +57,7 @@ const ( NO_INHERITS = "no-inherits" REPORT_DIR = "report-dir" HEAP_FILE_HASH = "heap-file-hash" + SNAPSHOT_ATTEMPTS = "snapshot-attempts" DEFAULT_HISTORY_SYNC_STANDBY_TIMEOUT = 300 ) @@ -95,6 +96,7 @@ func SetBackupFlagDefaults(flagSet *pflag.FlagSet) { flagSet.Bool(WITH_STATS, false, "Back up query plan statistics") flagSet.Bool(WITHOUT_GLOBALS, false, "Skip backup of global metadata") flagSet.Bool(NO_INHERITS, false, "For a filtered backup, don't back up all tables that inherit included tables") + flagSet.Int(SNAPSHOT_ATTEMPTS, 3, "Maximum Cloudberry snapshot preparation attempts, including the first; 1 disables retries. Fail the backup if table storage or identity still conflicts after the last attempt") flagSet.Bool(HEAP_FILE_HASH, false, "Skip unchanged heap tables in incremental backups by hashing their data files. Issues a cluster-wide CHECKPOINT before the backup starts") } diff --git a/options/options.go b/options/options.go index 716c249f..9ef1fb06 100644 --- a/options/options.go +++ b/options/options.go @@ -23,6 +23,7 @@ type Options struct { ExcludedSchemas []string IncludedSchemas []string originalIncludedRelations []string + originalExcludedRelations []string RedirectSchema string } @@ -74,7 +75,8 @@ func NewOptions(initialFlags *pflag.FlagSet) (*Options, error) { IncludedSchemas: includedSchemas, ExcludedSchemas: excludedSchemas, isLeafPartitionData: leafPartitionData, - originalIncludedRelations: includedRelations, + originalIncludedRelations: append([]string(nil), includedRelations...), + originalExcludedRelations: append([]string(nil), excludedRelations...), RedirectSchema: redirectSchema, }, nil } @@ -136,6 +138,16 @@ func (o Options) GetExcludedSchemas() []string { return o.ExcludedSchemas } +// ResetTableFilters restores the input names without rereading filter files. +func (o *Options) ResetTableFilters(flags *pflag.FlagSet) error { + o.IncludedRelations = append([]string(nil), o.originalIncludedRelations...) + o.ExcludedRelations = append([]string(nil), o.originalExcludedRelations...) + if err := flags.Lookup(INCLUDE_RELATION).Value.(pflag.SliceValue).Replace(o.IncludedRelations); err != nil { + return err + } + return flags.Lookup(EXCLUDE_RELATION).Value.(pflag.SliceValue).Replace(o.ExcludedRelations) +} + func (o *Options) AddIncludedRelation(relation string) { o.IncludedRelations = append(o.IncludedRelations, relation) } diff --git a/options/options_test.go b/options/options_test.go index 539f82b1..1888dc19 100644 --- a/options/options_test.go +++ b/options/options_test.go @@ -21,6 +21,49 @@ var _ = Describe("options", func() { myflags = &pflag.FlagSet{} options.SetBackupFlagDefaults(myflags) }) + Describe("snapshot attempts and filter reset", func() { + It("defaults to three attempts and rejects noninteger values", func() { + value, err := myflags.GetInt(options.SNAPSHOT_ATTEMPTS) + Expect(err).NotTo(HaveOccurred()) + Expect(value).To(Equal(3)) + Expect(myflags.Set(options.SNAPSHOT_ATTEMPTS, "1.5")).NotTo(Succeed()) + restoreFlags := pflag.NewFlagSet("restore", pflag.ContinueOnError) + options.SetRestoreFlagDefaults(restoreFlags) + Expect(restoreFlags.Lookup(options.SNAPSHOT_ATTEMPTS)).To(BeNil()) + }) + It("restores original names after expansion without reading the filter file again", func() { + file, err := os.CreateTemp("", "snapshot-filters") + Expect(err).NotTo(HaveOccurred()) + defer os.Remove(file.Name()) + _, err = file.WriteString("public.root\n") + Expect(err).NotTo(HaveOccurred()) + Expect(file.Close()).To(Succeed()) + Expect(myflags.Set(options.INCLUDE_RELATION_FILE, file.Name())).To(Succeed()) + subject, err := options.NewOptions(myflags) + Expect(err).NotTo(HaveOccurred()) + subject.AddIncludedRelation("public.old_leaf") + Expect(myflags.Set(options.INCLUDE_RELATION, "public.old_leaf")).To(Succeed()) + Expect(os.Remove(file.Name())).To(Succeed()) + Expect(subject.ResetTableFilters(myflags)).To(Succeed()) + Expect(subject.GetIncludedTables()).To(Equal([]string{"public.root"})) + Expect(options.MustGetFlagStringArray(myflags, options.INCLUDE_RELATION)).To(Equal([]string{"public.root"})) + Expect(subject.GetOriginalIncludedTables()).To(Equal([]string{"public.root"})) + Expect(subject.ResetTableFilters(myflags)).To(Succeed()) + }) + It("restores exclusions and owns copies of original names", func() { + Expect(myflags.Set(options.INCLUDE_RELATION, "public.root")).To(Succeed()) + Expect(myflags.Set(options.EXCLUDE_RELATION, "public.omitted")).To(Succeed()) + subject, err := options.NewOptions(myflags) + Expect(err).NotTo(HaveOccurred()) + subject.IncludedRelations[0] = "public.changed" + subject.ExcludedRelations[0] = "public.changed" + Expect(subject.ResetTableFilters(myflags)).To(Succeed()) + Expect(subject.GetIncludedTables()).To(Equal([]string{"public.root"})) + Expect(subject.GetExcludedTables()).To(Equal([]string{"public.omitted"})) + Expect(options.MustGetFlagStringArray(myflags, options.EXCLUDE_RELATION)).To(Equal([]string{"public.omitted"})) + }) + }) + Describe("Options initialization", func() { It("returns no included tables when none specified", func() { subject, err := options.NewOptions(myflags) From 9d3ba34606fcf2f771cb71e74c9397fcb80ccfa2 Mon Sep 17 00:00:00 2001 From: woblerr Date: Fri, 27 Nov 2026 01:22:26 +0300 Subject: [PATCH 2/7] Acquire table locks before taking the backup snapshot. A concurrent TRUNCATE can make a table appear empty to a snapshot taken before locking. Checking relfilenode also triggers retries after VACUUM FULL, even when the old snapshot can still read the rows. Lock tables before taking the snapshot to close the TRUNCATE race. Retry preparation if concurrent DDL leaves a required table unlocked. --- backup/backup.go | 28 +-- backup/global_variables.go | 1 - backup/snapshot.go | 157 ++++++------- backup/snapshot_internal_test.go | 226 +++++++++---------- backup/wrappers.go | 23 +- end_to_end/snapshot_retry_test.go | 107 +++++++-- integration/snapshot_test.go | 353 ++++++++++++------------------ integration/wrappers_test.go | 2 +- options/flag.go | 2 +- 9 files changed, 443 insertions(+), 456 deletions(-) diff --git a/backup/backup.go b/backup/backup.go index 3fb618dc..e96a2674 100644 --- a/backup/backup.go +++ b/backup/backup.go @@ -49,28 +49,18 @@ func DoSetup() { utils.CheckGpexpandRunning(utils.BackupPreventedByGpexpandMessage) timestamp := history.CurrentTimestamp() createBackupLockFile(timestamp) - // Heap file hashes must be read before initializeConnectionPool takes the - // backup snapshot, and verified after it; see CollectHeapFileHashes. + // Collect heap hashes before the snapshot and verify them after it. var hashedHeapTables []heapTable if MustGetFlagBool(options.HEAP_FILE_HASH) && collectsIncrementalMetadata() { gplog.Info("Collecting heap table file hashes") hashedHeapTables, heapFileHashes = CollectHeapFileHashes(MustGetFlagString(options.DBNAME)) } initializeConnectionPool(timestamp) - if heapFileHashes != nil { - heapFileHashes = VerifyHeapFileHashes(MustGetFlagString(options.DBNAME), hashedHeapTables, heapFileHashes) - } gplog.Info("Apache Cloudberry Version = %s", connectionPool.Version.VersionString) gplog.Info("Starting backup of database %s", MustGetFlagString(options.DBNAME)) opts, err := options.NewOptions(cmdFlags) gplog.FatalOnError(err) - backupOptions = opts - - ValidateAndProcessFilterLists(opts) - includeOids := GetOidsFromRelationList(IncludedRelationFqns) - err = ExpandIncludesForPartitions(connectionPool, opts, includeOids, cmdFlags) - gplog.FatalOnError(err) clusterConfigConn := dbconn.NewDBConnFromEnvironment(MustGetFlagString(options.DBNAME)) clusterConfigConn.MustConnect(1) @@ -93,6 +83,17 @@ func DoSetup() { globalTOC = &toc.TOC{} globalTOC.InitializeMetadataEntryMap() utils.InitializePipeThroughParameters(!MustGetFlagBool(options.NO_COMPRESSION), MustGetFlagString(options.COMPRESSION_TYPE), MustGetFlagInt(options.COMPRESSION_LEVEL)) + // Signal cleanup needs globalFPInfo.Timestamp to cancel blocked sessions. + if connectionPool.Version.IsCBDB() { + gplog.FatalOnError(PrepareBackupSnapshot(opts)) + } else { + ValidateAndProcessFilterLists(opts) + includeOids := GetOidsFromRelationList(IncludedRelationFqns) + gplog.FatalOnError(ExpandIncludesForPartitions(connectionPool, opts, includeOids, cmdFlags)) + } + if heapFileHashes != nil { + heapFileHashes = VerifyHeapFileHashes(MustGetFlagString(options.DBNAME), hashedHeapTables, heapFileHashes) + } getQuotedRoleNames(connectionPool) pluginConfigFlag := MustGetFlagString(options.PLUGIN_CONFIG) @@ -144,7 +145,7 @@ func DoBackup() { } gplog.Info("Gathering table state information") - metadataTables, dataTables := RetrieveAndProcessTables(backupOptions) + metadataTables, dataTables := RetrieveAndProcessTables() dataTables, numExtOrForeignTables := GetBackupDataSet(dataTables) if len(dataTables) == 0 && !backupReport.MetadataOnly { gplog.Warn("No tables in backup set contain data. Performing metadata-only backup instead.") @@ -524,7 +525,8 @@ func DoCleanup(backupFailed bool) { // panics, there should be no way for gpbackup to exit that leaves the entry in the initial status. historyUpdated := false - if !MustGetFlagBool(options.NO_HISTORY) { + // Cancellation during lock acquisition can precede report creation. + if backupReport != nil && !MustGetFlagBool(options.NO_HISTORY) { var statusString string if backupFailed { statusString = history.BackupStatusFailed diff --git a/backup/global_variables.go b/backup/global_variables.go index 881da88e..01233617 100644 --- a/backup/global_variables.go +++ b/backup/global_variables.go @@ -49,7 +49,6 @@ var ( quotedRoleNames map[string]string backupSnapshot string heapFileHashes map[uint32]string - backupOptions *options.Options /* * Used for synchronizing DoCleanup. In DoInit() we increment the group * and then wait for at least one DoCleanup to finish, either in DoTeardown diff --git a/backup/snapshot.go b/backup/snapshot.go index 8cfbd205..ff880ba6 100644 --- a/backup/snapshot.go +++ b/backup/snapshot.go @@ -1,11 +1,6 @@ package backup -/* - * This file contains functions related to use of synchronized database snapshots. - */ - import ( - "database/sql" "errors" "fmt" "sort" @@ -18,53 +13,44 @@ import ( "github.com/jackc/pgx/v5/pgconn" ) -// CheckSnapshotTables compares the Cloudberry MVCC catalog with the current relation cache -// after ACCESS SHARE locks have been acquired. A rewrite can commit while LOCK -// waits, leaving the snapshot's old storage inaccessible. Catalog functions use -// current identity, as pg_relation_filepath does for incremental heap hashes. -func CheckSnapshotTables(conn *dbconn.DBConn, tables []Relation) ([]string, error) { +// CheckSnapshotTableLocks finds relations in the backup snapshot without a +// lock, including descendants read through a parent. +func CheckSnapshotTableLocks(conn *dbconn.DBConn, tables []Relation) ([]string, error) { if len(tables) == 0 { return nil, nil } - oids := make([]string, len(tables)) - for i, table := range tables { - oids[i] = strconv.FormatUint(uint64(table.Oid), 10) - } - // Include descendants even when COPY reads their data through a parent. - query := fmt.Sprintf(`WITH RECURSIVE relations(oid) AS ( + conflicts := make(map[string]bool) + const batchSize = 1000 + for start := 0; start < len(tables); start += batchSize { + end := start + batchSize + if end > len(tables) { + end = len(tables) + } + oids := make([]string, end-start) + for i, table := range tables[start:end] { + oids[i] = strconv.FormatUint(uint64(table.Oid), 10) + } + query := fmt.Sprintf(`WITH RECURSIVE relations(oid) AS ( SELECT oid FROM pg_catalog.pg_class WHERE oid IN (%s) UNION SELECT i.inhrelid FROM pg_catalog.pg_inherits i JOIN relations r ON i.inhparent = r.oid ) - SELECT quote_ident(n.nspname) || '.' || quote_ident(c.relname) AS fqn, - c.oid AS oid, c.relfilenode AS snapshotnode, - pg_catalog.pg_relation_filenode(c.oid) AS currentnode, - pg_catalog.to_regclass(quote_ident(n.nspname) || '.' || quote_ident(c.relname))::oid AS currentoid + SELECT quote_ident(n.nspname) || '.' || quote_ident(c.relname) AS fqn FROM relations r JOIN pg_catalog.pg_class c ON c.oid = r.oid - JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace`, strings.Join(oids, ",")) - var rows []struct { - FQN string - Oid uint32 - SnapshotNode uint32 - CurrentNode sql.NullInt64 - CurrentOid sql.NullInt64 - } - if err := conn.Select(&rows, query); err != nil { - return nil, fmt.Errorf("checking table storage against backup snapshot: %w", err) - } - conflicts := make(map[string]bool) - for _, row := range rows { - var reason string - switch { - case !row.CurrentOid.Valid || row.CurrentOid.Int64 != int64(row.Oid): - reason = "table name no longer identifies the snapshot OID" - case row.SnapshotNode != 0 && !row.CurrentNode.Valid: - reason = "table storage disappeared" - case row.SnapshotNode != 0 && row.CurrentNode.Int64 != int64(row.SnapshotNode): - reason = "table storage changed after the snapshot" + JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE NOT EXISTS ( + SELECT 1 FROM pg_catalog.pg_locks l + WHERE l.locktype = 'relation' AND l.relation = c.oid + AND l.database = (SELECT oid FROM pg_catalog.pg_database WHERE datname = current_database()) + AND l.pid = pg_catalog.pg_backend_pid() + AND l.mode = 'AccessShareLock' AND l.granted + )`, strings.Join(oids, ",")) + var rows []struct{ FQN string } + if err := conn.Select(&rows, query); err != nil { + return nil, fmt.Errorf("checking backup table locks: %w", err) } - if reason != "" { - conflicts[fmt.Sprintf("%s (%s)", row.FQN, reason)] = true + for _, row := range rows { + conflicts[row.FQN] = true } } result := make([]string, 0, len(conflicts)) @@ -75,60 +61,79 @@ func CheckSnapshotTables(conn *dbconn.DBConn, tables []Relation) ([]string, erro return result, nil } -func prepareSnapshotTables(opts *options.Options) ([]Relation, error) { +// PrepareBackupSnapshot locks Cloudberry tables before exporting the shared +// snapshot. The connection pool must have no open transactions on entry. +func PrepareBackupSnapshot(opts *options.Options) error { maxAttempts := MustGetFlagInt(options.SNAPSHOT_ATTEMPTS) - checkSnapshot := connectionPool.Version.IsCBDB() && !MustGetFlagBool(options.METADATA_ONLY) - for attempt := 1; ; attempt++ { + for attempt := 1; attempt <= maxAttempts; attempt++ { + if err := resolveSnapshotFilters(opts); err != nil { + return err + } tables := ConvertRelationsOptionsToBackup(GetIncludedUserTableRelations(connectionPool, IncludedRelationFqns)) + // A SELECT before LOCK would establish the transaction snapshot too early. + if err := connectionPool.Begin(0); err != nil { + return err + } lockErr := LockTables(connectionPool, tables) var conflicts []string if lockErr != nil { var pgErr *pgconn.PgError - if !checkSnapshot || !errors.As(lockErr, &pgErr) || (pgErr.Code != "42P01" && pgErr.Code != "3F000") { - return nil, lockErr + if !errors.As(lockErr, &pgErr) || (pgErr.Code != "42P01" && pgErr.Code != "3F000") { + return lockErr } conflicts = []string{lockErr.Error()} - } else if checkSnapshot { + } else { var err error - conflicts, err = CheckSnapshotTables(connectionPool, tables) + backupSnapshot, err = GetSynchronizedSnapshot(connectionPool) if err != nil { - return nil, err + return err + } + if err = resolveSnapshotFilters(opts); err != nil { + return err + } + tables = ConvertRelationsOptionsToBackup(GetIncludedUserTableRelations(connectionPool, IncludedRelationFqns)) + // Locking new tables here would reopen the concurrent TRUNCATE race. + conflicts, err = CheckSnapshotTableLocks(connectionPool, tables) + if err != nil { + return err } } if len(conflicts) == 0 { - return tables, nil - } - if attempt >= maxAttempts { - return nil, fmt.Errorf("could not obtain a consistent backup snapshot after %d attempt(s): %s", attempt, strings.Join(conflicts, "; ")) - } - gplog.Warn("Backup snapshot conflict: %s. Starting snapshot attempt %d of %d", strings.Join(conflicts, "; "), attempt+1, maxAttempts) - if attempt == 1 { - heapFileHashes = nil - if MustGetFlagBool(options.HEAP_FILE_HASH) { - gplog.Warn("Snapshot retry disables heap file hashes for this backup; all heap table data will be included and the backup may be larger") + for connNum := 1; connNum < connectionPool.NumConns; connNum++ { + if err := SetSynchronizedSnapshot(connectionPool, connNum, backupSnapshot); err != nil { + return err + } } + return nil } - if err := restartBackupTransactions(); err != nil { - return nil, err - } - if err := opts.ResetTableFilters(cmdFlags); err != nil { - return nil, err + if err := connectionPool.Rollback(0); err != nil { + return fmt.Errorf("rolling back backup snapshot preparation: %w", err) } - filterRelationClause = "" - ValidateAndProcessFilterLists(opts) - if err := ExpandIncludesForPartitions(connectionPool, opts, GetOidsFromRelationList(IncludedRelationFqns), cmdFlags); err != nil { - return nil, err + backupSnapshot = "" + details := snapshotConflictSummary(conflicts) + if attempt >= maxAttempts { + return fmt.Errorf("could not lock the backup table set before taking a snapshot after %d attempt(s): %s", attempt, details) } + gplog.Warn("Backup table set changed: %s. Starting snapshot attempt %d of %d", details, attempt+1, maxAttempts) } + return fmt.Errorf("snapshot preparation requires at least one attempt") } -func restartBackupTransactions() error { - for connNum := 0; connNum < connectionPool.NumConns; connNum++ { - if err := connectionPool.Rollback(connNum); err != nil { - return fmt.Errorf("rolling back backup connection %d for snapshot retry: %w", connNum, err) - } +func resolveSnapshotFilters(opts *options.Options) error { + if err := opts.ResetTableFilters(cmdFlags); err != nil { + return err + } + filterRelationClause = "" + ValidateAndProcessFilterLists(opts) + return ExpandIncludesForPartitions(connectionPool, opts, GetOidsFromRelationList(IncludedRelationFqns), cmdFlags) +} + +func snapshotConflictSummary(conflicts []string) string { + const limit = 10 + if len(conflicts) > limit { + return fmt.Sprintf("%s; and %d more", strings.Join(conflicts[:limit], "; "), len(conflicts)-limit) } - return initializeBackupTransactions(globalFPInfo.Timestamp) + return strings.Join(conflicts, "; ") } const ( diff --git a/backup/snapshot_internal_test.go b/backup/snapshot_internal_test.go index 43875f7b..7e824dbc 100644 --- a/backup/snapshot_internal_test.go +++ b/backup/snapshot_internal_test.go @@ -20,7 +20,6 @@ under the License. package backup import ( - "database/sql/driver" "errors" "fmt" @@ -37,7 +36,6 @@ import ( var _ = Describe("snapshot preparation", func() { var mock sqlmock.Sqlmock var opts *options.Options - columns := []string{"fqn", "oid", "snapshotnode", "currentnode", "currentoid"} table := Relation{Oid: 10, Schema: "public", Name: "t"} BeforeEach(func() { connectionPool, mock, _, _, _ = testhelper.SetupTestEnvironment() @@ -60,43 +58,49 @@ var _ = Describe("snapshot preparation", func() { heapFileHashes = nil }) - DescribeTable("storage and identity conflicts", func(node, oid driver.Value, oldNode int, reason string) { - mock.ExpectQuery("WITH RECURSIVE").WillReturnRows(sqlmock.NewRows(columns).AddRow("public.t", 10, oldNode, node, oid)) - conflicts, err := CheckSnapshotTables(connectionPool, []Relation{table}) - Expect(err).NotTo(HaveOccurred()) - if reason == "" { - Expect(conflicts).To(BeEmpty()) - } else { - Expect(conflicts).To(ConsistOf(ContainSubstring(reason))) + check := func(missing ...string) { + rows := sqlmock.NewRows([]string{"fqn"}) + for _, name := range missing { + rows.AddRow(name) } - }, - Entry("unchanged", 20, 10, 20, ""), - Entry("rewritten", 21, 10, 20, "storage changed"), - Entry("missing storage", nil, 10, 20, "storage disappeared"), - Entry("replaced OID", 20, 11, 20, "snapshot OID"), - Entry("missing name", 20, nil, 20, "snapshot OID"), - Entry("no own storage", nil, 10, 0, ""), - ) + mock.ExpectQuery("WITH RECURSIVE.*").WillReturnRows(rows) + } + It("accepts tables and descendants already locked before the snapshot", func() { + check() + conflicts, err := CheckSnapshotTableLocks(connectionPool, []Relation{table}) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(BeEmpty()) + }) It("does not query for an empty table set", func() { - conflicts, err := CheckSnapshotTables(connectionPool, nil) + conflicts, err := CheckSnapshotTableLocks(connectionPool, nil) Expect(err).NotTo(HaveOccurred()) Expect(conflicts).To(BeEmpty()) }) - It("reports nested descendants only once", func() { - mock.ExpectQuery("WITH RECURSIVE.*JOIN relations").WillReturnRows(sqlmock.NewRows(columns). - AddRow("public.root", 10, 0, nil, 10). - AddRow("public.leaf", 11, 20, 21, 11). - AddRow("public.leaf", 11, 20, 21, 11)) - conflicts, err := CheckSnapshotTables(connectionPool, []Relation{table}) + It("deduplicates missing descendants across bounded OID batches", func() { + tables := make([]Relation, 1001) + for i := range tables { + tables[i] = Relation{Oid: uint32(i + 10)} + } + check("public.leaf", "public.leaf") + check("public.leaf", "public.other") + conflicts, err := CheckSnapshotTableLocks(connectionPool, tables) Expect(err).NotTo(HaveOccurred()) - Expect(conflicts).To(HaveLen(1)) - Expect(conflicts[0]).To(ContainSubstring("public.leaf")) + Expect(conflicts).To(Equal([]string{"public.leaf", "public.other"})) }) - It("fails closed on a check error", func() { + It("fails closed on a lock validation error", func() { mock.ExpectQuery("WITH RECURSIVE").WillReturnError(errors.New("catalog failure")) - _, err := CheckSnapshotTables(connectionPool, []Relation{table}) + _, err := CheckSnapshotTableLocks(connectionPool, []Relation{table}) Expect(err).To(MatchError(ContainSubstring("catalog failure"))) }) + It("bounds conflict diagnostics", func() { + names := make([]string, 12) + for i := range names { + names[i] = fmt.Sprintf("t%d", i) + } + summary := snapshotConflictSummary(names) + Expect(summary).To(ContainSubstring("t9; and 2 more")) + Expect(summary).NotTo(ContainSubstring("t10")) + }) begin := func() { mock.ExpectBegin() @@ -107,118 +111,104 @@ var _ = Describe("snapshot preparation", func() { mock.ExpectExec(query).WillReturnResult(sqlmock.NewResult(0, 0)) } } - restart := func() { - mock.ExpectRollback() - mock.ExpectExec("SET application_name").WillReturnResult(sqlmock.NewResult(0, 0)) - begin() - mock.ExpectQuery("SELECT pg_catalog.pg_export_snapshot").WillReturnRows(sqlmock.NewRows([]string{"snapshot"}).AddRow("new-snapshot")) - session() - } - tables := func(lockErr error, changed bool) { + tables := func() { mock.ExpectQuery("SELECT n.oid AS schemaoid").WillReturnRows(sqlmock.NewRows([]string{"schemaoid", "oid", "schema", "name"}).AddRow(1, 10, "public", "t")) - lock := mock.ExpectExec("LOCK TABLE public.t") - if lockErr != nil { - lock.WillReturnError(lockErr) - return - } - lock.WillReturnResult(sqlmock.NewResult(0, 0)) - node := 20 - if changed { - node = 21 + } + lock := func(err error) { + tables() + begin() + expectation := mock.ExpectExec("LOCK TABLE public.t") + if err != nil { + expectation.WillReturnError(err) + } else { + expectation.WillReturnResult(sqlmock.NewResult(0, 0)) } - mock.ExpectQuery("WITH RECURSIVE").WillReturnRows(sqlmock.NewRows(columns).AddRow("public.t", 10, 20, node, 10)) } - It("exports before any worker imports and applies session queries afterwards", func() { - // Two mock connections share expectations, so ordering verifies import precedes queries. + snapshot := func() { + mock.ExpectQuery("SELECT pg_catalog.pg_export_snapshot").WillReturnRows(sqlmock.NewRows([]string{"snapshot"}).AddRow("new-snapshot")) + tables() + } + twoConnections := func() { connectionPool.ConnPool[0].SetMaxOpenConns(2) connectionPool.ConnPool = append(connectionPool.ConnPool, connectionPool.ConnPool[0]) connectionPool.Tx = append(connectionPool.Tx, nil) connectionPool.NumConns = 2 + } + It("sets session GUCs before beginning any Cloudberry backup transaction", func() { + twoConnections() for i := 0; i < 2; i++ { mock.ExpectExec("SET application_name").WillReturnResult(sqlmock.NewResult(0, 0)) - begin() - if i == 0 { - mock.ExpectQuery("SELECT pg_catalog.pg_export_snapshot").WillReturnRows(sqlmock.NewRows([]string{"snapshot"}).AddRow("new-snapshot")) - } else { - mock.ExpectExec("SET TRANSACTION SNAPSHOT 'new-snapshot'").WillReturnResult(sqlmock.NewResult(0, 0)) - } session() } - Expect(initializeBackupTransactions("20261120000000")).To(Succeed()) + Expect(initializeBackupTransactions("20261124000000")).To(Succeed()) + Expect(connectionPool.Tx[0]).To(BeNil()) + Expect(connectionPool.Tx[1]).To(BeNil()) + Expect(backupSnapshot).To(BeEmpty()) + }) + It("locks before exporting and imports workers only after validating the final table set", func() { + twoConnections() + lock(nil) + snapshot() + check() + begin() + mock.ExpectExec("SET TRANSACTION SNAPSHOT 'new-snapshot'").WillReturnResult(sqlmock.NewResult(0, 0)) + Expect(PrepareBackupSnapshot(opts)).To(Succeed()) Expect(backupSnapshot).To(Equal("new-snapshot")) }) - DescribeTable("honors the attempt budget", func(limit int) { + DescribeTable("honors the attempt budget for unprotected tables", func(limit int) { Expect(cmdFlags.Set(options.SNAPSHOT_ATTEMPTS, fmt.Sprint(limit))).To(Succeed()) - begin() - connectionPool.MustBegin() - for i := 1; i <= limit; i++ { - tables(nil, true) - if i < limit { - restart() - } + for i := 0; i < limit; i++ { + lock(nil) + snapshot() + check("public.new_leaf") + mock.ExpectRollback() } - _, err := prepareSnapshotTables(opts) - Expect(err).To(MatchError(ContainSubstring(fmt.Sprintf("after %d attempt(s): public.t", limit)))) + err := PrepareBackupSnapshot(opts) + Expect(err).To(MatchError(ContainSubstring(fmt.Sprintf("after %d attempt(s): public.new_leaf", limit)))) + Expect(backupSnapshot).To(BeEmpty()) }, Entry("one", 1), Entry("three", 3)) - It("discards heap hashes and accepts the new snapshot", func() { - begin() - connectionPool.MustBegin() - heapFileHashes = map[uint32]string{10: "old"} - tables(nil, true) - restart() - tables(nil, false) - result, err := prepareSnapshotTables(opts) - Expect(err).NotTo(HaveOccurred()) - Expect(result).To(Equal([]Relation{{SchemaOid: 1, Oid: 10, Schema: "public", Name: "t"}})) - Expect(heapFileHashes).To(BeNil()) - Expect(backupSnapshot).To(Equal("new-snapshot")) - }) - It("does not retry unrelated SQL errors", func() { - tables(&pgconn.PgError{Code: "42501", Message: "permission denied"}, false) - _, err := prepareSnapshotTables(opts) - Expect(err).To(MatchError(ContainSubstring("permission denied"))) + It("keeps heap hashes until they can be verified against the final snapshot", func() { + heapFileHashes = map[uint32]string{10: "hash"} + lock(nil) + snapshot() + check("public.new_leaf") + mock.ExpectRollback() + lock(nil) + snapshot() + check() + Expect(PrepareBackupSnapshot(opts)).To(Succeed()) + Expect(heapFileHashes).To(Equal(map[uint32]string{10: "hash"})) }) DescribeTable("retries missing names", func(code string) { - begin() - connectionPool.MustBegin() - tables(&pgconn.PgError{Code: code, Message: "disappeared"}, false) - restart() - tables(nil, false) - _, err := prepareSnapshotTables(opts) - Expect(err).NotTo(HaveOccurred()) + lock(&pgconn.PgError{Code: code, Message: "disappeared"}) + mock.ExpectRollback() + lock(nil) + snapshot() + check() + Expect(PrepareBackupSnapshot(opts)).To(Succeed()) }, Entry("table", "42P01"), Entry("schema", "3F000")) - It("does not validate physical storage for metadata-only backups", func() { - Expect(cmdFlags.Set(options.METADATA_ONLY, "true")).To(Succeed()) - mock.ExpectQuery("SELECT n.oid AS schemaoid").WillReturnRows(sqlmock.NewRows([]string{"schemaoid", "oid", "schema", "name"}).AddRow(1, 10, "public", "t")) - mock.ExpectExec("LOCK TABLE public.t").WillReturnResult(sqlmock.NewResult(0, 0)) - result, err := prepareSnapshotTables(opts) - Expect(err).NotTo(HaveOccurred()) - Expect(result).To(HaveLen(1)) + It("does not retry unrelated SQL errors", func() { + lock(&pgconn.PgError{Code: "42501", Message: "permission denied"}) + Expect(PrepareBackupSnapshot(opts)).To(MatchError(ContainSubstring("permission denied"))) }) - - It("does not retry a storage validation query failure", func() { - mock.ExpectQuery("SELECT n.oid AS schemaoid").WillReturnRows(sqlmock.NewRows([]string{"schemaoid", "oid", "schema", "name"}).AddRow(1, 10, "public", "t")) - mock.ExpectExec("LOCK TABLE public.t").WillReturnResult(sqlmock.NewResult(0, 0)) + It("does not import workers after a snapshot export failure", func() { + twoConnections() + lock(nil) + mock.ExpectQuery("SELECT pg_catalog.pg_export_snapshot").WillReturnError(errors.New("export failed")) + Expect(PrepareBackupSnapshot(opts)).To(MatchError("export failed")) + Expect(connectionPool.Tx[1]).To(BeNil()) + }) + It("stops on a lock validation query failure", func() { + lock(nil) + snapshot() mock.ExpectQuery("WITH RECURSIVE").WillReturnError(errors.New("check failed")) - _, err := prepareSnapshotTables(opts) - Expect(err).To(MatchError(ContainSubstring("check failed"))) + Expect(PrepareBackupSnapshot(opts)).To(MatchError(ContainSubstring("check failed"))) }) - It("stops on rollback failure", func() { - begin() - connectionPool.MustBegin() - tables(nil, true) + lock(nil) + snapshot() + check("public.new_leaf") mock.ExpectRollback().WillReturnError(errors.New("rollback failure")) - _, err := prepareSnapshotTables(opts) - Expect(err).To(MatchError(ContainSubstring("rollback failure"))) - }) - It("stops on snapshot preparation failure", func() { - begin() - connectionPool.MustBegin() - tables(nil, true) - mock.ExpectRollback() - mock.ExpectExec("SET application_name").WillReturnError(errors.New("session failure")) - _, err := prepareSnapshotTables(opts) - Expect(err).To(MatchError("session failure")) + Expect(PrepareBackupSnapshot(opts)).To(MatchError(ContainSubstring("rollback failure"))) }) }) diff --git a/backup/wrappers.go b/backup/wrappers.go index 55631b5d..f51d4787 100644 --- a/backup/wrappers.go +++ b/backup/wrappers.go @@ -70,28 +70,28 @@ func initializeConnectionPool(timestamp string) { gplog.FatalOnError(initializeBackupTransactions(timestamp)) } -// On Cloudberry, import the snapshot before session queries establish a worker snapshot. -// application_name is set outside the transaction so rollback preserves cleanup's identity. +// Set application_name outside transactions so cleanup can find sessions after rollback. func initializeBackupTransactions(timestamp string) error { backupSnapshot = "" for connNum := 0; connNum < connectionPool.NumConns; connNum++ { if _, err := connectionPool.Exec(fmt.Sprintf("SET application_name TO 'gpbackup_%s'", timestamp), connNum); err != nil { return err } + if connectionPool.Version.IsCBDB() { + // SetSessionGUCs runs a SELECT that would establish the snapshot. + SetSessionGUCs(connNum) + continue + } if err := connectionPool.Begin(connNum); err != nil { return err } - if connectionPool.Version.IsCBDB() || (connectionPool.Version.IsGPDB() && connectionPool.Version.AtLeast(SNAPSHOT_GPDB_MIN_VERSION)) { + if connectionPool.Version.IsGPDB() && connectionPool.Version.AtLeast(SNAPSHOT_GPDB_MIN_VERSION) { if connNum == 0 { var err error backupSnapshot, err = GetSynchronizedSnapshot(connectionPool) if err != nil { return err } - } else if connectionPool.Version.IsCBDB() { - if err := SetSynchronizedSnapshot(connectionPool, connNum, backupSnapshot); err != nil { - return err - } } } SetSessionGUCs(connNum) @@ -218,9 +218,12 @@ func createBackupDirectoriesOnAllHosts() { * Metadata retrieval wrapper functions */ -func RetrieveAndProcessTables(opts *options.Options) ([]Table, []Table) { - tableRelations, err := prepareSnapshotTables(opts) - gplog.FatalOnError(err) +func RetrieveAndProcessTables() ([]Table, []Table) { + tableRelations := ConvertRelationsOptionsToBackup(GetIncludedUserTableRelations(connectionPool, IncludedRelationFqns)) + // PrepareBackupSnapshot already holds these locks on Cloudberry. + if !connectionPool.Version.IsCBDB() { + gplog.FatalOnError(LockTables(connectionPool, tableRelations)) + } if (connectionPool.Version.IsGPDB() && connectionPool.Version.AtLeast("6")) || connectionPool.Version.IsCBDB() { tableRelations = append(tableRelations, GetForeignTableRelations(connectionPool)...) diff --git a/end_to_end/snapshot_retry_test.go b/end_to_end/snapshot_retry_test.go index 7a7a9231..b3f168ff 100644 --- a/end_to_end/snapshot_retry_test.go +++ b/end_to_end/snapshot_retry_test.go @@ -23,14 +23,18 @@ import ( "fmt" "os" "os/exec" + "strings" "syscall" "time" "github.com/apache/cloudberry-backup/testutils" + "github.com/apache/cloudberry-backup/toc" + "github.com/apache/cloudberry-go-libs/cluster" "github.com/apache/cloudberry-go-libs/dbconn" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gexec" + "gopkg.in/yaml.v2" ) // Wait for this backup's lock request, never a fixed sleep or another client's lock. @@ -42,7 +46,7 @@ func waitForSnapshotBackupLock(relation string) { } func startSnapshotBackup(args ...string) *Session { - args = append([]string{"--dbname", "testdb", "--backup-dir", backupDir, "--verbose", "--no-history-sync-standby"}, args...) + args = append([]string{"--dbname", "testdb", "--backup-dir", backupDir, "--verbose", "--no-history-sync-standby", "--snapshot-attempts", "1"}, args...) session, err := Start(exec.Command(gpbackupPath, args...), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) DeferCleanup(func() { @@ -69,10 +73,10 @@ func waitForSnapshotBackupSessionsToClose() { }, 10*time.Second, 100*time.Millisecond).Should(BeZero()) } -var _ = Describe("snapshot lock retry", func() { +var _ = Describe("snapshot lock preparation", func() { BeforeEach(func() { if useOldBackupVersion || !backupConn.Version.IsCBDB() { - Skip("snapshot retries require Cloudberry and current gpbackup") + Skip("snapshot preparation requires Cloudberry and current gpbackup") } end_to_end_setup() backupConn.MustExec("CREATE SCHEMA snapshot_retry") @@ -116,7 +120,7 @@ var _ = Describe("snapshot lock retry", func() { } restore := func(session *Session) { Expect(session.ExitCode()).To(Equal(0)) - Expect(string(session.Out.Contents())).To(ContainSubstring("Starting snapshot attempt 2 of 3")) + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Starting snapshot attempt")) ts := getBackupTimestamp(string(session.Out.Contents())) gprestore(gprestorePath, restoreHelperPath, ts, "--backup-dir", backupDir, "--redirect-db", "restoredb") Expect(snapshotRetryRows(backupConn)).To(Equal([]int{4, 5, 6})) @@ -139,7 +143,7 @@ var _ = Describe("snapshot lock retry", func() { }) } } - It("retries with single data file and a table filter file", func() { + It("restores with single data file and a table filter file", func() { createTable("heap", true) file, err := os.CreateTemp("", "snapshot-include") Expect(err).NotTo(HaveOccurred()) @@ -150,14 +154,7 @@ var _ = Describe("snapshot lock retry", func() { restoreConn.MustExec("CREATE SCHEMA snapshot_retry") restore(truncateDuringBackup(true, "--include-table-file", file.Name(), "--single-data-file", "--leaf-partition-data")) }) - It("fails the entire backup when only one attempt is allowed", func() { - createTable("heap", false) - session := truncateDuringBackup(false, "--include-schema", "snapshot_retry", "--snapshot-attempts", "1") - Expect(session.ExitCode()).NotTo(Equal(0)) - Expect(string(session.Out.Contents())).To(ContainSubstring("after 1 attempt(s): snapshot_retry.t")) - Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Backup completed successfully")) - }) - It("fails after two consecutive storage conflicts", func() { + It("does not deadlock when another exclusive lock queues behind the backup", func() { createTable("heap", false) first := testutils.SetupTestDbConn("testdb") defer first.Close() @@ -168,7 +165,7 @@ var _ = Describe("snapshot lock retry", func() { } }() first.MustExec("TRUNCATE snapshot_retry.t; INSERT INTO snapshot_retry.t VALUES(4),(5),(6)") - session := startSnapshotBackup("--include-schema", "snapshot_retry", "--snapshot-attempts", "2") + session := startSnapshotBackup("--include-schema", "snapshot_retry", "--jobs", "2") waitForSnapshotBackupLock("snapshot_retry.t") second := testutils.SetupTestDbConn("testdb") defer second.Close() @@ -199,40 +196,102 @@ var _ = Describe("snapshot lock retry", func() { return count, err }, 30*time.Second, 100*time.Millisecond).Should(BeNumerically(">", 0)) first.MustCommit() + Eventually(session, 90*time.Second).Should(Exit(0)) Eventually(ready, 30*time.Second).Should(Receive(BeNil())) - waitForSnapshotBackupLock("snapshot_retry.t") second.MustCommit() - Eventually(session, 90*time.Second).Should(Exit()) - Expect(session.ExitCode()).NotTo(Equal(0)) - Expect(string(session.Out.Contents())).To(ContainSubstring("after 2 attempt(s): snapshot_retry.t")) - Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Backup completed successfully")) + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Starting snapshot attempt")) + ts := getBackupTimestamp(string(session.Out.Contents())) + gprestore(gprestorePath, restoreHelperPath, ts, "--backup-dir", backupDir, "--redirect-db", "restoredb") + Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{4, 5, 6})) + Expect(snapshotRetryRows(backupConn)).To(Equal([]int{7, 8, 9})) waitForSnapshotBackupSessionsToClose() }) - It("restores full then incremental after a retry with heap file hashes", func() { + It("restores an incremental after TRUNCATE and retains hashes for unchanged heap tables", func() { createTable("heap", false) + backupConn.MustExec("CREATE TABLE snapshot_retry.unchanged(id int) DISTRIBUTED BY(id); INSERT INTO snapshot_retry.unchanged VALUES(42)") + var count int + Expect(backupConn.Get(&count, "SELECT count(*) FROM snapshot_retry.unchanged")).To(Succeed()) full := gpbackup(gpbackupPath, backupHelperPath, "--backup-dir", backupDir, "--include-schema", "snapshot_retry", "--leaf-partition-data", "--heap-file-hash") fullTS := getBackupTimestamp(string(full)) session := truncateDuringBackup(false, "--include-schema", "snapshot_retry", "--leaf-partition-data", "--heap-file-hash", "--incremental", "--from-timestamp", fullTS) Expect(session.ExitCode()).To(Equal(0)) - Expect(string(session.Out.Contents())).To(ContainSubstring("Snapshot retry disables heap file hashes")) + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Starting snapshot attempt")) + var currentTOC toc.TOC ts := getBackupTimestamp(string(session.Out.Contents())) + Expect(yaml.Unmarshal(getMetdataFileContents(backupDir, ts, "toc.yaml"), ¤tTOC)).To(Succeed()) + Expect(currentTOC.IncrementalMetadata.Heap["snapshot_retry.unchanged"].FileHashMD5).NotTo(BeEmpty()) gprestore(gprestorePath, restoreHelperPath, ts, "--backup-dir", backupDir, "--redirect-db", "restoredb") Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{4, 5, 6})) + next := gpbackup(gpbackupPath, backupHelperPath, "--backup-dir", backupDir, "--include-schema", "snapshot_retry", "--leaf-partition-data", "--heap-file-hash", "--incremental", "--from-timestamp", ts) + nextTS := getBackupTimestamp(string(next)) + var nextTOC toc.TOC + Expect(yaml.Unmarshal(getMetdataFileContents(backupDir, nextTS, "toc.yaml"), &nextTOC)).To(Succeed()) + Expect(nextTOC.IncrementalMetadata.Heap["snapshot_retry.unchanged"].FileHashMD5).NotTo(BeEmpty()) + for _, entry := range nextTOC.DataEntries { + Expect(entry.Schema + "." + entry.Name).NotTo(Equal("snapshot_retry.unchanged")) + } }) - It("cancels blocked locks and leaves no backup sessions after interruption", func() { + DescribeTable("accepts a safe heap rewrite before the snapshot without retrying", func(command string) { + createTable("heap", false) + backupConn.MustExec("CREATE TABLE snapshot_retry.rewrite(id int) DISTRIBUTED BY(id); INSERT INTO snapshot_retry.rewrite VALUES(41),(42); CREATE INDEX snapshot_rewrite_idx ON snapshot_retry.rewrite(id)") + if command == "ALTER TABLE snapshot_retry.rewrite SET TABLESPACE snapshot_rewrite_ts" { + output := backupCluster.GenerateAndExecuteCommand("Creating snapshot test tablespace directories", cluster.ON_HOSTS|cluster.INCLUDE_COORDINATOR, func(host string) string { return "mkdir -p /tmp/snapshot_rewrite_ts" }) + Expect(output.NumErrors).To(BeZero()) + backupConn.MustExec("CREATE TABLESPACE snapshot_rewrite_ts LOCATION '/tmp/snapshot_rewrite_ts'") + DeferCleanup(func() { + backupConn.MustExec("DROP TABLESPACE snapshot_rewrite_ts") + output := backupCluster.GenerateAndExecuteCommand("Removing snapshot test tablespace directories", cluster.ON_HOSTS|cluster.INCLUDE_COORDINATOR, func(host string) string { return "rmdir /tmp/snapshot_rewrite_ts" }) + Expect(output.NumErrors).To(BeZero()) + }) + } + var before, after uint32 + Expect(backupConn.Get(&before, "SELECT relfilenode FROM pg_class WHERE oid='snapshot_retry.rewrite'::regclass")).To(Succeed()) + gate := testutils.SetupTestDbConn("testdb") + defer gate.Close() + gate.MustBegin() + defer func() { + if gate.Tx[0] != nil { + gate.MustRollback() + } + }() + gate.MustExec("LOCK TABLE snapshot_retry.t IN ACCESS EXCLUSIVE MODE") + session := startSnapshotBackup("--include-schema", "snapshot_retry") + waitForSnapshotBackupLock("snapshot_retry.t") + backupConn.MustExec(command) + Expect(backupConn.Get(&after, "SELECT relfilenode FROM pg_class WHERE oid='snapshot_retry.rewrite'::regclass")).To(Succeed()) + Expect(after).NotTo(Equal(before)) + gate.MustCommit() + Eventually(session, 90*time.Second).Should(Exit(0)) + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Starting snapshot attempt")) + ts := getBackupTimestamp(string(session.Out.Contents())) + gprestore(gprestorePath, restoreHelperPath, ts, "--backup-dir", backupDir, "--redirect-db", "restoredb") + var rows []int + Expect(restoreConn.Select(&rows, "SELECT id FROM snapshot_retry.rewrite ORDER BY id")).To(Succeed()) + Expect(rows).To(Equal([]int{41, 42})) + }, Entry("VACUUM FULL", "VACUUM FULL snapshot_retry.rewrite"), + Entry("CLUSTER", "CLUSTER snapshot_retry.rewrite USING snapshot_rewrite_idx"), + Entry("SET TABLESPACE", "ALTER TABLE snapshot_retry.rewrite SET TABLESPACE snapshot_rewrite_ts")) + + DescribeTable("cancels blocked locks and completes cleanup after interruption", func(args []string) { createTable("heap", false) writer := testutils.SetupTestDbConn("testdb") defer writer.Close() writer.MustBegin() defer writer.MustRollback() writer.MustExec("TRUNCATE snapshot_retry.t") - session := startSnapshotBackup("--include-schema", "snapshot_retry") + session := startSnapshotBackup(append([]string{"--include-schema", "snapshot_retry"}, args...)...) waitForSnapshotBackupLock("snapshot_retry.t") + var application string + Expect(backupConn.Get(&application, "SELECT application_name FROM pg_stat_activity WHERE datname=current_database() AND application_name LIKE 'gpbackup_%' AND query LIKE 'LOCK TABLE%'")).To(Succeed()) session.Signal(syscall.SIGINT) Eventually(session, 30*time.Second).Should(Exit()) Expect(session.ExitCode()).NotTo(Equal(0)) Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Backup completed successfully")) + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Encountered error during cleanup")) + Expect(string(session.Out.Contents())).To(ContainSubstring("Cleanup complete")) + _, err := os.Stat("/tmp/" + strings.TrimPrefix(application, "gpbackup_") + ".lck") + Expect(os.IsNotExist(err)).To(BeTrue()) waitForSnapshotBackupSessionsToClose() - }) + }, Entry("with history", []string{}), Entry("with single data file", []string{"--single-data-file"}), Entry("without history", []string{"--no-history"})) }) diff --git a/integration/snapshot_test.go b/integration/snapshot_test.go index 56231f61..f9210cde 100644 --- a/integration/snapshot_test.go +++ b/integration/snapshot_test.go @@ -2,12 +2,13 @@ package integration import ( "fmt" + "time" "github.com/apache/cloudberry-backup/backup" "github.com/apache/cloudberry-backup/options" "github.com/apache/cloudberry-backup/testutils" "github.com/apache/cloudberry-go-libs/dbconn" - "github.com/spf13/cobra" + "github.com/spf13/pflag" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -223,240 +224,168 @@ var _ = Describe("synchronized snapshot integration tests", func() { }) }) -var _ = Describe("snapshot storage validation", func() { +var _ = Describe("lock before snapshot integration", func() { + var reader *dbconn.DBConn + var opts *options.Options + var readerPID int BeforeEach(func() { if !connectionPool.Version.IsCBDB() { - Skip("snapshot storage validation is supported only on Cloudberry") + Skip("lock-before-snapshot preparation requires Cloudberry") } - connectionPool.MustExec("CREATE TABLE public.snapshot_storage (id int) DISTRIBUTED BY (id); INSERT INTO public.snapshot_storage VALUES (1),(2),(3)") - }) - AfterEach(func() { connectionPool.MustExec("DROP TABLE public.snapshot_storage") }) - It("detects a committed rewrite and accepts a fresh shared snapshot", func() { - reader := testutils.SetupTestDbConn("testdb") - reader.MustExec("SET search_path TO pg_catalog") - defer reader.Close() - worker := testutils.SetupTestDbConn("testdb") - defer worker.Close() - reader.MustBegin() - _, err := backup.GetSynchronizedSnapshot(reader) - Expect(err).NotTo(HaveOccurred()) - var oid uint32 - Expect(reader.Get(&oid, "SELECT 'public.snapshot_storage'::regclass::oid")).To(Succeed()) - tables := []backup.Relation{{Oid: oid, Schema: "public", Name: "snapshot_storage"}} - var before, after []string - query := "SELECT gp_segment_id::text || ':' || relfilenode::text FROM gp_dist_random('pg_class') WHERE oid='public.snapshot_storage'::regclass ORDER BY gp_segment_id" - Expect(connectionPool.Select(&before, query)).To(Succeed()) - connectionPool.MustExec("TRUNCATE public.snapshot_storage; INSERT INTO public.snapshot_storage VALUES (4),(5),(6)") - Expect(connectionPool.Select(&after, query)).To(Succeed()) - Expect(after).NotTo(Equal(before)) - Expect(backup.LockTables(reader, tables)).To(Succeed()) - conflicts, err := backup.CheckSnapshotTables(reader, tables) - Expect(err).NotTo(HaveOccurred()) - Expect(conflicts).To(ConsistOf(ContainSubstring("storage changed"))) - reader.MustRollback() - reader.MustBegin() - snapshot, err := backup.GetSynchronizedSnapshot(reader) - Expect(err).NotTo(HaveOccurred()) - Expect(backup.SetSynchronizedSnapshot(worker, 0, snapshot)).To(Succeed()) - Expect(backup.LockTables(reader, tables)).To(Succeed()) - conflicts, err = backup.CheckSnapshotTables(reader, tables) - Expect(err).NotTo(HaveOccurred()) - Expect(conflicts).To(BeEmpty()) - for _, conn := range []*dbconn.DBConn{reader, worker} { - var rows []int - Expect(conn.Select(&rows, "SELECT id FROM public.snapshot_storage ORDER BY id")).To(Succeed()) - Expect(rows).To(Equal([]int{4, 5, 6})) - conn.MustRollback() + connectionPool.MustExec("CREATE SCHEMA snapshot_prepare; CREATE TABLE snapshot_prepare.t(id int) DISTRIBUTED BY(id); INSERT INTO snapshot_prepare.t VALUES(1),(2),(3)") + reader = dbconn.NewDBConnFromEnvironment("testdb") + reader.MustConnect(2) + backup.SetConnection(reader) + backup.InitializeMetadataParams(reader) + for i := 0; i < 2; i++ { + reader.MustExec("SET application_name TO 'snapshot_prepare_test'", i) + backup.SetSessionGUCs(i) } - }) - It("does not reject ordinary concurrent DML", func() { - reader := testutils.SetupTestDbConn("testdb") - reader.MustExec("SET search_path TO pg_catalog") - defer reader.Close() - reader.MustBegin() - defer reader.MustRollback() - _, err := backup.GetSynchronizedSnapshot(reader) + Expect(reader.Get(&readerPID, "SELECT pg_backend_pid()")).To(Succeed()) + Expect(backupCmdFlags.Set(options.INCLUDE_SCHEMA, "snapshot_prepare")).To(Succeed()) + var err error + opts, err = options.NewOptions(backupCmdFlags) Expect(err).NotTo(HaveOccurred()) - var oid uint32 - Expect(reader.Get(&oid, "SELECT 'public.snapshot_storage'::regclass::oid")).To(Succeed()) - connectionPool.MustExec("INSERT INTO public.snapshot_storage VALUES (4); UPDATE public.snapshot_storage SET id=8 WHERE id=2; DELETE FROM public.snapshot_storage WHERE id=3") - tables := []backup.Relation{{Oid: oid, Schema: "public", Name: "snapshot_storage"}} - Expect(backup.LockTables(reader, tables)).To(Succeed()) - conflicts, err := backup.CheckSnapshotTables(reader, tables) - Expect(err).NotTo(HaveOccurred()) - Expect(conflicts).To(BeEmpty()) - var rows []int - Expect(reader.Select(&rows, "SELECT id FROM public.snapshot_storage ORDER BY id")).To(Succeed()) - Expect(rows).To(Equal([]int{1, 2, 3})) - }) - It("detects a renamed table replaced under its old name", func() { - defer connectionPool.MustExec("DROP TABLE IF EXISTS public.snapshot_old") - reader := testutils.SetupTestDbConn("testdb") - reader.MustExec("SET search_path TO pg_catalog") - defer reader.Close() - reader.MustBegin() - defer reader.MustRollback() - _, err := backup.GetSynchronizedSnapshot(reader) - Expect(err).NotTo(HaveOccurred()) - var oid uint32 - Expect(reader.Get(&oid, "SELECT oid FROM pg_class WHERE relname='snapshot_storage'")).To(Succeed()) - connectionPool.MustExec("ALTER TABLE public.snapshot_storage RENAME TO snapshot_old; CREATE TABLE public.snapshot_storage (id int) DISTRIBUTED BY (id)") - tables := []backup.Relation{{Oid: oid, Schema: "public", Name: "snapshot_storage"}} - Expect(backup.LockTables(reader, tables)).To(Succeed()) - conflicts, err := backup.CheckSnapshotTables(reader, tables) - Expect(err).NotTo(HaveOccurred()) - Expect(conflicts).To(ConsistOf(ContainSubstring("snapshot OID"))) - }) - It("checks a nested leaf when only the root is supplied", func() { - connectionPool.MustExec(`CREATE TABLE public.snapshot_root (id int) PARTITION BY RANGE(id) DISTRIBUTED BY(id); - CREATE TABLE public.snapshot_middle PARTITION OF public.snapshot_root FOR VALUES FROM (0) TO (10) PARTITION BY RANGE(id); - CREATE TABLE public.snapshot_leaf PARTITION OF public.snapshot_middle FOR VALUES FROM (0) TO (10); - INSERT INTO public.snapshot_root VALUES(1),(2),(3)`) - defer connectionPool.MustExec("DROP TABLE public.snapshot_root") - reader := testutils.SetupTestDbConn("testdb") - reader.MustExec("SET search_path TO pg_catalog") - defer reader.Close() - reader.MustBegin() - defer reader.MustRollback() - _, err := backup.GetSynchronizedSnapshot(reader) - Expect(err).NotTo(HaveOccurred()) - var oid uint32 - Expect(reader.Get(&oid, "SELECT oid FROM pg_class WHERE relname='snapshot_root'")).To(Succeed()) - connectionPool.MustExec("TRUNCATE public.snapshot_leaf; INSERT INTO public.snapshot_leaf VALUES(4),(5),(6)") - tables := []backup.Relation{{Oid: oid, Schema: "public", Name: "snapshot_root"}} - Expect(backup.LockTables(reader, tables)).To(Succeed()) - conflicts, err := backup.CheckSnapshotTables(reader, tables) - Expect(err).NotTo(HaveOccurred()) - Expect(conflicts).To(ConsistOf(ContainSubstring("public.snapshot_leaf"))) }) -}) - -var _ = Describe("snapshot retry filter resolution", func() { - BeforeEach(func() { - if !connectionPool.Version.IsCBDB() { - Skip("snapshot retries are supported only on Cloudberry") + AfterEach(func() { + if reader != nil { + for i := 0; i < reader.NumConns; i++ { + if reader.Tx[i] != nil { + reader.MustRollback(i) + } + } + reader.Close() + reader = nil } + backup.SetConnection(connectionPool) + backup.InitializeMetadataParams(connectionPool) + backup.SetBackupSnapshot("") + backup.SetFilterRelationClause("") + connectionPool.MustExec("DROP SCHEMA IF EXISTS snapshot_prepare CASCADE") }) - It("resolves a replacement OID and restores session settings and worker snapshots", func() { - connectionPool.MustExec("CREATE TABLE public.retry_filter(id int) DISTRIBUTED BY(id); INSERT INTO public.retry_filter VALUES(1)") - defer connectionPool.MustExec("DROP TABLE public.retry_filter; DROP TABLE public.retry_filter_old") - reader := dbconn.NewDBConnFromEnvironment("testdb") - reader.MustConnect(2) - defer reader.Close() + prepare := func() <-chan error { + ready := make(chan error, 1) + go func() { + defer GinkgoRecover() + ready <- backup.PrepareBackupSnapshot(opts) + }() + return ready + } + waitForLock := func(table string) { + Eventually(func() (int, error) { + var count int + err := connectionPool.Get(&count, fmt.Sprintf("SELECT count(*) FROM pg_locks WHERE pid=%d AND relation='%s'::regclass AND NOT granted", readerPID, table)) + return count, err + }, 30*time.Second, 50*time.Millisecond).Should(BeNumerically(">", 0)) + } + It("includes a TRUNCATE and related DML committed while locks wait, on every worker", func() { + connectionPool.MustExec("CREATE TABLE snapshot_prepare.marker(id int) DISTRIBUTED BY(id); INSERT INTO snapshot_prepare.marker VALUES(1)") + writer := testutils.SetupTestDbConn("testdb") + defer writer.Close() + writer.MustBegin() defer func() { - backup.SetConnection(connectionPool) - backup.InitializeMetadataParams(connectionPool) - backup.SetBackupSnapshot("") + if writer.Tx[0] != nil { + writer.MustRollback() + } }() - cmd := &cobra.Command{} - backup.DoInit(cmd) - backup.SetConnection(reader) - backup.InitializeMetadataParams(reader) - Expect(cmd.Flags().Set(options.INCLUDE_RELATION, "public.retry_filter")).To(Succeed()) - opts, err := options.NewOptions(cmd.Flags()) - Expect(err).NotTo(HaveOccurred()) - reader.MustBegin(0) - reader.MustBegin(1) - snapshot, err := backup.GetSynchronizedSnapshot(reader) - Expect(err).NotTo(HaveOccurred()) - backup.SetBackupSnapshot(snapshot) - Expect(backup.SetSynchronizedSnapshot(reader, 1, snapshot)).To(Succeed()) - backup.ValidateAndProcessFilterLists(opts) - oldOid := backup.IncludedRelationFqns[0].Oid - connectionPool.MustExec("ALTER TABLE public.retry_filter RENAME TO retry_filter_old; CREATE TABLE public.retry_filter(id int) DISTRIBUTED BY(id); INSERT INTO public.retry_filter VALUES(4),(5),(6)") - _, data := backup.RetrieveAndProcessTables(opts) - Expect(data).To(HaveLen(1)) - Expect(data[0].Oid).NotTo(Equal(oldOid)) - Expect(backup.IncludedRelationFqns[0].Oid).To(Equal(data[0].Oid)) - connectionPool.MustExec("INSERT INTO public.retry_filter VALUES(7)") + writer.MustExec("TRUNCATE snapshot_prepare.t; INSERT INTO snapshot_prepare.t VALUES(4),(5),(6); UPDATE snapshot_prepare.marker SET id=2") + Expect(backupCmdFlags.Set(options.SNAPSHOT_ATTEMPTS, "1")).To(Succeed()) + ready := prepare() + waitForLock("snapshot_prepare.t") + writer.MustCommit() + Eventually(ready, 30*time.Second).Should(Receive(BeNil())) + connectionPool.MustExec("INSERT INTO snapshot_prepare.t VALUES(7); UPDATE snapshot_prepare.marker SET id=3") for i := 0; i < 2; i++ { var rows []int - Expect(reader.Select(&rows, "SELECT id FROM public.retry_filter ORDER BY id", i)).To(Succeed()) + Expect(reader.Select(&rows, "SELECT id FROM snapshot_prepare.t ORDER BY id", i)).To(Succeed()) Expect(rows).To(Equal([]int{4, 5, 6})) - var searchPath, appName, timeout string - Expect(reader.Get(&searchPath, "SHOW search_path", i)).To(Succeed()) - Expect(searchPath).To(Equal("pg_catalog")) - Expect(reader.Get(&timeout, "SHOW statement_timeout", i)).To(Succeed()) - Expect(timeout).To(Equal("0")) - Expect(reader.Get(&appName, "SHOW application_name", i)).To(Succeed()) - Expect(appName).To(HavePrefix("gpbackup_")) - reader.MustRollback(i) + var marker int + Expect(reader.Get(&marker, "SELECT id FROM snapshot_prepare.marker", i)).To(Succeed()) + Expect(marker).To(Equal(2)) } }) - It("rejects an explicitly included table that disappeared before retry", func() { - connectionPool.MustExec("CREATE TABLE public.retry_missing(id int) DISTRIBUTED BY(id)") - defer connectionPool.MustExec("DROP TABLE public.retry_missing_old") - reader := dbconn.NewDBConnFromEnvironment("testdb") - reader.MustConnect(2) - defer reader.Close() + DescribeTable("retries only when the final snapshot contains an unprotected table", func(limit int) { + Expect(backupCmdFlags.Set(options.SNAPSHOT_ATTEMPTS, fmt.Sprint(limit))).To(Succeed()) + gate := testutils.SetupTestDbConn("testdb") + defer gate.Close() + gate.MustBegin() defer func() { - backup.SetConnection(connectionPool) - backup.InitializeMetadataParams(connectionPool) - backup.SetBackupSnapshot("") + if gate.Tx[0] != nil { + gate.MustRollback() + } }() - cmd := &cobra.Command{} - backup.DoInit(cmd) - backup.SetConnection(reader) - backup.InitializeMetadataParams(reader) - Expect(cmd.Flags().Set(options.INCLUDE_RELATION, "public.retry_missing")).To(Succeed()) - opts, err := options.NewOptions(cmd.Flags()) - Expect(err).NotTo(HaveOccurred()) - reader.MustBegin(0) - reader.MustBegin(1) - defer func() { + gate.MustExec("LOCK TABLE snapshot_prepare.t IN ACCESS EXCLUSIVE MODE") + ready := prepare() + waitForLock("snapshot_prepare.t") + connectionPool.MustExec("CREATE TABLE snapshot_prepare.new_table(id int) DISTRIBUTED BY(id); INSERT INTO snapshot_prepare.new_table VALUES(9)") + gate.MustCommit() + if limit == 1 { + var err error + Eventually(ready, 30*time.Second).Should(Receive(&err)) + Expect(err).To(MatchError(ContainSubstring("snapshot_prepare.new_table"))) + Expect(reader.Tx[0]).To(BeNil()) + Expect(reader.Tx[1]).To(BeNil()) + } else { + Eventually(ready, 30*time.Second).Should(Receive(BeNil())) for i := 0; i < 2; i++ { - if reader.Tx[i] != nil { - reader.MustRollback(i) - } + var value int + Expect(reader.Get(&value, "SELECT id FROM snapshot_prepare.new_table", i)).To(Succeed()) + Expect(value).To(Equal(9)) } - }() - snapshot, err := backup.GetSynchronizedSnapshot(reader) + } + }, Entry("fails without retries", 1), Entry("locks the new table in a fresh transaction", 3)) + It("rebuilds explicit filters and partition expansion after a leaf is replaced", func() { + connectionPool.MustExec(`CREATE TABLE snapshot_prepare.root(id int) DISTRIBUTED BY(id) PARTITION BY RANGE(id); + CREATE TABLE snapshot_prepare.old_leaf PARTITION OF snapshot_prepare.root FOR VALUES FROM(0) TO(10)`) + Expect(backupCmdFlags.Lookup(options.INCLUDE_SCHEMA).Value.(pflag.SliceValue).Replace(nil)).To(Succeed()) + Expect(backupCmdFlags.Set(options.INCLUDE_RELATION, "snapshot_prepare.t")).To(Succeed()) + Expect(backupCmdFlags.Set(options.INCLUDE_RELATION, "snapshot_prepare.root")).To(Succeed()) + Expect(backupCmdFlags.Set(options.LEAF_PARTITION_DATA, "true")).To(Succeed()) + var err error + opts, err = options.NewOptions(backupCmdFlags) Expect(err).NotTo(HaveOccurred()) - backup.SetBackupSnapshot(snapshot) - Expect(backup.SetSynchronizedSnapshot(reader, 1, snapshot)).To(Succeed()) - backup.ValidateAndProcessFilterLists(opts) - connectionPool.MustExec("ALTER TABLE public.retry_missing RENAME TO retry_missing_old") - Expect(func() { backup.RetrieveAndProcessTables(opts) }).To(PanicWith(MatchRegexp("Table public.retry_missing does not exist"))) - }) - - It("discards expanded old partitions and discovers new ones after retry", func() { - connectionPool.MustExec(`CREATE TABLE public.retry_root(id int) DISTRIBUTED BY(id) PARTITION BY RANGE(id); - CREATE TABLE public.retry_old_leaf PARTITION OF public.retry_root FOR VALUES FROM(0) TO(10)`) - defer connectionPool.MustExec("DROP TABLE public.retry_root") - reader := dbconn.NewDBConnFromEnvironment("testdb") - reader.MustConnect(2) - defer reader.Close() + gate := testutils.SetupTestDbConn("testdb") + defer gate.Close() + gate.MustBegin() defer func() { - backup.SetConnection(connectionPool) - backup.InitializeMetadataParams(connectionPool) - backup.SetBackupSnapshot("") + if gate.Tx[0] != nil { + gate.MustRollback() + } }() - cmd := &cobra.Command{} - backup.DoInit(cmd) - backup.SetConnection(reader) - backup.InitializeMetadataParams(reader) - Expect(cmd.Flags().Set(options.INCLUDE_RELATION, "public.retry_root")).To(Succeed()) - Expect(cmd.Flags().Set(options.LEAF_PARTITION_DATA, "true")).To(Succeed()) - opts, err := options.NewOptions(cmd.Flags()) - Expect(err).NotTo(HaveOccurred()) - reader.MustBegin(0) - reader.MustBegin(1) - snapshot, err := backup.GetSynchronizedSnapshot(reader) - Expect(err).NotTo(HaveOccurred()) - backup.SetBackupSnapshot(snapshot) - Expect(backup.SetSynchronizedSnapshot(reader, 1, snapshot)).To(Succeed()) - backup.ValidateAndProcessFilterLists(opts) - Expect(backup.ExpandIncludesForPartitions(reader, opts, backup.GetOidsFromRelationList(backup.IncludedRelationFqns), cmd.Flags())).To(Succeed()) - Expect(opts.GetIncludedTables()).To(ContainElement("public.retry_old_leaf")) - connectionPool.MustExec(`ALTER TABLE public.retry_root DETACH PARTITION public.retry_old_leaf; DROP TABLE public.retry_old_leaf; - CREATE TABLE public.retry_new_leaf PARTITION OF public.retry_root FOR VALUES FROM(0) TO(10); INSERT INTO public.retry_root VALUES(4),(5),(6)`) - _, data := backup.RetrieveAndProcessTables(opts) - Expect(data).To(HaveLen(1)) - Expect(data[0].Name).To(Equal("retry_new_leaf")) - Expect(opts.GetIncludedTables()).NotTo(ContainElement("public.retry_old_leaf")) - Expect(opts.GetIncludedTables()).To(ContainElement("public.retry_new_leaf")) + gate.MustExec("LOCK TABLE snapshot_prepare.t IN ACCESS EXCLUSIVE MODE") + ready := prepare() + waitForLock("snapshot_prepare.t") + connectionPool.MustExec(`ALTER TABLE snapshot_prepare.root DETACH PARTITION snapshot_prepare.old_leaf; + DROP TABLE snapshot_prepare.old_leaf; + CREATE TABLE snapshot_prepare.new_leaf PARTITION OF snapshot_prepare.root FOR VALUES FROM(0) TO(10); + INSERT INTO snapshot_prepare.root VALUES(4),(5),(6)`) + gate.MustCommit() + Eventually(ready, 30*time.Second).Should(Receive(BeNil())) + Expect(opts.GetIncludedTables()).To(ContainElement("snapshot_prepare.new_leaf")) + Expect(opts.GetIncludedTables()).NotTo(ContainElement("snapshot_prepare.old_leaf")) for i := 0; i < 2; i++ { - reader.MustRollback(i) + var rows []int + Expect(reader.Select(&rows, "SELECT id FROM snapshot_prepare.root ORDER BY id", i)).To(Succeed()) + Expect(rows).To(Equal([]int{4, 5, 6})) } }) + It("checks nested descendants even when only a root is supplied", func() { + connectionPool.MustExec(`CREATE TABLE snapshot_prepare.root(id int) DISTRIBUTED BY(id) PARTITION BY RANGE(id); + CREATE TABLE snapshot_prepare.middle PARTITION OF snapshot_prepare.root FOR VALUES FROM(0) TO(10) PARTITION BY RANGE(id); + CREATE TABLE snapshot_prepare.leaf PARTITION OF snapshot_prepare.middle FOR VALUES FROM(0) TO(10)`) + var oid uint32 + Expect(reader.Get(&oid, "SELECT 'snapshot_prepare.root'::regclass::oid")).To(Succeed()) + reader.MustBegin() + reader.MustExec("LOCK TABLE ONLY snapshot_prepare.root IN ACCESS SHARE MODE") + tables := []backup.Relation{{Oid: oid, Schema: "snapshot_prepare", Name: "root"}} + conflicts, err := backup.CheckSnapshotTableLocks(reader, tables) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(ConsistOf("snapshot_prepare.middle", "snapshot_prepare.leaf")) + reader.MustRollback() + reader.MustBegin() + Expect(backup.LockTables(reader, tables)).To(Succeed()) + conflicts, err = backup.CheckSnapshotTableLocks(reader, tables) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(BeEmpty()) + }) }) diff --git a/integration/wrappers_test.go b/integration/wrappers_test.go index e39a2983..cb64c3f2 100644 --- a/integration/wrappers_test.go +++ b/integration/wrappers_test.go @@ -35,7 +35,7 @@ var _ = Describe("Wrappers Integration", func() { connectionPool.MustBegin(0) defer connectionPool.MustCommit(0) - _, dataTables := backup.RetrieveAndProcessTables(subject) + _, dataTables := backup.RetrieveAndProcessTables() Expect(len(dataTables)).To(Equal(2)) Expect(dataTables[0].Name).To(Equal("foo")) Expect(dataTables[1].Name).To(Equal(`"BAR"`)) diff --git a/options/flag.go b/options/flag.go index 76bcba06..a0ba8204 100644 --- a/options/flag.go +++ b/options/flag.go @@ -96,7 +96,7 @@ func SetBackupFlagDefaults(flagSet *pflag.FlagSet) { flagSet.Bool(WITH_STATS, false, "Back up query plan statistics") flagSet.Bool(WITHOUT_GLOBALS, false, "Skip backup of global metadata") flagSet.Bool(NO_INHERITS, false, "For a filtered backup, don't back up all tables that inherit included tables") - flagSet.Int(SNAPSHOT_ATTEMPTS, 3, "Maximum Cloudberry snapshot preparation attempts, including the first; 1 disables retries. Fail the backup if table storage or identity still conflicts after the last attempt") + flagSet.Int(SNAPSHOT_ATTEMPTS, 3, "Maximum Cloudberry snapshot preparation attempts when concurrent DDL changes the table set, including the first; 1 disables retries") flagSet.Bool(HEAP_FILE_HASH, false, "Skip unchanged heap tables in incremental backups by hashing their data files. Issues a cluster-wide CHECKPOINT before the backup starts") } From 6025d59589c31f2054a11da4ef1babbb336181a9 Mon Sep 17 00:00:00 2001 From: woblerr Date: Fri, 27 Nov 2026 16:24:59 +0300 Subject: [PATCH 3/7] Lock partition parents before taking the backup snapshot. ATTACH PARTITION can add a leaf after the backup snapshot because its parent lock is compatible with ACCESS SHARE. COPY through the root can then include rows whose partition is missing on restore. --- backup/queries_relations.go | 22 +++++----- backup/snapshot.go | 69 ++++++++++++++++++++++++++++- backup/snapshot_internal_test.go | 40 +++++++++++++++++ end_to_end/snapshot_retry_test.go | 72 ++++++++++++++++++++++++++++++- 4 files changed, 190 insertions(+), 13 deletions(-) diff --git a/backup/queries_relations.go b/backup/queries_relations.go index a658e7f1..b7cfeaa8 100644 --- a/backup/queries_relations.go +++ b/backup/queries_relations.go @@ -574,18 +574,9 @@ func LockTables(connectionPool *dbconn.DBConn, tables []Relation) error { } else { lockMode = `IN ACCESS SHARE MODE` } - // The LOCK TABLE query could block if someone else is holding an - // AccessExclusiveLock on the table. In the case gpbackup is interrupted, - // cancelBlockedQueries() will cancel these queries during cleanup. for i, currentBatch := range tableBatches { - _, err := connectionPool.Exec(fmt.Sprintf("LOCK TABLE %s %s", currentBatch, lockMode)) - if err != nil { - if wasTerminated { - gplog.Warn("Interrupt received while acquiring ACCESS SHARE locks on tables") - select {} // wait for cleanup thread to exit gpbackup - } else { - return fmt.Errorf("locking tables %s: %w", currentBatch, err) - } + if err := lockBackupTables(connectionPool, currentBatch, lockMode); err != nil { + return fmt.Errorf("locking tables %s: %w", currentBatch, err) } if i == len(tableBatches)-1 && lastBatchSize > 0 { currentBatchSize = lastBatchSize @@ -596,6 +587,15 @@ func LockTables(connectionPool *dbconn.DBConn, tables []Relation) error { return nil } +func lockBackupTables(conn *dbconn.DBConn, names, mode string) error { + _, err := conn.Exec(fmt.Sprintf("LOCK TABLE %s %s", names, mode)) + if err != nil && wasTerminated { + gplog.Warn("Interrupt received while acquiring table locks") + select {} // Wait for signal cleanup to exit gpbackup. + } + return err +} + // GenerateTableBatches batches tables to reduce network congestion and // resource contention. Returns an array of batches where a batch of tables is // a single string with comma separated tables diff --git a/backup/snapshot.go b/backup/snapshot.go index ff880ba6..abc61c2b 100644 --- a/backup/snapshot.go +++ b/backup/snapshot.go @@ -3,6 +3,7 @@ package backup import ( "errors" "fmt" + "slices" "sort" "strconv" "strings" @@ -61,20 +62,80 @@ func CheckSnapshotTableLocks(conn *dbconn.DBConn, tables []Relation) ([]string, return result, nil } +func snapshotPartitionParents(conn *dbconn.DBConn, tables []Relation, missingLocksOnly bool) ([]string, error) { + if len(tables) == 0 { + return nil, nil + } + oids := make([]string, len(tables)) + for i, table := range tables { + oids[i] = strconv.FormatUint(uint64(table.Oid), 10) + } + // Start at selected roots, but include subparents reached by COPY even if + // a filter omitted them from the explicit table list. + const query = `WITH RECURSIVE parents(oid, depth) AS ( + SELECT c.oid, 0 FROM pg_catalog.pg_class c + WHERE c.oid = ANY($1::oid[]) AND c.relkind = 'p' AND NOT c.relispartition + UNION ALL + SELECT c.oid, p.depth + 1 FROM parents p + JOIN pg_catalog.pg_inherits i ON i.inhparent = p.oid + JOIN pg_catalog.pg_class c ON c.oid = i.inhrelid + WHERE c.relkind = 'p' AND c.relispartition + ) + SELECT quote_ident(n.nspname) || '.' || quote_ident(c.relname) + FROM parents p JOIN pg_catalog.pg_class c ON c.oid = p.oid + JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE NOT $2::boolean OR NOT EXISTS ( + SELECT 1 FROM pg_catalog.pg_locks l + WHERE l.locktype = 'relation' AND l.relation = p.oid + AND l.database = (SELECT oid FROM pg_catalog.pg_database WHERE datname = current_database()) + AND l.pid = pg_catalog.pg_backend_pid() + AND l.mode = 'ShareUpdateExclusiveLock' AND l.granted + ) + ORDER BY p.depth, p.oid` + var parents []string + if err := conn.SelectWithArgs(&parents, query, "{"+strings.Join(oids, ",")+"}", missingLocksOnly); err != nil { + return nil, fmt.Errorf("checking partition parents for backup: %w", err) + } + return parents, nil +} + +func lockSnapshotPartitionParents(conn *dbconn.DBConn, parents []string) error { + for batch := range slices.Chunk(parents, 100) { + names := "ONLY " + strings.Join(batch, ", ONLY ") + if err := lockBackupTables(conn, names, "IN SHARE UPDATE EXCLUSIVE MODE"); err != nil { + return fmt.Errorf("locking partition parents %s in SHARE UPDATE EXCLUSIVE mode: %w", names, err) + } + } + return nil +} + // PrepareBackupSnapshot locks Cloudberry tables before exporting the shared // snapshot. The connection pool must have no open transactions on entry. func PrepareBackupSnapshot(opts *options.Options) error { maxAttempts := MustGetFlagInt(options.SNAPSHOT_ATTEMPTS) + copyThroughParent := !MustGetFlagBool(options.METADATA_ONLY) && !MustGetFlagBool(options.LEAF_PARTITION_DATA) for attempt := 1; attempt <= maxAttempts; attempt++ { if err := resolveSnapshotFilters(opts); err != nil { return err } tables := ConvertRelationsOptionsToBackup(GetIncludedUserTableRelations(connectionPool, IncludedRelationFqns)) + var parents []string + if copyThroughParent { + var err error + parents, err = snapshotPartitionParents(connectionPool, tables, false) + if err != nil { + return err + } + } // A SELECT before LOCK would establish the transaction snapshot too early. if err := connectionPool.Begin(0); err != nil { return err } - lockErr := LockTables(connectionPool, tables) + // ATTACH takes a lock on its parent that's compatible with ACCESS SHARE. + lockErr := lockSnapshotPartitionParents(connectionPool, parents) + if lockErr == nil { + lockErr = LockTables(connectionPool, tables) + } var conflicts []string if lockErr != nil { var pgErr *pgconn.PgError @@ -97,6 +158,12 @@ func PrepareBackupSnapshot(opts *options.Options) error { if err != nil { return err } + if copyThroughParent && len(conflicts) == 0 { + conflicts, err = snapshotPartitionParents(connectionPool, tables, true) + if err != nil { + return err + } + } } if len(conflicts) == 0 { for connNum := 1; connNum < connectionPool.NumConns; connNum++ { diff --git a/backup/snapshot_internal_test.go b/backup/snapshot_internal_test.go index 7e824dbc..2d6d8560 100644 --- a/backup/snapshot_internal_test.go +++ b/backup/snapshot_internal_test.go @@ -114,8 +114,16 @@ var _ = Describe("snapshot preparation", func() { tables := func() { mock.ExpectQuery("SELECT n.oid AS schemaoid").WillReturnRows(sqlmock.NewRows([]string{"schemaoid", "oid", "schema", "name"}).AddRow(1, 10, "public", "t")) } + partitionParents := func(missingLocksOnly bool, names ...string) { + rows := sqlmock.NewRows([]string{"fqn"}) + for _, name := range names { + rows.AddRow(name) + } + mock.ExpectQuery("WITH RECURSIVE parents").WithArgs("{10}", missingLocksOnly).WillReturnRows(rows) + } lock := func(err error) { tables() + partitionParents(false) begin() expectation := mock.ExpectExec("LOCK TABLE public.t") if err != nil { @@ -150,6 +158,7 @@ var _ = Describe("snapshot preparation", func() { lock(nil) snapshot() check() + partitionParents(true) begin() mock.ExpectExec("SET TRANSACTION SNAPSHOT 'new-snapshot'").WillReturnResult(sqlmock.NewResult(0, 0)) Expect(PrepareBackupSnapshot(opts)).To(Succeed()) @@ -176,6 +185,7 @@ var _ = Describe("snapshot preparation", func() { lock(nil) snapshot() check() + partitionParents(true) Expect(PrepareBackupSnapshot(opts)).To(Succeed()) Expect(heapFileHashes).To(Equal(map[uint32]string{10: "hash"})) }) @@ -185,12 +195,42 @@ var _ = Describe("snapshot preparation", func() { lock(nil) snapshot() check() + partitionParents(true) Expect(PrepareBackupSnapshot(opts)).To(Succeed()) }, Entry("table", "42P01"), Entry("schema", "3F000")) It("does not retry unrelated SQL errors", func() { lock(&pgconn.PgError{Code: "42501", Message: "permission denied"}) Expect(PrepareBackupSnapshot(opts)).To(MatchError(ContainSubstring("permission denied"))) }) + It("reports the partition parent and lock mode on a permission error", func() { + tables() + partitionParents(false, "public.t") + begin() + mock.ExpectExec("LOCK TABLE ONLY public.t IN SHARE UPDATE EXCLUSIVE MODE"). + WillReturnError(&pgconn.PgError{Code: "42501", Message: "permission denied"}) + Expect(PrepareBackupSnapshot(opts)).To(MatchError(ContainSubstring("public.t in SHARE UPDATE EXCLUSIVE mode"))) + }) + It("retries when ACCESS SHARE covers a newly attached subparent without a partition lock", func() { + tables() + partitionParents(false, "public.t") + begin() + mock.ExpectExec("LOCK TABLE ONLY public.t IN SHARE UPDATE EXCLUSIVE MODE").WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("LOCK TABLE public.t IN ACCESS SHARE MODE").WillReturnResult(sqlmock.NewResult(0, 0)) + snapshot() + check() + partitionParents(true, "public.middle") + mock.ExpectRollback() + + tables() + partitionParents(false, "public.t", "public.middle") + begin() + mock.ExpectExec("LOCK TABLE ONLY public.t, ONLY public.middle IN SHARE UPDATE EXCLUSIVE MODE").WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("LOCK TABLE public.t IN ACCESS SHARE MODE").WillReturnResult(sqlmock.NewResult(0, 0)) + snapshot() + check() + partitionParents(true) + Expect(PrepareBackupSnapshot(opts)).To(Succeed()) + }) It("does not import workers after a snapshot export failure", func() { twoConnections() lock(nil) diff --git a/end_to_end/snapshot_retry_test.go b/end_to_end/snapshot_retry_test.go index b3f168ff..f9497b81 100644 --- a/end_to_end/snapshot_retry_test.go +++ b/end_to_end/snapshot_retry_test.go @@ -23,6 +23,7 @@ import ( "fmt" "os" "os/exec" + "path/filepath" "strings" "syscall" "time" @@ -46,7 +47,10 @@ func waitForSnapshotBackupLock(relation string) { } func startSnapshotBackup(args ...string) *Session { - args = append([]string{"--dbname", "testdb", "--backup-dir", backupDir, "--verbose", "--no-history-sync-standby", "--snapshot-attempts", "1"}, args...) + if !hasCommandArgument(args, "--plugin-config") { + args = append(args, "--backup-dir", backupDir) + } + args = append([]string{"--dbname", "testdb", "--verbose", "--no-history-sync-standby", "--snapshot-attempts", "1"}, args...) session, err := Start(exec.Command(gpbackupPath, args...), GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) DeferCleanup(func() { @@ -154,6 +158,72 @@ var _ = Describe("snapshot lock preparation", func() { restoreConn.MustExec("CREATE SCHEMA snapshot_retry") restore(truncateDuringBackup(true, "--include-table-file", file.Name(), "--single-data-file", "--leaf-partition-data")) }) + DescribeTable("preserves the root copy when ATTACH starts after the backup snapshot", func(nested bool) { + backupConn.MustExec("CREATE TABLE snapshot_retry.t(id int) DISTRIBUTED BY(id) PARTITION BY RANGE(id)") + parent := "snapshot_retry.t" + if nested { + backupConn.MustExec(`CREATE TABLE snapshot_retry.middle PARTITION OF snapshot_retry.t + FOR VALUES FROM (0) TO (100) PARTITION BY RANGE(id)`) + parent = "snapshot_retry.middle" + } + backupConn.MustExec(fmt.Sprintf(`CREATE TABLE snapshot_retry.leaf PARTITION OF %s FOR VALUES FROM (0) TO (10); + INSERT INTO snapshot_retry.t VALUES (1),(2),(3); + CREATE TABLE snapshot_retry.new_leaf(id int) DISTRIBUTED BY(id); + INSERT INTO snapshot_retry.new_leaf VALUES (11),(12),(13)`, parent)) + + pluginPath := filepath.Join(backupDir, "snapshot-plugin.bash") + pluginConfig := filepath.Join(backupDir, "snapshot-plugin.yaml") + gate, release := filepath.Join(backupDir, "snapshot-ready"), filepath.Join(backupDir, "snapshot-release") + plugin, err := os.ReadFile(examplePluginExec) + Expect(err).NotTo(HaveOccurred()) + gatedSetup := fmt.Sprintf(`setup_plugin_for_backup(){ + if [[ "$3" == "coordinator" || "$3" == "master" ]]; then + touch %q + deadline=$((SECONDS + 45)) + until [[ -f %q ]]; do + ((SECONDS < deadline)) || exit 1 + sleep 0.1 + done + fi`, gate, release) + Expect(os.WriteFile(pluginPath, []byte(strings.Replace(string(plugin), "setup_plugin_for_backup(){", gatedSetup, 1)), 0755)).To(Succeed()) + Expect(os.WriteFile(pluginConfig, []byte(fmt.Sprintf("executablepath: %s\noptions:\n password: unknown\n", pluginPath)), 0600)).To(Succeed()) + copyPluginToAllHosts(backupConn, pluginPath) + restoreConn.MustExec("CREATE SCHEMA snapshot_retry") + + writer := testutils.SetupTestDbConn("testdb") + defer writer.Close() + writer.MustExec("SET statement_timeout = '60s'") + var pid int + Expect(writer.Get(&pid, "SELECT pg_backend_pid()")).To(Succeed()) + session := startSnapshotBackup("--include-table", "snapshot_retry.t", "--plugin-config", pluginConfig) + defer func() { _ = os.WriteFile(release, nil, 0600) }() + Eventually(gate, 30*time.Second).Should(BeAnExistingFile()) + attachDone := make(chan error, 1) + go func() { + _, err := writer.Exec(fmt.Sprintf("ALTER TABLE %s ATTACH PARTITION snapshot_retry.new_leaf FOR VALUES FROM (10) TO (20)", parent)) + attachDone <- err + }() + Eventually(func() (bool, error) { + select { + case err := <-attachDone: + return false, StopTrying(fmt.Sprintf("ATTACH finished before backup released the parent lock: %v", err)) + default: + } + var waiting bool + query := fmt.Sprintf(`SELECT EXISTS (SELECT 1 FROM pg_locks WHERE pid=%d + AND relation='%s'::regclass AND mode='ShareUpdateExclusiveLock' AND NOT granted)`, pid, parent) + err := backupConn.Get(&waiting, query) + return waiting, err + }, 10*time.Second, 50*time.Millisecond).Should(BeTrue()) + Expect(os.WriteFile(release, nil, 0600)).To(Succeed()) + Eventually(session, 90*time.Second).Should(Exit(0)) + Eventually(attachDone, 30*time.Second).Should(Receive(BeNil())) + + ts := getBackupTimestamp(string(session.Out.Contents())) + gprestore(gprestorePath, restoreHelperPath, ts, "--redirect-db", "restoredb", "--plugin-config", pluginConfig) + Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{1, 2, 3})) + Expect(snapshotRetryRows(backupConn)).To(Equal([]int{1, 2, 3, 11, 12, 13})) + }, Entry("on the root", false), Entry("on a subparent", true)) It("does not deadlock when another exclusive lock queues behind the backup", func() { createTable("heap", false) first := testutils.SetupTestDbConn("testdb") From f74499c7a71e4fc4ef74e1eca9412d9466b47ddd Mon Sep 17 00:00:00 2001 From: woblerr Date: Fri, 27 Nov 2026 22:12:57 +0300 Subject: [PATCH 4/7] Limit root COPY to partitions visible in the backup snapshot. Filtering by snapshot leaf OIDs excludes rows from late attachments and preserves root permissions and row security with ACCESS SHARE. --- backup/data.go | 11 +++- backup/queries_relations.go | 15 ++---- backup/queries_table_defs.go | 1 + backup/snapshot.go | 85 ++++++++++--------------------- backup/snapshot_internal_test.go | 40 --------------- backup/wrappers.go | 3 ++ end_to_end/snapshot_retry_test.go | 68 ++++++++++++++----------- 7 files changed, 85 insertions(+), 138 deletions(-) diff --git a/backup/data.go b/backup/data.go index 4ffb5172..e6323588 100644 --- a/backup/data.go +++ b/backup/data.go @@ -94,7 +94,16 @@ func CopyTableOut(connectionPool *dbconn.DBConn, table Table, destinationToWrite if gplog.GetVerbosity() >= gplog.LOGVERBOSE { workerInfo = fmt.Sprintf("Worker %d: ", connNum) } - query := fmt.Sprintf("COPY %s%s TO %s WITH CSV DELIMITER '%s' ON SEGMENT IGNORE EXTERNAL PARTITIONS;", table.FQN(), columnNames, copyCommand, tableDelim) + source := table.FQN() + columnNames + if table.snapshotLeafOIDs != "" { + columns := "*" + if columnNames != "" { + columns = columnNames[1 : len(columnNames)-1] + } + // Keep the root's access checks and row policies while excluding later attachments. + source = fmt.Sprintf("(SELECT %s FROM %s WHERE tableoid = ANY ('%s'::pg_catalog.oid[]))", columns, table.FQN(), table.snapshotLeafOIDs) + } + query := fmt.Sprintf("COPY %s TO %s WITH CSV DELIMITER '%s' ON SEGMENT IGNORE EXTERNAL PARTITIONS;", source, copyCommand, tableDelim) if (connectionPool.Version.IsGPDB() && connectionPool.Version.AtLeast("7")) || connectionPool.Version.IsCBDB() { utils.LogProgress(`%sExecuting "%s" on coordinator`, workerInfo, query) } else { diff --git a/backup/queries_relations.go b/backup/queries_relations.go index b7cfeaa8..47e3a65f 100644 --- a/backup/queries_relations.go +++ b/backup/queries_relations.go @@ -575,7 +575,11 @@ func LockTables(connectionPool *dbconn.DBConn, tables []Relation) error { lockMode = `IN ACCESS SHARE MODE` } for i, currentBatch := range tableBatches { - if err := lockBackupTables(connectionPool, currentBatch, lockMode); err != nil { + if _, err := connectionPool.Exec(fmt.Sprintf("LOCK TABLE %s %s", currentBatch, lockMode)); err != nil { + if wasTerminated { + gplog.Warn("Interrupt received while acquiring ACCESS SHARE locks on tables") + select {} // Wait for signal cleanup to exit gpbackup. + } return fmt.Errorf("locking tables %s: %w", currentBatch, err) } if i == len(tableBatches)-1 && lastBatchSize > 0 { @@ -587,15 +591,6 @@ func LockTables(connectionPool *dbconn.DBConn, tables []Relation) error { return nil } -func lockBackupTables(conn *dbconn.DBConn, names, mode string) error { - _, err := conn.Exec(fmt.Sprintf("LOCK TABLE %s %s", names, mode)) - if err != nil && wasTerminated { - gplog.Warn("Interrupt received while acquiring table locks") - select {} // Wait for signal cleanup to exit gpbackup. - } - return err -} - // GenerateTableBatches batches tables to reduce network congestion and // resource contention. Returns an array of batches where a batch of tables is // a single string with comma separated tables diff --git a/backup/queries_table_defs.go b/backup/queries_table_defs.go index 3cb5d9f9..2a0810dd 100644 --- a/backup/queries_table_defs.go +++ b/backup/queries_table_defs.go @@ -85,6 +85,7 @@ type TableDefinition struct { PartitionKeyDef string AttachPartitionInfo AttachPartitionInfo ForceRowSecurity bool + snapshotLeafOIDs string } /* diff --git a/backup/snapshot.go b/backup/snapshot.go index abc61c2b..c3721670 100644 --- a/backup/snapshot.go +++ b/backup/snapshot.go @@ -3,7 +3,6 @@ package backup import ( "errors" "fmt" - "slices" "sort" "strconv" "strings" @@ -62,49 +61,40 @@ func CheckSnapshotTableLocks(conn *dbconn.DBConn, tables []Relation) ([]string, return result, nil } -func snapshotPartitionParents(conn *dbconn.DBConn, tables []Relation, missingLocksOnly bool) ([]string, error) { - if len(tables) == 0 { - return nil, nil - } - oids := make([]string, len(tables)) +// collectSnapshotPartitionLeaves reads the partition tree from the backup snapshot. +func collectSnapshotPartitionLeaves(conn *dbconn.DBConn, tables []Table) error { + roots := make(map[uint32]int) + var oids []string for i, table := range tables { - oids[i] = strconv.FormatUint(uint64(table.Oid), 10) + if table.PartitionLevelInfo.Level == "p" { + roots[table.Oid] = i + oids = append(oids, strconv.FormatUint(uint64(table.Oid), 10)) + } + } + if len(oids) == 0 { + return nil } - // Start at selected roots, but include subparents reached by COPY even if - // a filter omitted them from the explicit table list. - const query = `WITH RECURSIVE parents(oid, depth) AS ( - SELECT c.oid, 0 FROM pg_catalog.pg_class c - WHERE c.oid = ANY($1::oid[]) AND c.relkind = 'p' AND NOT c.relispartition + + const query = `WITH RECURSIVE partitions(root, oid, relkind) AS ( + SELECT oid, oid, relkind FROM pg_catalog.pg_class + WHERE oid = ANY($1::oid[]) UNION ALL - SELECT c.oid, p.depth + 1 FROM parents p + SELECT p.root, c.oid, c.relkind FROM partitions p JOIN pg_catalog.pg_inherits i ON i.inhparent = p.oid JOIN pg_catalog.pg_class c ON c.oid = i.inhrelid - WHERE c.relkind = 'p' AND c.relispartition + WHERE p.relkind = 'p' AND NOT i.inhdetachpending ) - SELECT quote_ident(n.nspname) || '.' || quote_ident(c.relname) - FROM parents p JOIN pg_catalog.pg_class c ON c.oid = p.oid - JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace - WHERE NOT $2::boolean OR NOT EXISTS ( - SELECT 1 FROM pg_catalog.pg_locks l - WHERE l.locktype = 'relation' AND l.relation = p.oid - AND l.database = (SELECT oid FROM pg_catalog.pg_database WHERE datname = current_database()) - AND l.pid = pg_catalog.pg_backend_pid() - AND l.mode = 'ShareUpdateExclusiveLock' AND l.granted - ) - ORDER BY p.depth, p.oid` - var parents []string - if err := conn.SelectWithArgs(&parents, query, "{"+strings.Join(oids, ",")+"}", missingLocksOnly); err != nil { - return nil, fmt.Errorf("checking partition parents for backup: %w", err) + SELECT root, COALESCE(array_agg(oid ORDER BY oid) FILTER (WHERE relkind <> 'p'), '{}'::oid[])::text AS leaves + FROM partitions GROUP BY root` + var partitions []struct { + Root uint32 + Leaves string } - return parents, nil -} - -func lockSnapshotPartitionParents(conn *dbconn.DBConn, parents []string) error { - for batch := range slices.Chunk(parents, 100) { - names := "ONLY " + strings.Join(batch, ", ONLY ") - if err := lockBackupTables(conn, names, "IN SHARE UPDATE EXCLUSIVE MODE"); err != nil { - return fmt.Errorf("locking partition parents %s in SHARE UPDATE EXCLUSIVE mode: %w", names, err) - } + if err := conn.SelectWithArgs(&partitions, query, "{"+strings.Join(oids, ",")+"}"); err != nil { + return fmt.Errorf("reading partition leaves from the backup snapshot: %w", err) + } + for _, partition := range partitions { + tables[roots[partition.Root]].snapshotLeafOIDs = partition.Leaves } return nil } @@ -113,29 +103,16 @@ func lockSnapshotPartitionParents(conn *dbconn.DBConn, parents []string) error { // snapshot. The connection pool must have no open transactions on entry. func PrepareBackupSnapshot(opts *options.Options) error { maxAttempts := MustGetFlagInt(options.SNAPSHOT_ATTEMPTS) - copyThroughParent := !MustGetFlagBool(options.METADATA_ONLY) && !MustGetFlagBool(options.LEAF_PARTITION_DATA) for attempt := 1; attempt <= maxAttempts; attempt++ { if err := resolveSnapshotFilters(opts); err != nil { return err } tables := ConvertRelationsOptionsToBackup(GetIncludedUserTableRelations(connectionPool, IncludedRelationFqns)) - var parents []string - if copyThroughParent { - var err error - parents, err = snapshotPartitionParents(connectionPool, tables, false) - if err != nil { - return err - } - } // A SELECT before LOCK would establish the transaction snapshot too early. if err := connectionPool.Begin(0); err != nil { return err } - // ATTACH takes a lock on its parent that's compatible with ACCESS SHARE. - lockErr := lockSnapshotPartitionParents(connectionPool, parents) - if lockErr == nil { - lockErr = LockTables(connectionPool, tables) - } + lockErr := LockTables(connectionPool, tables) var conflicts []string if lockErr != nil { var pgErr *pgconn.PgError @@ -158,12 +135,6 @@ func PrepareBackupSnapshot(opts *options.Options) error { if err != nil { return err } - if copyThroughParent && len(conflicts) == 0 { - conflicts, err = snapshotPartitionParents(connectionPool, tables, true) - if err != nil { - return err - } - } } if len(conflicts) == 0 { for connNum := 1; connNum < connectionPool.NumConns; connNum++ { diff --git a/backup/snapshot_internal_test.go b/backup/snapshot_internal_test.go index 2d6d8560..7e824dbc 100644 --- a/backup/snapshot_internal_test.go +++ b/backup/snapshot_internal_test.go @@ -114,16 +114,8 @@ var _ = Describe("snapshot preparation", func() { tables := func() { mock.ExpectQuery("SELECT n.oid AS schemaoid").WillReturnRows(sqlmock.NewRows([]string{"schemaoid", "oid", "schema", "name"}).AddRow(1, 10, "public", "t")) } - partitionParents := func(missingLocksOnly bool, names ...string) { - rows := sqlmock.NewRows([]string{"fqn"}) - for _, name := range names { - rows.AddRow(name) - } - mock.ExpectQuery("WITH RECURSIVE parents").WithArgs("{10}", missingLocksOnly).WillReturnRows(rows) - } lock := func(err error) { tables() - partitionParents(false) begin() expectation := mock.ExpectExec("LOCK TABLE public.t") if err != nil { @@ -158,7 +150,6 @@ var _ = Describe("snapshot preparation", func() { lock(nil) snapshot() check() - partitionParents(true) begin() mock.ExpectExec("SET TRANSACTION SNAPSHOT 'new-snapshot'").WillReturnResult(sqlmock.NewResult(0, 0)) Expect(PrepareBackupSnapshot(opts)).To(Succeed()) @@ -185,7 +176,6 @@ var _ = Describe("snapshot preparation", func() { lock(nil) snapshot() check() - partitionParents(true) Expect(PrepareBackupSnapshot(opts)).To(Succeed()) Expect(heapFileHashes).To(Equal(map[uint32]string{10: "hash"})) }) @@ -195,42 +185,12 @@ var _ = Describe("snapshot preparation", func() { lock(nil) snapshot() check() - partitionParents(true) Expect(PrepareBackupSnapshot(opts)).To(Succeed()) }, Entry("table", "42P01"), Entry("schema", "3F000")) It("does not retry unrelated SQL errors", func() { lock(&pgconn.PgError{Code: "42501", Message: "permission denied"}) Expect(PrepareBackupSnapshot(opts)).To(MatchError(ContainSubstring("permission denied"))) }) - It("reports the partition parent and lock mode on a permission error", func() { - tables() - partitionParents(false, "public.t") - begin() - mock.ExpectExec("LOCK TABLE ONLY public.t IN SHARE UPDATE EXCLUSIVE MODE"). - WillReturnError(&pgconn.PgError{Code: "42501", Message: "permission denied"}) - Expect(PrepareBackupSnapshot(opts)).To(MatchError(ContainSubstring("public.t in SHARE UPDATE EXCLUSIVE mode"))) - }) - It("retries when ACCESS SHARE covers a newly attached subparent without a partition lock", func() { - tables() - partitionParents(false, "public.t") - begin() - mock.ExpectExec("LOCK TABLE ONLY public.t IN SHARE UPDATE EXCLUSIVE MODE").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("LOCK TABLE public.t IN ACCESS SHARE MODE").WillReturnResult(sqlmock.NewResult(0, 0)) - snapshot() - check() - partitionParents(true, "public.middle") - mock.ExpectRollback() - - tables() - partitionParents(false, "public.t", "public.middle") - begin() - mock.ExpectExec("LOCK TABLE ONLY public.t, ONLY public.middle IN SHARE UPDATE EXCLUSIVE MODE").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("LOCK TABLE public.t IN ACCESS SHARE MODE").WillReturnResult(sqlmock.NewResult(0, 0)) - snapshot() - check() - partitionParents(true) - Expect(PrepareBackupSnapshot(opts)).To(Succeed()) - }) It("does not import workers after a snapshot export failure", func() { twoConnections() lock(nil) diff --git a/backup/wrappers.go b/backup/wrappers.go index f51d4787..0daa7c44 100644 --- a/backup/wrappers.go +++ b/backup/wrappers.go @@ -232,6 +232,9 @@ func RetrieveAndProcessTables() ([]Table, []Table) { tables := ConstructDefinitionsForTables(connectionPool, tableRelations) metadataTables, dataTables := SplitTablesByPartitionType(tables, IncludedRelationFqns) + if connectionPool.Version.IsCBDB() && !MustGetFlagBool(options.METADATA_ONLY) && !MustGetFlagBool(options.LEAF_PARTITION_DATA) { + gplog.FatalOnError(collectSnapshotPartitionLeaves(connectionPool, dataTables)) + } objectCounts["Tables"] = len(metadataTables) return metadataTables, dataTables diff --git a/end_to_end/snapshot_retry_test.go b/end_to_end/snapshot_retry_test.go index f9497b81..45ab1ad3 100644 --- a/end_to_end/snapshot_retry_test.go +++ b/end_to_end/snapshot_retry_test.go @@ -158,7 +158,30 @@ var _ = Describe("snapshot lock preparation", func() { restoreConn.MustExec("CREATE SCHEMA snapshot_retry") restore(truncateDuringBackup(true, "--include-table-file", file.Name(), "--single-data-file", "--leaf-partition-data")) }) - DescribeTable("preserves the root copy when ATTACH starts after the backup snapshot", func(nested bool) { + It("backs up a partitioned root with SELECT and applies its row policy", func() { + createTable("heap", true) + backupConn.MustExec("CREATE ROLE snapshot_retry_reader") + DeferCleanup(func() { + restoreConn.MustExec("DROP OWNED BY snapshot_retry_reader") + backupConn.MustExec("DROP OWNED BY snapshot_retry_reader; DROP ROLE snapshot_retry_reader") + }) + backupConn.MustExec(`GRANT USAGE ON SCHEMA snapshot_retry TO snapshot_retry_reader; + GRANT SELECT ON ALL TABLES IN SCHEMA snapshot_retry, pg_catalog TO snapshot_retry_reader; + GRANT pg_execute_server_program TO snapshot_retry_reader; + ALTER TABLE snapshot_retry.t ENABLE ROW LEVEL SECURITY; + CREATE POLICY root_read ON snapshot_retry.t FOR SELECT TO snapshot_retry_reader USING (id <> 2)`) + cmd := exec.Command(gpbackupPath, "--dbname", "testdb", "--include-table", "snapshot_retry.t", "--without-globals", + "--no-history", "--no-history-sync-standby", "--backup-dir", backupDir) + cmd.Env = append(os.Environ(), "PGOPTIONS="+strings.TrimSpace(os.Getenv("PGOPTIONS")+" -c role=snapshot_retry_reader")) + output, err := cmd.CombinedOutput() + Expect(err).NotTo(HaveOccurred(), "%s", output) + + restoreConn.MustExec("CREATE SCHEMA snapshot_retry") + gprestore(gprestorePath, restoreHelperPath, getBackupTimestamp(string(output)), "--redirect-db", "restoredb", "--backup-dir", backupDir) + Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{1, 3})) + }) + + DescribeTable("preserves the root copy when ATTACH starts after the backup snapshot", func(nested, empty bool) { backupConn.MustExec("CREATE TABLE snapshot_retry.t(id int) DISTRIBUTED BY(id) PARTITION BY RANGE(id)") parent := "snapshot_retry.t" if nested { @@ -166,10 +189,14 @@ var _ = Describe("snapshot lock preparation", func() { FOR VALUES FROM (0) TO (100) PARTITION BY RANGE(id)`) parent = "snapshot_retry.middle" } - backupConn.MustExec(fmt.Sprintf(`CREATE TABLE snapshot_retry.leaf PARTITION OF %s FOR VALUES FROM (0) TO (10); - INSERT INTO snapshot_retry.t VALUES (1),(2),(3); - CREATE TABLE snapshot_retry.new_leaf(id int) DISTRIBUTED BY(id); - INSERT INTO snapshot_retry.new_leaf VALUES (11),(12),(13)`, parent)) + var expectedRows []int + if !empty { + backupConn.MustExec(fmt.Sprintf(`CREATE TABLE snapshot_retry.leaf PARTITION OF %s FOR VALUES FROM (0) TO (10); + INSERT INTO snapshot_retry.t VALUES (1),(2),(3)`, parent)) + expectedRows = []int{1, 2, 3} + } + backupConn.MustExec(`CREATE TABLE snapshot_retry.new_leaf(id int) DISTRIBUTED BY(id); + INSERT INTO snapshot_retry.new_leaf VALUES (11),(12),(13)`) pluginPath := filepath.Join(backupDir, "snapshot-plugin.bash") pluginConfig := filepath.Join(backupDir, "snapshot-plugin.yaml") @@ -192,38 +219,19 @@ var _ = Describe("snapshot lock preparation", func() { writer := testutils.SetupTestDbConn("testdb") defer writer.Close() - writer.MustExec("SET statement_timeout = '60s'") - var pid int - Expect(writer.Get(&pid, "SELECT pg_backend_pid()")).To(Succeed()) - session := startSnapshotBackup("--include-table", "snapshot_retry.t", "--plugin-config", pluginConfig) + writer.MustExec("SET lock_timeout = '5s'") + session := startSnapshotBackup("--include-table", "snapshot_retry.t", "--plugin-config", pluginConfig, "--jobs", "2") defer func() { _ = os.WriteFile(release, nil, 0600) }() Eventually(gate, 30*time.Second).Should(BeAnExistingFile()) - attachDone := make(chan error, 1) - go func() { - _, err := writer.Exec(fmt.Sprintf("ALTER TABLE %s ATTACH PARTITION snapshot_retry.new_leaf FOR VALUES FROM (10) TO (20)", parent)) - attachDone <- err - }() - Eventually(func() (bool, error) { - select { - case err := <-attachDone: - return false, StopTrying(fmt.Sprintf("ATTACH finished before backup released the parent lock: %v", err)) - default: - } - var waiting bool - query := fmt.Sprintf(`SELECT EXISTS (SELECT 1 FROM pg_locks WHERE pid=%d - AND relation='%s'::regclass AND mode='ShareUpdateExclusiveLock' AND NOT granted)`, pid, parent) - err := backupConn.Get(&waiting, query) - return waiting, err - }, 10*time.Second, 50*time.Millisecond).Should(BeTrue()) + writer.MustExec(fmt.Sprintf("ALTER TABLE %s ATTACH PARTITION snapshot_retry.new_leaf FOR VALUES FROM (10) TO (20)", parent)) Expect(os.WriteFile(release, nil, 0600)).To(Succeed()) Eventually(session, 90*time.Second).Should(Exit(0)) - Eventually(attachDone, 30*time.Second).Should(Receive(BeNil())) ts := getBackupTimestamp(string(session.Out.Contents())) gprestore(gprestorePath, restoreHelperPath, ts, "--redirect-db", "restoredb", "--plugin-config", pluginConfig) - Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{1, 2, 3})) - Expect(snapshotRetryRows(backupConn)).To(Equal([]int{1, 2, 3, 11, 12, 13})) - }, Entry("on the root", false), Entry("on a subparent", true)) + Expect(snapshotRetryRows(restoreConn)).To(Equal(expectedRows)) + Expect(snapshotRetryRows(backupConn)).To(Equal(append(expectedRows, 11, 12, 13))) + }, Entry("on the root", false, false), Entry("on a subparent", true, false), Entry("on an empty root", false, true)) It("does not deadlock when another exclusive lock queues behind the backup", func() { createTable("heap", false) first := testutils.SetupTestDbConn("testdb") From 6c1391bf86f7d3f69decc0082f9468b62cf36f55 Mon Sep 17 00:00:00 2001 From: woblerr Date: Fri, 27 Nov 2026 23:14:16 +0300 Subject: [PATCH 5/7] Prepare backup reports and plugins before locking tables. Initialize the report early so snapshot failures are recorded, and run plugin setup before it can wait on locks held by gpbackup. Validate explicit filters first to avoid invoking plugins for invalid requests. --- backup/backup.go | 14 +++- end_to_end/snapshot_retry_test.go | 104 +++++++++++++++++++++++------- 2 files changed, 92 insertions(+), 26 deletions(-) diff --git a/backup/backup.go b/backup/backup.go index e96a2674..2ab84bb1 100644 --- a/backup/backup.go +++ b/backup/backup.go @@ -62,6 +62,10 @@ func DoSetup() { opts, err := options.NewOptions(cmdFlags) gplog.FatalOnError(err) + if connectionPool.Version.IsCBDB() && MustGetFlagString(options.PLUGIN_CONFIG) != "" { + ValidateAndProcessFilterLists(opts) + } + clusterConfigConn := dbconn.NewDBConnFromEnvironment(MustGetFlagString(options.DBNAME)) clusterConfigConn.MustConnect(1) @@ -85,6 +89,7 @@ func DoSetup() { utils.InitializePipeThroughParameters(!MustGetFlagBool(options.NO_COMPRESSION), MustGetFlagString(options.COMPRESSION_TYPE), MustGetFlagInt(options.COMPRESSION_LEVEL)) // Signal cleanup needs globalFPInfo.Timestamp to cancel blocked sessions. if connectionPool.Version.IsCBDB() { + setupBackupReportAndPlugin(timestamp, *opts) gplog.FatalOnError(PrepareBackupSnapshot(opts)) } else { ValidateAndProcessFilterLists(opts) @@ -95,10 +100,16 @@ func DoSetup() { heapFileHashes = VerifyHeapFileHashes(MustGetFlagString(options.DBNAME), hashedHeapTables, heapFileHashes) } getQuotedRoleNames(connectionPool) + if !connectionPool.Version.IsCBDB() { + setupBackupReportAndPlugin(timestamp, *opts) + } +} +func setupBackupReportAndPlugin(timestamp string, opts options.Options) { pluginConfigFlag := MustGetFlagString(options.PLUGIN_CONFIG) if pluginConfigFlag != "" { + var err error pluginConfig, err = utils.ReadPluginConfig(pluginConfigFlag) gplog.FatalOnError(err) configFilename := path.Base(pluginConfig.ConfigPath) @@ -108,7 +119,7 @@ func DoSetup() { gplog.Debug("Plugin config path: %s", pluginConfig.ConfigPath) } - initializeBackupReport(*opts) + initializeBackupReport(opts) if pluginConfigFlag != "" { backupReport.PluginVersion = pluginConfig.CheckPluginExistsOnAllHosts(globalCluster) @@ -525,7 +536,6 @@ func DoCleanup(backupFailed bool) { // panics, there should be no way for gpbackup to exit that leaves the entry in the initial status. historyUpdated := false - // Cancellation during lock acquisition can precede report creation. if backupReport != nil && !MustGetFlagBool(options.NO_HISTORY) { var statusString string if backupFailed { diff --git a/end_to_end/snapshot_retry_test.go b/end_to_end/snapshot_retry_test.go index 45ab1ad3..860328e3 100644 --- a/end_to_end/snapshot_retry_test.go +++ b/end_to_end/snapshot_retry_test.go @@ -28,6 +28,7 @@ import ( "syscall" "time" + "github.com/apache/cloudberry-backup/history" "github.com/apache/cloudberry-backup/testutils" "github.com/apache/cloudberry-backup/toc" "github.com/apache/cloudberry-go-libs/cluster" @@ -42,7 +43,7 @@ import ( func waitForSnapshotBackupLock(relation string) { query := fmt.Sprintf(`SELECT count(*) FROM pg_locks l JOIN pg_stat_activity a ON a.pid=l.pid WHERE l.relation='%s'::regclass AND NOT l.granted AND l.mode='AccessShareLock' - AND a.datname=current_database() AND a.application_name LIKE 'gpbackup_%%' AND a.query LIKE 'LOCK TABLE%%'`, relation) + AND a.datname=current_database() AND a.application_name LIKE 'gpbackup_%%'`, relation) Eventually(func() (int, error) { var count int; err := backupConn.Get(&count, query); return count, err }, 30*time.Second, 100*time.Millisecond).Should(BeNumerically(">", 0)) } @@ -181,6 +182,70 @@ var _ = Describe("snapshot lock preparation", func() { Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{1, 3})) }) + It("writes a failure report when snapshot preparation runs out of attempts", func() { + createTable("heap", false) + writer := testutils.SetupTestDbConn("testdb") + defer writer.Close() + writer.MustBegin() + defer func() { + if writer.Tx[0] != nil { + writer.MustRollback() + } + }() + writer.MustExec("LOCK TABLE snapshot_retry.t IN ACCESS EXCLUSIVE MODE") + session := startSnapshotBackup("--include-schema", "snapshot_retry") + waitForSnapshotBackupLock("snapshot_retry.t") + backupConn.MustExec("CREATE TABLE snapshot_retry.added(id int) DISTRIBUTED BY(id)") + writer.MustCommit() + + Eventually(session, 90*time.Second).Should(Exit(2)) + Expect(string(session.Out.Contents())).To(ContainSubstring("after 1 attempt(s): snapshot_retry.added")) + reports, err := filepath.Glob(filepath.Join(backupDir, "*-1", "backups", "*", "*", "*_report")) + Expect(err).NotTo(HaveOccurred()) + Expect(reports).To(HaveLen(1)) + contents, err := os.ReadFile(reports[0]) + Expect(err).NotTo(HaveOccurred()) + Expect(string(contents)).To(ContainSubstring("backup status:")) + Expect(string(contents)).To(ContainSubstring("Failure")) + Expect(string(contents)).To(ContainSubstring("after 1 attempt(s): snapshot_retry.added")) + contents, err = os.ReadFile(strings.TrimSuffix(reports[0], "_report") + "_config.yaml") + Expect(err).NotTo(HaveOccurred()) + var config history.BackupConfig + Expect(yaml.Unmarshal(contents, &config)).To(Succeed()) + Expect(config.Status).To(Equal(history.BackupStatusFailed)) + }) + + It("validates table filters before plugin setup and takes the snapshot afterward", func() { + createTable("heap", false) + pluginPath := filepath.Join(backupDir, "snapshot-plugin.bash") + pluginConfig := filepath.Join(backupDir, "snapshot-plugin.yaml") + setupMarker := filepath.Join(backupDir, "snapshot-plugin-started") + plugin, err := os.ReadFile(examplePluginExec) + Expect(err).NotTo(HaveOccurred()) + setup := fmt.Sprintf(`setup_plugin_for_backup(){ + if [[ "$3" == "coordinator" || "$3" == "master" ]]; then + touch %q + PGOPTIONS="${PGOPTIONS:-} -c lock_timeout=5000" psql -X -v ON_ERROR_STOP=1 -d testdb \ + -c 'VACUUM FULL snapshot_retry.t' -c 'INSERT INTO snapshot_retry.t VALUES (4)' + fi`, setupMarker) + Expect(os.WriteFile(pluginPath, []byte(strings.Replace(string(plugin), "setup_plugin_for_backup(){", setup, 1)), 0755)).To(Succeed()) + Expect(os.WriteFile(pluginConfig, []byte(fmt.Sprintf("executablepath: %s\noptions:\n password: unknown\n", pluginPath)), 0600)).To(Succeed()) + copyPluginToAllHosts(backupConn, pluginPath) + + invalid := startSnapshotBackup("--include-table", "snapshot_retry.absent", "--plugin-config", pluginConfig) + Eventually(invalid, 90*time.Second).Should(Exit(2)) + Expect(string(invalid.Out.Contents())).To(ContainSubstring("Table snapshot_retry.absent does not exist")) + Expect(setupMarker).NotTo(BeAnExistingFile()) + + session := startSnapshotBackup("--include-table", "snapshot_retry.t", "--plugin-config", pluginConfig) + Eventually(session, 90*time.Second).Should(Exit(0)) + Expect(setupMarker).To(BeAnExistingFile()) + ts := getBackupTimestamp(string(session.Out.Contents())) + restoreConn.MustExec("CREATE SCHEMA snapshot_retry") + gprestore(gprestorePath, restoreHelperPath, ts, "--redirect-db", "restoredb", "--plugin-config", pluginConfig) + Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{1, 2, 3, 4})) + }) + DescribeTable("preserves the root copy when ATTACH starts after the backup snapshot", func(nested, empty bool) { backupConn.MustExec("CREATE TABLE snapshot_retry.t(id int) DISTRIBUTED BY(id) PARTITION BY RANGE(id)") parent := "snapshot_retry.t" @@ -198,37 +263,28 @@ var _ = Describe("snapshot lock preparation", func() { backupConn.MustExec(`CREATE TABLE snapshot_retry.new_leaf(id int) DISTRIBUTED BY(id); INSERT INTO snapshot_retry.new_leaf VALUES (11),(12),(13)`) - pluginPath := filepath.Join(backupDir, "snapshot-plugin.bash") - pluginConfig := filepath.Join(backupDir, "snapshot-plugin.yaml") - gate, release := filepath.Join(backupDir, "snapshot-ready"), filepath.Join(backupDir, "snapshot-release") - plugin, err := os.ReadFile(examplePluginExec) - Expect(err).NotTo(HaveOccurred()) - gatedSetup := fmt.Sprintf(`setup_plugin_for_backup(){ - if [[ "$3" == "coordinator" || "$3" == "master" ]]; then - touch %q - deadline=$((SECONDS + 45)) - until [[ -f %q ]]; do - ((SECONDS < deadline)) || exit 1 - sleep 0.1 - done - fi`, gate, release) - Expect(os.WriteFile(pluginPath, []byte(strings.Replace(string(plugin), "setup_plugin_for_backup(){", gatedSetup, 1)), 0755)).To(Succeed()) - Expect(os.WriteFile(pluginConfig, []byte(fmt.Sprintf("executablepath: %s\noptions:\n password: unknown\n", pluginPath)), 0600)).To(Succeed()) - copyPluginToAllHosts(backupConn, pluginPath) - restoreConn.MustExec("CREATE SCHEMA snapshot_retry") + gate := testutils.SetupTestDbConn("testdb") + defer gate.Close() + gate.MustBegin() + defer func() { + if gate.Tx[0] != nil { + gate.MustRollback() + } + }() + gate.MustExec("LOCK TABLE pg_catalog.pg_description IN ACCESS EXCLUSIVE MODE") + session := startSnapshotBackup("--include-table", "snapshot_retry.t", "--jobs", "2") + waitForSnapshotBackupLock("pg_catalog.pg_description") writer := testutils.SetupTestDbConn("testdb") defer writer.Close() writer.MustExec("SET lock_timeout = '5s'") - session := startSnapshotBackup("--include-table", "snapshot_retry.t", "--plugin-config", pluginConfig, "--jobs", "2") - defer func() { _ = os.WriteFile(release, nil, 0600) }() - Eventually(gate, 30*time.Second).Should(BeAnExistingFile()) writer.MustExec(fmt.Sprintf("ALTER TABLE %s ATTACH PARTITION snapshot_retry.new_leaf FOR VALUES FROM (10) TO (20)", parent)) - Expect(os.WriteFile(release, nil, 0600)).To(Succeed()) + gate.MustCommit() Eventually(session, 90*time.Second).Should(Exit(0)) ts := getBackupTimestamp(string(session.Out.Contents())) - gprestore(gprestorePath, restoreHelperPath, ts, "--redirect-db", "restoredb", "--plugin-config", pluginConfig) + restoreConn.MustExec("CREATE SCHEMA snapshot_retry") + gprestore(gprestorePath, restoreHelperPath, ts, "--redirect-db", "restoredb", "--backup-dir", backupDir) Expect(snapshotRetryRows(restoreConn)).To(Equal(expectedRows)) Expect(snapshotRetryRows(backupConn)).To(Equal(append(expectedRows, 11, 12, 13))) }, Entry("on the root", false, false), Entry("on a subparent", true, false), Entry("on an empty root", false, true)) From 32cea5b73cced46bdfdfd896683b23730bb34aab Mon Sep 17 00:00:00 2001 From: woblerr Date: Sat, 28 Nov 2026 10:51:19 +0300 Subject: [PATCH 6/7] Fix partition root backup tests. The unexported leaf OIDs field prevents partial metadata comparisons. Both forms of COPY emit the same table-write log, which identifies the worker that handles each table. --- backup/queries_table_defs.go | 4 ++-- end_to_end/locks_test.go | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/backup/queries_table_defs.go b/backup/queries_table_defs.go index 2a0810dd..4ac5d000 100644 --- a/backup/queries_table_defs.go +++ b/backup/queries_table_defs.go @@ -20,6 +20,7 @@ import ( type Table struct { Relation TableDefinition + snapshotLeafOIDs string } func (t Table) SkipDataBackup() bool { @@ -85,7 +86,6 @@ type TableDefinition struct { PartitionKeyDef string AttachPartitionInfo AttachPartitionInfo ForceRowSecurity bool - snapshotLeafOIDs string } /* @@ -141,7 +141,7 @@ func ConstructDefinitionsForTables(connectionPool *dbconn.DBConn, tableRelations if tableDef.Inherits == nil { tableDef.Inherits = []string{} } - tables = append(tables, Table{tableRel, tableDef}) + tables = append(tables, Table{Relation: tableRel, TableDefinition: tableDef}) } return tables } diff --git a/end_to_end/locks_test.go b/end_to_end/locks_test.go index 046a5730..c80f8d56 100644 --- a/end_to_end/locks_test.go +++ b/end_to_end/locks_test.go @@ -178,7 +178,7 @@ var _ = Describe("Deadlock handling", func() { // Only the main worker thread, worker 0, will run COPY on all the test tables for _, dataTable := range dataTables { - expectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Executing "COPY %s`, dataTable) + expectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Writing data for table %s to file`, dataTable) Expect(stdout).To(ContainSubstring(expectedString)) } @@ -346,7 +346,7 @@ var _ = Describe("Deadlock handling", func() { // Only the main worker thread, worker 0, will run COPY on all the test tables for _, dataTable := range dataTables { - expectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Executing "COPY %s`, dataTable) + expectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Writing data for table %s to file`, dataTable) Expect(stdout).To(ContainSubstring(expectedString)) } @@ -507,11 +507,11 @@ var _ = Describe("Deadlock handling", func() { // Only the main worker thread, worker 0, will run COPY on the 2 locked test tables for _, lockedTable := range lockedTables { - expectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Executing "COPY %s`, lockedTable) + expectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Writing data for table %s to file`, lockedTable) Expect(stdout).To(ContainSubstring(expectedString)) } for _, dataTable := range dataTables { - unexpectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Executing "COPY %s`, dataTable) + unexpectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Writing data for table %s to file`, dataTable) Expect(stdout).ToNot(ContainSubstring(unexpectedString)) } Expect(stdout).To(ContainSubstring("Backup completed successfully")) From b13a4706ab001bae56efd5dda120bc194afbd9a4 Mon Sep 17 00:00:00 2001 From: woblerr Date: Sat, 28 Nov 2026 10:51:38 +0300 Subject: [PATCH 7/7] Fix ambiguous concatenation in heap hash queries. Implicit casts to text can make concatenation ambiguous on Cloudberry, causing incremental backups to skip heap hashes. --- backup/queries_incremental.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/backup/queries_incremental.go b/backup/queries_incremental.go index a484bb1a..e4708cf1 100644 --- a/backup/queries_incremental.go +++ b/backup/queries_incremental.go @@ -400,7 +400,7 @@ BEGIN IF v_segno = 0 THEN v_path := v_base; ELSE - v_path := v_base || '.' || v_segno; + v_path := v_base || '.' || v_segno::text; END IF; BEGIN @@ -412,7 +412,7 @@ BEGIN IF v_mod >= v_now THEN RETURN ''; END IF; - v_result := v_result || ';' || v_segno || ':' || v_mod::text || '|' || v_size; + v_result := v_result || ';' || v_segno::text || ':' || v_mod::text || '|' || v_size::text; v_segno := v_segno + 1; END LOOP; @@ -649,11 +649,11 @@ func getHeapColumnHashes(connectionPool *dbconn.DBConn) (map[uint32]string, erro FROM column_types ct JOIN type_deps d ON d.typid = ct.typid ), type_defs(typid, def) AS ( - SELECT enumtypid, 'e' || enumtypid::text || ':' || enumsortorder || ':' || enumlabel + SELECT enumtypid, 'e' || enumtypid::text || ':' || enumsortorder::text || ':' || enumlabel::text FROM pg_enum UNION ALL - SELECT t.oid, 'c' || t.oid::text || ':' || ta.attnum || ':' || ta.attname || ':' || ta.atttypid - || ':' || ta.atttypmod || ':' || ta.attisdropped + SELECT t.oid, 'c' || t.oid::text || ':' || ta.attnum::text || ':' || ta.attname::text || ':' || ta.atttypid::text + || ':' || ta.atttypmod::text || ':' || ta.attisdropped::text FROM pg_type t JOIN pg_attribute ta ON ta.attrelid = t.typrelid WHERE t.typtype = 'c' AND ta.attnum > 0 @@ -675,8 +675,8 @@ func getHeapColumnHashes(connectionPool *dbconn.DBConn) (map[uint32]string, erro FROM column_types ct JOIN type_defs td ON td.typid = ct.typid UNION ALL - SELECT ca.attrelid, 'a' || ca.attnum::text || ':' || ca.attname || ':' || ca.atttypid - || ':' || ca.atttypmod || ':' || ca.attisdropped + SELECT ca.attrelid, 'a' || ca.attnum::text || ':' || ca.attname::text || ':' || ca.atttypid::text + || ':' || ca.atttypmod::text || ':' || ca.attisdropped::text FROM pg_attribute ca WHERE ca.attnum > 0 AND ca.attrelid IN (SELECT relid FROM column_types)