Files
Pulse/internal/api/http_metrics_allocations_test.go
rcourtman 3d322ff3a8 Stop timing the route normaliser rows that flip with layout
The advisory Benchmarks check failed #2884 on NormalizeRoute/with_uuid
alone, +12.25% (p=0.000), though that PR changed only AI handler code.
It was not the only one. Since the bounded route scanner landed on
9 October (01788459f1), normalizeRoute takes 30-180ns a path on CI runners. In 72
paired CI comparisons that measured internal/api from then until 13
October, the BenchmarkNormalizeRoute rows and their parallel variant
failed the gate 17 times. None of those PRs touched route code, and 6
of the 17 failures did not involve with_uuid: deep_path_truncated,
with_query_params, metrics_history, with_numeric_id and Parallel each
crossed 10% too. with_uuid moved past 10% in 21 of the 72 comparisons,
in both directions.

This is the same layout effect that retired the "/" fast path (#2255)
and NormalizeSegment (#2258). Go aligns functions to 32 bytes, so code
added earlier in the package moves normalizeRoute between the halves of
a 64-byte block. That changes its loops by a cycle per iteration. Every
path shares those loops, so retiring with_uuid alone would leave the
other rows failing. Summed over all six paths, a mixed-path row would
still have moved up to 10%.

BenchmarkNormalizeRoute and BenchmarkNormalizeRoute_Parallel are
removed. Their allocation columns never varied, and they are now pinned
by TestNormalizeRoute_LabelAllocationProfile. For each former path it
requires exactly one allocation, of the same size as a fresh copy of the
label. It runs in the existing isolated child process and takes the
lowest of three windows, so one stray runtime allocation cannot fail it.
BenchmarkFullMiddlewarePath still times the normaliser inside the
request path, with a CI maximum of +8.4% over those 72 runs, and
BenchmarkNormalizeRoute_DiscardedSuffix still times a long discarded
suffix. Gross classification slowdowns are left to those rows: a
doubled UUID scan has no deterministic signal, and the retired row
could not separate one from layout.

Proofs, on pulse-dev with the CI runner narrowed to ./internal/api/ at
30 samples. The probe is an unrelated init-time function in a file
sorted before http_metrics.go. It moves normalizeRoute from 32 to 0 mod
64 in the test binary without changing its size:

- old tree vs old tree plus probe: with_uuid -14.70% (p=0.001). Read the
  other way, as a PR that removes the probe, the gate exits 1 on
  NormalizeRoute/with_uuid alone, +17.23% (p=0.001). That is #2884's
  shape.
- new tree vs new tree plus probe: gate exits 0 in both directions. On
  a first run under load 9-15, three millisecond-scale rows that run no
  route code flagged at p=0.025-0.046 with spreads of 15-38%. The
  repeat came back clean in both directions.
- mutation controls on the final test: sizing the label buffer at twice
  the label fails only the new test. The existing at-most-one-allocation
  test passes it. Joining the label through an intermediate fails both.
- the route tests pass 20 times plain and 10 times under -race.
2026-10-13 10:25:33 +01:00

126 lines
3.6 KiB
Go

package api
import (
"context"
"flag"
"os"
"os/exec"
"regexp"
"strings"
"sync/atomic"
"testing"
"time"
)
var routeAllocationChild = flag.Bool("test.routeAllocationChild", false, "measure route allocations in an isolated test process")
// AllocsPerRun reads process-wide MemStats, even with GOMAXPROCS=1. Router,
// alert and monitoring fixtures may have background workers in this package;
// their allocations must not be attributed to a constant-return fast path.
// Reuse the actual test binary (including race instrumentation), but select
// only the requested measurement. No allocation floor, retries or skips.
func isolatedRouteAllocationCheck(t *testing.T, measure func()) {
t.Helper()
if *routeAllocationChild {
measure()
t.Log("ROUTE_ALLOCATION_MEASURED " + t.Name())
return
}
runRouteAllocationTest(t, t.Name())
}
func runRouteAllocationTest(t *testing.T, name string) {
t.Helper()
switch name {
case "TestNormalizeSegment_DoesNotAllocate", "TestNormalizeRoute_RootFastPathDoesNotAllocate", "TestNormalizeRoute_BoundedAllocations", "TestNormalizeRoute_LabelAllocationProfile":
default:
t.Fatalf("unknown route allocation measurement %q", name)
}
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, executable,
"-test.run=^"+regexp.QuoteMeta(name)+"$", "-test.count=1", "-test.v",
"-test.timeout=25s", "-test.routeAllocationChild=true")
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("isolated %s failed: %v\n%s", name, err, output)
}
if !strings.Contains(string(output), "ROUTE_ALLOCATION_MEASURED "+name) {
t.Fatalf("isolated %s did not execute its measurement:\n%s", name, output)
}
}
func TestRouteAllocationMeasurementExcludesBackgroundFixtures(t *testing.T) {
requests := make(chan struct{})
acknowledged := make(chan struct{})
stop := make(chan struct{})
done := make(chan struct{})
var sink []byte
var calls atomic.Uint64
go func() {
defer close(done)
for {
select {
case <-stop:
return
case <-requests:
sink = make([]byte, 256)
calls.Add(1)
acknowledged <- struct{}{}
}
}
}()
t.Cleanup(func() {
close(stop)
<-done
if len(sink) != 256 {
t.Error("background fixture did not retain its allocation")
}
})
allocateElsewhere := func() {
requests <- struct{}{}
<-acknowledged
}
// Synchronise an unrelated allocation inside each measured call. The
// normaliser still returns a literal, but the old process-wide assertion
// necessarily attributes this other goroutine's allocation to it.
contaminated := testing.AllocsPerRun(100, func() {
normalizeRouteSink = normalizeRoute("/")
allocateElsewhere()
})
if contaminated < 1 {
t.Fatal("control failed to demonstrate process-wide allocation accounting")
}
t.Logf("unrelated fixture contaminates root measurement: %v allocations/call", contaminated)
// Keep the parent fixture active while the same binary's isolated root
// and segment checks execute. Both must still enforce exactly zero.
pumpStop := make(chan struct{})
pumpDone := make(chan struct{})
go func() {
defer close(pumpDone)
ticker := time.NewTicker(time.Millisecond)
defer ticker.Stop()
for {
select {
case <-pumpStop:
return
case <-ticker.C:
allocateElsewhere()
}
}
}()
t.Cleanup(func() { close(pumpStop); <-pumpDone })
before := calls.Load()
runRouteAllocationTest(t, "TestNormalizeRoute_RootFastPathDoesNotAllocate")
runRouteAllocationTest(t, "TestNormalizeSegment_DoesNotAllocate")
if calls.Load() <= before {
t.Fatal("background fixture was not active during isolated checks")
}
}