Skip to content

Commit 391713e

Browse files
di37ashhart
authored andcommitted
feat(vision): image URLs over HTTPS on port 443, bounded image preparation, a redacted request log
From #64 (Qwen3.8 MLX image input), carried into the vision branch's modules: - image URLs must be HTTPS on port 443 without a fragment, and the fetch sends a User-Agent and an Accept list of the image types it takes (hosts that refuse clients without one now serve the image); - a response must declare image/jpeg, image/png or image/webp, and the decoder opens only JPEG, PNG and WebP; - at most 16 requests decode and process images at once; others wait up to a minute, and past 128 waiting the server answers 503 so clients retry (CapacityError, on the Mac and CUDA servers); - the request log records image parts as <redacted>.
1 parent 05cbb54 commit 391713e

8 files changed

Lines changed: 172 additions & 62 deletions

File tree

‎src/tensorfold/cuda/server.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from typing import Any, Callable
1717

1818
from tensorfold.server.cancellation import RequestCancelled, socket_cancellation
19-
from tensorfold.server.errors import RequestError
19+
from tensorfold.server.errors import CapacityError, RequestError
2020
from tensorfold.server.http import Server
2121
from tensorfold.server.messages import (_normalize_tool_call_arguments, late_system_role, normalize_messages,
2222
validate_modalities)
@@ -478,7 +478,8 @@ def do_POST(self):
478478
try:
479479
prepared = app.prepare(body, chat)
480480
except RequestError as exc:
481-
return self._json(400, {"error": {"message": str(exc), "type": "invalid_request_error"}})
481+
return self._json(503 if isinstance(exc, CapacityError) else 400,
482+
{"error": {"message": str(exc), "type": "invalid_request_error"}})
482483
except Exception as exc: # any other failure to read the request is refused too, as on MLX
483484
_log_error(exc)
484485
return self._json(400, {"error": {"message": _error_message(exc)}})
@@ -549,7 +550,8 @@ def emit(delta: dict[str, Any]) -> bool:
549550
self.close_connection = True
550551
return
551552
except RequestError as exc:
552-
return self._json(400, {"error": {"message": str(exc), "type": "invalid_request_error"}})
553+
return self._json(503 if isinstance(exc, CapacityError) else 400,
554+
{"error": {"message": str(exc), "type": "invalid_request_error"}})
553555
except Exception as exc:
554556
_log_error(exc)
555557
try:

‎src/tensorfold/server/errors.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@ class RequestError(ValueError):
22
"""A request refusal: HTTP 400, or a named error after a stream starts."""
33

44

5+
class CapacityError(RequestError):
6+
"""A transient capacity refusal: HTTP 503, retry shortly."""
7+
8+
59
class RoundError(RuntimeError):
610
"""A failed round's type and message, without its engine frames or exception payloads."""
711

‎src/tensorfold/server/http.py‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
from tensorfold.server.tools import (active_tool_specs, parse_tool_calls_from_content, stream_tool_call_deltas,
1414
tool_choice_requires_call)
15-
from tensorfold.server.errors import RequestError
15+
from tensorfold.server.errors import CapacityError, RequestError
1616
from tensorfold.server.request_options import parse_numbers
1717
from tensorfold.server.messages import normalize_messages, validate_modalities
1818
from tensorfold.server.tool_policy import ToolCallPolicy
@@ -44,6 +44,18 @@ class Server(ThreadingHTTPServer):
4444
request_queue_size = 128
4545

4646

47+
def redact_images(value: Any) -> Any:
48+
"""A request body for the request log: every image part's URL or data replaced, the rest kept."""
49+
50+
if isinstance(value, list):
51+
return [redact_images(item) for item in value]
52+
if not isinstance(value, dict):
53+
return value
54+
if value.get("type") == "image_url":
55+
return {**value, "image_url": {"url": "<redacted>"}}
56+
return {key: redact_images(item) for key, item in value.items()}
57+
58+
4759
def served_model_ids(served_name: str, aliases: list[str] | None = None) -> list[str]:
4860
"""Return the OpenAI model ids this endpoint advertises."""
4961

