Skip to content

[BUG] Remote-image total_timeout excludes response headers and automatic redirects #3832

Closed

Description

@devin-ai-integration

Describe the bug

The new wall-clock image-fetch budget is not enforced over the complete HTTP operation. Valid image URLs with delayed/trickling headers or individually responsive redirects can block multimodal calibration beyond the budget and still return success. The default 120-second path has the same lifecycle gap; the numerical default duration was not exercised. This is a defect in the total_timeout API/contract added by #3483, not a re-report of the old absence of HTTP timeouts.

Priority: P2 — a supported configuration produces incorrect behavior. Specific triggers and validation boundaries are below.

Reviewed at 35987dfb7, within the merged-change window 2026-09-25 07:00 UTC–2026-11-13 07:00 UTC. The changes through 8ea76c395 were checked before filing; these causes remain.

GPU / software / model information

These are focused correctness reproductions using small generic fixtures and public model classes; no external model or dataset download is required. Each case states its execution environment and any hardware or mocking limitation. Accelerator execution is not claimed from a CPU dispatch test.

Trigger

Supported HTTP/HTTPS image URL passed to load_image_from_url(), or image/image_url content in a multimodal calibration conversation. Actual caller lifecycle: BaseQModel builds a partial of self.prepare_dataset -> LoopProcessor calls CalibrationConfig.prepare_dataset synchronously -> BaseQwen2VLGPTQ.prepare_dataset -> process_vision_info -> fetch_image -> load_image_from_url -> _download_image_bytes. InternS1QModel and Ovis2_5QModel also route remote images through this helper. No enclosing deadline was found in the traced calibration path.

Introducing change

