carlos / platform Public

perf: detached calls after the request count as background; the log throttle runs in warning time

A call made on a finished request's context (work detached with
context.WithoutCancel keeps the measuring writer) was dropped from the
sample and from the background counts alike. The writer now accepts or
refuses the count under the lock finish hands the sample over under; a
refused call is background. Recorded samples stay as they were.

The over-budget throttle keyed both limits on Sample.At, when the
request began. Stalled requests finish late and out of order, so two
warnings a second apart could both pass. The allowance is now reserved
with a time read from the recorder's clock under its lock; At stays as
metadata.

The recorder's clock is settable from tests, so the first-byte test
moves time by hand instead of trusting a 20 ms scheduler window, and the
103 test records the statuses forwarded underneath.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 9c11f55beb1e2e8fb1d936b96f4d717170a7d20c parent 2ba5184
5 files changed, +341 −76
  • internal/perf/export_test.go +7 −0
  • internal/perf/middleware.go +29 −15
  • internal/perf/middleware_test.go +135 −17
  • internal/perf/perf.go +47 −25
  • internal/perf/perf_test.go +123 −19
diff --git a/internal/perf/export_test.go b/internal/perf/export_test.go
new file mode 100644
index 000000000..17668baa9
--- /dev/null
+++ b/internal/perf/export_test.go
@@ -0,0 +1,7 @@
+package perf
+
+import "time"
+
+// SetClock makes c read the time from clock, for the middleware's own
+// first-byte, total and span times and for the log throttle. Tests only.
+func SetClock(c *Recorder, clock func() time.Time) { c.clock = clock }
diff --git a/internal/perf/middleware.go b/internal/perf/middleware.go
index b284aae41..5faf600d5 100644
--- a/internal/perf/middleware.go
+++ b/internal/perf/middleware.go
@@ -120,11 +120,12 @@ type writer struct {
}
func begin(c *Recorder, w http.ResponseWriter, r *http.Request, opts *Options) (*writer, *http.Request) {
- s := Sample{At: time.Now().UTC(), Method: method(r.Method)}
+ start := c.now()
+ s := Sample{At: start.UTC(), Method: method(r.Method)}
if r.Method == http.MethodGet || r.Method == http.MethodHead {
s.Budget = ms(opts.Budget)
}
- q := &writer{ResponseWriter: w, recorder: c, opts: opts, start: time.Now(), sample: s}
+ q := &writer{ResponseWriter: w, recorder: c, opts: opts, start: start, sample: s}
r2 := r.WithContext(context.WithValue(r.Context(), contextKey{}, q))
// A mux outside this one may already have set Pattern. Cleared on
// this copy, so the pattern read back is the inner mux's or
@@ -180,11 +181,11 @@ func SpanFor(w http.ResponseWriter, name string) func() {
// span starts a span and returns its end, which adds the elapsed time
// once however often it is called.
func (q *writer) span(name string) func() {
- start := time.Now()
+ start := q.recorder.now()
var once sync.Once
return func() {
once.Do(func() {
- d := ms(time.Since(start))
+ d := ms(q.since(start))
q.mu.Lock()
defer q.mu.Unlock()
if q.done {
@@ -198,17 +199,27 @@ func (q *writer) span(name string) func() {
}
}
-// call counts one outbound request named name.
-func (q *writer) call(name string) {
+// since is the time from t to now on the recorder's clock.
+func (q *writer) since(t time.Time) time.Duration { return q.recorder.now().Sub(t) }
+
+// call counts one outbound request named name on the request, and
+// reports whether it did. It does not once the sample has been handed
+// to the recorder: the call is then the request's detached work, not
+// the request, and the caller counts it as background. The check and
+// the count are one step under q.mu, the lock finish hands the sample
+// over under, so a call is counted exactly once, in one place or the
+// other.
+func (q *writer) call(name string) bool {
q.mu.Lock()
defer q.mu.Unlock()
if q.done {
- return
+ return false
}
if q.sample.Calls == nil {
q.sample.Calls = map[string]int{}
}
q.sample.Calls[name]++
+ return true
}
func (q *writer) WriteHeader(status int) {
@@ -233,7 +244,7 @@ func (q *writer) commit(status int) bool {
}
q.committed = true
q.sample.Status = status
- q.sample.TTFB = ms(time.Since(q.start))
+ q.sample.TTFB = ms(q.since(q.start))
names := make([]string, 0, len(q.sample.Spans))
for name := range q.sample.Spans {
names = append(names, name)
@@ -275,7 +286,7 @@ func (q *writer) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if !q.committed {
q.committed = true
q.sample.Status = http.StatusSwitchingProtocols
- q.sample.TTFB = ms(time.Since(q.start))
+ q.sample.TTFB = ms(q.since(q.start))
}
q.mu.Unlock()
}
@@ -297,7 +308,7 @@ func (q *writer) finish(r *http.Request, screenIsDefault bool, lostRoute *sync.O
q.sample.Status = http.StatusInternalServerError
if !committed {
q.committed = true
- q.sample.TTFB = ms(time.Since(q.start))
+ q.sample.TTFB = ms(q.since(q.start))
}
}
q.mu.Unlock()
@@ -315,7 +326,7 @@ func (q *writer) finish(r *http.Request, screenIsDefault bool, lostRoute *sync.O
// once, rather than let the numbers mislead quietly.
lost := screenIsDefault && r.Pattern == "" &&
q.sample.Status != http.StatusNotFound && q.sample.Status != http.StatusMethodNotAllowed
- q.sample.Total = ms(time.Since(q.start))
+ q.sample.Total = ms(q.since(q.start))
q.sample.Over = q.sample.Budget > 0 && q.sample.TTFB > q.sample.Budget
// Handed over once. From here the sample is the recorder's (add
// keeps its own copy of the maps), and done turns every later span
@@ -344,8 +355,12 @@ type Doer interface {
// TimeDoer wraps d so that each Do is one span named name and one count
// in Calls[name] on the measured request the outgoing request's context
// belongs to. On a context no measured request owns it counts into c's
-// background counts instead (a nil c drops the count). Counting is at
-// the HTTP boundary, so every page of a paginated listing is one count.
+// background counts instead (a nil c drops the count). So does a call
+// made on a measured request's context after that request finished,
+// by work it detached (context.WithoutCancel keeps the request's
+// values): the recorded sample never changes, and the call is still
+// counted somewhere. Counting is at the HTTP boundary, so every page of
+// a paginated listing is one count.
//
// The span stays open until the response body reaches EOF or is closed,
// whichever comes first, so a prompt header followed by a slow body is
@@ -366,13 +381,12 @@ type timedDoer struct {
func (t *timedDoer) Do(req *http.Request) (*http.Response, error) {
q := fromContext(req.Context())
- if q == nil {
+ if q == nil || !q.call(t.name) {
if t.c != nil {
t.c.countBackground(t.name)
}
return t.d.Do(req)
}
- q.call(t.name)
end := q.span(t.name)
resp, err := t.d.Do(req)
if err != nil || resp == nil || resp.Body == nil || resp.Body == http.NoBody {
diff --git a/internal/perf/middleware_test.go b/internal/perf/middleware_test.go
index 761784a7c..6e9d69bc1 100644
--- a/internal/perf/middleware_test.go
+++ b/internal/perf/middleware_test.go
@@ -321,39 +321,127 @@ func TestTimeDoerCountsBackgroundCalls(t *testing.T) {
resp.Body.Close()
}
-// TestOverBudgetIsJudgedOnFirstByte: not acceptance.
+// answering is a Doer that answers every call at once with a short body.
+type answering struct{}
+
+func (answering) Do(*http.Request) (*http.Response, error) {
+ return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("pong"))}, nil
+}
+
+// TestTimeDoerDetachedCallAfterTheRequestIsBackground: not acceptance.
+// Work a handler detaches with context.WithoutCancel keeps the
+// request's values, the measuring writer among them. A call it makes
+// after the request was recorded is background work: counted there, and
+// the recorded sample left as it was. It used to be dropped from both.
+func TestTimeDoerDetachedCallAfterTheRequestIsBackground(t *testing.T) {
+ var c perf.Recorder
+ release := make(chan struct{})
+ done := make(chan struct{})
+ mux := http.NewServeMux()
+ mux.HandleFunc("POST /job", func(w http.ResponseWriter, r *http.Request) {
+ d := perf.TimeDoer(answering{}, "s3", &c)
+ call := func(ctx context.Context) {
+ req, _ := http.NewRequestWithContext(ctx, "GET", "http://store.example.com/k", nil)
+ resp, err := d.Do(req)
+ if err != nil {
+ t.Errorf("Do: %v", err)
+ return
+ }
+ io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ }
+ call(r.Context()) // the request's own call
+ ctx := context.WithoutCancel(r.Context())
+ go func() {
+ defer close(done)
+ <-release
+ call(ctx)
+ }()
+ w.WriteHeader(http.StatusAccepted)
+ })
+ _, before := serve(t, &c, perf.Options{}, mux, "POST", "/job")
+ if s := only(t, before); s.Calls["s3"] != 1 {
+ t.Fatalf("calls = %v, want the request's own s3 call", s.Calls)
+ }
+ if bg := c.Background(); len(bg) != 0 {
+ t.Fatalf("background before the detached call = %v, want none", bg)
+ }
+ close(release)
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the detached call never finished")
+ }
+ if got := c.Background()["s3"]; got != 1 {
+ t.Fatalf("background s3 = %d, want 1 (the detached call after the request finished)", got)
+ }
+ if after := c.Snapshot(); !reflect.DeepEqual(before, after) {
+ t.Fatalf("recorded sample changed:\nbefore %+v\nafter %+v", before, after)
+ }
+}
+
+// manualClock is a time source the test moves by hand, so a timing
+// assertion does not depend on how promptly the scheduler runs.
+type manualClock struct {
+ mu sync.Mutex
+ t time.Time
+}
+
+func newManualClock() *manualClock {
+ return &manualClock{t: time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)}
+}
+
+func (m *manualClock) now() time.Time {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.t
+}
+
+func (m *manualClock) advance(d time.Duration) {
+ m.mu.Lock()
+ m.t = m.t.Add(d)
+ m.mu.Unlock()
+}
+
+// TestOverBudgetIsJudgedOnFirstByte: not acceptance. The clock is moved
+// by hand inside the handlers, so the first-byte and total times are
+// exact and nothing waits on a real sleep.
func TestOverBudgetIsJudgedOnFirstByte(t *testing.T) {
+ clk := newManualClock()
opts := perf.Options{Budget: 20 * time.Millisecond}
mux := http.NewServeMux()
mux.HandleFunc("GET /stream", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "first")
w.(http.Flusher).Flush()
- time.Sleep(50 * time.Millisecond)
+ clk.advance(50 * time.Millisecond)
io.WriteString(w, "rest")
})
mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
- time.Sleep(50 * time.Millisecond)
+ clk.advance(50 * time.Millisecond)
io.WriteString(w, "late")
})
mux.HandleFunc("POST /slow", func(w http.ResponseWriter, r *http.Request) {
- time.Sleep(50 * time.Millisecond)
+ clk.advance(50 * time.Millisecond)
io.WriteString(w, "late")
})
var a perf.Recorder
+ perf.SetClock(&a, clk.now)
_, ss := serve(t, &a, opts, mux, "GET", "/stream")
- if s := only(t, ss); s.Over || s.Budget != 20 || s.Total < 50 {
- t.Fatalf("stream sample = %+v, want not over, budget 20, total at least 50", s)
+ if s := only(t, ss); s.Over || s.Budget != 20 || s.TTFB != 0 || s.Total != 50 {
+ t.Fatalf("stream sample = %+v, want not over, budget 20, ttfb 0, total 50", s)
}
var b perf.Recorder
+ perf.SetClock(&b, clk.now)
_, ss = serve(t, &b, opts, mux, "GET", "/slow")
- if s := only(t, ss); !s.Over || s.TTFB < 50 {
- t.Fatalf("slow GET sample = %+v, want over with ttfb at least 50", s)
+ if s := only(t, ss); !s.Over || s.TTFB != 50 {
+ t.Fatalf("slow GET sample = %+v, want over with ttfb 50", s)
}
var p perf.Recorder
+ perf.SetClock(&p, clk.now)
_, ss = serve(t, &p, opts, mux, "POST", "/slow")
- if s := only(t, ss); s.Over || s.Budget != 0 {
- t.Fatalf("POST sample = %+v, want not over and budget 0", s)
+ if s := only(t, ss); s.Over || s.Budget != 0 || s.TTFB != 50 {
+ t.Fatalf("POST sample = %+v, want ttfb 50, not over and budget 0", s)
}
}
@@ -597,22 +685,52 @@ func TestSpanAfterFirstByteCountsButMissesTheHeader(t *testing.T) {
}
}
-// TestInformationalHeadersPassThrough: not acceptance. A 103 goes out
-// without committing; the real status and Server-Timing follow.
+// statusLog is a ResponseWriter that records every WriteHeader it is
+// handed and the Server-Timing header at that moment.
+type statusLog struct {
+ header http.Header
+ statuses []int
+ timing []string
+}
+
+func (l *statusLog) Header() http.Header { return l.header }
+func (l *statusLog) Write(b []byte) (int, error) {
+ if len(l.statuses) == 0 {
+ l.WriteHeader(http.StatusOK)
+ }
+ return len(b), nil
+}
+func (l *statusLog) WriteHeader(code int) {
+ l.statuses = append(l.statuses, code)
+ l.timing = append(l.timing, l.header.Get("Server-Timing"))
+}
+
+// TestInformationalHeadersPassThrough: not acceptance. A 103 is
+// forwarded to the writer underneath without committing: no
+// Server-Timing goes with it, and the real status, with Server-Timing,
+// follows.
func TestInformationalHeadersPassThrough(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Link", "</style.css>; rel=preload")
w.WriteHeader(http.StatusEarlyHints)
perf.Span(r, "db")()
w.WriteHeader(http.StatusAccepted)
})
var c perf.Recorder
- rec, ss := serve(t, &c, perf.Options{}, mux, "GET", "/x")
- if s := only(t, ss); s.Status != http.StatusAccepted {
- t.Fatalf("status = %d, want 202", s.Status)
+ out := &statusLog{header: http.Header{}}
+ perf.Middleware(&c, perf.Options{Logger: quiet})(mux).ServeHTTP(out, httptest.NewRequest("GET", "/x", nil))
+ if !reflect.DeepEqual(out.statuses, []int{http.StatusEarlyHints, http.StatusAccepted}) {
+ t.Fatalf("statuses forwarded = %v, want [103 202]", out.statuses)
+ }
+ if out.timing[0] != "" {
+ t.Fatalf("Server-Timing went with the 103: %q", out.timing[0])
}
- if _, n := metric(t, rec.Header().Get("Server-Timing"), "db"); n != 1 {
- t.Fatalf("Server-Timing = %q, want db (the 103 did not commit)", rec.Header().Get("Server-Timing"))
+ if _, n := metric(t, out.timing[1], "db"); n != 1 {
+ t.Fatalf("Server-Timing with the 202 = %q, want db (the 103 did not commit)", out.timing[1])
+ }
+ if s := only(t, c.Snapshot()); s.Status != http.StatusAccepted {
+ t.Fatalf("status = %d, want 202", s.Status)
}
}
diff --git a/internal/perf/perf.go b/internal/perf/perf.go
index d9e578cdc..100963cbe 100644
--- a/internal/perf/perf.go
+++ b/internal/perf/perf.go
@@ -74,8 +74,24 @@ type Recorder struct {
// dependency makes every page slow at once, and the log is where
// someone goes to find out why, so it must not be the thing that
// drowns.
+ //
+ // Both are kept in warning time, read from the clock under mu as
+ // the allowance is reserved, never in a sample's At: At is when the
+ // request began, and requests that stall finish late and out of
+ // order, exactly when the limit matters.
logged []time.Time
lastLog map[string]time.Time
+
+ // clock is the time source; nil is time.Now. Tests set it.
+ clock func() time.Time
+}
+
+// now reads c's clock. A nil Recorder reads time.Now.
+func (c *Recorder) now() time.Time {
+ if c == nil || c.clock == nil {
+ return time.Now()
+ }
+ return c.clock()
}
// Snapshot returns the samples held, oldest first.
@@ -213,31 +229,7 @@ func (c *Recorder) add(s Sample, log *slog.Logger) {
c.samples[c.next] = stored
}
c.next = (c.next + 1) % Capacity
- key := s.Method + "\x00" + s.Screen
- emit := s.Over
- if last, ok := c.lastLog[key]; ok && s.At.Sub(last) < time.Minute {
- emit = false
- }
- if emit && len(c.logged) >= maxLogsPerMinute && s.At.Sub(c.logged[len(c.logged)-maxLogsPerMinute]) < time.Minute {
- emit = false
- }
- if emit {
- c.logged = append(c.logged, s.At)
- if len(c.logged) >= 2*maxLogsPerMinute {
- c.logged = append(c.logged[:0], c.logged[len(c.logged)-maxLogsPerMinute:]...)
- }
- if len(c.lastLog) >= Capacity {
- for k, at := range c.lastLog {
- if s.At.Sub(at) >= time.Minute {
- delete(c.lastLog, k)
- }
- }
- }
- if c.lastLog == nil {
- c.lastLog = map[string]time.Time{}
- }
- c.lastLog[key] = s.At
- }
+ emit := s.Over && c.reserveLog(s.Method+"\x00"+s.Screen)
c.mu.Unlock()
if emit && log != nil {
log.Warn("request over performance budget",
@@ -245,3 +237,33 @@ func (c *Recorder) add(s Sample, log *slog.Logger) {
"ttfb_ms", s.TTFB, "total_ms", s.Total, "budget_ms", s.Budget, "spans_ms", s.Spans)
}
}
+
+// reserveLog reports whether an over-budget warning for key may be
+// written now, and if so takes the allowance. The time is read here,
+// under c.mu, so the reservations are in the order they are made and
+// each is stamped with when its warning goes out.
+func (c *Recorder) reserveLog(key string) bool {
+ now := c.now()
+ if last, ok := c.lastLog[key]; ok && now.Sub(last) < time.Minute {
+ return false
+ }
+ if len(c.logged) >= maxLogsPerMinute && now.Sub(c.logged[len(c.logged)-maxLogsPerMinute]) < time.Minute {
+ return false
+ }
+ c.logged = append(c.logged, now)
+ if len(c.logged) >= 2*maxLogsPerMinute {
+ c.logged = append(c.logged[:0], c.logged[len(c.logged)-maxLogsPerMinute:]...)
+ }
+ if len(c.lastLog) >= Capacity {
+ for k, at := range c.lastLog {
+ if now.Sub(at) >= time.Minute {
+ delete(c.lastLog, k)
+ }
+ }
+ }
+ if c.lastLog == nil {
+ c.lastLog = map[string]time.Time{}
+ }
+ c.lastLog[key] = now
+ return true
+}
diff --git a/internal/perf/perf_test.go b/internal/perf/perf_test.go
index 0cf01efbb..e371748b7 100644
--- a/internal/perf/perf_test.go
+++ b/internal/perf/perf_test.go
@@ -101,12 +101,37 @@ func (h *countHandler) count() int {
return h.n
}
+// fakeClock is a time source the test moves by hand.
+type fakeClock struct {
+ mu sync.Mutex
+ t time.Time
+}
+
+func (f *fakeClock) now() time.Time {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.t
+}
+
+func (f *fakeClock) set(t time.Time) {
+ f.mu.Lock()
+ f.t = t
+ f.mu.Unlock()
+}
+
+// clocked returns a Recorder reading clk, and clk, starting at t0.
+func clocked(t0 time.Time) (*Recorder, *fakeClock) {
+ clk := &fakeClock{t: t0}
+ return &Recorder{clock: clk.now}, clk
+}
+
func TestOverBudgetLogIsThrottled(t *testing.T) {
h := &countHandler{}
log := slog.New(h)
- var r Recorder
t0 := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)
+ r, clk := clocked(t0)
for _, d := range []time.Duration{0, 30 * time.Second, 61 * time.Second} {
+ clk.set(t0.Add(d))
r.add(Sample{At: t0.Add(d), Screen: "GET /x", Method: "GET", Over: true}, log)
}
if got := h.count(); got != 2 {
@@ -117,10 +142,9 @@ func TestOverBudgetLogIsThrottled(t *testing.T) {
t1 := t0.Add(10 * time.Minute)
before := h.count()
for i := 0; i < 200; i++ {
- r.add(Sample{
- At: t1.Add(time.Duration(i) * 200 * time.Millisecond),
- Screen: fmt.Sprintf("GET /s%d", i), Method: "GET", Over: true,
- }, log)
+ at := t1.Add(time.Duration(i) * 200 * time.Millisecond)
+ clk.set(at)
+ r.add(Sample{At: at, Screen: fmt.Sprintf("GET /s%d", i), Method: "GET", Over: true}, log)
}
if got := h.count() - before; got > 120 || got == 0 {
t.Fatalf("records in one minute = %d, want 1..120", got)
@@ -133,11 +157,12 @@ func TestOverBudgetLogIsThrottled(t *testing.T) {
func TestOverBudgetLogBoundaryBurst(t *testing.T) {
h := &countHandler{}
log := slog.New(h)
- var r Recorder
t0 := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)
+ r, clk := clocked(t0)
// An under-budget sample starts the clock.
r.add(Sample{At: t0, Screen: "GET /ok", Method: "GET"}, log)
burst := func(at time.Time, prefix string) int {
+ clk.set(at)
before := h.count()
for i := 0; i < 120; i++ {
r.add(Sample{At: at, Screen: fmt.Sprintf("GET /%s%d", prefix, i), Method: "GET", Over: true}, log)
@@ -161,9 +186,10 @@ func TestOverBudgetLogBoundaryBurst(t *testing.T) {
func TestOverBudgetLogPerRouteRolls(t *testing.T) {
h := &countHandler{}
log := slog.New(h)
- var r Recorder
t0 := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)
+ r, clk := clocked(t0)
for _, d := range []time.Duration{0, 59 * time.Second, 60 * time.Second, 119 * time.Second, 120 * time.Second} {
+ clk.set(t0.Add(d))
r.add(Sample{At: t0.Add(d), Screen: "GET /x", Method: "GET", Over: true}, log)
}
if got := h.count(); got != 3 {
@@ -171,6 +197,96 @@ func TestOverBudgetLogPerRouteRolls(t *testing.T) {
}
}
+// The throttle counts warnings by when they are written, not by when
+// their requests began. A request that stalls starts early and finishes
+// late, and concurrent ones finish out of the order they started in:
+// keyed on Sample.At, two slow requests that began 61 s apart but
+// finished 1 s apart both logged, and a later-starting burst slipped
+// past the minute's 120. The samples keep their At either way.
+func TestOverBudgetLogThrottleUsesWarningTime(t *testing.T) {
+ t0 := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)
+
+ t.Run("per route, delayed", func(t *testing.T) {
+ h := &countHandler{}
+ log := slog.New(h)
+ r, clk := clocked(t0)
+ // Began at 0 s and 61 s; finished at 62 s and 63 s.
+ clk.set(t0.Add(62 * time.Second))
+ r.add(Sample{At: t0, Screen: "GET /x", Method: "GET", Over: true}, log)
+ clk.set(t0.Add(63 * time.Second))
+ r.add(Sample{At: t0.Add(61 * time.Second), Screen: "GET /x", Method: "GET", Over: true}, log)
+ if got := h.count(); got != 1 {
+ t.Fatalf("records = %d, want 1 (two warnings 1 s apart)", got)
+ }
+ // A minute after the logged one, the route may log again,
+ // whenever its request began.
+ clk.set(t0.Add(122 * time.Second))
+ r.add(Sample{At: t0.Add(5 * time.Second), Screen: "GET /x", Method: "GET", Over: true}, log)
+ if got := h.count(); got != 2 {
+ t.Fatalf("records = %d, want 2", got)
+ }
+ if ss := r.Snapshot(); ss[0].At != t0 || ss[1].At != t0.Add(61*time.Second) || ss[2].At != t0.Add(5*time.Second) {
+ t.Fatalf("samples' At changed: %v %v %v", ss[0].At, ss[1].At, ss[2].At)
+ }
+ })
+
+ t.Run("per route, out of order", func(t *testing.T) {
+ h := &countHandler{}
+ log := slog.New(h)
+ r, clk := clocked(t0)
+ // The later-starting request finishes first.
+ clk.set(t0.Add(62 * time.Second))
+ r.add(Sample{At: t0.Add(61 * time.Second), Screen: "GET /x", Method: "GET", Over: true}, log)
+ clk.set(t0.Add(63 * time.Second))
+ r.add(Sample{At: t0, Screen: "GET /x", Method: "GET", Over: true}, log)
+ if got := h.count(); got != 1 {
+ t.Fatalf("records = %d, want 1", got)
+ }
+ })
+
+ t.Run("aggregate, out of order", func(t *testing.T) {
+ h := &countHandler{}
+ log := slog.New(h)
+ r, clk := clocked(t0)
+ burst := func(warnAt time.Time, began func(i int) time.Time, prefix string) int {
+ clk.set(warnAt)
+ before := h.count()
+ for i := 0; i < 120; i++ {
+ r.add(Sample{At: began(i), Screen: fmt.Sprintf("GET /%s%d", prefix, i), Method: "GET", Over: true}, log)
+ }
+ return h.count() - before
+ }
+ // 120 routes finish together at 200 s, having begun in reverse
+ // order, from 120 s back to 1 s.
+ if got := burst(t0.Add(200*time.Second), func(i int) time.Time { return t0.Add(time.Duration(120-i) * time.Second) }, "a"); got != 120 {
+ t.Fatalf("first burst logged %d, want 120", got)
+ }
+ // 120 more finish a second later; they began after the first
+ // burst's oldest start by more than a minute.
+ if got := burst(t0.Add(201*time.Second), func(i int) time.Time { return t0.Add(300 * time.Second) }, "b"); got != 0 {
+ t.Fatalf("second burst, 1 s of warning time later, logged %d, want 0", got)
+ }
+ // A minute of warning time after the first burst, the
+ // allowance is back.
+ if got := burst(t0.Add(260*time.Second), func(i int) time.Time { return t0 }, "c"); got != 120 {
+ t.Fatalf("burst a minute later logged %d, want 120", got)
+ }
+ })
+}
+
+func TestUnderBudgetNeverLogs(t *testing.T) {
+ h := &countHandler{}
+ t0 := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)
+ r, clk := clocked(t0)
+ for i := 0; i < 10; i++ {
+ clk.set(t0.Add(time.Duration(i) * time.Hour))
+ r.add(Sample{At: t0.Add(time.Duration(i) * time.Hour), Screen: "GET /x", Method: "GET", Over: false}, slog.New(h))
+ }
+ if got := h.count(); got != 0 {
+ t.Fatalf("records = %d, want 0", got)
+ }
+}
+
func TestSnapshotIsADeepCopy(t *testing.T) {
var r Recorder
in := Sample{Screen: "GET /x", Method: "GET", Spans: map[string]float64{"db": 1}, Calls: map[string]int{"s3": 2}}
@@ -199,18 +315,6 @@ func TestSnapshotIsADeepCopy(t *testing.T) {
}
}
-func TestUnderBudgetNeverLogs(t *testing.T) {
- h := &countHandler{}
- var r Recorder
- t0 := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)
- for i := 0; i < 10; i++ {
- r.add(Sample{At: t0.Add(time.Duration(i) * time.Hour), Screen: "GET /x", Method: "GET", Over: false}, slog.New(h))
- }
- if got := h.count(); got != 0 {
- t.Fatalf("records = %d, want 0", got)
- }
-}
-
func TestBackgroundCountsAccumulate(t *testing.T) {
var r Recorder
if got := r.Background(); len(got) != 0 {