diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md index 9114a5ed3e..38e692e4a6 100644 --- a/docs/release-control/v6/internal/subsystems/monitoring.md +++ b/docs/release-control/v6/internal/subsystems/monitoring.md @@ -7218,10 +7218,16 @@ points also outlive that live cache: an incomplete, cancelled or unobserved gues inventory must not reconcile missing durable points, including after a monitor replacement. Only snapshots returned by an accepted listing may renew point-level evidence; carried-forward rows remain live continuity, not fresh observations. -Instance-wide deletion waits for a nonempty target inventory whose listings all -succeeded, without cancellation or carried-forward rows. An accepted complete -empty snapshot listing still clears that instance's snapshot scope, preserving -other instances and backup/task classes. `TestPVESnapshotIncompletePollRetainsRecoveryHistory`, +Removal waits for a nonempty target inventory whose listings all succeeded, +without cancellation or carried-forward rows. Even then, a successful pass over +the loaded guests only establishes absence for the exact connection, node, native +guest kind and VMID of each accepted listing. An explicitly empty listing can +still clear that guest's stored points. A guest missing from a freshly loaded +inventory supplies no listing or deletion evidence, and past points are not +restored to the live inventory or renewed. Other instances and point classes +are unchanged. `TestPVESnapshotColdSubsetDoesNotReconcileUnqueriedGuest` covers +the actual HTTP, poll and store flow after a cold monitor replacement. +`TestPVESnapshotIncompletePollRetainsRecoveryHistory`, `TestPVESnapshotUnobservedInventoryPreservesRecoveryHistory` and `TestPVESnapshotCancelledAfterListingsCannotReconcile` in `internal/monitoring/recovery_ingest_test.go` exercise the actual poll, queue and diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md index 8a592b0de6..2ee0121083 100644 --- a/docs/release-control/v6/internal/subsystems/storage-recovery.md +++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md @@ -1955,6 +1955,19 @@ rescued by a reused node name or a singleton fallback. With no connection scope, an exact native node/alias must identify one candidate; wholly unscoped singleton observations retain their existing compatibility behaviour. +Snapshot removal has a different boundary from display attribution. A complete +successful snapshot pass authorizes removal of absent PVE snapshot points only +for its accepted connection, native node, QEMU/LXC kind and VMID tuples. +An absent guest, an opposite-kind occupant or a point with unknown inventory +origin cannot supply that authority. An explicit empty listing still removes +points for its exact guest. This neither re-ingests unqueried points nor counts a +retained guest snapshot as a backup. The other inventory classes retain their +existing instance-wide reconciliation rules. Overlapping snapshot batches +remain ordered rather than superseding one another. +`TestStore_ReconcilePVESnapshotPointsRequiresExactReadTarget` and +`TestRecoveryIngestKeepsOverlappingSnapshotReadScopesInOrder` verify these +boundaries. + PBS instance and datastore identify a repository, not a PVE workload. A PBS row takes its workload from the server's `guestInstance`, the attribution described at the top of this contract. No namespace, label or lone VMID can pool it onto a guest diff --git a/internal/monitoring/monitor_backups.go b/internal/monitoring/monitor_backups.go index 917c6b7fa3..2a03e35df9 100644 --- a/internal/monitoring/monitor_backups.go +++ b/internal/monitoring/monitor_backups.go @@ -17,6 +17,7 @@ import ( "github.com/rcourtman/pulse-go-rewrite/internal/monitoring/errors" "github.com/rcourtman/pulse-go-rewrite/internal/recovery" proxmoxrecoverymapper "github.com/rcourtman/pulse-go-rewrite/internal/recovery/mapper/proxmox" + recoverystore "github.com/rcourtman/pulse-go-rewrite/internal/recovery/store" "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources" "github.com/rcourtman/pulse-go-rewrite/pkg/pbs" "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox" @@ -1602,16 +1603,20 @@ func (m *Monitor) pollGuestSnapshots(ctx context.Context, instanceName string, c Msg("Failed to attach PVE snapshot recovery evidence; preserving existing points") } else if len(targets) > 0 && len(polledGuestKeys) == len(targets) && carriedForward == 0 && snapshotCtx.Err() == nil { - // Only an accepted complete listing can establish instance-wide - // absence. In particular, after a monitor replacement the live cache - // can be empty while durable snapshots still exist for a failed guest. - // No observed guest inventory is not a successful empty enumeration. + // Success for every loaded guest establishes absence for those guests + // only. After monitor replacement even the live carry-forward can be + // empty while another guest's durable snapshots still exist. + readGuests := make(map[recoverystore.PVESnapshotGuest]struct{}, len(targets)) + for _, target := range targets { + readGuests[recoverystore.PVESnapshotGuest{Node: target.node, Kind: target.guestType, VMID: target.vmid}] = struct{}{} + } m.ingestAndReconcileRecoveryPointsAsync( points, recoveryReconcileScope{ - provider: string(recovery.ProviderProxmoxPVE), - idPrefix: "pve-snapshot:", - instance: instanceName, + provider: string(recovery.ProviderProxmoxPVE), + idPrefix: "pve-snapshot:", + instance: instanceName, + snapshotGuests: readGuests, }, ) } else { diff --git a/internal/monitoring/recovery_ingest.go b/internal/monitoring/recovery_ingest.go index c79d5d93a5..632bee658c 100644 --- a/internal/monitoring/recovery_ingest.go +++ b/internal/monitoring/recovery_ingest.go @@ -20,6 +20,10 @@ type recoveryReconcileScope struct { provider string idPrefix string instance string + + // A snapshot poll only has removal authority for its exact read targets. + // Nil leaves the existing instance-wide scope for full backup inventories. + snapshotGuests map[recoverystore.PVESnapshotGuest]struct{} } // recoveryIngestBatch is one poll cycle's worth of recovery points, plus an @@ -43,7 +47,9 @@ type recoveryIngestCoalesceKey struct { } func (batch recoveryIngestBatch) coalesceKey() (recoveryIngestCoalesceKey, bool) { - if batch.reconcile == nil { + // Guest-scoped batches can overlap without superseding one another. Keep + // their observations and removals in source order, just like partial reads. + if batch.reconcile == nil || batch.reconcile.snapshotGuests != nil { return recoveryIngestCoalesceKey{}, false } return recoveryIngestCoalesceKey{ @@ -113,8 +119,8 @@ func (m *Monitor) enqueueRecoveryIngest(batch recoveryIngestBatch) { m.recoveryIngestMu.Lock() if m.recoveryIngestRunning { - // A reconcile batch is a complete current enumeration for one source - // scope, so only its newest pending value is authoritative. Distinct + // An instance-wide reconcile batch is a complete enumeration, so only + // its newest pending value is authoritative. Distinct // scopes and non-reconciling event batches remain FIFO; this preserves // their facts without retaining every superseded full poll result. if m.coalescePendingRecoveryIngest(batch) { @@ -225,7 +231,13 @@ func (m *Monitor) ingestRecoveryPointsBestEffort(ctx context.Context, batch reco for _, p := range batch.points { keepIDs = append(keepIDs, p.ID) } - if _, err := store.ReconcileInstancePoints(ctx, batch.reconcile.provider, batch.reconcile.idPrefix, batch.reconcile.instance, keepIDs); err != nil { + scope := batch.reconcile + if scope.snapshotGuests != nil { + _, err = store.ReconcilePVESnapshotPoints(ctx, scope.instance, scope.snapshotGuests, keepIDs) + } else { + _, err = store.ReconcileInstancePoints(ctx, scope.provider, scope.idPrefix, scope.instance, keepIDs) + } + if err != nil { log.Warn(). Err(err). Str("org_id", orgID). diff --git a/internal/monitoring/recovery_ingest_test.go b/internal/monitoring/recovery_ingest_test.go index 013d42bfdd..196e0f5fdf 100644 --- a/internal/monitoring/recovery_ingest_test.go +++ b/internal/monitoring/recovery_ingest_test.go @@ -358,6 +358,36 @@ func TestRecoveryIngestCompletePollCannotOvertakePartialBatch(t *testing.T) { } } +func TestRecoveryIngestKeepsOverlappingSnapshotReadScopesInOrder(t *testing.T) { + m := &Monitor{recoveryIngestRunning: true} + guestA := recoverystore.PVESnapshotGuest{Node: "node-a", Kind: "qemu", VMID: 101} + guestB := recoverystore.PVESnapshotGuest{Node: "node-b", Kind: "qemu", VMID: 202} + enqueue := func(guests ...recoverystore.PVESnapshotGuest) { + targets := make(map[recoverystore.PVESnapshotGuest]struct{}, len(guests)) + for _, guest := range guests { + targets[guest] = struct{}{} + } + m.enqueueRecoveryIngest(recoveryIngestBatch{reconcile: &recoveryReconcileScope{ + provider: string(recovery.ProviderProxmoxPVE), idPrefix: "pve-snapshot:", instance: "site", + snapshotGuests: targets, + }}) + } + enqueue(guestA, guestB) + enqueue(guestB) + enqueue(guestA) + want := []map[recoverystore.PVESnapshotGuest]struct{}{ + {guestA: {}, guestB: {}}, {guestB: {}}, {guestA: {}}, + } + if len(m.recoveryIngestPending) != len(want) { + t.Fatalf("expected three pending overlapping read scopes, got %d", len(m.recoveryIngestPending)) + } + for i, batch := range m.recoveryIngestPending { + if !reflect.DeepEqual(want[i], batch.reconcile.snapshotGuests) { + t.Fatalf("read scope %d was reordered or replaced: %v", i, batch.reconcile.snapshotGuests) + } + } +} + // Snapshot inventory in memory can be empty after an ordinary monitor // replacement while its durable recovery points still exist. Exercise the // actual poll, ingest queue and public store reader, not database internals. diff --git a/internal/monitoring/snapshot_reconcile_scope_test.go b/internal/monitoring/snapshot_reconcile_scope_test.go new file mode 100644 index 0000000000..8bf5a7d32c --- /dev/null +++ b/internal/monitoring/snapshot_reconcile_scope_test.go @@ -0,0 +1,75 @@ +package monitoring + +import ( + "context" + "testing" + + "github.com/rcourtman/pulse-go-rewrite/internal/models" + "github.com/stretchr/testify/require" +) + +func showSnapshotFixtureGuests(m *Monitor, kind string, showFirst bool) { + var vms []models.VM + var containers []models.Container + for _, guest := range []struct { + node string + id int + name string + }{{"node-a", 101, "Ledger VM"}, {"node-b", 202, "Worker VM"}} { + if guest.id == 101 && !showFirst { + continue + } + id := makeGuestID("site", guest.node, guest.id) + if kind == "qemu" { + vms = append(vms, models.VM{ID: id, Instance: "site", Node: guest.node, VMID: guest.id, Name: guest.name, Type: kind, Status: "running"}) + } else { + containers = append(containers, models.Container{ID: id, Instance: "site", Node: guest.node, VMID: guest.id, Name: guest.name, Type: kind, Status: "running"}) + } + } + m.state.UpdateGuestsForInstance("site", vms, containers) +} + +// A warm cache can carry the unknown sibling. After restart, only the durable +// evidence still knows it exists. Use the same actual snapshot HTTP reader +// and reconcile path in both cases. +func TestPVESnapshotColdSubsetDoesNotReconcileUnqueriedGuest(t *testing.T) { + for _, kind := range []string{"qemu", "lxc"} { + t.Run(kind, func(t *testing.T) { + h := newSnapshotInventoryHTTPFixture(t, kind) + showSnapshotFixtureGuests(h.f.m, kind, true) + h.poll(t, "site") + h.poll(t, "other-site") + before := h.f.points(t) + const unreadID = "pve-snapshot:site-node-a-101-weekly" + const emptyID = "pve-snapshot:site-node-b-202-weekly" + const otherID = "pve-snapshot:other-site-node-a-101-weekly" + require.Len(t, before, 3) + require.Contains(t, before, unreadID) + require.Contains(t, before, emptyID) + require.Contains(t, before, otherID) + + h.f.coldState(false) + showSnapshotFixtureGuests(h.f.m, kind, false) + h.set("node-b", `{"data":[]}`) + h.f.m.pollGuestSnapshots(context.Background(), "site", h.client) + h.f.wait(t) + require.Equal(t, 4, h.requests, "one actual HTTP read for the single visible guest") + now := h.f.points(t) + require.Equal(t, before[unreadID], now[unreadID], "an unqueried guest's exact record must survive") + require.Equal(t, before[otherID], now[otherID], "the namesake is untouched") + require.NotContains(t, now, emptyID, "the queried guest's explicit empty list still removes its stale record") + require.Empty(t, snapshotCollectionByID(h.f.m), "retained history is not fabricated live snapshot inventory") + + showSnapshotFixtureGuests(h.f.m, kind, true) + h.set("node-a", `{"data":null}`) + h.poll(t, "site") + require.Equal(t, now, h.f.points(t), "returning guest plus unread snapshot listing cannot renew or delete prior history") + + h.set("node-a", `{"data":[]}`) + h.poll(t, "site") + after := h.f.points(t) + require.Len(t, after, 1) + require.Equal(t, before[otherID], after[otherID], "an explicit empty listing removes only this guest's stored row") + }) + } +} diff --git a/internal/recovery/store/store.go b/internal/recovery/store/store.go index 40b36e0254..7825d9c27e 100644 --- a/internal/recovery/store/store.go +++ b/internal/recovery/store/store.go @@ -481,6 +481,28 @@ func (s *Store) PurgeStalePVEPBSBackups(ctx context.Context) error { // prune and kept re-raising age alerts (#1580). Callers must only pass // enumerations that fully succeeded (or carried forward unpolled entries). func (s *Store) ReconcileInstancePoints(ctx context.Context, provider, idPrefix, instance string, keepIDs []string) (int64, error) { + return s.reconcileInstancePoints(ctx, provider, idPrefix, instance, keepIDs, nil) +} + +// PVESnapshotGuest is the exact node, native kind and VMID used to list +// snapshots for one guest on a PVE connection. +type PVESnapshotGuest struct { + Node string + Kind string + VMID int +} + +// ReconcilePVESnapshotPoints removes absent points only for guests whose +// snapshot inventories were accepted. A guest missing from the monitor's +// current inventory did not supply an empty listing. +func (s *Store) ReconcilePVESnapshotPoints(ctx context.Context, instance string, readGuests map[PVESnapshotGuest]struct{}, keepIDs []string) (int64, error) { + if len(readGuests) == 0 { + return 0, nil + } + return s.reconcileInstancePoints(ctx, string(recovery.ProviderProxmoxPVE), "pve-snapshot:", instance, keepIDs, readGuests) +} + +func (s *Store) reconcileInstancePoints(ctx context.Context, provider, idPrefix, instance string, keepIDs []string, snapshotGuests map[PVESnapshotGuest]struct{}) (int64, error) { if err := s.ensureInitialized(); err != nil { return 0, err } @@ -504,7 +526,7 @@ func (s *Store) ReconcileInstancePoints(ctx context.Context, provider, idPrefix, // PVE points carry the connection in details_json.instance; PBS points in // repository_ref_json.namespace. The id prefix keeps the classes apart, so // matching either field never crosses providers. - rows, err := s.db.QueryContext(ctx, ` + query := ` SELECT id, subject_key FROM recovery_points WHERE provider = ? AND id LIKE ? || '%' @@ -512,7 +534,29 @@ func (s *Store) ReconcileInstancePoints(ctx context.Context, provider, idPrefix, json_extract(details_json, '$.instance') = ? OR json_extract(repository_ref_json, '$.namespace') = ? ) - `, provider, idPrefix, instance, instance) + ` + args := []any{provider, idPrefix, instance, instance} + if snapshotGuests != nil { + // Use the observed identity fields, not names, the guest's current + // placement or a split of the opaque persisted ID. Legacy rows with + // unknown origin cannot be claimed by a successful guest listing. + query = ` + SELECT id, subject_key, json_extract(details_json, '$.node'), + json_extract(details_json, '$.type'), json_extract(details_json, '$.vmid') + FROM recovery_points + WHERE provider = ? + AND id LIKE ? || '%' + AND kind = 'snapshot' + AND json_extract(details_json, '$.instance') = ? + AND json_type(details_json, '$.node') = 'text' + AND json_extract(details_json, '$.node') <> '' + AND json_extract(details_json, '$.type') IN ('qemu', 'lxc') + AND json_type(details_json, '$.vmid') = 'integer' + AND json_extract(details_json, '$.vmid') > 0 + ` + args = args[:3] + } + rows, err := s.db.QueryContext(ctx, query, args...) if err != nil { return 0, err } @@ -523,7 +567,15 @@ func (s *Store) ReconcileInstancePoints(ctx context.Context, provider, idPrefix, for rows.Next() { var id string var subjectKey sql.NullString - if err := rows.Scan(&id, &subjectKey); err != nil { + if snapshotGuests != nil { + var guest PVESnapshotGuest + if err := rows.Scan(&id, &subjectKey, &guest.Node, &guest.Kind, &guest.VMID); err != nil { + return 0, err + } + if _, read := snapshotGuests[guest]; !read { + continue + } + } else if err := rows.Scan(&id, &subjectKey); err != nil { return 0, err } if _, ok := keep[id]; !ok { diff --git a/internal/recovery/store/store_test.go b/internal/recovery/store/store_test.go index 66be6ea9c5..f8f0f98f19 100644 --- a/internal/recovery/store/store_test.go +++ b/internal/recovery/store/store_test.go @@ -300,6 +300,70 @@ func TestStore_ReconcileInstancePoints(t *testing.T) { } } +func TestStore_ReconcilePVESnapshotPointsRequiresExactReadTarget(t *testing.T) { + t.Parallel() + ctx := context.Background() + store, err := Open(filepath.Join(t.TempDir(), "recovery.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = store.Close() }) + now := time.Now().UTC() + point := func(name, instance, node, kind string, vmid int) recovery.RecoveryPoint { + return recovery.RecoveryPoint{ + ID: "pve-snapshot:" + name, Provider: recovery.ProviderProxmoxPVE, + Kind: recovery.KindSnapshot, Mode: recovery.ModeSnapshot, Outcome: recovery.OutcomeSuccess, + StartedAt: &now, CompletedAt: &now, + Details: map[string]any{"instance": instance, "node": node, "type": kind, "vmid": vmid}, + } + } + stale := point("absent", "east", "node-a", "qemu", 101) + fresh := point("still-listed", "east", "node-a", "qemu", 101) + otherProvider := point("different-provider", "east", "node-a", "qemu", 101) + otherProvider.Provider = recovery.ProviderTrueNAS + archive := point("archive", "east", "node-a", "qemu", 101) + archive.ID, archive.Kind, archive.Mode = "pve-backup:archive", recovery.KindBackup, recovery.ModeLocal + keep := []recovery.RecoveryPoint{ + fresh, + point("opposite-kind", "east", "node-a", "lxc", 101), + point("different-vmid", "east", "node-a", "qemu", 102), + point("different-node", "east", "node-b", "qemu", 101), + point("different-connection", "west", "node-a", "qemu", 101), + point("legacy-kind", "east", "node-a", "", 101), + point("legacy-node", "east", "", "qemu", 101), + otherProvider, + archive, + } + if err := store.UpsertPoints(ctx, append([]recovery.RecoveryPoint{stale}, keep...)); err != nil { + t.Fatal(err) + } + check := func(targets map[PVESnapshotGuest]struct{}, listed []string, want int64) { + t.Helper() + deleted, err := store.ReconcilePVESnapshotPoints(ctx, "east", targets, listed) + if err != nil || deleted != want { + t.Fatalf("reconcile deleted %d, want %d: %v", deleted, want, err) + } + } + check(nil, nil, 0) + targets := map[PVESnapshotGuest]struct{}{{Node: "node-a", Kind: "qemu", VMID: 101}: {}} + check(targets, []string{fresh.ID}, 1) + got, _, err := store.ListPoints(ctx, recovery.ListPointsOptions{}) + if err != nil || len(got) != len(keep) { + t.Fatalf("retained points: got %d, want %d: %v", len(got), len(keep), err) + } + retained := make(map[string]bool, len(got)) + for _, p := range got { + retained[p.ID] = true + } + for _, p := range keep { + if !retained[p.ID] { + t.Errorf("reconciled untouched point %s", p.ID) + } + } + check(targets, nil, 1) // Explicit empty inventory removes the last exact point. + check(targets, nil, 0) +} + func TestStore_ListPoints_IgnoresMalformedJSONFields(t *testing.T) { t.Parallel()