Skip to content

Breaking PyReadonlyArray #258

Closed
Closed
@adamreichold

Description

@adamreichold

I am sorry for repeatedly opening soundness issues, but I fear that using NumPy's writeable is insufficient to protect safe code from mutable aliasing.

At least it seems incompatible with a safe as_cell_slice as demonstrated by the following test failing

#[test]
fn alias_readonly_cell_slice() {
    Python::with_gil(|py| {
        let array = PyArray::<i32, _>::zeros(py, (2, 3), false);

        let slice = array.as_cell_slice().unwrap();

        let array = array.readonly();
        let value = array.get((0, 0)).unwrap();

        assert_eq!(*value, 0);
        slice[0].set(1);
        assert_eq!(*value, 0);
    });
}

which implies that as_cell_slice cannot be safe. (I am not sure if it adds anything over as_array(_mut) at all viewed this way. I think a safe method that yields an ndarray::RawArraView might be preferable to handle situations involving aliasing.)

Another issue I see is that Python does not need to leave the writeable flag alone, i.e. the test

#[test]
fn alias_readonly_python() {
    use pyo3::py_run;

    Python::with_gil(|py| {
        let array = PyArray::<i32, _>::zeros(py, (2, 3), false);

        let array = array.readonly();
        let value = array.get((0, 0)).unwrap();

        assert_eq!(*value, 0);
        py_run!(py, array, "array.flags.writeable = True\narray[(0,0)] = 1");
        assert_eq!(*value, 0);
    });
}

also fails, but I have to admit that this might be a case of "you're holding it wrong" as I am not sure what guarantees we can expect from the Python code? (After all PyArray<A,D>: !Send which Python code does not need to respect either even just trying to access an array and thereby checking its flags from another thread might race with us modifying the flags without atomics.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions