wardite 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. checksums.yaml +4 -4
  2. data/Makefile +9 -1
  3. data/README.md +65 -7
  4. data/Steepfile +1 -0
  5. data/assets/wardite.svg +12 -0
  6. data/benchmark/count_ruby_wasm_functions.rb +37 -0
  7. data/benchmark/measure_mir_cache_restore.rb +59 -0
  8. data/benchmark/measure_mir_cache_verify.rb +58 -0
  9. data/benchmark/measure_ruby_wasm_cache_hit.rb +59 -0
  10. data/benchmark/measure_ruby_wasm_startup.rb +43 -0
  11. data/benchmark/results/efflorescence-mir2-cache-integrity.json +390 -0
  12. data/benchmark/results/efflorescence-mir2-function-restore.json +480 -0
  13. data/benchmark/results/efflorescence-unboxed-globals.json +3451 -0
  14. data/docs/adr/0007-efflorescence-ruby-wasm-phase1.md +75 -0
  15. data/docs/adr/0008-efflorescence-ruby-wasm-phase2.md +75 -0
  16. data/docs/adr/0009-efflorescence-mir2-cache-integrity-modes.md +77 -0
  17. data/docs/adr/0010-efflorescence-mir2-cache-function-restore.md +80 -0
  18. data/docs/adr/0011-efflorescence-unboxed-globals.md +89 -0
  19. data/docs/adr/0012-efflorescence-startup-snapshot.md +173 -0
  20. data/docs/adr/0013-efflorescence-frame-acquisition.md +114 -0
  21. data/docs/efflorescence-generated-c-guards.md +5 -0
  22. data/docs/efflorescence-mir2-cache.md +152 -0
  23. data/docs/efflorescence-ruby-wasm-phase1.md +90 -0
  24. data/docs/efflorescence-spinel-linear-memory.md +74 -0
  25. data/docs/efflorescence-startup-snapshot.md +60 -0
  26. data/docs/efflorescence-unboxed-globals.md +61 -0
  27. data/lib/wardite/alu_f32.generated.rb +10 -2
  28. data/lib/wardite/alu_f64.generated.rb +10 -2
  29. data/lib/wardite/alu_i32.generated.rb +40 -8
  30. data/lib/wardite/alu_i64.generated.rb +55 -11
  31. data/lib/wardite/cli/cli.rb +58 -6
  32. data/lib/wardite/efflorescence/ir.rb +26 -4
  33. data/lib/wardite/efflorescence/mir_cache.rb +749 -0
  34. data/lib/wardite/efflorescence/register_validation.rb +128 -56
  35. data/lib/wardite/efflorescence/snapshot.rb +232 -0
  36. data/lib/wardite/efflorescence/store_access.rb +103 -8
  37. data/lib/wardite/efflorescence/translator.rb +10 -3
  38. data/lib/wardite/efflorescence/vm.rb +203 -38
  39. data/lib/wardite/efflorescence/wasi.rb +0 -56
  40. data/lib/wardite/efflorescence.rb +6 -0
  41. data/lib/wardite/load.rb +109 -24
  42. data/lib/wardite/version.rb +1 -1
  43. data/lib/wardite/wasi/spinel.rb +41 -0
  44. data/lib/wardite/wasi.rb +483 -268
  45. data/lib/wardite.rb +218 -70
  46. data/scripts/build_spinel_zig.rb +121 -0
  47. data/scripts/gen_alu.rb +55 -11
  48. data/scripts/verify_ruby_wasm.rb +70 -0
  49. data/sig/generated/wardite/cli/cli.rbs +15 -0
  50. data/sig/generated/wardite/efflorescence/ir.rbs +12 -2
  51. data/sig/generated/wardite/efflorescence/mir_cache.rbs +263 -0
  52. data/sig/generated/wardite/efflorescence/register_validation.rbs +31 -3
  53. data/sig/generated/wardite/efflorescence/snapshot.rbs +84 -0
  54. data/sig/generated/wardite/efflorescence/store_access.rbs +13 -2
  55. data/sig/generated/wardite/efflorescence/translator.rbs +5 -1
  56. data/sig/generated/wardite/efflorescence/vm.rbs +68 -7
  57. data/sig/generated/wardite/efflorescence/wasi.rbs +0 -13
  58. data/sig/generated/wardite/load.rbs +33 -5
  59. data/sig/generated/wardite/wasi/spinel.rbs +15 -0
  60. data/sig/generated/wardite/wasi.rbs +111 -4
  61. data/sig/generated/wardite.rbs +67 -3
  62. data/sig/io_buffer.rbs +7 -0
  63. data/sig/mir_cache_stdlib.rbs +5 -0
  64. metadata +32 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0d4da4f11b96b8ba754957752182019d0f5e1b398c857ff53aff1dd832976273
