PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FIX (backups): Probe summarizer liveness instead of WAL-since-checkpoint lag (issue #756)
Rostislav Dugin1f8382d39947
diff --git a/backend/internal/features/backups/backups/backuping/physical/backuper.go b/backend/internal/features/backups/backups/backuping/physical/backuper.goindex 8704e0e9..7e23da18 100644--- a/backend/internal/features/backups/backups/backuping/physical/backuper.go+++ b/backend/internal/features/backups/backups/backuping/physical/backuper.go@@ -233,6 +233,11 @@ func (b *PhysicalBackuper) runIncrementalBackup(return}+ if backupResult.Status == physical_enums.PhysicalBackupStatusError &&+ b.isIncrRetryBudgetExhausted(ctx, logger, incrBackup) {+ backupResult.Status = physical_enums.PhysicalBackupStatusChainBroken+ }+if backupResult.Status != physical_enums.PhysicalBackupStatusCompleted {logger.WarnContext(ctx, "incremental executor returned non-COMPLETED result","status", backupResult.Status,@@ -506,6 +511,45 @@ func (b *PhysicalBackuper) persistIncrResult()}+// The current attempt's row is already IN_PROGRESS in the table (claimAndInsert+// writes it before the backuper runs), so it is dropped before counting.+// Requiring the exact remaining count matters: on a young chain a shorter slice+// would make "every one of them failed" vacuously true and close the chain an+// attempt early. A read failure answers false, because losing a chain to a+// transient database error is worse than granting one retry too many.+//+// Only the executor-result path asks this. The pre-executor finalize paths stay+// plain ERROR deliberately: they return before any notification is sent, and a+// chain that closes without telling anyone is worse than one that closes an+// attempt late.+func (b *PhysicalBackuper) isIncrRetryBudgetExhausted(+ ctx context.Context,+ logger *slog.Logger,+ incrBackup *physical_models.PhysicalIncrementalBackup,+) bool {+ recentBackups, err := b.incrRepo.FindNewestAnyStatusByRootFull(+ incrBackup.RootFullBackupID, maxConsecutiveFailedIncrTries)+ if err != nil {+ logger.ErrorContext(ctx, "failed to read the chain's recent incrementals", "error", err)++ return false+ }++ priorBackups := slices.DeleteFunc(recentBackups,+ func(backup *physical_models.PhysicalIncrementalBackup) bool {+ return backup.ID == incrBackup.ID+ })++ if len(priorBackups) != maxConsecutiveFailedIncrTries-1 {+ return false+ }++ return !slices.ContainsFunc(priorBackups,+ func(backup *physical_models.PhysicalIncrementalBackup) bool {+ return backup.Status != physical_enums.PhysicalBackupStatusError+ })+}+// saveTerminalResultIfInProgress writes the mutated backup row and releases its// in-flight claim in one transaction, but only while the row is still// IN_PROGRESS. A backuper can return after a restart-recovery sweep already@@ -590,10 +634,11 @@ func (b *PhysicalBackuper) finalizeIncrAsError(}// finalizeIncrAsChainBroken closes the chain instead of marking a transient-// failure. Use it only for irreversible conditions (a missing parent manifest,-// expired summaries) where retrying the same INCR is futile: CHAIN_BROKEN forces-// the next scheduler tick to open a fresh FULL, whereas ERROR would keep the-// chain extendable and retry the doomed INCR forever.+// failure. Use it for irreversible conditions (a missing parent manifest,+// expired summaries) where retrying the same INCR is futile: CHAIN_BROKEN makes+// the scheduler re-anchor on a fresh FULL, whereas ERROR would keep the chain+// extendable and retry the doomed INCR forever. A run of maxConsecutiveFailedIncrTries+// ordinary failures reaches the same verdict through isIncrRetryBudgetExhausted.func (b *PhysicalBackuper) finalizeIncrAsChainBroken(incrBackup *physical_models.PhysicalIncrementalBackup,reason physical_enums.PhysicalBackupErrorReason,diff --git a/backend/internal/features/backups/backups/backuping/physical/backuper_test.go b/backend/internal/features/backups/backups/backuping/physical/backuper_test.goindex 2c450627..116d5f0d 100644--- a/backend/internal/features/backups/backups/backuping/physical/backuper_test.go+++ b/backend/internal/features/backups/backups/backuping/physical/backuper_test.go@@ -693,6 +693,70 @@ func Test_RunIncrementalBackup_WhenExecutorResultErrorStatus_PersistsErrorAndSenassert.Equal(t, notifier_models.NotificationTypeBackupFailed, sender.sentNotifications[0].Notification.Type)}+func Test_RunIncrementalBackup_WhenSecondConsecutiveFailure_KeepsChainExtendable(t *testing.T) {+ prereqs := seedBackupPrereqs(t)+ backuper := CreateTestPhysicalBackuper(&recordingNotificationSender{})+ _, incrExecutor := installFakeExecutors(backuper)+ incrExecutor.result = erroredResult()++ rootFull := seedCompletedRootFull(t, prereqs)+ seedIncrWithStatusAndAge(t, prereqs, rootFull.ID, physical_enums.PhysicalBackupStatusError, 2, 2)+ incrBackup := seedInProgressIncr(t, prereqs, rootFull.ID)++ backuper.MakeBackup(t.Context(), incrBackup.ID, true)++ persisted, err := physical_repositories.GetIncrementalBackupRepository().FindByID(incrBackup.ID)+ require.NoError(t, err)+ assert.Equal(t, physical_enums.PhysicalBackupStatusError, persisted.Status,+ "the budget is three attempts, so the second failure must leave the chain extendable")+}++func Test_RunIncrementalBackup_WhenRetryBudgetExhausted_BreaksChainKeepingErrorReason(t *testing.T) {+ prereqs := seedBackupPrereqs(t)+ sender := &recordingNotificationSender{}+ backuper := CreateTestPhysicalBackuper(sender)+ _, incrExecutor := installFakeExecutors(backuper)+ incrExecutor.result = erroredResult()++ rootFull := seedCompletedRootFull(t, prereqs)+ seedIncrWithStatusAndAge(t, prereqs, rootFull.ID, physical_enums.PhysicalBackupStatusError, 2, 3)+ seedIncrWithStatusAndAge(t, prereqs, rootFull.ID, physical_enums.PhysicalBackupStatusError, 3, 2)+ incrBackup := seedInProgressIncr(t, prereqs, rootFull.ID)++ backuper.MakeBackup(t.Context(), incrBackup.ID, true)++ persisted, err := physical_repositories.GetIncrementalBackupRepository().FindByID(incrBackup.ID)+ require.NoError(t, err)+ assert.Equal(t, physical_enums.PhysicalBackupStatusChainBroken, persisted.Status)+ require.NotNil(t, persisted.ErrorReason)+ assert.Equal(t, physical_enums.PhysicalBackupErrorPgBasebackupFailed, *persisted.ErrorReason,+ "the operator still needs to see what actually failed, not just that the chain closed")++ require.Len(t, sender.sentNotifications, 1)+ assert.Contains(t, sender.sentNotifications[0].Notification.Heading, "chain-broken",+ "the row and the notification must agree on the verdict")+}++func Test_RunIncrementalBackup_WhenCompletedBackupSeparatesFailures_KeepsChainExtendable(t *testing.T) {+ prereqs := seedBackupPrereqs(t)+ backuper := CreateTestPhysicalBackuper(&recordingNotificationSender{})+ _, incrExecutor := installFakeExecutors(backuper)+ incrExecutor.result = erroredResult()++ rootFull := seedCompletedRootFull(t, prereqs)+ seedIncrWithStatusAndAge(t, prereqs, rootFull.ID, physical_enums.PhysicalBackupStatusError, 2, 4)+ seedIncrWithStatusAndAge(t, prereqs, rootFull.ID, physical_enums.PhysicalBackupStatusCompleted, 3, 3)+ seedIncrWithStatusAndAge(t, prereqs, rootFull.ID, physical_enums.PhysicalBackupStatusError, 4, 2)+ incrBackup := seedInProgressIncr(t, prereqs, rootFull.ID)++ backuper.MakeBackup(t.Context(), incrBackup.ID, true)++ persisted, err := physical_repositories.GetIncrementalBackupRepository().FindByID(incrBackup.ID)+ require.NoError(t, err)+ assert.Equal(t, physical_enums.PhysicalBackupStatusError, persisted.Status,+ "a COMPLETED backup between failures ends the run, so the budget is not spent")+}+func Test_ReleaseOwned_WhenForeignBackupHoldsClaim_LeavesItIntact(t *testing.T) {prereqs := seedBackupPrereqs(t)inFlightRepo := physical_repositories.GetInFlightBackupRepository()diff --git a/backend/internal/features/backups/backups/backuping/physical/constants.go b/backend/internal/features/backups/backups/backuping/physical/constants.goindex db1496b1..0800a970 100644--- a/backend/internal/features/backups/backups/backuping/physical/constants.go+++ b/backend/internal/features/backups/backups/backuping/physical/constants.go@@ -77,3 +77,12 @@ const minWalDeleteBudgetMB float64 = 256// Conservative fallback floor in cleaner grace logic, mirroring logical's// 60-minute floor on individual backups.const recentBackupGracePeriod = 60 * time.Minute++// A chain that fails this many INCR attempts in a row is not recovering on its+// own: close it so a fresh FULL re-anchors instead of retrying every cadence+// tick forever. Mirrors the logical scheduler's default MaxFailedTriesCount.+const maxConsecutiveFailedIncrTries = 3++// How many of the newest FULL attempts the re-anchor brake weighs. None of them+// completing means the source, not the chain, is what needs attention.+const recentFullAttemptsWindow = 3diff --git a/backend/internal/features/backups/backups/backuping/physical/scheduler.go b/backend/internal/features/backups/backups/backuping/physical/scheduler.goindex 75c795a2..b901f6ff 100644--- a/backend/internal/features/backups/backups/backuping/physical/scheduler.go+++ b/backend/internal/features/backups/backups/backuping/physical/scheduler.go@@ -4,6 +4,7 @@ import ("context""fmt""log/slog"+ "slices""sync/atomic""time"@@ -30,7 +31,9 @@ import (// - ERROR: the chain stays extendable, so the next cadence-due tick re-attempts// the SAME kind. A freshly-failed attempt is the newest row of its kind, so// the cadence check on its created_at prevents a tight retry loop.-// - CHAIN_BROKEN: no extendable chain remains, so the next tick opens a new FULL.+// - CHAIN_BROKEN: nothing is left to extend, so the incremental cadence re-anchors+// with a new FULL rather than the tick going idle until the FULL cadence, unless+// the source produced no completed FULL recently.// - CANCELED: neither COMPLETED nor CHAIN_BROKEN; the chain it belonged to stays// extendable and resumes on cadence — no immediate auto-retry.type PhysicalBackupsScheduler struct {@@ -155,12 +158,9 @@ type backupDecision struct {forceIncrementalRequestedAt *time.Time}-// decideBackupKind picks FULL or INCR purely from catalog state + cadence (no-// source-PG connection): FULL when its interval is due (covers bootstrap, chain-// rotation, and post-CHAIN_BROKEN re-anchor since no extendable chain exists);-// INCR when incrementals are enabled, an extendable chain exists, and the INCR-// interval is due. The shipped executors handle summarizer/timeline reality at-// run time, returning CHAIN_BROKEN when an INCR cannot actually proceed.+// decideBackupKind picks FULL or INCR purely from catalog state and cadence, with+// no source-PG connection: the shipped executors handle summarizer and timeline+// reality at run time.func (s *PhysicalBackupsScheduler) decideBackupKind(logger *slog.Logger,now time.Time,@@ -216,18 +216,16 @@ func (s *PhysicalBackupsScheduler) decideBackupKind(lastBackupTime := newestCreatedAt(lastFull, lastIncr)- if extendableChain == nil {- logger.Debug("nothing due: no extendable chain to add an incremental to")-- return backupDecision{}, false- }-if !backupConfig.IncrementalBackupInterval.ShouldTriggerBackup(now, lastBackupTime) {logger.Debug("nothing due: neither cadence has elapsed")return backupDecision{}, false}+ if extendableChain == nil {+ return s.decideReAnchoringFull(logger, backupConfig, lastIncr)+ }+parentIncrID, err := s.resolveIncrParent(extendableChain.RootFull.ID)if err != nil {logger.Error("failed to resolve incremental parent", "error", err)@@ -598,6 +596,72 @@ func newestCreatedAt(}}+// decideReAnchoringFull answers the incremental cadence when no chain is left to+// extend. Waiting for the FULL cadence instead would leave the database without+// new restore points for a whole FULL interval, which on a weekly FULL is a week.+// Two exceptions fall back to that wait anyway: a chain broken by SUMMARIZER_OFF+// (a fresh FULL cannot fix a server-side setting, so re-anchoring at incremental+// speed would just alternate full backups with broken incrementals forever) and+// a source that produced no completed FULL in its newest few attempts (the+// cluster is broken rather than merely chainless, and re-anchoring it at+// incremental speed only burns it).+func (s *PhysicalBackupsScheduler) decideReAnchoringFull(+ logger *slog.Logger,+ backupConfig *backups_config_physical.PhysicalBackupConfig,+ lastIncr *physical_models.PhysicalIncrementalBackup,+) (backupDecision, bool) {+ if isChainBrokenBySummarizerOff(lastIncr) {+ logger.Debug("nothing due: chain broken by summarizer off, which a fresh FULL cannot fix")++ return backupDecision{}, false+ }++ recentFullBackups, err := s.fullRepo.FindNewestAnyStatusByDatabase(+ backupConfig.DatabaseID, recentFullAttemptsWindow)+ if err != nil {+ logger.Error("failed to find recent full backups", "error", err)++ return backupDecision{}, false+ }++ if hasNoRecentCompletedFull(recentFullBackups) {+ logger.Debug(fmt.Sprintf(+ "nothing due: no extendable chain and no completed full among the newest %d",+ recentFullAttemptsWindow))++ return backupDecision{}, false+ }++ return backupDecision{+ kind: physical_enums.PhysicalBackupTypeFull,+ reason: "re-anchoring: no extendable chain",+ }, true+}++// The newest incremental row is the right witness: any completed INCR after it+// would have kept the chain extendable, so this branch would not run at all.+// Once the operator re-enables summarize_wal, incrementals resume with the next+// FULL on its own cadence (or a forced FULL), because the scheduler reads only+// the catalog and never sees the live GUC.+func isChainBrokenBySummarizerOff(lastIncr *physical_models.PhysicalIncrementalBackup) bool {+ return lastIncr != nil &&+ lastIncr.Status == physical_enums.PhysicalBackupStatusChainBroken &&+ lastIncr.ErrorReason != nil &&+ *lastIncr.ErrorReason == physical_enums.PhysicalBackupErrorSummarizerOff+}++// Asking for a completed FULL rather than counting failures also weighs cancels:+// a source whose newest attempts all failed or were cancelled has produced+// nothing to anchor on. A single cancel among completed neighbours does not+// engage the brake, matching the CANCELED policy of resuming on cadence. An empty history+// answers true, which only ever means "wait", never "hammer the source".+func hasNoRecentCompletedFull(recentFullBackups []*physical_models.PhysicalFullBackup) bool {+ return !slices.ContainsFunc(recentFullBackups,+ func(fullBackup *physical_models.PhysicalFullBackup) bool {+ return fullBackup.Status == physical_enums.PhysicalBackupStatusCompleted+ })+}+func isIncrementalEnabled(backupConfig *backups_config_physical.PhysicalBackupConfig) bool {if backupConfig.PostgresqlPhysical == nil {return falsediff --git a/backend/internal/features/backups/backups/backuping/physical/scheduler_test.go b/backend/internal/features/backups/backups/backuping/physical/scheduler_test.goindex db8829bb..cad6efe2 100644--- a/backend/internal/features/backups/backups/backuping/physical/scheduler_test.go+++ b/backend/internal/features/backups/backups/backuping/physical/scheduler_test.go@@ -156,7 +156,7 @@ func Test_DecideBackupKind_WhenChainBrokenAndFullCadenceDue_ReAnchorsWithFull(t"a CHAIN_BROKEN chain re-anchors with a new FULL, never an INCR")}-func Test_DecideBackupKind_WhenChainBrokenAndIncrDueButFullNotDue_SchedulesNothing(t *testing.T) {+func Test_DecideBackupKind_WhenChainBrokenAndIncrDueButFullNotDue_ReAnchorsWithFull(t *testing.T) {prereqs := seedBackupPrereqs(t)makeIncrementalDue(prereqs) // full weekly (not due), incr hourlyfull := seedFullWithStatusAndAge(t, prereqs, physical_enums.PhysicalBackupStatusCompleted, 1, 3)@@ -164,9 +164,81 @@ func Test_DecideBackupKind_WhenChainBrokenAndIncrDueButFullNotDue_SchedulesNothischeduler := CreateTestPhysicalScheduler()+ decision, ok := scheduler.decideBackupKind(logger.GetLogger(), time.Now().UTC(), prereqs.Config)++ require.True(t, ok)+ assert.Equal(t, physical_enums.PhysicalBackupTypeFull, decision.kind,+ "a broken chain re-anchors on the incremental cadence instead of idling until the full one")+}++func Test_DecideBackupKind_WhenChainBrokenAndRecentFullsAllErrored_SchedulesNothing(t *testing.T) {+ prereqs := seedBackupPrereqs(t)+ makeIncrementalDue(prereqs)+ rootFull := seedFullWithStatusAndAge(t, prereqs, physical_enums.PhysicalBackupStatusCompleted, 1, 10)+ seedIncrWithStatusAndAge(t, prereqs, rootFull.ID, physical_enums.PhysicalBackupStatusChainBroken, 2, 9)++ for index := range recentFullAttemptsWindow {+ seedFullWithStatusAndAge(t, prereqs, physical_enums.PhysicalBackupStatusError, 3+index, 4-index)+ }++ scheduler := CreateTestPhysicalScheduler()++ _, ok := scheduler.decideBackupKind(logger.GetLogger(), time.Now().UTC(), prereqs.Config)++ assert.False(t, ok,+ "a source whose recent fulls all failed is broken itself; re-anchoring at incr speed only burns it")+}++func Test_DecideBackupKind_WhenChainBrokenAndRecentFullsCanceled_SchedulesNothing(t *testing.T) {+ prereqs := seedBackupPrereqs(t)+ makeIncrementalDue(prereqs)+ rootFull := seedFullWithStatusAndAge(t, prereqs, physical_enums.PhysicalBackupStatusCompleted, 1, 10)+ seedIncrWithStatusAndAge(t, prereqs, rootFull.ID, physical_enums.PhysicalBackupStatusChainBroken, 2, 9)++ for index := range recentFullAttemptsWindow {+ seedFullWithStatusAndAge(t, prereqs, physical_enums.PhysicalBackupStatusCanceled, 3+index, 4-index)+ }++ scheduler := CreateTestPhysicalScheduler()++ _, ok := scheduler.decideBackupKind(logger.GetLogger(), time.Now().UTC(), prereqs.Config)++ assert.False(t, ok, "a user who keeps cancelling fulls must not have one restarted on the incr cadence")+}++func Test_DecideBackupKind_WhenChainBrokenAndOneFullErrored_ReAnchorsWithFull(t *testing.T) {+ prereqs := seedBackupPrereqs(t)+ makeIncrementalDue(prereqs)+ rootFull := seedFullWithStatusAndAge(t, prereqs, physical_enums.PhysicalBackupStatusCompleted, 1, 10)+ seedIncrWithStatusAndAge(t, prereqs, rootFull.ID, physical_enums.PhysicalBackupStatusChainBroken, 2, 9)+ seedFullWithStatusAndAge(t, prereqs, physical_enums.PhysicalBackupStatusError, 3, 2)++ scheduler := CreateTestPhysicalScheduler()++ decision, ok := scheduler.decideBackupKind(logger.GetLogger(), time.Now().UTC(), prereqs.Config)++ require.True(t, ok)+ assert.Equal(t, physical_enums.PhysicalBackupTypeFull, decision.kind,+ "one failed full is not a broken source, so the re-anchor still goes ahead")+}++func Test_DecideBackupKind_WhenChainBrokenBySummarizerOff_WaitsForFullCadence(t *testing.T) {+ prereqs := seedBackupPrereqs(t)+ makeIncrementalDue(prereqs)+ rootFull := seedFullWithStatusAndAge(t, prereqs, physical_enums.PhysicalBackupStatusCompleted, 1, 10)++ brokenIncr := seedIncrWithStatusAndAge(t, prereqs, rootFull.ID,+ physical_enums.PhysicalBackupStatusChainBroken, 2, 9)+ summarizerOff := physical_enums.PhysicalBackupErrorSummarizerOff+ brokenIncr.ErrorReason = &summarizerOff+ require.NoError(t, storage.GetDb().Save(brokenIncr).Error)++ scheduler := CreateTestPhysicalScheduler()+_, ok := scheduler.decideBackupKind(logger.GetLogger(), time.Now().UTC(), prereqs.Config)- assert.False(t, ok, "a broken chain never spawns an INCR; it waits for the FULL cadence")+ assert.False(t, ok,+ "a fresh FULL cannot fix summarize_wal being off, so re-anchoring would loop full backups forever")}func Test_DecideBackupKind_WhenCanceledIncrRecent_SchedulesNothing(t *testing.T) {diff --git a/backend/internal/features/backups/backups/core/physical/enums/enums.go b/backend/internal/features/backups/backups/core/physical/enums/enums.goindex 33b57ef8..f537a4af 100644--- a/backend/internal/features/backups/backups/core/physical/enums/enums.go+++ b/backend/internal/features/backups/backups/core/physical/enums/enums.go@@ -52,15 +52,15 @@ const (// between the CANCEL and the DROP.PhysicalBackupErrorCanceledByDbRemoval PhysicalBackupErrorReason = "CANCELED_BY_DB_REMOVAL"- // INCR-specific (all chain-killing, status = CHAIN_BROKEN).+ // INCR-specific and chain-killing (status = CHAIN_BROKEN).PhysicalBackupErrorSummariesExpired PhysicalBackupErrorReason = "SUMMARIES_EXPIRED"PhysicalBackupErrorSummarizerOff PhysicalBackupErrorReason = "SUMMARIZER_OFF"PhysicalBackupErrorParentManifestMissing PhysicalBackupErrorReason = "PARENT_MANIFEST_MISSING"- // The summarizer is on and covers the parent, but trails current WAL by- // more than the lag threshold (or stayed behind for the whole bounded- // wait): pushing an INCR would race a moving target, so the chain is closed- // and the next tick opens a fresh FULL.+ // INCR-specific and transient (status = ERROR): the summarizer is on and+ // covers the parent, but its process is not publishing summaries. The chain+ // stays extendable and the next cadence tick retries it; only a run of+ // consecutive failures closes the chain.PhysicalBackupErrorSummarizerFallingBehind PhysicalBackupErrorReason = "SUMMARIZER_FALLING_BEHIND")diff --git a/backend/internal/features/backups/backups/core/physical/repositories/full_backup_repository.go b/backend/internal/features/backups/backups/core/physical/repositories/full_backup_repository.goindex 16a62503..21c73f8b 100644--- a/backend/internal/features/backups/backups/core/physical/repositories/full_backup_repository.go+++ b/backend/internal/features/backups/backups/core/physical/repositories/full_backup_repository.go@@ -113,25 +113,37 @@ func (r *PhysicalFullBackupRepository) DeleteByID(id uuid.UUID) error {return storage.GetDb().Delete(&physical_models.PhysicalFullBackup{}, "id = ?", id).Error}-func (r *PhysicalFullBackupRepository) FindLastFullAnyStatusByDatabase(+func (r *PhysicalFullBackupRepository) FindNewestAnyStatusByDatabase(databaseID uuid.UUID,-) (*physical_models.PhysicalFullBackup, error) {- var backup physical_models.PhysicalFullBackup+ limit int,+) ([]*physical_models.PhysicalFullBackup, error) {+ var backups []*physical_models.PhysicalFullBackup- err := storage.+ if err := storage.GetDb().Where("database_id = ?", databaseID).Order("created_at DESC").- First(&backup).Error- if err != nil {- if errors.Is(err, gorm.ErrRecordNotFound) {- return nil, nil- }+ Limit(limit).+ Find(&backups).Error; err != nil {+ return nil, err+ }++ return backups, nil+}+func (r *PhysicalFullBackupRepository) FindLastFullAnyStatusByDatabase(+ databaseID uuid.UUID,+) (*physical_models.PhysicalFullBackup, error) {+ backups, err := r.FindNewestAnyStatusByDatabase(databaseID, 1)+ if err != nil {return nil, err}- return &backup, nil+ if len(backups) == 0 {+ return nil, nil+ }++ return backups[0], nil}func (r *PhysicalFullBackupRepository) FindAllInProgress() ([]*physical_models.PhysicalFullBackup, error) {diff --git a/backend/internal/features/backups/backups/core/physical/repositories/incremental_backup_repository.go b/backend/internal/features/backups/backups/core/physical/repositories/incremental_backup_repository.goindex e2ad0114..519411ef 100644--- a/backend/internal/features/backups/backups/core/physical/repositories/incremental_backup_repository.go+++ b/backend/internal/features/backups/backups/core/physical/repositories/incremental_backup_repository.go@@ -74,6 +74,27 @@ func (r *PhysicalIncrementalBackupRepository) FindLatestCompletedByRootFull(return &backup, nil}+// FindNewestAnyStatusByRootFull orders by created_at rather than start_lsn+// because failed attempts never get one: persistIncrResult writes LSNs only for+// COMPLETED rows.+func (r *PhysicalIncrementalBackupRepository) FindNewestAnyStatusByRootFull(+ rootFullBackupID uuid.UUID,+ limit int,+) ([]*physical_models.PhysicalIncrementalBackup, error) {+ var backups []*physical_models.PhysicalIncrementalBackup++ if err := storage.+ GetDb().+ Where("root_full_backup_id = ?", rootFullBackupID).+ Order("created_at DESC").+ Limit(limit).+ Find(&backups).Error; err != nil {+ return nil, err+ }++ return backups, nil+}+func (r *PhysicalIncrementalBackupRepository) FindAllByRootFull(rootFullBackupID uuid.UUID,) ([]*physical_models.PhysicalIncrementalBackup, error) {diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/byte_stall.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/byte_stall.goindex 12b3efb3..deaf95fe 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/byte_stall.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/byte_stall.go@@ -10,14 +10,23 @@ import ("time")-// ByteStallTimeout bounds how long pg_basebackup may make zero progress before-// the watcher tears it down. Kernel-pipe back pressure means a healthy slow+// ByteStallTimeout bounds how long pg_basebackup may make zero progress after+// its first byte before the watcher tears it down. Kernel-pipe back pressure means a healthy slow// storage still ticks bytes forward; zero bytes for this long is a stuck TCP// connection (mid-write NAT timeout, silently-dropped firewall) that// pg_basebackup's own session-level keepalives won't notice for tens of// minutes.const ByteStallTimeout = 60 * time.Second+// FirstByteTimeout bounds the silent stretch before pg_basebackup's first+// byte. The server spends it inside backup start: the forced checkpoint and,+// for incrementals, the wait for WAL summarization — both legitimately run for+// minutes on a large busy cluster, and PostgreSQL already aborts that wait+// itself when summarization makes no progress, so this watchdog must not be+// stricter than the server's own. The cost: a connection dead from the very+// start is detected in minutes rather than in ByteStallTimeout.+const FirstByteTimeout = 10 * time.Minute+// byteStallPollInterval — the watcher reads BytesWritten on this cadence.// Tight enough that we detect a stall within ~10 s of crossing the timeout,// cheap enough that we don't add measurable CPU during a multi-hour backup.@@ -55,14 +64,22 @@ func (b *ByteCounter) BytesWritten() int64 {return b.bytes.Load()}+// ByteStallThresholds separates the budget for reaching the first byte from+// the steady-state stall budget; see FirstByteTimeout for why the two differ.+type ByteStallThresholds struct {+ FirstByteTimeout time.Duration+ StallTimeout time.Duration+}+// WithByteStallWatcher polls counter.BytesWritten on a fixed interval and-// invokes onStall when no bytes have moved for stallTimeout. The returned-// stop function tears down the watcher; the caller defers it on the+// invokes onStall when no bytes have moved for the applicable threshold:+// FirstByteTimeout while no byte has arrived yet, StallTimeout afterwards. The+// returned stop function tears down the watcher; the caller defers it on the// success path so the watcher does not outlive the executor.func WithByteStallWatcher(ctx context.Context,counter *ByteCounter,- stallTimeout time.Duration,+ thresholds ByteStallThresholds,onStall func(),) (stop func()) {watcherCtx, cancel := context.WithCancel(ctx)@@ -91,7 +108,12 @@ func WithByteStallWatcher(continue}- if now.Sub(lastProgressAt) > stallTimeout {+ stallBudget := thresholds.StallTimeout+ if current == 0 {+ stallBudget = thresholds.FirstByteTimeout+ }++ if now.Sub(lastProgressAt) > stallBudget {onStall()returndiff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/byte_stall_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/byte_stall_test.gonew file mode 100644index 00000000..7ddc7bf8--- /dev/null+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/byte_stall_test.go@@ -0,0 +1,70 @@+package usecases_physical_postgresql++import (+ "bytes"+ "sync/atomic"+ "testing"+ "time"++ "github.com/stretchr/testify/require"+)++// The watcher polls on byteStallPollInterval (10 s), so each test below spends a+// real tick or two. The thresholds are picked around that tick rather than+// stubbing it: the poll cadence is part of the behaviour under test.++func Test_ByteStallWatcher_WhenNoBytesBeforeFirstByteTimeout_DoesNotTrip(t *testing.T) {+ counter := NewByteCounter(&bytes.Buffer{})++ var isStalled atomic.Bool++ stopWatcher := WithByteStallWatcher(t.Context(), counter, ByteStallThresholds{+ FirstByteTimeout: time.Hour,+ StallTimeout: time.Millisecond,+ }, func() { isStalled.Store(true) })+ defer stopWatcher()++ time.Sleep(byteStallPollInterval + 2*time.Second)++ require.False(t, isStalled.Load(),+ "zero bytes within the first-byte budget must not trip, even long past the steady-state budget")+}++func Test_ByteStallWatcher_WhenFirstByteTimeoutExceeded_Trips(t *testing.T) {+ counter := NewByteCounter(&bytes.Buffer{})++ stalled := make(chan struct{})++ stopWatcher := WithByteStallWatcher(t.Context(), counter, ByteStallThresholds{+ FirstByteTimeout: time.Millisecond,+ StallTimeout: time.Hour,+ }, func() { close(stalled) })+ defer stopWatcher()++ select {+ case <-stalled:+ case <-time.After(byteStallPollInterval + 5*time.Second):+ t.Fatal("watcher did not trip after the first-byte budget elapsed with zero bytes")+ }+}++func Test_ByteStallWatcher_WhenStallAfterFirstByte_TripsOnStallTimeout(t *testing.T) {+ counter := NewByteCounter(&bytes.Buffer{})++ _, err := counter.Write([]byte("x"))+ require.NoError(t, err)++ stalled := make(chan struct{})++ stopWatcher := WithByteStallWatcher(t.Context(), counter, ByteStallThresholds{+ FirstByteTimeout: time.Hour,+ StallTimeout: time.Millisecond,+ }, func() { close(stalled) })+ defer stopWatcher()++ select {+ case <-stalled:+ case <-time.After(byteStallPollInterval + 5*time.Second):+ t.Fatal("the first-byte leniency must end with the first byte, not extend the steady-state budget")+ }+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/create_incremental_uc.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/create_incremental_uc.goindex cccabef4..2848b943 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/create_incremental_uc.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/create_incremental_uc.go@@ -48,11 +48,10 @@ func (uc *CreateIncrementalBackupUsecase) Execute(return refusalResult, nil}- // Gate on WAL-summarizer readiness BEFORE any work: a doomed- // pg_basebackup --incremental (summarizer off / summaries expired / falling- // behind) is turned into a deterministic CHAIN_BROKEN here, so the next- // scheduler tick re-anchors on a fresh FULL instead of looping transient- // ERRORs. Runs before the parent-manifest download so a bail costs nothing.+ // Gate on WAL-summarizer readiness BEFORE any work: summarizer off and expired+ // summaries are conditions no retry can fix, so they close the chain here rather+ // than after a doomed pg_basebackup --incremental. Runs before the+ // parent-manifest download so a bail costs nothing.preCheckResult, canProceed := runSummarizerPreCheck(ctx, spec)if !canProceed {return preCheckResult, nil@@ -156,13 +155,13 @@ func verifyIncrTimelineCompatibility(}// runSummarizerPreCheck opens an inspection connection and resolves the-// WAL-summarizer decision (including the bounded wait for a lagging-but-catching-up-// summarizer). It returns proceed=true to run the incremental, or a terminal-// result the caller must return verbatim:-// - DecisionGoIncremental → proceed-// - DecisionFullSameChain / wait timeout → CHAIN_BROKEN / SUMMARIZER_FALLING_BEHIND-// - DecisionFullNewChain → CHAIN_BROKEN / SUMMARIZER_OFF | SUMMARIES_EXPIRED-// - ctx cancelled mid-wait → CANCELED / CANCELED_BY_USER+// WAL-summarizer decision (including the bounded wait for a summarizer that has+// published no summary yet). It returns proceed=true to run the incremental, or+// a terminal result the caller must return verbatim:+// - DecisionGoIncremental → proceed+// - DecisionRetryNextCadence → ERROR / SUMMARIZER_FALLING_BEHIND+// - DecisionFullNewChain → CHAIN_BROKEN / SUMMARIZER_OFF | SUMMARIES_EXPIRED+// - ctx cancelled mid-wait → CANCELED / CANCELED_BY_USERfunc runSummarizerPreCheck(ctx context.Context, spec IncrementalBackupSpec) (PhysicalBackupResult, bool) {conn, err := spec.SourceDB.OpenInspectionConn(ctx, spec.FieldEncryptor)if err != nil {@@ -185,22 +184,29 @@ func runSummarizerPreCheck(ctx context.Context, spec IncrementalBackupSpec) (Phycase DecisionGoIncremental:return PhysicalBackupResult{}, true- case DecisionFullSameChain:- return summarizerChainBroken(physical_enums.PhysicalBackupErrorSummarizerFallingBehind,- "summarizer trailing current WAL; closing chain, new FULL required"), false+ case DecisionRetryNextCadence:+ return summarizerRefusedResult(+ physical_enums.PhysicalBackupStatusError,+ physical_enums.PhysicalBackupErrorSummarizerFallingBehind,+ "WAL summarizer is not publishing summaries (none yet, or its process is gone); retrying on the next cadence",+ ), falsedefault: // DecisionFullNewChain — Reason is always set on this branch- return summarizerChainBroken(*decision.Reason,- "summarizer pre-check refused incremental; new FULL required"), false+ return summarizerRefusedResult(+ physical_enums.PhysicalBackupStatusChainBroken,+ *decision.Reason,+ "summarizer pre-check refused incremental; new FULL required",+ ), false}}-func summarizerChainBroken(+func summarizerRefusedResult(+ status physical_enums.PhysicalBackupStatus,reason physical_enums.PhysicalBackupErrorReason,message string,) PhysicalBackupResult {return PhysicalBackupResult{- Status: physical_enums.PhysicalBackupStatusChainBroken,+ Status: status,ErrorReason: &reason,ErrorMessage: message,CompletedAt: time.Now().UTC(),@@ -300,14 +306,34 @@ func decryptParentManifest(reader io.Reader, spec IncrementalBackupSpec) (io.Reareturn dec, nil}+// Verbatim messages from PostgreSQL's basebackup_incremental.c and+// walsummarizer.c, matched by substring because the timeline and LSN arguments+// are interpolated per call.+const (+ summariesMissingForRangeStderr = "WAL summaries are required on timeline"+ summarizerStalledStderr = "WAL summarization is not progressing"+)+func classifyIncrStreamError(streamErr error, stderr []byte) streamOutcome {+ message := fmt.Sprintf("%v; stderr: %s", streamErr, truncateStderr(stderr))+if isSummariesExpiredError(stderr) {reason := physical_enums.PhysicalBackupErrorSummariesExpiredreturn streamOutcome{Status: physical_enums.PhysicalBackupStatusChainBroken,ErrorReason: &reason,- ErrorMessage: fmt.Sprintf("%v; stderr: %s", streamErr, truncateStderr(stderr)),+ ErrorMessage: message,+ }+ }++ if isSummarizerStalledError(stderr) {+ reason := physical_enums.PhysicalBackupErrorSummarizerFallingBehind++ return streamOutcome{+ Status: physical_enums.PhysicalBackupStatusError,+ ErrorReason: &reason,+ ErrorMessage: message,}}@@ -316,26 +342,22 @@ func classifyIncrStreamError(streamErr error, stderr []byte) streamOutcome {return streamOutcome{Status: physical_enums.PhysicalBackupStatusError,ErrorReason: &reason,- ErrorMessage: fmt.Sprintf("%v; stderr: %s", streamErr, truncateStderr(stderr)),+ ErrorMessage: message,}}// isSummariesExpiredError detects the post-readiness-check race where the source cluster// pruned WAL summaries between CheckSummarizerReadiness returning OK and pg_basebackup-// --incremental opening the actual range. PG surfaces this as "WAL summary file-// ... not found" or "could not open WAL summary".+// --incremental opening the actual range. The same message covers a range that was never+// summarized at all and one summarized with a hole in the middle.func isSummariesExpiredError(stderr []byte) bool {- msg := string(stderr)-- for _, needle := range []string{- "WAL summary file",- "could not open WAL summary",- "WAL summary not found",- } {- if strings.Contains(msg, needle) {- return true- }- }+ return strings.Contains(string(stderr), summariesMissingForRangeStderr)+}- return false+// isSummarizerStalledError detects a summarizer that stopped absorbing WAL.+// PostgreSQL waits for summarization through the backup start LSN and gives up+// only after a minute without a single absorbed record, so this is a real stall+// rather than a slow cluster.+func isSummarizerStalledError(stderr []byte) bool {+ return strings.Contains(string(stderr), summarizerStalledStderr)}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/create_incremental_uc_internal_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/create_incremental_uc_internal_test.gonew file mode 100644index 00000000..1fb1a62d--- /dev/null+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/create_incremental_uc_internal_test.go@@ -0,0 +1,58 @@+package usecases_physical_postgresql++import (+ "errors"+ "testing"++ "github.com/stretchr/testify/require"++ physical_enums "databasus-backend/internal/features/backups/backups/core/physical/enums"+)++// The stderr fixtures below carry PostgreSQL's own wording. Paraphrasing one would+// let the test pass while the real message went unmatched in production.++func Test_ClassifyIncrStreamError_WhenSummariesMissingForRange_ReturnsChainBrokenSummariesExpired(t *testing.T) {+ stderr := []byte("pg_basebackup: error: could not initiate base backup: ERROR: WAL summaries are " ++ "required on timeline 1 from 0/1000000 to 0/2000000, but no summaries for that timeline and " ++ "LSN range exist")++ outcome := classifyIncrStreamError(errors.New("exit status 1"), stderr)++ require.Equal(t, physical_enums.PhysicalBackupStatusChainBroken, outcome.Status)+ require.NotNil(t, outcome.ErrorReason)+ require.Equal(t, physical_enums.PhysicalBackupErrorSummariesExpired, *outcome.ErrorReason)+}++func Test_ClassifyIncrStreamError_WhenSummariesIncompleteForRange_ReturnsChainBrokenSummariesExpired(t *testing.T) {+ stderr := []byte("pg_basebackup: error: could not initiate base backup: ERROR: WAL summaries are " ++ "required on timeline 1 from 0/1000000 to 0/2000000, but the summaries for that timeline and " ++ "LSN range are incomplete")++ outcome := classifyIncrStreamError(errors.New("exit status 1"), stderr)++ require.Equal(t, physical_enums.PhysicalBackupStatusChainBroken, outcome.Status)+ require.NotNil(t, outcome.ErrorReason)+ require.Equal(t, physical_enums.PhysicalBackupErrorSummariesExpired, *outcome.ErrorReason)+}++func Test_ClassifyIncrStreamError_WhenSummarizationNotProgressing_ReturnsErrorSummarizerFallingBehind(t *testing.T) {+ stderr := []byte("pg_basebackup: error: could not initiate base backup: ERROR: WAL summarization " ++ "is not progressing")++ outcome := classifyIncrStreamError(errors.New("exit status 1"), stderr)++ require.Equal(t, physical_enums.PhysicalBackupStatusError, outcome.Status,+ "a stalled summarizer is transient, so the chain must stay extendable")+ require.NotNil(t, outcome.ErrorReason)+ require.Equal(t, physical_enums.PhysicalBackupErrorSummarizerFallingBehind, *outcome.ErrorReason)+}++func Test_ClassifyIncrStreamError_WhenUnrelatedStderr_ReturnsErrorPgBasebackupFailed(t *testing.T) {+ outcome := classifyIncrStreamError(errors.New("exit status 1"),+ []byte("pg_basebackup: error: connection to server failed"))++ require.Equal(t, physical_enums.PhysicalBackupStatusError, outcome.Status)+ require.NotNil(t, outcome.ErrorReason)+ require.Equal(t, physical_enums.PhysicalBackupErrorPgBasebackupFailed, *outcome.ErrorReason)+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/create_incremental_uc_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/create_incremental_uc_test.goindex 2017a89b..249ac2d3 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/create_incremental_uc_test.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/create_incremental_uc_test.go@@ -44,11 +44,11 @@ func Test_CreateIncremental_WhenSummarizerOff_ChainBrokenNoArtifact(t *testing.T"pre-check must bail before claiming a file name, so no artifact is uploaded")}-// Test_CreateIncremental_WhenSummarizerHealthy_GoesIncremental proves the-// pre-check does not regress the happy path: with summaries covering the-// parent's stop_lsn and a healthy (small) trailing lag, the INCR runs to-// COMPLETED and produces an artifact.-func Test_CreateIncremental_WhenSummarizerHealthy_GoesIncremental(t *testing.T) {+// Test_CreateIncremental_WhenWalWrittenSinceLastCheckpoint_Completes pins issue 756.+// WAL summaries close only at checkpoint records, so on a cluster that keeps writing+// the newest published summary ends far behind the WAL tip. The incremental must run+// anyway: pg_basebackup forces its own checkpoint, which closes the summary it needs.+func Test_CreateIncremental_WhenWalWrittenSinceLastCheckpoint_Completes(t *testing.T) {fixture := postgresql_executor.SetupPhysicalDBForBackup(t)backuping_physical.CreateTestPhysicalBackuper(nil).MakeBackup(t.Context(), fixture.BackupID, false)@@ -64,19 +64,13 @@ func Test_CreateIncremental_WhenSummarizerHealthy_GoesIncremental(t *testing.T)ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute)defer cancel()- // Cross a segment boundary and close it so the summarizer flushes a summary- // past the FULL's stop_lsn (it never summarizes the active segment).- _, err = postgresql_executor.GenerateWalActivity(ctx, conn, 32*1024*1024)+ // Several segments' worth, and deliberately no manual CHECKPOINT, pg_switch_wal+ // or wait for a summary: the newest published summary must end well behind the+ // WAL tip when the pre-check runs. pg_basebackup forces its own checkpoint, and+ // that is what closes the summary file the incremental actually needs.+ _, err = postgresql_executor.GenerateWalActivity(ctx, conn, 64*1024*1024)require.NoError(t, err)- _, err = conn.Exec(ctx, "CHECKPOINT")- require.NoError(t, err)-- _, err = conn.Exec(ctx, "SELECT pg_switch_wal()")- require.NoError(t, err)-- require.NoError(t, postgresql_executor.WaitForWalSummaries(ctx, conn, *fullRow.StopLSN, 2*time.Minute))-incrID := postgresql_executor.BuildAndClaimIncremental(t, fixture, nil)backuping_physical.CreateTestPhysicalBackuper(nil).MakeBackup(t.Context(), incrID, false)diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/stream.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/stream.goindex 10feb3f0..db6c28ea 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/stream.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/stream.go@@ -125,7 +125,10 @@ func runStream(counter := NewByteCounter(finalWriter)- stopWatcher := WithByteStallWatcher(streamCtx, counter, ByteStallTimeout, func() {+ stopWatcher := WithByteStallWatcher(streamCtx, counter, ByteStallThresholds{+ FirstByteTimeout: FirstByteTimeout,+ StallTimeout: ByteStallTimeout,+ }, func() {p.Logger.Warn("byte-stall timeout tripped; terminating pg_basebackup","backup_id", p.BackupID,"file_name", p.FileName)diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/summarizer.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/summarizer.goindex f74b3fec..0466a50a 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/summarizer.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/summarizer.go@@ -13,14 +13,15 @@ import ()// SummarizerDecision encodes the outcome of a per-tick incremental pre-check.-// The scheduler in PR 3 maps each value to one of: spawn INCR, wait then-// recheck, spawn FULL on same chain, or spawn FULL anchoring a new chain.+// The caller maps each value to one of: run the INCR, poll and recheck, abandon+// this attempt so the INCR cadence brings the next one, or spawn a FULL+// anchoring a new chain.type SummarizerDecision intconst (DecisionGoIncremental SummarizerDecision = iotaDecisionWait- DecisionFullSameChain+ DecisionRetryNextCadenceDecisionFullNewChain)@@ -35,45 +36,41 @@ type SummarizerResult struct {}const (- // summarizerWaitPollInterval — how often the scheduler in PR 3 will poll- // after DecisionWait. Five seconds is tight enough that recovery is felt- // quickly, loose enough that we don't hammer pg_available_wal_summaries.+ // summarizerWaitPollInterval bounds how often the bounded wait re-probes.+ // Five seconds is tight enough that recovery is felt quickly, loose enough+ // that we don't hammer the source catalog.summarizerWaitPollInterval = 5 * time.Second- // summarizerWaitCap — DecisionWait timeout is min(cadence/4, this).+ // summarizerWaitCap bounds the DecisionWait timeout, which is+ // min(cadence/4, this).summarizerWaitCap = 30 * time.Minute-- // summarizerFullThresholdBytes — once the summarizer trails current WAL by- // more than this, we stop waiting and spawn a FULL: a gap this large would- // stall pg_basebackup --incremental for too long, so a fresh FULL is the- // cheaper recovery. Generous on purpose — we'd rather wait out a temporary- // summarizer backlog (DecisionWait) than rotate to FULL prematurely.- summarizerFullThresholdBytes int64 = 1024 * 1024 * 1024-- // summarizerGoSegments — the summarizer never summarizes the currently- // active segment (and may have one more in flight), so a trailing lag of a- // couple of segments is the healthy steady state, not "behind". A lag below- // summarizerGoSegments × wal_segment_size means "caught up": go incremental- // directly and let pg_basebackup wait out the last sliver itself.- summarizerGoSegments int64 = 2)// CheckSummarizerReadiness classifies the state of the WAL summarizer relative to// prevStopLSN (the parent backup's stop_lsn, or — for the WAL-gap fallback// path — the current LSN). The conn must be an ordinary, non-replication// connection.+//+// WAL summary files close only at checkpoint records, so a summarizer that has+// read every byte still publishes nothing until the next checkpoint.+// pg_basebackup --incremental forces its own checkpoint at backup start, which+// closes a summary file at exactly the LSN it then waits for, so how far the+// published summaries trail current WAL never decides the outcome. Liveness is+// all that is worth probing here: a summarizer that absorbs no WAL record for a+// minute is caught by PostgreSQL itself, which fails the backup with+// "WAL summarization is not progressing".func CheckSummarizerReadiness(ctx context.Context,conn *pgx.Conn,prevStopLSN walmath.LSN,incrementalCadence time.Duration,) (SummarizerResult, error) {- enabled, err := isSummarizerEnabled(ctx, conn)+ isEnabled, err := isSummarizerEnabled(ctx, conn)if err != nil {return SummarizerResult{}, err}- if !enabled {+ if !isEnabled {reason := physical_enums.PhysicalBackupErrorSummarizerOffreturn SummarizerResult{@@ -98,61 +95,29 @@ func CheckSummarizerReadiness(}, nil}- // Summarizer on but nothing produced yet: not expiry, just not ready. Wait for the- // first summary rather than mismeasuring lag against a NULL MAX(end_lsn).+ // Summarizer on but nothing published yet: not expiry, just not ready.if !window.hasAny {- return SummarizerResult{- Decision: DecisionWait,- WaitFor: waitWindowForCadence(incrementalCadence),- PollEvery: summarizerWaitPollInterval,- }, nil+ return newWaitResult(incrementalCadence), nil}- lag, err := measureSummarizerLag(ctx, conn)+ isRunning, err := isSummarizerRunning(ctx, conn)if err != nil {return SummarizerResult{}, err}- if lag >= summarizerFullThresholdBytes {- return SummarizerResult{Decision: DecisionFullSameChain}, nil+ if !isRunning {+ return newWaitResult(incrementalCadence), nil}- goThreshold, err := summarizerGoThresholdBytes(ctx, conn)- if err != nil {- return SummarizerResult{}, err- }-- // A trailing lag within the active-segment band is the healthy steady state —- // go incremental. prevStopLSN is at or above the oldest retained summary (the- // aged-out case bailed above); if it sits in the last unsummarized sliver,- // pg_basebackup --incremental waits that segment out itself.- if lag < goThreshold {- return SummarizerResult{Decision: DecisionGoIncremental}, nil- }+ return SummarizerResult{Decision: DecisionGoIncremental}, nil+}+func newWaitResult(incrementalCadence time.Duration) SummarizerResult {return SummarizerResult{Decision: DecisionWait,WaitFor: waitWindowForCadence(incrementalCadence),PollEvery: summarizerWaitPollInterval,- }, nil-}--// summarizerGoThresholdBytes is the lag (in bytes) below which the summarizer-// counts as caught up: summarizerGoSegments × the cluster's wal_segment_size.-// wal_segment_size is a server GUC reported in bytes by current_setting.-func summarizerGoThresholdBytes(ctx context.Context, conn *pgx.Conn) (int64, error) {- var segmentSizeBytes int64-- // current_setting reports the GUC with its display unit (e.g. "16MB"), so- // run it through pg_size_bytes rather than a raw ::bigint cast.- if err := conn.QueryRow(- ctx,- "SELECT pg_size_bytes(current_setting('wal_segment_size'))::bigint",- ).Scan(&segmentSizeBytes); err != nil {- return 0, fmt.Errorf("read wal_segment_size: %w", err)}-- return summarizerGoSegments * segmentSizeBytes, nil}// summarizerCheck is the readiness probe behind a package var so the@@ -160,11 +125,11 @@ func summarizerGoThresholdBytes(ctx context.Context, conn *pgx.Conn) (int64, errvar summarizerCheck = CheckSummarizerReadiness// resolveSummarizerDecision runs the readiness probe and, when it reports-// DecisionWait (summarizer on and covering, but trailing current WAL), polls-// until the summarizer catches up, falls definitively behind, or the bounded-// window elapses. The returned decision is never DecisionWait: a window that-// expires while still lagging collapses to DecisionFullSameChain so the caller-// closes the chain rather than racing a moving target.+// DecisionWait (no summaries published yet, or the summarizer process is gone),+// polls until the state resolves or the bounded window elapses. The returned+// decision is never DecisionWait: a window that expires unresolved collapses to+// DecisionRetryNextCadence, so the caller fails this attempt instead of racing a+// summarizer that is not coming back within the tick.func resolveSummarizerDecision(ctx context.Context,conn *pgx.Conn,@@ -187,7 +152,7 @@ func resolveSummarizerDecision(// summarizer reaches a terminal decision or result.WaitFor elapses. It never// writes any catalog state — the INCR row stays IN_PROGRESS throughout, so a// recovery within the window proceeds to a normal incremental with no-// intermediate CHAIN_BROKEN.+// intermediate failure row.func waitForSummarizer(ctx context.Context,conn *pgx.Conn,@@ -216,7 +181,7 @@ func waitForSummarizer(}if time.Now().UTC().After(deadline) {- return SummarizerResult{Decision: DecisionFullSameChain}, nil+ return SummarizerResult{Decision: DecisionRetryNextCadence}, nil}}}@@ -239,26 +204,41 @@ func isSummarizerEnabled(ctx context.Context, conn *pgx.Conn) (bool, error) {return setting == "on", nil}+// pg_get_wal_summarizer_state() reports a NULL pid once the summarizer has+// exited, and collapses pending_lsn onto summarized_lsn at the same moment, so+// the pid is the only field that tells a dead summarizer from an idle one.+func isSummarizerRunning(ctx context.Context, conn *pgx.Conn) (bool, error) {+ var isRunning bool++ if err := conn.QueryRow(+ ctx,+ "SELECT summarizer_pid IS NOT NULL FROM pg_get_wal_summarizer_state()",+ ).Scan(&isRunning); err != nil {+ return false, fmt.Errorf("read WAL summarizer state: %w", err)+ }++ return isRunning, nil+}+type summaryWindow struct {// hasAny is false when the summarizer is on but has produced no summary file yet —// just enabled, or idle before the first checkpoint.hasAny boololdestStart walmath.LSN- newestEnd walmath.LSN}func readSummaryWindow(ctx context.Context, conn *pgx.Conn) (summaryWindow, error) {- var oldestStart, newestEnd *string+ var oldestStart *stringerr := conn.QueryRow(ctx, `- SELECT MIN(start_lsn)::text, MAX(end_lsn)::text+ SELECT MIN(start_lsn)::textFROM pg_available_wal_summaries()- `).Scan(&oldestStart, &newestEnd)+ `).Scan(&oldestStart)if err != nil {return summaryWindow{}, fmt.Errorf("read WAL summary window: %w", err)}- if oldestStart == nil || newestEnd == nil {+ if oldestStart == nil {return summaryWindow{}, nil}@@ -267,42 +247,16 @@ func readSummaryWindow(ctx context.Context, conn *pgx.Conn) (summaryWindow, erroreturn summaryWindow{}, fmt.Errorf("parse oldest summary start_lsn: %w", err)}- end, err := walmath.ParseLSN(*newestEnd)- if err != nil {- return summaryWindow{}, fmt.Errorf("parse newest summary end_lsn: %w", err)- }-- return summaryWindow{hasAny: true, oldestStart: start, newestEnd: end}, nil+ return summaryWindow{hasAny: true, oldestStart: start}, nil}-// measureSummarizerLag returns how far the summarizer's coverage trails-// pg_current_wal_lsn, in bytes. This is an instantaneous snapshot: the-// "catching up vs falling behind" distinction is made not from a rate but by-// re-sampling — CheckSummarizerReadiness maps the snapshot to GoIncremental /-// Wait / FullSameChain, and waitForSummarizer re-checks on each poll, so a lag-// that shrinks back under the go-threshold within the window proceeds and one-// that stays high collapses to a FULL.-func measureSummarizerLag(ctx context.Context, conn *pgx.Conn) (int64, error) {- var lagBytes int64-- err := conn.QueryRow(ctx, `- SELECT COALESCE(pg_wal_lsn_diff(- pg_current_wal_lsn(),- (SELECT MAX(end_lsn) FROM pg_available_wal_summaries())- ), 0)::bigint- `).Scan(&lagBytes)- if err != nil {- return 0, fmt.Errorf("measure summarizer lag: %w", err)- }-- if lagBytes < 0 {- return 0, nil+func waitWindowForCadence(cadence time.Duration) time.Duration {+ // ApproxPeriod returns 0 for cron intervals; a zero window would skip the+ // wait entirely.+ if cadence == 0 {+ return summarizerWaitCap}- return lagBytes, nil-}--func waitWindowForCadence(cadence time.Duration) time.Duration {quarter := cadence / 4if quarter > summarizerWaitCap {return summarizerWaitCapdiff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/summarizer_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/summarizer_test.goindex 1f94dd37..7674135e 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/summarizer_test.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/summarizer_test.go@@ -74,13 +74,13 @@ func Test_CheckSummarizerReadiness_WhenStopLsnPredatesOldestSummary_FallsBackToFrequire.Equal(t, physical_enums.PhysicalBackupErrorSummariesExpired, *result.Reason)}-// Test_CheckSummarizerReadiness_WhenStopLsnAheadOfSummaries_DoesNotBreakChain is the+// Test_CheckSummarizerReadiness_WhenStopLsnAheadOfSummaries_GoesIncremental is the// regression guard for the field report: right after a FULL on a near-idle DB the// WAL summarizer trails the FULL's stop_lsn (it never summarizes the active segment).-// A stop_lsn the summarizer simply hasn't reached yet is NOT expiry — the check must-// fall through to the lag path (GoIncremental / Wait), never CHAIN_BROKEN the chain-// with SUMMARIES_EXPIRED. Runs on both PG majors since PG 18 is the reported engine.-func Test_CheckSummarizerReadiness_WhenStopLsnAheadOfSummaries_DoesNotBreakChain(t *testing.T) {+// A stop_lsn the summarizer simply hasn't reached yet is NOT expiry, and with the+// summarizer process alive there is nothing left to wait for either. Runs on both PG+// majors since PG 18 is the reported engine.+func Test_CheckSummarizerReadiness_WhenStopLsnAheadOfSummaries_GoesIncremental(t *testing.T) {for _, version := range []string{"17", "18"} {t.Run("PostgreSQL "+version, func(t *testing.T) {fixture := SetupPhysicalDBForBackupVersion(t, version)@@ -100,11 +100,9 @@ func Test_CheckSummarizerReadiness_WhenStopLsnAheadOfSummaries_DoesNotBreakChainresult, err := CheckSummarizerReadiness(ctx, conn, walTipLSN, time.Hour)require.NoError(t, err)- require.NotEqual(t, DecisionFullNewChain, result.Decision,- "a stop_lsn the summarizer has not reached yet must not break the chain")+ require.Equal(t, DecisionGoIncremental, result.Decision,+ "a stop_lsn the summarizer has not reached yet must neither stall nor break the chain")require.Nil(t, result.Reason)- require.Contains(t,- []SummarizerDecision{DecisionGoIncremental, DecisionWait}, result.Decision)})}}@@ -162,16 +160,55 @@ func Test_WaitForSummarizer_LaggingThenCatchesUp_ProceedsNoChainBroken(t *testin"a summarizer that catches up within the window must proceed with the incremental")}-func Test_WaitForSummarizer_StaysLaggingPastDeadline_FallsBackToFullSameChain(t *testing.T) {- // WaitFor is tiny and every probe keeps reporting Wait, so the window- // expires while still lagging — the loop must collapse to FullSameChain.+func Test_WaitForSummarizer_WhenWaitDecisionOutlivesDeadline_FallsBackToRetryNextCadence(t *testing.T) {+ // WaitFor is tiny and every probe keeps reporting Wait, so the window expires+ // with the summarizer still publishing nothing.stubSummarizerCheck(t, waitStep(20*time.Millisecond, 5*time.Millisecond))result, err := resolveSummarizerDecision(context.Background(), nil, walmath.LSN(0), time.Hour)require.NoError(t, err)- require.Equal(t, DecisionFullSameChain, result.Decision,- "a summarizer that never catches up within the window must fall back to a FULL")+ require.Equal(t, DecisionRetryNextCadence, result.Decision,+ "a wait window that expires unresolved must hand the attempt to the next cadence")+}++func Test_WaitWindowForCadence_WhenCronIntervalHasNoPeriod_FallsBackToCap(t *testing.T) {+ require.Equal(t, summarizerWaitCap, waitWindowForCadence(0),+ "a cron interval reports no period, and a zero window would skip the wait entirely")+}++func Test_WaitWindowForCadence_WhenHourlyCadence_UsesQuarterOfCadence(t *testing.T) {+ require.Equal(t, 15*time.Minute, waitWindowForCadence(time.Hour))+}++func Test_WaitWindowForCadence_WhenDailyCadence_ClampsToCap(t *testing.T) {+ require.Equal(t, summarizerWaitCap, waitWindowForCadence(24*time.Hour))+}++func Test_IsSummarizerRunning_OnClusterWithSummarizerOn_ReturnsTrue(t *testing.T) {+ fixture := SetupPhysicalDBForBackup(t)+ conn := OpenAdminConn(t, fixture)++ isRunning, err := isSummarizerRunning(context.Background(), conn)++ require.NoError(t, err)+ require.True(t, isRunning)+}++func Test_IsSummarizerRunning_OnClusterWithoutSummarizer_ReturnsFalse(t *testing.T) {+ source := containers.StartPhysicalPostgres(t, "postgres:17", containers.WithoutSummarizer())+ sourceDB := databases.GetTestPhysicalPostgresConfigNoSummary(source.Host, source.Port, "17")++ ctx := context.Background()++ conn, err := sourceDB.OpenInspectionConn(ctx, encryption.GetFieldEncryptor())+ require.NoError(t, err)+ t.Cleanup(func() { _ = conn.Close(context.Background()) })++ isRunning, err := isSummarizerRunning(ctx, conn)++ require.NoError(t, err)+ require.False(t, isRunning, "the summarizer process never starts when summarize_wal is off")}func Test_WaitForSummarizer_SummariesExpireMidWait_FallsBackToFullNewChain(t *testing.T) {