PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FIX (physical): Guard incomplete WAL segments and bound the recovery point on quiet databases
Rostislav Dugin4f5f6b86bdfa
diff --git a/CLAUDE.md b/CLAUDE.mdindex d72b476c..fd16d11d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -17,7 +17,7 @@ This root file holds the engineering philosophy that applies everywhere.Work happens inside the repo's [Dev Container](.devcontainer/devcontainer.json). The container ships Go, Node.js + pnpm, Docker-in-Docker, linters and matching VS Code extensions, so the toolchain is identical for every contributor. Ports `4005` (backend) and `5173` (Vite) are forwarded automatically. Don't install or rely on host-level SDKs — run `make`, `pnpm` and `docker` commands from inside the container.-Running the backend suite host-native is supported on Fedora via `make test-fedora`, which shims the Debian soname the bundled `assets/tools` clients expect. Any other host distro is on its own — the container stays the reference environment. Also project sometimes is run in different worktrees, in this case it is needed to copy .env.example -> .env and `pnpm install` to run tests+Running the backend suite host-native is supported on Fedora via `make test-fedora`, which shims the Debian soname the bundled `assets/tools` clients expect. Any other host distro is on its own — the container stays the reference environment. Also project sometimes is run in different worktrees, in this case it is needed to copy .env.example -> .env, `make swagger` and `pnpm install` to run tests---diff --git a/backend/internal/features/backups/backups/backuping/physical/constants.go b/backend/internal/features/backups/backups/backuping/physical/constants.goindex 9a8ca04d..0d2318e1 100644--- a/backend/internal/features/backups/backups/backuping/physical/constants.go+++ b/backend/internal/features/backups/backups/backuping/physical/constants.go@@ -54,7 +54,7 @@ const (walStreamSupervisorJobName = "physical_wal_stream_supervisor"// One notification per incident, not one per reclaim cycle.- chainAlertMinInterval = 15 * time.Minute+ defaultChainAlertMinInterval = 15 * time.Minute)// Per-tick WAL deletion budget anchors to the latest FULL's size (a clusterdiff --git a/backend/internal/features/backups/backups/backuping/physical/di.go b/backend/internal/features/backups/backups/backuping/physical/di.goindex 0a8d0eee..901797ad 100644--- a/backend/internal/features/backups/backups/backuping/physical/di.go+++ b/backend/internal/features/backups/backups/backuping/physical/di.go@@ -82,6 +82,7 @@ var physicalWalStreamSupervisor = &PhysicalWalStreamSupervisor{encryption_secrets.GetSecretKeyService(),encryption.GetFieldEncryptor(),logger.GetLogger(),+ defaultChainAlertMinInterval,sync.Mutex{},make(map[uuid.UUID]*runningStreamer),atomicTime{},diff --git a/backend/internal/features/backups/backups/backuping/physical/dto.go b/backend/internal/features/backups/backups/backuping/physical/dto.goindex 84478b4d..c5e7d0d6 100644--- a/backend/internal/features/backups/backups/backuping/physical/dto.go+++ b/backend/internal/features/backups/backups/backuping/physical/dto.go@@ -34,6 +34,8 @@ const (chainAlertStreamerFailed chainAlertKind = "STREAMER_FAILED"chainAlertSlotRebuilt chainAlertKind = "SLOT_REBUILT"chainAlertChainAtRisk chainAlertKind = "CHAIN_AT_RISK"+ chainAlertArchiveStale chainAlertKind = "WAL_ARCHIVE_STALE"+ chainAlertRotationDenied chainAlertKind = "WAL_ROTATION_DENIED")type chainAlertKey struct {diff --git a/backend/internal/features/backups/backups/backuping/physical/testing.go b/backend/internal/features/backups/backups/backuping/physical/testing.goindex cfe21a8c..5e24e436 100644--- a/backend/internal/features/backups/backups/backuping/physical/testing.go+++ b/backend/internal/features/backups/backups/backuping/physical/testing.go@@ -71,11 +71,24 @@ func CreateTestPhysicalScheduler() *PhysicalBackupsScheduler {}}+type WalStreamSupervisorTestSpec struct {+ NotificationSender NotificationSender++ // Zero means the production default; the streamer spec in the executor package+ // reads zero as "disabled", hence the different name.+ ChainAlertMinIntervalOverride time.Duration+}+// CreateTestWalStreamSupervisor returns a fresh WAL stream supervisor wired to// the production repos and services. A fresh instance (not a copy of the DI// singleton) keeps each test's hasRun/running state isolated and avoids copying// the embedded mutex.-func CreateTestWalStreamSupervisor(notificationSender NotificationSender) *PhysicalWalStreamSupervisor {+func CreateTestWalStreamSupervisor(spec WalStreamSupervisorTestSpec) *PhysicalWalStreamSupervisor {+ chainAlertMinInterval := spec.ChainAlertMinIntervalOverride+ if chainAlertMinInterval == 0 {+ chainAlertMinInterval = defaultChainAlertMinInterval+ }+return &PhysicalWalStreamSupervisor{databases.GetDatabaseService(),backups_config_physical.GetBackupConfigService(),@@ -83,11 +96,12 @@ func CreateTestWalStreamSupervisor(notificationSender NotificationSender) *Physiphysical_repositories.GetWalSegmentRepository(),physical_repositories.GetWalHistoryRepository(),physical_repositories.GetWalStreamerRepository(),- notificationSender,+ spec.NotificationSender,tasks_cancellation.GetTaskCancelManager(),encryption_secrets.GetSecretKeyService(),encryption.GetFieldEncryptor(),logger.GetLogger(),+ chainAlertMinInterval,sync.Mutex{},make(map[uuid.UUID]*runningStreamer),atomicTime{},@@ -163,7 +177,9 @@ func StartPhysicalSchedulerForTest(t *testing.T) context.CancelFunc {func StartPhysicalWalStreamSupervisorForTest(t *testing.T) context.CancelFunc {t.Helper()- supervisor := CreateTestWalStreamSupervisor(notifiers.GetNotifierService())+ supervisor := CreateTestWalStreamSupervisor(WalStreamSupervisorTestSpec{+ NotificationSender: notifiers.GetNotifierService(),+ })ctx, cancel := context.WithCancel(context.Background())diff --git a/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.go b/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.goindex 71dfe11a..882a2a72 100644--- a/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.go+++ b/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.go@@ -45,6 +45,8 @@ type PhysicalWalStreamSupervisor struct {fieldEncryptor util_encryption.FieldEncryptorlogger *slog.Logger+ chainAlertMinInterval time.Duration+mu sync.Mutexrunning map[uuid.UUID]*runningStreamer@@ -251,21 +253,23 @@ func (s *PhysicalWalStreamSupervisor) startStreamer(})supervisor := postgresql_executor.NewWalStreamSupervisor(postgresql_executor.WalStreamSpec{- DatabaseID: db.ID,- SourceDB: db.PostgresqlPhysical,- StorageID: storage.ID,- Storage: storage,- Encryption: backupConfig.Encryption,- MasterKey: masterKey,- FieldEncryptor: s.fieldEncryptor,- WalSegmentRepo: s.walSegmentRepo,- HistoryRepo: s.historyRepo,- WatchDirRoot: config.GetEnv().DataFolder,- WalLagThresholdBytes: backupConfig.WalLagThresholdBytes,- OnGapDetected: s.gapNotifier(db, backupConfig),- OnSlotRebuilt: s.slotRebuildFullRequester(logger, db, backupConfig),- OnChainAtRisk: s.chainRiskNotifier(db, backupConfig),- Logger: s.logger,+ DatabaseID: db.ID,+ SourceDB: db.PostgresqlPhysical,+ StorageID: storage.ID,+ Storage: storage,+ Encryption: backupConfig.Encryption,+ MasterKey: masterKey,+ FieldEncryptor: s.fieldEncryptor,+ WalSegmentRepo: s.walSegmentRepo,+ HistoryRepo: s.historyRepo,+ WatchDirRoot: config.GetEnv().DataFolder,+ WalLagThresholdBytes: backupConfig.WalLagThresholdBytes,+ ForcedRotationInterval: postgresql_executor.DefaultForcedRotationInterval,+ ArchiveStalenessThreshold: postgresql_executor.DefaultArchiveStalenessThreshold,+ OnGapDetected: s.gapNotifier(db, backupConfig),+ OnSlotRebuilt: s.slotRebuildFullRequester(logger, db, backupConfig),+ OnChainAtRisk: s.chainRiskNotifier(db, backupConfig),+ Logger: s.logger,})s.mu.Lock()@@ -371,12 +375,50 @@ func (s *PhysicalWalStreamSupervisor) chainRiskNotifier(backupConfig *backups_config_physical.PhysicalBackupConfig,) func(postgresql_executor.ChainRiskReport) {return func(report postgresql_executor.ChainRiskReport) {- s.notifyChainBroken(db, backupConfig, chainAlert{+ s.notifyChainBroken(db, backupConfig, buildChainRiskAlert(db, report))+ }+}++// Each risk gets its own kind: the throttle key is (database, kind), so folding+// them together would let a slot-retention warning mute the alert that says the+// recovery point has stopped advancing.+func buildChainRiskAlert(db *databases.Database, report postgresql_executor.ChainRiskReport) chainAlert {+ switch report.Reason {+ case postgresql_executor.ChainRiskReasonArchiveStale:+ lastArchivedAt := "never"+ if report.LastArchivedWalAt != nil {+ lastArchivedAt = report.LastArchivedWalAt.Format(time.RFC3339)+ }++ return chainAlert{+ Kind: chainAlertArchiveStale,+ Heading: fmt.Sprintf("Physical WAL archiving fell behind for %q", db.Name),+ Message: fmt.Sprintf(+ "database_id=%s reason=%s last_archived_wal_at=%s lag_bytes=%d; "++ "the recovery point stopped advancing while the source kept writing",+ db.ID, report.Reason, lastArchivedAt, report.LagBytes,+ ),+ }++ case postgresql_executor.ChainRiskReasonRotationDenied:+ return chainAlert{+ Kind: chainAlertRotationDenied,+ Heading: fmt.Sprintf("Cannot force WAL rotation for %q", db.Name),+ Message: fmt.Sprintf(+ "database_id=%s reason=%s; a rarely-written database keeps its newest WAL local until the segment "++ "fills. Either GRANT EXECUTE ON FUNCTION pg_switch_wal() TO the backup role, "++ "or set archive_timeout on the source",+ db.ID, report.Reason,+ ),+ }++ default:+ return chainAlert{Kind: chainAlertChainAtRisk,Heading: fmt.Sprintf("Physical WAL chain at risk for %q", db.Name),Message: fmt.Sprintf("database_id=%s reason=%s slot_wal_status=%s lag_bytes=%d",db.ID, report.Reason, report.SlotWalStatus, report.LagBytes),- })+ }}}@@ -411,7 +453,7 @@ func (s *PhysicalWalStreamSupervisor) recordChainAlertIfDue(key chainAlertKey) bnow := time.Now().UTC()if sentAt, wasNotified := s.lastChainAlertAt[key]; wasNotified &&- now.Sub(sentAt) < chainAlertMinInterval {+ now.Sub(sentAt) < s.chainAlertMinInterval {return false}diff --git a/backend/internal/features/backups/backups/backuping/physical/wal_supervisor_test.go b/backend/internal/features/backups/backups/backuping/physical/wal_supervisor_test.goindex 22bab209..865f4b67 100644--- a/backend/internal/features/backups/backups/backuping/physical/wal_supervisor_test.go+++ b/backend/internal/features/backups/backups/backuping/physical/wal_supervisor_test.go@@ -11,6 +11,7 @@ import (physical_enums "databasus-backend/internal/features/backups/backups/core/physical/enums"physical_repositories "databasus-backend/internal/features/backups/backups/core/physical/repositories"+ postgresql_executor "databasus-backend/internal/features/backups/backups/usecases/physical/postgresql"backups_config_physical "databasus-backend/internal/features/backups/config/physical""databasus-backend/internal/features/notifiers""databasus-backend/internal/storage"@@ -133,7 +134,9 @@ func Test_ClaimIfClaimable_WhenConcurrentClaims_ExactlyOneWins(t *testing.T) {}func Test_PhysicalWalStreamSupervisorRun_WhenCalledTwice_Panics(t *testing.T) {- supervisor := CreateTestWalStreamSupervisor(notifiers.GetNotifierService())+ supervisor := CreateTestWalStreamSupervisor(WalStreamSupervisorTestSpec{+ NotificationSender: notifiers.GetNotifierService(),+ })ctx := t.Context()@@ -156,7 +159,9 @@ func Test_PhysicalWalStreamSupervisorRun_WhenCalledTwice_Panics(t *testing.T) {func Test_StopStreamer_WhenOwnedStreamerStops_MarksRowFailed(t *testing.T) {prereqs := seedBackupPrereqs(t)- supervisor := CreateTestWalStreamSupervisor(notifiers.GetNotifierService())+ supervisor := CreateTestWalStreamSupervisor(WalStreamSupervisorTestSpec{+ NotificationSender: notifiers.GetNotifierService(),+ })require.NoError(t, physical_repositories.GetWalStreamerRepository().Claim(prereqs.DB.ID))done := make(chan struct{})@@ -184,7 +189,9 @@ func Test_RecoverStreamersOnStartup_WhenRunningRowStale_MarksFailed(t *testing.Tphysical_enums.PhysicalWalStreamerStatusRunning,)- supervisor := CreateTestWalStreamSupervisor(notifiers.GetNotifierService())+ supervisor := CreateTestWalStreamSupervisor(WalStreamSupervisorTestSpec{+ NotificationSender: notifiers.GetNotifierService(),+ })require.NoError(t, supervisor.recoverStreamersOnStartup())@@ -195,7 +202,9 @@ func Test_RecoverStreamersOnStartup_WhenRunningRowStale_MarksFailed(t *testing.T}func Test_RemoveWatchDirIfRequested_WhenCleanupRequested_RemovesQueue(t *testing.T) {- supervisor := CreateTestWalStreamSupervisor(notifiers.GetNotifierService())+ supervisor := CreateTestWalStreamSupervisor(WalStreamSupervisorTestSpec{+ NotificationSender: notifiers.GetNotifierService(),+ })watchDir := filepath.Join(t.TempDir(), "wal-queue")require.NoError(t, os.MkdirAll(watchDir, 0o700))require.NoError(t, os.WriteFile(filepath.Join(watchDir, "segment"), []byte("wal"), 0o600))@@ -212,7 +221,7 @@ func Test_NotifyChainBroken_WhenSameIncidentRepeats_SendsOneNotificationPerWindoprereqs := seedBackupPrereqs(t)sender := &recordingNotificationSender{}- supervisor := CreateTestWalStreamSupervisor(sender)+ supervisor := CreateTestWalStreamSupervisor(WalStreamSupervisorTestSpec{NotificationSender: sender})prereqs.Config.SendNotificationsOn = []backups_config_physical.BackupNotificationType{backups_config_physical.NotificationChainBroken,@@ -236,7 +245,7 @@ func Test_NotifyChainBroken_WhenConfigDoesNotOptIn_SendsNoNotification(t *testinprereqs := seedBackupPrereqs(t)sender := &recordingNotificationSender{}- supervisor := CreateTestWalStreamSupervisor(sender)+ supervisor := CreateTestWalStreamSupervisor(WalStreamSupervisorTestSpec{NotificationSender: sender})prereqs.Config.SendNotificationsOn = []backups_config_physical.BackupNotificationType{backups_config_physical.NotificationBackupSuccess,@@ -255,7 +264,7 @@ func Test_NotifyChainBroken_WhenDifferentIncidentKinds_SendsEachOnce(t *testing.prereqs := seedBackupPrereqs(t)sender := &recordingNotificationSender{}- supervisor := CreateTestWalStreamSupervisor(sender)+ supervisor := CreateTestWalStreamSupervisor(WalStreamSupervisorTestSpec{NotificationSender: sender})prereqs.Config.SendNotificationsOn = []backups_config_physical.BackupNotificationType{backups_config_physical.NotificationChainBroken,@@ -277,3 +286,97 @@ func Test_NotifyChainBroken_WhenDifferentIncidentKinds_SendsEachOnce(t *testing.require.Equal(t, "chain at risk", sender.sentNotifications[0].Notification.Heading)require.Equal(t, "chain rebuilt", sender.sentNotifications[1].Notification.Heading)}++func Test_NotifyChainBroken_WhenThrottleWindowElapsed_SendsAgain(t *testing.T) {+ prereqs := seedBackupPrereqs(t)++ sender := &recordingNotificationSender{}+ supervisor := CreateTestWalStreamSupervisor(WalStreamSupervisorTestSpec{+ NotificationSender: sender,+ ChainAlertMinIntervalOverride: time.Millisecond,+ })++ prereqs.Config.SendNotificationsOn = []backups_config_physical.BackupNotificationType{+ backups_config_physical.NotificationChainBroken,+ }++ streamerFailed := chainAlert{+ Kind: chainAlertStreamerFailed,+ Heading: "WAL streaming stopped",+ Message: "database_id=x",+ }++ supervisor.notifyChainBroken(prereqs.DB, prereqs.Config, streamerFailed)++ time.Sleep(5 * time.Millisecond)++ supervisor.notifyChainBroken(prereqs.DB, prereqs.Config, streamerFailed)++ require.Len(t, sender.sentNotifications, 2,+ "the throttle must mute a burst, not the incident itself — an unfixed break has to keep reminding the operator")+}++func Test_StopStreamer_WhenStreamerStops_ForgetsChainAlertThrottle(t *testing.T) {+ prereqs := seedBackupPrereqs(t)++ sender := &recordingNotificationSender{}+ supervisor := CreateTestWalStreamSupervisor(WalStreamSupervisorTestSpec{NotificationSender: sender})++ prereqs.Config.SendNotificationsOn = []backups_config_physical.BackupNotificationType{+ backups_config_physical.NotificationChainBroken,+ }++ streamerFailed := chainAlert{+ Kind: chainAlertStreamerFailed,+ Heading: "WAL streaming stopped",+ Message: "database_id=x",+ }++ supervisor.notifyChainBroken(prereqs.DB, prereqs.Config, streamerFailed)++ done := make(chan struct{})+ close(done)++ supervisor.running[prereqs.DB.ID] = &runningStreamer{cancel: func() {}, done: done}+ supervisor.stopStreamer(prereqs.DB.ID, false)++ supervisor.notifyChainBroken(prereqs.DB, prereqs.Config, streamerFailed)++ require.Len(t, sender.sentNotifications, 2,+ "a reclaimed database is a fresh incident, so the throttle from the previous streamer must not mute it")+}++func Test_ChainRiskNotifier_WhenReasonsDiffer_UsesSeparateThrottleKinds(t *testing.T) {+ prereqs := seedBackupPrereqs(t)++ sender := &recordingNotificationSender{}+ supervisor := CreateTestWalStreamSupervisor(WalStreamSupervisorTestSpec{NotificationSender: sender})++ prereqs.Config.SendNotificationsOn = []backups_config_physical.BackupNotificationType{+ backups_config_physical.NotificationChainBroken,+ }++ notifyChainRisk := supervisor.chainRiskNotifier(prereqs.DB, prereqs.Config)++ lastArchivedWalAt := time.Now().UTC().Add(-2 * time.Hour)++ notifyChainRisk(postgresql_executor.ChainRiskReport{+ Reason: postgresql_executor.ChainRiskReasonSlotRetention,+ SlotWalStatus: "extended",+ LagBytes: 64 * 1024 * 1024,+ })+ notifyChainRisk(postgresql_executor.ChainRiskReport{+ Reason: postgresql_executor.ChainRiskReasonArchiveStale,+ LagBytes: 16 * 1024 * 1024,+ LastArchivedWalAt: &lastArchivedWalAt,+ })+ notifyChainRisk(postgresql_executor.ChainRiskReport{+ Reason: postgresql_executor.ChainRiskReasonRotationDenied,+ })++ require.Len(t, sender.sentNotifications, 3,+ "a slot-retention warning must not mute the alerts about a stalled recovery point or a refused rotation")++ require.Contains(t, sender.sentNotifications[1].Notification.Message, lastArchivedWalAt.Format(time.RFC3339))+ require.Contains(t, sender.sentNotifications[2].Notification.Message, "pg_switch_wal()")+}diff --git a/backend/internal/features/backups/backups/core/physical/repositories/wal_segment_repository.go b/backend/internal/features/backups/backups/core/physical/repositories/wal_segment_repository.goindex 5b5b9636..38dda3e0 100644--- a/backend/internal/features/backups/backups/core/physical/repositories/wal_segment_repository.go+++ b/backend/internal/features/backups/backups/core/physical/repositories/wal_segment_repository.go@@ -263,3 +263,27 @@ func (r *PhysicalWalSegmentRepository) FindLatestCommittedBefore(return &endLSN, nil}++// The newest segment that is durable in storage — the database's actual recovery+// point. In-flight claims are excluded: a claim row means an upload was started,+// not that the WAL can be restored from.+func (r *PhysicalWalSegmentRepository) FindLatestCommittedSegment(+ databaseID uuid.UUID,+) (*physical_models.PhysicalWalSegment, error) {+ var segment physical_models.PhysicalWalSegment++ err := storage.+ GetDb().+ Where("database_id = ? AND file_name IS NOT NULL", databaseID).+ Order("timeline_id DESC, start_lsn DESC").+ First(&segment).Error+ if err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, nil+ }++ return nil, err+ }++ return &segment, nil+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/dto.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/dto.goindex 617d06df..00e2b8ee 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/dto.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/dto.go@@ -91,10 +91,21 @@ type ParentManifestRef struct {StopLSN walmath.LSN}-// Payload of WalStreamSpec.OnChainAtRisk. Reason is a walBreakReason string:-// the type is unexported, and the wiring package cannot name it.+// Values of ChainRiskReport.Reason. Exported because the wiring package routes+// each one to its own notification kind, and the walBreakReason type it comes+// from is unexported.+const (+ ChainRiskReasonSlotRetention = "SLOT_WAL_RETENTION"+ ChainRiskReasonArchiveStale = "WAL_ARCHIVE_STALE"+ ChainRiskReasonRotationDenied = "WAL_ROTATION_DENIED"+)++// Payload of WalStreamSpec.OnChainAtRisk. SlotWalStatus and LagBytes describe the+// slot; LastArchivedWalAt is set only for ChainRiskReasonArchiveStale, where the+// question is how far the recovery point has fallen behind.type ChainRiskReport struct {- Reason string- SlotWalStatus string- LagBytes int64+ Reason string+ SlotWalStatus string+ LagBytes int64+ LastArchivedWalAt *time.Time}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/lag_monitor.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/lag_monitor.goindex 2fa20b36..0b382c30 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/lag_monitor.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/lag_monitor.go@@ -5,6 +5,8 @@ import ("fmt""log/slog""time"++ "databasus-backend/internal/util/walmath")const (@@ -33,10 +35,11 @@ const (type walBreakReason stringconst (- breakReasonSlotLost walBreakReason = "SLOT_LOST"- breakReasonWalLag walBreakReason = "WAL_LAG_THRESHOLD"- breakReasonSlotStolen walBreakReason = "SLOT_STOLEN"- breakReasonSlotRetention walBreakReason = "SLOT_WAL_RETENTION"+ breakReasonSlotLost walBreakReason = "SLOT_LOST"+ breakReasonWalLag walBreakReason = "WAL_LAG_THRESHOLD"+ breakReasonSlotStolen walBreakReason = "SLOT_STOLEN"+ breakReasonSlotRetention walBreakReason = ChainRiskReasonSlotRetention+ breakReasonRotationDenied walBreakReason = ChainRiskReasonRotationDenied)type slotBreakAction int@@ -121,6 +124,8 @@ func (s *WalStreamSupervisor) runLagMonitor(ctx context.Context, logger *slog.Lovar classifier slotBreakClassifier+ var stalenessTracker walArchiveStalenessTracker+for {select {case <-ctx.Done():@@ -132,6 +137,8 @@ func (s *WalStreamSupervisor) runLagMonitor(ctx context.Context, logger *slog.Locontinue}+ s.reportArchiveStalenessIfDue(logger, &stalenessTracker, state)+reason, action := classifier.recordSampleAndClassifyBreak(slotBreakSample{SlotState: state,WalLagThresholdBytes: s.spec.WalLagThresholdBytes,@@ -157,9 +164,54 @@ func (s *WalStreamSupervisor) runLagMonitor(ctx context.Context, logger *slog.Lo}}+// The slot's restart_lsn plus its lag is where the source currently is, so the+// staleness check needs no extra query on the source.+func (s *WalStreamSupervisor) reportArchiveStalenessIfDue(+ logger *slog.Logger,+ stalenessTracker *walArchiveStalenessTracker,+ state *SlotState,+) {+ lastCommittedWalLSN, lastCommittedWalAt := s.getLastCommittedWal(logger)++ isArchiveStale := stalenessTracker.recordSampleAndDetectStaleness(walArchiveSample{+ SourceCurrentLSN: state.RestartLSN + walmath.LSN(state.LagBytes),+ LastCommittedWalLSN: lastCommittedWalLSN,+ ObservedAt: time.Now().UTC(),+ StalenessThreshold: s.spec.ArchiveStalenessThreshold,+ })++ if !isArchiveStale {+ return+ }++ logger.Warn("wal archiving fell behind the source; the recovery point is no longer advancing",+ "reason", ChainRiskReasonArchiveStale,+ "slot", s.slotName,+ )++ if s.spec.OnChainAtRisk == nil {+ return+ }++ s.spec.OnChainAtRisk(ChainRiskReport{+ Reason: ChainRiskReasonArchiveStale,+ SlotWalStatus: state.WalStatus,+ LagBytes: state.LagBytes,+ LastArchivedWalAt: lastCommittedWalAt,+ })+}++// state is nil for a risk that is not about the slot at all (a refused rotation).func (s *WalStreamSupervisor) reportChainAtRisk(logger *slog.Logger, reason walBreakReason, state *SlotState) {+ report := ChainRiskReport{Reason: string(reason)}++ if state != nil {+ report.SlotWalStatus = state.WalStatus+ report.LagBytes = state.LagBytes+ }+logger.Warn(- fmt.Sprintf("wal chain at risk: slot wal_status=%s, %d bytes behind", state.WalStatus, state.LagBytes),+ fmt.Sprintf("wal chain at risk: slot wal_status=%s, %d bytes behind", report.SlotWalStatus, report.LagBytes),"reason", string(reason),"slot", s.slotName,)@@ -168,9 +220,5 @@ func (s *WalStreamSupervisor) reportChainAtRisk(logger *slog.Logger, reason walBreturn}- s.spec.OnChainAtRisk(ChainRiskReport{- Reason: string(reason),- SlotWalStatus: state.WalStatus,- LagBytes: state.LagBytes,- })+ s.spec.OnChainAtRisk(report)}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/mocks_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/mocks_test.gonew file mode 100644index 00000000..9e434f04--- /dev/null+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/mocks_test.go@@ -0,0 +1,139 @@+package usecases_physical_postgresql++import (+ "context"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "os"+ "path/filepath"+ "sync"+ "sync/atomic"+ "testing"++ "github.com/stretchr/testify/require"++ "databasus-backend/internal/util/encryption"+ "databasus-backend/internal/util/walmath"+)++const testWalSegmentSize = int64(16 * 1024 * 1024)++// Used when a chain-span query must match every segment regardless of position.+const lsnSpanUpperBoundForTests = walmath.LSN(1) << 62++type mockWalStorage struct {+ mu sync.Mutex+ saved map[string][]byte+ deleted []string+ saveCount atomic.Int64++ failSaveTimes int++ isFailingAllSaves atomic.Bool++ // Interleaves the DeleteFull cascade race: SaveFile for this exact object name+ // signals started and waits on release before returning.+ blockOn string+ started chan struct{}+ release chan struct{}+}++func newMockWalStorage() *mockWalStorage {+ return &mockWalStorage{saved: make(map[string][]byte)}+}++func (m *mockWalStorage) SaveFile(+ _ context.Context, _ encryption.FieldEncryptor, _ *slog.Logger, fileName string, file io.Reader,+) error {+ m.saveCount.Add(1)++ body, _ := io.ReadAll(file)++ if m.blockOn != "" && fileName == m.blockOn {+ close(m.started)+ <-m.release+ }++ if m.isFailingAllSaves.Load() {+ return fmt.Errorf("mock storage is failing every save for %s", fileName)+ }++ m.mu.Lock()+ defer m.mu.Unlock()++ if m.failSaveTimes > 0 {+ m.failSaveTimes--++ return fmt.Errorf("mock storage induced failure for %s", fileName)+ }++ m.saved[fileName] = body++ return nil+}++func (m *mockWalStorage) startFailingSaves() {+ m.isFailingAllSaves.Store(true)+}++func (m *mockWalStorage) stopFailingSaves() {+ m.isFailingAllSaves.Store(false)+}++func (m *mockWalStorage) DeleteFile(_ encryption.FieldEncryptor, fileName string) error {+ m.mu.Lock()+ defer m.mu.Unlock()++ delete(m.saved, fileName)+ m.deleted = append(m.deleted, fileName)++ return nil+}++func (m *mockWalStorage) GetFile(_ encryption.FieldEncryptor, _ string) (io.ReadCloser, error) {+ return nil, errors.New("GetFile not implemented in mockWalStorage")+}+func (m *mockWalStorage) Validate(_ encryption.FieldEncryptor) error { return nil }+func (m *mockWalStorage) TestConnection(_ encryption.FieldEncryptor) error { return nil }+func (m *mockWalStorage) HideSensitiveData() {}+func (m *mockWalStorage) EncryptSensitiveData(_ encryption.FieldEncryptor) error { return nil }++func (m *mockWalStorage) hasObject(name string) bool {+ m.mu.Lock()+ defer m.mu.Unlock()++ _, ok := m.saved[name]++ return ok+}++// 256 segments per logid, i.e. the default 16 MB segment size.+func walName(timeline uint32, segNo uint64) string {+ const segmentsPerLogID = 256++ return fmt.Sprintf("%08X%08X%08X", timeline, segNo/segmentsPerLogID, segNo%segmentsPerLogID)+}++// The segments are sparse: only the reported size matters to the uploader and to+// the resume-point math, so allocating real bytes would only slow tests down.+func writeSegmentOfSize(t *testing.T, dir, name string, sizeBytes int64) string {+ t.Helper()++ path := filepath.Join(dir, name)++ file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)+ require.NoError(t, err)++ require.NoError(t, file.Truncate(sizeBytes))+ require.NoError(t, file.Close())++ return path+}++func writeWalFile(t *testing.T, dir, name string) string {+ t.Helper()++ return writeSegmentOfSize(t, dir, name, testWalSegmentSize)+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/mtls_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/mtls_test.goindex ce59daf4..e087a4f8 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/mtls_test.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/mtls_test.go@@ -131,7 +131,10 @@ func Test_WalStreamOverMtls_StreamerArchivesSegments(t *testing.T) {store := newMockWalStorage()- stop := StartWalStreamerForTest(t, fixture, store, t.TempDir()).Stop+ stop := StartWalStreamerForTest(+ t,+ WalStreamerTestSpec{Fixture: fixture, Storage: store, WatchDirRoot: t.TempDir()},+ ).Stopt.Cleanup(stop)adminConn := OpenAdminConn(t, fixture)diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_cleanup_listener_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_cleanup_listener_test.goindex d6969170..44fa2d41 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_cleanup_listener_test.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_cleanup_listener_test.go@@ -99,7 +99,11 @@ func Test_DropWalSlot_WhenStreamerSlotActive_RefusesAndKeepsSlot(t *testing.T) {adminConn := postgresql_executor.OpenAdminConn(t, fixture)streamerSlot := fixture.DB.PostgresqlPhysical.ReplicationSlotName- stop := postgresql_executor.StartWalStreamerForTest(t, fixture, fixture.Storage, t.TempDir()).Stop+ stop := postgresql_executor.StartWalStreamerForTest(t, postgresql_executor.WalStreamerTestSpec{+ Fixture: fixture,+ Storage: fixture.Storage,+ WatchDirRoot: t.TempDir(),+ }).Stopdefer stop()waitUntilSlotActive(t, adminConn, streamerSlot, 30*time.Second)diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_rebuild.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_rebuild.goindex 2afb2505..6d2d2294 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_rebuild.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_rebuild.go@@ -5,6 +5,7 @@ import ("errors""fmt""log/slog"+ "slices""strings""time")@@ -174,3 +175,10 @@ func (s *WalStreamSupervisor) recordRebuildAttemptWithinCap() bool {return true}++func (s *WalStreamSupervisor) GetSlotRebuildTimestamps() []time.Time {+ s.rebuildMu.Lock()+ defer s.rebuildMu.Unlock()++ return slices.Clone(s.rebuildTimestamps)+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/testing.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/testing.goindex 507d2f0b..d0e3da0c 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/testing.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/testing.go@@ -720,35 +720,48 @@ type WalStreamerForTest struct {Stop func()}+type WalStreamerTestSpec struct {+ Fixture *PhysicalDBFixture+ Storage storages.StorageFileSaver+ WatchDirRoot string+ WalLagThresholdBytes int64+ ForcedRotationInterval time.Duration+ ArchiveStalenessThreshold time.Duration+ OnSlotRebuilt func(ctx context.Context, reason string) error+ OnChainAtRisk func(report ChainRiskReport)+}+// A replication slot is meant to outlive a streamer restart (so WAL is never// lost), so the supervisor deliberately does NOT drop it on shutdown. In tests// that would leak one slot per run until max_replication_slots is exhausted, so// drop this streamer's slot here. Registered before the caller's stop cleanup,// it runs (LIFO) right after the streamer has stopped and before the conn closes.-func StartWalStreamerForTest(- t *testing.T,- fixture *PhysicalDBFixture,- store storages.StorageFileSaver,- watchDirRoot string,-) *WalStreamerForTest {+func StartWalStreamerForTest(t *testing.T, spec WalStreamerTestSpec) *WalStreamerForTest {t.Helper()+ fixture := spec.Fixture+adminConn := OpenAdminConn(t, fixture)t.Cleanup(func() {DropReplicationSlotExternally(t, adminConn, fixture.DB.PostgresqlPhysical.ReplicationSlotName)})supervisor := NewWalStreamSupervisor(WalStreamSpec{- DatabaseID: fixture.DB.ID,- SourceDB: fixture.DB.PostgresqlPhysical,- StorageID: fixture.Storage.ID,- Storage: store,- Encryption: backups_core_enums.BackupEncryptionNone,- FieldEncryptor: encryption.GetFieldEncryptor(),- WalSegmentRepo: physical_repositories.GetWalSegmentRepository(),- HistoryRepo: physical_repositories.GetWalHistoryRepository(),- WatchDirRoot: watchDirRoot,- Logger: logger.GetLogger(),+ DatabaseID: fixture.DB.ID,+ SourceDB: fixture.DB.PostgresqlPhysical,+ StorageID: fixture.Storage.ID,+ Storage: spec.Storage,+ Encryption: backups_core_enums.BackupEncryptionNone,+ FieldEncryptor: encryption.GetFieldEncryptor(),+ WalSegmentRepo: physical_repositories.GetWalSegmentRepository(),+ HistoryRepo: physical_repositories.GetWalHistoryRepository(),+ WatchDirRoot: spec.WatchDirRoot,+ WalLagThresholdBytes: spec.WalLagThresholdBytes,+ ForcedRotationInterval: spec.ForcedRotationInterval,+ ArchiveStalenessThreshold: spec.ArchiveStalenessThreshold,+ OnSlotRebuilt: spec.OnSlotRebuilt,+ OnChainAtRisk: spec.OnChainAtRisk,+ Logger: logger.GetLogger(),})ctx, cancel := context.WithCancel(t.Context())@@ -762,7 +775,7 @@ func StartWalStreamerForTest(return &WalStreamerForTest{Supervisor: supervisor,- WatchDir: filepath.Join(watchDirRoot, "wal-queue", fixture.DB.ID.String()),+ WatchDir: filepath.Join(spec.WatchDirRoot, "wal-queue", fixture.DB.ID.String()),Stop: func() {cancel()diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_backpressure.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_backpressure.goindex 1d8ab98b..50e9af9c 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_backpressure.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_backpressure.go@@ -4,6 +4,7 @@ import ("context""log/slog""os"+ "path/filepath""time""databasus-backend/internal/util/walmath"@@ -63,9 +64,16 @@ func (s *WalStreamSupervisor) waitForBacklogBelowLow(ctx context.Context, logger}// Uploaded segments are removed by the uploader, so summing what is left is the-// local queue depth; .partial and .history files are excluded.+// local queue depth; .partial and .history files are excluded. Segments staged out+// of pg_receivewal's resume path (wal_resume.go) are still waiting for the same+// uploader on the same disk, so they count too — otherwise a storage outage plus a+// realign grows the queue past the watermark with nothing throttling the receiver.func (s *WalStreamSupervisor) backlogBytes() int64 {- entries, err := os.ReadDir(s.watchDir)+ return sumWalSegmentBytes(s.watchDir) + sumWalSegmentBytes(filepath.Join(s.watchDir, pendingUploadDirName))+}++func sumWalSegmentBytes(dir string) int64 {+ entries, err := os.ReadDir(dir)if err != nil {return 0}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_backpressure_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_backpressure_test.goindex ecf615e4..19a71189 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_backpressure_test.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_backpressure_test.go@@ -1,6 +1,8 @@package usecases_physical_postgresqlimport (+ "os"+ "path/filepath""testing""github.com/stretchr/testify/require"@@ -23,3 +25,28 @@ func Test_WalStream_BackpressureWatermarks_ScaleWithWalSegmentSize(t *testing.T)require.Equal(t, 8*customSegSize, supervisor.highWatermarkBytes)require.Equal(t, 8*customSegSize/5, supervisor.lowWatermarkBytes)}++func Test_BacklogBytes_WhenSegmentsStagedOutOfResumePath_CountsThemTowardTheWatermark(t *testing.T) {+ fixture := SetupPhysicalDBForBackup(t)++ supervisor := NewWalStreamSupervisor(WalStreamSpec{+ DatabaseID: fixture.DB.ID,+ SourceDB: fixture.DB.PostgresqlPhysical,+ WatchDirRoot: t.TempDir(),+ Logger: logger.GetLogger(),+ })++ pendingUploadDir := filepath.Join(supervisor.watchDir, pendingUploadDirName)+ require.NoError(t, os.MkdirAll(pendingUploadDir, 0o700))++ for _, segmentNo := range []uint64{50, 51} {+ writeSegmentOfSize(t, supervisor.watchDir, walName(1, segmentNo), testWalSegmentSize)+ }++ for _, stagedSegmentNo := range []uint64{47, 48, 49} {+ writeSegmentOfSize(t, pendingUploadDir, walName(1, stagedSegmentNo), testWalSegmentSize)+ }++ require.Equal(t, 5*testWalSegmentSize, supervisor.backlogBytes(),+ "segments awaiting upload still occupy the local queue's disk, wherever they were staged")+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_resume.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_resume.goindex eaef9124..30f5d6a2 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_resume.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_resume.go@@ -36,9 +36,7 @@ func GetResumeSegmentNo(continue}- // pg_receivewal ignores a short file: a torn segment is re-streamed, not resumed past.- info, err := entry.Info()- if err != nil || info.Size() != segmentSizeBytes {+ if !isCompleteSegmentFile(filepath.Join(watchDir, entry.Name()), segmentSizeBytes) {continue}@@ -84,10 +82,13 @@ func movePendingUploadsOutOfResumePath(continue}- moveErr := os.Rename(- filepath.Join(watchDir, entry.Name()),- filepath.Join(pendingUploadDir, entry.Name()),- )+ segmentPath := filepath.Join(watchDir, entry.Name())++ if !isCompleteSegmentFile(segmentPath, segmentSizeBytes) {+ continue+ }++ moveErr := os.Rename(segmentPath, filepath.Join(pendingUploadDir, entry.Name()))if moveErr != nil && !os.IsNotExist(moveErr) {return movedCount, fmt.Errorf("move %s out of the resume path: %w", entry.Name(), moveErr)}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_resume_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_resume_test.goindex e0283c31..a0b41070 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_resume_test.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_resume_test.go@@ -1,22 +1,19 @@package usecases_physical_postgresqlimport (- "bytes""os""path/filepath""testing"+ "github.com/google/uuid""github.com/stretchr/testify/require"+ postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical"+ "databasus-backend/internal/util/encryption"+ "databasus-backend/internal/util/logger""databasus-backend/internal/util/walmath")-func writeSegmentOfSize(t *testing.T, dir, name string, sizeBytes int64) {- t.Helper()-- require.NoError(t, os.WriteFile(filepath.Join(dir, name), bytes.Repeat([]byte{0}, int(sizeBytes)), 0o600))-}-func Test_GetResumeSegmentNo_WithCompletePartialAndTornFiles_ReturnsHighestCompletePlusOne(t *testing.T) {watchDir := t.TempDir()@@ -81,6 +78,58 @@ func Test_MovePendingUploadsOutOfResumePath_LeavesHistoryFilesAndSubdirectories(require.DirExists(t, filepath.Join(watchDir, "archive_status"))}+func Test_MovePendingUploadsOutOfResumePath_WhenSegmentIsShort_LeavesItForRestreaming(t *testing.T) {+ watchDir := t.TempDir()++ writeSegmentOfSize(t, watchDir, walName(1, 40), testWalSegmentSize)+ writeSegmentOfSize(t, watchDir, walName(1, 41), testWalSegmentSize/2)++ movedCount, err := movePendingUploadsOutOfResumePath(watchDir, walmath.WalSegmentNo(42), testWalSegmentSize)+ require.NoError(t, err)+ require.Equal(t, 1, movedCount)++ require.FileExists(t, filepath.Join(watchDir, pendingUploadDirName, walName(1, 40)))+ require.FileExists(+ t,+ filepath.Join(watchDir, walName(1, 41)),+ "a torn segment is re-streamed, and it cannot anchor the resume point, so staging it would only risk uploading it",+ )+ require.NoFileExists(t, filepath.Join(watchDir, pendingUploadDirName, walName(1, 41)))+}++func Test_RealignResumePath_WhenSourceUnreachable_LeavesQueueUntouched(t *testing.T) {+ unreachableSourceDB := &postgresql_physical.PostgresqlPhysicalDatabase{+ Host: "127.0.0.1",+ Port: 1,+ Username: "streamer",+ Password: "streamer",+ ReplicationSlotName: "databasus_unreachable_source",+ }++ supervisor := NewWalStreamSupervisor(WalStreamSpec{+ DatabaseID: uuid.New(),+ SourceDB: unreachableSourceDB,+ FieldEncryptor: encryption.GetFieldEncryptor(),+ WatchDirRoot: t.TempDir(),+ Logger: logger.GetLogger(),+ })++ require.NoError(t, os.MkdirAll(supervisor.watchDir, 0o700))++ for _, segmentNo := range []uint64{60, 61} {+ writeSegmentOfSize(t, supervisor.watchDir, walName(1, segmentNo), testWalSegmentSize)+ }++ supervisor.realignResumePath(t.Context(), logger.GetLogger())++ for _, segmentNo := range []uint64{60, 61} {+ require.FileExists(t, filepath.Join(supervisor.watchDir, walName(1, segmentNo)),+ "without the slot's restart_lsn there is no floor to realign against, so the queue must stay put")+ }++ require.NoDirExists(t, filepath.Join(supervisor.watchDir, pendingUploadDirName))+}+func Test_SegmentNoAtLsn_WithNonDefaultSegmentSize_UsesTheClusterSize(t *testing.T) {const customSegmentSize = int64(64 * 1024 * 1024)diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_rotation.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_rotation.gonew file mode 100644index 00000000..b95a505d--- /dev/null+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_rotation.go@@ -0,0 +1,173 @@+package usecases_physical_postgresql++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "strings"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"++ "databasus-backend/internal/util/walmath"+)++// Only a finalized segment is uploaded, so a database that writes a few bytes an+// hour would keep its newest WAL local until the segment fills — hours or days of+// recovery point sitting on one disk. Forcing a rotation on this cadence bounds+// that, at the cost of one mostly-empty segment per interval while the source is+// being written to. Exported because the wiring layer builds WalStreamSpec.+const DefaultForcedRotationInterval = 5 * time.Minute++const forcedRotationPollInterval = 30 * time.Second++const pgErrorCodeInsufficientPrivilege = "42501"++type walRotationSample struct {+ CurrentLSN walmath.LSN+ ObservedAt time.Time+}++type walRotationTracker struct {+ lastRotatedLSN walmath.LSN+ lastRotatedAt time.Time+}++// A source that has written nothing since the last rotation must not be rotated+// again: otherwise a database that takes one write per day would still archive a+// padded segment every interval. The first sample only starts the clock, so the+// very first rotation waits one interval like every other.+func (t *walRotationTracker) recordSampleAndDecideRotation(+ sample walRotationSample,+ rotationInterval time.Duration,+) (shouldRotate bool) {+ if t.lastRotatedAt.IsZero() {+ t.lastRotatedAt = sample.ObservedAt++ return false+ }++ if sample.CurrentLSN <= t.lastRotatedLSN {+ return false+ }++ return sample.ObservedAt.Sub(t.lastRotatedAt) >= rotationInterval+}++// The post-rotation position, not the position we decided on: pg_switch_wal moves+// the insert point into the new segment, and treating that move as fresh WAL would+// rotate again every interval on an otherwise idle source.+func (t *walRotationTracker) recordRotation(currentLSNAfterRotation walmath.LSN, rotatedAt time.Time) {+ t.lastRotatedLSN = currentLSNAfterRotation+ t.lastRotatedAt = rotatedAt+}++// Rotation is best effort: pg_switch_wal is superuser-only unless EXECUTE is+// granted, while physical backups only require REPLICATION. A refusal is+// permanent, so the loop reports it once and stops instead of polling forever.+func (s *WalStreamSupervisor) runForcedWalRotation(ctx context.Context, logger *slog.Logger) {+ if s.spec.ForcedRotationInterval <= 0 {+ return+ }++ ticker := time.NewTicker(min(forcedRotationPollInterval, s.spec.ForcedRotationInterval))+ defer ticker.Stop()++ var rotationTracker walRotationTracker++ for {+ select {+ case <-ctx.Done():+ return++ case <-ticker.C:+ currentLSN, isSourceReachable := s.getCurrentWalLsnIfReachable(ctx, logger)+ if !isSourceReachable {+ continue+ }++ isRotationDue := rotationTracker.recordSampleAndDecideRotation(walRotationSample{+ CurrentLSN: currentLSN,+ ObservedAt: time.Now().UTC(),+ }, s.spec.ForcedRotationInterval)++ if !isRotationDue {+ continue+ }++ currentLSNAfterRotation, err := s.forceWalRotation(ctx)+ if err != nil {+ if !isInsufficientPrivilegeError(err) {+ logger.Warn("forced wal rotation failed; will retry", "error", err)++ continue+ }++ logger.Warn("source refuses pg_switch_wal; forced wal rotation disabled for this streamer",+ "error", err)++ s.reportChainAtRisk(logger, breakReasonRotationDenied, nil)++ return+ }++ rotationTracker.recordRotation(currentLSNAfterRotation, time.Now().UTC())++ logger.Debug("forced a wal segment switch so the recovery point keeps advancing")+ }+ }+}++func (s *WalStreamSupervisor) getCurrentWalLsnIfReachable(+ ctx context.Context,+ logger *slog.Logger,+) (currentLSN walmath.LSN, isSourceReachable bool) {+ conn, err := s.spec.SourceDB.OpenInspectionConn(ctx, s.spec.FieldEncryptor)+ if err != nil {+ logger.Debug("forced wal rotation: source unreachable this tick", "error", err)++ return 0, false+ }+ defer func() { _ = conn.Close(context.Background()) }()++ currentLSN, err = readCurrentWalLSN(ctx, conn)+ if err != nil {+ return 0, false+ }++ return currentLSN, true+}++func readCurrentWalLSN(ctx context.Context, conn *pgx.Conn) (walmath.LSN, error) {+ var currentLSNText string+ if err := conn.QueryRow(ctx, "SELECT pg_current_wal_lsn()::text").Scan(¤tLSNText); err != nil {+ return 0, fmt.Errorf("read current wal position: %w", err)+ }++ return walmath.ParseLSN(currentLSNText)+}++func (s *WalStreamSupervisor) forceWalRotation(ctx context.Context) (currentLSNAfterRotation walmath.LSN, err error) {+ conn, err := s.spec.SourceDB.OpenInspectionConn(ctx, s.spec.FieldEncryptor)+ if err != nil {+ return 0, fmt.Errorf("open conn for wal switch: %w", err)+ }+ defer func() { _ = conn.Close(context.Background()) }()++ if _, err := conn.Exec(ctx, "SELECT pg_switch_wal()"); err != nil {+ return 0, fmt.Errorf("pg_switch_wal: %w", err)+ }++ return readCurrentWalLSN(ctx, conn)+}++func isInsufficientPrivilegeError(err error) bool {+ var pgErr *pgconn.PgError+ if errors.As(err, &pgErr) {+ return pgErr.Code == pgErrorCodeInsufficientPrivilege+ }++ return strings.Contains(strings.ToLower(err.Error()), "permission denied")+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_rotation_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_rotation_test.gonew file mode 100644index 00000000..5845c799--- /dev/null+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_rotation_test.go@@ -0,0 +1,104 @@+package usecases_physical_postgresql++import (+ "errors"+ "fmt"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgconn"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/util/walmath"+)++const testRotationInterval = 5 * time.Minute++func Test_RecordSampleAndDecideRotation_WhenWalWrittenSinceLastRotation_RotatesSegment(t *testing.T) {+ var rotationTracker walRotationTracker++ base := time.Now().UTC()++ require.False(t, rotationTracker.recordSampleAndDecideRotation(walRotationSample{+ CurrentLSN: walmath.LSN(1_000),+ ObservedAt: base,+ }, testRotationInterval), "the first sample only anchors the interval")++ require.True(t, rotationTracker.recordSampleAndDecideRotation(walRotationSample{+ CurrentLSN: walmath.LSN(2_000),+ ObservedAt: base.Add(testRotationInterval + time.Second),+ }, testRotationInterval), "WAL was written and the interval elapsed, so it must not wait for the segment to fill")+}++func Test_RecordSampleAndDecideRotation_WhenNothingWrittenSinceLastRotation_SkipsRotation(t *testing.T) {+ var rotationTracker walRotationTracker++ base := time.Now().UTC()+ idleLSN := walmath.LSN(1_000)++ require.False(t, rotationTracker.recordSampleAndDecideRotation(walRotationSample{+ CurrentLSN: idleLSN,+ ObservedAt: base,+ }, testRotationInterval))++ rotationTracker.recordRotation(idleLSN, base.Add(time.Second))++ require.False(t, rotationTracker.recordSampleAndDecideRotation(walRotationSample{+ CurrentLSN: idleLSN,+ ObservedAt: base.Add(3 * testRotationInterval),+ }, testRotationInterval), "a dead-quiet source must not be charged a padded segment per interval")+}++func Test_RecordSampleAndDecideRotation_WhenIntervalNotElapsed_SkipsRotation(t *testing.T) {+ var rotationTracker walRotationTracker++ base := time.Now().UTC()++ require.False(t, rotationTracker.recordSampleAndDecideRotation(walRotationSample{+ CurrentLSN: walmath.LSN(1_000),+ ObservedAt: base,+ }, testRotationInterval))++ require.False(t, rotationTracker.recordSampleAndDecideRotation(walRotationSample{+ CurrentLSN: walmath.LSN(2_000),+ ObservedAt: base.Add(testRotationInterval / 2),+ }, testRotationInterval), "a busy source rotates on its own; forcing it more often than the interval is waste")+}++func Test_IsInsufficientPrivilegeError_WhenSwitchWalRefused_DetectsMissingPrivilege(t *testing.T) {+ refusal := fmt.Errorf("pg_switch_wal: %w", &pgconn.PgError{+ Code: pgErrorCodeInsufficientPrivilege,+ Message: "permission denied for function pg_switch_wal",+ })++ require.True(t, isInsufficientPrivilegeError(refusal),+ "physical backups only require REPLICATION, so a refusal is the expected case, not a retryable blip")+}++func Test_IsInsufficientPrivilegeError_WhenSourceUnreachable_ReportsRetryable(t *testing.T) {+ require.False(t, isInsufficientPrivilegeError(errors.New("dial tcp 127.0.0.1:5432: connect: connection refused")))+}++func Test_RecordRotation_WhenSwitchMovedTheInsertPoint_DoesNotCountItAsFreshWal(t *testing.T) {+ var rotationTracker walRotationTracker++ base := time.Now().UTC()++ require.False(t, rotationTracker.recordSampleAndDecideRotation(walRotationSample{+ CurrentLSN: walmath.LSN(1_000),+ ObservedAt: base,+ }, testRotationInterval))++ require.True(t, rotationTracker.recordSampleAndDecideRotation(walRotationSample{+ CurrentLSN: walmath.LSN(1_000),+ ObservedAt: base.Add(testRotationInterval),+ }, testRotationInterval), "WAL written before the streamer started still has to reach storage")++ currentLSNAfterRotation := walmath.LSN(16 * 1024 * 1024)+ rotationTracker.recordRotation(currentLSNAfterRotation, base.Add(testRotationInterval))++ require.False(t, rotationTracker.recordSampleAndDecideRotation(walRotationSample{+ CurrentLSN: currentLSNAfterRotation,+ ObservedAt: base.Add(10 * testRotationInterval),+ }, testRotationInterval), "the switch itself moved the insert point; that is not the source writing")+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_staleness.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_staleness.gonew file mode 100644index 00000000..f10642e9--- /dev/null+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_staleness.go@@ -0,0 +1,92 @@+package usecases_physical_postgresql++import (+ "log/slog"+ "time"++ "databasus-backend/internal/util/walmath"+)++// A rarely-written database can legitimately hold its newest WAL locally for a+// while, but past this the recovery point has silently stopped tracking the+// source and only the operator can decide what to do about it.+const DefaultArchiveStalenessThreshold = 30 * time.Minute++type walArchiveSample struct {+ SourceCurrentLSN walmath.LSN+ LastCommittedWalLSN walmath.LSN+ ObservedAt time.Time+ StalenessThreshold time.Duration+}++type walArchiveStalenessTracker struct {+ previousSourceCurrentLSN walmath.LSN+ lastCommittedWalLSN walmath.LSN+ hasSample bool++ fallingBehindSince time.Time+ isStaleReported bool+}++// Falling behind means the source keeps writing while nothing new becomes+// restorable. Both halves are needed: an idle source always leaves its open+// segment slightly ahead of the last archived one — that is the RPO forced+// rotation exists for, not an incident — and a slow archive that still delivers+// segments is not stale either. The clock survives quiet ticks, so bursty writes+// with a broken archive are still caught.+func (t *walArchiveStalenessTracker) recordSampleAndDetectStaleness(sample walArchiveSample) bool {+ if sample.StalenessThreshold <= 0 {+ *t = walArchiveStalenessTracker{}++ return false+ }++ isSourceWriting := t.hasSample && sample.SourceCurrentLSN > t.previousSourceCurrentLSN+ isArchiveProgressing := sample.LastCommittedWalLSN > t.lastCommittedWalLSN++ t.previousSourceCurrentLSN = sample.SourceCurrentLSN+ t.lastCommittedWalLSN = max(t.lastCommittedWalLSN, sample.LastCommittedWalLSN)+ t.hasSample = true++ if isArchiveProgressing {+ t.fallingBehindSince = time.Time{}+ t.isStaleReported = false++ return false+ }++ if t.fallingBehindSince.IsZero() {+ if !isSourceWriting {+ return false+ }++ t.fallingBehindSince = sample.ObservedAt++ return false+ }++ if t.isStaleReported || sample.ObservedAt.Sub(t.fallingBehindSince) < sample.StalenessThreshold {+ return false+ }++ t.isStaleReported = true++ return true+}++func (s *WalStreamSupervisor) getLastCommittedWal(logger *slog.Logger) (endLSN walmath.LSN, committedAt *time.Time) {+ segment, err := s.spec.WalSegmentRepo.FindLatestCommittedSegment(s.spec.DatabaseID)+ if err != nil {+ logger.Error("failed to read the last committed wal segment", "error", err)++ return 0, nil+ }++ if segment == nil {+ return 0, nil+ }++ receivedAt := segment.ReceivedAt++ return segment.EndLSN, &receivedAt+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_staleness_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_staleness_test.gonew file mode 100644index 00000000..f44583a7--- /dev/null+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_staleness_test.go@@ -0,0 +1,139 @@+package usecases_physical_postgresql++import (+ "testing"+ "time"++ "github.com/stretchr/testify/require"++ "databasus-backend/internal/util/walmath"+)++const testStalenessThreshold = 30 * time.Minute++// The source keeps writing while the newest restorable segment stays where it is.+func fallingBehindSample(sourceCurrentLSN walmath.LSN, observedAt time.Time) walArchiveSample {+ return walArchiveSample{+ SourceCurrentLSN: sourceCurrentLSN,+ LastCommittedWalLSN: walmath.LSN(testWalSegmentSize),+ ObservedAt: observedAt,+ StalenessThreshold: testStalenessThreshold,+ }+}++func Test_RecordSampleAndDetectStaleness_WhenSourceKeepsWritingAndNothingCommitsPastThreshold_DetectsStaleness(+ t *testing.T,+) {+ var stalenessTracker walArchiveStalenessTracker++ base := time.Now().UTC()+ writtenLSN := walmath.LSN(2 * testWalSegmentSize)++ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(fallingBehindSample(writtenLSN, base)),+ "the first sample cannot tell whether the source is writing")+ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(+ fallingBehindSample(writtenLSN+4096, base.Add(time.Minute)),+ ), "the source is writing now, so the clock starts")++ require.True(t, stalenessTracker.recordSampleAndDetectStaleness(+ fallingBehindSample(writtenLSN+8192, base.Add(testStalenessThreshold+2*time.Minute)),+ ), "WAL kept being written and none of it became restorable — the operator has to hear about it")++ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(+ fallingBehindSample(writtenLSN+12288, base.Add(2*testStalenessThreshold)),+ ), "one alert per incident; the throttle in the wiring layer must not be the only guard")+}++func Test_RecordSampleAndDetectStaleness_WhenSourceIsIdle_DoesNotDetectStaleness(t *testing.T) {+ var stalenessTracker walArchiveStalenessTracker++ base := time.Now().UTC()++ // An idle source parks its insert point inside the open segment, so it sits+ // permanently ahead of the newest archived one. That gap is what forced+ // rotation is for, not an incident.+ idleSourceLSN := walmath.LSN(testWalSegmentSize + 4096)++ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(fallingBehindSample(idleSourceLSN, base)))+ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(+ fallingBehindSample(idleSourceLSN, base.Add(24*time.Hour)),+ ), "a database nobody writes to can never fall further behind")+}++func Test_RecordSampleAndDetectStaleness_WhenSegmentCommits_ReArmsClock(t *testing.T) {+ var stalenessTracker walArchiveStalenessTracker++ base := time.Now().UTC()+ writtenLSN := walmath.LSN(2 * testWalSegmentSize)++ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(fallingBehindSample(writtenLSN, base)))+ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(+ fallingBehindSample(writtenLSN+4096, base.Add(time.Minute)),+ ))++ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(walArchiveSample{+ SourceCurrentLSN: writtenLSN + 8192,+ LastCommittedWalLSN: walmath.LSN(2 * testWalSegmentSize),+ ObservedAt: base.Add(testStalenessThreshold / 2),+ StalenessThreshold: testStalenessThreshold,+ }), "a segment reached storage")++ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(walArchiveSample{+ SourceCurrentLSN: writtenLSN + 12288,+ LastCommittedWalLSN: walmath.LSN(2 * testWalSegmentSize),+ ObservedAt: base.Add(testStalenessThreshold + time.Minute),+ StalenessThreshold: testStalenessThreshold,+ }), "a slow but progressing archive must not accumulate staleness across the segments it did deliver")+}++func Test_RecordSampleAndDetectStaleness_WithinThreshold_DoesNotDetectStaleness(t *testing.T) {+ var stalenessTracker walArchiveStalenessTracker++ base := time.Now().UTC()+ writtenLSN := walmath.LSN(2 * testWalSegmentSize)++ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(fallingBehindSample(writtenLSN, base)))+ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(+ fallingBehindSample(writtenLSN+4096, base.Add(time.Minute)),+ ))+ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(+ fallingBehindSample(writtenLSN+8192, base.Add(testStalenessThreshold-time.Minute)),+ ), "a segment being filled right now is normal, not a stalled recovery point")+}++func Test_RecordSampleAndDetectStaleness_WhenWritesAreBursty_KeepsCountingAcrossQuietTicks(t *testing.T) {+ var stalenessTracker walArchiveStalenessTracker++ base := time.Now().UTC()+ writtenLSN := walmath.LSN(2 * testWalSegmentSize)++ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(fallingBehindSample(writtenLSN, base)))+ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(+ fallingBehindSample(writtenLSN+4096, base.Add(time.Minute)),+ ))++ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(+ fallingBehindSample(writtenLSN+4096, base.Add(2*time.Minute)),+ ), "a quiet tick mid-incident is not recovery")++ require.True(t, stalenessTracker.recordSampleAndDetectStaleness(+ fallingBehindSample(writtenLSN+4096, base.Add(testStalenessThreshold+2*time.Minute)),+ ), "a broken archive must not escape detection just because the writes came in bursts")+}++func Test_RecordSampleAndDetectStaleness_WhenThresholdDisabled_DoesNotDetectStaleness(t *testing.T) {+ var stalenessTracker walArchiveStalenessTracker++ base := time.Now().UTC()+ writtenLSN := walmath.LSN(2 * testWalSegmentSize)++ disabledSample := fallingBehindSample(writtenLSN, base)+ disabledSample.StalenessThreshold = 0++ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(disabledSample))++ disabledSample.SourceCurrentLSN = writtenLSN + 4096+ disabledSample.ObservedAt = base.Add(24 * time.Hour)++ require.False(t, stalenessTracker.recordSampleAndDetectStaleness(disabledSample))+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream.goindex cc4cc009..bd5e0bc9 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream.go@@ -48,6 +48,33 @@ const (pausePollInterval = 1 * time.Second)+type resumeMismatchAction int++const (+ resumeMismatchActionRetry resumeMismatchAction = iota+ resumeMismatchActionRebuildSlot+)++type resumeMismatchEscalator struct {+ mismatchCount int+}++func (e *resumeMismatchEscalator) recordMismatchAndDecideEscalation() resumeMismatchAction {+ e.mismatchCount++++ if e.mismatchCount >= receivewalMaxResumeMismatches {+ e.mismatchCount = 0++ return resumeMismatchActionRebuildSlot+ }++ return resumeMismatchActionRetry+}++func (e *resumeMismatchEscalator) reset() {+ e.mismatchCount = 0+}+type WalStreamSpec struct {DatabaseID uuid.UUIDSourceDB *postgresql_physical.PostgresqlPhysicalDatabase@@ -67,6 +94,15 @@ type WalStreamSpec struct {// A slot lag over this many bytes triggers a rebuild (lag_monitor.go).WalLagThresholdBytes int64+ // How often a source that is being written to is asked to close its current WAL+ // segment, so the newest WAL reaches storage without waiting for the segment to+ // fill (wal_rotation.go). Zero disables it.+ ForcedRotationInterval time.Duration++ // How far the archived recovery point may fall behind a source that keeps+ // writing before the operator is alerted (wal_staleness.go). Zero disables it.+ ArchiveStalenessThreshold time.Duration+// Fires once per newly-observed WAL gap (see WalUploader); nil disables// notification.OnGapDetected func(gapStart, gapEnd walmath.LSN)@@ -183,6 +219,7 @@ func (s *WalStreamSupervisor) Run(ctx context.Context) error {s.runBackpressureMonitor,s.runSlotLsnWatcher,s.runLagMonitor,+ s.runForcedWalRotation,} {wg.Go(func() { loop(runCtx, logger) })}@@ -210,7 +247,8 @@ func (s *WalStreamSupervisor) runReceivewalSupervision(ctx context.Context, loggpgBin := tools.GetPostgresqlExecutable(s.spec.SourceDB.Version, tools.PostgresqlExecutablePgReceivewal)respawnBackoff := receivewalRespawnBackoffrapidFailures := 0- resumeMismatches := 0++ var mismatchEscalator resumeMismatchEscalatorfor {if ctx.Err() != nil {@@ -245,16 +283,13 @@ func (s *WalStreamSupervisor) runReceivewalSupervision(ctx context.Context, logg// top-of-loop backlog/pause gates already throttle the cause.respawnBackoff = receivewalRespawnBackoffrapidFailures = 0- resumeMismatches = 0++ mismatchEscalator.reset()continuecase receiverResumeMismatch:- resumeMismatches++-- if resumeMismatches >= receivewalMaxResumeMismatches {- resumeMismatches = 0-+ if mismatchEscalator.recordMismatchAndDecideEscalation() == resumeMismatchActionRebuildSlot {if err := s.rebuildSlot(ctx, logger, breakReasonSlotLost); err != nil {return fmt.Errorf("rebuild slot after repeated wal resume mismatch: %w", err)}@@ -267,7 +302,7 @@ func (s *WalStreamSupervisor) runReceivewalSupervision(ctx context.Context, loggcontinue}- resumeMismatches = 0+ mismatchEscalator.reset()// receiverRetryable: a run that streamed for a healthy span is a transient// blip (network) — reset the crash-loop counter; a string of sub-uptimediff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream_test.goindex 0360035b..8853c4e7 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream_test.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream_test.go@@ -2,8 +2,12 @@ package usecases_physical_postgresqlimport ("context"+ "fmt""os""path/filepath"+ "slices"+ "strings"+ "sync""testing""time"@@ -15,6 +19,7 @@ import ("databasus-backend/internal/features/backups/backups/core/physical/chain_view"physical_models "databasus-backend/internal/features/backups/backups/core/physical/models"physical_repositories "databasus-backend/internal/features/backups/backups/core/physical/repositories"+ postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical""databasus-backend/internal/util/encryption""databasus-backend/internal/util/logger""databasus-backend/internal/util/walmath"@@ -32,7 +37,10 @@ func Test_WalStream_FullIncrementalAndWalStream_StreamerArchivesSegments(t *teststore := newMockWalStorage()- stop := StartWalStreamerForTest(t, fixture, store, t.TempDir()).Stop+ stop := StartWalStreamerForTest(+ t,+ WalStreamerTestSpec{Fixture: fixture, Storage: store, WatchDirRoot: t.TempDir()},+ ).Stopt.Cleanup(stop)adminConn := OpenAdminConn(t, fixture)@@ -129,8 +137,18 @@ func Test_WalStream_MultipleDbs_EachArchivesSegmentsIndependently(t *testing.T)storeA := newMockWalStorage()storeB := newMockWalStorage()- t.Cleanup(StartWalStreamerForTest(t, fixtureA, storeA, t.TempDir()).Stop)- t.Cleanup(StartWalStreamerForTest(t, fixtureB, storeB, t.TempDir()).Stop)+ t.Cleanup(+ StartWalStreamerForTest(+ t,+ WalStreamerTestSpec{Fixture: fixtureA, Storage: storeA, WatchDirRoot: t.TempDir()},+ ).Stop,+ )+ t.Cleanup(+ StartWalStreamerForTest(+ t,+ WalStreamerTestSpec{Fixture: fixtureB, Storage: storeB, WatchDirRoot: t.TempDir()},+ ).Stop,+ )connA := OpenAdminConn(t, fixtureA)@@ -166,7 +184,12 @@ func Test_WalStream_MissingSegmentInStreamedChain_SurfacesAsGapChainStaysExtendastore := newMockWalStorage()adminConn := OpenAdminConn(t, fixture)- t.Cleanup(StartWalStreamerForTest(t, fixture, store, t.TempDir()).Stop)+ t.Cleanup(+ StartWalStreamerForTest(+ t,+ WalStreamerTestSpec{Fixture: fixture, Storage: store, WatchDirRoot: t.TempDir()},+ ).Stop,+ )ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute)defer cancel()@@ -228,7 +251,11 @@ func Test_WalStream_SlotLagGrowsWithoutConsumer_DrainsOnceStreaming(t *testing.TWaitUntilSlotLag(t, adminConn, slotName, lagTarget, 30*time.Second)// Once our streamer attaches, it consumes the backlog and the lag drains.- t.Cleanup(StartWalStreamerForTest(t, fixture, newMockWalStorage(), t.TempDir()).Stop)+ t.Cleanup(StartWalStreamerForTest(t, WalStreamerTestSpec{+ Fixture: fixture,+ Storage: newMockWalStorage(),+ WatchDirRoot: t.TempDir(),+ }).Stop)deadline := time.Now().UTC().Add(60 * time.Second)for time.Now().UTC().Before(deadline) {@@ -263,7 +290,8 @@ func Test_WalStream_CustomWalSegmentSize_LsnMathCorrect(t *testing.T) {// logid=2, segLow=3 starts at (2<<32) + 3*64MB.dir := t.TempDir()name := "000000010000000200000003"- require.NoError(t, uploader.ProcessSegment(context.Background(), writeWalFile(t, dir, name), name))+ segmentPath := writeSegmentOfSize(t, dir, name, customSegSize)+ require.NoError(t, uploader.ProcessSegment(context.Background(), segmentPath, name))expectedStartLSN := walmath.LSN((uint64(2) << 32) + 3*uint64(customSegSize))@@ -338,7 +366,11 @@ func Test_WalStream_ResumePointBelowSlotRestartLsn_RealignsAndKeepsStreaming(t *store := newMockWalStorage()store.startFailingSaves()- firstRun := StartWalStreamerForTest(t, fixture, store, watchDirRoot)+ firstRun := StartWalStreamerForTest(t, WalStreamerTestSpec{+ Fixture: fixture,+ Storage: store,+ WatchDirRoot: watchDirRoot,+ })for range 3 {_, err := ForceWalRotation(ctx, adminConn)@@ -375,7 +407,11 @@ func Test_WalStream_ResumePointBelowSlotRestartLsn_RealignsAndKeepsStreaming(t *requireQueueBelowSlot(t, ctx, adminConn, slotName, resumeSegmentNo)- secondRun := StartWalStreamerForTest(t, fixture, store, watchDirRoot)+ secondRun := StartWalStreamerForTest(t, WalStreamerTestSpec{+ Fixture: fixture,+ Storage: store,+ WatchDirRoot: watchDirRoot,+ })t.Cleanup(secondRun.Stop)pendingUploadDir := filepath.Join(secondRun.WatchDir, pendingUploadDirName)@@ -487,3 +523,299 @@ func requireQueueBelowSlot(require.Less(t, uint64(resumeSegmentNo), uint64(segmentNoAtLSN(slotState.RestartLSN, segmentSizeBytes)),"the queue must sit below the recreated slot for this test to mean anything")}++// The supervisor invokes these callbacks from its own loops, so a plain slice+// would race with the assertions (and with require.Eventually's polling+// goroutine).+type chainEventRecorder struct {+ mu sync.Mutex+ reasons []string+}++func (r *chainEventRecorder) recordReason(reason string) {+ r.mu.Lock()+ defer r.mu.Unlock()++ r.reasons = append(r.reasons, reason)+}++func (r *chainEventRecorder) getReasons() []string {+ r.mu.Lock()+ defer r.mu.Unlock()++ return slices.Clone(r.reasons)+}++func (r *chainEventRecorder) getReasonCount() int {+ r.mu.Lock()+ defer r.mu.Unlock()++ return len(r.reasons)+}++func Test_RecordMismatchAndDecideEscalation_WhenFirstMismatch_RetriesAfterRealign(t *testing.T) {+ var mismatchEscalator resumeMismatchEscalator++ require.Equal(t, resumeMismatchActionRetry, mismatchEscalator.recordMismatchAndDecideEscalation(),+ "a realign clears the resume path, so the next spawn deserves a chance before the chain is broken")+}++func Test_RecordMismatchAndDecideEscalation_WhenSecondMismatch_RequestsSlotRebuild(t *testing.T) {+ var mismatchEscalator resumeMismatchEscalator++ require.Equal(t, resumeMismatchActionRetry, mismatchEscalator.recordMismatchAndDecideEscalation())+ require.Equal(t, resumeMismatchActionRebuildSlot, mismatchEscalator.recordMismatchAndDecideEscalation(),+ "a realigned queue that still asks for recycled WAL means the slot itself no longer covers the source")+}++func Test_RecordMismatchAndDecideEscalation_WhenHealthyRunBetweenMismatches_ResetsCounter(t *testing.T) {+ var mismatchEscalator resumeMismatchEscalator++ require.Equal(t, resumeMismatchActionRetry, mismatchEscalator.recordMismatchAndDecideEscalation())++ mismatchEscalator.reset()++ require.Equal(t, resumeMismatchActionRetry, mismatchEscalator.recordMismatchAndDecideEscalation(),+ "mismatches must be back-to-back to escalate; a healthy run in between clears the incident")+}++func Test_RecordMismatchAndDecideEscalation_AfterRebuild_StartsCountingFromScratch(t *testing.T) {+ var mismatchEscalator resumeMismatchEscalator++ mismatchEscalator.recordMismatchAndDecideEscalation()+ require.Equal(t, resumeMismatchActionRebuildSlot, mismatchEscalator.recordMismatchAndDecideEscalation())++ require.Equal(t, resumeMismatchActionRetry, mismatchEscalator.recordMismatchAndDecideEscalation(),+ "a rebuild is expensive, so the next one needs its own pair of mismatches")+}++func Test_WalStream_WhenSourceIsIdle_KeepsReceiverAliveAndDoesNotRebuildSlot(t *testing.T) {+ if testing.Short() {+ t.Skip("streamer integration test runs pg_receivewal; skipped in -short")+ }++ fixture := SetupPhysicalDBForBackup(t)+ t.Cleanup(func() {+ _ = physical_repositories.GetWalStreamerRepository().DeleteByDatabaseID(fixture.DB.ID)+ })++ adminConn := OpenAdminConn(t, fixture)+ slotName := fixture.DB.PostgresqlPhysical.ReplicationSlotName++ var slotRebuilds, chainRisks chainEventRecorder++ streamer := StartWalStreamerForTest(t, WalStreamerTestSpec{+ Fixture: fixture,+ Storage: newMockWalStorage(),+ WatchDirRoot: t.TempDir(),+ OnSlotRebuilt: func(_ context.Context, reason string) error {+ slotRebuilds.recordReason(reason)++ return nil+ },+ OnChainAtRisk: func(report ChainRiskReport) {+ chainRisks.recordReason(report.Reason)+ },+ })+ t.Cleanup(streamer.Stop)++ attachedReceiverPID := waitForAttachedReceiverPID(t, adminConn, slotName)++ // The stall window is 60 s and the watcher polls every 10 s, so this outlasts+ // several full detection cycles: restart_lsn parking on an idle source is not a+ // stall, and must not cost the receiver its connection.+ idleDeadline := time.Now().UTC().Add(150 * time.Second)+ for time.Now().UTC().Before(idleDeadline) {+ slotState, err := InspectSlot(t.Context(), adminConn, slotName)+ require.NoError(t, err)+ require.NotNil(t, slotState)+ require.NotNil(t, slotState.ActivePID, "an idle database is not a reason to drop the replication connection")+ require.Equal(t, attachedReceiverPID, *slotState.ActivePID,+ "restart_lsn parks legitimately while nothing is written; restarting pg_receivewal over it is the bug")++ time.Sleep(2 * time.Second)+ }++ streamer.Stop()++ require.Empty(t, slotRebuilds.getReasons(),+ "an idle database must never cost a WAL gap and an out-of-cadence full backup")+ require.Empty(t, chainRisks.getReasons())+ require.Empty(t, streamer.Supervisor.GetSlotRebuildTimestamps())+}++func waitForAttachedReceiverPID(t *testing.T, adminConn *pgx.Conn, slotName string) int {+ t.Helper()++ var attachedReceiverPID int++ require.Eventually(t, func() bool {+ slotState, err := InspectSlot(t.Context(), adminConn, slotName)+ if err != nil || slotState == nil || slotState.ActivePID == nil {+ return false+ }++ attachedReceiverPID = *slotState.ActivePID++ return true+ }, 60*time.Second, 250*time.Millisecond, "pg_receivewal never attached to the slot")++ return attachedReceiverPID+}++func Test_WalStream_WhenSourceWritesRarely_UploadsSegmentWithinRotationInterval(t *testing.T) {+ if testing.Short() {+ t.Skip("streamer integration test runs pg_receivewal; skipped in -short")+ }++ fixture := SetupPhysicalDBForBackup(t)+ t.Cleanup(func() {+ _ = physical_repositories.GetWalStreamerRepository().DeleteByDatabaseID(fixture.DB.ID)+ })++ adminConn := OpenAdminConn(t, fixture)++ t.Cleanup(StartWalStreamerForTest(t, WalStreamerTestSpec{+ Fixture: fixture,+ Storage: newMockWalStorage(),+ WatchDirRoot: t.TempDir(),+ ForcedRotationInterval: time.Second,+ }).Stop)++ // A handful of rows is nowhere near a full segment, so without a forced+ // rotation this WAL would sit in the local queue for as long as the source+ // stays quiet.+ _, err := GenerateWalActivity(t.Context(), adminConn, 4096)+ require.NoError(t, err)++ WaitForCommittedWalSegmentCount(t, fixture.DB.ID, 1, 90*time.Second)+}++func Test_WalStream_WhenSwitchWalIsRefused_AlertsOnceAndStopsRotating(t *testing.T) {+ if testing.Short() {+ t.Skip("streamer integration test runs pg_receivewal; skipped in -short")+ }++ fixture := SetupPhysicalDBForBackup(t)+ t.Cleanup(func() {+ _ = physical_repositories.GetWalStreamerRepository().DeleteByDatabaseID(fixture.DB.ID)+ })++ adminConn := OpenAdminConn(t, fixture)++ fixture.DB.PostgresqlPhysical = createReplicationOnlyRole(t, adminConn, fixture)++ var chainRisks chainEventRecorder++ t.Cleanup(StartWalStreamerForTest(t, WalStreamerTestSpec{+ Fixture: fixture,+ Storage: newMockWalStorage(),+ WatchDirRoot: t.TempDir(),+ ForcedRotationInterval: time.Second,+ OnChainAtRisk: func(report ChainRiskReport) {+ chainRisks.recordReason(report.Reason)+ },+ }).Stop)++ _, err := GenerateWalActivity(t.Context(), adminConn, 4096)+ require.NoError(t, err)++ require.Eventually(t, func() bool {+ return chainRisks.getReasonCount() > 0+ }, 90*time.Second, 500*time.Millisecond, "a source that refuses pg_switch_wal must be reported, not retried silently")++ require.Equal(t, []string{ChainRiskReasonRotationDenied}, chainRisks.getReasons())++ // The refusal is permanent, so the loop must be gone rather than re-alerting+ // every interval; streaming itself is unaffected.+ require.Never(t, func() bool {+ return chainRisks.getReasonCount() > 1+ }, 5*time.Second, time.Second, "a permanent refusal must be reported once, not once per interval")++ _, err = ForceWalRotation(t.Context(), adminConn)+ require.NoError(t, err)++ WaitForCommittedWalSegmentCount(t, fixture.DB.ID, 1, 90*time.Second)+}++// The physical backup role only needs REPLICATION, and PostgreSQL restricts+// pg_switch_wal to superusers unless EXECUTE is granted — so this is what a real+// deployment looks like, not a contrived setup.+func createReplicationOnlyRole(+ t *testing.T,+ adminConn *pgx.Conn,+ fixture *PhysicalDBFixture,+) *postgresql_physical.PostgresqlPhysicalDatabase {+ t.Helper()++ roleName := "databasus_no_switch_" + strings.ReplaceAll(uuid.New().String(), "-", "")[:12]++ _, err := adminConn.Exec(t.Context(),+ fmt.Sprintf("CREATE ROLE %s LOGIN REPLICATION PASSWORD 'switchless'", pgx.Identifier{roleName}.Sanitize()),+ )+ require.NoError(t, err)++ t.Cleanup(func() {+ _, _ = adminConn.Exec(context.Background(),+ fmt.Sprintf(+ "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = %s",+ pgx.Identifier{roleName}.Sanitize(),+ ),+ )+ _, _ = adminConn.Exec(context.Background(),+ fmt.Sprintf("DROP ROLE IF EXISTS %s", pgx.Identifier{roleName}.Sanitize()),+ )+ })++ replicationOnlySourceDB := *fixture.DB.PostgresqlPhysical+ replicationOnlySourceDB.Username = roleName+ replicationOnlySourceDB.Password = "switchless"++ return &replicationOnlySourceDB+}++func Test_WalStream_WhenUploadsKeepFailing_AlertsArchiveStaleOnce(t *testing.T) {+ if testing.Short() {+ t.Skip("streamer integration test runs pg_receivewal; skipped in -short")+ }++ fixture := SetupPhysicalDBForBackup(t)+ t.Cleanup(func() {+ _ = physical_repositories.GetWalStreamerRepository().DeleteByDatabaseID(fixture.DB.ID)+ })++ adminConn := OpenAdminConn(t, fixture)++ store := newMockWalStorage()+ store.startFailingSaves()++ var chainRisks chainEventRecorder++ t.Cleanup(StartWalStreamerForTest(t, WalStreamerTestSpec{+ Fixture: fixture,+ Storage: store,+ WatchDirRoot: t.TempDir(),+ ArchiveStalenessThreshold: time.Second,+ OnChainAtRisk: func(report ChainRiskReport) {+ chainRisks.recordReason(report.Reason)+ },+ }).Stop)++ // The source has to keep writing: an archive that stands still behind an idle+ // source is not falling behind, it is just waiting for the next segment.+ require.Eventually(t, func() bool {+ _, err := GenerateWalActivity(t.Context(), adminConn, 4096)++ return err == nil && chainRisks.getReasonCount() > 0+ }, 3*time.Minute, 2*time.Second,+ "WAL the source already wrote is not reaching storage — the recovery point has stopped advancing")++ require.Equal(t, []string{ChainRiskReasonArchiveStale}, chainRisks.getReasons(),+ "one alert per incident, not one per lag-monitor tick")++ store.stopFailingSaves()++ WaitForCommittedWalSegmentCount(t, fixture.DB.ID, 1, 90*time.Second)++ require.Len(t, chainRisks.getReasons(), 1)+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_upload.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_upload.goindex 6d9c42cd..b0af4024 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_upload.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_upload.go@@ -59,10 +59,14 @@ type WalUploader struct {mu sync.MutexlastNotifiedGapEnd walmath.LSN++ // The uploader loop retries every second, so a torn segment that never gets+ // re-streamed would otherwise warn once per second forever.+ warnedIncompleteSegments map[string]struct{}}func NewWalUploader(deps WalUploadDeps) *WalUploader {- return &WalUploader{deps: deps}+ return &WalUploader{deps: deps, warnedIncompleteSegments: make(map[string]struct{})}}// ProcessSegment runs the full insert-first claim flow for one finalized WAL@@ -75,6 +79,14 @@ func (u *WalUploader) ProcessSegment(ctx context.Context, localPath, walFilenamereturn err}+ if !isCompleteSegmentFile(localPath, u.deps.WalSegmentSizeBytes) {+ u.warnIncompleteSegmentOnce(walFilename)++ return nil+ }++ u.forgetIncompleteSegment(walFilename)+claim := &physical_models.PhysicalWalSegment{ID: uuid.New(),DatabaseID: u.deps.DatabaseID,@@ -113,6 +125,14 @@ func (u *WalUploader) RecoverSegment(ctx context.Context, localPath, walFilenamereturn err}+ if !isCompleteSegmentFile(localPath, u.deps.WalSegmentSizeBytes) {+ u.warnIncompleteSegmentOnce(walFilename)++ return nil+ }++ u.forgetIncompleteSegment(walFilename)+claim := &physical_models.PhysicalWalSegment{ID: uuid.New(),DatabaseID: u.deps.DatabaseID,@@ -343,6 +363,26 @@ func (u *WalUploader) removeLocal(localPath, walFilename string) {}}+func (u *WalUploader) warnIncompleteSegmentOnce(walFilename string) {+ u.mu.Lock()+ _, wasWarned := u.warnedIncompleteSegments[walFilename]+ u.warnedIncompleteSegments[walFilename] = struct{}{}+ u.mu.Unlock()++ if wasWarned {+ return+ }++ u.deps.Logger.Warn("skipping incomplete local wal segment", "wal_filename", walFilename)+}++func (u *WalUploader) forgetIncompleteSegment(walFilename string) {+ u.mu.Lock()+ defer u.mu.Unlock()++ delete(u.warnedIncompleteSegments, walFilename)+}+func segmentBounds(walFilename string, segSizeBytes int64) (timelineID int, startLSN, endLSN walmath.LSN, err error) {timeline, segmentNo, err := walmath.ParseWALFilenameWithSize(walFilename, uint64(segSizeBytes))if err != nil {diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_upload_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_upload_test.goindex 0eddc8db..c16bf0c5 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_upload_test.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_upload_test.go@@ -3,13 +3,9 @@ package usecases_physical_postgresqlimport ("bytes""context"- "errors"- "fmt""io"- "log/slog""os""path/filepath"- "sync""sync/atomic""testing"@@ -24,119 +20,6 @@ import ("databasus-backend/internal/util/walmath")-const testWalSegmentSize = int64(16 * 1024 * 1024)--// lsnSpanUpperBoundForTests is an effectively-unbounded upper LSN used when a-// chain-span query should return every segment regardless of position.-const lsnSpanUpperBoundForTests = walmath.LSN(1) << 62--// blockOn exists to interleave the DeleteFull cascade race.-type mockWalStorage struct {- mu sync.Mutex- saved map[string][]byte- deleted []string- saveCount atomic.Int64-- failSaveTimes int-- isFailingAllSaves atomic.Bool-- // blockOn, when set, makes SaveFile for that exact object name signal started- // and wait on release before returning.- blockOn string- started chan struct{}- release chan struct{}-}--func newMockWalStorage() *mockWalStorage {- return &mockWalStorage{saved: make(map[string][]byte)}-}--func (m *mockWalStorage) SaveFile(- _ context.Context, _ encryption.FieldEncryptor, _ *slog.Logger, fileName string, file io.Reader,-) error {- m.saveCount.Add(1)-- body, _ := io.ReadAll(file)-- if m.blockOn != "" && fileName == m.blockOn {- close(m.started)- <-m.release- }-- if m.isFailingAllSaves.Load() {- return fmt.Errorf("mock storage is failing every save for %s", fileName)- }-- m.mu.Lock()- defer m.mu.Unlock()-- if m.failSaveTimes > 0 {- m.failSaveTimes---- return fmt.Errorf("mock storage induced failure for %s", fileName)- }-- m.saved[fileName] = body-- return nil-}--func (m *mockWalStorage) startFailingSaves() {- m.isFailingAllSaves.Store(true)-}--func (m *mockWalStorage) stopFailingSaves() {- m.isFailingAllSaves.Store(false)-}--func (m *mockWalStorage) DeleteFile(_ encryption.FieldEncryptor, fileName string) error {- m.mu.Lock()- defer m.mu.Unlock()-- delete(m.saved, fileName)- m.deleted = append(m.deleted, fileName)-- return nil-}--func (m *mockWalStorage) GetFile(_ encryption.FieldEncryptor, _ string) (io.ReadCloser, error) {- return nil, errors.New("GetFile not implemented in mockWalStorage")-}-func (m *mockWalStorage) Validate(_ encryption.FieldEncryptor) error { return nil }-func (m *mockWalStorage) TestConnection(_ encryption.FieldEncryptor) error { return nil }-func (m *mockWalStorage) HideSensitiveData() {}-func (m *mockWalStorage) EncryptSensitiveData(_ encryption.FieldEncryptor) error { return nil }--func (m *mockWalStorage) hasObject(name string) bool {- m.mu.Lock()- defer m.mu.Unlock()-- _, ok := m.saved[name]-- return ok-}--// walName builds a canonical 24-hex WAL filename for a timeline + segment number-// at the default 16 MB segment size (256 segments per logid).-func walName(timeline uint32, segNo uint64) string {- const segmentsPerLogID = 256-- return fmt.Sprintf("%08X%08X%08X", timeline, segNo/segmentsPerLogID, segNo%segmentsPerLogID)-}--// writeWalFile writes a small placeholder segment file under dir named for the-// WAL filename. The body size is irrelevant — LSN bounds come from the filename,-// not the file length — so a tiny file keeps the test fast.-func writeWalFile(t *testing.T, dir, name string) string {- t.Helper()-- path := filepath.Join(dir, name)- require.NoError(t, os.WriteFile(path, []byte("wal-segment-body-"+name), 0o600))-- return path-}-// newTestUploader wires a WalUploader against the real catalog repo and a mock// storage, using the fixture's database/storage IDs for FK integrity.func newTestUploader(@@ -223,6 +106,42 @@ func Test_WalUpload_SaveFileFails_ClaimRowDeletedLocalRetained_NextTickSucceeds(require.NoFileExists(t, localPath)}+func Test_WalUpload_WhenSegmentFileIsShort_SkipsClaimAndRetainsFile(t *testing.T) {+ fixture := SetupPhysicalDBForBackup(t)++ store := newMockWalStorage()+ uploader := newTestUploader(fixture, store, nil)++ dir := t.TempDir()+ name := walName(1, 21)+ tornSegmentPath := writeSegmentOfSize(t, dir, name, testWalSegmentSize/2)++ require.NoError(t, uploader.ProcessSegment(context.Background(), tornSegmentPath, name))++ require.Nil(t, findWalSegment(t, fixture.DB.ID, 1, walmath.LSN(21*uint64(testWalSegmentSize))),+ "LSN bounds come from the filename, so claiming a short file would promise WAL the object does not hold")+ require.FileExists(t, tornSegmentPath, "the receiver owns the file and will re-stream it")+}++func Test_WalUpload_WhenSegmentFileIsShort_WritesNothingToStorage(t *testing.T) {+ fixture := SetupPhysicalDBForBackup(t)++ store := newMockWalStorage()+ uploader := newTestUploader(fixture, store, nil)++ dir := t.TempDir()+ name := walName(1, 22)++ require.NoError(t, uploader.ProcessSegment(+ context.Background(), writeSegmentOfSize(t, dir, name, testWalSegmentSize-1), name,+ ))+ require.NoError(t, uploader.RecoverSegment(+ context.Background(), writeSegmentOfSize(t, t.TempDir(), name, 0), name,+ ))++ require.Zero(t, store.saveCount.Load())+}+func Test_WalUpload_DuplicateClaim_CompletedRow_DropsLocalNoStorageWrite(t *testing.T) {fixture := SetupPhysicalDBForBackup(t)diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_watch_dir.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_watch_dir.goindex b1e2eb2a..06af1688 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_watch_dir.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_watch_dir.go@@ -17,6 +17,16 @@ import (// low without measurable CPU.const uploaderPollInterval = 1 * time.Second+// A segment's LSN bounds come from its filename, so a file that is not exactly+// one wal_segment_size long would be catalogued as covering WAL it does not hold.+// pg_receivewal only renames a segment into place once it is full, so anything+// short is a torn leftover the receiver will re-stream.+func isCompleteSegmentFile(localPath string, segmentSizeBytes int64) bool {+ info, err := os.Stat(localPath)++ return err == nil && info.Size() == segmentSizeBytes+}+func (s *WalStreamSupervisor) runUploaderLoop(ctx context.Context, logger *slog.Logger) {ticker := time.NewTicker(uploaderPollInterval)defer ticker.Stop()diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_watch_dir_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_watch_dir_test.gonew file mode 100644index 00000000..c2722d83--- /dev/null+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_watch_dir_test.go@@ -0,0 +1,73 @@+package usecases_physical_postgresql++import (+ "os"+ "path/filepath"+ "testing"++ "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"+)++func createSupervisorWithStagedSegment(+ t *testing.T,+ fixture *PhysicalDBFixture,+ store *mockWalStorage,+ segmentNo uint64,+) (supervisor *WalStreamSupervisor, stagedSegmentPath string) {+ t.Helper()++ supervisor = NewWalStreamSupervisor(WalStreamSpec{+ DatabaseID: fixture.DB.ID,+ SourceDB: fixture.DB.PostgresqlPhysical,+ StorageID: fixture.Storage.ID,+ Storage: store,+ Encryption: backups_core_enums.BackupEncryptionNone,+ FieldEncryptor: encryption.GetFieldEncryptor(),+ WalSegmentRepo: physical_repositories.GetWalSegmentRepository(),+ HistoryRepo: physical_repositories.GetWalHistoryRepository(),+ WatchDirRoot: t.TempDir(),+ Logger: logger.GetLogger(),+ })++ pendingUploadDir := filepath.Join(supervisor.watchDir, pendingUploadDirName)+ require.NoError(t, os.MkdirAll(pendingUploadDir, 0o700))++ return supervisor, writeSegmentOfSize(t, pendingUploadDir, walName(1, segmentNo), testWalSegmentSize)+}++func Test_SweepPendingUploads_WhenUploadSucceeds_RemovesSegmentFromStagingDir(t *testing.T) {+ fixture := SetupPhysicalDBForBackup(t)++ store := newMockWalStorage()+ supervisor, stagedSegmentPath := createSupervisorWithStagedSegment(t, fixture, store, 70)++ supervisor.sweepPendingUploads(t.Context(), logger.GetLogger(), supervisor.uploader.ProcessSegment)++ require.True(t, store.hasObject(walSegmentObjectName(fixture.DB.ID, 1, walName(1, 70))),+ "a segment staged out of the resume path is valid WAL of the older chain and must still reach storage")+ require.NoFileExists(t, stagedSegmentPath, "an uploaded segment must not keep occupying the local queue")+}++func Test_SweepPendingUploads_WhenUploadFails_RetainsSegmentForNextTick(t *testing.T) {+ fixture := SetupPhysicalDBForBackup(t)++ store := newMockWalStorage()+ store.startFailingSaves()++ supervisor, stagedSegmentPath := createSupervisorWithStagedSegment(t, fixture, store, 71)++ supervisor.sweepPendingUploads(t.Context(), logger.GetLogger(), supervisor.uploader.ProcessSegment)++ require.FileExists(t, stagedSegmentPath, "staged WAL must survive a storage outage")++ store.stopFailingSaves()+ supervisor.sweepPendingUploads(t.Context(), logger.GetLogger(), supervisor.uploader.ProcessSegment)++ require.True(t, store.hasObject(walSegmentObjectName(fixture.DB.ID, 1, walName(1, 71))))+ require.NoFileExists(t, stagedSegmentPath)+}