4
- data.tar.gz: 51beb8eca890338b30d724f14625d2f61eaeddf43c541a6a24ba2486207e1d37
3
+ metadata.gz: 3b374367cbbab2b2e5f937c73cff6c53df9c62f4c62653d294b28c683b015e59
4
+ data.tar.gz: b72512938d20ffdbdbb9537867fa0c631ab6455b51aae271d97f947bcca3126d
5
5
  SHA512:
6
- metadata.gz: 6e43c0e691c242623cc3e4acf622286d151e59793b7afcae6eed08d2291088446459ad91728e6f65b1997ee89f8a42753fc942622aea7f7e8b56f2da6b41b40d
7
- data.tar.gz: 6122649785369333e8f6fc345d2b4717eee2579e56e5df50b76e72fc6dfd20a0bbc9f3332ce06a02c555b21e55e6318d191d2bb10271279045f2f920c62a694d
6
+ metadata.gz: 1af12383881dc3bac104e53bce974eccdcaef83cb4029b64395c75db05ffc8dc2d4a22030c97ae80a56e100cbe5e13fe56c6cf5e50439d5418c7f8f44448d262
7
+ data.tar.gz: 36e9b39213cde17b08235b9036f860a280f8bcc266a029b48c3f2d060387ec9fbe27101e14e3a0dd64e1f38cb5d9348711fe698209025ac3366676967a5a8eb1
data/Makefile CHANGED
@@ -2,8 +2,13 @@ SPINEL ?= spinel
2
2
  SPINELFLAGS ?= -O2
3
3
  RUBY ?= ruby
4
4
  BUILD_DIR ?= build
5
+ ZIG ?= zig
6
+ ZIG_GLIBC ?= 2.28
7
+ ZIG_MACOS ?= 13.0
8
+ ZIG_JOBS ?= 8
9
+ ZIG_TARGETS ?= aarch64-macos x86_64-linux aarch64-linux
5
10
 
6
- .PHONY: spinel spinel-test
11
+ .PHONY: spinel spinel-test spinel-zig
7
12
 
8
13
  # Keep inline RBS and the compiler's default integer overflow checks enabled.
9
14
  spinel:
@@ -12,3 +17,6 @@ spinel:
12
17
 
13
18
  spinel-test: spinel
14
19
  WARDITE_SPINEL_BIN="$(abspath $(BUILD_DIR)/wardite)" $(RUBY) -Ilib:test -e 'Dir["test/e2e/spinel*_test.rb"].each { |path| require_relative path }'
20
+
21
+ spinel-zig:
22
+ ZIG="$(ZIG)" $(RUBY) scripts/build_spinel_zig.rb "$(MAKE)" "$(BUILD_DIR)" "$(ZIG_GLIBC)" "$(ZIG_MACOS)" "$(ZIG_JOBS)" "$(SPINELFLAGS)" $(ZIG_TARGETS)
data/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # Wardite
2
2
 
