python / python/cpython

asyncio.StreamReader raises BufferError with active memoryview

Abierto
#146,379 9 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

stdlib topic-asyncio type-bug
Lenguaje dominante
Python
Estrellas
77.2k
Forks
35.9k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Bug report

Bug description:
Summary

When StreamReader has an active memoryview export of its internal buffer, methods that mutate the buffer in place can raise:

BufferError: Existing exports of data: object cannot be re-sized

This appears in real workloads with async database drivers, but the root cause is in StreamReader buffer mutation behavior.

Steps to reproduce
import asyncio

async def main():
    r = asyncio.StreamReader()
    r.feed_data(b"AABBCCDD")

    # Simulate a consumer that keeps a memoryview alive
    mv = memoryview(r._buffer)

    # Triggers BufferError in current implementation
    await r.readexactly(4)

    mv.release()

asyncio.run(main())
Expected behavior

readexactly(4) should return b"AABB" without raising BufferError.

Actual behavior

BufferError: Existing exports of data: object cannot be re-sized

Why this happens

Some StreamReader paths mutate bytearray in place, for example slice deletion and clear operations. In-place resize is not allowed while a memoryview export exists.

Affected methods
  • read
  • readline
  • readuntil
  • readexactly
Environment
  • Python: 3.13.x, 3.14.x (also reproducible in local tests with newer builds)
  • OS: macOS (also observed in Linux server workloads)
  • Third-party context where this is frequently hit: async DB drivers using memoryview over packet buffers
Possible fix direction

Replace in-place buffer mutations with non-mutating replacement assignments, for example:

  • replace slice delete with reassignment to remaining bytes
  • replace clear with assigning a new empty bytearray

If useful, I can open a PR with tests covering the regression paths.

CPython versions tested on:

3.13

Operating systems tested on:

macOS

Linked PRs
  • gh-146380

Guía de contribución

Abrir la guía de contribución

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.

Línea de trabajo

Comienza con asyncio.StreamReader y las rutas de read, readline, readuntil y readexactly descritas en el informe; ejecuta la reproducción proporcionada para observar el BufferError con un memoryview activo. Se considera completado cuando estos métodos devuelvan los datos esperados sin generar una excepción, con cobertura de regresión para las rutas afectadas de mutación del búfer.

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

Evaluación

Stack tecnológico
python
Área
backend
Tipo de issue
Error
Dificultad
3/5
Tiempo estimado
1-2 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.