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
+36 -2
View File
@@ -22,6 +22,7 @@ import (
"runtime"
"sort"
"strings"
"sync"
"syscall"
"time"
@@ -76,6 +77,7 @@ type sim struct {
extra []libp2p.Option // transport conditions (latency, connection loss)
timeout time.Duration
made []*listing.Listing
mu sync.Mutex // guards nodes against the sampler
seedConns int // raised connection limit of the seeds; 0 keeps libp2p's default
}
@@ -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
}
+22
View File
@@ -621,6 +621,28 @@ packet loss looks like above TCP), `-hostile` (an attacker with no validators),
| all seeds shut down | the network keeps working (329 of 329 listings); newcomers that remember two live peers of their own region got everything (160 of 160) |
| 300 nodes, 8 regions | 100% delivered (listings p95 75 ms, messages p95 0.8 s, reports p95 0.5 s), all agreed; 1.3 GB heap, 100k goroutines, 137 KB per node |
**How large a network can it carry?** `scripts/sim-sweep.sh` runs growing
networks (8 regions, 3 seeds, 30 listings, 20 messages, 3 reports, 10% churn)
and records each as JSON in `.tmp/sim/`; `scripts/sim-report.mjs` turns them
into the tables behind the graphs. Result on a 16 GB, 8-core machine:
| Nodes | Seed limit lifted | libp2p default limit |
|---|---|---|
| 100 | complete in 3.5 s, 100% delivered | complete in 3.2 s, 100% |
| 200 | 6.1 s, 100% (p95 50 ms) | **never completed**: 12 nodes without any peer, 91.8% delivered |
| 300 | 9.5 s, 100% (p95 75 ms) | 112 nodes without a peer, 43% delivered |
| 400 | 14 s, 100% (p95 97 ms) | 212 nodes without a peer, 16% delivered |
| 600 | 24 s, 100% (p95 111 ms) | not run |
With the limit lifted, delivery stayed at 100% and agreement held up to 600
nodes; time to form the mesh grows roughly with the square of the network
size (3.5 s at 100, 24 s at 600), and so does the simulator's cost (2.5 GB
heap, 230k goroutines, 255 CPU-seconds at 600). That cost is the sum of all the
nodes sharing one machine, so it measures the limit of the simulation as much
as of the protocol; 800 nodes was left out to avoid exhausting memory. With
the default limit the network stops working where the seeds run out of
inbound connections (three seeds hold about 187 each).
Findings (nothing here is fixed yet; see "What is left" in SPECS.md):
1. **Connection limit on the bootstrap node.** libp2p's resource manager caps
+102
View File
@@ -0,0 +1,102 @@
// Turns the JSON files of scripts/sim-sweep.sh (and allmende-sim -json) into
// the tables the graphs are drawn from: .tmp/sim/data/{scaling,timeline,phases,arrival}.json
//
// node scripts/sim-report.mjs [dir] # default dir: .tmp/sim
import { readdirSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { join } from "node:path";
const dir = process.argv[2] ?? ".tmp/sim";
const out = join(dir, "data");
mkdirSync(out, { recursive: true });
const pct = (ms, q) => (ms.length ? ms[Math.min(ms.length - 1, Math.floor(q * ms.length))] : null);
const r1 = (x) => (x == null ? null : Math.round(x * 10) / 10);
const runs = readdirSync(dir)
.filter((f) => f.endsWith(".json"))
.map((f) => ({ name: f.replace(/\.json$/, ""), ...JSON.parse(readFileSync(join(dir, f), "utf8")) }))
.sort((a, b) => a.meta.nodes - b.meta.nodes);
const scaling = [];
for (const r of runs) {
const m = r.meta;
const s = r.samples;
const last = s[s.length - 1] ?? {};
// a series nothing arrived in has no list of times (null)
const get = (k) => ({ sent: 0, ...r.series[k], ms: r.series[k]?.ms ?? [] });
const lst = get("listing");
const msg = get("message");
const rep = get("report");
const rej = get("rejoin");
const alone = /(\d+) of them have no peer at all/.exec(m.mesh ?? "");
scaling.push({
run: r.name,
limit: m.seed_conns > 0 ? "lifted" : "libp2p default",
nodes: m.nodes,
mesh_s: r1(m.mesh_s),
mesh_complete: m.mesh_complete,
nodes_without_peers: alone ? Number(alone[1]) : 0,
listing_delivered_pct: lst.sent ? r1((100 * lst.ms.length) / lst.sent) : null,
listing_p50_ms: r1(pct(lst.ms, 0.5)),
listing_p95_ms: r1(pct(lst.ms, 0.95)),
listing_p99_ms: r1(pct(lst.ms, 0.99)),
message_delivered_pct: msg.sent ? r1((100 * msg.ms.length) / msg.sent) : null,
message_p95_ms: r1(pct(msg.ms, 0.95)),
report_delivered_pct: rep.sent ? r1((100 * rep.ms.length) / rep.sent) : null,
report_p95_ms: r1(pct(rep.ms, 0.95)),
rejoin_p95_ms: r1(pct(rej.ms, 0.95)),
agreed: /identical listings/.test(m.agreement ?? ""),
heap_peak_mb: r1(Math.max(0, ...s.map((x) => x.heap_mb))),
goroutines_peak: Math.max(0, ...s.map((x) => x.goroutines)),
cpu_seconds: r1(last.cpu_s),
traffic_mb: r1(last.sent_mb),
traffic_kb_per_node: last.sent_mb ? r1((last.sent_mb * 1024) / m.nodes) : null,
duration_s: r1(last.t),
});
}
writeFileSync(join(out, "scaling.json"), JSON.stringify(scaling));
// per-second series of the runs worth looking at over time: the smallest, a middle one and the largest of each limit
const pick = new Set();
for (const limit of ["lifted", "libp2p default"]) {
const rs = scaling.filter((x) => x.limit === limit);
if (rs.length) {
pick.add(rs[0].run);
pick.add(rs[Math.floor(rs.length / 2)].run);
pick.add(rs[rs.length - 1].run);
}
}
const timeline = [];
const phases = [];
for (const r of runs.filter((x) => pick.has(x.name))) {
const s = r.samples;
for (let i = 0; i < s.length; i++) {
const dt = i ? s[i].t - s[i - 1].t : 1;
timeline.push({
run: r.name,
t: r1(s[i].t),
heap_mb: r1(s[i].heap_mb),
goroutines: s[i].goroutines,
cpu_cores: i ? r1((s[i].cpu_s - s[i - 1].cpu_s) / dt) : 0,
sent_mb_per_s: i ? Math.round(((s[i].sent_mb - s[i - 1].sent_mb) / dt) * 100) / 100 : 0,
});
}
for (const p of r.phases) phases.push({ run: r.name, name: p.name, from: r1(p.from), to: r1(p.to) });
}
writeFileSync(join(out, "timeline.json"), JSON.stringify(timeline));
writeFileSync(join(out, "phases.json"), JSON.stringify(phases));
// how listings arrive: the share of deliveries done after x milliseconds, 40 points per run
const arrival = [];
for (const r of runs) {
const lst = r.series.listing;
if (!lst || !lst.ms?.length) continue;
for (let i = 1; i <= 40; i++) {
const q = i / 40;
arrival.push({ run: r.name, nodes: r.meta.nodes, limit: r.meta.seed_conns > 0 ? "lifted" : "libp2p default", ms: r1(pct(lst.ms, q - 1e-9)), share: Math.round(((q * lst.ms.length) / lst.sent) * 1000) / 10 });
}
}
writeFileSync(join(out, "arrival.json"), JSON.stringify(arrival));
console.log(`${runs.length} runs: scaling ${scaling.length} rows, timeline ${timeline.length} rows (${[...pick].join(", ")}), arrival ${arrival.length} rows`);
console.table(scaling.map((x) => ({ run: x.run, mesh_s: x.mesh_s, ok: x.mesh_complete, alone: x.nodes_without_peers, lst_pct: x.listing_delivered_pct, lst_p95: x.listing_p95_ms, heapMB: x.heap_peak_mb, gor: x.goroutines_peak, cpu_s: x.cpu_seconds, kb_node: x.traffic_kb_per_node })));
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env bash
# How large a network can the protocol carry? Runs allmende-sim at growing sizes
# and records every run as JSON in .tmp/sim/ (see scripts/sim-report.mjs for the graphs).
#
# scripts/sim-sweep.sh # the default sweep
# SIZES="100 200" LIMITED="200" scripts/sim-sweep.sh
#
# SIZES run with the seeds' connection limit lifted; LIMITED run again with
# libp2p's default limit (about 190 inbound connections on 16 GB of RAM).
cd "$(dirname "$0")/.." || exit 1
OUT=.tmp/sim
mkdir -p "$OUT"
go build -o .tmp/allmende-sim ./cmd/allmende-sim || exit 1
SIZES=${SIZES:-"50 100 200 300 400 600 800"}
LIMITED=${LIMITED:-"100 200 300 400"}
run() { # run NODES SEEDCONNS LABEL
local n=$1 conns=$2 label=$3
local regions=8; [ "$n" -lt 100 ] && regions=3
echo "== $label: $n nodes, seed limit ${conns:-default}"
.tmp/allmende-sim -nodes "$n" -regions $regions -seeds 3 -listings 30 -messages 20 -reports 3 -churn 0.1 \
-timeout 60s ${conns:+-seed-conns $conns} -json "$OUT/$label.json" > "$OUT/$label.txt" 2>&1
local code=$?
grep "^ mesh\|^ listing\|^ report \|^ message " "$OUT/$label.txt" | cut -c1-200
[ $code -ne 0 ] && echo " exit code $code (see $OUT/$label.txt)"
return 0
}
for n in $SIZES; do run "$n" 5000 "lifted-$n"; done
for n in $LIMITED; do run "$n" "" "default-$n"; done
echo "done: $(ls $OUT/*.json | wc -l) runs in $OUT"