@@ -1152,6 +1152,47 @@ def _iter_content_4() -> Iterable[bytes]:
11521152 for i , expected_range in enumerate (expected_ranges ):
11531153 assert mock_stream_backoff .call_args_list [i ].kwargs ["headers" ] == {"Range" : expected_range }
11541154
1155+ def test_http_get_retry_resets_file_when_range_ignored (self , caplog ):
1156+ """Test that http_get resets the file when the server ignores the Range header.
1157+
1158+ When a download is interrupted and retried with a Range header, some servers
1159+ (e.g. CloudFront with Accept-Encoding: gzip) ignore the Range header and return
1160+ 200 with the full file instead of 206. In that case, the code must truncate
1161+ the file before writing to avoid appending the full content to partial data.
1162+ """
1163+
1164+ def _iter_content_1 () -> Iterable [bytes ]:
1165+ yield b"A" * 30
1166+ raise httpx .TimeoutException ("Fake timeout" )
1167+
1168+ def _iter_content_2 () -> Iterable [bytes ]:
1169+ # Server ignores Range, returns full content
1170+ yield b"B" * 100
1171+
1172+ mock_response_1 = Mock ()
1173+ mock_response_1 .status_code = 200
1174+ mock_response_1 .headers = {"Content-Length" : "100" }
1175+ mock_response_1 .iter_bytes .return_value = _iter_content_1 ()
1176+
1177+ mock_response_2 = Mock ()
1178+ mock_response_2 .status_code = 200 # 200, not 206 — Range was ignored
1179+ mock_response_2 .headers = {"Content-Length" : "100" }
1180+ mock_response_2 .iter_bytes .return_value = _iter_content_2 ()
1181+
1182+ mock_responses = iter ([mock_response_1 , mock_response_2 ])
1183+
1184+ @contextmanager
1185+ def _mock_stream (* args , ** kwargs ):
1186+ yield next (mock_responses )
1187+
1188+ with patch ("huggingface_hub.file_download.http_stream_backoff" , side_effect = _mock_stream ):
1189+ temp_file = io .BytesIO ()
1190+ http_get ("fake_url" , temp_file = temp_file )
1191+
1192+ # File should contain only the full content from retry (100 bytes), not 130
1193+ assert temp_file .tell () == 100
1194+ assert temp_file .getvalue () == b"B" * 100
1195+
11551196
11561197class CreateSymlinkTest (unittest .TestCase ):
11571198 @unittest .skipIf (os .name == "nt" , "No symlinks on Windows" )
0 commit comments