main.go raw

   1  // Command torly-stress exercises the torly store engine under a synthetic load.
   2  //
   3  // It is a database-engine rig, not a relay protocol client: events are built
   4  // directly and saved through store.Engine, so signature verification and
   5  // WebSocket transport are deliberately excluded from the measurements.
   6  package main
   7  
   8  import (
   9  	"encoding/binary"
  10  	"encoding/json"
  11  	"flag"
  12  	"fmt"
  13  	"math/rand"
  14  	"os"
  15  	"path/filepath"
  16  	"sort"
  17  	"strconv"
  18  	"strings"
  19  	"sync"
  20  	"sync/atomic"
  21  	"time"
  22  
  23  	"git.smesh.lol/torly/pkg/nostr"
  24  	"git.smesh.lol/torly/pkg/store"
  25  )
  26  
  27  type latencyStats struct {
  28  	Count int     `json:"count"`
  29  	Mean  float64 `json:"mean_ms"`
  30  	P50   float64 `json:"p50_ms"`
  31  	P95   float64 `json:"p95_ms"`
  32  	P99   float64 `json:"p99_ms"`
  33  	Max   float64 `json:"max_ms"`
  34  }
  35  
  36  type queryResult struct {
  37  	Name    string       `json:"name"`
  38  	Events  int          `json:"events"`
  39  	Latency latencyStats `json:"latency"`
  40  }
  41  
  42  type mixedResult struct {
  43  	Seconds     float64      `json:"seconds"`
  44  	Saves       int64        `json:"saves"`
  45  	SaveErrors  int64        `json:"save_errors"`
  46  	Queries     int64        `json:"queries"`
  47  	QueryErrors int64        `json:"query_errors"`
  48  	Latency     latencyStats `json:"query_latency"`
  49  }
  50  
  51  type summary struct {
  52  	DataDir     string        `json:"data_dir"`
  53  	SeedEvents  int           `json:"seed_events"`
  54  	Stored      int           `json:"stored"`
  55  	SeedSeconds float64       `json:"seed_seconds"`
  56  	SeedEPS     float64       `json:"seed_eps"`
  57  	RSSMB       float64       `json:"rss_mb"`
  58  	RunFiles    int           `json:"run_files"`
  59  	IndexBytes  int64         `json:"index_bytes"`
  60  	Queries     []queryResult `json:"queries"`
  61  	Mixed       *mixedResult  `json:"mixed,omitempty"`
  62  	CompactMS   float64       `json:"compact_ms"`
  63  	ReopenMS    float64       `json:"reopen_ms"`
  64  	CloseMS     float64       `json:"close_ms"`
  65  	FinalRSSMB  float64       `json:"final_rss_mb"`
  66  }
  67  
  68  type generator struct {
  69  	rng       *rand.Rand
  70  	authors   [][32]byte
  71  	authorHex []string
  72  	tagVals   []string
  73  	ids       [][32]byte
  74  }
  75  
  76  func newGenerator(seed int64, authors int) *generator {
  77  	g := &generator{rng: rand.New(rand.NewSource(seed))}
  78  	for a := 0; a < authors; a++ {
  79  		var pub [32]byte
  80  		binary.BigEndian.PutUint64(pub[:8], uint64(a)+0x5354524553530000)
  81  		for i := 8; i < len(pub); i++ {
  82  			pub[i] = byte(a*31 + i)
  83  		}
  84  		g.authors = append(g.authors, pub)
  85  		g.authorHex = append(g.authorHex, nostr.Hex(pub[:]))
  86  	}
  87  	for i := 0; i < 400; i++ {
  88  		g.tagVals = append(g.tagVals, "tag"+strconv.Itoa(i))
  89  	}
  90  	return g
  91  }
  92  
  93  func (g *generator) clone(seed int64) *generator {
  94  	return &generator{
  95  		rng:       rand.New(rand.NewSource(seed)),
  96  		authors:   g.authors,
  97  		authorHex: g.authorHex,
  98  		tagVals:   g.tagVals,
  99  	}
 100  }
 101  
 102  func stressAuthor(i int) string {
 103  	var p [32]byte
 104  	binary.BigEndian.PutUint64(p[:8], uint64(i)+0x5354524553530000)
 105  	for j := 8; j < len(p); j++ {
 106  		p[j] = byte(i*17 + j)
 107  	}
 108  	return nostr.Hex(p[:])
 109  }
 110  
 111  func (g *generator) event(i int, now int64) *nostr.Event {
 112  	var id [32]byte
 113  	binary.BigEndian.PutUint64(id[:8], uint64(i)+1)
 114  	copy(id[8:], "torly-store-stress-event-id")
 115  	ev := &nostr.Event{
 116  		ID:        id,
 117  		PubKey:    g.authors[i%len(g.authors)],
 118  		CreatedAt: now - 30*24*3600 + int64(i),
 119  		Kind:      1,
 120  		Content:   "stress event " + strconv.Itoa(i) + " alpha beta gamma delta epsilon",
 121  	}
 122  	switch n := g.rng.Intn(100); {
 123  	case n < 88:
 124  		ev.Kind = 1
 125  	case n < 93:
 126  		ev.Kind = 7
 127  	case n < 94:
 128  		ev.Kind = 6
 129  	case n < 96:
 130  		ev.Kind = 3
 131  	case n < 97:
 132  		ev.Kind = 1111
 133  	case n < 98:
 134  		ev.Kind = 1059
 135  	default:
 136  		ev.Kind = 0
 137  	}
 138  	// Seed one contact list per author so the graph scenarios always have a
 139  	// valid seed and at least one outbound edge.
 140  	if i < len(g.authors) {
 141  		ev.Kind = 3
 142  	}
 143  	if ev.Kind == 0 {
 144  		ev.Content = `{"name":"author ` + strconv.Itoa(i%len(g.authors)) + `"}`
 145  	}
 146  	tag := g.tagVals[g.rng.Intn(len(g.tagVals))]
 147  	ev.Tags = nostr.Tags{{"t", tag}}
 148  	if ev.Kind == 3 {
 149  		ev.Content = ""
 150  		follows := 10
 151  		if i%1000 == 0 {
 152  			follows = 600
 153  		}
 154  		for j := 0; j < follows; j++ {
 155  			ev.Tags = append(ev.Tags, nostr.Tag{"p", stressAuthor(i*1000 + j)})
 156  		}
 157  	}
 158  	if ev.Kind == 1 || ev.Kind == 7 || ev.Kind == 6 || ev.Kind == 1111 || ev.Kind == 1059 {
 159  		ev.Tags = append(ev.Tags, nostr.Tag{"p", g.authorHex[g.rng.Intn(len(g.authorHex))]})
 160  	}
 161  	if ev.Kind == 7 || ev.Kind == 6 {
 162  		ev.Tags = append(ev.Tags, nostr.Tag{"e", nostr.Hex(id[:])})
 163  	}
 164  	// A small fraction have more than 256 tags; those must not enter the graph.
 165  	if g.rng.Intn(200) == 0 {
 166  		for j := 0; j < 300; j++ {
 167  			ev.Tags = append(ev.Tags, nostr.Tag{"x", "bulk-" + strconv.Itoa(j)})
 168  		}
 169  	}
 170  	return ev
 171  }
 172  
 173  func main() {
 174  	var (
 175  		dataDir   = flag.String("data-dir", "", "store parent directory (default temporary)")
 176  		events    = flag.Int("events", 100000, "number of events to seed")
 177  		seed      = flag.Int64("seed", 1, "PRNG seed")
 178  		authors   = flag.Int("authors", 1000, "distinct authors")
 179  		iters     = flag.Int("iterations", 25, "iterations per query scenario")
 180  		duration  = flag.Duration("duration", 5*time.Second, "mixed workload duration")
 181  		readers   = flag.Int("readers", 4, "concurrent readers in mixed workload")
 182  		writers   = flag.Int("writers", 1, "concurrent writers in mixed workload")
 183  		skipSeed  = flag.Bool("skip-seed", false, "reuse an existing database")
 184  		skipMixed = flag.Bool("skip-mixed", false, "skip the mixed workload")
 185  		keep      = flag.Bool("keep", false, "keep the temporary database")
 186  		compact   = flag.Bool("compact", true, "run CompactRuns after queries")
 187  	)
 188  	flag.Parse()
 189  
 190  	if *events < 1 {
 191  		*events = 1
 192  	}
 193  	if *authors < 1 {
 194  		*authors = 1
 195  	}
 196  	if *readers < 1 {
 197  		*readers = 1
 198  	}
 199  	if *writers < 1 {
 200  		*writers = 1
 201  	}
 202  
 203  	dir := *dataDir
 204  	if dir == "" {
 205  		d, err := os.MkdirTemp("", "torly-stress-*")
 206  		if err != nil {
 207  			fatal(err)
 208  		}
 209  		dir = d
 210  	} else if err := os.MkdirAll(dir, 0o755); err != nil {
 211  		fatal(err)
 212  	}
 213  	if !*keep && *dataDir == "" {
 214  		defer os.RemoveAll(dir)
 215  	}
 216  
 217  	dbDir := filepath.Join(dir, "db")
 218  	eng, err := store.Open(dbDir, store.Options{MaxResults: 5000})
 219  	if err != nil {
 220  		fatal(err)
 221  	}
 222  	out := summary{DataDir: dir, SeedEvents: *events, RSSMB: rssMB()}
 223  	g := newGenerator(*seed, *authors)
 224  	now := time.Now().Unix()
 225  	graphSeed := ""
 226  	sampleTag := ""
 227  
 228  	if !*skipSeed {
 229  		fmt.Fprintf(os.Stderr, "seed: %d events, %d authors\n", *events, *authors)
 230  		start := time.Now()
 231  		stored := 0
 232  		var seedIDs [][32]byte
 233  		var graphAuthor string
 234  		for i := 0; i < *events; i++ {
 235  			ev := g.event(i, now)
 236  			seedIDs = append(seedIDs, ev.ID)
 237  			if t, ok := ev.Tags.First("t"); ok {
 238  				sampleTag = t
 239  			}
 240  			if ev.Kind == 3 {
 241  				graphAuthor = nostr.Hex(ev.PubKey[:])
 242  			}
 243  			ok, err := eng.SaveEvent(ev)
 244  			if err != nil {
 245  				fatal(fmt.Errorf("save event %d: %w", i, err))
 246  			}
 247  			if ok {
 248  				stored++
 249  			}
 250  			if (i+1)%10000 == 0 {
 251  				fmt.Fprintf(os.Stderr, "  seeded %d/%d (%s)\n", i+1, *events, time.Since(start).Round(time.Second))
 252  			}
 253  		}
 254  		out.Stored = stored
 255  		g.ids = seedIDs
 256  		graphSeed = graphAuthor
 257  		if sampleTag != "" {
 258  			g.tagVals[0] = sampleTag
 259  		}
 260  		// Large follow lists are deferred; drain them before querying so the
 261  		// stress result includes the graph they create.
 262  		if _, err := eng.ProcessGraphBacklog(0); err != nil {
 263  			fatal(err)
 264  		}
 265  		out.SeedSeconds = time.Since(start).Seconds()
 266  		out.SeedEPS = float64(*events) / out.SeedSeconds
 267  		fmt.Fprintf(os.Stderr, "seed: stored %d in %.1fs (%.0f events/s)\n", stored, out.SeedSeconds, out.SeedEPS)
 268  	}
 269  	out.RSSMB = rssMB()
 270  	out.RunFiles, out.IndexBytes = indexStats(dbDir)
 271  
 272  	// Use real IDs from the generator for point lookups; with -skip-seed the
 273  	// generated events may not exist, so derive them from the newest query.
 274  	sample := g.ids
 275  	if len(sample) == 0 {
 276  		latest, _ := eng.Query(&nostr.Filter{Kinds: []int{1}, Limit: 100})
 277  		if len(latest) == 0 {
 278  			latest, _ = eng.Query(&nostr.Filter{Limit: 100})
 279  		}
 280  		for _, ev := range latest {
 281  			sample = append(sample, ev.ID)
 282  			if t, ok := ev.Tags.First("t"); ok && sampleTag == "" {
 283  				sampleTag = t
 284  			}
 285  		}
 286  		if sampleTag != "" {
 287  			g.tagVals[0] = sampleTag
 288  		}
 289  	}
 290  	if len(sample) > 20 {
 291  		sample = sample[len(sample)-20:]
 292  	}
 293  	author := g.authorHex[len(g.authorHex)/2]
 294  	if graphSeed == "" {
 295  		graphSeed = author
 296  	}
 297  	tagVal := g.tagVals[0]
 298  
 299  	scenarios := []struct {
 300  		name   string
 301  		filter *nostr.Filter
 302  	}{
 303  		{"id", &nostr.Filter{IDs: []string{nostr.Hex(sample[len(sample)-1][:])}, Limit: 1}},
 304  		{"kind1-limit1", &nostr.Filter{Kinds: []int{1}, Limit: 1}},
 305  		{"kind1-limit100", &nostr.Filter{Kinds: []int{1}, Limit: 100}},
 306  		{"kind1-limit5000", &nostr.Filter{Kinds: []int{1}, Limit: 5000}},
 307  		{"author-limit20", &nostr.Filter{Authors: []string{author}, Limit: 20}},
 308  		{"tag-limit20", &nostr.Filter{Tags: map[string][]string{"t": {tagVal}}, Limit: 20}},
 309  		{"search-limit100", &nostr.Filter{Search: "alpha", Limit: 100}},
 310  		{"empty-limit100", &nostr.Filter{Limit: 100}},
 311  	}
 312  	// Warm the caches before recording percentiles.
 313  	for _, sc := range scenarios {
 314  		_, _ = eng.Query(sc.filter)
 315  	}
 316  
 317  	out.Queries = make([]queryResult, 0, len(scenarios))
 318  	for _, sc := range scenarios {
 319  		res := queryResult{Name: sc.name}
 320  		times := make([]time.Duration, 0, *iters)
 321  		for i := 0; i < *iters; i++ {
 322  			t0 := time.Now()
 323  			got, err := eng.Query(sc.filter)
 324  			if err != nil {
 325  				fatal(fmt.Errorf("%s: %w", sc.name, err))
 326  			}
 327  			times = append(times, time.Since(t0))
 328  			res.Events = len(got)
 329  		}
 330  		res.Latency = stats(times)
 331  		out.Queries = append(out.Queries, res)
 332  		fmt.Fprintf(os.Stderr, "query %-18s events=%d p50=%.1fms p95=%.1fms p99=%.1fms\n",
 333  			res.Name, res.Events, res.Latency.P50, res.Latency.P95, res.Latency.P99)
 334  	}
 335  
 336  	// Graph traversal, if there is a seed and enough data.
 337  	if len(g.authorHex) > 0 {
 338  		q := &nostr.GraphQuery{Seed: graphSeed, Depth: 2, Edge: "pp", Direction: "out"}
 339  		if err := q.Validate(); err == nil {
 340  			times := make([]time.Duration, 0, *iters)
 341  			res := queryResult{Name: "graph-pp-depth2"}
 342  			for i := 0; i < *iters; i++ {
 343  				t0 := time.Now()
 344  				got, err := eng.TraverseGraph(q)
 345  				if err != nil {
 346  					break
 347  				}
 348  				times = append(times, time.Since(t0))
 349  				res.Events = got.TotalPubkeys
 350  			}
 351  			if len(times) > 0 {
 352  				res.Latency = stats(times)
 353  				out.Queries = append(out.Queries, res)
 354  				fmt.Fprintf(os.Stderr, "query %-18s pubkeys=%d p50=%.1fms p95=%.1fms\n",
 355  					res.Name, res.Events, res.Latency.P50, res.Latency.P95)
 356  			}
 357  		}
 358  	}
 359  
 360  	if !*skipMixed {
 361  		out.Mixed = runMixed(eng, g, now, *duration, *readers, *writers, int(now)*1000000, *seed)
 362  	}
 363  
 364  	if *compact {
 365  		start := time.Now()
 366  		if err := eng.CompactRuns(); err != nil {
 367  			fatal(fmt.Errorf("compact: %w", err))
 368  		}
 369  		out.CompactMS = float64(time.Since(start).Microseconds()) / 1000
 370  		out.RunFiles, out.IndexBytes = indexStats(dbDir)
 371  		fmt.Fprintf(os.Stderr, "compact: %.0fms, runs=%d\n", out.CompactMS, out.RunFiles)
 372  	}
 373  
 374  	start := time.Now()
 375  	if err := eng.Close(); err != nil {
 376  		fatal(fmt.Errorf("close: %w", err))
 377  	}
 378  	out.CloseMS = float64(time.Since(start).Microseconds()) / 1000
 379  	out.FinalRSSMB = rssMB()
 380  
 381  	start = time.Now()
 382  	eng2, err := store.Open(dbDir, store.Options{MaxResults: 5000})
 383  	if err != nil {
 384  		fatal(fmt.Errorf("reopen: %w", err))
 385  	}
 386  	out.ReopenMS = float64(time.Since(start).Microseconds()) / 1000
 387  	if err := eng2.Close(); err != nil {
 388  		fatal(err)
 389  	}
 390  	fmt.Fprintf(os.Stderr, "close=%.0fms reopen=%.0fms rss=%.0fMB\n", out.CloseMS, out.ReopenMS, out.FinalRSSMB)
 391  
 392  	body, _ := json.MarshalIndent(out, "", "  ")
 393  	fmt.Println(string(body))
 394  }
 395  
 396  func runMixed(eng *store.Engine, g *generator, now int64, dur time.Duration, readers, writers, base int, seed int64) *mixedResult {
 397  	res := &mixedResult{Seconds: dur.Seconds()}
 398  	var saves, saveErr, queries, queryErr int64
 399  	var mu sync.Mutex
 400  	lat := make([]time.Duration, 0, 1024)
 401  	deadline := time.Now().Add(dur)
 402  	scenarios := []*nostr.Filter{
 403  		{Kinds: []int{1}, Limit: 1},
 404  		{Kinds: []int{1}, Limit: 100},
 405  		{Authors: []string{g.authorHex[0]}, Limit: 20},
 406  		{Tags: map[string][]string{"t": {g.tagVals[0]}}, Limit: 20},
 407  	}
 408  	var wg sync.WaitGroup
 409  	for w := 0; w < writers; w++ {
 410  		wg.Add(1)
 411  		go func(w int) {
 412  			defer wg.Done()
 413  			gw := g.clone(seed + int64(w)*7919)
 414  			i := base + w*1000000
 415  			for time.Now().Before(deadline) {
 416  				ev := gw.event(i, now)
 417  				_, err := eng.SaveEvent(ev)
 418  				atomic.AddInt64(&saves, 1)
 419  				if err != nil {
 420  					atomic.AddInt64(&saveErr, 1)
 421  				}
 422  				i++
 423  			}
 424  		}(w)
 425  	}
 426  	for r := 0; r < readers; r++ {
 427  		wg.Add(1)
 428  		go func(r int) {
 429  			defer wg.Done()
 430  			n := 0
 431  			for time.Now().Before(deadline) {
 432  				f := scenarios[(r+n)%len(scenarios)]
 433  				t0 := time.Now()
 434  				_, err := eng.Query(f)
 435  				d := time.Since(t0)
 436  				mu.Lock()
 437  				lat = append(lat, d)
 438  				mu.Unlock()
 439  				atomic.AddInt64(&queries, 1)
 440  				if err != nil {
 441  					atomic.AddInt64(&queryErr, 1)
 442  				}
 443  				n++
 444  			}
 445  		}(r)
 446  	}
 447  	wg.Wait()
 448  	res.Saves = saves
 449  	res.SaveErrors = saveErr
 450  	res.Queries = queries
 451  	res.QueryErrors = queryErr
 452  	res.Latency = stats(lat)
 453  	fmt.Fprintf(os.Stderr, "mixed: %.0fs saves=%d errors=%d queries=%d qerr=%d p50=%.1fms p95=%.1fms\n",
 454  		res.Seconds, res.Saves, res.SaveErrors, res.Queries, res.QueryErrors, res.Latency.P50, res.Latency.P95)
 455  	return res
 456  }
 457  
 458  func stats(times []time.Duration) latencyStats {
 459  	if len(times) == 0 {
 460  		return latencyStats{}
 461  	}
 462  	sort.Slice(times, func(i, j int) bool { return times[i] < times[j] })
 463  	sum := time.Duration(0)
 464  	for _, d := range times {
 465  		sum += d
 466  	}
 467  	at := func(p float64) float64 {
 468  		i := int(float64(len(times)-1) * p)
 469  		return float64(times[i].Microseconds()) / 1000
 470  	}
 471  	return latencyStats{
 472  		Count: len(times),
 473  		Mean:  float64(sum.Microseconds()) / float64(len(times)) / 1000,
 474  		P50:   at(0.50), P95: at(0.95), P99: at(0.99),
 475  		Max: float64(times[len(times)-1].Microseconds()) / 1000,
 476  	}
 477  }
 478  
 479  func indexStats(dbDir string) (runs int, bytes int64) {
 480  	idx := filepath.Join(dbDir, "idx")
 481  	entries, _ := os.ReadDir(idx)
 482  	for _, e := range entries {
 483  		info, err := e.Info()
 484  		if err != nil {
 485  			continue
 486  		}
 487  		bytes += info.Size()
 488  		if strings.Contains(e.Name(), ".buf.") {
 489  			runs++
 490  		}
 491  	}
 492  	return runs, bytes
 493  }
 494  
 495  func rssMB() float64 {
 496  	body, err := os.ReadFile("/proc/self/status")
 497  	if err != nil {
 498  		return 0
 499  	}
 500  	for _, line := range strings.Split(string(body), "\n") {
 501  		if strings.HasPrefix(line, "VmRSS:") {
 502  			f := strings.Fields(line)
 503  			if len(f) >= 2 {
 504  				n, _ := strconv.ParseFloat(f[1], 64)
 505  				return n / 1024
 506  			}
 507  		}
 508  	}
 509  	return 0
 510  }
 511  
 512  func fatal(err error) {
 513  	fmt.Fprintln(os.Stderr, "torly-stress:", err)
 514  	os.Exit(1)
 515  }
 516