PyO3/pyo3

Explore whether we can generate more friendly runtime borrow-checker errors

Opened this issue · 0 comments

There are two possible situations where users might run into runtime borrow-checker errors for a mutable pyclass.

  • In single-threaded use by mutably borrowing data stored in a pyclass once and then trying to borrow again. This can happen without re-entrancy in a single scope by e.g. calling Bound::borrow() twice on the same value or less trivially with some form of re-entrancy. Both of these are likely programming errors.

  • In multithreaded use, if a thread mutably borrows a value and then another thread tries to borrow the same value. This is a different kind of programming error and indicates that the user is not using a mutable object in the way it was designed, e.g. by building the object on one thread and then sharing it without mutating it.

It should be possible to check whether or not the current thread has an exclusive borrow or not when generating a borrow checker error and then generate two different error messages for these two cases. I'm not sure whether it's possible to do this unconditionally without adding any new overhead to PyO3's borrow-checking scheme. If there is overhead, we could also make it possible to opt-in to this mode (e.g. #[pyclass(thread_unsafe)] or something like that).