Class: Rubyagents::Sandbox::ForkExecutor

Inherits:
Executor
  • Object
show all
Defined in:
lib/rubyagents/sandbox.rb

Overview

MRI / TruffleRuby: fork gives full process isolation and safe kill.

Instance Method Summary collapse

Methods inherited from Executor

for_platform

Instance Method Details

#call(timeout, &block) ⇒ Object



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
# File 'lib/rubyagents/sandbox.rb', line 25

def call(timeout, &block)
  reader, writer = IO.pipe

  pid = Process.fork do
    reader.close
    Marshal.dump(block.call, writer)
  rescue => e
    Marshal.dump({ error: "#{e.class}: #{e.message}" }, writer)
  ensure
    writer.close
    exit!(0)
  end

  writer.close

  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
  loop do
    _, status = Process.waitpid2(pid, Process::WNOHANG)
    if status
      break
    elsif Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
      Process.kill("KILL", pid)
      Process.waitpid(pid)
      reader.close
      return { error: "Execution timed out after #{timeout}s" }
    end
    sleep 0.05
  end

  data = reader.read
  reader.close

  data.empty? ? { output: "", result: nil, is_final_answer: false } : Marshal.load(data) # rubocop:disable Security/MarshalLoad
end