# bm28.rb <bm_file> <model> <W> <k> — one Spinel program under threads / ractors / fork, W workers on W cores.
# Prism splits the program: def/class/module/constant writes load once in the main Ractor (constants through
# Ractor.make_shareable, the same in every model); every other top-level statement becomes __bm_run, which
# captures $stdout. A task runs __bm_run k times and checks every output against Spinel's .expected.
# TASKS tasks per rep, split round-robin over W workers; 1 warm-up rep, then >= 2 reps and >= 3 s; median rep.
# One JSON line on stdout; a non-Ractor-safe program prints {error: …} and exits 0 (it is a result, not a crash).
require "prism"
require "stringio"
require "json"
require "etc"
Warning[:experimental] = false
file, model, w, k = ARGV.shift, ARGV.shift, Integer(ARGV.shift), Integer(ARGV.shift)
ARGV.clear
TASKS = 8
def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
def median(a) = a.sort[a.size / 2]
def pss_kb(pid) = File.read("/proc/#{pid}/smaps_rollup")[/^Pss:\s+(\d+)/, 1].to_i
def rss_kb(pid) = File.read("/proc/#{pid}/smaps_rollup")[/^Rss:\s+(\d+)/, 1].to_i
bm = File.basename(file, ".rb").sub(/\Abm_/, "")
out = { test: "bm28", bm: bm, model: model, w: w, k: k, tasks: TASKS, ruby: RUBY_VERSION,
        yjit: defined?(RubyVM::YJIT) && RubyVM::YJIT.enabled?, cpus: Etc.nprocessors }
EXPECTED = Ractor.make_shareable(File.read("#{file}.expected"))
stmts = Prism.parse(File.read(file)).value.statements.body
DEFN = [Prism::DefNode, Prism::ClassNode, Prism::ModuleNode, Prism::ConstantWriteNode, Prism::ConstantPathWriteNode]
defs, body = stmts.partition { |n| DEFN.any? { n.is_a?(_1) } }
defs_src = defs.map { |n| n.is_a?(Prism::ConstantWriteNode) ? "#{n.name} = Ractor.make_shareable(#{n.value.slice})" : n.slice }.join("\n")
TOPLEVEL_BINDING.eval(defs_src, file)
TOPLEVEL_BINDING.eval(<<~RUBY, file)
  def __bm_run
    o = StringIO.new; Thread.current[:bm_out] = o
    begin
  #{body.map(&:slice).join("\n")}
    ensure
      Thread.current[:bm_out] = nil
    end
    o.string
  end
  def __bm_task(k)
    k.times { raise "output != .expected" unless __bm_run == EXPECTED }
    1
  end
RUBY
Ractor.make_shareable(ARGV)
class BmOut   # $stdout forwarder: output goes to the calling thread's buffer, in every model
  def target = Thread.current[:bm_out] || STDOUT   # inside __bm_run: the run's buffer; outside (fork's flush, at_exit): the real stdout
  def write(*a) = target.write(*a)
  def method_missing(m, *a, &b) = target.__send__(m, *a, &b)
  def respond_to_missing?(*) = true
end
$stdout = BmOut.new

begin
  __bm_task(1)   # the program must be correct in the main Ractor first
rescue Exception => e
  STDOUT.puts JSON.generate(out.merge(error: "main: #{e.class}: #{e.message.lines.first.to_s.strip[0, 160]}")); exit 0
end

shares = Array.new(w) { |i| (i...TASKS).step(w).count }
rep = case model
when "threads"
  Thread.abort_on_exception = true   # a worker that raises ends the process (the cell fails) instead of leaving back.pop waiting
  qs = Array.new(w) { Queue.new }; back = Queue.new
  w.times { |i| Thread.new { while qs[i].pop; back << shares[i].times.sum { __bm_task(k) }; end } }
  -> { qs.each { _1 << true }; Array.new(w) { back.pop }.sum }
when "ractors"
  back = Ractor::Port.new
  begin   # one task in a Ractor first: a program that is not Ractor-safe is a result, not a hang
    Ractor.new(k) { |k| $stdout = BmOut.new; __bm_task(k) }.value
  rescue Ractor::RemoteError => e
    STDOUT.puts JSON.generate(out.merge(error: "ractor: #{e.cause.class}: #{e.cause.message.lines.first.to_s.strip[0, 160]}")); exit 0
  end
  rs = Array.new(w) { |i| Ractor.new(shares[i], k, back) { |n, k, b| $stdout = BmOut.new; while Ractor.receive; b << n.times.sum { __bm_task(k) }; end } }
  rs.each { _1.monitor(back) }       # a worker that dies posts :aborted to the results port -> the task count check fails the cell
  -> { rs.each { _1.send(true) }; Array.new(w) { v = back.receive; raise "ractor worker died: #{v.inspect}" unless v.is_a?(Integer); v }.sum }
when "fork"
  kids = Array.new(w) do |i|
    cr, cw = IO.pipe; pr, pw = IO.pipe
    pid = fork { cw.close; pr.close; while cr.gets; pw.puts(shares[i].times.sum { __bm_task(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

begin
  abort "task count" unless rep.call == TASKS   # warm-up rep
  times = []; t_end = now + 3.0
  while times.size < 2 || now < t_end
    t = now; abort "task count" unless rep.call == TASKS; times << now - t
  end
rescue Ractor::RemoteError => e
  STDOUT.puts JSON.generate(out.merge(error: "ractor: #{e.cause.class}: #{e.cause.message.lines.first.to_s.strip[0, 160]}")); exit 0
end
pids = [Process.pid] + (model == "fork" ? kids.map { _1[2] } : [])
t = median(times)
STDOUT.puts JSON.generate(out.merge(reps: times.size, median_s: t.round(6), runs_per_s: (TASKS * k / t).round(3),
  pss_kb: pids.sum { pss_kb(_1) }, rss_kb: pids.sum { rss_kb(_1) }, procs: pids.size, checksum: EXPECTED.bytesize))
if model == "fork"   # close every command pipe first: each later child holds copies of the earlier children's pipes,
  kids.each { |cw, _, _| cw.close }          # so closing and waiting one by one deadlocks; all closed, they exit last-to-first
  kids.each { |_, _, pid| Process.wait(pid) }
end
