python / python/cpython

`_pyio.BufferedReader.readinto()` can raise `ValueError` after partially filling the destination

未关闭
#155,074 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib topic-IO type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description:

The pure Python implementation of BufferedReader.readinto() can raise ValueError for a valid writable buffer after partially modifying it.

import io
import _pyio

for module in (io, _pyio):
    reader = module.BufferedReader(module.BytesIO(b"abcd"), buffer_size=2)
    assert reader.read(1) == b"a"

    destination = bytearray(2)
    try:
        result = reader.readinto(destination)
    except ValueError as error:
        result = f"{type(error).__name__}: {error}"

    print(module.__name__, result, destination, reader.read())

Current output on main:

io 2 bytearray(b'bc') b'd'
_pyio ValueError: memoryview assignment: lvalue and rvalue have different structures bytearray(b'b\x00') b'cd'

_pyio should match io: return 2, fill the destination with b"bc", and leave b"d" unread. readinto() first partially fills the destination with data from its internal buffer, then refills that buffer with more data than fits in the remaining space. It then raises ValueError. Because the destination has already been modified and the stream has advanced when the exception is raised, the caller receives no byte count and cannot safely retry on a non-seekable stream.

_pyio.BufferedRandom.readinto() and _pyio.BufferedRWPair.readinto() are also affected because they use the same reader path.

I am working on a PR with a regression test shared by the C and pure Python implementations.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs
  • gh-155075

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 _pyio.BufferedReader.readinto() 入口点开始,运行 issue 中的 reproducer,并将其与 io.BufferedReader.readinto() 进行比较。完成的标准是纯 Python 路径返回 2,使用 b"bc" 填充目标,使 b"d" 保持未读取状态,并覆盖针对 BufferedRandom 和 BufferedRWPair 描述的共享回归行为。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
backend
Issue 类型
缺陷
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
描述清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。