Files
Pulse/internal/monitoring/poll_planning_progress_test.go
pulse-triage[bot] 088f32d58e Repair reconnect guardrail and use the race-safe poll test logger
Exercise paused PVE, PBS and PMG retry behavior instead of matching the former local variable names. Route the imported blocked-debug-output fixture through the atomic test sink added on main, preserving the logger race repair.

Contract-Neutral: Test-only compatibility repair for reviewed reconnect and poll-cycle behavior; no production or contract delta.
Change-source: pulse-maintainer
2026-11-29 12:09:14 +00:00

342 lines
10 KiB
Go

package monitoring
import (
"context"
"fmt"
"strings"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
"github.com/rs/zerolog"
)
type heldPlanningRoster struct {
testPollProvider
hold func()
}
func TestCanceledPollPlanDoesNotPublishAfterRosterReturns(t *testing.T) {
for _, mode := range []string{"fixed", "adaptive"} {
t.Run(mode, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
m := newScheduleFixture(ctx, mode == "adaptive", nil)
// A cycle that reached alert synchronization would replace
// this marker with the alert manager's empty active set.
m.state.UpdateActiveAlerts([]models.Alert{{ID: "existing-alert"}})
held, release, returned := make(chan struct{}), make(chan struct{}), make(chan struct{})
unblock := sync.OnceFunc(func() { close(release) })
defer unblock()
if err := m.RegisterPollProvider(heldPlanningRoster{
testPollProvider: testPollProvider{providerType: "fixture"},
hold: func() {
close(held)
<-release
},
}); err != nil {
t.Fatal(err)
}
var laterReads int
if err := m.RegisterPollProvider(heldPlanningRoster{
testPollProvider: testPollProvider{providerType: "later-fixture"},
hold: func() { laterReads++ },
}); err != nil {
t.Fatal(err)
}
go func() {
defer close(returned)
m.poll(ctx, nil)
}()
<-held
cancel()
unblock()
<-returned
if laterReads != 0 {
t.Errorf("retired monitor started %d later provider roster read(s)", laterReads)
}
if depth := m.taskQueue.Size(); depth != 0 {
t.Errorf("retired monitor enqueued %d poll(s)", depth)
}
if m.scheduler != nil {
if task, ok := m.scheduler.LastScheduled(InstanceTypePVE, scheduleFixtureNode); ok {
t.Errorf("retired monitor cached an adaptive poll: %+v", task)
}
}
state := m.state.GetSnapshot()
if state.Stats.PollingCycles != 0 {
t.Errorf("retired monitor recorded %d poll cycle(s)", state.Stats.PollingCycles)
}
if len(state.ActiveAlerts) != 1 || state.ActiveAlerts[0].ID != "existing-alert" {
t.Errorf("retired monitor reconciled alert state after cancellation: %+v", state.ActiveAlerts)
}
if m.activePollCount != 0 {
t.Error("retired planner did not release its slot")
}
})
})
}
}
func (p heldPlanningRoster) pollPlanningRoster(*Monitor) []pollPlanInstance {
p.hold()
return nil
}
type cancelingCadenceProvider struct {
testPollProvider
onList, onCadence func()
}
func (p cancelingCadenceProvider) ListInstances(m *Monitor) []string {
p.onList()
return p.testPollProvider.ListInstances(m)
}
func (p cancelingCadenceProvider) FixedInstanceInterval(*Monitor, string) time.Duration {
p.onCadence()
return time.Minute
}
func TestCanceledPollPlanSkipsRemainingCadenceReads(t *testing.T) {
for _, tc := range []struct {
name string
cancelDuringList bool
wantCadenceReads int
}{
{name: "active", wantCadenceReads: 2},
{name: "roster", cancelDuringList: true},
{name: "first cadence", wantCadenceReads: 1},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
m := newScheduleFixture(ctx, true, nil)
var cadenceReads int
// Install the provider without the registration-time health
// roster read: this cancellation must happen during planning.
m.pollProviders = map[InstanceType]PollProvider{"fixture": cancelingCadenceProvider{
testPollProvider: testPollProvider{providerType: "fixture", instances: []string{"second", "first"}},
onList: func() {
if tc.cancelDuringList {
cancel()
}
},
onCadence: func() {
cadenceReads++
if tc.name == "first cadence" {
cancel()
}
},
}}
m.poll(ctx, nil)
if cadenceReads != tc.wantCadenceReads {
t.Errorf("cadence reads = %d; want %d", cadenceReads, tc.wantCadenceReads)
}
task, queued := m.taskQueue.Get("fixture", "second")
if tc.name == "active" {
if !queued || task.Interval != time.Minute {
t.Errorf("active plan did not publish fixed cadence: queued=%v task=%+v", queued, task)
}
} else if m.taskQueue.Size() != 0 {
t.Error("retired monitor published a partial plan")
}
})
}
}
func TestSchedulerPlanningAgeWhileBothPollCyclesAreHeld(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
ctx := t.Context()
m := newScheduleFixture(ctx, true, func(context.Context) ([]proxmox.Node, error) {
return []proxmox.Node{{Node: scheduleFixtureNode, Status: "online", CPU: 0.42, Uptime: 36000}}, nil
})
reg := prometheus.NewRegistry()
m.pollMetrics = newPollMetrics(reg)
defer m.pollMetrics.trackTaskQueue(ctx, m.taskQueue)()
var calls atomic.Int32
first, second := make(chan struct{}), make(chan struct{})
releaseFirst := sync.OnceFunc(func() { close(first) })
releaseSecond := sync.OnceFunc(func() { close(second) })
defer releaseFirst()
defer releaseSecond()
if err := m.RegisterPollProvider(heldPlanningRoster{
testPollProvider: testPollProvider{providerType: "fixture"},
hold: func() {
switch calls.Add(1) {
case 1:
<-first
panic("fixture roster panic")
case 2:
<-second
}
},
}); err != nil {
t.Fatal(err)
}
scrape := func(age int) {
t.Helper()
const name = "pulse_scheduler_poll_planning_age_seconds"
want := fmt.Sprintf("# HELP %[1]s Age in seconds of the oldest poll planning pass still running; zero if none.\n"+
"# TYPE %[1]s gauge\n%[1]s %[2]d\n", name, age)
if err := testutil.GatherAndCompare(reg, strings.NewReader(want), name); err != nil {
t.Error(err)
}
}
scrape(0)
go m.poll(ctx, nil)
synctest.Wait()
time.Sleep(20 * time.Second)
go m.poll(ctx, nil)
synctest.Wait()
time.Sleep(12 * time.Second)
// A third cycle cannot admit a plan. Neither held cycle has reached
// the queue, so queue and worker diagnostics cannot see this stall.
m.poll(ctx, nil)
if got := calls.Load(); got != 2 || m.taskQueue.Size() != 0 {
t.Fatalf("expected two held planning passes and an empty queue, got calls=%d depth=%d", got, m.taskQueue.Size())
}
scrape(32)
// Completing the newer pass cannot clear or reset the older one.
releaseSecond()
synctest.Wait()
if _, ok := m.taskQueue.Get(InstanceTypePVE, scheduleFixtureNode); !ok {
t.Fatal("returning planner did not queue the PVE poll")
}
time.Sleep(3 * time.Second)
scrape(35)
// A panic unwinds the older pass and releases both its slot and marker.
releaseFirst()
synctest.Wait()
scrape(0)
if m.activePollCount != 0 {
t.Fatalf("planning slots left held after both returns: %d", m.activePollCount)
}
})
}
// Route through the package's atomic sink instead of replacing log.Logger:
// earlier tests may still have background goroutines emitting unrelated logs.
type heldPollLifecycleWriter struct {
message string
resume <-chan struct{}
}
func (w heldPollLifecycleWriter) Write(p []byte) (int, error) {
if strings.Contains(string(p), w.message) {
<-w.resume
}
return len(p), nil
}
func TestPollCycleProgressDoesNotDependOnDebugLifecycleLogging(t *testing.T) {
for _, tc := range []struct {
name, message string
saturated bool
}{
{name: "before-planning", message: "starting polling cycle"},
{name: "before-slot-release", message: "polling cycle completed"},
{name: "at-capacity", message: "too many concurrent polls, skipping", saturated: true},
} {
t.Run(tc.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
ctx := t.Context()
m := newScheduleFixture(ctx, false, nil)
resume := make(chan struct{})
var running sync.WaitGroup
restore := setPackageTestLogOutput(t, heldPollLifecycleWriter{
message: tc.message, resume: resume,
}, zerolog.DebugLevel)
defer func() {
close(resume)
running.Wait()
restore()
}()
startCycle := func() <-chan struct{} {
done := make(chan struct{})
running.Go(func() {
defer close(done)
m.poll(ctx, nil)
})
return done
}
checkReturned := func(done <-chan struct{}) bool {
select {
case <-done:
return true
default:
return false
}
}
if tc.saturated {
release := make(chan struct{})
unblock := sync.OnceFunc(func() { close(release) })
defer unblock()
var rosterReads atomic.Int32
if err := m.RegisterPollProvider(heldPlanningRoster{
testPollProvider: testPollProvider{providerType: "fixture"},
hold: func() {
rosterReads.Add(1)
<-release
},
}); err != nil {
t.Fatal(err)
}
first, second := startCycle(), startCycle()
synctest.Wait()
if got := rosterReads.Load(); got != 2 {
t.Fatalf("expected two held planners, got %d", got)
}
var skipped [8]<-chan struct{}
for i := range skipped {
skipped[i] = startCycle()
}
synctest.Wait()
for i, done := range skipped {
if !checkReturned(done) {
t.Fatalf("skipped tick %d did not return while its debug output was blocked", i)
}
}
if got := rosterReads.Load(); got != 2 || m.taskQueue.Size() != 0 {
t.Fatalf("skipped ticks admitted work: roster reads=%d, queued=%d", got, m.taskQueue.Size())
}
unblock()
<-first
<-second
} else {
done := startCycle()
synctest.Wait()
if !checkReturned(done) {
t.Fatal("admitted cycle did not return while its debug output was blocked")
}
}
if _, ok := m.taskQueue.Get(InstanceTypePVE, scheduleFixtureNode); !ok || m.activePollCount != 0 {
t.Fatalf("expected an admitted poll and released cycle slots: queued=%v active=%d", ok, m.activePollCount)
}
wantCycles := 1
if tc.saturated {
wantCycles = 2
}
if got := int(m.state.GetSnapshot().Stats.PollingCycles); got != wantCycles {
t.Errorf("completed cycles = %d; want %d", got, wantCycles)
}
})
})
}
}