Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 128 additions & 2 deletions studio/backend/core/inference/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
(DuckDuckGo), Python code execution, and terminal commands."""

import ast
import codecs
import fnmatch
import http.client
import os
Expand Down Expand Up @@ -3581,6 +3582,64 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
# sections stripped during conversion; 512 KB reaches article content even
# where <head> alone is ~200 KB.
_MAX_FETCH_BYTES = 512 * 1024
# Undecodable bytes and controls, excluding text whitespace and ESC for ANSI logs.
# More than 12.5% is binary after allowing 16 minor encoding glitches.
_BINARY_CHAR_RE = re.compile("[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1a\\x1c-\\x1f\\x7f-\\x9f\\ufffd]")
_MIN_BINARY_CHARS = 16
_BINARY_CHAR_DIVISOR = 8
# Common binary signatures that can otherwise look text-heavy when mislabeled.
_BINARY_MAGIC = (
b"%PDF-", # PDF
b"PK\x03\x04", # zip / docx / xlsx / pptx / epub / jar
b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1", # OLE / legacy Office
b"\x89PNG\r\n\x1a\n", # PNG
b"\xff\xd8\xff", # JPEG
b"GIF87a",
b"GIF89a",
b"\x1f\x8b", # gzip
b"BZh", # bzip2
b"\xfd7zXZ\x00", # xz
b"\x28\xb5\x2f\xfd", # zstd
)

# Check UTF-32 first because its little-endian BOM starts with the UTF-16 BOM.
_UNICODE_BOM_CODECS = (
(codecs.BOM_UTF32_LE, "utf-32"),
(codecs.BOM_UTF32_BE, "utf-32"),
(codecs.BOM_UTF16_LE, "utf-16"),
(codecs.BOM_UTF16_BE, "utf-16"),
(codecs.BOM_UTF8, "utf-8-sig"),
)

# A cp1252 retry needs 75% ASCII structure so it cannot rescue high-byte binary.
_MIN_SINGLE_BYTE_ASCII_RATIO = 3 / 4
_ASCII_TEXT_BYTES = frozenset((*range(0x20, 0x7F), 0x09, 0x0A, 0x0D, 0x1B))


def _looks_binary(text: str) -> bool:
"""Whether control or undecodable characters exceed the binary threshold."""
return len(_BINARY_CHAR_RE.findall(text)) > max(
_MIN_BINARY_CHARS, len(text) // _BINARY_CHAR_DIVISOR
)


def _has_binary_magic(data: bytes) -> bool:
"""Whether a common binary signature follows optional BOM or whitespace."""
head = data[:1024].lstrip()
for bom, _codec in _UNICODE_BOM_CODECS:
if head.startswith(bom):
head = head.removeprefix(bom).lstrip()
break
return head.startswith(_BINARY_MAGIC)


def _has_single_byte_text_evidence(data: bytes) -> bool:
"""True when *data* has enough ASCII structure for a cp1252 text retry."""
if not data:
return True
ascii_text_bytes = sum(byte in _ASCII_TEXT_BYTES for byte in data)
return ascii_text_bytes / len(data) >= _MIN_SINGLE_BYTE_ASCII_RATIO


_USER_AGENTS = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
Expand Down Expand Up @@ -3682,6 +3741,42 @@ def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, str
return True, "", first_ip


# Known binary application subtypes are rejected by MIME type. Unknown
# application types are sniffed so textual artifacts such as SQL remain usable.
_BINARY_APPLICATION_SUBTYPES = frozenset(
{
"epub+zip",
"gzip",
"java-archive",
"pdf",
"vnd.apple.installer+xml",
"wasm",
"x-7z-compressed",
"x-bzip2",
"x-gzip",
"x-rar-compressed",
"x-tar",
"x-xz",
"zip",
"zstd",
}
)


def _is_text_candidate_content_type(content_type: str | None) -> bool:
"""Whether a MIME type is textual or ambiguous enough for byte sniffing."""
match = re.match(r"[\w.+-]+/[\w.+-]+", content_type or "")
if not match:
return True
ct = match.group(0).lower()
if ct.startswith("text/"):
return True
if ct.startswith("application/"):
subtype = ct[len("application/") :]
return subtype not in _BINARY_APPLICATION_SUBTYPES
return False
Comment thread
oobabooga marked this conversation as resolved.
Resolved


def _fetch_page_text(
url: str,
max_chars: int = _MAX_PAGE_CHARS,
Expand Down Expand Up @@ -3762,8 +3857,39 @@ def _fetch_page_text(
else:
return "Failed to fetch URL: too many redirects."

charset = resp.headers.get_content_charset() or "utf-8"
raw_html = raw_bytes.decode(charset, errors = "replace")
# Reject MIME types known to be binary before decoding.
content_type = resp.headers.get_content_type()
if not _is_text_candidate_content_type(content_type):
# Only echo a clean MIME token back to the model.
m = re.match(r"[\w.+-]+/[\w.+-]+", content_type or "")
safe_type = m.group(0) if m else "unknown type"
return f"(non-text content: {safe_type}, {len(raw_bytes)} bytes; not readable as text)"

# Catch text-labeled binary whose header and first chunk look textual.
if _has_binary_magic(raw_bytes):
return f"(binary content, {len(raw_bytes)} bytes; not readable as text)"

declared = resp.headers.get_content_charset()
declared_codec = codecs.lookup(declared).name if declared else None
bom_codec = next(
(codec for bom, codec in _UNICODE_BOM_CODECS if raw_bytes.startswith(bom)),
None,
)
raw_html = raw_bytes.decode(declared or bom_codec or "utf-8", errors = "replace")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject Latin-1 declared binary before returning it

When a response declares charset=iso-8859-1 or windows-1252, decoding here can map arbitrary high-byte binary to printable characters, so _looks_binary(raw_html) stays false and the blob is returned to the model instead of the new placeholder. For example, a text/plain; charset=iso-8859-1 body with no magic header and mostly bytes 0xA0..0xFF passes this guard and still poisons context with unreadable data; apply the same ASCII-structure sniffing used for the cp1252 rescue to declared Latin-1/cp1252 decodes before accepting them as text.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declining this: it is the direct inverse of the earlier review that (correctly) flagged the same gate for dropping legitimate dense-accented Latin-1 text. The ASCII-ratio signal cannot separate dense Latin-1 text from high-byte Latin-1 binary (byte-identical), so gating declared Latin-1/cp1252 regresses real text. This path requires a server mislabeling binary as iso-8859-1 text, matches pre-PR behavior (not a regression), and any true binary is already bounded by the MIME, magic-byte, and control-density guards. Leaving declared single-byte responses to decode and keep.


# Catch mislabeled or unlabeled binary, including valid UTF-8 controls.
if _looks_binary(raw_html):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require ASCII evidence for Latin-1 bodies

For responses declared as text/plain; charset=iso-8859-1, high-byte binary payloads such as long runs of bytes in 0xA0..0xFF decode to printable Latin-1 characters, so _looks_binary(raw_html) sees no controls or replacement chars and this branch accepts them without ever applying _has_single_byte_text_evidence. That leaves exactly the “high-byte binary accepted as text” case unguarded when a server supplies a Latin-1 charset; apply the ASCII-structure check before accepting declared Latin-1/cp1252-style decodes, not only when the first decode already looks binary.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c7fbec2: the ASCII-structure gate now also applies to declared iso-8859-1/windows-1252 decodes, so high-byte binary mislabeled as Latin-1 is rejected. Scoped to the Latin family so legitimate non-Latin single-byte pages (Cyrillic, Greek) with dense high bytes are not dropped. Verified against a full declared-encoding matrix.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On reflection this is reverted (3b7bebe). The only available signal (ASCII ratio) cannot separate dense-accented Latin-1 text from high-byte binary, so gating declared Latin-1/cp1252 regressed legitimate text (see the follow-up review). The mislabeled-binary-as-Latin-1 case matches pre-PR behavior and is already bounded by the MIME, magic-byte, and control-density guards, so the declared single-byte path is left to decode and keep.

# Rescue undeclared cp1252 only when the bytes have text structure.
alt = (
raw_bytes.decode("cp1252", "replace")
if declared_codec in (None, "iso8859-1")
and _has_single_byte_text_evidence(raw_bytes)
else None
Comment thread
oobabooga marked this conversation as resolved.
Resolved
)
if alt is not None and not _looks_binary(alt):
raw_html = alt
Comment thread
oobabooga marked this conversation as resolved.
Resolved
else:
return f"(binary content, {len(raw_bytes)} bytes; not readable as text)"
except _HTTPError as e:
return f"Failed to fetch URL: HTTP {e.code} {getattr(e, 'reason', '')}"
except Exception as e:
Expand Down
Loading
Loading