pyo3: Unexpected memory management behavior

I’m very excited about this library. The effort going into documentation and ergonomics is fantastic. I’ve been waiting to use it on stable Rust for months, and have finally started trying to integrate it into my CPU-bound Python codebase to write extension modules.

Right now, pyo3 seems to have a serious issue to me. The use of the object storage (even the lighter #887 implementation) means that this library is not zero-cost, and worse, can easily leak memory. The additional management layer that’s built on top of Python’s own reference counting, while ergonomic, is a big problem for my use-case.

The current situation, as I understand it:

  • GilGuard acquire overhead (minimal, and rare):

    • Acquire a Mutex on the PyObject alloc/dealloc array.
    • Allocate a Vec to copy the PyObject alloc/dealloc array out of TLS.
    • Write to 2x thread-local storage.
    • Allocate two Vec for storing pointers to owned references.
  • &PyAny owned reference creation (mostly method returns, cheap, but very frequent):

    • Write to thread-local storage.
    • Occasionally re-alloate owned reference Vecs as they grow.
    • Memory is only freed at GilGuard drop
  • PyObject drop (cheap, but frequent):

    • Read from thread-local storage.
    • Possibly acquire a Mutex on the dealloc array.
    • Possibly only free memory at next GitGuard acquire

The regular access to TLS and global mutexes are regrettable, but the memory-freeing behavior is really worrying to me. I’m not writing Python extensions because I want pretty-damn fast and unbounded memory growth. I’m going to the effort of writing a Python extension because I need as fast as possible and predictable memory usage.

The solution outlined in #885 seems perfect. A PyAny<'a> has no need for object storage, and Clone and Drop work as one would expect. I’d even go one stage further and have PyObject and Py<T> always acquire the GIL for Clone and Drop. Sure, it’s slower than using the current TLS and deferred drop, but it’s simpler, more predictable, and people can always use ManuallyDrop turn them back into PyAny<'a> to batch clone/drop if performance is suffering.

You could even remove the mirrored object API on PyObject and require that they’re converted into PyAny<'a> to call or getattr, making PyObject’s only purpose to be storing a long-term reference to a Python object between GIL acquisitions.

At that point, there’s no additional global state beyond what’s already provided by the Python interpreter. Things are deallocated predictably. There’s a smaller API surface. The library is truly zero-cost and adds no additional complexity.

I would urge you to be bold with making breaking changes while the library is young and the userbase relatively small. It would be a trememdous shame if the most popular Rust/Python bindings were significantly slower than the equivalent C, and introduced an unexpected additional memory model.

In any case, thanks for all the work you’ve put in so far. 😃

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 4
  • Comments: 21 (13 by maintainers)

Commits related to this issue

Most upvoted comments

Incredible, I’ve been watching and hoping for a long while for this to be sorted! I’m really glad it was included for 1.0. ❤️

To me, the imporant things to get right for this library are, in order:

  1. Sound.
  2. Predictable memory usage, with no unbounded growth.
  3. Zero-cost (fast as C)
  4. Ergonomic, well documented

Currently, 1 and 4 are pretty well nailed, but 2 and 3 are both being held back by object storage. Here’s my attempt at a solution that does away with all thread locals and object storage.

The first part of the solution is already solved by the current PyAny (zero-cost wrapper around a pointer) and PyDict, PyList (zero-cost wrapper around a pointer that asserts a native type). The change I’d make is that a user never interacts with &PyAny or &PyDict directly.

Instead, these are always wrapped by either:

  • PyRef<'py, T> (e.g. PyRef<'py, PyAny> or PyRef<'py, PyDict>

    • The 'py lifetime is tied to Python<'py>, so guarantees that the GIL is held.
    • Clone and Drop perform immediate refcount incr/decr.
    • Deref impl to T for easy .call(...) and getattr(...) etc.
  • PyOwned<T> (e.g. PyOwned<PyAny> or PyOwned<PyDict>)

    • These assume that the GIL is not held.
    • Clone and Drop acquire the GIL and perform immediate refcount incr/decr, then drop the GIL again. This is not efficient, but it keeps the memory model predictable and correct. People can use .into_ref(...) (below) for efficient batch clone and drop.
    • An .into_ref(self, py: Python<'py>) method consumes the PyOwned<T> and returns a PyRef<'py, T>.
    • An .as_ref(&self, py: Python<'py>) method does not consume the PyOwned<T>, and returns a &'py T (the only time a user ever deals with a &'py T directly. I’m not 100% sure about the lifetimes here, or whether it would actually work. Maybe .clone().into_ref(py) is more correct, at the expese of a refcount.

I believe this does away with all thread locals and all object storage, and brings the performance and memory characteristics in line with the equivalent C.

I’d be happy to have a go at this myself, but I don’t want to step on other people’s toes, or spend time on something that isn’t wanted, or has already been tried and found problematic.

With the release of the Bound API in 0.21 (beta), there is finally a resolution to this problem. 🎉

Migrating to the Bound API will solve this problem immediately for code which needs this fixed, and the follow-up to this work is #3960 to remove the existing GIL Refs API.

@etianen thanks for all the ideas. I agree that the direction I want for PyO3 is to remove as much object storage as possible.

TLDR; Yes, I like this design and have considered it myself, but I’m not sure it’s the right time to do it.

I’ve thought many times about ideas similar to your PyOwned<T> / PyRef<'a, T> combination. Note that your proposal for PyOwned<T> is more or less exactly what the current Py<T> is, except for the drop semantics. (PyObject is very similar to Py<PyAny>, and I’d like to remove it, but haven’t quite found the appropriate way to do it given how PyO3’s conversion traits work currently.)

Regarding PyRef<'a, T> - again, this is an API that I’ve considered moving towards. It fits nicely as PyRef is already a name we use for #[pyclass], and the meaning would be essentially the same for native types (except “refcell” semantics wouldn’t be needed for native types).

Why I’m not sure now is the moment.

The biggest downside of PyRef<'py, T> with current Rust, is that the GIL lifetime 'py isn’t perfectly preserved over multiple calls. Consider, for example, this method definition which we would adopt if we switched to PyRef<'py, T>:

impl PyAny {
    fn call0(&'a self) -> PyRef<'a, PyAny> { ... }
}

If PyRef<'py, PyAny> derefs to &'a PyAny for the method call, then this lifetime 'a is not the original GIL lifetime 'py. Instead, 'a is the lifetime of the derefencing borrow. So as far as Rust is concerned the result of the method call is borrowed from the original receiver. This is obviously wrong!

The result of this is that a series of chained PyO3 API calls gradually see the GIL lifetime which the compiler guarantees get narrower and narrower. It’s not the end of the world, but it’s quite an annoying papercut.

The future solution I see

There is, fortunately, a way that I can see this being resolved in the future: arbitrary self types. If we were able to use &PyRef<'py, T> as a self type, then this problem goes away:

impl PyAny {
    fn call0<'py>(self: &PyRef<'py, Self>) -> PyRef<'py, PyAny> { ... }
}

With arbitrary self types, we really can have our cake and eat it! So this is a direction which I would like to see for PyO3, but I’m not actively pursuing it now because we need someone to champion getting the feature added to the Rust language first!

Thanks. I think it’s good timing to revisit our object model now, since recently some safety problems are pointed out aroung GILGuard. Let me create the 2nd draft.