Skip to content

The only tool you need to know what is happening and how to fix it.

more benching

dduxf2e73187c5c9
diff --git a/benchmarks/README.md b/benchmarks/README.md
index a289a80e..c934ca0c 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -57,11 +57,23 @@ Per matrix entry (one tier × one mode × one signal):
`--step-duration` (default 2 min). Stops at the first failing step.
- **Phase 2 — request-rate ramp.** Batch size fixed at
`min(Phase 1 winner, --phase2-batch-cap=8192)`. Request rates step
- through `1,5,25,100,400`.
-6. A step "fails" when combined error rate (HTTP failures + OTLP
- `PartialSuccess` rejected items) exceeds `--ingest-err-threshold`
- (default 5%). The headline is
- `maxSustainableItemsPerSec = batchSize × maxRequestRate`.
+ through `1,5,25,100,400`. When the coarse ramp finds the first failing
+ step, up to `--phase2-bisect-max-steps` (default 3) bisection steps run
+ between the last passing rate and the failing rate to pin the cliff
+ within `--phase2-bisect-tolerance` (default 20%). So `5→25` (a 5× jump)
+ gets refined into something like `5, 15, 10, 12` until the gap is
+ <20% of the last passing rate.
+6. A step "fails" when **either**:
+ - combined error rate (HTTP failures + OTLP `PartialSuccess` rejected items)
+ exceeds `--ingest-err-threshold` (default 5%), **or**
+ - the *achieved* request rate falls below `--soft-cliff-ratio` × target rate
+ (default 70%) — meaning the workers can't keep up with the limiter, the
+ SUT has cliffed on latency, and we'd be erroring out one step later anyway.
+
+ The headline `maxSustainableItemsPerSec` is the highest `actualItemsPerSec`
+ recorded across passing Phase 2 steps — measured from real OK responses,
+ not the formula `batchSize × targetRate` (which over-reports when workers
+ saturate before the limiter does).
7. `hetzner-down.sh` deletes everything via a bash `trap` — even on Ctrl-C.
After all matrix entries finish, `chart.py` renders three bar charts
diff --git a/benchmarks/loadgen/bench-loadgen b/benchmarks/loadgen/bench-loadgen
new file mode 100755
index 00000000..9bbf69f7
Binary files /dev/null and b/benchmarks/loadgen/bench-loadgen differ
diff --git a/benchmarks/loadgen/ingest.go b/benchmarks/loadgen/ingest.go
index 8191f854..0bf918f2 100644
--- a/benchmarks/loadgen/ingest.go
+++ b/benchmarks/loadgen/ingest.go
@@ -6,6 +6,7 @@ import (
"net/http"
"sync"
"sync/atomic"
+ "time"
"golang.org/x/time/rate"
)
@@ -25,9 +26,13 @@ type ingester struct {
// rng pool: each worker grabs one to avoid contending on the global source
rngPool sync.Pool
- // workerWg + workerCancel let the ramp resize the pool between steps.
+ // Two contexts let the ramp stop accepting new requests at step boundaries
+ // without killing in-flight HTTP. acceptCancel ends the limiter.Wait loop;
+ // the request ctx (parent of acceptCtx) remains alive so HTTP responses
+ // can complete and be counted. Stop() forces a hard cancel by deriving the
+ // hard-stop ctx from the parent.
workerWg *sync.WaitGroup
- workerCancel context.CancelFunc
+ acceptCancel context.CancelFunc
}
func newIngester(cfg config, client *http.Client, stats *latencyTracker) (*ingester, error) {
@@ -100,12 +105,14 @@ func (i *ingester) SnapshotAndResetItems() (attempted, rejected int64) {
return
}
-// Start launches the worker pool sized for the current request rate. Call Stop
-// before changing the worker count via another Start.
+// Start launches the worker pool sized for the current request rate. The
+// passed ctx is used directly for HTTP requests so in-flight requests survive
+// across step boundaries; the limiter loop uses a derived acceptCtx that
+// StopAccepting can cancel independently.
func (i *ingester) Start(ctx context.Context) {
- workerCtx, cancel := context.WithCancel(ctx)
+ acceptCtx, cancelAccept := context.WithCancel(ctx)
wg := &sync.WaitGroup{}
- i.workerCancel = cancel
+ i.acceptCancel = cancelAccept
i.workerWg = wg
workers := workerCountFor(i.RequestRate())
@@ -116,37 +123,68 @@ func (i *ingester) Start(ctx context.Context) {
rng := i.rngPool.Get().(*rand.Rand)
defer i.rngPool.Put(rng)
for {
- if err := i.limiter.Wait(workerCtx); err != nil {
+ if err := i.limiter.Wait(acceptCtx); err != nil {
return
}
batchSize := int(i.batchSize.Load())
- sendOneOTLP(workerCtx, i.client, i.cfg, i.sender, rng, batchSize, i.stats, &i.attemptedItems, &i.rejectedItems)
+ // HTTP uses the parent ctx (not acceptCtx) so requests in
+ // flight when StopAccepting fires aren't canceled mid-flight.
+ sendOneOTLP(ctx, i.client, i.cfg, i.sender, rng, batchSize, i.stats, &i.attemptedItems, &i.rejectedItems)
}
}()
}
}
-func (i *ingester) Stop() {
- if i.workerCancel != nil {
- i.workerCancel()
+// StopAccepting tells the worker pool to stop pulling from the rate limiter.
+// In-flight HTTP requests continue under the parent ctx until they finish or
+// the parent ctx is canceled. Pair with WaitForDrain to give them a grace
+// window before the next step starts.
+func (i *ingester) StopAccepting() {
+ if i.acceptCancel != nil {
+ i.acceptCancel()
+ }
+}
+
+// WaitForDrain blocks up to d for the worker pool to finish any in-flight
+// HTTP requests. Returns earlier when all workers exit.
+func (i *ingester) WaitForDrain(d time.Duration) {
+ if i.workerWg == nil {
+ return
}
- if i.workerWg != nil {
- i.workerWg.Wait()
+ done := make(chan struct{})
+ go func() { i.workerWg.Wait(); close(done) }()
+ if d <= 0 {
+ <-done
+ return
}
- i.workerCancel = nil
+ select {
+ case <-done:
+ case <-time.After(d):
+ }
+}
+
+// Stop ends acceptance and waits forever for the pool to drain. The parent
+// ctx still gates HTTP cancellation, so this won't hang past the overall run
+// deadline.
+func (i *ingester) Stop() {
+ i.StopAccepting()
+ i.WaitForDrain(0)
+ i.acceptCancel = nil
i.workerWg = nil
}
-// workerCountFor scales worker count with request rate. 256 workers idling on
-// a 5 req/sec limiter is wasteful; on the other hand, a 400 req/sec target
-// with 8 workers + a 200ms p99 leaves the limiter starved.
+// workerCountFor scales worker count with request rate. The headroom is
+// generous because high-latency steps (multi-second P50) can otherwise starve
+// the rate limiter: at rps=5 with P50=4s, 10 workers only deliver 2.5 req/sec.
+// 30 seconds of in-flight headroom guarantees we hit target rate unless the
+// SUT is truly past its cliff.
func workerCountFor(rps float64) int {
- n := int(rps * 2)
- if n < 8 {
- n = 8
+ n := int(rps * 30)
+ if n < 32 {
+ n = 32
}
- if n > 256 {
- n = 256
+ if n > 512 {
+ n = 512
}
return n
}
diff --git a/benchmarks/loadgen/main.go b/benchmarks/loadgen/main.go
index cf6d0ac3..a7e607d0 100644
--- a/benchmarks/loadgen/main.go
+++ b/benchmarks/loadgen/main.go
@@ -27,7 +27,11 @@ type config struct {
phase2RequestRates []float64
phase1FixedRate float64
phase2BatchCap int
- ingestErrThreshold float64
+ ingestErrThreshold float64
+ softCliffRatio float64
+ stepDrainSeconds time.Duration
+ phase2BisectMaxSteps int
+ phase2BisectTolerance float64
fillLevels []int64
readThresholdMs int
settleSeconds time.Duration
@@ -59,6 +63,10 @@ func main() {
flag.Float64Var(&cfg.phase1FixedRate, "phase1-fixed-rate", 5, "Fixed request rate during Phase 1 (req/sec)")
flag.IntVar(&cfg.phase2BatchCap, "phase2-batch-cap", 8192, "Cap on Phase 2 batch size; Phase 2 uses min(this, Phase 1 winner)")
flag.Float64Var(&cfg.ingestErrThreshold, "ingest-err-threshold", 0.05, "Step fails if combined (HTTP error + OTLP rejected) item rate exceeds this")
+ flag.Float64Var(&cfg.softCliffRatio, "soft-cliff-ratio", 0.70, "Step fails when achieved req-rate is below this fraction of target — catches saturated-but-not-erroring cliffs. 0 disables.")
+ flag.DurationVar(&cfg.stepDrainSeconds, "step-drain-seconds", 10*time.Second, "After step duration expires, wait up to this long for in-flight HTTP requests to complete before hard-canceling (reduces error-count noise at boundaries)")
+ flag.IntVar(&cfg.phase2BisectMaxSteps, "phase2-bisect-max-steps", 3, "After Phase 2 finds the cliff, run up to this many bisection steps between the last passing and first failing rate to narrow the cliff. 0 disables.")
+ flag.Float64Var(&cfg.phase2BisectTolerance, "phase2-bisect-tolerance", 0.20, "Bisection stops when (firstFailRate-lastPassRate)/lastPassRate falls below this fraction (e.g. 0.20 = stop when the cliff is pinned to within 20% of the last passing rate).")
flag.StringVar(&fillLevelsStr, "fill-levels", "100000,1000000,10000000,100000000", "Comma-separated row counts to fill before probing a read (read-probe scenario)")
flag.IntVar(&cfg.readThresholdMs, "read-threshold-ms", 5000, "Read latency threshold in ms; step fails if a probe exceeds it (read-probe scenario)")
flag.DurationVar(&cfg.settleSeconds, "settle-seconds", 10*time.Second, "Wait between finishing ingest and probing the read (read-probe scenario)")
diff --git a/benchmarks/loadgen/ramp.go b/benchmarks/loadgen/ramp.go
index 52ca08eb..fcfc4fb7 100644
--- a/benchmarks/loadgen/ramp.go
+++ b/benchmarks/loadgen/ramp.go
@@ -43,12 +43,11 @@ type finalReport struct {
func (r *finalReport) computeHeadline() {
if r.Phase2 != nil {
- if r.Phase2.FixedBatchSize > 0 && r.Phase2.MaxRequestRate > 0 {
- r.MaxSustainableItemsPerSec = float64(r.Phase2.FixedBatchSize) * r.Phase2.MaxRequestRate
- return
- }
- // Fall back to the best actual measured throughput from any passing Phase 2
- // step — useful when Phase 2 had to round down or skipped steps.
+ // Use the achieved throughput of the last passing step. The
+ // FixedBatchSize × MaxRequestRate formula is unreliable: at the cliff,
+ // workers saturate on HTTP latency and never deliver the target rate,
+ // so the formula overstates capacity. ActualItemsPerSec is measured
+ // from real OK responses and tells the truth.
var best float64
for _, s := range r.Phase2.Steps {
if s.Passed && s.ActualItemsPerSec > best {
@@ -112,27 +111,65 @@ func runRequestRateRamp(ctx context.Context, cfg config, ing *ingester, ingest *
ing.SetBatchSize(batch)
- for idx, rate := range cfg.phase2RequestRates {
+ var lastPassRate, firstFailRate float64
+ stepNo := 0
+
+ for _, rate := range cfg.phase2RequestRates {
if ctx.Err() != nil {
break
}
+ stepNo++
ing.SetRequestRate(rate)
- s := runOneStep(ctx, cfg, ing, ingest, idx+1, batch, rate)
+ s := runOneStep(ctx, cfg, ing, ingest, stepNo, batch, rate)
res.Steps = append(res.Steps, s)
fmt.Fprintf(stderrPrefix(), "phase2 step %d: batch=%d rate=%.1f items/s=%.0f p99=%.0fms err=%.2f%% passed=%t %s\n",
s.Step, s.BatchSize, s.RequestRate, s.ActualItemsPerSec, s.Ingest.P99, s.Ingest.ErrRate*100, s.Passed, s.FailReason)
if !s.Passed {
+ firstFailRate = rate
break
}
res.MaxRequestRate = rate
+ lastPassRate = rate
+ }
+
+ // Bisection refinement. After the coarse ramp finds an adjacent
+ // (passing, failing) pair, halve the gap up to phase2BisectMaxSteps
+ // times to pin the real cliff. Skipped when nothing failed (no cliff
+ // in the configured range) or nothing passed (cliff below the
+ // smallest configured rate — bisecting below it isn't informative).
+ if cfg.phase2BisectMaxSteps > 0 && lastPassRate > 0 && firstFailRate > lastPassRate {
+ for b := 0; b < cfg.phase2BisectMaxSteps; b++ {
+ if ctx.Err() != nil {
+ break
+ }
+ gap := (firstFailRate - lastPassRate) / lastPassRate
+ if gap <= cfg.phase2BisectTolerance {
+ break
+ }
+ mid := (lastPassRate + firstFailRate) / 2
+ stepNo++
+ ing.SetRequestRate(mid)
+ s := runOneStep(ctx, cfg, ing, ingest, stepNo, batch, mid)
+ res.Steps = append(res.Steps, s)
+ fmt.Fprintf(stderrPrefix(), "phase2 bisect %d: batch=%d rate=%.1f items/s=%.0f p99=%.0fms err=%.2f%% passed=%t %s\n",
+ s.Step, s.BatchSize, s.RequestRate, s.ActualItemsPerSec, s.Ingest.P99, s.Ingest.ErrRate*100, s.Passed, s.FailReason)
+ if s.Passed {
+ lastPassRate = mid
+ res.MaxRequestRate = mid
+ } else {
+ firstFailRate = mid
+ }
+ }
}
return res
}
// runOneStep resizes the worker pool for the new rate, holds the step for
-// stepDuration, then snapshots latency + item counters. The worker pool is
-// torn down between steps so worker count tracks the current rate.
+// stepDuration, drains in-flight HTTP for stepDrainSeconds, then snapshots
+// latency + item counters. The drain window matters: without it, every step
+// boundary cancels ~workerCount in-flight requests mid-flight, inflating the
+// recorded error count and depressing the OK count.
func runOneStep(ctx context.Context, cfg config, ing *ingester, ingest *latencyTracker, stepNo, batchSize int, requestRate float64) stepResult {
ingest.SnapshotAndReset()
ing.SnapshotAndResetItems()
@@ -143,8 +180,13 @@ func runOneStep(ctx context.Context, cfg config, ing *ingester, ingest *latencyT
start := time.Now()
<-stepCtx.Done()
cancel()
- elapsed := time.Since(start)
+ // Stop accepting new requests; let in-flight ones complete. elapsed
+ // includes the drain window so the rate divisor reflects the full window
+ // during which items could have arrived.
+ ing.StopAccepting()
+ ing.WaitForDrain(cfg.stepDrainSeconds)
+ elapsed := time.Since(start)
ing.Stop()
snap := ingest.SnapshotAndReset()
@@ -165,7 +207,7 @@ func runOneStep(ctx context.Context, cfg config, ing *ingester, ingest *latencyT
actualIps = float64(actualItems) / elapsed.Seconds()
}
- passed, reason := evaluateStep(cfg, snap, attempted, rejected)
+ passed, reason := evaluateStep(cfg, snap, attempted, rejected, requestRate, elapsed)
return stepResult{
Step: stepNo,
@@ -180,10 +222,14 @@ func runOneStep(ctx context.Context, cfg config, ing *ingester, ingest *latencyT
}
}
-// evaluateStep combines HTTP-level error rate with OTLP partial-success
-// rejections. A SUT that returns 200 OK but rejects half the items is failing
-// just as surely as one that 500s.
-func evaluateStep(cfg config, snap latencySnapshot, attempted, rejected int64) (bool, string) {
+// evaluateStep combines three failure criteria:
+// 1. HTTP-level error rate + OTLP partial-success rejections > threshold
+// (combined item-error budget).
+// 2. Soft cliff: achieved request rate is far below target. This catches
+// the "workers saturated but SUT not yet erroring" state, where latency
+// has cliffed to multiple seconds and only error-rate-based detection
+// would let the ramp keep climbing one more step before noticing.
+func evaluateStep(cfg config, snap latencySnapshot, attempted, rejected int64, targetRate float64, elapsed time.Duration) (bool, string) {
totalReq := snap.OK + snap.Errors
if totalReq == 0 {
return false, "no requests completed"
@@ -198,5 +244,12 @@ func evaluateStep(cfg config, snap latencySnapshot, attempted, rejected int64) (
return false, fmt.Sprintf("combined error rate %.2f%% (http %.2f%% + rejected %.2f%%) > %.2f%% threshold",
combined*100, httpErrRate*100, rejectRate*100, cfg.ingestErrThreshold*100)
}
+ if targetRate > 0 && elapsed > 0 && cfg.softCliffRatio > 0 {
+ achievedRate := float64(snap.OK) / elapsed.Seconds()
+ if achievedRate < targetRate*cfg.softCliffRatio {
+ return false, fmt.Sprintf("achieved %.2f req/sec is below %.0f%% of target %.2f req/sec (workers saturated, SUT past cliff)",
+ achievedRate, cfg.softCliffRatio*100, targetRate)
+ }
+ }
return true, ""
}
diff --git a/benchmarks/scripts/chart.py b/benchmarks/scripts/chart.py
index 67e373ad..c88e3efe 100755
--- a/benchmarks/scripts/chart.py
+++ b/benchmarks/scripts/chart.py
@@ -114,8 +114,11 @@ def render_throughput_detail(runs: list[dict], signal: str, out: Path) -> None:
for run in sorted(runs, key=lambda r: (tier_rank(r["tier"]), mode_rank(r["mode"]))):
steps = (run.get("phase2") or {}).get("steps") or []
- xs = [s["requestRate"] for s in steps if s.get("ingest")]
- ys = [s["ingest"]["p99"] for s in steps if s.get("ingest")]
+ # Bisection appends steps in execution order, not rate order. Sort
+ # by requestRate so the line draws monotonically across the X axis.
+ steps = sorted([s for s in steps if s.get("ingest")], key=lambda s: s.get("requestRate", 0))
+ xs = [s["requestRate"] for s in steps]
+ ys = [s["ingest"]["p99"] for s in steps]
if not xs:
continue
ax.plot(xs, ys, marker="o", label=f"{run['tier']} / {run['mode']}")