3
- [![workflow](https://github.com/udzura/wardite/actions/workflows/main.yml/badge.svg)](https://github.com/udzura/wardite/actions) [![gem version](https://badge.fury.io/rb/wardite.svg)](https://rubygems.org/gems/wardite)
3
+ <img src="assets/wardite.svg" alt="Wardite logo" width="160">
4
+
5
+ [![Test CRuby and Spinel](https://github.com/udzura/wardite/actions/workflows/runtime-tests.yml/badge.svg)](https://github.com/udzura/wardite/actions/workflows/runtime-tests.yml) [![Test Wardite](https://github.com/udzura/wardite/actions/workflows/spec.yml/badge.svg)](https://github.com/udzura/wardite/actions/workflows/spec.yml) [![gem version](https://badge.fury.io/rb/wardite.svg)](https://rubygems.org/gems/wardite)
4
6
 
5
7
  A pure-ruby webassembly runtime.
6
8
 
@@ -80,6 +82,31 @@ Use `--mir-disable NAME` to compare
80
82
  individual features, `--mir-dump` to inspect MIR and `--mir-profile` for counters.
81
83
  See [Phase 2](docs/efflorescence-phase2.md) ([日本語](docs/efflorescence-phase2-ja.md)).
82
84
 
85
+ On CRuby and Spinel, pass `--mir-cache DIR` with `--new-engine` to reuse lowered
86
+ MIR across processes. Use a local directory you control. Each run still decodes
87
+ the Wasm, links imports, and initializes a fresh instance. `--mir-dump` and
88
+ `--mir-profile` build MIR normally. Ruby callers can pass `mir_cache: dir` with
89
+ `engine: :efflorescence`. CRuby and Spinel use different cache keys.
90
+
91
+ The default `--mir-cache-verify checksum` checks the payload size and samples
92
+ blocks. Use `--mir-cache-verify sha256` or Ruby's `mir_cache_verify: :sha256`
93
+ to check the whole payload. Both modes use the same cache file. By default,
94
+ each function is restored and structurally checked before its first execution.
95
+ Use `--mir-cache-eager` or Ruby's `mir_cache_eager: true` to check every
96
+ function at load time. If a lazy check fails, Wardite stops and reports the
97
+ cache path. Delete that file and rerun. Corruption outside the sampled blocks
98
+ can go undetected in checksum mode, including changes that leave the MIR
99
+ structurally valid.
100
+ [MIR2 cache measurements](docs/efflorescence-mir2-cache.md)
101
+
102
+ For WASI commands, `--snapshot DIR` (with `--new-engine --mir-cache DIR`) saves
103
+ the guest state just before its first WASI call that reads files or writes output,
104
+ and later runs with the same Wasm, arguments, environment, preopens and stdio
105
+ kinds resume from there. Clock values and random bytes read before that point
106
+ are frozen into the snapshot, so every resumed run sees the same values (for Ruby, the same hash
107
+ seed). Do not use it where that matters, such as hashing untrusted keys.
108
+ [ADR 0012](docs/adr/0012-efflorescence-startup-snapshot.md)
109
+
83
110
  [M1](docs/efflorescence-m1.md) adds the remaining basic i32 operations,
84
111
  if/else/select/br_table, and new exception handling (try_table/throw/throw_ref).
85
112
  Tags can carry numeric payloads. Nullable exnref locals and multi-result blocks carry
@@ -130,18 +157,49 @@ return value: I32(300)
130
157
  $ make spinel-test
131
158
  ```
132
159
 
133
- The executable defaults to WASI disabled. This initial integration tests small
134
- Wasm modules with `i32.const`, `i32.add`, internal calls, and `if`/`else`, comparing
135
- the native CLI's results with CRuby. WASI and Vernier profiling are excluded from
136
- the native build. Ruby's dynamic export helpers (`instance.add(...)` and
160
+ The executable enables the shared WASI Preview 1 host by default. Use
161
+ `--no-wasi` to disable it. To boot a Ruby 4.0.9 WASI binary, run
162
+ `build/wardite --new-engine -- "$ruby_wasm" --disable-gems -e 'puts 6*7'`.
163
+ See the [ruby.wasm verification record](docs/efflorescence-ruby-wasm-phase1.md)
164
+ for the build and file-loading commands. Vernier profiling is available in the
165
+ CRuby build. Ruby's dynamic export helpers (`instance.add(...)` and
137
166
  `runtime.add(...)`) rely on `method_missing`; use `instance.runtime.call("add",
138
167
  [100, 200])` when compiling an application with Spinel.
139
168
 
140
169
  The build leaves inline RBS and Spinel's default integer overflow checks enabled.
141
170
  Wasm integer operations bound their intermediate values, so
142
171
  `--int-overflow=promote` is not required.
143
- Tested with Spinel `2026.10.25+1967` (`6e7fc1355`) on macOS
144
- arm64. Override `SPINEL`, `SPINELFLAGS`, `BUILD_DIR`, or `RUBY` when needed.
172
+ CI builds Spinel from the upstream commit `58ee6361`, which includes the
173
+ required `IO::Buffer` changes.
174
+ See the [build instructions and host memory API](docs/efflorescence-spinel-linear-memory.md).
175
+ Override `SPINEL`, `SPINELFLAGS`, `BUILD_DIR`, or `RUBY` when needed.
176
+
177
+ #### Cross-compile from macOS with Zig
178
+
179
+ With Zig 0.17.1, Ruby, and the Xcode Command Line Tools installed, run:
180
+
181
+ ```sh
182
+ make spinel-zig
183
+ ```
184
+
185
+ The first build downloads and builds the same Spinel revision used in CI.
186
+ It builds the Spinel runtime and native StringIO code for each target and
187
+ uses Zig to compile and link the resulting Wardite executables.
188
+
189
+ | Target | Executable |
190
+ | --- | --- |
191
+ | macOS arm64 | `build/spinel-zig/aarch64-macos.13.0/wardite` |
192
+ | Linux x86_64 | `build/spinel-zig/x86_64-linux-gnu.2.28/wardite` |
193
+ | Linux arm64 | `build/spinel-zig/aarch64-linux-gnu.2.28/wardite` |
194
+
195
+ Linux builds dynamically link the target system's glibc. The default glibc
196
+ baseline is 2.28 and the macOS deployment target is 13.0. Set `ZIG_GLIBC`
197
+ or `ZIG_MACOS` to change those values. Use `ZIG` to select the compiler,
198
+ `ZIG_JOBS` to set parallelism, or `ZIG_TARGETS` to build a subset:
199
+
200
+ ```sh
201
+ make spinel-zig ZIG=/opt/homebrew/bin/zig ZIG_TARGETS=x86_64-linux
202
+ ```
145
203
 
146
204
  ## Contributing
147
205
 
data/Steepfile CHANGED
@@ -6,6 +6,7 @@ target :lib do
6
6
  library "pp"
7
7
  library "securerandom"
8
8
  library "optparse"
9
+ library "fileutils"
9
10
  # configure_code_diagnostics(Steep::Diagnostic::Ruby.strict)
10
11
  end
11
12
 
@@ -0,0 +1,12 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" role="img" aria-labelledby="title description">
2
+ <title id="title">Wardite icon</title>
3
+ <desc id="description">A white W carved into a faceted teal mineral, with a dark offset shadow.</desc>
4
+ <rect width="1024" height="1024" fill="#f8f5f0"/>
5
+ <path fill="#17141f" d="M418 230h324l136 136v324L742 826H324l-42-110V366Z"/>
6
+ <path fill="#287a78" d="M350 162h324l136 136v324L674 758H256l-42-110V298Z"/>
7
+ <path fill="#65aaa0" d="M350 162h324l-62 110H384l-170 26Z"/>
8
+ <path fill="#398f88" d="m214 298 170-26-70 328-58 158-42-110Z"/>
9
+ <path fill="#1d5b60" d="m674 162 136 136v324L674 758l-42-154 78-260Z"/>
10
+ <path fill="#226b6b" d="m314 600 318 4 42 154H256Z"/>
11
+ <path d="M326 350h66l38 172 60-130h48l34 130 68-172h66L600 602h-60l-34-128-60 128h-60Z" fill="#fff"/>
12
+ </svg>
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Pass Wardite's normal CLI arguments. Run on CRuby outside timing samples.
4
+ require "json"
5
+ require "wardite"
6
+ require "wardite/cli/cli"
7
+
8
+ module FunctionCoverage
9
+ DEFINED = {}
10
+ CALLS = Hash.new(0)
11
+
12
+ def initialize(function, *args)
13
+ @coverage_index = function.index
14
+ DEFINED[@coverage_index] = true
15
+ super
16
+ end
17
+
18
+ def acquire(destination)
19
+ CALLS[@coverage_index] += 1
20
+ super
21
+ end
22
+ end
23
+
24
+ Wardite::Efflorescence::FramePool.prepend(FunctionCoverage)
25
+ at_exit do
26
+ calls = FunctionCoverage::CALLS.values.sort.reverse
27
+ total = calls.sum
28
+ cumulative = 0
29
+ hot = calls.take_while do |count|
30
+ more = cumulative * 10 < total * 9
31
+ cumulative += count
32
+ more
33
+ end
34
+ warn JSON.generate(defined: FunctionCoverage::DEFINED.size, used: calls.size,
35
+ calls: total, functions_for_ninety_percent: hot.size)
36
+ end
37
+ Wardite::Cli::Cli.new(ARGV).run
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Usage: ruby benchmark/measure_mir_cache_restore.rb WASM BEFORE_BIN DIRECT_BIN [LAZY_BIN]
4
+ require "digest"
5
+ require "json"
6
+ require "open3"
7
+ require "tmpdir"
8
+
9
+ abort "Usage: ruby #{$PROGRAM_NAME} WASM BEFORE_BIN DIRECT_BIN [LAZY_BIN]" unless (3..4).cover?(ARGV.size)
10
+ wasm, *binaries = ARGV.map { |path| File.expand_path(path) }
11
+ runs = Integer(ENV.fetch("RUNS", "6"))
12
+ warmups = Integer(ENV.fetch("WARMUPS", "1"))
13
+ abort "Invalid run or warmup count" unless runs >= 3 && warmups >= 0
14
+ snapshot = ENV["SNAPSHOT"] == "1"
15
+
16
+ guest = ["--disable-gems", "-e", "puts RUBY_VERSION"]
17
+ expected, status = Open3.capture2("wasmtime", "run", wasm, *guest)
18
+ abort "Wasmtime did not run Ruby 4.0.9" unless status.success? && expected == "4.0.9\n"
19
+
20
+ macos = RUBY_PLATFORM.include?("darwin")
21
+ timer = macos ? ["/usr/bin/time", "-l"] : ["/usr/bin/time", "-f", "%M maximum RSS KiB"]
22
+ rss_pattern = macos ? /^\s*(\d+)\s+maximum resident set size$/ : /^(\d+) maximum RSS KiB$/
23
+ invoke = lambda do |command, *traces|
24
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
25
+ stdout, stderr, status = Open3.capture3({"WARDITE_TRACE" => "1"}, *timer, *command, unsetenv_others: true)
26
+ total = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
27
+ load = stderr[/^load_from_buffer: (\S+)$/, 1]
28
+ rss = stderr[rss_pattern, 1]
29
+ unless status.success? && stdout == expected && load && rss && traces.all? { |trace| stderr.include?(trace) }
30
+ abort "#{command.inspect}\n#{stdout}#{stderr}"
31
+ end
32
+ {load_seconds: Float(load), process_seconds: total, after_load_seconds: total - Float(load),
33
+ peak_rss_bytes: Integer(rss) * (macos ? 1 : 1024)}
34
+ end
35
+
36
+ samples = Dir.mktmpdir("wardite-mir-cache-restore") do |directory|
37
+ commands = %w[before direct lazy].zip(binaries).filter_map do |version, binary|
38
+ next unless binary
39
+ command = [binary, "--new-engine", "--mir-cache", File.join(directory, version)]
40
+ command += ["--snapshot", File.join(directory, "#{version}-snapshot")] if snapshot
41
+ [version, [*command, "--", wasm, *guest]]
42
+ end
43
+ miss = ["MIR2 cache miss:"]
44
+ hit = ["MIR2 cache hit:"]
45
+ if snapshot
46
+ miss << "snapshot saved:"
47
+ hit << "snapshot restored:"
48
+ end
49
+ commands.each { |_, command| invoke.call(command, *miss) }
50
+ (warmups + runs).times.flat_map do |iteration|
51
+ commands.rotate(iteration).filter_map do |version, command|
52
+ sample = invoke.call(command, *hit)
53
+ sample.merge(version: version, run: iteration - warmups + 1) if iteration >= warmups
54
+ end
55
+ end
56
+ end
57
+
58
+ puts JSON.pretty_generate(wasm_sha256: Digest::SHA256.file(wasm).hexdigest, guest_arguments: guest,
59
+ runs: runs, warmups: warmups, snapshot: snapshot, samples: samples)
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Usage: ruby benchmark/measure_mir_cache_verify.rb RUBY_WASM BASELINE_BIN CURRENT_BIN
4
+ require "digest"
5
+ require "json"
6
+ require "open3"
7
+ require "tmpdir"
8
+
9
+ abort "Usage: ruby #{$PROGRAM_NAME} RUBY_WASM BASELINE_BIN CURRENT_BIN" unless ARGV.size == 3
10
+ wasm, baseline, current = ARGV.map { |path| File.expand_path(path) }
11
+ runs = Integer(ENV.fetch("RUNS", "9"))
12
+ warmups = Integer(ENV.fetch("WARMUPS", "2"))
13
+ abort "Invalid run or warmup count" unless runs >= 3 && warmups >= 0
14
+
15
+ guest = ["--disable-gems", "-e", "puts RUBY_VERSION"]
16
+ expected, status = Open3.capture2("wasmtime", "run", wasm, *guest)
17
+ abort "Wasmtime did not run Ruby 4.0.9" unless status.success? && expected == "4.0.9\n"
18
+
19
+ def invoke(command, expected, *traces)
20
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
21
+ stdout, stderr, status = Open3.capture3({"WARDITE_TRACE" => "1"}, *command, unsetenv_others: true)
22
+ total = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
23
+ load_time = stderr[/^load_from_buffer: (\S+)$/, 1]
24
+ unless status.success? && stdout == expected && load_time && traces.all? { |trace| stderr.include?(trace) }
25
+ abort "#{command.inspect}\n#{stdout}#{stderr}"
26
+ end
27
+ {load_seconds: Float(load_time), process_seconds: total}
28
+ end
29
+
30
+ samples = Dir.mktmpdir("wardite-mir-cache-verify") do |directory|
31
+ baseline_cache = [baseline, "--new-engine", "--mir-cache", File.join(directory, "before")]
32
+ current_cache = [current, "--new-engine", "--mir-cache", File.join(directory, "after")]
33
+ inputs = ["--", wasm, *guest]
34
+ snapshot = ->(version) { ["--snapshot", File.join(directory, "#{version}-snapshot")] }
35
+ invoke([*baseline_cache, *snapshot.call("before"), *inputs], expected, "MIR2 cache miss:", "snapshot saved:")
36
+ invoke([*current_cache, *snapshot.call("after"), *inputs], expected, "MIR2 cache miss:", "snapshot saved:")
37
+
38
+ [false, true].flat_map do |with_snapshot|
39
+ commands = {
40
+ "before" => baseline_cache,
41
+ "sha256" => [*current_cache, "--mir-cache-verify", "sha256"],
42
+ "checksum" => [*current_cache, "--mir-cache-verify", "checksum"],
43
+ }
44
+ traces = ["MIR2 cache hit:"]
45
+ traces << "snapshot restored:" if with_snapshot
46
+ (warmups + runs).times.flat_map do |iteration|
47
+ commands.keys.rotate(iteration).filter_map do |mode|
48
+ command = commands.fetch(mode)
49
+ command = [*command, *snapshot.call(mode == "before" ? "before" : "after")] if with_snapshot
50
+ sample = invoke([*command, *inputs], expected, *traces)
51
+ sample.merge(mode: mode, snapshot: with_snapshot, run: iteration - warmups + 1) if iteration >= warmups
52
+ end
53
+ end
54
+ end
55
+ end
56
+
57
+ puts JSON.pretty_generate(wasm_sha256: Digest::SHA256.file(wasm).hexdigest, guest_arguments: guest,
58
+ runs: runs, warmups: warmups, samples: samples)
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Usage: ruby benchmark/measure_ruby_wasm_cache_hit.rb RUBY_WASM BASELINE BASELINE_BIN CURRENT_BIN
4
+ require "digest"
5
+ require "json"
6
+ require "open3"
7
+ require "rbconfig"
8
+ require "tmpdir"
9
+
10
+ wasm, baseline, baseline_bin, current_bin = ARGV.map { |path| File.expand_path(path) }
11
+ abort "Usage: ruby #{$PROGRAM_NAME} RUBY_WASM BASELINE BASELINE_BIN CURRENT_BIN" unless ARGV.size == 4
12
+ current = File.expand_path("..", __dir__)
13
+ runs = Integer(ENV.fetch("RUNS", "7"))
14
+ warmups = Integer(ENV.fetch("WARMUPS", "2"))
15
+ abort "Invalid run or warmup count" unless runs >= 3 && warmups >= 0
16
+
17
+ guest = ["--disable-gems", "-e", "puts RUBY_DESCRIPTION"]
18
+ expected, status = Open3.capture2("wasmtime", "run", wasm, *guest)
19
+ abort "Wasmtime did not run Ruby 4.0.9" unless status.success? && expected.start_with?("ruby 4.0.9 ")
20
+
21
+ commands = [
22
+ ["Spinel", "before", [baseline_bin]],
23
+ ["Spinel", "after", [current_bin]],
24
+ ]
25
+ { "CRuby" => "--disable-yjit", "CRuby YJIT" => "--yjit" }.each do |runtime, option|
26
+ { "before" => baseline, "after" => current }.each do |version, root|
27
+ commands << [runtime, version, [RbConfig.ruby, option, "-I#{root}/lib", "#{root}/exe/wardite"]]
28
+ end
29
+ end
30
+
31
+ samples = Dir.mktmpdir("wardite-cache-hit") do |cache|
32
+ args = ["--new-engine", "--mir-cache", cache, "--", wasm, *guest]
33
+ run = lambda do |command, cache_status|
34
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
35
+ stdout, stderr, status = Open3.capture3({ "WARDITE_TRACE" => "1" }, *command, *args)
36
+ total = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
37
+ load = stderr[/^load_from_buffer: (\S+)$/, 1]
38
+ unless status.success? && stdout == expected && stderr.include?("MIR2 cache #{cache_status}:") && load
39
+ abort "#{command.inspect}\n#{stdout}#{stderr}"
40
+ end
41
+ load = Float(load)
42
+ { process_seconds: total, load_seconds: load, guest_seconds: total - load }
43
+ end
44
+
45
+ # MIR2 keys include the runtime, so prime both native and CRuby entries.
46
+ commands.select { |runtime, version, _| version == "before" && runtime != "CRuby YJIT" }.each do |_, _, command|
47
+ run.call(command, "miss")
48
+ end
49
+ (warmups + runs).times.flat_map do |iteration|
50
+ order = iteration.even? ? commands : commands.reverse
51
+ order.filter_map do |runtime, version, command|
52
+ result = run.call(command, "hit")
53
+ result.merge(runtime: runtime, version: version, run: iteration - warmups + 1) if iteration >= warmups
54
+ end
55
+ end
56
+ end
57
+
58
+ puts JSON.pretty_generate(wasm_sha256: Digest::SHA256.file(wasm).hexdigest, guest: expected.strip,
59
+ guest_arguments: guest, host_ruby: RUBY_DESCRIPTION, warmups: warmups, runs: runs, samples: samples)
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "wardite"
5
+ require "wardite/cli/cli"
6
+
7
+ module StartupMeasurement
8
+ SECONDS = Hash.new(0.0)
9
+
10
+ def self.measure(klass, method_name, phase)
11
+ wrapper = Module.new do
12
+ define_method(method_name) do |*args, **kwargs, &block|
13
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
14
+ super(*args, **kwargs, &block)
15
+ ensure
16
+ SECONDS[phase] += Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
17
+ end
18
+ private method_name if klass.private_method_defined?(method_name)
19
+ end
20
+ klass.prepend(wrapper)
21
+ end
22
+ end
23
+
24
+ wasm = ARGV.shift || abort("Usage: ruby -Ilib #{$PROGRAM_NAME} RUBY.wasm [--mir-cache DIR]")
25
+ efflorescence = Wardite::Efflorescence
26
+ StartupMeasurement.measure(Wardite::BinaryLoader.singleton_class, :sections, :decode)
27
+ StartupMeasurement.measure(Wardite::Store, :initialize, :store)
28
+ StartupMeasurement.measure(efflorescence::Translator, :translate, :translate)
29
+ StartupMeasurement.measure(efflorescence::Optimizer, :optimize, :optimize)
30
+ StartupMeasurement.measure(efflorescence::RegisterValidation, :validate, :validate)
31
+ StartupMeasurement.measure(efflorescence::Lowerer, :compile, :lower)
32
+ StartupMeasurement.measure(efflorescence::VM, :call, :execute)
33
+ StartupMeasurement.measure(Wardite::Cli::Cli, :new_instance, :load)
34
+ if ARGV.include?("--mir-cache")
35
+ require "wardite/efflorescence/mir_cache"
36
+ StartupMeasurement.measure(efflorescence::MIRCache, :read, :cache_read)
37
+ StartupMeasurement.measure(efflorescence::MIRCache, :write, :cache_write)
38
+ end
39
+
40
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
41
+ Wardite::Cli::Cli.new(["--new-engine", *ARGV, "--", wasm, "--disable-gems", "-e", "puts RUBY_VERSION; puts 6*7"]).run
42
+ StartupMeasurement::SECONDS[:total] = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
43
+ warn JSON.generate(ruby: RUBY_DESCRIPTION, yjit: RubyVM::YJIT.enabled?, seconds: StartupMeasurement::SECONDS)