Squash merge e4778c5, fix(calibration): bound and diagnose remote image fetches (#3483), committed 2026-11-02T16:18:16+08:00 (2026-11-02T08:18:16Z), within the requested window. e4778c5 ; #3483 . git blame attributes request and late watchdog lines to this commit. Path-limited git log shows no later image.py change through pinned HEAD; ancestry checks confirm baseline -> introducing merge -> pinned HEAD. Baseline image.py has only unbounded requests.get in fetch_image and no load_image_from_url/total_timeout API. PR #3483 explicitly advertises a 120-second wall-clock budget.

Source evidence

requests.get(stream=True, timeout=timeout) runs before any watchdog:

def _download_image_bytes(
url: str,
*,
timeout: Union[float, Tuple[float, float]],
max_bytes: int,
total_timeout: float,
) -> bytes:
try:
response = requests.get(url, stream=True, timeout=timeout)
except requests.Timeout as exc:
# A stall on one attempt usually means the origin is unreachable; do
# not multiply the wall-clock cost by retrying it.
raise _FetchFailure(f"timed out after {timeout} seconds ({exc})", retryable=False) from exc
except _PERMANENT_REQUEST_ERRORS as exc:
raise _FetchFailure(f"request failed ({exc})", retryable=False) from exc
except requests.RequestException as exc:
raise _FetchFailure(f"request failed ({exc})", retryable=True) from exc

Only after final response headers have arrived does the helper create a fresh deadline and start its watchdog:
with response:
status = response.status_code
if status >= 400:
raise _FetchFailure(
f"HTTP {status} {response.reason or ''}".strip(),
retryable=status in _RETRYABLE_STATUS_CODES,
)
declared = response.headers.get("Content-Length")
if declared is not None:
try:
declared_bytes = int(declared)
except ValueError:
declared_bytes = None
if declared_bytes is not None and declared_bytes > max_bytes:
raise _FetchFailure(
f"response is {declared_bytes} bytes, exceeding the {max_bytes} byte limit",
retryable=False,
)
buffer = BytesIO()
received = 0
deadline = time.monotonic() + total_timeout
# A per-read timeout alone lets a server keep a download alive forever
# by trickling a byte at a time. A watchdog closes the socket when the
# whole download exceeds the wall-clock budget.
watchdog = threading.Timer(total_timeout, _abort_response, args=(response,))
watchdog.daemon = True
watchdog.start()
try:
for chunk in response.iter_content(chunk_size=64 * 1024):
if not chunk:
continue
received += len(chunk)
if time.monotonic() > deadline:
raise _FetchFailure(
f"download exceeded the {total_timeout} second total time limit",
retryable=False,
)

The caller computes the overall deadline and passes remaining time without clamping request timeouts; after successful download it decodes and returns without rechecking that deadline:
last_failure: Optional[_FetchFailure] = None
# The wall-clock budget covers every attempt, not just one download.
deadline = time.monotonic() + total_timeout
for attempt in range(1, attempts + 1):
remaining = deadline - time.monotonic()
if remaining <= 0:
last_failure = _FetchFailure(
f"download exceeded the {total_timeout} second total time limit",
retryable=False,
)
break
try:
data = _download_image_bytes(
url, timeout=timeout, max_bytes=max_bytes, total_timeout=remaining
)
except _FetchFailure as failure:
last_failure = failure
if not failure.retryable or attempt == attempts:
break
delay = backoff_seconds * (2 ** (attempt - 1))
if time.monotonic() + delay >= deadline:
break
time.sleep(delay)
continue
try:
image = Image.open(BytesIO(data))
except Image.DecompressionBombError as exc:
raise ImageFetchError(url, f"image is too large to decode safely ({exc})") from exc
except Exception as exc: # PIL raises several unrelated exception types
raise ImageFetchError(url, f"response is not a decodable image ({exc})") from exc
# Check the declared dimensions before ``load()`` allocates the pixel
# buffer: a small compressed file can still expand to a huge bitmap.
width, height = image.size
if width * height > max_pixels:
image.close()
raise ImageFetchError(
url,
f"image is {width}x{height} ({width * height} pixels), exceeding the "
f"{max_pixels} pixel limit",
)
try:
image.load()
except Exception as exc:
image.close()
raise ImageFetchError(url, f"response is not a decodable image ({exc})") from exc
return image

HTTP URL dispatch:
def fetch_image(
ele: dict[str, str | Image.Image],
image_patch_size: int | None = None,
) -> Image.Image:
# Some multimodal model adapters forward image-related kwargs here even
# though local image loading does not need them.
del image_patch_size
if "image" in ele:
image = ele["image"]
else:
image = ele["image_url"]
image_obj = None
if isinstance(image, Image.Image):
image_obj = image
elif image.startswith("http://") or image.startswith("https://"):
image_obj = load_image_from_url(image)

Calibration callback binding:
prepare_dataset_func = partial(
self.prepare_dataset,
calibration_data_min_length=calibration_data_min_length,
)
calibration_config = self._build_calibration_config(
calibration,
prepare_dataset_func,
calibration_concat_size,
calibration_sort,
calibration_concat_separator,
run_plan.batch_size,
)
args = {
"tokenizer": self.tokenizer,
"qcfg": self.quantize_config,
"calibration": calibration_config,
"calculate_w_wq_diff": ProcessorStep.EORA in run_plan.processors,

Synchronous callback execution:
# prepare dataset
calibration_dataset = self.calibration.dataset
if calibration_dataset is not None:
if len(calibration_dataset) == 0:
raise ValueError("Calibration dataset must not be empty.")
min_calibration_dataset_size = 256
min_calibration_dataset_input_ids_avg_length = 256
if len(calibration_dataset) < min_calibration_dataset_size:
log.warn(f"Calibration dataset size should be more than {min_calibration_dataset_size}. "
f"Current: {len(calibration_dataset)}.")
if self.calibration.prepare_dataset is None:
raise ValueError("CalibrationConfig.prepare_dataset must be provided when calibration data is supplied.")
calibration_dataset = self.calibration.prepare_dataset(
calibration_dataset=calibration_dataset,
calibration_dataset_concat_size=self.calibration.concat_size,
calibration_dataset_sort=self.calibration.sort,
batch_size=self.calibration.batch_size,
calibration_concat_separator=self.calibration.concat_separator,
)

Multimodal caller and dataset loop:
@staticmethod
def process_vision_info(
conversations: list[dict] | list[list[dict]],
) -> Optional[list[Image.Image]]:
vision_infos = extract_vision_info(conversations)
# Read images
image_inputs = []
for vision_info in vision_infos:
if "image" in vision_info or "image_url" in vision_info:
image_inputs.append(fetch_image(vision_info))
else:
raise ValueError("image, image_url should in content.")
if len(image_inputs) == 0:
image_inputs = None
return image_inputs
def preprocess_dataset(self, sample: Dict) -> Dict:
return sample
def load_processor(self) -> ProcessorMixin:
return AutoProcessor.from_pretrained(self.model_local_path)
def prepare_dataset(self, calibration_dataset, batch_size: int = 1, **kwargs):
processor = self.load_processor()
calib_data = []
for batch in batched_conversations(calibration_dataset, batch_size, process_func=self.preprocess_dataset):
text = processor.apply_chat_template(
batch, tokenize=False, add_generation_prompt=True
)
image_inputs = self.process_vision_info(batch)
inputs = processor(
text=text,
images=image_inputs,
videos=None,
padding=True,
return_tensors="pt",
)
calib_data.append(inputs)

Other direct caller:
@staticmethod
def replace_image_with_pil(sample):
"""
image url -> PIL.Image
"""
for msg in sample:
if "content" not in msg and not isinstance(msg["content"], dict):
continue
for item in msg["content"]:
if isinstance(item, dict) and item.get("type") == "image":
item["image"] = load_image_from_url(item["image"])
return sample
def prepare_dataset(self, calibration_dataset, batch_size: int = 1, **kwargs):
processor = self.load_processor()
calib_data = []
for batch in batched_conversations(calibration_dataset, batch_size, process_func=self.preprocess_dataset):
batched_samples = []
for sample in batch:
batched_samples.append(self.replace_image_with_pil(sample))
calib_data.append(
self.prepare_inputs_for_conversations(
processor,
batched_samples,
)
)

Existing hang/retry-budget tests use short socket timeouts and do not cover a total budget expiring during headers:
def test_hanging_server_is_bounded_by_read_timeout(image_server):
base, server = image_server
with pytest.raises(ImageFetchError) as excinfo:
load_image_from_url(
f"{base}/hang",
timeout=(0.2, 0.2),
attempts=2,
backoff_seconds=0,
)
assert "timed out" in str(excinfo.value)
assert excinfo.value.url.endswith("/hang")
def test_timeout_budget_is_not_multiplied_by_retries(image_server):
base, _ = image_server
started = time.monotonic()
with pytest.raises(ImageFetchError):
load_image_from_url(f"{base}/hang", timeout=(0.2, 0.2), total_timeout=0.6, attempts=3)
# Timed-out attempts are not retried, so this must finish well under the
# 3 * (connect + read) budget the naive implementation would need.
assert time.monotonic() - started < 3.0

Existing slow-drip test sends complete headers before delayed body data:
elif path == "/slow-drip":
# Trickle bytes below the per-read timeout so only a wall-clock
# budget can stop the download.
drip = 400
self.send_response(200)
self.send_header("Content-Length", str(drip))
self.send_header("Connection", "close")
self.end_headers()
try:
for _ in range(drip):
if self.server.release_hang.wait(0.05):
break
self.wfile.write(b"\x00")
self.wfile.flush()
except OSError:
# The client aborts once its deadline expires; expected here.
pass
and
def test_slow_drip_body_is_bounded_by_total_timeout(image_server):
base, _ = image_server
with pytest.raises(ImageFetchError) as excinfo:
load_image_from_url(
f"{base}/slow-drip",
timeout=(1.0, 1.0),
total_timeout=0.3,
attempts=1,
)
assert "total time limit" in str(excinfo.value)

To reproduce / expected behavior

At the root of a clean public GPTQModel checkout at 35987df, save the following as repro_image_budget.py and run python repro_image_budget.py with requests and Pillow installed. The script loads the entire unmodified shipped module directly with importlib to avoid unrelated ML-package initialization; no mocks, extracted AST, models, datasets or remote downloads are used. Expected: /ok succeeds; /slow-headers, /redirect/3, /slow-body, /header-drip fail when their total budget is exhausted. The header-drip case uses a per-read timeout smaller than the total budget, ruling out simply reducing timeout below total_timeout as a fix. Exact code:

import importlib.util
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from io import BytesIO
from pathlib import Path

from PIL import Image

# Load the complete shipped module without initializing the ML package.
spec = importlib.util.spec_from_file_location("image_utils", Path("gptqmodel/utils/image.py"))
image_utils = importlib.util.module_from_spec(spec)
spec.loader.exec_module(image_utils)

buffer = BytesIO()
Image.new("RGB", (1, 1)).save(buffer, "PNG")
png = buffer.getvalue()


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def do_GET(self):
        if self.path == "/header-drip":
            self.wfile.write(b"HTTP/1.0 200 OK\r\nX-Pad: ")
            self.wfile.flush()
            for _ in range(12):
                time.sleep(0.03)
                self.wfile.write(b"x")
                self.wfile.flush()
            self.wfile.write(b"\r\nContent-Length: " + str(len(png)).encode() + b"\r\n\r\n" + png)
            self.wfile.flush()
            return
        if self.path == "/slow-headers":
            time.sleep(0.4)
        if self.path.startswith("/redirect/"):
            remaining = int(self.path.rsplit("/", 1)[1])
            time.sleep(0.1)
            self.send_response(302)
            self.send_header("Location", f"/redirect/{remaining - 1}" if remaining else "/ok")
            self.send_header("Content-Length", "0")
            self.end_headers()
            return
        self.send_response(200)
        self.send_header("Content-Length", str(len(png)))
        self.end_headers()
        if self.path == "/slow-body":
            time.sleep(0.4)
        try:
            self.wfile.write(png)
        except OSError:
            # The body-timeout control deliberately disconnects early.
            pass


server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
server.daemon_threads = True
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
    base = f"http://127.0.0.1:{server.server_port}"
    for path, timeout, budget in [
        ("/ok", (1, 1), 0.05),
        ("/slow-headers", (1, 1), 0.05),
        ("/redirect/3", (1, 1), 0.05),
        ("/slow-body", (1, 1), 0.05),
        ("/header-drip", (0.1, 0.1), 0.15),
    ]:
        started = time.monotonic()
        try:
            image = image_utils.load_image_from_url(
                base + path, timeout=timeout, total_timeout=budget, attempts=1
            )
            outcome = f"SUCCESS {image.size}"
            image.close()
        except image_utils.ImageFetchError as exc:
            outcome = "ImageFetchError: " + exc.reason
        print(f"{path}: {outcome}; elapsed={time.monotonic() - started:.3f}s; total_timeout={budget}s")
finally:
    server.shutdown()
    server.server_close()
    thread.join()

Observed result

Independently executed twice for the first four cases and twice for the header-drip case. Combined-run output on Python 3.10.12, requests 2.34.2, Pillow 12.3.0:
/ok: SUCCESS (1, 1); elapsed=0.003s; total_timeout=0.05s
/slow-headers: SUCCESS (1, 1); elapsed=0.405s; total_timeout=0.05s
/redirect/3: SUCCESS (1, 1); elapsed=0.412s; total_timeout=0.05s
/slow-body: ImageFetchError: empty response body; elapsed=0.052s; total_timeout=0.05s
/header-drip: SUCCESS (1, 1); elapsed=0.366s; total_timeout=0.15s
The last case sends one header byte every 0.03s with timeout=(0.1,0.1), so it exceeds both the 0.1s read timeout and the 0.15s wall-clock budget without failure. The body-delay control does abort around its budget; the diagnostic message is not a separate finding.

Validation limits

Real localhost HTTP I/O against the complete pinned shipped module; no HTTP/network mocks and no AST extraction. The default interpreter lacks torch, so normal gptqmodel package import failed and shipped pytest/model integration was not run; direct importlib module loading is explicitly a focused HTTP-helper validation, not full package/model validation. No GPU is needed for this HTTP logic; GPU hardware was not probed, and no GPU numerics are claimed. Did not wait 120+ seconds, test DNS/TLS failure modes, run an indefinitely trickling server, or execute whole-model multimodal calibration. Default-setting impact is static lifecycle proof plus scaled deadline reproductions.

Duplicate check

Independently used gh issue list --repo ModelCloud/GPTQModel --state all --limit 100 with queries: image timeout; image in:title; "total_timeout"; "wall-clock"; "image" "redirect"; "image" "fetch"; "total time limit"; "image" "hang"; "calibration" "timeout"; "load_image_from_url"; "image" "header"; "image" "slow". No matching open or closed image-header/redirect deadline report was found. Read closed #1781 (multimodal calibration usage), #2928 (vision calibration/weight coverage), #3407 (different adapter-path trust issue), #2898 (JIT source packaging/performance), #2621 (AWQ rotary shapes), #1999 (notebook logging), and #1792 (large VL model quantization speed) sufficiently to distinguish them. No matching closed timeout fix was identified to validate as a duplicate. Inspected merged PR #3483 body and comments; its claimed wall-clock guarantee and tests do not address the pre-watchdog interval.

Activity

  1. added
    bug
    on Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions