Доработать инструменты экспериментов: чередовать повторы, останавливать лестницу на первой проваленной ступени, задавать maxconn и CPU базы в сериях, записывать замер скорости хоста и контроль шума, сократить комментарии

This commit is contained in:
2026-11-04 12:39:04 +03:00
parent ce47c138e4
commit baa5995938
24 changed files with 253 additions and 240 deletions
+2 -3
View File
@@ -52,9 +52,8 @@ func (c *client) postMessage(chatID, token, text string, out any) error {
return c.do(req, token, http.StatusCreated, out)
}
// sendWithKey sends one attempt of a message under the given key on a
// connection of its own and reports the status, the message (on 201) and the
// replica that answered.
// sendWithKey sends one attempt on a connection of its own, so that the
// attempts of one key reach different replicas.
func (c *client) sendWithKey(chatID, token, key, text string) (int, chat.MessageResponse, string, error) {
var msg chat.MessageResponse
raw, err := json.Marshal(map[string]string{"text": text})
+3 -6
View File
@@ -4,12 +4,9 @@
// then the history is paged and must contain exactly N*M unique messages in
// id order.
//
// Phase 2, shared idempotency: in each of K rounds one user sends the same
// message with the same Idempotency-Key P times in parallel, each attempt on
// its own connection, so the balancer spreads them over the replicas. Every
// attempt must answer 201 with the same message, the attempts must have
// reached at least two replicas, the history must hold exactly K messages,
// and the key with another text must answer 409.
// Phase 2: in each of K rounds one key is sent P times in parallel through the
// balancer; every attempt must get 201 with one message, at least two replicas
// must answer, the history must hold K messages, and another text must get 409.
package main
import (
+16 -25
View File
@@ -1,21 +1,10 @@
// Command loadgen is the open-loop load generator of the scaling study
// (track 1) and of the failover and rolling-update experiments.
// Command loadgen is the open-loop load generator of the experiments.
//
// loadgen bench — seeds users, chats and messages, warms up, then offers
// each rate of -rates for -step: a mix of history reads
// (-read-ratio) and message sends. Writes steps.json and
// seconds.csv, and metrics.jsonl with -scrape.
// loadgen timeline — one user sends messages into one chat at -rate for
// -duration; a send with an uncertain outcome (no answer,
// 5xx) is retried with the same Idempotency-Key. At the
// end the whole history is read back: every confirmed
// message must be there, and none twice. Writes
// timeline.json and seconds.csv.
//
// Requests are sent on schedule whatever the response times (open loop), and
// the generator records how late it sent them: a step it could not keep up
// with is marked invalid rather than reported as the system's limit. Tokens
// stay in memory and are never written out.
// loadgen bench — seeds data, warms up, then offers each rate of -rates
// for -step as a mix of history reads and message sends.
// loadgen timeline — one user sends messages at -rate, retrying uncertain
// sends with the same Idempotency-Key, then reads the
// history back: every confirmed message once.
package main
import (
@@ -52,6 +41,7 @@ type config struct {
Timeout string `json:"client_timeout"`
Seed uint64 `json:"seed"`
Scrape bool `json:"scrape"`
StopOnFail bool `json:"stop_on_fail"`
StatsURL string `json:"stats_url"`
APIHost string `json:"api_host"`
DebugPort string `json:"debug_port"`
@@ -98,6 +88,7 @@ func parse(mode string, args []string) (config, error) {
fs.StringVar(&cfg.Duration, "duration", "60s", "timeline: duration")
fs.StringVar(&cfg.Timeout, "timeout", "2s", "how long the generator waits for a response (class client_timeout)")
fs.Uint64Var(&cfg.Seed, "seed", 1, "random seed of the request mix")
fs.BoolVar(&cfg.StopOnFail, "stop-on-fail", false, "bench: end the ladder after the first step that fails the capacity criterion")
fs.BoolVar(&cfg.Scrape, "scrape", false, "sample HAProxy statistics and replica expvar every second")
fs.StringVar(&cfg.StatsURL, "stats-url", "http://lb:8404/;csv", "HAProxy statistics CSV")
fs.StringVar(&cfg.APIHost, "api-host", "api", "DNS name of the API replicas")
@@ -138,8 +129,7 @@ func writeJSON(path string, v any) error {
return os.WriteFile(path, append(raw, '\n'), 0o644)
}
// startScrape samples the system in the background when asked to; the
// returned function stops it and waits.
// startScrape returns the function that stops the sampling and waits.
func startScrape(ctx context.Context, cfg config, start time.Time) func() {
if !cfg.Scrape {
return func() {}
@@ -177,8 +167,7 @@ func runBench(ctx context.Context, cfg config) error {
stopScrape := startScrape(ctx, cfg, start)
defer stopScrape()
// next picks the request on the scheduling goroutine, where the random
// source may be used safely.
// next runs on the scheduling goroutine, which owns the random source.
counter := 0
next := func(rec *recorder) func(time.Time) func() {
return func(planned time.Time) func() {
@@ -217,8 +206,11 @@ func runBench(ctx context.Context, cfg config) error {
for _, x := range rec.all() {
all.add(x)
}
fmt.Printf("step %6.0f rps: ok %7.1f rps, errors %5.2f%%, p99 %7.1f ms, lag p99 %5.1f ms, valid %v\n",
rate, s.OKRPS, 100*s.ErrorShare, s.P99Ms, s.LagP99Ms, s.Valid)
fmt.Printf("step %6.0f rps: ok %7.1f rps, errors %5.2f%%, p99 %7.1f ms, lag p99 %5.1f ms, valid %v, passed %v\n",
rate, s.OKRPS, 100*s.ErrorShare, s.P99Ms, s.LagP99Ms, s.Valid, s.Passed)
if cfg.StopOnFail && !s.Passed {
break
}
}
stopScrape()
if err := os.WriteFile(filepath.Join(cfg.Out, "seconds.csv"), []byte(secondsCSV(start, all.all())), 0o644); err != nil {
@@ -247,8 +239,7 @@ type timelineReport struct {
// retryDelay spaces the attempts of one message whose outcome was uncertain.
const retryDelay = 200 * time.Millisecond
// retryGrace is how long after the schedule ends an uncertain message keeps
// being retried before it counts as unresolved.
// retryGrace bounds the retries of an uncertain message after the schedule ends.
const retryGrace = 10 * time.Second
func runTimeline(ctx context.Context, cfg config) error {
+3 -8
View File
@@ -6,14 +6,9 @@ import (
"time"
)
// openLoop offers requests at a constant rate for d, whatever the response
// times: request i is planned at start + i/rate and sent then, or at once if
// the generator is already late. Waiting for responses before sending more
// (a closed loop) would let a slow system lower its own load and hide its
// latency: coordinated omission. next runs on the scheduling goroutine, so it
// may use non-thread-safe state such as the random source; the job it
// returns runs on a goroutine of its own. openLoop returns once every job
// has finished.
// openLoop sends request i at start + i/rate whatever the response times: a
// closed loop would let a slow system lower its own load and hide its latency
// (coordinated omission). It returns once every job has finished.
func openLoop(ctx context.Context, rate float64, d time.Duration, next func(planned time.Time) func()) {
n := int(rate * d.Seconds())
interval := time.Duration(float64(time.Second) / rate)
+2 -5
View File
@@ -12,11 +12,8 @@ import (
"time"
)
// scraper samples, once a second, what the balancer and every replica report
// about themselves, so a saturated step can be explained: the HAProxy
// statistics per replica and the expvar of each API process (pool waits,
// GOMAXPROCS, memory and GC). Replicas are found the way HAProxy finds them,
// through Docker DNS, and asked directly on their internal debug port.
// scraper samples the HAProxy statistics and every replica's expvar once a
// second; replicas are found through Docker DNS, as HAProxy finds them.
type scraper struct {
statsURL string
apiHost string
+15 -10
View File
@@ -12,11 +12,17 @@ import (
"time"
)
// maxValidLag is the generator's own tolerance: if requests left more than
// this late at the 99th percentile, the generator, not the system, limited
// the step, and the step is excluded from the conclusions.
// maxValidLag: if requests left later than this at p99, the generator, not
// the system, limited the step.
const maxValidLag = 10 * time.Millisecond
// The capacity criterion of the study: a step passes when it is valid, has
// fewer than 1 % errors and its successful requests have a p99 within 500 ms.
const (
maxErrorShare = 0.01
sloP99 = 500 * time.Millisecond
)
// sample is one request as the generator saw it.
type sample struct {
planned time.Time
@@ -27,11 +33,9 @@ type sample struct {
write bool
}
// classify names the outcome of a request. HTTP errors produced by the
// balancer itself carry no X-Instance-Id and are kept apart from the API's
// own: a 503 from HAProxy means no replica was available, a 503 from the API
// means a dependency was. client_timeout is the generator giving up on a
// response, not a timeout of the system.
// classify names the outcome of a request. Errors of the balancer itself carry
// no X-Instance-Id and get the suffix _lb; client_timeout is the generator
// giving up, not a timeout of the system.
func classify(r result) string {
switch {
case r.err != nil && isTimeout(r.err):
@@ -78,12 +82,12 @@ type stepSummary struct {
P99Ms float64 `json:"ok_p99_ms"`
LagP99Ms float64 `json:"lag_p99_ms"`
Valid bool `json:"valid"`
Passed bool `json:"passed"`
Instances map[string]int `json:"instances"`
Writes int `json:"writes_ok"`
}
// summarize reduces one step. Latency percentiles cover successful requests
// only, as the course's report format asks; the errors are counted by class.
// summarize reduces one step; latency percentiles cover successful requests.
func summarize(rate float64, d time.Duration, samples []sample) stepSummary {
s := stepSummary{
OfferedRPS: rate,
@@ -117,6 +121,7 @@ func summarize(rate float64, d time.Duration, samples []sample) stepSummary {
lagP99 := percentile(lags, 99)
s.LagP99Ms = ms(lagP99)
s.Valid = lagP99 <= maxValidLag
s.Passed = s.Valid && s.ErrorShare < maxErrorShare && percentile(ok, 99) <= sloP99
return s
}
+22
View File
@@ -104,3 +104,25 @@ func TestOpenLoopDoesNotWaitForResponses(t *testing.T) {
t.Fatalf("open loop took %v, want about 1.2 s", took)
}
}
func TestStepPassesOnlyWithinTheObjective(t *testing.T) {
ok := func(latency, lag time.Duration) sample {
return sample{class: "ok", latency: latency, lag: lag}
}
fast := []sample{ok(10*time.Millisecond, time.Millisecond), ok(20*time.Millisecond, time.Millisecond)}
if s := summarize(2, time.Second, fast); !s.Passed {
t.Fatalf("fast clean step must pass: %+v", s)
}
slow := []sample{ok(10*time.Millisecond, time.Millisecond), ok(600*time.Millisecond, time.Millisecond)}
if s := summarize(2, time.Second, slow); s.Passed {
t.Fatalf("p99 above 500 ms must fail: %+v", s)
}
failing := append(fast, sample{class: "http_503_lb", lag: time.Millisecond})
if s := summarize(3, time.Second, failing); s.Passed {
t.Fatalf("errors above 1 %% must fail: %+v", s)
}
late := []sample{ok(10*time.Millisecond, 50*time.Millisecond), ok(10*time.Millisecond, 50*time.Millisecond)}
if s := summarize(2, time.Second, late); s.Passed {
t.Fatalf("an invalid step must fail: %+v", s)
}
}