// Command torly-stress exercises the torly store engine under a synthetic load. // // It is a database-engine rig, not a relay protocol client: events are built // directly and saved through store.Engine, so signature verification and // WebSocket transport are deliberately excluded from the measurements. package main import ( "encoding/binary" "encoding/json" "flag" "fmt" "math/rand" "os" "path/filepath" "sort" "strconv" "strings" "sync" "sync/atomic" "time" "git.smesh.lol/torly/pkg/nostr" "git.smesh.lol/torly/pkg/store" ) type latencyStats struct { Count int `json:"count"` Mean float64 `json:"mean_ms"` P50 float64 `json:"p50_ms"` P95 float64 `json:"p95_ms"` P99 float64 `json:"p99_ms"` Max float64 `json:"max_ms"` } type queryResult struct { Name string `json:"name"` Events int `json:"events"` Latency latencyStats `json:"latency"` } type mixedResult struct { Seconds float64 `json:"seconds"` Saves int64 `json:"saves"` SaveErrors int64 `json:"save_errors"` Queries int64 `json:"queries"` QueryErrors int64 `json:"query_errors"` Latency latencyStats `json:"query_latency"` } type summary struct { DataDir string `json:"data_dir"` SeedEvents int `json:"seed_events"` Stored int `json:"stored"` SeedSeconds float64 `json:"seed_seconds"` SeedEPS float64 `json:"seed_eps"` RSSMB float64 `json:"rss_mb"` RunFiles int `json:"run_files"` IndexBytes int64 `json:"index_bytes"` Queries []queryResult `json:"queries"` Mixed *mixedResult `json:"mixed,omitempty"` CompactMS float64 `json:"compact_ms"` ReopenMS float64 `json:"reopen_ms"` CloseMS float64 `json:"close_ms"` FinalRSSMB float64 `json:"final_rss_mb"` } type generator struct { rng *rand.Rand authors [][32]byte authorHex []string tagVals []string ids [][32]byte } func newGenerator(seed int64, authors int) *generator { g := &generator{rng: rand.New(rand.NewSource(seed))} for a := 0; a < authors; a++ { var pub [32]byte binary.BigEndian.PutUint64(pub[:8], uint64(a)+0x5354524553530000) for i := 8; i < len(pub); i++ { pub[i] = byte(a*31 + i) } g.authors = append(g.authors, pub) g.authorHex = append(g.authorHex, nostr.Hex(pub[:])) } for i := 0; i < 400; i++ { g.tagVals = append(g.tagVals, "tag"+strconv.Itoa(i)) } return g } func (g *generator) clone(seed int64) *generator { return &generator{ rng: rand.New(rand.NewSource(seed)), authors: g.authors, authorHex: g.authorHex, tagVals: g.tagVals, } } func stressAuthor(i int) string { var p [32]byte binary.BigEndian.PutUint64(p[:8], uint64(i)+0x5354524553530000) for j := 8; j < len(p); j++ { p[j] = byte(i*17 + j) } return nostr.Hex(p[:]) } func (g *generator) event(i int, now int64) *nostr.Event { var id [32]byte binary.BigEndian.PutUint64(id[:8], uint64(i)+1) copy(id[8:], "torly-store-stress-event-id") ev := &nostr.Event{ ID: id, PubKey: g.authors[i%len(g.authors)], CreatedAt: now - 30*24*3600 + int64(i), Kind: 1, Content: "stress event " + strconv.Itoa(i) + " alpha beta gamma delta epsilon", } switch n := g.rng.Intn(100); { case n < 88: ev.Kind = 1 case n < 93: ev.Kind = 7 case n < 94: ev.Kind = 6 case n < 96: ev.Kind = 3 case n < 97: ev.Kind = 1111 case n < 98: ev.Kind = 1059 default: ev.Kind = 0 } // Seed one contact list per author so the graph scenarios always have a // valid seed and at least one outbound edge. if i < len(g.authors) { ev.Kind = 3 } if ev.Kind == 0 { ev.Content = `{"name":"author ` + strconv.Itoa(i%len(g.authors)) + `"}` } tag := g.tagVals[g.rng.Intn(len(g.tagVals))] ev.Tags = nostr.Tags{{"t", tag}} if ev.Kind == 3 { ev.Content = "" follows := 10 if i%1000 == 0 { follows = 600 } for j := 0; j < follows; j++ { ev.Tags = append(ev.Tags, nostr.Tag{"p", stressAuthor(i*1000 + j)}) } } if ev.Kind == 1 || ev.Kind == 7 || ev.Kind == 6 || ev.Kind == 1111 || ev.Kind == 1059 { ev.Tags = append(ev.Tags, nostr.Tag{"p", g.authorHex[g.rng.Intn(len(g.authorHex))]}) } if ev.Kind == 7 || ev.Kind == 6 { ev.Tags = append(ev.Tags, nostr.Tag{"e", nostr.Hex(id[:])}) } // A small fraction have more than 256 tags; those must not enter the graph. if g.rng.Intn(200) == 0 { for j := 0; j < 300; j++ { ev.Tags = append(ev.Tags, nostr.Tag{"x", "bulk-" + strconv.Itoa(j)}) } } return ev } func main() { var ( dataDir = flag.String("data-dir", "", "store parent directory (default temporary)") events = flag.Int("events", 100000, "number of events to seed") seed = flag.Int64("seed", 1, "PRNG seed") authors = flag.Int("authors", 1000, "distinct authors") iters = flag.Int("iterations", 25, "iterations per query scenario") duration = flag.Duration("duration", 5*time.Second, "mixed workload duration") readers = flag.Int("readers", 4, "concurrent readers in mixed workload") writers = flag.Int("writers", 1, "concurrent writers in mixed workload") skipSeed = flag.Bool("skip-seed", false, "reuse an existing database") skipMixed = flag.Bool("skip-mixed", false, "skip the mixed workload") keep = flag.Bool("keep", false, "keep the temporary database") compact = flag.Bool("compact", true, "run CompactRuns after queries") ) flag.Parse() if *events < 1 { *events = 1 } if *authors < 1 { *authors = 1 } if *readers < 1 { *readers = 1 } if *writers < 1 { *writers = 1 } dir := *dataDir if dir == "" { d, err := os.MkdirTemp("", "torly-stress-*") if err != nil { fatal(err) } dir = d } else if err := os.MkdirAll(dir, 0o755); err != nil { fatal(err) } if !*keep && *dataDir == "" { defer os.RemoveAll(dir) } dbDir := filepath.Join(dir, "db") eng, err := store.Open(dbDir, store.Options{MaxResults: 5000}) if err != nil { fatal(err) } out := summary{DataDir: dir, SeedEvents: *events, RSSMB: rssMB()} g := newGenerator(*seed, *authors) now := time.Now().Unix() graphSeed := "" sampleTag := "" if !*skipSeed { fmt.Fprintf(os.Stderr, "seed: %d events, %d authors\n", *events, *authors) start := time.Now() stored := 0 var seedIDs [][32]byte var graphAuthor string for i := 0; i < *events; i++ { ev := g.event(i, now) seedIDs = append(seedIDs, ev.ID) if t, ok := ev.Tags.First("t"); ok { sampleTag = t } if ev.Kind == 3 { graphAuthor = nostr.Hex(ev.PubKey[:]) } ok, err := eng.SaveEvent(ev) if err != nil { fatal(fmt.Errorf("save event %d: %w", i, err)) } if ok { stored++ } if (i+1)%10000 == 0 { fmt.Fprintf(os.Stderr, " seeded %d/%d (%s)\n", i+1, *events, time.Since(start).Round(time.Second)) } } out.Stored = stored g.ids = seedIDs graphSeed = graphAuthor if sampleTag != "" { g.tagVals[0] = sampleTag } // Large follow lists are deferred; drain them before querying so the // stress result includes the graph they create. if _, err := eng.ProcessGraphBacklog(0); err != nil { fatal(err) } out.SeedSeconds = time.Since(start).Seconds() out.SeedEPS = float64(*events) / out.SeedSeconds fmt.Fprintf(os.Stderr, "seed: stored %d in %.1fs (%.0f events/s)\n", stored, out.SeedSeconds, out.SeedEPS) } out.RSSMB = rssMB() out.RunFiles, out.IndexBytes = indexStats(dbDir) // Use real IDs from the generator for point lookups; with -skip-seed the // generated events may not exist, so derive them from the newest query. sample := g.ids if len(sample) == 0 { latest, _ := eng.Query(&nostr.Filter{Kinds: []int{1}, Limit: 100}) if len(latest) == 0 { latest, _ = eng.Query(&nostr.Filter{Limit: 100}) } for _, ev := range latest { sample = append(sample, ev.ID) if t, ok := ev.Tags.First("t"); ok && sampleTag == "" { sampleTag = t } } if sampleTag != "" { g.tagVals[0] = sampleTag } } if len(sample) > 20 { sample = sample[len(sample)-20:] } author := g.authorHex[len(g.authorHex)/2] if graphSeed == "" { graphSeed = author } tagVal := g.tagVals[0] scenarios := []struct { name string filter *nostr.Filter }{ {"id", &nostr.Filter{IDs: []string{nostr.Hex(sample[len(sample)-1][:])}, Limit: 1}}, {"kind1-limit1", &nostr.Filter{Kinds: []int{1}, Limit: 1}}, {"kind1-limit100", &nostr.Filter{Kinds: []int{1}, Limit: 100}}, {"kind1-limit5000", &nostr.Filter{Kinds: []int{1}, Limit: 5000}}, {"author-limit20", &nostr.Filter{Authors: []string{author}, Limit: 20}}, {"tag-limit20", &nostr.Filter{Tags: map[string][]string{"t": {tagVal}}, Limit: 20}}, {"search-limit100", &nostr.Filter{Search: "alpha", Limit: 100}}, {"empty-limit100", &nostr.Filter{Limit: 100}}, } // Warm the caches before recording percentiles. for _, sc := range scenarios { _, _ = eng.Query(sc.filter) } out.Queries = make([]queryResult, 0, len(scenarios)) for _, sc := range scenarios { res := queryResult{Name: sc.name} times := make([]time.Duration, 0, *iters) for i := 0; i < *iters; i++ { t0 := time.Now() got, err := eng.Query(sc.filter) if err != nil { fatal(fmt.Errorf("%s: %w", sc.name, err)) } times = append(times, time.Since(t0)) res.Events = len(got) } res.Latency = stats(times) out.Queries = append(out.Queries, res) fmt.Fprintf(os.Stderr, "query %-18s events=%d p50=%.1fms p95=%.1fms p99=%.1fms\n", res.Name, res.Events, res.Latency.P50, res.Latency.P95, res.Latency.P99) } // Graph traversal, if there is a seed and enough data. if len(g.authorHex) > 0 { q := &nostr.GraphQuery{Seed: graphSeed, Depth: 2, Edge: "pp", Direction: "out"} if err := q.Validate(); err == nil { times := make([]time.Duration, 0, *iters) res := queryResult{Name: "graph-pp-depth2"} for i := 0; i < *iters; i++ { t0 := time.Now() got, err := eng.TraverseGraph(q) if err != nil { break } times = append(times, time.Since(t0)) res.Events = got.TotalPubkeys } if len(times) > 0 { res.Latency = stats(times) out.Queries = append(out.Queries, res) fmt.Fprintf(os.Stderr, "query %-18s pubkeys=%d p50=%.1fms p95=%.1fms\n", res.Name, res.Events, res.Latency.P50, res.Latency.P95) } } } if !*skipMixed { out.Mixed = runMixed(eng, g, now, *duration, *readers, *writers, int(now)*1000000, *seed) } if *compact { start := time.Now() if err := eng.CompactRuns(); err != nil { fatal(fmt.Errorf("compact: %w", err)) } out.CompactMS = float64(time.Since(start).Microseconds()) / 1000 out.RunFiles, out.IndexBytes = indexStats(dbDir) fmt.Fprintf(os.Stderr, "compact: %.0fms, runs=%d\n", out.CompactMS, out.RunFiles) } start := time.Now() if err := eng.Close(); err != nil { fatal(fmt.Errorf("close: %w", err)) } out.CloseMS = float64(time.Since(start).Microseconds()) / 1000 out.FinalRSSMB = rssMB() start = time.Now() eng2, err := store.Open(dbDir, store.Options{MaxResults: 5000}) if err != nil { fatal(fmt.Errorf("reopen: %w", err)) } out.ReopenMS = float64(time.Since(start).Microseconds()) / 1000 if err := eng2.Close(); err != nil { fatal(err) } fmt.Fprintf(os.Stderr, "close=%.0fms reopen=%.0fms rss=%.0fMB\n", out.CloseMS, out.ReopenMS, out.FinalRSSMB) body, _ := json.MarshalIndent(out, "", " ") fmt.Println(string(body)) } func runMixed(eng *store.Engine, g *generator, now int64, dur time.Duration, readers, writers, base int, seed int64) *mixedResult { res := &mixedResult{Seconds: dur.Seconds()} var saves, saveErr, queries, queryErr int64 var mu sync.Mutex lat := make([]time.Duration, 0, 1024) deadline := time.Now().Add(dur) scenarios := []*nostr.Filter{ {Kinds: []int{1}, Limit: 1}, {Kinds: []int{1}, Limit: 100}, {Authors: []string{g.authorHex[0]}, Limit: 20}, {Tags: map[string][]string{"t": {g.tagVals[0]}}, Limit: 20}, } var wg sync.WaitGroup for w := 0; w < writers; w++ { wg.Add(1) go func(w int) { defer wg.Done() gw := g.clone(seed + int64(w)*7919) i := base + w*1000000 for time.Now().Before(deadline) { ev := gw.event(i, now) _, err := eng.SaveEvent(ev) atomic.AddInt64(&saves, 1) if err != nil { atomic.AddInt64(&saveErr, 1) } i++ } }(w) } for r := 0; r < readers; r++ { wg.Add(1) go func(r int) { defer wg.Done() n := 0 for time.Now().Before(deadline) { f := scenarios[(r+n)%len(scenarios)] t0 := time.Now() _, err := eng.Query(f) d := time.Since(t0) mu.Lock() lat = append(lat, d) mu.Unlock() atomic.AddInt64(&queries, 1) if err != nil { atomic.AddInt64(&queryErr, 1) } n++ } }(r) } wg.Wait() res.Saves = saves res.SaveErrors = saveErr res.Queries = queries res.QueryErrors = queryErr res.Latency = stats(lat) fmt.Fprintf(os.Stderr, "mixed: %.0fs saves=%d errors=%d queries=%d qerr=%d p50=%.1fms p95=%.1fms\n", res.Seconds, res.Saves, res.SaveErrors, res.Queries, res.QueryErrors, res.Latency.P50, res.Latency.P95) return res } func stats(times []time.Duration) latencyStats { if len(times) == 0 { return latencyStats{} } sort.Slice(times, func(i, j int) bool { return times[i] < times[j] }) sum := time.Duration(0) for _, d := range times { sum += d } at := func(p float64) float64 { i := int(float64(len(times)-1) * p) return float64(times[i].Microseconds()) / 1000 } return latencyStats{ Count: len(times), Mean: float64(sum.Microseconds()) / float64(len(times)) / 1000, P50: at(0.50), P95: at(0.95), P99: at(0.99), Max: float64(times[len(times)-1].Microseconds()) / 1000, } } func indexStats(dbDir string) (runs int, bytes int64) { idx := filepath.Join(dbDir, "idx") entries, _ := os.ReadDir(idx) for _, e := range entries { info, err := e.Info() if err != nil { continue } bytes += info.Size() if strings.Contains(e.Name(), ".buf.") { runs++ } } return runs, bytes } func rssMB() float64 { body, err := os.ReadFile("/proc/self/status") if err != nil { return 0 } for _, line := range strings.Split(string(body), "\n") { if strings.HasPrefix(line, "VmRSS:") { f := strings.Fields(line) if len(f) >= 2 { n, _ := strconv.ParseFloat(f[1], 64) return n / 1024 } } } return 0 } func fatal(err error) { fmt.Fprintln(os.Stderr, "torly-stress:", err) os.Exit(1) }