Requests are not retried when received body length is shorter than Content-Length
还没有人认领这个 Issue。
评估
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 新手友好度
- 35/100
- Issue 类型
- 缺陷
- 描述清晰度
- 基本清楚
- 活跃度
- 停滞
- 技术栈
- python
- 领域
- api, networking
调研方向
从 src/requests/adapters.py 和 src/requests/models.py 开始,然后阅读 tests/test_lowlevel.py 中现有的低级响应测试。运行截断响应的复现,并将其与 test_retry_truncated_response 进行比较;完成的标准是,非流式请求会根据 HTTPAdapter 的策略进行重试,并返回完整的预期内容,同时不会泄漏 urllib3 异常。
由索引模型根据 Issue 内容生成。
描述
When a server sends less bytes than indicated by Content-Length, we get a ChunkedEncodingError instead of retrying the request.
urllib3 supports retrying requests in this situation by setting preload_content=True. When a user specifies stream=True, obviously, all bets are off: the response cannot be preloaded and therefore the request cannot be retried. However, even when stream=False, the response is still not preloaded and therefore the urllib3 retry mechanism in this situation is bypassed.
As a background to this issue, I've been investigating rare failures in my CI builds during pip install. I believe this issue to be the proximate cause: pip makes some requests to PyPI, with stream=False and retries configured but still fails.
In the current version of pip (which has an out of date urllib3 package), pip falls victim to https://github.com/psf/requests/issues/4956 and fails to parse the PyPI metadata with a JSONDecodeError. Upgrading pip's urllib3 version results in a ChunkedEncodingError as below.
Expected Result
The request is retried according to the specified retry policy.
Actual Result
requests.exceptions.ChunkedEncodingError: ('Connection broken: IncompleteRead(10 bytes read, 26227 more expected)', IncompleteRead(10 bytes read, 26227 more expected))
Because the response is not preloaded, urllib3 cannot retry the request, and requests has no retry functionality of its own.
Reproduction Steps
import requests
from requests.adapters import HTTPAdapter
s = requests.Session()
s.mount("http://", HTTPAdapter(max_retries=5))
r = s.get('http://127.0.0.1:5000/test', stream=False)
I'm using an intentionally broken local server for testing. See here for an example.
System Information
$ python -m requests.help
{
"chardet": {
"version": null
},
"charset_normalizer": {
"version": "3.2.0"
},
"cryptography": {
"version": ""
},
"idna": {
"version": "3.4"
},
"implementation": {
"name": "CPython",
"version": "3.11.4"
},
"platform": {
"release": "6.4.11-100.fc37.x86_64",
"system": "Linux"
},
"pyOpenSSL": {
"openssl_version": "",
"version": null
},
"requests": {
"version": "2.31.0"
},
"system_ssl": {
"version": "30000090"
},
"urllib3": {
"version": "2.0.4"
},
"using_charset_normalizer": true,
"using_pyopenssl": false
}
Proposed Patch
I have a proposed patch which I believe fixes this problem. Unfortunately, my patch breaks a bunch of the tests (and probably also breaks backwards compatibility, in particular, this patch causes requests to start leaking urllib3 exceptions). On the off chance it's useful in coming up with a proper fix, here it is:
diff --git a/src/requests/adapters.py b/src/requests/adapters.py
index eb240fa9..ce01c2a5 100644
--- a/src/requests/adapters.py
+++ b/src/requests/adapters.py
@@ -489,8 +489,8 @@ class HTTPAdapter(BaseAdapter):
headers=request.headers,
redirect=False,
assert_same_host=False,
- preload_content=False,
- decode_content=False,
+ preload_content=not stream,
+ decode_content=not stream,
retries=self.max_retries,
timeout=timeout,
chunked=chunked,
diff --git a/src/requests/models.py b/src/requests/models.py
index 44556394..f43f1bf8 100644
--- a/src/requests/models.py
+++ b/src/requests/models.py
@@ -893,6 +893,8 @@ class Response:
if self.status_code == 0 or self.raw is None:
self._content = None
+ elif getattr(self.raw, "data", None) is not None:
+ self._content = self.raw.data
else:
self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b""
diff --git a/tests/test_lowlevel.py b/tests/test_lowlevel.py
index 859d07e8..39a1175e 100644
--- a/tests/test_lowlevel.py
+++ b/tests/test_lowlevel.py
@@ -4,6 +4,7 @@ import pytest
from tests.testserver.server import Server, consume_socket_content
import requests
+from requests.adapters import HTTPAdapter
from requests.compat import JSONDecodeError
from .utils import override_environ
@@ -426,3 +427,33 @@ def test_json_decode_compatibility_for_alt_utf_encodings():
assert isinstance(excinfo.value, requests.exceptions.RequestException)
assert isinstance(excinfo.value, JSONDecodeError)
assert r.text not in str(excinfo.value)
+
+
+def test_retry_truncated_response():
+ data = b"truncated before retry"
+ response_lengths = [len(data), 9]
+
+ def retry_handler(sock):
+ request_content = consume_socket_content(sock, timeout=0.5)
+
+ response = (
+ b"HTTP/1.1 200 OK\r\n"
+ b"Content-Length: %d\r\n\r\n"
+ b"%s"
+ ) % (len(data), data[:response_lengths.pop()])
+ sock.send(response)
+
+ return request_content
+
+ close_server = threading.Event()
+ server = Server(retry_handler, wait_to_close_event=close_server, requests_to_handle=2)
+
+ s = requests.Session()
+ s.mount("http://", HTTPAdapter(max_retries=2))
+
+ with server as (host, port):
+ url = f"http://{host}:{port}/"
+ r = s.get(url, stream=False)
+ assert r.status_code == 200
+ assert r.content == data
+ close_server.set()
- 主要语言
- Python
- 星标
- 54.7k
- 派生
- 10.8k
- 平均合并
- 18 分钟
- 30 天内合并 PR
- 1
环境准备
- 没有 Dockerfile 或 Docker Compose 文件
- 没有 Pull Request 模板
- 阅读贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
psf/requests 的其他 Issue
-
难度 1/5 1 小时以内 新手友好度 85/100
-
`iter_lines(decode_unicode=True, delimiter=<str>)` raises `TypeError` when `Response.encoding` is `None`可能重新可做 关联的 PR 已关闭且未合并。 未关闭
难度 2/5 1-3 小时 新手友好度 62/100
-
get_encoding_from_headers treats any content type containing 'text' as text/* (ISO-8859-1)可能已有人在做 @suyashgitt 于 1 天前认领。 未关闭
难度 2/5 1-3 小时 新手友好度 76/100
-
难度 2/5 1-3 小时 新手友好度 78/100
-
Invalid `params` type (e.g. int) raises misleading "TypeError: Cannot mix str and non-str arguments"未关闭
难度 2/5 1-3 小时 新手友好度 72/100
相似的 Issue
-
bug
难度 1/5 1 小时以内 新手友好度 78/100
splunk/security_content#4418 ·
维护者通常 1 天内回复
-
[Bug / Enhancement]: Improve teleop_robot CLI with configurable timeout, robust input validation, and clean ROS shutdown可能已有人在做 @muskan-creates352 今天认领。 未关闭
难度 2/5 1-3 小时 新手友好度 72/100
维护者通常 3 天内回复
-
bug(pipelines): shortcode stripping deletes text between a {{< >}} shortcode and the next {{% %}}可能已有人在做 @Ashborne-lab 今天认领。 未关闭
难度 2/5 1-3 小时 新手友好度 70/100
kubeflow/docs-agent#293 ·
维护者通常 3 天内回复
-
难度 2/5 1-3 小时 新手友好度 62/100
Imbad0202/academic-research-skills#1093 ·
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 78/100
pierreaubert/gpui-toolkit#114 ·
维护者通常 1 天内回复