-
Notifications
You must be signed in to change notification settings - Fork 350
Expand file tree
/
Copy pathtempo.nu
More file actions
executable file
·3617 lines (3267 loc) · 168 KB
/
Copy pathtempo.nu
File metadata and controls
executable file
·3617 lines (3267 loc) · 168 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
source contrib/bench/txgen/helpers.nu
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 MINIO_BUCKET = "minio/tempo-binaries"
const BENCH_META_SUBDIR = ".bench-meta"
const LOCALNET_SIGNING_KEY_SECRET = "tempo-localnet-signing-key-secret"
# 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" "info"] }
}
# Keep benchmark OTLP logs useful without emitting high-volume HTTP transport internals.
def benchmark-otlp-args [endpoint: string] {
if $endpoint == "" {
[]
} else {
[
$"--tracing-otlp=($endpoint)"
"--logs-otlp.filter=debug,h2=off,hyper=off,hyper_util=off"
]
}
}
def prepare-localnet-consensus-secret-fifo [node_dir: string] {
let secret_path = $"($node_dir)/consensus-secret.fifo"
rm -f $secret_path
mkfifo $secret_path
chmod 600 $secret_path
$secret_path
}
def start-localnet-consensus-secret-writer [secret_path: string] {
job spawn { $"($LOCALNET_SIGNING_KEY_SECRET)\n" | save -f $secret_path } | ignore
}
# 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
}
}
# Compute effective features and RUSTFLAGS for tracy builds.
# The "tracy" cargo feature on bin/tempo already includes tracy-client/ondemand,
# so we only need to append "tracy" here.
def tracy-build-config [features: string, tracy: string] {
if $tracy == "off" {
{ features: $features, extra_rustflags: "" }
} else {
let tracy_features = if $features == "" { "tracy" } else { $"($features),tracy" }
{ features: $tracy_features, extra_rustflags: " -C force-frame-pointers=yes" }
}
}
def cargo-feature-args [features: string, no_default_features: bool] {
let no_default_args = if $no_default_features { ["--no-default-features"] } else { [] }
let feature_args = if $features == "" { [] } else { ["--features" $features] }
$no_default_args | append $feature_args
}
# 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, --no-default-features, --extra-rustflags: string = ""] {
let bin_args = ($bins | each { |bin| ["--bin" $bin] } | flatten)
let feature_args = (cargo-feature-args $features $no_default_features)
let build_cmd = ["cargo" "build" "--profile" $profile]
| append $feature_args
| append $bin_args
let rustflags = $"($RUSTFLAGS)($extra_rustflags)"
print $"Building ($bins | str join ', '): `($build_cmd | str join ' ')`..."
with-env { RUSTFLAGS: $rustflags } {
run-external ($build_cmd | first) ...($build_cmd | skip 1)
}
}
def tempo-xtask-bin [profile: string] {
if $profile == "dev" {
"./target/debug/tempo-xtask"
} else {
$"./target/($profile)/tempo-xtask"
}
}
def build-tempo-xtask [profile: string] {
let build_cmd = ["cargo" "build" "-p" "tempo-xtask" "--profile" $profile]
print $"Building tempo-xtask: `($build_cmd | str join ' ')`..."
run-external ($build_cmd | first) ...($build_cmd | skip 1)
}
def run-tempo-xtask [profile: string, skip_build: bool, args: list<string>] {
if $skip_build {
let xtask_bin = (tempo-xtask-bin $profile)
if not ($xtask_bin | path exists) {
print $"Error: --skip-build requires ($xtask_bin). Build it first with `cargo build -p tempo-xtask --profile ($profile)`."
exit 1
}
run-external $xtask_bin ...$args
} else {
let run_cmd = ["cargo" "run" "-p" "tempo-xtask" "--profile" $profile "--"]
| append $args
run-external ($run_cmd | first) ...($run_cmd | skip 1)
}
}
# Find tempo node process PIDs.
def find-tempo-pids [] {
ps | where name =~ '(^|/)tempo$' | 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, skip_build: bool] {
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)
run-tempo-xtask $profile $skip_build ["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
}
# ============================================================================
# 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
}
# Force-clear schelk's "is_mounted" state after a crash where dm-era is gone
def schelk-force-unmount-state [] {
let state_path = "/var/lib/schelk/state.json"
print $" Clearing stale is_mounted flag in ($state_path)..."
let state = (sudo cat $state_path | from json | update is_mounted false)
$state | to json | sudo tee $state_path | ignore
}
# Clean database files from a datadir (db, static_files, rocksdb, etc.)
def bench-clean-datadir [datadir: string] {
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 }
}
}
# Initialize a database: run `tempo init`, optionally load state bloat
def bench-init-db [tempo_bin: string, genesis: string, datadir: string, bloat: int, bloat_file: string] {
print $"Initializing database at ($datadir)..."
run-external $tempo_bin "init" "--chain" $genesis "--datadir" $datadir
if $bloat > 0 {
print $"Loading state bloat into ($datadir)..."
run-external $tempo_bin "init-from-binary-dump" "--chain" $genesis "--datadir" $datadir $bloat_file | complete
}
}
# Save genesis files, bloat, and marker to meta dir, then promote and remount.
# Everything is written before promote so it's part of the virgin snapshot.
def bench-save-and-promote [datadir: string, meta_dir: string, marker: record, genesis_files: list, bloat: int, bloat_file: string] {
mkdir $meta_dir
for pair in $genesis_files {
cp ($pair | first) $"($meta_dir)/($pair | last)"
}
if $bloat > 0 and ($bloat_file | path exists) {
cp $bloat_file $"($meta_dir)/state_bloat.bin"
}
let marker_path = $"($meta_dir)/marker.json"
$marker | insert initialized_at (date now | format date "%Y-%m-%dT%H:%M:%SZ") | to json | save -f $marker_path
print $"Bench marker written to ($marker_path)"
bench-promote $datadir
bench-mount
}
# 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
}
try {
sudo schelk recover -y
} catch {
print "Surgical recover failed, falling back to full-recover..."
schelk-force-unmount-state
sudo schelk full-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 "Surgical recover failed, falling back to full-recover..."
schelk-force-unmount-state
sudo schelk full-recover -y
}
}
print "Mounting schelk scratch volume..."
try { sudo schelk mount } catch {
# Mount failed — state may be inconsistent after a crash
print "Mount failed, forcing recover..."
try { sudo schelk recover -y } catch {
print "Surgical recover failed, falling back to full-recover..."
schelk-force-unmount-state
sudo schelk full-recover -y
}
sudo schelk mount
}
sudo chown -R (whoami | str trim) /reth-bench
}
}
# ============================================================================
# Bench metadata marker (persists across workspace wipes)
# ============================================================================
# Read bench metadata marker from the datadir's meta directory. Returns record or null.
def read-bench-marker [datadir: string] {
let path = $"($datadir)/($BENCH_META_SUBDIR)/marker.json"
if ($path | path exists) {
open $path
} else {
null
}
}
# ============================================================================
# Comparison mode helpers
# ============================================================================
const TEMPO_DISABLED_HARDFORK_TIME = 9223372036854775807
def tempo-hardforks [] {
let forks = (
open crates/node/tests/assets/test-genesis.json
| get config
| columns
| where { |key| $key =~ '^t[0-9]+[a-z]?Time$' }
| each { |key| $key | str replace "Time" "" | str upcase }
)
if ($forks | is-empty) {
print "Error: failed to read Tempo hardforks from crates/node/tests/assets/test-genesis.json"
exit 1
}
$forks
}
def normalize-hardfork [fork: string] {
let hardforks = (tempo-hardforks)
let fork_upper = ($fork | str upcase)
let idx = ($hardforks | enumerate | where item == $fork_upper)
if ($idx | length) == 0 {
print $"Error: unknown hardfork '($fork)'. Valid: ($hardforks | str join ', ')"
exit 1
}
$fork_upper
}
def hardfork-index [fork: string] {
let fork_upper = (normalize-hardfork $fork)
(tempo-hardforks | enumerate | where item == $fork_upper | get 0.index)
}
def latest-tempo-hardfork [] {
tempo-hardforks | last
}
def highest-hardfork [forks: list<string>] {
if ($forks | length) == 0 {
return (latest-tempo-hardfork)
}
mut highest = (normalize-hardfork ($forks | first))
for fork in ($forks | skip 1) {
let current = (normalize-hardfork $fork)
if (hardfork-index $current) > (hardfork-index $highest) {
$highest = $current
}
}
$highest
}
def hardfork-genesis-config-fields [fork: string] {
let cutoff = (hardfork-index $fork)
tempo-hardforks | enumerate | each { |it|
{
fork: $it.item
name: $"($it.item | str downcase)Time"
value: (if $it.index <= $cutoff { 0 } else { $TEMPO_DISABLED_HARDFORK_TIME })
}
}
}
# Map a hardfork name to generate-genesis CLI args.
# Forks up to and including the given fork are active at genesis (time=0).
# Forks after are disabled (time=max u64).
# Returns a list of CLI flag strings, e.g. ["--t0-time" "0" "--t1-time" "0" "--t1a-time" "9223372036854775807" ...]
def hardfork-to-genesis-args [fork: string] {
hardfork-genesis-config-fields $fork | each { |it|
let flag = $"--($it.fork | str downcase)-time"
let time = ($it.value | into string)
[$flag $time]
} | flatten
}
# Resolve a git ref to a full commit SHA
def resolve-git-ref [ref: string] {
git rev-parse $ref | str trim
}
# Resolve a SHA to a human-readable label: tag > branch > fallback.
def resolve-git-ref-label [sha: string, fallback: string] {
let tag = (git tag --points-at $sha | lines | first | default "")
if $tag != "" {
return $tag
}
let branch = (git branch -r --points-at $sha | lines | first | default "" | str replace -r '^\s*origin/' '')
if $branch != "" {
return $branch
}
$fallback
}
def bench-cache-key [commit_sha: string, features: string, no_default_features: bool] {
if (not $no_default_features) and $features == $DEFAULT_FEATURES {
return $commit_sha
}
let feature_key = if $features == "" {
"none"
} else {
$features
| str replace -a "," "_"
| str replace -a "/" "_"
| str replace -a " " "_"
}
let mode_key = if $no_default_features { "no-default" } else { "features" }
$"($commit_sha)-($mode_key)-($feature_key)"
}
# 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, cache_key: string] {
if not (has-mc) { return false }
let bins = ["tempo"]
# Check that all binaries exist in the cache
for bin in $bins {
let remote = $"($MINIO_BUCKET)/($cache_key)/($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)/($cache_key)/($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, cache_key: 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"] {
let local = $"($target_dir)/($bin)"
let remote = $"($MINIO_BUCKET)/($cache_key)/($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 binary 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, --no-default-features, --extra-rustflags: string = "", --bench-features: string = ""] {
let cache_key = (bench-cache-key $commit_sha $features $no_default_features)
# Try cache first
if not $no_cache and (try-cache-download $worktree_dir $profile $commit_sha $cache_key) {
return
}
print $"Building tempo for ($ref) in ($worktree_dir)..."
let rustflags = $"($RUSTFLAGS)($extra_rustflags)"
let feature_args = (cargo-feature-args $features $no_default_features)
let build_cmd = ["cargo" "build" "--profile" $profile]
| append $feature_args
| append ["--bin" "tempo"]
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 $cache_key
}
# 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)"
}
}
# Dedup CLI args: if extra_args provides a flag already present in base_args,
# the default (in base_args) is dropped so clap doesn't see it twice.
# Handles both `--flag value` and `--flag=value` forms.
def dedup-args [base_args: list<string>, extra_args: list<string>] {
if ($extra_args | is-empty) { return $base_args }
# Collect flag keys the user wants to override
let override_keys = ($extra_args | where { |a| $a starts-with "--" }
| each { |a| $a | split row "=" | first })
# Walk base_args, skip any flag (and its value) whose key is overridden
mut result = []
mut skip_next = false
for arg in $base_args {
if $skip_next {
$skip_next = false
continue
}
if ($arg starts-with "--") {
let key = ($arg | split row "=" | first)
if ($key in $override_keys) {
# Skip this flag; if it's `--flag value` form (no =), skip next token too
if not ($arg | str contains "=") {
$skip_next = true
}
continue
}
}
$result = ($result | append $arg)
}
$result | append $extra_args
}
def parse-cli-args [args: string] {
mut result = []
mut current = ""
mut quote = ""
mut escaped = false
mut token_started = false
for ch in ($args | split chars) {
if $escaped {
$current = $"($current)($ch)"
$escaped = false
$token_started = true
continue
}
if $ch == "\\" {
$escaped = true
$token_started = true
continue
}
if $quote != "" {
if $ch == $quote {
$quote = ""
} else {
$current = $"($current)($ch)"
}
$token_started = true
continue
}
if $ch == "'" or $ch == '"' {
$quote = $ch
$token_started = true
continue
}
if $ch in [" " "\t" "\n" "\r"] {
if $token_started {
$result = ($result | append $current)
$current = ""
$token_started = false
}
continue
}
$current = $"($current)($ch)"
$token_started = true
}
if $escaped {
$current = $"($current)('\')"
}
if $quote != "" {
print $"Error: unterminated quote in args: ($args)"
exit 1
}
if $token_started {
$result = ($result | append $current)
}
$result
}
# Run a single benchmark run (start node, run bench, stop node, collect report)
def run-bench-single [
--tempo-bin: string
--txgen-tempo-bin: string
--txgen-bench-bin: string
--rpc-urls: string
--metrics-url: list<string>
--genesis-path: string
--datadir: string
--run-label: string
--results-dir: string
--tps: int
--duration: int
--accounts: int
--max-concurrent-requests: int
--preset-path: string
--bench-args: string = ""
--loud
--node-args: string = ""
--extra-env: string = ""
--bench-env: string = ""
--bloat: int = 0
--git-ref: string = ""
--build-profile: string = ""
--benchmark-mode: string = ""
--benchmark-id: string = ""
--reference-epoch: int = 0
--samply
--samply-args: list<string> = []
--tracy: string = "off"
--tracy-filter: string = "debug"
--tracy-seconds: int = 0
--tracy-offset: int = 0
--tracing-otlp: string = ""
] {
print $"=== Starting run: ($run_label) ==="
let log_dir = $"($LOCALNET_DIR)/logs-($run_label)"
mkdir $log_dir
let run_type = if ($run_label | str starts-with "baseline") { "baseline" } else { "feature" }
# Parse extra node args
let extra_args = (parse-cli-args $node_args)
# Build node arguments, then dedup so user-provided args override defaults
let base_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 (if $tracy != "off" { ["--log.tracy" "--log.tracy.filter" $tracy_filter] } else { [] })
| append (benchmark-otlp-args $tracing_otlp)
let args = (dedup-args $base_args $extra_args)
# Tracy environment variables
let tracy_env_prefix = if $tracy == "tracy" {
"TRACY_SAMPLING_HZ=18999 "
} else { "" }
# OTEL resource attributes for benchmark identification in logs/traces
let otel_attrs = $"OTEL_RESOURCE_ATTRIBUTES=benchmark_id=($benchmark_id),benchmark_run=($run_label),run_type=($run_type),git_ref=($git_ref) "
# Start tempo node in background (optionally wrapped with samply)
let full_samply_args = if $samply {
$samply_args | append ["--save-only" "--presymbolicate" "--output" $"($results_dir)/profile-($run_label).json.gz"]
} else { [] }
let node_cmd = wrap-samply [$tempo_bin ...$args] $samply $full_samply_args
let node_cmd_str = ($node_cmd | str join " ")
let profiling_label = if $samply { " (samply)" } else if $tracy != "off" { $" \(tracy=($tracy)\)" } else { "" }
let env_prefix = if $extra_env != "" { $"($extra_env) " } else { "" }
print $" Starting node: ($tempo_bin | path basename)($profiling_label)"
job spawn { sh -c $"($env_prefix)($otel_attrs)($tracy_env_prefix)($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
# Start tracy-capture after RPC is ready (node must be running for connection)
# If tracy-offset > 0, delay the capture start in a background job so txgen isn't blocked
let tracy_output = $"($results_dir)/tracy-profile-($run_label).tracy"
let tracy_capture_started = if $tracy != "off" {
let seconds_flag = if $tracy_seconds > 0 { $"-s ($tracy_seconds)" } else { "" }
let limit_msg = if $tracy_seconds > 0 { $" \(($tracy_seconds)s limit\)" } else { "" }
if $tracy_offset > 0 {
print $" Tracy-capture will start in ($tracy_offset)s($limit_msg)..."
job spawn { sleep ($"($tracy_offset)sec" | into duration); sh -c $"tracy-capture -f -o ($tracy_output) ($seconds_flag)" }
} else {
print $" Starting tracy-capture($limit_msg)..."
job spawn { sh -c $"tracy-capture -f -o ($tracy_output) ($seconds_flag)" }
sleep 500ms
}
true
} else { false }
print $" Running txgen benchmark..."
let report_path = $"($results_dir)/report-($run_label).json"
let bench_result = (try {
let result = (txgen-run-preset-pipeline
--txgen-tempo-bin $txgen_tempo_bin
--txgen-bench-bin $txgen_bench_bin
--preset-path $preset_path
--generate-rpc-url "http://localhost:8545"
--submit-rpc-url $rpc_urls
--metrics-url $metrics_url
--report-path $report_path
--tps $tps
--duration $duration
--accounts $accounts
--max-concurrent-requests $max_concurrent_requests
--bench-args $bench_args
--bench-env $bench_env
--git-ref $git_ref
--build-profile $build_profile
--benchmark-mode $benchmark_mode
--bloat-mib $bloat
--bloat-token-count ($TIP20_TOKEN_IDS | length)
--skip-funding=($bloat > 0))
if not $result.ok {
print $" Benchmark run ($run_label) failed with exit code ($result.exit_code)"
}
$result
} catch { |e|
print $" Benchmark run ($run_label) failed: ($e.msg)"
{ ok: false, exit_code: 1, report_path: $report_path }
})
let bench_failed = not $bench_result.ok
# Stop tracy-capture FIRST (it needs the node alive to flush data)
if $tracy_capture_started {
print " Stopping tracy-capture..."
let capture_pids = (ps | where name =~ "tracy-capture" | get pid)
for pid in $capture_pids {
kill -s 2 $pid # SIGINT for graceful flush
}
mut wait_tracy = 0
while $wait_tracy < 30 {
if (ps | where name =~ "tracy-capture" | length) == 0 { break }
sleep 1sec
$wait_tracy = $wait_tracy + 1
}
if $wait_tracy >= 30 {
print " Warning: tracy-capture did not exit, sending SIGKILL"
for pid in (ps | where name =~ "tracy-capture" | get pid) {
kill -s 9 $pid
}
}
}
# 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
}
}
# Wait for samply to finish saving profile
if $samply {
print " Waiting for samply to finish saving profile..."
mut wait = 0
while $wait < 120 {
if (ps | where name =~ "samply" | length) == 0 { break }
sleep 500ms
$wait = $wait + 1
}
if $wait >= 120 {
print " Warning: samply did not exit in time"
}
}
print $"=== Run ($run_label) complete ==="
if $bench_failed {
error make { msg: $"Benchmark run ($run_label) failed" }
}
}
# Upload a samply profile (.json.gz) to Firefox Profiler and return the short URL.
# Returns null on failure. Uses the same approach as reth-bench.
def upload-samply-profile [profile_path: string] {
if not ($profile_path | path exists) {
print $" Warning: profile not found: ($profile_path)"
return null
}
let profile_size = (ls $profile_path | get size | first)
print $" Uploading ($profile_path | path basename) \(($profile_size)\) to Firefox Profiler..."
let script = $"($BENCH_DIR)/upload-samply-profile.sh"
let result = (bash $script $profile_path | complete)
if $result.exit_code != 0 {
print $" Warning: failed to upload profile"
return null
}
let url = ($result.stdout | str trim)
print $" Profile URL: ($url)"
$url
}
# Upload a tracy profile (.tracy) to R2 via mc and return the viewer and raw profile URLs.
# Returns null on failure or if mc is not available.
# Deletes the large .tracy file after successful upload to save disk.
def upload-tracy-profile [profile_path: string, label: string, commit_sha: string] {
if not ($profile_path | path exists) {
print $" Warning: tracy profile not found: ($profile_path)"
return null
}
if not (has-mc) {
print " Warning: mc not available, skipping tracy upload"
return null
}
let profile_size = (ls $profile_path | get size | first)
print $" Uploading ($profile_path | path basename) \(($profile_size)\) to R2..."
let timestamp = (date now | format date "%Y%m%d-%H%M%S")
let short_sha = ($commit_sha | str substring 0..7)
let remote_name = $"($label)-($short_sha)-($timestamp).tracy"
let mc_alias = "r2"
let viewer_base = "https://tracy.tempoxyz.dev"
let remote_profile_path = $"/profiles/($remote_name)"
try {
mc cp $profile_path $"($mc_alias)/tracy/profiles/($remote_name)"
let viewer_url = $"($viewer_base)?profile_url=($remote_profile_path)"
let profile_url = $"($viewer_base)($remote_profile_path)"
print $" ($label): ($viewer_url)"
# Delete large .tracy file after upload to free disk
rm $profile_path
{ viewer_url: $viewer_url, profile_url: $profile_url }
} catch {
print " Warning: failed to upload tracy profile"
null
}
}
# 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 iso-from-epoch-ms [epoch_ms: int] {
let seconds = ($epoch_ms / 1000 | into int)
let millis = ($epoch_ms mod 1000 | into int)
let base = (^date -u -d $"@($seconds)" "+%Y-%m-%dT%H:%M:%S")
$"($base).($millis | into string | fill --alignment right --character '0' --width 3)Z"
}
def grafana-performance-url [benchmark_id: string, from_ms: int, to_ms: int] {
if $benchmark_id == "" or $from_ms <= 0 or $to_ms <= 0 {
return ""
}
let from = (iso-from-epoch-ms $from_ms)
let to = (iso-from-epoch-ms $to_ms)
$"https://tempoxyz.grafana.net/d/performance/performance?orgId=1&from=($from)&to=($to)&timezone=browser&var-datasource=efk1hcn87dnnkd&var-filter_label=benchmark_id&var-filter_value=($benchmark_id)&var-group_by=benchmark_run"
}
def internal-perf-url [clickhouse_run_id: string] {
if $clickhouse_run_id == "" {
return ""
}
$"http://go/dev/tempo-internal-perf/benchmark/($clickhouse_run_id)"
}
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,
--baseline-hardfork: string = "",
--feature-hardfork: string = "",
--summary-warmup-blocks: int = 0,
] {
if $summary_warmup_blocks < 0 {
error make { msg: "--summary-warmup-blocks must be non-negative" }
}
let run_order_path = $"($results_dir)/run-order.txt"
let candidate_run_labels = if ($run_order_path | path exists) {
open $run_order_path | lines | where { |label| $label != "" }
} else {
["baseline-1" "feature-1" "feature-2" "baseline-2"]
}
let run_labels = ($candidate_run_labels | where { |label| ($"($results_dir)/report-($label).json" | path exists) })
mut run_data = []
mut baseline_blocks = []
mut feature_blocks = []
mut baseline_intervals = []
mut feature_intervals = []
mut baseline_builder_latency_values = []
mut feature_builder_latency_values = []
mut baseline_builder_finish_samples = []
mut feature_builder_finish_samples = []
mut baseline_builder_pool_fetch_samples = []
mut feature_builder_pool_fetch_samples = []
mut baseline_builder_invalid_tx_execution_attempts_samples = []
mut feature_builder_invalid_tx_execution_attempts_samples = []
mut baseline_builder_reverted_txs = []
mut feature_builder_reverted_txs = []
mut baseline_builder_invalid_tx_skips = []
mut feature_builder_invalid_tx_skips = []
mut baseline_builder_nonce_too_low_skips = []
mut feature_builder_nonce_too_low_skips = []
mut baseline_builder_stop_rlp_size = []
mut feature_builder_stop_rlp_size = []
mut baseline_builder_stop_gas_limit = []
mut feature_builder_stop_gas_limit = []
mut baseline_builder_stop_pool_empty = []
mut feature_builder_stop_pool_empty = []
mut baseline_builder_stop_build_budget = []
mut feature_builder_stop_build_budget = []
mut baseline_builder_fill_idle_samples = []
mut feature_builder_fill_idle_samples = []
mut baseline_validation_latency_values = []
mut feature_validation_latency_values = []
mut baseline_builder_gas_values = []
mut feature_builder_gas_values = []
mut baseline_validation_gas_values = []
mut feature_validation_gas_values = []
mut baseline_serialized_block_size_values = []
mut feature_serialized_block_size_values = []
mut baseline_serialized_block_size_per_tx_values = []
mut feature_serialized_block_size_per_tx_values = []
let compute_block_time_stats = { |intervals: list<any>|
let sorted_intervals = ($intervals | sort)
{
p50: (percentile $sorted_intervals 50 | math round --precision 1)
p90: (percentile $sorted_intervals 90 | math round --precision 1)
p99: (percentile $sorted_intervals 99 | math round --precision 1)
}
}
let compute_value_stats = { |values: list<any>|