@@ -151,7 +163,7 @@ def do_POST(self) -> None:
151163
validate_modalities(body)
152164
if _REQUEST_LOG and body.get("priority") != "background": # batch jobs are not client traffic
153165
with open(_REQUEST_LOG, "a") as handle:
154-
handle.write(json.dumps(body) + "\n")
166+
handle.write(json.dumps(redact_images(body)) + "\n")
155167
raw_kw: dict[str, Any] = {}
156168
if is_chat_completion:
157169
messages = normalize_messages(body.get("messages"), allow_images=getattr(app, "vision", None) is not None)
@@ -194,7 +206,8 @@ def do_POST(self) -> None:
194206
stream = bool(body.get("stream", False))
195207
tool_policy = ToolCallPolicy(body)
196208
except RequestError as exc:
197-
self._send_json({"error": {"message": str(exc), "type": "invalid_request_error"}}, status=400)
209+
self._send_json({"error": {"message": str(exc), "type": "invalid_request_error"}},
210+
status=503 if isinstance(exc, CapacityError) else 400)
198211
return
199212
except Exception as exc:
200213
self._send_json({"error": {"message": str(exc)}}, status=400)

‎src/tensorfold/server/prompts.py‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22
from __future__ import annotations
33

44
from dataclasses import dataclass
5+
import threading
56
from typing import Any
67

7-
from tensorfold.server.errors import RequestError
8+
from tensorfold.server.errors import CapacityError, RequestError
89
from tensorfold.server.messages import _normalize_tool_call_arguments, normalize_messages
910

1011

@@ -21,18 +22,41 @@ def has_images(messages):
2122
for m in messages or [])
2223

2324

25+
IMAGE_SLOTS = threading.BoundedSemaphore(16) # requests decoding and processing images at once (host memory)
26+
IMAGE_WAITERS = threading.BoundedSemaphore(128) # requests waiting for a slot; past that, refused at once
27+
IMAGE_WAIT_S = 60.0
28+
29+
30+
def image_slot():
31+
"""Hold one image-preparation slot, or refuse with 503 when the queue is full or the wait runs out."""
32+
if not IMAGE_WAITERS.acquire(blocking=False):
33+
raise CapacityError('image request queue is full; retry shortly')
34+
try:
35+
if not IMAGE_SLOTS.acquire(timeout=IMAGE_WAIT_S):
36+
raise CapacityError('image processing capacity is busy; retry shortly')
37+
finally:
38+
IMAGE_WAITERS.release()
39+
return IMAGE_SLOTS
40+
41+
2442
def prepare_images(frontend, messages, render, *, context_limit=None):
2543
from tensorfold.vision.images import ImageInputError, load_images, split_images
2644

2745
if frontend is None:
2846
raise RequestError('image input requires a supported vision checkpoint served with --vision')
47+
allow_urls = bool(getattr(frontend, 'allow_urls', False))
2948
try:
30-
allow_urls = bool(getattr(frontend, 'allow_urls', False))
3149
template, sources = split_images(messages, allow_urls=allow_urls)
50+
except (ImageInputError, ValueError) as exc:
51+
raise RequestError(str(exc)) from exc
52+
slot = image_slot()
53+
try:
3254
images = load_images(sources, allow_urls=allow_urls)
3355
prepared = frontend.prepare(render(template), images, max_prompt_tokens=context_limit)
3456
except (ImageInputError, ValueError, ImportError) as exc:
3557
raise RequestError(str(exc)) from exc
58+
finally:
59+
slot.release()
3660
return RenderedPrompt(list(prepared.token_ids), vision=prepared)
3761

3862

‎src/tensorfold/vision/images.py‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@
1414
from typing import Any
1515
from urllib.parse import unquote_to_bytes
1616

17-
from .images_http import ImageInputError, fetch_image
17+
from .images_http import MEDIA_TYPES, ImageInputError, fetch_image
1818

1919
_DETAILS = {"auto", "low", "high"}
20-
_FORMATS = ("JPEG", "PNG", "WEBP", "GIF", "BMP", "TIFF")
20+
_FORMATS = tuple(MEDIA_TYPES.values())
2121
_MEDIA = {"image", "images", "image_url", "input_image", "audio", "input_audio", "video", "video_url"}
2222

2323

