Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Keep replication observations owned through ordinary polling recovery
pulse-triage[bot]1b8f077012f2
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 9b79344156..8bfb34cad6 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -5722,3 +5722,32 @@ VMIDs in separate instances, expiry/offline/empty/withdrawal/recovery and abackup lock with zero filesystem calls. Sequential snapshot replacement pinsinventory removal/recovery without restarting the monitor. These are syntheticsource controls, not a native cause, thaw or installed recovery for #2616/#2619.++### Runtime-owned Proxmox replication observations — #2606++The ordinary PVE scheduler/provider/executor dispatches a bounded replication+read independently of `cluster/resources` availability, traditional guest+fallback and disabled guest-detail monitoring. Its ten-second context is+captured from the monitor runtime before dispatch, not from the short-lived+scheduled task. One read per registered instance/client coalesces overlapping+cycles; runtime replacement and retirement cancel/invalidate the claim. A+replacement client can recover on the next ordinary cycle without waiting for+an old read. Publication checks cancellation, the claim and the current client+under the same lock; a late obsolete completion cannot overwrite or clear a+newer result, including a successful empty inventory.++Only an explicitly decoded `data` array is a complete replication inventory.+Missing/null/malformed envelopes, cancellation (including after final status+body consumption), access/transport errors and unavailable endpoints preserve+the prior jobs and their original `LastPolled`. A complete successful empty+array removes only that instance's jobs. Individual uncanceled status-access+failures retain the existing unknown-outcome contract, not inferred success.+No wire fields, classification, permission contract or scheduler cadence change.++`monitor_pve_replication_lifecycle_test.go` exercises ordinary fallback/disabled+paths and canceled/unavailable versus complete empty reads; the owned-boundary+controls in `monitor_pve_replication_owner_test.go` cover coalescing, cycle/runtime+cancellation, replacement, retirement, late completion and ordinary recovery.+`pkg/proxmox/replication_lifecycle_test.go` binds envelope and cancellation+controls to the real HTTP client. Synthetic proofs do not establish #2606's+reported eleven-hour cause, native PVE recovery or published availability.diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex 0d7a4eeaeb..7aa9e9849e 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -1217,6 +1217,7 @@ type Monitor struct {lastAuthAttempt map[string]time.Time // Track last auth attempt timelastClusterCheck map[string]time.Time // Track last cluster check for standalone nodeslastPhysicalDiskPoll map[string]time.Time // Track last physical disk poll time per instance+ pveReplicationPolls map[string]*pveReplicationPoll // Owned runtime/client-scoped replication reads; guarded by mulastPVEBackupPoll map[string]time.Time // Track last PVE backup poll per instancevzdumpJobTaskCache map[string]vzdumpJobTaskCacheEntry // Cache synthesized per-guest tasks for multi-guest vzdump job runs, keyed by instance|UPIDlastPBSBackupPoll map[string]time.Time // Track last PBS backup poll per instance@@ -1347,6 +1348,12 @@ type Monitor struct {func (m *Monitor) setRuntimeContext(ctx context.Context, hub *websocket.Hub) {m.mu.Lock()defer m.mu.Unlock()+ // A new runtime invalidates detached replication reads even when the old+ // caller has not yet canceled its parent context.+ for name, poll := range m.pveReplicationPolls {+ poll.cancel()+ delete(m.pveReplicationPolls, name)+ }m.runtimeCtx = ctxm.wsHub = hub}diff --git a/internal/monitoring/monitor_cluster_dedupe.go b/internal/monitoring/monitor_cluster_dedupe.goindex 8c59f2c48a..34a0ee81d9 100644--- a/internal/monitoring/monitor_cluster_dedupe.go+++ b/internal/monitoring/monitor_cluster_dedupe.go@@ -87,6 +87,10 @@ func (m *Monitor) retirePVEInstanceRuntime(instanceName string) {key := schedulerKey(InstanceTypePVE, instanceName)m.mu.Lock()+ if poll := m.pveReplicationPolls[instanceName]; poll != nil {+ poll.cancel()+ delete(m.pveReplicationPolls, instanceName)+ }delete(m.pveClients, instanceName)delete(m.lastClusterCheck, instanceName)delete(m.lastPhysicalDiskPoll, instanceName)diff --git a/internal/monitoring/monitor_pve.go b/internal/monitoring/monitor_pve.goindex 581307f263..d583d78bcd 100644--- a/internal/monitoring/monitor_pve.go+++ b/internal/monitoring/monitor_pve.go@@ -1539,8 +1539,13 @@ func (m *Monitor) pollPVEInstance(ctx context.Context, instanceName string, clie// Poll VMs and containers FIRST - this is the most critical data.// This happens immediately after starting the storage fallback goroutine,// so VM/container polling runs in parallel with (and is not blocked by) storage operations.- if err := m.pollGuestsWithFallback(ctx, instanceName, instanceCfg, client, nodes, nodeEffectiveStatus); err != nil {- pollErr = err+ guestErr := m.pollGuestsWithFallback(ctx, instanceName, instanceCfg, client, nodes, nodeEffectiveStatus)+ // Replication is independent of guest-detail availability and the short+ // scheduled cycle. Include fallback/disabled guest monitoring too; a failed+ // guest read must not leave replication frozen until a manual restart.+ m.pollReplicationStatusAsync(instanceName, client, nil)+ if guestErr != nil {+ pollErr = guestErrreturn}diff --git a/internal/monitoring/monitor_pve_guest_poll.go b/internal/monitoring/monitor_pve_guest_poll.goindex 7c6f4e6bd0..5d3fd159c6 100644--- a/internal/monitoring/monitor_pve_guest_poll.go+++ b/internal/monitoring/monitor_pve_guest_poll.go@@ -85,8 +85,6 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNamm.recordGuestMetrics(allVMs, allContainers, cycleStart)- m.pollReplicationStatusAsync(instanceName, client, allVMs)-log.Debug().Str("instance", instanceName).Int("vms", len(allVMs)).diff --git a/internal/monitoring/monitor_pve_replication.go b/internal/monitoring/monitor_pve_replication.goindex e5a3429f5b..e97958b0de 100644--- a/internal/monitoring/monitor_pve_replication.go+++ b/internal/monitoring/monitor_pve_replication.go@@ -14,22 +14,95 @@ import (const pveReplicationPollTimeout = 10 * time.Second+// pveReplicationPoll owns one background observation. The claim is installed+// before dispatch and checked under m.mu together with the registered client at+// publication, so a retired/replaced instance cannot publish a late inventory.+type pveReplicationPoll struct {+ ctx context.Context+ cancel context.CancelFunc+ client PVEClientInterface+ done chan struct{}+}+func (m *Monitor) pollReplicationStatusAsync(instanceName string, client PVEClientInterface, vms []models.VM) {- parentCtx := m.getRuntimeContext()+ m.mu.Lock()+ if client == nil || m.pveClients[instanceName] != client {+ m.mu.Unlock()+ return+ }+ parentCtx := m.runtimeCtxif parentCtx == nil {parentCtx = context.Background()}+ if parentCtx.Err() != nil {+ m.mu.Unlock()+ return+ }+ if m.pveReplicationPolls == nil {+ m.pveReplicationPolls = make(map[string]*pveReplicationPoll)+ }+ if previous := m.pveReplicationPolls[instanceName]; previous != nil {+ if previous.client == client && previous.ctx.Err() == nil {+ m.mu.Unlock()+ return // A slow read must not stack up once per ordinary cycle.+ }+ previous.cancel()+ }+ ctx, cancel := context.WithTimeout(parentCtx, pveReplicationPollTimeout)+ owner := &pveReplicationPoll{ctx: ctx, cancel: cancel, client: client, done: make(chan struct{})}+ m.pveReplicationPolls[instanceName] = owner+ m.mu.Unlock()+guestSnapshot := append([]models.VM(nil), vms...)+ if vms == nil {+ // Only replication identity is needed; do not clone guest enrichment or+ // rebuild all prior guest/agent indexes for each scheduled cycle.+ if state := m.GetUnifiedReadStateOrSnapshot(); state != nil {+ for _, vm := range state.VMs() {+ if vm != nil && vm.Instance() == instanceName {+ guestSnapshot = append(guestSnapshot, models.VM{VMID: vm.VMID(), Name: vm.Name(), Type: "qemu", Node: vm.Node()})+ }+ }+ }+ }go func() {+ defer func() {+ cancel()+ m.mu.Lock()+ if m.pveReplicationPolls[instanceName] == owner {+ delete(m.pveReplicationPolls, instanceName)+ }+ m.mu.Unlock()+ close(owner.done)+ }()defer recoverFromPanic(fmt.Sprintf("pollReplicationStatus-%s", instanceName))- ctx, cancel := context.WithTimeout(parentCtx, pveReplicationPollTimeout)- defer cancel()- m.pollReplicationStatus(ctx, instanceName, client, guestSnapshot)+ m.pollReplicationStatusOwned(ctx, instanceName, client, guestSnapshot, owner)}()}+// publishReplicationJobs never treats an interrupted observation as an empty+// inventory, and never lets an old client overwrite its replacement's result.+func (m *Monitor) publishReplicationJobs(ctx context.Context, instanceName string, jobs []models.ReplicationJob, owner *pveReplicationPoll) {+ m.mu.Lock()+ defer m.mu.Unlock()+ if ctx.Err() != nil {+ return+ }+ if owner != nil && (m.pveReplicationPolls[instanceName] != owner || m.pveClients[instanceName] != owner.client) {+ return+ }+ m.state.UpdateReplicationJobsForInstance(instanceName, jobs)+}+// pollReplicationStatus polls storage replication jobs for a PVE instance.func (m *Monitor) pollReplicationStatus(ctx context.Context, instanceName string, client PVEClientInterface, vms []models.VM) {+ m.pollReplicationStatusOwned(ctx, instanceName, client, vms, nil)+}++func (m *Monitor) pollReplicationStatusOwned(ctx context.Context, instanceName string, client PVEClientInterface, vms []models.VM, owner *pveReplicationPoll) {+ if ctx.Err() != nil {+ return+ }log.Debug().Str("instance", instanceName).Msg("polling replication status")jobs, err := client.GetReplicationStatus(ctx)@@ -40,7 +113,7 @@ func (m *Monitor) pollReplicationStatus(ctx context.Context, instanceName stringlog.Debug().Str("instance", instanceName).Msg("Replication API not available on this Proxmox instance")- m.state.UpdateReplicationJobsForInstance(instanceName, []models.ReplicationJob{})+ // An unavailable endpoint is not a successful empty inventory.return}@@ -52,8 +125,11 @@ func (m *Monitor) pollReplicationStatus(ctx context.Context, instanceName stringreturn}+ if ctx.Err() != nil {+ return+ }if len(jobs) == 0 {- m.state.UpdateReplicationJobsForInstance(instanceName, []models.ReplicationJob{})+ m.publishReplicationJobs(ctx, instanceName, []models.ReplicationJob{}, owner)return}@@ -170,7 +246,7 @@ func (m *Monitor) pollReplicationStatus(ctx context.Context, instanceName string})}- m.state.UpdateReplicationJobsForInstance(instanceName, converted)+ m.publishReplicationJobs(ctx, instanceName, converted, owner)}func formatSeconds(total int) string {diff --git a/internal/monitoring/monitor_pve_replication_lifecycle_test.go b/internal/monitoring/monitor_pve_replication_lifecycle_test.gonew file mode 100644index 0000000000..6f17ba782b--- /dev/null+++ b/internal/monitoring/monitor_pve_replication_lifecycle_test.go@@ -0,0 +1,196 @@+package monitoring++import (+ "context"+ "fmt"+ "reflect"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"+)++type lifecycleReplicationClient struct {+ stubPVEClient+ read func(context.Context) ([]proxmox.ReplicationJob, error)+ clusterErr error+}++func (c *lifecycleReplicationClient) GetReplicationStatus(ctx context.Context) ([]proxmox.ReplicationJob, error) {+ return c.read(ctx)+}+func (c *lifecycleReplicationClient) GetClusterResources(ctx context.Context, _ string) ([]proxmox.ClusterResource, error) {+ return nil, c.clusterErr+}++func newReplicationLifecycleMonitor(t *testing.T, client PVEClientInterface, monitorGuests bool) *Monitor {+ t.Helper()+ physicalDisks := false+ m := newUnreachableTestMonitor(t, &config.Config{PVEInstances: []config.PVEInstance{{Name: "site-a", Host: "https://example.invalid:9999", MonitorVMs: monitorGuests, MonitorPhysicalDisks: &physicalDisks}}})+ m.pveClients["site-a"] = client+ m.lastClusterCheck["site-a"] = time.Now() // No external discovery; test only scheduler/client lifecycle.+ m.SetExecutor(newRealExecutor(m))+ return m+}+func runReplicationCycle(m *Monitor) {+ tasks := m.buildScheduledTasks(time.Now())+ for _, task := range tasks {+ if task.InstanceType == InstanceTypePVE && task.InstanceName == "site-a" {+ m.executeScheduledTask(context.Background(), task)+ return+ }+ }+ panic("missing scheduled site-a task")+}+func waitReplication(t *testing.T, done <-chan struct{}, stage string) {+ t.Helper()+ select {+ case <-done:+ case <-time.After(3 * time.Second):+ t.Fatalf("%s did not finish", stage)+ }+}+func replicationSeed(m *Monitor) []models.ReplicationJob {+ rows := []models.ReplicationJob{{ID: "site-a-100-0", Instance: "site-a", JobID: "100-0", GuestID: 100, LastSyncStatus: "error", LastPolled: time.Unix(100, 0)}}+ m.state.UpdateReplicationJobsForInstance("site-a", rows)+ m.state.UpdateReplicationJobsForInstance("site-b", []models.ReplicationJob{{ID: "site-b-100-0", Instance: "site-b", JobID: "100-0", LastSyncStatus: "ok", LastPolled: time.Unix(200, 0)}})+ return m.state.GetSnapshot().ReplicationJobs+}++// These controls use only the old public-to-package entry points as well as+// the real scheduler/provider/executor path, so identical tests run on parent.+func TestReplicationLifecycleScheduledFallbackAndDisabledGuests(t *testing.T) {+ for _, monitorGuests := range []bool{true, false} {+ t.Run(fmt.Sprint(monitorGuests), func(t *testing.T) {+ called := make(chan struct{}, 1)+ c := &lifecycleReplicationClient{clusterErr: fmt.Errorf("cluster/resources unavailable"), read: func(ctx context.Context) ([]proxmox.ReplicationJob, error) {+ called <- struct{}{}+ return []proxmox.ReplicationJob{{ID: "100-0", GuestID: 100, LastSyncStatus: "ok"}}, nil+ }}+ m := newReplicationLifecycleMonitor(t, c, monitorGuests)+ runReplicationCycle(m)+ waitReplication(t, called, "ordinary replication read")+ deadline := time.Now().Add(3 * time.Second)+ for len(m.state.GetSnapshot().ReplicationJobs) == 0 && time.Now().Before(deadline) {+ time.Sleep(time.Millisecond)+ }+ rows := m.state.GetSnapshot().ReplicationJobs+ if len(rows) != 1 || rows[0].ID != "site-a-100-0" || rows[0].LastSyncStatus != "ok" || rows[0].LastPolled.IsZero() {+ t.Fatalf("ordinary read not published: %+v", rows)+ }+ })+ }+}+func TestReplicationLifecycleInterruptedAndUnavailablePreserveInventory(t *testing.T) {+ for _, mode := range []string{"canceled-empty", "canceled-jobs", "404", "501", "403", "transport"} {+ t.Run(mode, func(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ c := &lifecycleReplicationClient{read: func(context.Context) ([]proxmox.ReplicationJob, error) {+ switch mode {+ case "canceled-empty":+ cancel()+ return nil, nil+ case "canceled-jobs":+ cancel()+ return []proxmox.ReplicationJob{{ID: "100-0", GuestID: 100, LastSyncStatus: "ok"}}, nil+ default:+ return nil, fmt.Errorf("%s unavailable", mode)+ }+ }}+ m := newReplicationLifecycleMonitor(t, c, true)+ before := replicationSeed(m)+ m.pollReplicationStatus(ctx, "site-a", c, nil)+ if got := m.state.GetSnapshot().ReplicationJobs; !reflect.DeepEqual(got, before) {+ t.Fatalf("interrupted/unavailable inventory renewed or cleared: before=%+v after=%+v", before, got)+ }+ // Only a later complete successful read can refresh/clear this instance.+ c.read = func(context.Context) ([]proxmox.ReplicationJob, error) {+ return []proxmox.ReplicationJob{{ID: "100-0", GuestID: 100, LastSyncStatus: "ok"}}, nil+ }+ m.pollReplicationStatus(context.Background(), "site-a", c, nil)+ rows := m.state.GetSnapshot().ReplicationJobs+ if len(rows) != 2 {+ t.Fatalf("recovery lost another instance: %+v", rows)+ }+ for _, row := range rows {+ if row.Instance == "site-a" && (row.LastSyncStatus != "ok" || !row.LastPolled.After(time.Unix(100, 0))) {+ t.Fatalf("recovery not fresh: %+v", row)+ }+ }+ c.read = func(context.Context) ([]proxmox.ReplicationJob, error) { return []proxmox.ReplicationJob{}, nil }+ m.pollReplicationStatus(context.Background(), "site-a", c, nil)+ rows = m.state.GetSnapshot().ReplicationJobs+ if len(rows) != 1 || rows[0].Instance != "site-b" {+ t.Fatalf("complete empty should remove only site-a: %+v", rows)+ }+ })+ }+}++// The exact-parent control uses only pre-existing entry points. It observes the+// obsolete write for a bounded window; the companion owned-boundary test also+// waits for final goroutine termination, not just absence within this window.+func TestReplicationLifecycleObsoleteScheduledCompletion(t *testing.T) {+ for _, mode := range []string{"runtime", "client", "retire"} {+ t.Run(mode, func(t *testing.T) {+ started := make(chan struct{})+ release := make(chan struct{})+ returned := make(chan struct{})+ var released bool+ old := &lifecycleReplicationClient{read: func(context.Context) ([]proxmox.ReplicationJob, error) {+ close(started)+ <-release+ defer close(returned)+ return []proxmox.ReplicationJob{{ID: "obsolete-0", LastSyncStatus: "ok"}}, nil+ }}+ m := newReplicationLifecycleMonitor(t, old, true)+ m.setRuntimeContext(context.Background(), nil)+ defer func() {+ if !released {+ close(release)+ }+ }()+ runReplicationCycle(m)+ waitReplication(t, started, "old scheduled read")+ if mode == "runtime" {+ m.setRuntimeContext(context.Background(), nil)+ }+ if mode == "retire" {+ m.retirePVEInstanceRuntime("site-a")+ }+ newer := &lifecycleReplicationClient{read: func(context.Context) ([]proxmox.ReplicationJob, error) {+ return []proxmox.ReplicationJob{{ID: "current-0", LastSyncStatus: "error"}}, nil+ }}+ m.mu.Lock()+ m.pveClients["site-a"] = newer+ m.lastClusterCheck["site-a"] = time.Now()+ m.mu.Unlock()+ runReplicationCycle(m)+ end := time.Now().Add(3 * time.Second)+ for {+ rows := m.state.GetSnapshot().ReplicationJobs+ if len(rows) == 1 && rows[0].JobID == "current-0" {+ break+ }+ if time.Now().After(end) {+ t.Fatalf("current scheduled read did not recover: %+v", rows)+ }+ time.Sleep(time.Millisecond)+ }+ close(release)+ released = true+ waitReplication(t, returned, "obsolete client return")+ end = time.Now().Add(500 * time.Millisecond)+ for time.Now().Before(end) {+ rows := m.state.GetSnapshot().ReplicationJobs+ if len(rows) != 1 || rows[0].JobID != "current-0" {+ t.Fatalf("obsolete scheduled result replaced current inventory: %+v", rows)+ }+ time.Sleep(time.Millisecond)+ }+ })+ }+}diff --git a/internal/monitoring/monitor_pve_replication_owner_test.go b/internal/monitoring/monitor_pve_replication_owner_test.gonew file mode 100644index 0000000000..bf724d6c59--- /dev/null+++ b/internal/monitoring/monitor_pve_replication_owner_test.go@@ -0,0 +1,167 @@+package monitoring++import (+ "context"+ "fmt"+ "reflect"+ "sync/atomic"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"+)++func replicationOwner(t *testing.T, m *Monitor) *pveReplicationPoll {+ t.Helper()+ m.mu.RLock()+ owner := m.pveReplicationPolls["site-a"]+ m.mu.RUnlock()+ if owner == nil {+ t.Fatal("replication claim missing")+ }+ return owner+}+func TestReplicationLifecycleSingleFlightAndCycleCancellation(t *testing.T) {+ started := make(chan struct{})+ release := make(chan struct{})+ var calls atomic.Int32+ c := &lifecycleReplicationClient{read: func(ctx context.Context) ([]proxmox.ReplicationJob, error) {+ if calls.Add(1) == 1 {+ close(started)+ }+ select {+ case <-release:+ return []proxmox.ReplicationJob{{ID: "100-0", LastSyncStatus: "ok"}}, nil+ case <-ctx.Done():+ return nil, ctx.Err()+ }+ }}+ m := newReplicationLifecycleMonitor(t, c, true)+ runCtx, cancel := context.WithCancel(context.Background())+ defer cancel()+ m.setRuntimeContext(runCtx, nil)+ t.Cleanup(func() { cancel(); close(release) })+ runReplicationCycle(m)+ waitReplication(t, started, "first read")+ owner := replicationOwner(t, m)+ // executeScheduledTask canceled its short-lived task context on return.+ if owner.ctx.Err() != nil {+ t.Fatalf("cycle canceled background read: %v", owner.ctx.Err())+ }+ deadline, ok := owner.ctx.Deadline()+ if !ok || time.Until(deadline) > pveReplicationPollTimeout {+ t.Fatal("background read has no bounded deadline")+ }+ for i := 0; i < 5; i++ {+ runReplicationCycle(m)+ }+ if calls.Load() != 1 {+ t.Fatalf("overlapping cycles stacked %d reads", calls.Load())+ }+ cancel()+ waitReplication(t, owner.done, "runtime cancellation")+ if len(m.state.GetSnapshot().ReplicationJobs) != 0 {+ t.Fatal("cancellation published an inventory")+ }+ // A new ordinary runtime/cycle recovers without a manual inventory invocation.+ m.setRuntimeContext(context.Background(), nil)+ c.read = func(context.Context) ([]proxmox.ReplicationJob, error) {+ return []proxmox.ReplicationJob{{ID: "100-0", LastSyncStatus: "ok"}}, nil+ }+ runReplicationCycle(m)+ end := time.Now().Add(3 * time.Second)+ for len(m.state.GetSnapshot().ReplicationJobs) == 0 && time.Now().Before(end) {+ time.Sleep(time.Millisecond)+ }+ if len(m.state.GetSnapshot().ReplicationJobs) != 1 {+ t.Fatal("ordinary recovery did not publish")+ }+}+func TestReplicationLifecycleReplacementRejectsLateCompletion(t *testing.T) {+ for _, mode := range []string{"runtime", "client", "retire", "client-empty", "client-error"} {+ t.Run(mode, func(t *testing.T) {+ started := make(chan struct{})+ release := make(chan struct{})+ var released bool+ old := &lifecycleReplicationClient{read: func(ctx context.Context) ([]proxmox.ReplicationJob, error) {+ close(started)+ <-release+ return []proxmox.ReplicationJob{{ID: "stale-0", LastSyncStatus: "ok"}}, nil+ }}+ m := newReplicationLifecycleMonitor(t, old, true)+ m.setRuntimeContext(context.Background(), nil)+ before := replicationSeed(m)+ defer func() {+ if !released {+ close(release)+ }+ }()+ runReplicationCycle(m)+ waitReplication(t, started, "old read")+ owner := replicationOwner(t, m)+ switch mode {+ case "runtime":+ m.setRuntimeContext(context.Background(), nil) // Old parent deliberately still live.+ case "retire":+ m.retirePVEInstanceRuntime("site-a")+ }+ newer := &lifecycleReplicationClient{read: func(context.Context) ([]proxmox.ReplicationJob, error) {+ if mode == "client-empty" {+ return []proxmox.ReplicationJob{}, nil+ }+ if mode == "client-error" {+ return nil, fmt.Errorf("403 permission denied")+ }+ return []proxmox.ReplicationJob{{ID: "fresh-0", LastSyncStatus: "error"}}, nil+ }}+ m.mu.Lock()+ m.pveClients["site-a"] = newer+ m.lastClusterCheck["site-a"] = time.Now()+ m.mu.Unlock()+ // Dispatch through current provider binding, then wait for the owned terminal+ // boundary even when a successful empty result cannot be observed as a row.+ runReplicationCycle(m)+ // It may already have completed, so capture the terminal through state/claim.+ end := time.Now().Add(3 * time.Second)+ for {+ m.mu.RLock()+ current := m.pveReplicationPolls["site-a"]+ m.mu.RUnlock()+ if current == nil {+ break+ }+ if time.Now().After(end) {+ t.Fatal("replacement read did not terminate")+ }+ time.Sleep(time.Millisecond)+ }+ expected := m.state.GetSnapshot().ReplicationJobs+ if mode == "client-error" && !reflect.DeepEqual(expected, before) {+ t.Fatalf("failed replacement renewed inventory: %+v", expected)+ }+ if mode != "client-error" {+ expectedCount := 2+ if mode == "client-empty" {+ expectedCount = 1+ }+ if len(expected) != expectedCount {+ t.Fatalf("replacement result %+v", expected)+ }+ for _, row := range expected {+ if row.Instance == "site-a" && row.JobID != "fresh-0" {+ t.Fatalf("wrong replacement identity: %+v", row)+ }+ }+ }+ close(release)+ released = true+ waitReplication(t, owner.done, "old late completion")+ if got := m.state.GetSnapshot().ReplicationJobs; !reflect.DeepEqual(got, expected) {+ t.Fatalf("old read overwrote replacement: before=%+v after=%+v", expected, got)+ }+ if owner.ctx.Err() == nil {+ t.Fatal("superseded read not canceled")+ }+ })+ }+}diff --git a/pkg/proxmox/replication.go b/pkg/proxmox/replication.goindex 864ed3cb8b..13963489aa 100644--- a/pkg/proxmox/replication.go+++ b/pkg/proxmox/replication.go@@ -48,6 +48,9 @@ type ReplicationJob struct {// job with status data (last_sync, next_sync, duration, fail_count, state) from// /nodes/{node}/replication/{id}/status.func (c *Client) GetReplicationStatus(ctx context.Context) ([]ReplicationJob, error) {+ if err := ctx.Err(); err != nil {+ return nil, err+ }resp, err := c.get(ctx, "/cluster/replication")if err != nil {return nil, err@@ -55,24 +58,34 @@ func (c *Client) GetReplicationStatus(ctx context.Context) ([]ReplicationJob, erdefer resp.Body.Close()var raw struct {- Data []map[string]json.RawMessage `json:"data"`+ Data *[]map[string]json.RawMessage `json:"data"`}if err := json.NewDecoder(resp.Body).Decode(&raw); err != nil {return nil, err}- jobs := make([]ReplicationJob, 0, len(raw.Data))- for _, entry := range raw.Data {+ if raw.Data == nil {+ return nil, fmt.Errorf("replication inventory response is missing a data array")+ }+ jobs := make([]ReplicationJob, 0, len(*raw.Data))+ for _, entry := range *raw.Data {jobs = append(jobs, parseReplicationJob(entry))}// Enrich jobs with status data from the per-node status endpoint// The /cluster/replication endpoint only returns config, not statusfor i := range jobs {+ if err := ctx.Err(); err != nil {+ return nil, err+ }c.enrichReplicationJobStatus(ctx, &jobs[i])}-+ // Status enrichment deliberately tolerates individual access errors, but+ // cancellation invalidates the whole observation, not just one job.+ if err := ctx.Err(); err != nil {+ return nil, err+ }return jobs, nil}diff --git a/pkg/proxmox/replication_lifecycle_test.go b/pkg/proxmox/replication_lifecycle_test.gonew file mode 100644index 0000000000..8353a93383--- /dev/null+++ b/pkg/proxmox/replication_lifecycle_test.go@@ -0,0 +1,119 @@+package proxmox++import (+ "context"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++func TestReplicationLifecycleInventoryEnvelope(t *testing.T) {+ for _, tc := range []struct {+ name, body string+ valid bool+ }{{"empty", `{"data":[]}`, true}, {"missing", `{}`, false}, {"null", `{"data":null}`, false}, {"wrong-shape", `{"data":{}}`, false}} {+ t.Run(tc.name, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, tc.body) }))+ defer server.Close()+ client, err := NewClient(ClientConfig{Host: server.URL, TokenName: "reader@pve!manual", TokenValue: "synthetic"})+ if err != nil {+ t.Fatal(err)+ }+ jobs, err := client.GetReplicationStatus(context.Background())+ if tc.valid {+ if err != nil || jobs == nil || len(jobs) != 0 {+ t.Fatalf("valid explicit empty: jobs=%+v err=%v", jobs, err)+ }+ } else if err == nil {+ t.Fatalf("invalid envelope accepted as complete empty: %+v", jobs)+ }+ })+ }+}+func TestReplicationLifecycleHTTPCancellationStopsEnrichment(t *testing.T) {+ started := make(chan struct{})+ var statusReads atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/api2/json/cluster/replication" {+ fmt.Fprint(w, `{"data":[{"id":"100-0","source":"node1"},{"id":"101-0","source":"node1"}]}`)+ return+ }+ if statusReads.Add(1) == 1 {+ close(started)+ }+ select {+ case <-r.Context().Done():+ case <-time.After(3 * time.Second):+ }+ }))+ defer server.Close()+ client, err := NewClient(ClientConfig{Host: server.URL, TokenName: "reader@pve!manual", TokenValue: "synthetic"})+ if err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ done := make(chan struct{})+ var jobs []ReplicationJob+ var readErr error+ go func() { defer close(done); jobs, readErr = client.GetReplicationStatus(ctx) }()+ select {+ case <-started:+ case <-time.After(3 * time.Second):+ t.Fatal("status read not reached")+ }+ cancel()+ select {+ case <-done:+ case <-time.After(3 * time.Second):+ t.Fatal("client did not terminate")+ }+ if !errors.Is(readErr, context.Canceled) || jobs != nil {+ t.Fatalf("canceled read returned publishable config: jobs=%+v err=%v", jobs, readErr)+ }+ if statusReads.Load() != 1 {+ t.Fatalf("cancellation attempted more status reads: %d", statusReads.Load())+ }+}++type replicationEOFBody struct {+ io.ReadCloser+ cancel context.CancelFunc+}++func (b *replicationEOFBody) Read(p []byte) (int, error) {+ n, err := b.ReadCloser.Read(p)+ if err == io.EOF {+ b.cancel()+ }+ return n, err+}++type replicationTransport func(*http.Request) (*http.Response, error)++func (f replicationTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }+func TestReplicationLifecycleCancellationAfterFinalBody(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ client, err := NewClient(ClientConfig{Host: "http://example.invalid:8006", TokenName: "reader@pve!manual", TokenValue: "synthetic"})+ if err != nil {+ t.Fatal(err)+ }+ client.httpClient.Transport = replicationTransport(func(r *http.Request) (*http.Response, error) {+ body := io.NopCloser(strings.NewReader(`{"data":[{"id":"100-0","source":"node1"}]}`))+ if r.URL.Path != "/api2/json/cluster/replication" {+ body = &replicationEOFBody{io.NopCloser(strings.NewReader(`{"data":{"last_sync":1791330000,"fail_count":0}}`)), cancel}+ }+ return &http.Response{StatusCode: 200, Header: make(http.Header), Body: body, Request: r}, nil+ })+ jobs, err := client.GetReplicationStatus(ctx)+ if !errors.Is(err, context.Canceled) || jobs != nil {+ t.Fatalf("final-body cancellation returned fresh success: jobs=%+v err=%v", jobs, err)+ }+}