Push the new origin into the sample ring so a reset cannot underflow the totals

This commit is contained in:
flamingcow
2026-08-04 12:59:50 -07:00
parent a285b8999c
commit fb6a0d2c1b
2 changed files with 42 additions and 2 deletions
+4 -2
View File
@@ -263,11 +263,13 @@ func (d *direction) snapshot() sample {
} }
// Counters keep climbing in the workers, so resetting just moves the origin // Counters keep climbing in the workers, so resetting just moves the origin
// everything is measured from. Rates are deliberately left running, since they // everything is measured from. Rates and the rolling error window are about now
// are instantaneous and would only blink to zero and back. // rather than since the reset, so they keep running; the origin goes into the
// ring so the newest bucket never sits behind it.
func (d *direction) reset() { func (d *direction) reset() {
d.mu.Lock() d.mu.Lock()
d.base = d.capture(time.Now()) d.base = d.capture(time.Now())
d.win.push(d.base)
d.mu.Unlock() d.mu.Unlock()
d.heldFrames = heldValue{} d.heldFrames = heldValue{}
+38
View File
@@ -0,0 +1,38 @@
package main
import (
"testing"
"time"
)
// A reset re-bases from a fresh capture while the ring still holds buckets from
// just before it, so the newest bucket must not be left behind the new origin.
func TestResetDoesNotUnderflowTotals(t *testing.T) {
d := &direction{
win: newRateWindow(8),
cable: newCableStats(),
rxStats: []*rxStats{{}},
}
d.rxStats[0].frames.Store(100)
d.rxStats[0].bytes.Store(6400)
d.sample(time.Now())
d.rxStats[0].frames.Store(150)
d.rxStats[0].bytes.Store(9600)
d.reset()
v := d.displayView(time.Now())
if v.rxFrames != 0 {
t.Errorf("rxFrames = %d, want 0", v.rxFrames)
}
if v.rxGot != 0 {
t.Errorf("rxGot = %d, want 0", v.rxGot)
}
// The rolling window and the rates are about now rather than since the
// reset, so the buckets from before it have to survive.
if got := d.win.count(); got < 2 {
t.Errorf("ring holds %d buckets after reset, want the pre-reset history kept", got)
}
}