# Ractor benchmarks (Ruby 4.0). One JSON line per run on stdout.
#   ruby --yjit rb.rb scale <workload> <model> <W>    workload: int float str hash json sym ; model: threads ractors fork
#   ruby --yjit rb.rb msg <mode> <n>                  mode: thread copy move shareable ; n = strings of 100 B in the payload
#   ruby --yjit rb.rb spawn <model>                   model: thread ractor fork
#   ruby --yjit rb.rb mem <model>                     model: thread ractor  (RSS per idle worker)
require "json"
Warning[:experimental] = false

def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
def median(a) = a.sort[a.size / 2]
def rss_kb(f = "VmRSS") = File.read("/proc/self/status")[/#{f}:\s+(\d+)/, 1].to_i
def emit(h) = puts(JSON.generate(h.merge(ruby: RUBY_VERSION, yjit: defined?(RubyVM::YJIT) && RubyVM::YJIT.enabled?, cpus: Etc.nprocessors)))
require "etc"

# ---------- workloads: task(i) -> Integer; every task does the same amount of work ----------
def fib(n) = n < 2 ? n : fib(n - 1) + fib(n - 2)

def w_int(i) = fib(22) + i

def w_float(i)                       # flonums: no heap allocation on 64-bit
  x = 0.0; y = 0.0; k = 0
  20_000.times { |j| x = x * 0.5 + (j + i) * 1.0e-3; y += x * x; k += 1 }
  (y * 1000).to_i + k
end

def w_str(i)                         # 2,000 short String objects
  a = Array.new(2_000) { |j| "item-#{i}-#{j}" }
  a.sum(&:bytesize)
end

def w_hash(i)                        # 500 Hash rows with a nested Array
  rows = Array.new(500) { |j| { id: j, name: "n#{j}", tags: [i, j, i + j] } }
  rows.sum { |r| r[:id] + r[:tags].sum + r[:name].bytesize }
end

DOC = Ractor.make_shareable(JSON.generate(Array.new(200) { |j| { "id" => j, "name" => "user-#{j}", "score" => j * 0.5, "tags" => %w[a b c], "active" => j.odd? } }))
def w_json(i)                        # parse a 15 KB document
  JSON.parse(DOC).sum { |r| r["id"] + r["name"].bytesize + r["tags"].size } + i
end

def w_sym(i)                         # 2,000 String -> Symbol lookups (all symbols already exist)
  s = 0
  2_000.times { |j| s += SYMSTR[(i + j) % 1000].to_sym.size }
  s
end
SYMSTR = Ractor.make_shareable(Array.new(1000) { |j| "sym_#{j}" })
SYMSTR.each(&:to_sym)

TASKS = { "int" => 256, "float" => 256, "str" => 512, "hash" => 512, "json" => 512, "sym" => 1024 }

def run_share(wl, ids) = ids.sum { |i| __send__(:"w_#{wl}", i) }   # not send: inside a Ractor block self is the Ractor, and Ractor#send is messaging

# ---------- scale ----------
def scale(wl, model, w)
  total = TASKS.fetch(wl)
  shares = Array.new(w) { |k| (k...total).step(w).to_a }
  rep = case model
  when "threads"
    qs = Array.new(w) { Queue.new }; out = Queue.new
    w.times { |k| Thread.new { while qs[k].pop; out << run_share(wl, shares[k]); end } }
    -> { qs.each { _1 << true }; Array.new(w) { out.pop }.sum }
  when "ractors"
    out = Ractor::Port.new
    rs = Array.new(w) { |k| Ractor.new(wl, shares[k], out) { |wl, ids, out| while Ractor.receive; out << run_share(wl, ids); end } }
    -> { rs.each { _1.send(true) }; Array.new(w) { out.receive }.sum }
  when "fork"
    kids = Array.new(w) do |k|
      cr, cw = IO.pipe; pr, pw = IO.pipe
      pid = fork { cw.close; pr.close; while cr.gets; pw.puts run_share(wl, shares[k]); end; exit! 0 }
      cr.close; pw.close; [cw, pr, pid]
    end
    -> { kids.each { |cw, _, _| cw.puts "go" }; kids.sum { |_, pr, _| pr.gets.to_i } }
  else abort "model?"
  end
  sums = []; times = []
  t_end = now + 3.0; reps = 0
  2.times { sums << rep.call }                                    # warm-up
  GC.disable if ENV["RB_GC_OFF"] == "1"                            # C1 ceiling: no GC during the timed reps
  g0 = GC.stat.slice(:count, :time, :minor_gc_count, :major_gc_count)
  while reps < 5 || now < t_end
    t = now; sums << rep.call; times << now - t; reps += 1
  end
  g1 = GC.stat.slice(:count, :time, :minor_gc_count, :major_gc_count)
  abort "checksum drift #{sums.uniq}" unless sums.uniq.size == 1
  t = median(times)
  gc = { gc_per_rep: ((g1[:count] - g0[:count]) / reps.to_f).round(2), gc_ms_per_rep: ((g1[:time] - g0[:time]) / reps.to_f).round(2),
         gc_share: ((g1[:time] - g0[:time]) / 1000.0 / times.sum).round(4) }
  emit(test: "scale", workload: wl, model: model, w: w, tasks: total, reps: reps, median_s: t.round(6),
       tasks_per_s: (total / t).round(1), checksum: sums[0], peak_rss_kb: rss_kb("VmHWM"), gc_off: ENV["RB_GC_OFF"] == "1", gc_env: ENV.select { |k, _| k.start_with?("RUBY_GC_") }, **gc)
end

# ---------- msg: one message to an echo Ractor and a 1-int reply ----------
def payload(n) = Array.new(n) { |j| ("x" * 92) + format("%08d", j) }   # n strings of 100 B

def msg(mode, n)
  iters = [[200_000 / [n, 1].max, 20].max, 2_000].min
  if mode == "thread"
    q = Queue.new; back = Queue.new
    Thread.new { while (o = q.pop); back << o.size; end }
    obj = payload(n)
    send1 = ->(_) { q << obj; back.pop }
  else
    back = Ractor::Port.new
    r = Ractor.new(back) { |b| while (o = Ractor.receive); b << o.size; end }
    case mode
    when "copy"      then obj = payload(n); send1 = ->(_) { r.send(obj); back.receive }
    when "move"      then pool = Array.new(iters + 3) { payload(n) }; send1 = ->(k) { r.send(pool[k], move: true); back.receive }
    when "shareable"
      obj = payload(n)
      t = now; Ractor.make_shareable(obj); share_s = now - t
      send1 = ->(_) { r.send(obj); back.receive }
    else abort "mode?"
    end
  end
  3.times { |k| abort "bad reply" unless send1.(k) == n }
  ts = Array.new(iters) { |k| t = now; abort "bad reply" unless send1.(k + 3) == n; now - t }
  emit(test: "msg", mode: mode, n: n, bytes: n * 100, iters: iters, median_us: (median(ts) * 1e6).round(2),
       p10_us: (ts.sort[iters / 10] * 1e6).round(2), make_shareable_us: share_s && (share_s * 1e6).round(1), checksum: n)
end

# ---------- spawn: create one worker, run an empty block, wait for it ----------
def spawn_cost(model)
  one = case model
  when "thread" then -> { Thread.new { 1 }.value }
  when "ractor" then -> { Ractor.new { 1 }.value }
  when "fork"   then -> { pid = fork { exit! 0 }; Process.wait(pid); 1 }
  else abort "model?"
  end
  n = model == "fork" ? 300 : 2_000
  50.times { one.() }
  ts = Array.new(n) { t = now; one.(); now - t }
  emit(test: "spawn", model: model, n: n, median_us: (median(ts) * 1e6).round(2), p90_us: (ts.sort[n * 9 / 10] * 1e6).round(2), checksum: 1)
end

# ---------- mem: RSS added by 200 idle workers that each ran fib(15) once ----------
def mem(model)
  n = 200
  GC.start; base = rss_kb
  ws = case model
  when "thread" then Array.new(n) { q = Queue.new; [Thread.new { fib(15); q.pop }, q] }
  when "ractor" then Array.new(n) { Ractor.new { fib(15); Ractor.receive } }
  else abort "model?"
  end
  sleep 0.5; GC.start; after = rss_kb
  model == "thread" ? ws.each { |t, q| q << 1; t.join } : ws.each { |r| r.send(1); r.join }
  emit(test: "mem", model: model, n: n, kb_per_worker: ((after - base) / n.to_f).round(1), checksum: n)
end

case ARGV[0]
when "scale" then scale(ARGV[1], ARGV[2], Integer(ARGV[3]))
when "msg"   then msg(ARGV[1], Integer(ARGV[2]))
when "spawn" then spawn_cost(ARGV[1])
when "mem"   then mem(ARGV[1])
else abort "usage: see header"
end
