-
Notifications
You must be signed in to change notification settings - Fork 235
Expand file tree
/
Copy pathtempo.nu
More file actions
executable file
·2145 lines (1885 loc) · 85.3 KB
/
tempo.nu
File metadata and controls
executable file
·2145 lines (1885 loc) · 85.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env nu
# Tempo local utilities
const BENCH_DIR = "contrib/bench"
const LOCALNET_DIR = "localnet"
const LOGS_DIR = "contrib/bench/logs"
const RUSTFLAGS = "-C target-cpu=native"
const DEFAULT_PROFILE = "profiling"
const DEFAULT_FEATURES = "jemalloc,asm-keccak"
const BENCH_WORKTREES_DIR = ".bench-worktrees"
const BENCH_RESULTS_DIR = "bench-results"
const BLOAT_MNEMONIC = "test test test test test test test test test test test junk"
const METRICS_PROXY_SCRIPT = "contrib/bench/bench-metrics-proxy.py"
const METRICS_LABELS_FILE = "/tmp/bench-metrics-labels.json"
const MINIO_BUCKET = "minio/tempo-binaries"
const BENCH_META_SUBDIR = ".bench-meta"
# Preset weight configurations: [tip20, erc20, swap, order]
const PRESETS = {
tip20: [1.0, 0.0, 0.0, 0.0],
erc20: [0.0, 1.0, 0.0, 0.0],
swap: [0.0, 0.0, 1.0, 0.0],
order: [0.0, 0.0, 0.0, 1.0],
"tempo-mix": [0.8, 0, 0.19, 0.01]
}
# TIP20 token IDs created by localnet genesis (pathUSD, AlphaUSD, BetaUSD, ThetaUSD)
const TIP20_TOKEN_IDS = [0, 1, 2, 3]
# ============================================================================
# Helper functions
# ============================================================================
# Convert consensus port to node index (e.g., 8000 -> 0, 8100 -> 1)
def port-to-node-index [port: int] {
($port - 8000) / 100 | into int
}
# Build log filter args based on --loud flag
def log-filter-args [loud: bool] {
if $loud { [] } else { ["--log.stdout.filter" "warn"] }
}
# Wrap command with samply if enabled
def wrap-samply [cmd: list<string>, samply: bool, samply_args: list<string>] {
if $samply {
["samply" "record" ...$samply_args "--" ...$cmd]
} else {
$cmd
}
}
# Validate mode is either "dev" or "consensus"
def validate-mode [mode: string] {
if $mode != "dev" and $mode != "consensus" {
print $"Unknown mode: ($mode). Use 'dev' or 'consensus'."
exit 1
}
}
# Build tempo binary with cargo
def build-tempo [bins: list<string>, profile: string, features: string] {
let bin_args = ($bins | each { |bin| ["--bin" $bin] } | flatten)
let build_cmd = ["cargo" "build" "--profile" $profile "--features" $features] | append $bin_args
print $"Building ($bins | str join ', '): `($build_cmd | str join ' ')`..."
with-env { RUSTFLAGS: $RUSTFLAGS } {
run-external ($build_cmd | first) ...($build_cmd | skip 1)
}
}
# Find tempo process PIDs (excluding tempo-bench)
def find-tempo-pids [] {
ps | where name =~ "tempo" | where name !~ "tempo-bench" | get pid
}
# Initialize node with state bloat
# 1. Run `tempo init` to create the database
# 2. Generate state bloat binary file
# 3. Run `tempo init-from-binary-dump` to load the bloat
# Generate the bloat binary file once (skips if already exists)
def generate-bloat-file [bloat_size: int, profile: string] {
let bloat_file = $"($LOCALNET_DIR)/state_bloat.bin"
if ($bloat_file | path exists) {
print $"State bloat file already exists \(($bloat_size) MiB\)"
return
}
print $"Generating state bloat \(($bloat_size) MiB\)..."
let token_args = ($TIP20_TOKEN_IDS | each { |id| ["--token" $"($id)"] } | flatten)
cargo run -p tempo-xtask --profile $profile -- generate-state-bloat --size $bloat_size --out $bloat_file ...$token_args
}
# Load the bloat file into a single node's database
def load-bloat-into-node [tempo_bin: string, genesis_path: string, datadir: string] {
let bloat_file = $"($LOCALNET_DIR)/state_bloat.bin"
let db_path = $"($datadir)/db"
# Skip if this node already has a database with bloat loaded
if ($db_path | path exists) {
print $"State bloat already loaded into ($datadir | path basename)"
return
}
# Remove existing reth database files while preserving key files (signing.key, signing.share, etc.)
if ($datadir | path exists) {
for subdir in [db static_files rocksdb consensus invalid_block_hooks] {
let path = $"($datadir)/($subdir)"
if ($path | path exists) { rm -rf $path }
}
for file in [reth.toml jwt.hex] {
let path = $"($datadir)/($file)"
if ($path | path exists) { rm $path }
}
}
print $"Initializing ($datadir | path basename) database..."
run-external $tempo_bin "init" "--chain" $genesis_path "--datadir" $datadir
print $"Loading state bloat into ($datadir | path basename)..."
run-external $tempo_bin "init-from-binary-dump" "--chain" $genesis_path "--datadir" $datadir $bloat_file | complete
}
# ============================================================================
# Schelk / snapshot helpers
# ============================================================================
# Check if schelk is available
def has-schelk [] {
(which schelk | length) > 0
}
# Check if MinIO client (mc) is available
def has-mc [] {
(which mc | length) > 0
}
# Recover snapshot to virgin state and remount
def bench-recover [datadir: string] {
if (has-schelk) {
print "Recovering schelk snapshot..."
if (mountpoint -q /reth-bench | complete).exit_code == 0 {
sudo umount -l /reth-bench | ignore
}
sudo schelk recover -y
sudo schelk mount
sudo chown -R (whoami | str trim) /reth-bench
} else {
print $"Restoring snapshot from ($datadir).virgin..."
rm -rf $datadir
cp -a $"($datadir).virgin" $datadir
}
}
# Promote current state as the new virgin baseline
def bench-promote [datadir: string] {
if (has-schelk) {
print "Promoting schelk scratch to virgin..."
sudo schelk promote -y
} else {
print $"Saving snapshot to ($datadir).virgin..."
rm -rf $"($datadir).virgin"
cp -a $datadir $"($datadir).virgin"
}
}
# Mount schelk scratch volume (no-op without schelk)
def bench-mount [] {
if (has-schelk) {
# If volume is already mounted, recover first (unmounts + resets scratch)
if (mountpoint -q /reth-bench | complete).exit_code == 0 {
print "Schelk volume already mounted, recovering first..."
sudo umount -l /reth-bench | ignore
try { sudo schelk recover -y } catch { }
}
print "Mounting schelk scratch volume..."
try { sudo schelk mount } catch { |e|
# If mount fails because schelk still thinks it's mounted, force recover
print $"Mount failed, forcing recover..."
try { sudo schelk recover -y } catch { }
sudo schelk mount
}
sudo chown -R (whoami | str trim) /reth-bench
}
}
# ============================================================================
# Bench metadata marker (persists across workspace wipes)
# ============================================================================
# Read bench metadata marker from $HOME. Returns record or null.
def read-bench-marker [] {
let path = $"($env.HOME)/.tempo-bench-meta.json"
if ($path | path exists) {
open $path
} else {
null
}
}
# Write bench metadata marker to $HOME.
def write-bench-marker [bloat: int, accounts: int, datadir: string] {
let path = $"($env.HOME)/.tempo-bench-meta.json"
{
bloat_mib: $bloat
accounts: $accounts
bench_datadir: $datadir
initialized_at: (date now | format date "%Y-%m-%dT%H:%M:%SZ")
} | to json | save -f $path
print $"Bench marker written to ($path)"
}
# ============================================================================
# Comparison mode helpers
# ============================================================================
# Resolve a git ref to a full commit SHA
def resolve-git-ref [ref: string] {
git rev-parse $ref | str trim
}
# Try to download cached binaries from MinIO for a given commit SHA.
# Returns true on cache hit, false on miss or any failure.
def try-cache-download [worktree_dir: string, profile: string, commit_sha: string] {
if not (has-mc) { return false }
let bins = ["tempo" "tempo-bench"]
# Check that all binaries exist in the cache
for bin in $bins {
let remote = $"($MINIO_BUCKET)/($commit_sha)/($bin)"
try {
mc stat $remote | ignore
} catch {
print $"Cache miss: ($remote)"
return false
}
}
# All binaries exist – download them
let target_dir = if $profile == "dev" {
$"($worktree_dir)/target/debug"
} else {
$"($worktree_dir)/target/($profile)"
}
mkdir $target_dir
for bin in $bins {
let remote = $"($MINIO_BUCKET)/($commit_sha)/($bin)"
let local = $"($target_dir)/($bin)"
print $"Downloading cached ($bin) for ($commit_sha | str substring 0..8)..."
try {
mc cp $remote $local
chmod +x $local
} catch {
print $"Cache download failed for ($bin), falling back to build"
return false
}
}
# Verify binaries work
for bin in $bins {
let local = $"($target_dir)/($bin)"
try {
run-external $local "--version"
} catch {
print $"Cached ($bin) failed --version check, falling back to build"
return false
}
}
print $"Cache hit: using cached binaries for ($commit_sha | str substring 0..8)"
return true
}
# Upload built binaries to MinIO cache. Failures are non-fatal.
def cache-upload [worktree_dir: string, profile: string, commit_sha: string] {
if not (has-mc) { return }
let target_dir = if $profile == "dev" {
$"($worktree_dir)/target/debug"
} else {
$"($worktree_dir)/target/($profile)"
}
for bin in ["tempo" "tempo-bench"] {
let local = $"($target_dir)/($bin)"
let remote = $"($MINIO_BUCKET)/($commit_sha)/($bin)"
print $"Uploading ($bin) to cache for ($commit_sha | str substring 0..8)..."
try {
mc cp $local $remote
} catch {
print $"Warning: failed to upload ($bin) to cache"
}
}
}
# Build tempo binaries in a git worktree (with optional MinIO cache)
def build-in-worktree [worktree_dir: string, ref: string, profile: string, features: string, commit_sha: string, --no-cache] {
# Try cache first
if not $no_cache and (try-cache-download $worktree_dir $profile $commit_sha) {
return
}
# Build from source
print $"Building binaries for ($ref) in ($worktree_dir)..."
let bin_args = ["--bin" "tempo" "--bin" "tempo-bench"]
let build_cmd = ["cargo" "build" "--profile" $profile "--features" $features] | append $bin_args
with-env { RUSTFLAGS: $RUSTFLAGS } {
do { cd $worktree_dir; run-external ($build_cmd | first) ...($build_cmd | skip 1) }
}
# Upload to cache
cache-upload $worktree_dir $profile $commit_sha
}
# Get the path to a built binary in a worktree
def worktree-bin [worktree_dir: string, profile: string, bin_name: string] {
if $profile == "dev" {
$"($worktree_dir)/target/debug/($bin_name)"
} else {
$"($worktree_dir)/target/($profile)/($bin_name)"
}
}
# Run a single benchmark run (start node, run bench, stop node, collect report)
def run-bench-single [
tempo_bin: string
bench_bin: string
genesis_path: string
datadir: string
run_label: string
results_dir: string
tps: int
duration: int
accounts: int
max_concurrent_requests: int
weights: list<float>
preset: string
bench_args: string
loud: bool
node_args: string
bloat: int
git_ref: string
benchmark_id: string
reference_epoch: int
] {
print $"=== Starting run: ($run_label) ==="
let log_dir = $"($LOCALNET_DIR)/logs-($run_label)"
mkdir $log_dir
# Start metrics proxy with labels for this run
let run_type = if ($run_label | str starts-with "baseline") { "baseline" } else { "feature" }
let run_start_epoch = (date now | into int) / 1_000_000_000
let labels = {
benchmark_run: $run_label
run_type: $run_type
git_ref: $git_ref
benchmark_id: $benchmark_id
run_start_epoch: $"($run_start_epoch)"
reference_epoch: $"($reference_epoch)"
}
$labels | to json | save -f $METRICS_LABELS_FILE
let proxy_pid = if ($METRICS_PROXY_SCRIPT | path exists) {
let proxy_job = (job spawn {
python3 $METRICS_PROXY_SCRIPT --upstream "http://127.0.0.1:9001/" --port 9090
})
sleep 500ms
$proxy_job
} else {
null
}
# Parse extra node args
let extra_args = if $node_args == "" { [] } else { $node_args | split row " " }
# Build node arguments
let args = (build-base-args $genesis_path $datadir $log_dir "0.0.0.0" 8545 9001)
| append (build-dev-args)
| append (log-filter-args $loud)
| append $extra_args
# Start tempo node in background
let node_cmd = [$tempo_bin ...$args]
let node_cmd_str = ($node_cmd | str join " ")
print $" Starting node: ($tempo_bin | path basename)"
job spawn { sh -c $"($node_cmd_str) 2>&1" | lines | each { |line| print $"[($run_label)] ($line)" } }
# Wait for RPC
sleep 2sec
let rpc_timeout = if $bloat > 0 { 600 } else { 120 }
wait-for-rpc "http://localhost:8545" $rpc_timeout
# Run tempo-bench
let bench_cmd = [
$bench_bin
"run-max-tps"
"--tps" $"($tps)"
"--duration" $"($duration)"
"--accounts" $"($accounts)"
"--max-concurrent-requests" $"($max_concurrent_requests)"
"--target-urls" "http://localhost:8545"
"--faucet"
"--clear-txpool"
]
| append (if $preset != "" {
[
"--tip20-weight" $"($weights | get 0)"
"--erc20-weight" $"($weights | get 1)"
"--swap-weight" $"($weights | get 2)"
"--place-order-weight" $"($weights | get 3)"
]
} else { [] })
| append (if $bloat > 0 {
[
"--mnemonic" $"'($BLOAT_MNEMONIC)'"
"--existing-recipients"
]
} else { [] })
| append (if $bench_args != "" { $bench_args | split row " " } else { [] })
print $" Running benchmark..."
try {
bash -c $"ulimit -Sn unlimited && ($bench_cmd | str join ' ')"
} catch { |e|
print $" Benchmark run ($run_label) failed: ($e.msg)"
}
# Collect report
if ("report.json" | path exists) {
cp report.json $"($results_dir)/report-($run_label).json"
rm report.json
print $" Report saved: report-($run_label).json"
} else {
print $" ERROR: no report.json found for ($run_label)"
error make { msg: $"Benchmark run ($run_label) produced no report.json" }
}
# Stop node
print " Stopping node..."
let pids = (find-tempo-pids)
for pid in $pids {
kill -s 2 $pid
}
# Wait for tempo processes to fully exit
for pid in $pids {
mut wait = 0
while $wait < 30 {
if (ps | where pid == $pid | length) == 0 { break }
sleep 1sec
$wait = $wait + 1
}
if $wait >= 30 {
print $" Warning: PID ($pid) did not exit, sending SIGKILL"
kill -s 9 $pid
sleep 1sec
}
}
# Stop metrics proxy
if $proxy_pid != null {
let proxy_pids = (ps | where name =~ "bench-metrics-proxy" | get pid)
for pid in $proxy_pids {
kill -s 2 $pid
}
}
# Remove stale IPC socket
if ("/tmp/reth.ipc" | path exists) {
rm --force /tmp/reth.ipc
}
print $"=== Run ($run_label) complete ==="
}
# Generate summary.md from multiple report files
# Compute percentile from a sorted list (0-100)
def percentile [sorted_vals: list<any>, pct: int] {
if ($sorted_vals | length) == 0 { return 0.0 }
let idx = (($sorted_vals | length) * $pct / 100 | into int)
let clamped = [($idx) (($sorted_vals | length) - 1)] | math min
$sorted_vals | get $clamped
}
def generate-summary [results_dir: string, baseline_ref: string, feature_ref: string, bloat: int, preset: string, tps: int, duration: int, --benchmark-id: string = "", --reference-epoch: int = 0] {
let run_labels = ["baseline-1" "feature-1" "feature-2" "baseline-2"]
mut run_data = []
mut baseline_blocks = []
mut feature_blocks = []
for label in $run_labels {
let report_path = $"($results_dir)/report-($label).json"
if not ($report_path | path exists) {
print $"Warning: ($report_path) not found, skipping"
continue
}
let report = (open $report_path)
let blocks = ($report | get blocks)
if ($blocks | length) == 0 {
print $"Warning: ($label) report has no blocks, skipping"
continue
}
# Collect blocks into baseline/feature groups
if ($label | str starts-with "baseline") {
$baseline_blocks = ($baseline_blocks | append $blocks)
} else {
$feature_blocks = ($feature_blocks | append $blocks)
}
let total_tx = ($blocks | get tx_count | math sum)
let total_ok = ($blocks | get ok_count | math sum)
let total_err = ($blocks | get err_count | math sum)
let total_gas = ($blocks | get gas_used | math sum)
let latencies = ($blocks | where latency_ms != null | get latency_ms | sort)
let p50_latency = (percentile $latencies 50 | math round --precision 1)
let num_blocks = ($blocks | length)
# Compute TPS from block timestamps (timestamps are in milliseconds)
let timestamps = ($blocks | get timestamp)
let time_span_ms = if ($timestamps | length) > 1 {
let first = ($timestamps | first)
let last = ($timestamps | last)
[($last - $first) 1] | math max
} else { 1 }
let time_span_s = $time_span_ms / 1000.0
let actual_tps = ($total_tx / $time_span_s) | math round --precision 0
let gas_per_sec = ($total_gas / $time_span_s)
let mgas_per_sec = ($gas_per_sec / 1_000_000) | math round --precision 1
let success_rate = if $total_tx > 0 {
(($total_ok / $total_tx) * 100) | math round --precision 1
} else { 0 }
$run_data = ($run_data | append [{
label: $label
blocks: $num_blocks
total_tx: $total_tx
ok: $total_ok
err: $total_err
total_gas: $total_gas
p50_latency: $p50_latency
tps: $actual_tps
mgas_s: $mgas_per_sec
success_rate: $success_rate
}])
}
if ($run_data | length) == 0 {
print "No reports found, skipping summary generation"
return
}
# Compute per-block latency percentiles for each group
let compute_latency_stats = { |blocks: list<any>|
let latencies = ($blocks | where latency_ms != null | get latency_ms | sort)
{
n: ($blocks | length)
mean: (if ($latencies | length) > 0 { $latencies | math avg | math round --precision 1 } else { 0 })
stddev: (if ($latencies | length) > 1 { $latencies | math stddev | math round --precision 1 } else { 0 })
p50: (percentile $latencies 50 | math round --precision 1)
p90: (percentile $latencies 90 | math round --precision 1)
p99: (percentile $latencies 99 | math round --precision 1)
}
}
let b_lat = do $compute_latency_stats $baseline_blocks
let f_lat = do $compute_latency_stats $feature_blocks
# Aggregate TPS and Mgas/s from per-run totals (total_tx / total_time)
let baseline_runs = ($run_data | where { |r| $r.label | str starts-with "baseline" })
let feature_runs = ($run_data | where { |r| $r.label | str starts-with "feature" })
let b_tps = if ($baseline_runs | length) > 0 { $baseline_runs | get tps | math avg | math round --precision 0 } else { 0 }
let f_tps = if ($feature_runs | length) > 0 { $feature_runs | get tps | math avg | math round --precision 0 } else { 0 }
let b_mgas = if ($baseline_runs | length) > 0 { $baseline_runs | get mgas_s | math avg | math round --precision 1 } else { 0 }
let f_mgas = if ($feature_runs | length) > 0 { $feature_runs | get mgas_s | math avg | math round --precision 1 } else { 0 }
# Compute deltas (feature vs baseline)
let delta = { |base: float, feat: float| if $base != 0 { ((($feat - $base) / $base) * 100) | math round --precision 1 } else { 0 } }
# Build summary markdown
let summary = ([
$"# Bench Comparison: ($baseline_ref) vs ($feature_ref)"
""
"## Configuration"
$"- Bloat: ($bloat) MiB"
$"- Preset: ($preset)"
$"- Target TPS: ($tps)"
$"- Duration: ($duration)s"
$"- Snapshot: (if (has-schelk) { 'schelk' } else { 'cp fallback' })"
$"- Baseline blocks: ($b_lat.n)"
$"- Feature blocks: ($f_lat.n)"
""
"## Results"
""
"| Metric | Baseline | Feature | Delta |"
"|--------|----------|---------|-------|"
$"| Latency Mean [ms] | ($b_lat.mean) | ($f_lat.mean) | (do $delta $b_lat.mean $f_lat.mean)% |"
$"| Latency Std Dev [ms] | ($b_lat.stddev) | ($f_lat.stddev) | (do $delta $b_lat.stddev $f_lat.stddev)% |"
$"| Latency P50 [ms] | ($b_lat.p50) | ($f_lat.p50) | (do $delta $b_lat.p50 $f_lat.p50)% |"
$"| Latency P90 [ms] | ($b_lat.p90) | ($f_lat.p90) | (do $delta $b_lat.p90 $f_lat.p90)% |"
$"| Latency P99 [ms] | ($b_lat.p99) | ($f_lat.p99) | (do $delta $b_lat.p99 $f_lat.p99)% |"
$"| TPS | ($b_tps) | ($f_tps) | (do $delta $b_tps $f_tps)% |"
$"| Mgas/s | ($b_mgas) | ($f_mgas) | (do $delta $b_mgas $f_mgas)% |"
""
"## Per-Run Details"
""
"| Run | Blocks | Total Tx | Success | Failed | P50 Latency | TPS | Mgas/s |"
"|-----|--------|----------|---------|--------|-------------|-----|--------|"
] | str join "\n")
mut per_run_rows = ""
for row in $run_data {
$per_run_rows = $"($per_run_rows)| ($row.label) | ($row.blocks) | ($row.total_tx) | ($row.ok) | ($row.err) | ($row.p50_latency) | ($row.tps) | ($row.mgas_s) |\n"
}
let full_summary = $"($summary)\n($per_run_rows)"
$full_summary | save -f $"($results_dir)/summary.md"
print $"Summary saved: ($results_dir)/summary.md"
print $full_summary
# Write machine-readable summary.json for CI
let summary_json = {
benchmark_id: $benchmark_id
reference_epoch: $reference_epoch
baseline_ref: $baseline_ref
feature_ref: $feature_ref
config: {
bloat: $bloat
preset: $preset
tps: $tps
duration: $duration
}
results: {
baseline: {
latency_mean: $b_lat.mean
latency_stddev: $b_lat.stddev
latency_p50: $b_lat.p50
latency_p90: $b_lat.p90
latency_p99: $b_lat.p99
tps: $b_tps
mgas_s: $b_mgas
blocks: $b_lat.n
}
feature: {
latency_mean: $f_lat.mean
latency_stddev: $f_lat.stddev
latency_p50: $f_lat.p50
latency_p90: $f_lat.p90
latency_p99: $f_lat.p99
tps: $f_tps
mgas_s: $f_mgas
blocks: $f_lat.n
}
deltas: {
latency_mean: (do $delta $b_lat.mean $f_lat.mean)
latency_stddev: (do $delta $b_lat.stddev $f_lat.stddev)
latency_p50: (do $delta $b_lat.p50 $f_lat.p50)
latency_p90: (do $delta $b_lat.p90 $f_lat.p90)
latency_p99: (do $delta $b_lat.p99 $f_lat.p99)
tps: (do $delta $b_tps $f_tps)
mgas_s: (do $delta $b_mgas $f_mgas)
}
}
per_run: $run_data
}
$summary_json | to json | save -f $"($results_dir)/summary.json"
print $"Summary JSON saved: ($results_dir)/summary.json"
}
# ============================================================================
# Infra commands
# ============================================================================
# Start the observability stack (Grafana + Prometheus)
def "main infra up" [] {
print "Starting observability stack..."
docker compose -f $"($BENCH_DIR)/docker-compose.yml" up -d
print "Grafana available at http://localhost:3000 (admin/admin)"
print "Prometheus available at http://localhost:9090"
}
# Stop the observability stack
def "main infra down" [] {
print "Stopping observability stack..."
docker compose -f $"($BENCH_DIR)/docker-compose.yml" down
}
# ============================================================================
# Kill command
# ============================================================================
# Kill any running tempo processes and cleanup
def "main kill" [
--prompt # Prompt before killing (for interactive use)
] {
let pids = (find-tempo-pids)
let has_stale_ipc = ("/tmp/reth.ipc" | path exists)
if ($pids | length) == 0 and not $has_stale_ipc {
print "No tempo processes or stale IPC socket found."
return
}
if ($pids | length) > 0 {
print $"Found ($pids | length) running tempo process\(es\)."
}
if $has_stale_ipc {
print "Found stale /tmp/reth.ipc socket."
}
let should_kill = if $prompt {
let answer = (input "Clean up? [Y/n] " | str trim | str downcase)
$answer == "" or $answer == "y" or $answer == "yes"
} else {
true
}
if not $should_kill {
print "Aborting."
exit 1
}
if ($pids | length) > 0 {
print $"Sending SIGINT to ($pids | length) tempo processes..."
for pid in $pids {
kill -s 2 $pid
}
}
# Remove stale IPC socket
if $has_stale_ipc {
rm --force /tmp/reth.ipc
print "Removed /tmp/reth.ipc"
}
print "Done."
}
# ============================================================================
# Localnet command
# ============================================================================
# Run Tempo localnet
def "main localnet" [
--mode: string = "dev" # Mode: "dev" or "consensus"
--nodes: int = 3 # Number of validators (consensus mode)
--accounts: int = 1000 # Number of genesis accounts
--genesis: string = "" # Custom genesis file path (skips generation)
--samply # Enable samply profiling (foreground node only)
--samply-args: string = "" # Additional samply arguments (space-separated)
--reset # Wipe and regenerate localnet data
--profile: string = $DEFAULT_PROFILE # Cargo build profile
--features: string = $DEFAULT_FEATURES # Cargo features
--loud # Show all node logs (WARN/ERROR shown by default)
--node-args: string = "" # Additional node arguments (space-separated)
--skip-build # Skip building (assumes binary is already built)
--force # Kill dangling processes without prompting
--bloat: int = 0 # Generate state bloat (size in MiB) for TIP20 tokens
] {
validate-mode $mode
# Check for dangling processes or stale IPC socket
let pids = (find-tempo-pids)
let has_stale_ipc = ("/tmp/reth.ipc" | path exists)
if ($pids | length) > 0 or $has_stale_ipc {
main kill --prompt=($force | not $in)
}
# Parse custom args
let extra_args = if $node_args == "" { [] } else { $node_args | split row " " }
let samply_args_list = if $samply_args == "" { [] } else { $samply_args | split row " " }
# Build first (unless skipped)
if not $skip_build {
build-tempo ["tempo"] $profile $features
}
if $mode == "dev" {
if $nodes != 3 {
print "Error: --nodes is only valid with --mode consensus"
exit 1
}
run-dev-node $accounts $genesis $samply $samply_args_list $reset $profile $loud $extra_args $bloat
} else {
run-consensus-nodes $nodes $accounts $genesis $samply $samply_args_list $reset $profile $loud $extra_args $bloat
}
}
# ============================================================================
# Dev mode
# ============================================================================
def run-dev-node [accounts: int, genesis: string, samply: bool, samply_args: list<string>, reset: bool, profile: string, loud: bool, extra_args: list<string>, bloat: int] {
let tempo_bin = if $profile == "dev" {
"./target/debug/tempo"
} else {
$"./target/($profile)/tempo"
}
let datadir = $"($LOCALNET_DIR)/reth"
let log_dir = $"($LOCALNET_DIR)/logs"
let genesis_path = if $genesis != "" {
# Custom genesis provided - check if bloat requires init
if $bloat > 0 {
generate-bloat-file $bloat $profile
load-bloat-into-node $tempo_bin $genesis $datadir
}
$genesis
} else {
let default_genesis = $"($LOCALNET_DIR)/genesis.json"
let needs_generation = $reset or (not ($default_genesis | path exists))
if $needs_generation {
if $reset {
print "Resetting localnet data..."
} else {
print "Genesis not found, generating..."
}
rm -rf $LOCALNET_DIR
mkdir $LOCALNET_DIR
print $"Generating genesis with ($accounts) accounts..."
cargo run -p tempo-xtask --profile $profile -- generate-genesis --output $LOCALNET_DIR -a $accounts --no-dkg-in-genesis
}
# Apply state bloat if requested (requires fresh init)
if $bloat > 0 {
generate-bloat-file $bloat $profile
load-bloat-into-node $tempo_bin $default_genesis $datadir
}
$default_genesis
}
let args = (build-base-args $genesis_path $datadir $log_dir "0.0.0.0" 8545 9001)
| append (build-dev-args)
| append (log-filter-args $loud)
| append $extra_args
let cmd = wrap-samply [$tempo_bin ...$args] $samply $samply_args
print $"Running dev node: `($cmd | str join ' ')`..."
run-external ($cmd | first) ...($cmd | skip 1)
}
# Build base node arguments shared between dev and consensus modes
def build-base-args [genesis_path: string, datadir: string, log_dir: string, bind_ip: string, http_port: int, reth_metrics_port: int] {
[
"node"
"--chain" $genesis_path
"--datadir" $datadir
"--http"
"--http.addr" $bind_ip
"--http.port" $"($http_port)"
"--http.api" "all"
"--metrics" $"($bind_ip):($reth_metrics_port)"
"--log.file.directory" $log_dir
"--faucet.enabled"
"--faucet.private-key" "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
"--faucet.amount" "1000000000000"
"--faucet.address" "0x20c0000000000000000000000000000000000000"
"--faucet.address" "0x20c0000000000000000000000000000000000001"
]
}
# Build dev mode specific arguments
def build-dev-args [] {
[
"--dev"
"--dev.block-time" "1sec"
"--builder.gaslimit" "3000000000"
"--builder.max-tasks" "8"
"--builder.deadline" "3"
]
}
# ============================================================================
# Consensus mode
# ============================================================================
def run-consensus-nodes [nodes: int, accounts: int, genesis: string, samply: bool, samply_args: list<string>, reset: bool, profile: string, loud: bool, extra_args: list<string>, bloat: int] {
# Check if we need to generate localnet (only if no custom genesis provided)
if $genesis == "" {
let needs_generation = $reset or (not ($LOCALNET_DIR | path exists)) or (
(ls $LOCALNET_DIR | where type == "dir" | get name | where { |d| ($d | path basename) =~ '^\d+\.\d+\.\d+\.\d+:\d+$' } | length) == 0
)
if $needs_generation {
if $reset {
print "Resetting localnet data..."
} else {
print "Localnet not found, generating..."
}
rm -rf $LOCALNET_DIR
# Generate validator addresses with distinct loopback IPs (required by ValidatorConfigV2
# ingress uniqueness check which is per-IP, not per-socket-address)
let validators = (0..<$nodes | each { |i| $"127.0.0.($i + 1):($i * 100 + 8000)" } | str join ",")
print $"Generating localnet with ($accounts) accounts and ($nodes) validators..."
cargo run -p tempo-xtask --profile $profile -- generate-localnet -o $LOCALNET_DIR --accounts $accounts --validators $validators --force | ignore
}
}
# Parse the generated node configs
let genesis_path = if $genesis != "" { $genesis } else { $"($LOCALNET_DIR)/genesis.json" }
# Build trusted peers from enode.identity files
let validator_dirs = (ls $LOCALNET_DIR | where type == "dir" | get name | where { |d| ($d | path basename) =~ '^\d+\.\d+\.\d+\.\d+:\d+$' })
let trusted_peers = ($validator_dirs | each { |d|
let addr = ($d | path basename)
let ip = ($addr | split row ":" | get 0)
let port = ($addr | split row ":" | get 1 | into int)
let identity = (open $"($d)/enode.identity" | str trim)
$"enode://($identity)@($ip):($port + 1)"
} | str join ",")
print $"Found ($validator_dirs | length) validator configs"
let tempo_bin = if $profile == "dev" {
"./target/debug/tempo"
} else {
$"./target/($profile)/tempo"
}
# Ensure loopback aliases exist for distinct validator IPs (macOS only has 127.0.0.1 by default)
if (sys host | get name) == "Darwin" {
let extra_ips = ($validator_dirs | each { |d| $d | path basename | split row ":" | get 0 } | where { |ip| $ip != "127.0.0.1" })
if ($extra_ips | length) > 0 {
print $"Adding macOS loopback aliases for validator IPs: ($extra_ips | str join ', ') \(sudo required\)..."
}
for dir in $validator_dirs {
let ip = ($dir | path basename | split row ":" | get 0)
if $ip != "127.0.0.1" {
try { sudo ifconfig lo0 alias $ip up } catch { |e|
print $"(ansi red)Failed to add loopback alias ($ip): ($e.msg)(ansi reset)"
print "Run: sudo ifconfig lo0 alias $ip up"
exit 1
}
}
}
}
# Apply state bloat to each node's datadir if requested
if $bloat > 0 {
generate-bloat-file $bloat $profile
for node_dir in $validator_dirs {
load-bloat-into-node $tempo_bin $genesis_path $node_dir
}
}
# Start background nodes first (all except node 0)
print $"Starting ($validator_dirs | length) nodes..."
print $"Logs: ($LOGS_DIR)/"
print "Press Ctrl+C to stop all nodes."
let foreground_node = $validator_dirs | first
let background_nodes = $validator_dirs | skip 1
for node in $background_nodes {
run-consensus-node $node $genesis_path $trusted_peers $tempo_bin $loud false [] $extra_args true
}
# Run node 0 in foreground (receives Ctrl+C directly)
run-consensus-node $foreground_node $genesis_path $trusted_peers $tempo_bin $loud $samply $samply_args $extra_args false
}
# Run a single consensus node (foreground or background)
def run-consensus-node [
node_dir: string
genesis_path: string
trusted_peers: string
tempo_bin: string
loud: bool
samply: bool
samply_args: list<string>
extra_args: list<string>
background: bool
] {
let addr = ($node_dir | path basename)
let port = ($addr | split row ":" | get 1 | into int)
let node_index = (port-to-node-index $port)
let http_port = 8545 + $node_index
let log_dir = $"($LOGS_DIR)/($addr)"
mkdir $log_dir
let args = (build-consensus-node-args $node_dir $genesis_path $trusted_peers $port $log_dir)
| append (log-filter-args $loud)
| append $extra_args
let cmd = wrap-samply [$tempo_bin ...$args] $samply $samply_args
print $" Node ($addr) -> http://localhost:($http_port)(if $background { '' } else { ' (foreground)' })"
if $background {
job spawn { sh -c $"($cmd | str join ' ') 2>&1" | lines | each { |line| print $"[($addr)] ($line)" } }
} else {
print $" Running: ($cmd | str join ' ')"