From 64d047062ba9b4fa2287fcd0ff4fa59092e58501 Mon Sep 17 00:00:00 2001 From: Kakuya Ando Date: Sun, 8 Nov 2026 16:14:55 +0900 Subject: [PATCH 1/3] Fix stats reset race, history ordering, sort stability and beeper blocking --- internal/beep/beep.go | 47 +++++++----- internal/beep/beep_test.go | 31 ++++++++ internal/stats/history.go | 35 ++++++++- internal/stats/manager.go | 28 +++++-- internal/stats/metric.go | 15 +++- internal/stats/regression_test.go | 122 ++++++++++++++++++++++++++++++ 6 files changed, 245 insertions(+), 33 deletions(-) create mode 100644 internal/stats/regression_test.go diff --git a/internal/beep/beep.go b/internal/beep/beep.go index e0e6252..5073e99 100644 --- a/internal/beep/beep.go +++ b/internal/beep/beep.go @@ -2,6 +2,7 @@ package beep import ( "fmt" + "io" "os" "sync" "time" @@ -18,6 +19,9 @@ type Beeper struct { debounceTime time.Duration lastBeepTime time.Time mu sync.Mutex + out io.Writer + queue chan struct{} + startOnce sync.Once } // NewBeeper creates a new Beeper instance @@ -25,41 +29,44 @@ func NewBeeper() *Beeper { return &Beeper{ enabled: true, // Default is ON debounceTime: DefaultDebounceInterval, + out: os.Stdout, + queue: make(chan struct{}, 1), } } -// Beep plays a beep sound if enabled and debounce time has passed -// This function is non-blocking and thread-safe +// Beep requests a beep sound. It never blocks: requests are handed to a +// single worker through a one-slot queue and extra requests are dropped. func (b *Beeper) Beep() { - go func() { - b.mu.Lock() - defer b.mu.Unlock() - - // Skip if disabled - if !b.enabled { - return - } + b.startOnce.Do(func() { go b.worker() }) + select { + case b.queue <- struct{}{}: + default: // a beep is already pending + } +} - // Check debounce time +func (b *Beeper) worker() { + for range b.queue { + b.mu.Lock() now := time.Now() - if now.Sub(b.lastBeepTime) < b.debounceTime { - return // Skip if within debounce period + play := b.enabled && now.Sub(b.lastBeepTime) >= b.debounceTime + if play { + b.lastBeepTime = now } - - // Play beep sound + b.mu.Unlock() + if !play { + continue + } + // Write outside the lock so a blocked stdout cannot freeze Toggle if err := b.playBeep(); err != nil { // Log error but don't propagate - // This ensures beep failures don't affect main processing fmt.Fprintf(os.Stderr, "beep: failed to play sound: %v\n", err) } - - b.lastBeepTime = now - }() + } } // playBeep outputs the system bell character func (b *Beeper) playBeep() error { - _, err := fmt.Print("\a") + _, err := fmt.Fprint(b.out, "\a") return err } diff --git a/internal/beep/beep_test.go b/internal/beep/beep_test.go index 8e5e8ae..c4fcbaa 100644 --- a/internal/beep/beep_test.go +++ b/internal/beep/beep_test.go @@ -1,6 +1,7 @@ package beep import ( + "runtime" "testing" "time" ) @@ -106,3 +107,33 @@ func TestConcurrentAccess(t *testing.T) { // If we get here without deadlock or panic, the test passes } + +type blockingWriter struct{ release chan struct{} } + +func (w *blockingWriter) Write(p []byte) (int, error) { + <-w.release + return len(p), nil +} + +func TestBeepDoesNotBlockWhenOutputBlocked(t *testing.T) { + w := &blockingWriter{release: make(chan struct{})} + defer close(w.release) + b := NewBeeper() + b.out = w + b.debounceTime = 0 + before := runtime.NumGoroutine() + for i := 0; i < 200; i++ { + b.Beep() + } + time.Sleep(50 * time.Millisecond) + done := make(chan struct{}) + go func() { b.Toggle(); b.IsEnabled(); close(done) }() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("Toggle/IsEnabled blocked by a stuck stdout") + } + if n := runtime.NumGoroutine() - before; n > 5 { + t.Errorf("goroutines piled up: +%d", n) + } +} diff --git a/internal/stats/history.go b/internal/stats/history.go index 73d75bd..05f5798 100644 --- a/internal/stats/history.go +++ b/internal/stats/history.go @@ -1,6 +1,7 @@ package stats import ( + "sort" "time" "github.com/servak/mping/internal/prober" @@ -25,6 +26,9 @@ type TargetHistory struct { // NewTargetHistory creates a new TargetHistory func NewTargetHistory(size int) *TargetHistory { + if size < 1 { + size = 1 + } return &TargetHistory{ entries: make([]HistoryEntry, size), size: size, @@ -33,8 +37,17 @@ func NewTargetHistory(size int) *TargetHistory { } } -// AddEntry adds a new history entry +// AddEntry adds a new history entry. Entries are kept ordered by Timestamp +// (send time), so a late result for an older probe is inserted before newer +// ones instead of being appended at the newest end. func (th *TargetHistory) AddEntry(entry HistoryEntry) { + if th.count > 0 { + newest := th.entries[(th.index-1+th.size)%th.size] + if entry.Timestamp.Before(newest.Timestamp) { + th.insertOrdered(entry) + return + } + } th.entries[th.index] = entry th.index = (th.index + 1) % th.size if th.count < th.size { @@ -42,6 +55,26 @@ func (th *TargetHistory) AddEntry(entry HistoryEntry) { } } +// insertOrdered inserts an entry that is older than the newest one at its +// chronological position, dropping the oldest entry if the buffer is full. +func (th *TargetHistory) insertOrdered(entry HistoryEntry) { + list := make([]HistoryEntry, 0, th.count+1) + for i := th.count - 1; i >= 0; i-- { + list = append(list, th.entries[(th.index-1-i+th.size)%th.size]) + } + // after any entries with an equal timestamp + pos := sort.Search(len(list), func(i int) bool { return list[i].Timestamp.After(entry.Timestamp) }) + list = append(list, HistoryEntry{}) + copy(list[pos+1:], list[pos:]) + list[pos] = entry + if len(list) > th.size { + list = list[len(list)-th.size:] + } + copy(th.entries, list) + th.count = len(list) + th.index = th.count % th.size +} + // GetRecentEntries retrieves the latest n entries (newest first) func (th *TargetHistory) GetRecentEntries(n int) []HistoryEntry { if n <= 0 || th.count == 0 { diff --git a/internal/stats/manager.go b/internal/stats/manager.go index fd1ea59..f33cba8 100644 --- a/internal/stats/manager.go +++ b/internal/stats/manager.go @@ -97,6 +97,10 @@ func (mm *metricsManager) SuccessWithDetails(host string, rtt time.Duration, sen m := mm.getMetrics(host) mm.mu.Lock() + if sentTime.Before(m.resetAt) { + mm.mu.Unlock() + return // probe sent before the last reset + } m.Success(rtt, sentTime) if m.history != nil { m.history.AddEntry(HistoryEntry{ @@ -115,6 +119,10 @@ func (mm *metricsManager) Failed(host string, sentTime time.Time, msg string) { m := mm.getMetrics(host) mm.mu.Lock() + if sentTime.Before(m.resetAt) { + mm.mu.Unlock() + return // probe sent before the last reset + } name := m.Name m.Fail(sentTime, msg) if m.history != nil { @@ -196,16 +204,20 @@ func (mm *metricsManager) SortBy(k Key, ascending bool) []Metrics { mm.mu.Lock() defer mm.mu.Unlock() now := time.Now() - var res []Metrics - for _, m := range mm.metrics { - res = append(res, m.settledSnapshot(now)) + keys := make([]string, 0, len(mm.metrics)) + for key := range mm.metrics { + keys = append(keys, key) } - - if k != Host { - sort.SliceStable(res, func(i, j int) bool { - return res[i].GetName() < res[j].GetName() - }) + sort.Strings(keys) + // Tie-break deterministically: by display name, then by key + sort.SliceStable(keys, func(i, j int) bool { + return mm.metrics[keys[i]].Name < mm.metrics[keys[j]].Name + }) + res := make([]Metrics, 0, len(keys)) + for _, key := range keys { + res = append(res, mm.metrics[key].settledSnapshot(now)) } + // less must be a strict ordering: descending order swaps the operands // instead of negating the result, which would make equal elements // "less" than each other and reorder them on every call. diff --git a/internal/stats/metric.go b/internal/stats/metric.go index 6bf6fb6..f590ad0 100644 --- a/internal/stats/metric.go +++ b/internal/stats/metric.go @@ -56,16 +56,19 @@ type metrics struct { LastFailDetail string history *TargetHistory // 履歴情報 outage *outageTracker + resetAt time.Time // results of probes sent before this are stale } func (m *metrics) Success(rtt time.Duration, sentTime time.Time) { m.Successful++ - m.LastSuccTime = sentTime + if sentTime.After(m.LastSuccTime) { + m.LastSuccTime = sentTime + } m.LastRTT = rtt m.TotalRTT += rtt m.sumSquaredRTT += float64(rtt) * float64(rtt) m.AverageRTT = m.TotalRTT / time.Duration(m.Successful) - if m.MinimumRTT == 0 || rtt < m.MinimumRTT { + if m.Successful == 1 || rtt < m.MinimumRTT { m.MinimumRTT = rtt } if rtt > m.MaximumRTT { @@ -76,8 +79,11 @@ func (m *metrics) Success(rtt time.Duration, sentTime time.Time) { func (m *metrics) Fail(sentTime time.Time, msg string) { m.Failed++ - m.LastFailTime = sentTime - m.LastFailDetail = msg + // a late result of an older probe must not overwrite newer failure info + if !sentTime.Before(m.LastFailTime) { + m.LastFailTime = sentTime + m.LastFailDetail = msg + } m.loss() } @@ -90,6 +96,7 @@ func (m *metrics) Sent() { } func (m *metrics) Reset() { + m.resetAt = time.Now() m.Total = 0 m.Successful = 0 m.Failed = 0 diff --git a/internal/stats/regression_test.go b/internal/stats/regression_test.go new file mode 100644 index 0000000..5714903 --- /dev/null +++ b/internal/stats/regression_test.go @@ -0,0 +1,122 @@ +package stats + +import ( + "testing" + "time" +) + +func TestResetDropsStaleResults(t *testing.T) { + mm := NewMetricsManager().(*metricsManager) + sent := time.Now().Add(-time.Second) + mm.Sent("a") + time.Sleep(2 * time.Millisecond) + mm.ResetAllMetrics() + mm.SuccessWithDetails("a", time.Millisecond, sent, nil) + mm.Failed("a", sent, "late") + m := mm.GetMetrics("a") + if m.GetTotal() != 0 || m.GetSuccessful() != 0 || m.GetFailed() != 0 { + t.Errorf("stale results counted: %d/%d/%d", m.GetTotal(), m.GetSuccessful(), m.GetFailed()) + } + if len(m.GetRecentHistory(10)) != 0 { + t.Error("stale result entered history") + } + mm.SuccessWithDetails("a", time.Millisecond, time.Now(), nil) + if mm.GetMetrics("a").GetSuccessful() != 1 { + t.Error("fresh result after reset must be counted") + } +} + +func TestHistoryOrderedBySentTime(t *testing.T) { + h := NewTargetHistory(5) + base := time.Now().Add(-time.Minute) + h.AddEntry(HistoryEntry{Timestamp: base.Add(2 * time.Second), Success: true}) + h.AddEntry(HistoryEntry{Timestamp: base, Success: false}) // late timeout of older probe + if got := h.GetConsecutiveSuccesses(); got != 1 { + t.Errorf("consecutive successes = %d, want 1", got) + } + if got := h.GetConsecutiveFailures(); got != 0 { + t.Errorf("consecutive failures = %d, want 0", got) + } + e := h.GetRecentEntries(2) + if !e[0].Timestamp.After(e[1].Timestamp) { + t.Error("entries not newest-first by sent time") + } + // full buffer: insertion keeps order and size + for i := 3; i < 8; i++ { + h.AddEntry(HistoryEntry{Timestamp: base.Add(time.Duration(i) * time.Second), Success: true}) + } + h.AddEntry(HistoryEntry{Timestamp: base.Add(4500 * time.Millisecond), Success: false}) + e = h.GetRecentEntries(10) + if len(e) != 5 { + t.Fatalf("len = %d", len(e)) + } + for i := 1; i < len(e); i++ { + if e[i].Timestamp.After(e[i-1].Timestamp) { + t.Errorf("order broken at %d", i) + } + } +} + +func TestLastTimesKeepNewest(t *testing.T) { + m := newMetrics("a", 5, 0) + t1 := time.Now() + t0 := t1.Add(-time.Second) + m.Success(time.Millisecond, t1) + m.Success(time.Millisecond, t0) + if !m.LastSuccTime.Equal(t1) { + t.Error("LastSuccTime overwritten by older result") + } + m.Fail(t1, "new") + m.Fail(t0, "old") + if !m.LastFailTime.Equal(t1) || m.LastFailDetail != "new" { + t.Error("LastFailTime/Detail overwritten by older result") + } +} + +func TestMinimumRTTZeroSample(t *testing.T) { + m := newMetrics("a", 5, 0) + m.Success(0, time.Now()) + m.Success(5*time.Millisecond, time.Now()) + if m.MinimumRTT != 0 { + t.Errorf("MinimumRTT = %v, want 0", m.MinimumRTT) + } +} + +func TestSortDeterministicTies(t *testing.T) { + mm := NewMetricsManager().(*metricsManager) + for _, k := range []string{"k3", "k1", "k2", "k5", "k4"} { + mm.autoRegister(k, "same", "") + } + var first []string + // order must follow key order for equal names/values + mm.metrics["k1"].ProbeType = "p1" + mm.metrics["k2"].ProbeType = "p2" + mm.metrics["k3"].ProbeType = "p3" + mm.metrics["k4"].ProbeType = "p4" + mm.metrics["k5"].ProbeType = "p5" + for i := 0; i < 30; i++ { + var got []string + for _, r := range mm.SortBy(Sent, i%2 == 0) { + got = append(got, r.GetProbeType()) + } + if first == nil { + first = got + } + want := []string{"p1", "p2", "p3", "p4", "p5"} + for j := range want { + if got[j] != want[j] { + t.Fatalf("iteration %d: got %v, want %v", i, got, want) + } + } + } +} + +func TestNewMetricsZeroHistorySize(t *testing.T) { + m := NewMetrics("a", 0) + h := NewTargetHistory(-1) + h.AddEntry(HistoryEntry{Timestamp: time.Now()}) + if len(h.GetRecentEntries(5)) != 1 { + t.Error("expected one entry") + } + _ = m +} From 5128d2b2c371361eab2576dc7e56a5ad1ff8da2a Mon Sep 17 00:00:00 2001 From: Kakuya Ando Date: Sun, 8 Nov 2026 16:26:22 +0900 Subject: [PATCH 2/3] Address review findings: drop stale SENT after reset, newest-wins LastRTT, alloc-free history insert, single-sort SortBy, Beeper Close and zero-value safety --- internal/beep/beep.go | 62 +++++++++++++---- internal/beep/beep_test.go | 71 ++++++++++++++++++- internal/beep/notifier.go | 5 ++ internal/beep/notifier_test.go | 11 +-- internal/command/mping.go | 1 + internal/stats/history.go | 38 +++++++---- internal/stats/manager.go | 61 +++++++++++------ internal/stats/metric.go | 9 ++- internal/stats/regression_test.go | 109 +++++++++++++++++++++++++++++- 9 files changed, 307 insertions(+), 60 deletions(-) diff --git a/internal/beep/beep.go b/internal/beep/beep.go index 5073e99..cb70804 100644 --- a/internal/beep/beep.go +++ b/internal/beep/beep.go @@ -13,51 +13,85 @@ const ( DefaultDebounceInterval = 500 * time.Millisecond ) -// Beeper manages beep sound playback with debouncing +// Beeper manages beep sound playback with debouncing. The zero value is +// ready to use (enabled, writing to os.Stdout, no debounce); use NewBeeper +// for the default debounce interval. Call Close to stop the worker goroutine. type Beeper struct { - enabled bool + disabled bool // inverted so that the zero value is enabled debounceTime time.Duration lastBeepTime time.Time mu sync.Mutex out io.Writer queue chan struct{} - startOnce sync.Once + stop chan struct{} + done chan struct{} + initOnce sync.Once + closeOnce sync.Once } // NewBeeper creates a new Beeper instance func NewBeeper() *Beeper { return &Beeper{ - enabled: true, // Default is ON debounceTime: DefaultDebounceInterval, out: os.Stdout, - queue: make(chan struct{}, 1), } } +// init lazily prepares the queue and starts the worker, so that a zero-value +// Beeper works too. +func (b *Beeper) init() { + b.initOnce.Do(func() { + b.mu.Lock() + if b.out == nil { + b.out = os.Stdout + } + b.mu.Unlock() + b.queue = make(chan struct{}, 1) + b.stop = make(chan struct{}) + b.done = make(chan struct{}) + go b.worker() + }) +} + // Beep requests a beep sound. It never blocks: requests are handed to a // single worker through a one-slot queue and extra requests are dropped. func (b *Beeper) Beep() { - b.startOnce.Do(func() { go b.worker() }) + b.init() select { case b.queue <- struct{}{}: default: // a beep is already pending } } +// Close stops the worker goroutine and waits for it to exit. It is +// idempotent; Beep after Close is a harmless no-op. +func (b *Beeper) Close() { + b.init() + b.closeOnce.Do(func() { close(b.stop) }) + <-b.done +} + func (b *Beeper) worker() { - for range b.queue { + defer close(b.done) + for { + select { + case <-b.stop: + return + case <-b.queue: + } b.mu.Lock() now := time.Now() - play := b.enabled && now.Sub(b.lastBeepTime) >= b.debounceTime + play := !b.disabled && now.Sub(b.lastBeepTime) >= b.debounceTime if play { b.lastBeepTime = now } + out := b.out b.mu.Unlock() if !play { continue } // Write outside the lock so a blocked stdout cannot freeze Toggle - if err := b.playBeep(); err != nil { + if err := playBeep(out); err != nil { // Log error but don't propagate fmt.Fprintf(os.Stderr, "beep: failed to play sound: %v\n", err) } @@ -65,8 +99,8 @@ func (b *Beeper) worker() { } // playBeep outputs the system bell character -func (b *Beeper) playBeep() error { - _, err := fmt.Fprint(b.out, "\a") +func playBeep(out io.Writer) error { + _, err := fmt.Fprint(out, "\a") return err } @@ -74,15 +108,15 @@ func (b *Beeper) playBeep() error { func (b *Beeper) Toggle() bool { b.mu.Lock() defer b.mu.Unlock() - b.enabled = !b.enabled - return b.enabled + b.disabled = !b.disabled + return !b.disabled } // IsEnabled returns current beep sound state func (b *Beeper) IsEnabled() bool { b.mu.Lock() defer b.mu.Unlock() - return b.enabled + return !b.disabled } // GetLastBeepTime returns the last beep time (for testing) diff --git a/internal/beep/beep_test.go b/internal/beep/beep_test.go index c4fcbaa..710e7f8 100644 --- a/internal/beep/beep_test.go +++ b/internal/beep/beep_test.go @@ -1,13 +1,16 @@ package beep import ( + "bytes" "runtime" + "sync" "testing" "time" ) func TestNewBeeper(t *testing.T) { beeper := NewBeeper() + defer beeper.Close() if !beeper.IsEnabled() { t.Error("Expected beeper to be enabled by default") @@ -20,6 +23,7 @@ func TestNewBeeper(t *testing.T) { func TestToggle(t *testing.T) { beeper := NewBeeper() + defer beeper.Close() initialState := beeper.IsEnabled() beeper.Toggle() @@ -37,6 +41,7 @@ func TestToggle(t *testing.T) { func TestDebounce(t *testing.T) { debounceInterval := 100 * time.Millisecond beeper := NewBeeper() + defer beeper.Close() beeper.debounceTime = debounceInterval // First beep should work @@ -68,6 +73,7 @@ func TestDebounce(t *testing.T) { func TestBeepWhenDisabled(t *testing.T) { beeper := NewBeeper() + defer beeper.Close() beeper.Toggle() // disable // Beep should not update lastBeepTime when disabled @@ -81,6 +87,7 @@ func TestBeepWhenDisabled(t *testing.T) { func TestConcurrentAccess(t *testing.T) { beeper := NewBeeper() + defer beeper.Close() done := make(chan bool) // Test concurrent beep calls @@ -117,8 +124,10 @@ func (w *blockingWriter) Write(p []byte) (int, error) { func TestBeepDoesNotBlockWhenOutputBlocked(t *testing.T) { w := &blockingWriter{release: make(chan struct{})} - defer close(w.release) b := NewBeeper() + // Close waits for the worker, so release the writer first (LIFO defers) + defer b.Close() + defer close(w.release) b.out = w b.debounceTime = 0 before := runtime.NumGoroutine() @@ -137,3 +146,63 @@ func TestBeepDoesNotBlockWhenOutputBlocked(t *testing.T) { t.Errorf("goroutines piled up: +%d", n) } } + +func TestCloseIdempotentAndStopsWorker(t *testing.T) { + before := runtime.NumGoroutine() + b := NewBeeper() + b.Beep() + b.Close() + b.Close() // second call must not panic or block + b.Beep() // no-op after Close + time.Sleep(20 * time.Millisecond) + if n := runtime.NumGoroutine(); n > before { + t.Errorf("worker goroutine leaked: %d > %d", n, before) + } +} + +func TestCloseWithoutBeep(t *testing.T) { + b := NewBeeper() + b.Close() + b.Close() +} + +type syncBuf struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuf) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} + +func (s *syncBuf) String() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.String() +} + +func TestZeroValueBeeperWorks(t *testing.T) { + var b Beeper + defer b.Close() + if !b.IsEnabled() { + t.Error("zero value should be enabled") + } + b.Beep() // must not panic with nil out; writes to os.Stdout + time.Sleep(20 * time.Millisecond) + if b.GetLastBeepTime().IsZero() { + t.Error("zero-value Beeper dropped the beep") + } +} + +func TestZeroValueBeeperWritesToOut(t *testing.T) { + buf := &syncBuf{} + b := &Beeper{out: buf} + defer b.Close() + b.Beep() + time.Sleep(20 * time.Millisecond) + if buf.String() != "\a" { + t.Errorf("out = %q, want bell", buf.String()) + } +} diff --git a/internal/beep/notifier.go b/internal/beep/notifier.go index c466e9c..3ef223b 100644 --- a/internal/beep/notifier.go +++ b/internal/beep/notifier.go @@ -34,6 +34,11 @@ func (n *Notifier) OnFailure(name string) { n.beep() } +// Close stops the background beep worker. It is idempotent. +func (n *Notifier) Close() { + n.beeper.Close() +} + // Toggle switches the global beep on/off and returns the new state func (n *Notifier) Toggle() bool { return n.beeper.Toggle() diff --git a/internal/beep/notifier_test.go b/internal/beep/notifier_test.go index 5a402d6..bf41268 100644 --- a/internal/beep/notifier_test.go +++ b/internal/beep/notifier_test.go @@ -7,8 +7,9 @@ import ( ) // countingNotifier returns a Notifier whose bell only increments a counter -func countingNotifier(silenced ...string) (*Notifier, *atomic.Int32) { +func countingNotifier(t testing.TB, silenced ...string) (*Notifier, *atomic.Int32) { n := NewNotifier() + t.Cleanup(n.Close) for _, name := range silenced { n.ToggleSilence(name) } @@ -18,7 +19,7 @@ func countingNotifier(silenced ...string) (*Notifier, *atomic.Int32) { } func TestNotifierSilence(t *testing.T) { - n, _ := countingNotifier("quiet") + n, _ := countingNotifier(t, "quiet") if !n.IsSilenced("quiet") || n.IsSilenced("loud") { t.Error("initial silenced state wrong") } @@ -31,7 +32,7 @@ func TestNotifierSilence(t *testing.T) { } func TestNotifierOnFailureSkipsSilenced(t *testing.T) { - n, rang := countingNotifier("quiet") + n, rang := countingNotifier(t, "quiet") n.OnFailure("quiet") if got := rang.Load(); got != 0 { t.Errorf("silenced target rang %d times, want 0", got) @@ -43,7 +44,7 @@ func TestNotifierOnFailureSkipsSilenced(t *testing.T) { } func TestNotifierToggle(t *testing.T) { - n, _ := countingNotifier() + n, _ := countingNotifier(t) if !n.Enabled() { t.Fatal("beep should be enabled by default") } @@ -56,7 +57,7 @@ func TestNotifierToggle(t *testing.T) { } func TestNotifierConcurrent(t *testing.T) { - n, _ := countingNotifier() + n, _ := countingNotifier(t) var wg sync.WaitGroup for i := 0; i < 50; i++ { wg.Add(1) diff --git a/internal/command/mping.go b/internal/command/mping.go index b3b5b32..dc852ea 100644 --- a/internal/command/mping.go +++ b/internal/command/mping.go @@ -71,6 +71,7 @@ mping dns://8.8.8.8/google.com`, // The notifier rings the bell on failures unless the host was muted // with the "m" key in the TUI. notifier := beep.NewNotifier() + defer notifier.Close() sess, err := newSession(sessionParams{ Cfg: cfg, diff --git a/internal/stats/history.go b/internal/stats/history.go index 05f5798..11e6a94 100644 --- a/internal/stats/history.go +++ b/internal/stats/history.go @@ -58,21 +58,29 @@ func (th *TargetHistory) AddEntry(entry HistoryEntry) { // insertOrdered inserts an entry that is older than the newest one at its // chronological position, dropping the oldest entry if the buffer is full. func (th *TargetHistory) insertOrdered(entry HistoryEntry) { - list := make([]HistoryEntry, 0, th.count+1) - for i := th.count - 1; i >= 0; i-- { - list = append(list, th.entries[(th.index-1-i+th.size)%th.size]) - } - // after any entries with an equal timestamp - pos := sort.Search(len(list), func(i int) bool { return list[i].Timestamp.After(entry.Timestamp) }) - list = append(list, HistoryEntry{}) - copy(list[pos+1:], list[pos:]) - list[pos] = entry - if len(list) > th.size { - list = list[len(list)-th.size:] - } - copy(th.entries, list) - th.count = len(list) - th.index = th.count % th.size + // at returns the i-th entry counting from the oldest + at := func(i int) int { return (th.index - th.count + i + th.size*2) % th.size } + // position (from the oldest) after any entries with an equal timestamp + pos := sort.Search(th.count, func(i int) bool { return th.entries[at(i)].Timestamp.After(entry.Timestamp) }) + if th.count == th.size { + // Full: drop the oldest by shifting the older part one slot back, + // then place the entry at pos-1 (an entry older than all is dropped). + if pos == 0 { + return + } + for i := 0; i < pos-1; i++ { + th.entries[at(i)] = th.entries[at(i+1)] + } + th.entries[at(pos-1)] = entry + return + } + // Not full: shift the newer part one slot forward, then insert. + for i := th.count; i > pos; i-- { + th.entries[at(i)] = th.entries[at(i-1)] + } + th.entries[at(pos)] = entry + th.count++ + th.index = (th.index + 1) % th.size } // GetRecentEntries retrieves the latest n entries (newest first) diff --git a/internal/stats/manager.go b/internal/stats/manager.go index f33cba8..b622c42 100644 --- a/internal/stats/manager.go +++ b/internal/stats/manager.go @@ -1,7 +1,8 @@ package stats import ( - "sort" + "slices" + "strings" "sync" "time" @@ -142,11 +143,16 @@ func (mm *metricsManager) Failed(host string, sentTime time.Time, msg string) { } } -func (mm *metricsManager) Sent(host string) { +// Sent counts a sent probe. Probes sent before the last reset are dropped, +// like their results, so a SENT event queued before a reset cannot inflate +// Total afterwards. +func (mm *metricsManager) Sent(host string, sentTime time.Time) { m := mm.getMetrics(host) mm.mu.Lock() - m.Sent() + if !sentTime.Before(m.resetAt) { + m.Sent() + } mm.mu.Unlock() } @@ -162,7 +168,7 @@ func (mm *metricsManager) Subscribe(res <-chan *prober.Event) <-chan struct{} { case prober.REGISTER: mm.autoRegister(r.Key, r.DisplayName, string(r.ProbeType)) case prober.SENT: - mm.Sent(r.Key) + mm.Sent(r.Key, r.SentTime) case prober.SUCCESS: mm.SuccessWithDetails(r.Key, r.Rtt, r.SentTime, r.Details) case prober.TIMEOUT: @@ -204,18 +210,13 @@ func (mm *metricsManager) SortBy(k Key, ascending bool) []Metrics { mm.mu.Lock() defer mm.mu.Unlock() now := time.Now() - keys := make([]string, 0, len(mm.metrics)) - for key := range mm.metrics { - keys = append(keys, key) + type item struct { + key string + m Metrics } - sort.Strings(keys) - // Tie-break deterministically: by display name, then by key - sort.SliceStable(keys, func(i, j int) bool { - return mm.metrics[keys[i]].Name < mm.metrics[keys[j]].Name - }) - res := make([]Metrics, 0, len(keys)) - for _, key := range keys { - res = append(res, mm.metrics[key].settledSnapshot(now)) + items := make([]item, 0, len(mm.metrics)) + for key, m := range mm.metrics { + items = append(items, item{key, m.settledSnapshot(now)}) } // less must be a strict ordering: descending order swaps the operands @@ -242,16 +243,34 @@ func (mm *metricsManager) SortBy(k Key, ascending bool) []Metrics { } return false } - sort.SliceStable(res, func(i, j int) bool { + // One sort: primary key, then display name, then key as tie-breakers + slices.SortFunc(items, func(a, b item) int { // Unmeasured RTTs (zero) always go last, whatever the direction - if zi, zj := rttFor(k, res[i]) == 0, rttFor(k, res[j]) == 0; zi != zj { - return zj + if za, zb := rttFor(k, a.m) == 0, rttFor(k, b.m) == 0; za != zb { + if zb { + return -1 + } + return 1 + } + x, y := a.m, b.m + if !ascending { + x, y = y, x } - if ascending { - return less(res[i], res[j]) + if less(x, y) { + return -1 } - return less(res[j], res[i]) + if less(y, x) { + return 1 + } + if c := strings.Compare(a.m.GetName(), b.m.GetName()); c != 0 { + return c + } + return strings.Compare(a.key, b.key) }) + res := make([]Metrics, len(items)) + for i, it := range items { + res[i] = it.m + } return res } diff --git a/internal/stats/metric.go b/internal/stats/metric.go index f590ad0..8842935 100644 --- a/internal/stats/metric.go +++ b/internal/stats/metric.go @@ -61,10 +61,12 @@ type metrics struct { func (m *metrics) Success(rtt time.Duration, sentTime time.Time) { m.Successful++ - if sentTime.After(m.LastSuccTime) { + // Newest-or-equal send time wins (same tie rule as Fail), so a late + // result of an older probe overwrites neither the time nor the RTT. + if !sentTime.Before(m.LastSuccTime) { m.LastSuccTime = sentTime + m.LastRTT = rtt } - m.LastRTT = rtt m.TotalRTT += rtt m.sumSquaredRTT += float64(rtt) * float64(rtt) m.AverageRTT = m.TotalRTT / time.Duration(m.Successful) @@ -79,7 +81,8 @@ func (m *metrics) Success(rtt time.Duration, sentTime time.Time) { func (m *metrics) Fail(sentTime time.Time, msg string) { m.Failed++ - // a late result of an older probe must not overwrite newer failure info + // Newest-or-equal send time wins (same tie rule as Success); a late + // result of an older probe must not overwrite newer failure info. if !sentTime.Before(m.LastFailTime) { m.LastFailTime = sentTime m.LastFailDetail = msg diff --git a/internal/stats/regression_test.go b/internal/stats/regression_test.go index 5714903..30eb019 100644 --- a/internal/stats/regression_test.go +++ b/internal/stats/regression_test.go @@ -1,6 +1,7 @@ package stats import ( + "slices" "testing" "time" ) @@ -8,7 +9,7 @@ import ( func TestResetDropsStaleResults(t *testing.T) { mm := NewMetricsManager().(*metricsManager) sent := time.Now().Add(-time.Second) - mm.Sent("a") + mm.Sent("a", time.Now()) time.Sleep(2 * time.Millisecond) mm.ResetAllMetrics() mm.SuccessWithDetails("a", time.Millisecond, sent, nil) @@ -120,3 +121,109 @@ func TestNewMetricsZeroHistorySize(t *testing.T) { } _ = m } + +func TestSentProcessedAfterResetIsDropped(t *testing.T) { + mm := NewMetricsManager().(*metricsManager) + sent := time.Now() + time.Sleep(2 * time.Millisecond) + mm.getMetrics("h") + mm.ResetAllMetrics() + // SENT and its result were queued before the reset, processed after it + mm.Sent("h", sent) + mm.SuccessWithDetails("h", time.Millisecond, sent, nil) + m := mm.GetMetrics("h") + if m.GetTotal() != 0 || m.GetSuccessful() != 0 || m.GetFailed() != 0 { + t.Errorf("stale SENT counted: %d/%d/%d", m.GetTotal(), m.GetSuccessful(), m.GetFailed()) + } + mm.Sent("h", time.Now()) + if mm.GetMetrics("h").GetTotal() != 1 { + t.Error("fresh SENT after reset must be counted") + } +} + +func TestLastRTTKeepsNewest(t *testing.T) { + m := newMetrics("x", 10, 0) + now := time.Now() + m.Success(5*time.Millisecond, now) + m.Success(500*time.Millisecond, now.Add(-time.Second)) + if m.LastRTT != 5*time.Millisecond { + t.Errorf("LastRTT = %v, want 5ms", m.LastRTT) + } + // equal send time: newest-or-equal wins, for success and failure alike + m.Success(7*time.Millisecond, now) + if m.LastRTT != 7*time.Millisecond { + t.Errorf("LastRTT = %v, want 7ms on tie", m.LastRTT) + } + m.Fail(now, "a") + m.Fail(now, "b") + if m.LastFailDetail != "b" { + t.Errorf("LastFailDetail = %q, want b on tie", m.LastFailDetail) + } +} + +func TestInsertOrderedNoAllocAndOrder(t *testing.T) { + for _, size := range []int{1, 2, 3, 5, 8} { + base := time.Now() + h := NewTargetHistory(size) + added := 0 + // pseudo-random out-of-order timestamps, wrapping the ring several times + for i := 0; i < 40; i++ { + ts := base.Add(time.Duration((i*7)%13) * time.Second) + h.AddEntry(HistoryEntry{Timestamp: ts}) + added++ + e := h.GetRecentEntries(size) + for j := 1; j < len(e); j++ { + if e[j].Timestamp.After(e[j-1].Timestamp) { + t.Fatalf("size %d step %d: order broken", size, i) + } + } + if want := min(added, size); len(e) != want { + t.Fatalf("size %d step %d: len %d want %d", size, i, len(e), want) + } + } + } + h := NewTargetHistory(100) + base := time.Now() + for i := 0; i < 100; i++ { + h.AddEntry(HistoryEntry{Timestamp: base.Add(time.Duration(i) * time.Second)}) + } + allocs := testing.AllocsPerRun(100, func() { + h.AddEntry(HistoryEntry{Timestamp: base.Add(50*time.Second + time.Millisecond)}) + }) + if allocs != 0 { + t.Errorf("late insert allocated %v times", allocs) + } +} + +func TestInsertOrderedFullOlderThanAll(t *testing.T) { + th := NewTargetHistory(3) + base := time.Now() + for i := 1; i <= 3; i++ { + th.AddEntry(HistoryEntry{Timestamp: base.Add(time.Duration(i) * time.Second), RTT: time.Duration(i)}) + } + th.AddEntry(HistoryEntry{Timestamp: base, RTT: 99}) // older than all: dropped + th.AddEntry(HistoryEntry{Timestamp: base.Add(1500 * time.Millisecond), RTT: 15}) + var got []time.Duration + for _, e := range th.GetRecentEntries(3) { + got = append(got, e.RTT) + } + if !slices.Equal(got, []time.Duration{3, 2, 15}) { + t.Errorf("got %v, want [3 2 15]", got) + } +} + +func TestSortByTieBreakNameThenKey(t *testing.T) { + mm := NewMetricsManager().(*metricsManager) + mm.autoRegister("k2", "b", "p2") + mm.autoRegister("k1", "b", "p1") + mm.autoRegister("k3", "a", "p3") + for _, asc := range []bool{true, false} { + var got []string + for _, r := range mm.SortBy(Sent, asc) { + got = append(got, r.GetProbeType()) + } + if !slices.Equal(got, []string{"p3", "p1", "p2"}) { + t.Errorf("asc=%v got %v", asc, got) + } + } +} From 6158697bfb9fed76edefa42daf90ac530477296b Mon Sep 17 00:00:00 2001 From: Kakuya Ando Date: Sun, 8 Nov 2026 16:27:00 +0900 Subject: [PATCH 3/3] fix(beep): bound Close wait so shutdown never hangs on a blocked terminal --- internal/beep/beep.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/internal/beep/beep.go b/internal/beep/beep.go index cb70804..adf9fc5 100644 --- a/internal/beep/beep.go +++ b/internal/beep/beep.go @@ -63,12 +63,20 @@ func (b *Beeper) Beep() { } } -// Close stops the worker goroutine and waits for it to exit. It is -// idempotent; Beep after Close is a harmless no-op. +// closeWait bounds how long Close waits for the worker to exit. +const closeWait = 200 * time.Millisecond + +// Close stops the worker goroutine and waits (up to closeWait) for it to +// exit. It is idempotent; Beep after Close is a harmless no-op. func (b *Beeper) Close() { b.init() b.closeOnce.Do(func() { close(b.stop) }) - <-b.done + // Wait briefly for the worker; if it is stuck writing to a blocked + // terminal, don't hang the caller (e.g. app shutdown) on it. + select { + case <-b.done: + case <-time.After(closeWait): + } } func (b *Beeper) worker() {