@@ -104,8 +104,8 @@ def _check_source(source: ImageSource, limits: ImageLimits, allow_urls: bool = F
104104
if source.url.startswith("data:"):
105105
if len(source.url) > limits.max_encoded_bytes * 3 + 256:
106106
raise ImageInputError("image data URL exceeds the encoded byte limit")
107-
elif not source.url.startswith(("http://", "https://")):
108-
raise ImageInputError("images require data URLs or public HTTP(S) URLs")
107+
elif not source.url.startswith("https://"):
108+
raise ImageInputError("images require data URLs or public HTTPS URLs")
109109
elif not allow_urls:
110110
raise ImageInputError("image URLs are off on this server; send the image as a data URL, or start the server "
111111
"with --vision-urls")
@@ -208,7 +208,7 @@ def _decode(data: bytes, detail: str, limits: ImageLimits, remaining_pixels: int
208208
except ImageInputError:
209209
raise
210210
except (OSError, ValueError, SyntaxError, image.DecompressionBombWarning, image.DecompressionBombError):
211-
raise ImageInputError("image bytes are invalid or unsupported; use JPEG, PNG, WEBP, GIF, BMP or TIFF") from None
211+
raise ImageInputError("image bytes are invalid or unsupported; use JPEG, PNG or WebP") from None
212212

213213

214214
def load_images(sources: list[ImageSource], *, limits: ImageLimits = DEFAULT_LIMITS, allow_urls: bool = False
@@ -227,9 +227,9 @@ def load_images(sources: list[ImageSource], *, limits: ImageLimits = DEFAULT_LIM
227227
if source.url.startswith("data:"):
228228
data = _data_bytes(source.url, remaining)
229229
else:
230-
data = fetch_image(source.url, max_bytes=remaining,
231-
deadline=min(deadline, time.monotonic() + limits.timeout_seconds),
232-
max_redirects=limits.max_redirects, max_url_chars=limits.max_url_chars)
230+
data, _ = fetch_image(source.url, max_bytes=remaining,
231+
deadline=min(deadline, time.monotonic() + limits.timeout_seconds),
232+
max_redirects=limits.max_redirects, max_url_chars=limits.max_url_chars)
233233
total_bytes += len(data)
234234
decoded = _decode(data, source.detail, limits, limits.max_total_pixels - total_pixels)
235235
if time.monotonic() >= deadline:

‎src/tensorfold/vision/images_http.py‎

Lines changed: 27 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""Bounded HTTP image retrieval with validated, pinned public addresses."""
1+
"""Bounded HTTPS image retrieval with validated, pinned public addresses."""
22

33
from __future__ import annotations
44

@@ -11,6 +11,9 @@
1111
import time
1212
from urllib.parse import quote, urljoin, urlsplit
1313

14+
from tensorfold import __version__
15+
16+
MEDIA_TYPES = {"image/jpeg": "JPEG", "image/png": "PNG", "image/webp": "WEBP"} # a declared type, its format
1417
_DNS_SLOTS = threading.BoundedSemaphore(4)
1518
_REDIRECTS = {301, 302, 303, 307, 308}
1619
_SPECIAL_V4 = (ipaddress.ip_network("192.0.0.0/24"), ipaddress.ip_network("168.63.129.16/32"))
@@ -79,22 +82,22 @@ def _url(value: str, max_url_chars: int) -> tuple[str, str, int, str]:
7982
raise ImageInputError("image URL is too long or contains whitespace/control characters")
8083
try:
8184
parsed = urlsplit(value)
82-
if parsed.scheme not in ("http", "https") or not parsed.hostname:
85+
if parsed.scheme != "https" or not parsed.hostname or parsed.fragment:
8386
raise ValueError
8487
if parsed.username is not None or parsed.password is not None or "\\" in value:
8588
raise ValueError
8689
host = parsed.hostname.encode("idna").decode("ascii")
87-
port = parsed.port if parsed.port is not None else (443 if parsed.scheme == "https" else 80)
88-
if "%" in host or not 1 <= port <= 65535:
90+
port = parsed.port if parsed.port is not None else 443
91+
if "%" in host or port != 443:
8992
raise ValueError
9093
except (ValueError, UnicodeError):
91-
raise ImageInputError("image URL must be an HTTP(S) URL without credentials") from None
94+
raise ImageInputError("image URL must be HTTPS on port 443, without credentials or a fragment") from None
9295
if host.rstrip(".").lower() in {"localhost", "metadata.google.internal", "instance-data"}:
9396
raise ImageInputError("image URLs must use public internet hosts")
9497
target = quote(parsed.path or "/", safe="/%:@!$&'()*+,;=-._~")
9598
if parsed.query:
9699
target += "?" + quote(parsed.query, safe="/%?:@!$&'()*+,;=-._~")
97-
return parsed.scheme, host, port, target
100+
return host, port, target
98101

99102

100103
def _close_socket(sock: socket.socket) -> None:
@@ -105,8 +108,8 @@ def _close_socket(sock: socket.socket) -> None:
105108
sock.close()
106109

107110

108-
def _request(scheme: str, host: str, port: int, target: str, addresses: list[tuple],
109-
max_bytes: int, deadline: float) -> tuple[bytes | None, str | None]:
111+
def _request(host: str, port: int, target: str, addresses: list[tuple],
112+
max_bytes: int, deadline: float) -> tuple[bytes | None, str | None, str | None]:
110113
"""A watchdog bounds slow headers and TLS handshakes, not just individual reads."""
111114
timeout = _remaining(deadline)
112115
family, kind, protocol, _, address = addresses[0]
@@ -119,25 +122,28 @@ def _request(scheme: str, host: str, port: int, target: str, addresses: list[tup
119122
timer.start()
120123
sock.settimeout(_remaining(deadline))
121124
sock.connect(address)
122-
if scheme == "https":
123-
context = ssl.create_default_context()
124-
sock = context.wrap_socket(sock, server_hostname=host, do_handshake_on_connect=False)
125-
live_socket[0] = sock
126-
sock.settimeout(_remaining(deadline))
127-
sock.do_handshake()
125+
context = ssl.create_default_context() # TLS verified for the host, on the address checked for it
126+
sock = context.wrap_socket(sock, server_hostname=host, do_handshake_on_connect=False)
127+
live_socket[0] = sock
128+
sock.settimeout(_remaining(deadline))
129+
sock.do_handshake()
128130
connection.sock = sock
129-
connection.request("GET", target, headers={"Accept": "image/*", "Accept-Encoding": "identity"})
131+
connection.request("GET", target, headers={"Accept": ", ".join(MEDIA_TYPES), "Accept-Encoding": "identity",
132+
"User-Agent": f"TensorFold/{__version__}"})
130133
response = connection.getresponse()
131134
_remaining(deadline)
132135
if response.status in _REDIRECTS:
133136
location = response.getheader("Location")
134137
if not location:
135138
raise ImageInputError("image redirect has no destination")
136-
return None, location
139+
return None, location, None
137140
if response.status != 200:
138141
raise ImageInputError(f"image download returned HTTP {response.status}")
139142
if response.getheader("Content-Encoding", "identity").lower() != "identity":
140143
raise ImageInputError("compressed HTTP image responses are unsupported")
144+
media = response.getheader("Content-Type", "").split(";", 1)[0].strip().lower()
145+
if media not in MEDIA_TYPES:
146+
raise ImageInputError("image URL content type must be JPEG, PNG or WebP")
141147
length = response.getheader("Content-Length")
142148
if length is not None:
143149
if not length.isascii() or not length.isdecimal() or int(length) > max_bytes:
@@ -152,23 +158,23 @@ def _request(scheme: str, host: str, port: int, target: str, addresses: list[tup
152158
if len(data) > max_bytes:
153159
raise ImageInputError("image response exceeds the encoded byte limit")
154160
_remaining(deadline)
155-
return bytes(data), None
161+
return bytes(data), None, media
156162
finally:
157163
timer.cancel()
158164
connection.close()
159165
_close_socket(sock)
160166

161167

162168
def fetch_image(url: str, *, max_bytes: int, deadline: float, max_redirects: int,
163-
max_url_chars: int) -> bytes:
169+
max_url_chars: int) -> tuple[bytes, str]:
164170
"""Resolve and validate each redirect, then connect directly to its checked address."""
165171
try:
166172
for redirect in range(max_redirects + 1):
167-
scheme, host, port, target = _url(url, max_url_chars)
173+
host, port, target = _url(url, max_url_chars)
168174
addresses = _resolve(host, port, deadline)
169-
data, location = _request(scheme, host, port, target, addresses, max_bytes, deadline)
175+
data, location, media = _request(host, port, target, addresses, max_bytes, deadline)
170176
if location is None:
171-
return data
177+
return data, media
172178
if redirect == max_redirects:
173179
raise ImageInputError("image download has too many redirects")
174180
url = urljoin(url, location)

0 commit comments

Comments
 (0)