carlos / platform Public

perf: the sample ring, per-route p50/p95 and the throttled over-budget log

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev f9534f9feca9a87bc6d5462a41bca2e7c495e6bd parent 4ab578e
2 files changed, +370 −0
  • internal/perf/perf.go +210 −0
  • internal/perf/perf_test.go +160 −0
diff --git a/internal/perf/perf.go b/internal/perf/perf.go
new file mode 100644
index 000000000..eeeca55ac
--- /dev/null
+++ b/internal/perf/perf.go
@@ -0,0 +1,210 @@
+// Package perf measures the console's requests against a time budget and
+// keeps what it measured: a bounded ring of recent samples, summarised
+// per route as p50 and p95.
+//
+// The design follows Rastrillo's perf package, without its labels, cold
+// start or startup span: the console has no cold-start budget. The
+// budget is judged on time to first byte, so a download or a stream that
+// starts quickly is not a failure however long it runs, and only a read
+// (GET or HEAD) has one.
+//
+// A sample's Screen is a route pattern, never a path. A path can carry a
+// token, and an over-budget warning is a log line that outlives the
+// request.
+package perf
+
+import (
+ "log/slog"
+ "sort"
+ "sync"
+ "time"
+)
+
+// Capacity is how many samples a Recorder keeps: the most recent, in a
+// ring, so a busy process's memory is bounded by construction.
+const Capacity = 2048
+
+// DefaultBudget is the first-byte budget for a GET or HEAD.
+const DefaultBudget = 150 * time.Millisecond
+
+// Sample is one request. Times are in milliseconds.
+type Sample struct {
+ At time.Time `json:"at"`
+ Screen string `json:"screen"`
+ Method string `json:"method"`
+ Status int `json:"status"`
+ TTFB float64 `json:"ttfb_ms"`
+ Total float64 `json:"total_ms"`
+ Spans map[string]float64 `json:"spans_ms,omitempty"`
+ // Calls counts the outbound HTTP requests the request made, by span
+ // name.
+ Calls map[string]int `json:"calls,omitempty"`
+ Budget float64 `json:"budget_ms"`
+ Over bool `json:"over_budget"`
+}
+
+// Group is one screen and method's requests.
+type Group struct {
+ Screen string `json:"screen"`
+ Method string `json:"method"`
+ Requests int `json:"requests"`
+ Over int `json:"over_budget"`
+ P50 float64 `json:"p50_ms"`
+ P95 float64 `json:"p95_ms"`
+ Total95 float64 `json:"total_p95_ms"`
+ // Calls is summed over the group's samples.
+ Calls map[string]int `json:"calls,omitempty"`
+}
+
+// Recorder is the ring of recent samples. The zero value is ready; one
+// per process, shared by every request.
+type Recorder struct {
+ mu sync.Mutex
+ samples []Sample
+ next int
+
+ // background counts outbound requests made on a context no measured
+ // request owns, since the process started.
+ background map[string]int64
+
+ // Over-budget logging is throttled twice: once a minute per screen,
+ // and 120 lines a minute in all. A slow 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.
+ logWindow time.Time
+ logCount int
+ lastLog map[string]time.Time
+}
+
+// Snapshot returns the samples held, oldest first.
+func (c *Recorder) Snapshot() []Sample {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ out := make([]Sample, 0, len(c.samples))
+ if len(c.samples) == Capacity {
+ out = append(out, c.samples[c.next:]...)
+ return append(out, c.samples[:c.next]...)
+ }
+ return append(out, c.samples...)
+}
+
+// Groups summarises the samples held; see the package function.
+func (c *Recorder) Groups() []Group { return Groups(c.Snapshot()) }
+
+// Background returns how many outbound requests, by span name, were made
+// on a context no measured request owns (background passes, view-cache
+// loads), counted since the process started. It is a copy.
+func (c *Recorder) Background() map[string]int64 {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ out := make(map[string]int64, len(c.background))
+ for k, v := range c.background {
+ out[k] = v
+ }
+ return out
+}
+
+func (c *Recorder) countBackground(name string) {
+ c.mu.Lock()
+ if c.background == nil {
+ c.background = map[string]int64{}
+ }
+ c.background[name]++
+ c.mu.Unlock()
+}
+
+// Groups buckets samples by screen and method, with first-byte p50 and
+// p95 and total p95, slowest p95 first. Ties break by method, then
+// screen.
+func Groups(samples []Sample) []Group {
+ type key struct{ screen, method string }
+ buckets := map[key][]Sample{}
+ for _, s := range samples {
+ k := key{s.Screen, s.Method}
+ buckets[k] = append(buckets[k], s)
+ }
+ out := make([]Group, 0, len(buckets))
+ for k, ss := range buckets {
+ g := Group{Screen: k.screen, Method: k.method, Requests: len(ss)}
+ ttfb := make([]float64, 0, len(ss))
+ total := make([]float64, 0, len(ss))
+ for _, s := range ss {
+ if s.Over {
+ g.Over++
+ }
+ ttfb = append(ttfb, s.TTFB)
+ total = append(total, s.Total)
+ for name, n := range s.Calls {
+ if g.Calls == nil {
+ g.Calls = map[string]int{}
+ }
+ g.Calls[name] += n
+ }
+ }
+ g.P50 = percentile(ttfb, 50)
+ g.P95 = percentile(ttfb, 95)
+ g.Total95 = percentile(total, 95)
+ out = append(out, g)
+ }
+ sort.Slice(out, func(i, j int) bool {
+ a, b := out[i], out[j]
+ if a.P95 != b.P95 {
+ return a.P95 > b.P95
+ }
+ if a.Method != b.Method {
+ return a.Method < b.Method
+ }
+ return a.Screen < b.Screen
+ })
+ return out
+}
+
+// percentile is nearest-rank: the smallest value with at least p% of
+// the values at or below it. -1 for no values, so an empty group reads
+// as "no data" rather than as a suspiciously fast zero.
+func percentile(values []float64, p int) float64 {
+ if len(values) == 0 {
+ return -1
+ }
+ sort.Float64s(values)
+ return values[(len(values)*p+99)/100-1]
+}
+
+// add records s in the ring and, if it is over budget and the throttle
+// allows, logs it to log (nil logs nothing).
+func (c *Recorder) add(s Sample, log *slog.Logger) {
+ c.mu.Lock()
+ if len(c.samples) < Capacity {
+ c.samples = append(c.samples, s)
+ } else {
+ c.samples[c.next] = s
+ }
+ c.next = (c.next + 1) % Capacity
+ key := s.Method + "\x00" + s.Screen
+ emit := s.Over && (c.lastLog == nil || s.At.Sub(c.lastLog[key]) >= time.Minute)
+ if s.At.Sub(c.logWindow) >= time.Minute {
+ c.logWindow = s.At
+ c.logCount = 0
+ }
+ emit = emit && c.logCount < 120
+ if emit {
+ c.logCount++
+ 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
+ }
+ c.mu.Unlock()
+ if emit && log != nil {
+ log.Warn("request over performance budget",
+ "screen", s.Screen, "method", s.Method, "status", s.Status,
+ "ttfb_ms", s.TTFB, "total_ms", s.Total, "budget_ms", s.Budget, "spans_ms", s.Spans)
+ }
+}
diff --git a/internal/perf/perf_test.go b/internal/perf/perf_test.go
new file mode 100644
index 000000000..abb6e21be
--- /dev/null
+++ b/internal/perf/perf_test.go
@@ -0,0 +1,160 @@
+// These are unit tests, not acceptance: they exercise the ring, the
+// grouping and the log throttle directly. The console's behaviour under
+// the real server is covered by the tests that build it with NewServer.
+package perf
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "sync"
+ "testing"
+ "time"
+)
+
+func TestRingKeepsTheLast2048(t *testing.T) {
+ var r Recorder
+ for i := 0; i < 2050; i++ {
+ r.add(Sample{Screen: "GET /x", Method: "GET", TTFB: float64(i)}, nil)
+ }
+ got := r.Snapshot()
+ if len(got) != Capacity {
+ t.Fatalf("len = %d, want %d", len(got), Capacity)
+ }
+ if got[0].TTFB != 2 || got[len(got)-1].TTFB != 2049 {
+ t.Fatalf("first %v last %v, want 2 and 2049", got[0].TTFB, got[len(got)-1].TTFB)
+ }
+}
+
+func TestGroupsPercentilesNearestRank(t *testing.T) {
+ var ss []Sample
+ for i := 1; i <= 100; i++ {
+ ss = append(ss, Sample{Screen: "GET /x", Method: "GET", TTFB: float64(i), Total: float64(i), Over: i == 100})
+ }
+ gs := Groups(ss)
+ if len(gs) != 1 {
+ t.Fatalf("groups = %d, want 1", len(gs))
+ }
+ g := gs[0]
+ if g.Requests != 100 || g.P50 != 50 || g.P95 != 95 || g.Over != 1 {
+ t.Fatalf("got %+v, want 100 requests, p50 50, p95 95, 1 over", g)
+ }
+}
+
+func TestGroupsSlowestFirst(t *testing.T) {
+ gs := Groups([]Sample{
+ {Screen: "GET /a", Method: "GET", TTFB: 10},
+ {Screen: "GET /b", Method: "GET", TTFB: 90},
+ })
+ if len(gs) != 2 || gs[0].Screen != "GET /b" || gs[1].Screen != "GET /a" {
+ t.Fatalf("got %+v, want [B, A]", gs)
+ }
+}
+
+func TestGroupsSplitByMethod(t *testing.T) {
+ gs := Groups([]Sample{
+ {Screen: "/x", Method: "GET", TTFB: 1},
+ {Screen: "/x", Method: "POST", TTFB: 1},
+ })
+ if len(gs) != 2 {
+ t.Fatalf("groups = %d, want 2", len(gs))
+ }
+ if gs[0].Method != "GET" || gs[1].Method != "POST" {
+ t.Fatalf("ties should order by method: %+v", gs)
+ }
+}
+
+func TestGroupsSumCalls(t *testing.T) {
+ gs := Groups([]Sample{
+ {Screen: "GET /x", Method: "GET", Calls: map[string]int{"s3": 3}},
+ {Screen: "GET /x", Method: "GET", Calls: map[string]int{"s3": 2, "box": 1}},
+ })
+ if len(gs) != 1 || gs[0].Calls["s3"] != 5 || gs[0].Calls["box"] != 1 {
+ t.Fatalf("got %+v, want s3 5 and box 1", gs)
+ }
+}
+
+func TestPercentileEmpty(t *testing.T) {
+ if got := percentile(nil, 95); got != -1 {
+ t.Fatalf("percentile(nil) = %v, want -1", got)
+ }
+}
+
+// countHandler counts the records it is handed.
+type countHandler struct {
+ mu sync.Mutex
+ n int
+}
+
+func (h *countHandler) Enabled(context.Context, slog.Level) bool { return true }
+func (h *countHandler) Handle(context.Context, slog.Record) error {
+ h.mu.Lock()
+ h.n++
+ h.mu.Unlock()
+ return nil
+}
+func (h *countHandler) WithAttrs([]slog.Attr) slog.Handler { return h }
+func (h *countHandler) WithGroup(string) slog.Handler { return h }
+func (h *countHandler) count() int {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.n
+}
+
+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)
+ for _, d := range []time.Duration{0, 30 * time.Second, 61 * time.Second} {
+ r.add(Sample{At: t0.Add(d), Screen: "GET /x", Method: "GET", Over: true}, log)
+ }
+ if got := h.count(); got != 2 {
+ t.Fatalf("records = %d, want 2 (once a minute per screen)", got)
+ }
+
+ // 200 distinct screens inside one minute, well after the first window.
+ 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)
+ }
+ if got := h.count() - before; got > 120 || got == 0 {
+ t.Fatalf("records in one minute = %d, want 1..120", got)
+ }
+}
+
+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 {
+ t.Fatalf("zero value Background = %v, want empty", got)
+ }
+ for i := 0; i < 3; i++ {
+ r.countBackground("s3")
+ }
+ got := r.Background()
+ if got["s3"] != 3 {
+ t.Fatalf("Background()[s3] = %d, want 3", got["s3"])
+ }
+ got["s3"] = 99
+ got["x"] = 1
+ again := r.Background()
+ if again["s3"] != 3 || len(again) != 1 {
+ t.Fatalf("mutating the copy changed the recorder: %v", again)
+ }
+}