Issue #17543 has been updated by Eregon (Benoit Daloze).


Not preserving `self` would be confusing, e.g., when calling other methods like:
```ruby
class Foo
  def bar
    ...
  end

  def foo
    test { bar }
  end
end
```

It does mean the `Foo` instance would be (deeply) frozen.
It's a trade-off between being able to call other methods and freeze `self`, or magically `instance_exec` the block.

I think the only case where it's acceptable to change the self of a proc implicitly is `Ractor.new {}` because that already cannot capture any local variables:
```
ruby -e 'o=Object.new; Ractor.new { o }'                            
<internal:ractor>:267:in `new': can not isolate a Proc because it accesses outer variables (o). (ArgumentError)
```

Capturing variables or self is very similar IMHO, so I think they should be treated the same.
```
ruby -e 'o=Object.new; Ractor.make_shareable(-> { o }); p o.frozen?'
<internal:ractor>:816:in `make_shareable': can not make shareable Proc because it can refer unshareable object #<Object:0x0000000000d5ca28> from variable `o' (Ractor::IsolationError)
```
The most obvious fix is therefore to raise the same error if `self` is not shareable.

Although, I would have expected that to print `true` and freeze `o`.
What's the point of `Ractor.make_shareable` if it doesn't deeply make shareable as needed?

----------------------------------------
Bug #17543: Ractor isolation broken by `self` in shareable proc
https://bugs.ruby-lang.org/issues/17543#change-89968

* Author: marcandre (Marc-Andre Lafortune)
* Status: Open
* Priority: Normal
* Assignee: ko1 (Koichi Sasada)
* ruby -v: 3.0.0p0
* Backport: 2.5: UNKNOWN, 2.6: UNKNOWN, 2.7: UNKNOWN, 3.0: UNKNOWN
----------------------------------------
Discussing with @MaxLap we realized that the `self` in a shareable proc is not properly isolated:

```
class Foo
  attr_accessor :x

  def pr
    Ractor.make_shareable(Proc.new { self })
  end
end

f = Foo.new
f.x = [1, 2, 3]
Ractor.new(f.pr) { |pr| pr.call.x << :oops }
p f.x # => [1, 2, 3, :oops]
```

If the `self` refers to a shareable object then it's fine, but for non-shareable objects it has to be reset to `nil` or to a global shareable object that would have an instructive `inspect`.

```ruby
Ractor::DETACHED_SELF = Object.new
def << Ractor::DETACHED_SELF
  def inspect
    '<#detached self>'
  end
  alias to_s inspect
end
Ractor::DETACHED_SELF.freeze
```




-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>