Hacktoberfest 2026: los issues que los mantenedores marcaron para octubre, abiertos y aptos para principiantes. Explorar issues de Hacktoberfest

Is it sound to use a slice of numpy::PyReadonlyArray inside pyo3::allow_threads()?

Abierto
#497 1 comentario 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
25/100
Tipo de issue
Nueva funcionalidad
Claridad
Necesita aclaración
Estado de actividad
Estancado
Stack tecnológico
numpy, python, rust
Área
api, backend

Línea de trabajo

Comienza con el ema binding y los puntos de entrada de core_ema mostrados en el issue; después, lee la documentación sobre el préstamo de PyReadonlyArray y el comportamiento de pyo3::Python::allow_threads. Se considera terminado cuando exista una conclusión de seguridad documentada y respaldada por el proyecto, o un cambio o workaround claramente delimitado, con cualquier ejemplo o prueba relevante identificado por los maintainers.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Greetings,

My goal is to implement an efficient (and safe) way to wrap a Rust function, using numpy::PyReadonlyArray, with zero-copy and GIL release during computation.

My question is general, but here is a concrete example from my EMA function binding:

use crate::indicators::ema::core_ema;
use numpy::{PyArray1, PyArrayMethods};
use pyo3::pyfunction;

#[pyfunction(signature = (data, window_size = 14, alpha = None))]
pub(crate) fn ema<'py>(
    py: pyo3::Python<'py>,
    data: numpy::PyReadonlyArray1<'py, f64>,
    window_size: usize,
    alpha: Option<f64>,
) -> pyo3::PyResult<pyo3::Py<numpy::PyArray1<f64>>> {
    let slice = data.as_slice()?;

    let py_array_out = PyArray1::<f64>::zeros(py, [len], false);
    let py_array_ptr = unsafe { py_array_out.as_slice_mut()? };

    py.allow_threads(|| core_ema(slice, window_size, alpha.into(), py_array_ptr))
        .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{:?}", e)))?;

    Ok(py_array_out.into())
}

I want to release the GIL to enable multithreading. I wonder how to do it safely. Or if it's possible.

The documentation of numpy::PyReadonlyArray says:

An instance of this type ensures that there are no instances of PyReadwriteArray, i.e. that only shared references into the interior of the array can be created safely

Additionnally, in the numpy module borrow documentation, it says:

The aim of this module is to ensure that safe Rust code is unable to violate these requirements on its own. We cannot prevent unchecked code - this includes unsafe Rust, Python or other native code like C or Fortran - from violating them. Therefore the responsibility to avoid this lies with the author of that code instead of the compiler

So, in my understanding, I get a reference to input data which is owned by Python and can, in theory, be changed from the outside (e.g. by another Python thread). So in my understanding, the answer should be 'no' it is not sound. But I'm not sure if there is a way, or a workaround or a good practice or if I just need to avoid using allow_thread with PyReadonlyArray1.

Thanks a lot for your time.

Lenguaje dominante
Rust
Estrellas
1.4k
Forks
141
Merge medio
15 min
PR fusionados (30 d)
1

Preparar el entorno

Aún no hemos revisado los archivos de configuración de este proyecto. Empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de PyO3/rust-numpy

Todos los issues de PyO3/rust-numpy

Issues similares

Más issues de Rust

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.