Files
orchestra/internal/store/benchmark_test.go
T

61 lines
1.8 KiB
Go

package store
import (
"encoding/json"
"fmt"
"orchestra/internal/authz"
"orchestra/internal/domain"
"sort"
"testing"
"time"
)
// Append includes the fsynced event-log write and sparse projection-cache
// checkpoint. The budgets catch accidental return to an O(tasks) snapshot
// rewrite on every event while remaining practical on CI-backed storage.
const (
appendP95Budget1K = 10 * time.Second
appendP95Budget10K = 90 * time.Second
)
func BenchmarkAppend1K(b *testing.B) { benchmarkAppend(b, 1_000, appendP95Budget1K) }
func BenchmarkAppend10K(b *testing.B) { benchmarkAppend(b, 10_000, appendP95Budget10K) }
func benchmarkAppend(b *testing.B, events int, budget time.Duration) {
b.Helper()
samples := make([]time.Duration, 0, b.N)
b.ResetTimer()
for sample := 0; sample < b.N; sample++ {
b.StopTimer()
s, err := Open(b.TempDir())
if err != nil {
b.Fatal(err)
}
b.StartTimer()
started := time.Now()
for i := 0; i < events; i++ {
id := fmt.Sprintf("task-%d", i)
payload, _ := json.Marshal(map[string]any{"source": "benchmark", "external_id": id, "project": "p"})
if err := s.Append(domain.Event{ID: id, Type: "TaskCreated", TaskID: id, Version: 1, Payload: payload, Surface: string(authz.System)}); err != nil {
b.Fatal(err)
}
}
samples = append(samples, time.Since(started))
b.StopTimer()
}
p95 := appendDurationP95(samples)
b.ReportMetric(float64(p95.Microseconds()), "append_p95_us")
if p95 > budget {
b.Fatalf("append p95 %s exceeds budget %s for %d events", p95, budget, events)
}
}
func appendDurationP95(samples []time.Duration) time.Duration {
if len(samples) == 0 {
return 0
}
sorted := append([]time.Duration(nil), samples...)
sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] })
return sorted[(len(sorted)*95+99)/100-1]
}