allmende-sim: record runs as JSON (samples, phases, arrival times); sweep script and graph data; scaling results

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
2026-11-18 22:23:33 +01:00
co-authored by Claude Sonnet 5.5
parent 5db90c2720
commit 130ba5dc65
6 changed files with 321 additions and 3 deletions
+37 -3
View File
@@ -22,6 +22,7 @@ import (
"runtime"
"sort"
"strings"
"sync"
"syscall"
"time"
@@ -76,7 +77,8 @@ type sim struct {
extra []libp2p.Option // transport conditions (latency, connection loss)
timeout time.Duration
made []*listing.Listing
seedConns int // raised connection limit of the seeds; 0 keeps libp2p's default
mu sync.Mutex // guards nodes against the sampler
seedConns int // raised connection limit of the seeds; 0 keeps libp2p's default
}
func main() {
@@ -94,6 +96,7 @@ func main() {
latency := flag.Duration("latency", 0, "delay added to every write on connections a node dials (one direction), with up to 50% jitter")
lifetime := flag.Duration("lifetime", 0, "mean lifetime of a dialed connection before it is cut (0: never); redials and resyncs follow")
seedConns := flag.Int("seed-conns", 0, "raise the seeds' inbound connection limit to this many (0: libp2p's default, which scales with RAM)")
jsonOut := flag.String("json", "", "write the run (samples every second, phases, arrival times) to this JSON file, for graphs")
hostile := flag.Bool("hostile", false, "also run attackers: invalid listings, a message flood")
killSeeds := flag.Bool("kill-seeds", false, "also shut the seeds down and see what the network and newcomers do")
repair := flag.Bool("repair", false, "also test anti-entropy: a listing only one node has, nobody told (set -anti-entropy to a few seconds)")
@@ -115,7 +118,11 @@ func main() {
s.extra = conditions.options()
}
regions := allRegions[:*nregions]
report0 := newReport()
rec := newRecorder()
report0 := newReport(rec)
stopSampling := make(chan struct{})
go rec.run(s, stopSampling)
report0.phase("start")
// --- start the network ---------------------------------------------------
fmt.Printf("starting %d nodes (%d seeds), %d regions ...\n", *nodes, *seeds, *nregions)
@@ -131,7 +138,9 @@ func main() {
}
}
s.must(s.makeIdentity(n))
s.mu.Lock()
s.nodes = append(s.nodes, n)
s.mu.Unlock()
s.must(s.start(n))
if n.seed {
s.seedAddrs = append(s.seedAddrs, n.node.Addrs()[0])
@@ -140,11 +149,14 @@ func main() {
startup := time.Since(t0)
report0.row("start", fmt.Sprintf("%d nodes started in %s", *nodes, round(startup)))
report0.phase("mesh")
formed := s.waitFormed(regions, *timeout)
meshSeconds := time.Since(t0).Seconds()
report0.row("mesh", fmt.Sprintf("every node knows regional peers after %s (%s)", round(time.Since(t0)), formed))
report0.resources("after start", s)
// --- listings ------------------------------------------------------------
report0.phase("listings")
fmt.Printf("publishing %d listings at %.0f/s ...\n", *listings, *rate)
var made []*listing.Listing
var pairs []*pair
@@ -170,6 +182,7 @@ func main() {
report0.resources("after listings", s)
// --- messages ------------------------------------------------------------
report0.phase("messages")
fmt.Printf("sending %d buyer messages ...\n", *messages)
pairs = nil
refused := 0
@@ -197,6 +210,7 @@ func main() {
report0.latency("message", "from a random node of the region to the listing's owner", res)
// --- reports -------------------------------------------------------------
report0.phase("reports")
fmt.Printf("publishing %d abuse reports ...\n", *reports)
pairs = nil
var reps []*report.Report
@@ -226,6 +240,7 @@ func main() {
// --- churn ---------------------------------------------------------------
down := s.pickDown(int(float64(*nodes) * *churn))
if len(down) > 0 {
report0.phase("churn")
fmt.Printf("taking %d nodes offline, publishing 10 more listings, bringing them back ...\n", len(down))
for _, n := range down {
_ = n.node.Close() // the store (and so what it already knew) stays, as on a real machine
@@ -276,6 +291,17 @@ func main() {
report0.row("agreement", s.agreement(regions))
report0.resources("at the end", s)
report0.print(os.Stdout)
close(stopSampling)
if *jsonOut != "" {
meta := map[string]any{
"nodes": *nodes, "regions": *nregions, "seeds": *seeds, "seed_conns": *seedConns,
"latency_ms": latency.Milliseconds(), "lifetime_s": lifetime.Seconds(),
"mesh_s": meshSeconds, "mesh_complete": formed == "complete", "mesh": formed,
"agreement": s.agreement(regions), "date": time.Now().Format(time.RFC3339),
}
must(rec.write(*jsonOut, meta))
fmt.Println("recorded to", *jsonOut)
}
for _, n := range s.nodes {
if n.node != nil {
@@ -568,18 +594,26 @@ func await(pairs []*pair, timeout time.Duration) []*pair {
}
type reportTable struct {
rec *recorder
rows [][2]string
res []string
}
func newReport() *reportTable { return &reportTable{} }
func newReport(rec *recorder) *reportTable { return &reportTable{rec: rec} }
// phase marks where a part of the run begins, for the graphs.
func (r *reportTable) phase(name string) { r.rec.phase(name) }
func (r *reportTable) row(k, v string) {
r.rows = append(r.rows, [2]string{k, v})
r.rec.mu.Lock()
r.rec.rows[k] = v
r.rec.mu.Unlock()
fmt.Printf(" %-10s %s\n", k, v) // live, so a crash later does not lose it
}
func (r *reportTable) latency(k, what string, ps []*pair) {
r.rec.addSeries(k, what, ps)
var d []time.Duration
for _, p := range ps {
if p.done {
+123
View File
@@ -0,0 +1,123 @@
package main
// Recording of a run for graphs: a sample of the whole process every second,
// where each phase begins and ends, and how long each thing took to arrive.
import (
"encoding/json"
"os"
"runtime"
"sort"
"sync"
"syscall"
"time"
)
type sample struct {
T float64 `json:"t"` // seconds since the run began
HeapMB float64 `json:"heap_mb"`
Goroutines int `json:"goroutines"`
CPUSeconds float64 `json:"cpu_s"` // all nodes together, cumulative
SentMB float64 `json:"sent_mb"` // all nodes together, cumulative
Nodes int `json:"nodes_live"` // nodes that are up
}
type phaseSpan struct {
Name string `json:"name"`
From float64 `json:"from"`
To float64 `json:"to"`
}
// series is how long each of a kind of thing took to arrive; things that never
// arrived are counted in Sent only.
type series struct {
What string `json:"what"`
Sent int `json:"sent"`
Ms []float64 `json:"ms"` // sorted
At float64 `json:"at"` // seconds into the run when they were sent (first)
}
type recorder struct {
mu sync.Mutex
t0 time.Time
phases []phaseSpan
samples []sample
series map[string]*series
rows map[string]string
}
func newRecorder() *recorder {
return &recorder{t0: time.Now(), series: map[string]*series{}, rows: map[string]string{}}
}
func (r *recorder) now() float64 { return time.Since(r.t0).Seconds() }
// phase ends the running phase and begins a new one.
func (r *recorder) phase(name string) {
r.mu.Lock()
defer r.mu.Unlock()
t := r.now()
if n := len(r.phases); n > 0 {
r.phases[n-1].To = t
}
r.phases = append(r.phases, phaseSpan{Name: name, From: t, To: t})
}
func (r *recorder) addSeries(key, what string, ps []*pair) {
r.mu.Lock()
defer r.mu.Unlock()
sr := &series{What: what, Sent: len(ps), At: r.now()}
for _, p := range ps {
if p.done {
sr.Ms = append(sr.Ms, float64(p.took.Microseconds())/1000)
}
}
sort.Float64s(sr.Ms)
r.series[key] = sr
}
// run samples the process every second until stop is closed.
func (r *recorder) run(s *sim, stop <-chan struct{}) {
tick := time.NewTicker(time.Second)
defer tick.Stop()
for {
select {
case <-stop:
return
case <-tick.C:
}
var m runtime.MemStats
runtime.ReadMemStats(&m)
var ru syscall.Rusage
_ = syscall.Getrusage(syscall.RUSAGE_SELF, &ru)
var sent int64
live := 0
s.mu.Lock()
for _, n := range s.nodes {
sent += n.bw.GetBandwidthTotals().TotalOut
live++
}
s.mu.Unlock()
r.mu.Lock()
r.samples = append(r.samples, sample{
T: r.now(), HeapMB: float64(m.HeapAlloc) / (1 << 20), Goroutines: runtime.NumGoroutine(),
CPUSeconds: float64(ru.Utime.Nano()+ru.Stime.Nano()) / 1e9, SentMB: float64(sent) / (1 << 20), Nodes: live,
})
r.mu.Unlock()
}
}
// write saves the run as JSON.
func (r *recorder) write(path string, meta map[string]any) error {
r.mu.Lock()
defer r.mu.Unlock()
if n := len(r.phases); n > 0 {
r.phases[n-1].To = r.now()
}
out := map[string]any{"meta": meta, "phases": r.phases, "samples": r.samples, "series": r.series, "rows": r.rows}
b, err := json.Marshal(out)
if err != nil {
return err
}
return os.WriteFile(path, b, 0o644)
}
+5
View File
@@ -162,6 +162,7 @@ func (s *sim) totalListings() int {
// that honest traffic still gets through, and what the flood costs a sender.
func (s *sim) hostile(regions []string, rep *reportTable) {
region := regions[0]
rep.phase("attack")
fmt.Printf("attacking region %s: forged listings and a message flood ...\n", region)
pool := s.followers(region)
targets := pool[:min(10, len(pool))]
@@ -318,6 +319,7 @@ func (s *sim) hostile(regions []string, rep *reportTable) {
// repair puts listings into one node's store and tells nobody. Only
// anti-entropy (or a new connection's sync) can carry them to the region.
func (s *sim) repair(rep *reportTable) {
rep.phase("repair")
fmt.Println("anti-entropy: listings only one node has ...")
var pairs []*pair
for i := 0; i < 5; i++ {
@@ -340,6 +342,7 @@ func (s *sim) repair(rep *reportTable) {
// --- the seeds go away -----------------------------------------------------------------------
func (s *sim) killSeeds(regions []string, rep *reportTable) {
rep.phase("seeds down")
fmt.Println("shutting down the seeds ...")
for _, n := range s.nodes {
if n.seed && n.node != nil {
@@ -421,7 +424,9 @@ func (s *sim) killSeeds(regions []string, rep *reportTable) {
func (s *sim) spawn(regions, bootstrap []string) *simNode {
n := &simNode{idx: len(s.nodes), regions: regions, bootstrap: bootstrap}
s.must(s.makeIdentity(n))
s.mu.Lock()
s.nodes = append(s.nodes, n)
s.mu.Unlock()
s.must(s.start(n))
return n
}