pyo3: segmentation fault second run of rust function in python pyo3 0.21.2

Hi. I’m trying to apply pyo3 0.21.2 to 0.20 codes.

With 0.20 codes my python app works, but with the new code does not.

The current situation:

  • python version = 3.9.15
  1. the first call of rust_function in python succeeds, but the second call fails.
  2. The error was segmentation fault.
  3. The error messages are slightly different per run:
vk[d].setdefault(a, dict())[p_key] = sound_data
KeyError: 'chr11:871499/2' // <- this string can't be one of p_key, a or d. The string like that comes from another variable.

Exception ignored deletion of interned string failed:
Traceback (most recent call last):
  File "python_project.py", line 333, in rust_function
    self.rust_have_been_failed = True
KeyError: 'À\xad\x8dU' // <- A value that shouldn't exist if it's working properly.

Thread 1 "python" received signal SIGSEGV, Segmentation fault.
--Type <RET> for more, q to quit, c to continue without paging--
pymalloc_free (ctx=0x0, p=0x1)
    at /usr/local/src/conda/python-3.9.15/Objects/obmalloc.c:1866
1866    /usr/local/src/conda/python-3.9.15/Objects/obmalloc.c: No such file or directory.
/usr/local/src/conda/python-3.9.15/Objects/object.c: No such file or directory.
  1. returning (String, i32) instead of (Py<PyString>, i32) does not raise the error.

The codes here: https://gist.github.com/Crispy13/03d25f8d556e644b5425ddf1decff6dc

The rust function get input string from python, and return it back with additional i32.

Is it me? What’s the cause of the error?

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 25 (19 by maintainers)

Most upvoted comments

I see two problems: We do not control all reference count updates as some will have through Python/C code instead of our code paths. And this would undo the performance gains on which you worked so hard as part of the bound API.

Clone is convenient, and I now believe is fundamentally incorrect to defer without the GIL

I agree that we should not try to defer reference count updates. I think that the convenience is warranted though as user code cannot do something else but call with_gil to then call clone_ref. This has known deadlock issues, so if we remove the Clone, we should probably at least provide a try_with_gil so that user code can emulate its current mode of operation.

Considering the loopholes, its performance impacts and the possibility of solving this problem via a cooperating GILless Python interpreter, I fear we need to drop the reference pool unconditionally.

I think we might still want to keep the Clone impl though because we cannot remove the Drop impl, so we have to decide on what to do about the reference count updates without the GIL in any case, i.e. finish our discussion in #4095 albeit under different circumstances.

(Funny coincidence to get this bug report after discussing what to do about the reference pool. But then again, with the GIL pool on the way out, the reference pool is the last remnant of the “global state” memory management style we seem to be moving away from.)

make the reference pool update more algorithmically complex by identifying such pairs and eliding reference count operations involving them

I don’t think this will work as we cannot rely on getting these updates in pairs, e.g. the following reduced test case

#[test]
fn test_clone_drop_crash() {
    use crate::prelude::*;

    #[pyclass(crate = "crate")]
    struct TestClass {
        dropped: bool,
    }

    impl Drop for TestClass {
        fn drop(&mut self) {
            self.dropped = true;
        }
    }

    Python::with_gil(|py| {
        let obj = Py::new(py, TestClass { dropped: false }).unwrap();

        assert_eq!(obj.get_refcnt(py), 1);

        // put a clone operation on the release pool for obj
        let obj_clone = std::thread::scope(|s| s.spawn(|| obj.clone()).join().unwrap());

        drop(obj_clone); // immediately apply the drop here with the GIL

        assert_eq!(obj.get_refcnt(py), 1); // fails because the reference count underflowed
    });
}

will fail with

thread 'gil::tests::test_clone_drop_crash' panicked at src/gil.rs:968:9:
assertion `left == right` failed
  left: 140367188162640
 right: 1

because we apply the decrement before we had any chance to actually look at the increment.

I think we never ran into this because the common pattern is to wrap such sections in allow_threads which works around this. But my conclusion here would be that to provide the service that the global reference pool provides, we could actually “update the counts” before each and every single reference count operation. (And I am not even sure if this means, operation by us via Py or any reference count update.)