PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FIX (physical): Key WAL history rows on parent databases.id to fix cross-timeline PITR (issue #643)
Rostislav Duginf93a6c380e43
diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/create_full_uc.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/create_full_uc.goindex 8b67b777..c1317694 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/create_full_uc.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/create_full_uc.go@@ -72,7 +72,7 @@ func (uc *CreateFullBackupUsecase) Execute(ctx context.Context, spec FullBackupS}validation, valErr := ValidateStartLsnAgainstHistory(- spec.SourceDB.ID,+ spec.SourceDB.ParentDatabaseID(),streamResult.TimelineID,streamResult.StartLSN,spec.HistoryRepo,diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline.goindex af935571..69b9d676 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline.go@@ -83,7 +83,7 @@ func CheckTimelineCompatibility(}, nil}- knownTLI, err := newestKnownTimeline(db.ID, fullRepo, historyRepo)+ knownTLI, err := newestKnownTimeline(db.ParentDatabaseID(), fullRepo, historyRepo)if err != nil {return nil, err}@@ -176,14 +176,16 @@ func UploadHistoryFile(fieldEncryptor util_encryption.FieldEncryptor,logger *slog.Logger,) (*physical_models.PhysicalWalHistoryFile, error) {- existing, err := historyRepo.FindByDatabaseTimeline(db.ID, timelineID)+ databaseID := db.ParentDatabaseID()++ existing, err := historyRepo.FindByDatabaseTimeline(databaseID, timelineID)if err != nil {return nil, fmt.Errorf("query existing history row: %w", err)}if existing != nil {logger.Debug("history file already in catalog",- "database_id", db.ID,+ "database_id", databaseID,"timeline_id", timelineID)return existing, nil@@ -197,7 +199,7 @@ func UploadHistoryFile(}historyFileID := uuid.New()- storageObjectName := fmt.Sprintf("%s-HIST-tl%d.history.zst", db.ID, timelineID)+ storageObjectName := fmt.Sprintf("%s-HIST-tl%d.history.zst", databaseID, timelineID)artifactReader, encryptionSalt, encryptionIV, err := buildHistoryArtifactReader(body, encryption, masterKey, historyFileID,@@ -216,7 +218,7 @@ func UploadHistoryFile(sidecar := physical_dto.PhysicalWalHistoryMetadata{WalHistoryFileID: historyFileID,- DatabaseID: db.ID,+ DatabaseID: databaseID,TimelineID: timelineID,HistoryFilename: historyFilename,CompressedSizeBytes: compressedSizeBytes,@@ -248,7 +250,7 @@ func UploadHistoryFile(row := &physical_models.PhysicalWalHistoryFile{ID: historyFileID,- DatabaseID: db.ID,+ DatabaseID: databaseID,StorageID: storageID,TimelineID: timelineID,FileName: storageObjectName,@@ -260,10 +262,10 @@ func UploadHistoryFile(if err := historyRepo.Insert(row); err != nil {if isUniqueViolation(err) {logger.Debug("history row inserted by concurrent caller",- "database_id", db.ID,+ "database_id", databaseID,"timeline_id", timelineID)- return historyRepo.FindByDatabaseTimeline(db.ID, timelineID)+ return historyRepo.FindByDatabaseTimeline(databaseID, timelineID)}return nil, fmt.Errorf("insert history row: %w", err)diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline_history_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline_history_test.gonew file mode 100644index 00000000..adaee29c--- /dev/null+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline_history_test.go@@ -0,0 +1,96 @@+package usecases_physical_postgresql++import (+ "context"+ "fmt"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ backups_core_enums "databasus-backend/internal/features/backups/backups/core/enums"+ physical_repositories "databasus-backend/internal/features/backups/backups/core/physical/repositories"+ "databasus-backend/internal/util/encryption"+ "databasus-backend/internal/util/logger"+ "databasus-backend/internal/util/walmath"+)++// plantHistoryFileOnSource writes a synthetic .history file into the source+// cluster's pg_wal so UploadHistoryFile's pg_read_binary_file read succeeds —+// timeline 1 never produces a .history file, so without this the upload would+// fail at the read step before reaching the catalog insert under test. The+// shared source PG connects as a superuser, so a server-side COPY ... TO can+// create the file. timelineID is intentionally far above any real promotion+// timeline on the shared container, and there is no SQL to remove a server+// file, but a .history for a nonexistent timeline is inert.+func plantHistoryFileOnSource(t *testing.T, conn *pgx.Conn, timelineID int) {+ t.Helper()++ var dataDir string+ require.NoError(t, conn.QueryRow(context.Background(), "SHOW data_directory").Scan(&dataDir))++ historyPath := fmt.Sprintf("%s/pg_wal/%s", dataDir, walmath.FormatHistoryFilename(uint32(timelineID)))++ _, err := conn.Exec(context.Background(),+ fmt.Sprintf("COPY (SELECT '1'::text) TO '%s'", historyPath))+ require.NoError(t, err)+}++// Test_UploadHistoryFile_KeysRowOnParentDatabaseID asserts the WAL history-file+// catalog row is keyed on the parent databases.id, not the+// postgresql_physical_databases PK. fk_physical_wal_history_files_database_id+// REFERENCES databases(id), so keying on the physical PK fails the insert with+// SQLSTATE 23503 and aborts the WAL-stream supervisor before any segment is+// recorded (issue #643). The two ids are distinct uuids, so the wrong one is+// rejected outright.+func Test_UploadHistoryFile_KeysRowOnParentDatabaseID(t *testing.T) {+ if testing.Short() {+ t.Skip("reads a .history file from the source PG cluster; skipped in -short")+ }++ fixture := SetupPhysicalDBForBackup(t)++ sourceDB := fixture.DB.PostgresqlPhysical+ require.NotEqual(t, fixture.DB.ID, sourceDB.ID,+ "fixture must expose a physical PK distinct from the parent databases.id to exercise the FK")++ const timelineID = 1000++ adminConn := OpenAdminConn(t, fixture)+ plantHistoryFileOnSource(t, adminConn, timelineID)++ conn, err := sourceDB.OpenInspectionConn(t.Context(), encryption.GetFieldEncryptor())+ require.NoError(t, err)+ t.Cleanup(func() { _ = conn.Close(context.Background()) })++ historyRepo := physical_repositories.GetWalHistoryRepository()++ row, err := UploadHistoryFile(+ t.Context(),+ conn,+ timelineID,+ newMockWalStorage(),+ sourceDB,+ fixture.Storage.ID,+ historyRepo,+ backups_core_enums.BackupEncryptionNone,+ "",+ encryption.GetFieldEncryptor(),+ logger.GetLogger(),+ )+ require.NoError(t, err, "history insert must not violate fk_physical_wal_history_files_database_id")+ require.NotNil(t, row)+ t.Cleanup(func() { _ = historyRepo.DeleteByID(row.ID) })++ assert.Equal(t, fixture.DB.ID, row.DatabaseID,+ "history row must be keyed on the parent databases.id, not the physical PK")++ byParent, err := historyRepo.FindByDatabaseTimeline(fixture.DB.ID, timelineID)+ require.NoError(t, err)+ require.NotNil(t, byParent, "history row must be findable by the parent databases.id (chain assembly reads by it)")++ byPhysicalPK, err := historyRepo.FindByDatabaseTimeline(sourceDB.ID, timelineID)+ require.NoError(t, err)+ assert.Nil(t, byPhysicalPK, "history row must not be keyed on the physical PK")+}diff --git a/backend/internal/features/databases/databases/postgresql/physical/model.go b/backend/internal/features/databases/databases/postgresql/physical/model.goindex a6d52814..73829094 100644--- a/backend/internal/features/databases/databases/postgresql/physical/model.go+++ b/backend/internal/features/databases/databases/postgresql/physical/model.go@@ -219,6 +219,20 @@ func (p *PostgresqlPhysicalDatabase) PopulateDbData(return nil}+// ParentDatabaseID returns the parent databases.id this physical record hangs+// off — the target of every physical catalog FK (fk_physical_wal_*_database_id,+// fk_physical_full_backups_database_id, …), never the+// postgresql_physical_databases PK. The fallback to ID covers an unassociated+// in-memory row whose DatabaseID was not loaded, mirroring+// receivewalApplicationName's fallback.+func (p *PostgresqlPhysicalDatabase) ParentDatabaseID() uuid.UUID {+ if p.DatabaseID != nil {+ return *p.DatabaseID+ }++ return p.ID+}+func (p *PostgresqlPhysicalDatabase) SystemIdentifierUint64() uint64 {if p.SystemIdentifier == nil {return 0