Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: a binary request body should be a 422, not a 500 with the payload in the log (#8307)

Daniel Hanfddd3cc19635
diff --git a/studio/backend/loggers/config.py b/studio/backend/loggers/config.py
index 57cf7cecd66..dc2d14d6327 100644
--- a/studio/backend/loggers/config.py
+++ b/studio/backend/loggers/config.py
@@ -26,6 +26,80 @@ class _DropTorchDtypeDeprecation(logging.Filter):
return not ("torch_dtype" in msg and "deprecated" in msg)
+def _env_int(name: str, default: int) -> int:
+ try:
+ raw = (os.environ.get(name) or "").strip()
+ return int(raw) if raw else default
+ except ValueError:
+ return default
+
+
+# Cap on the rendered traceback in a single log record. A traceback is normally a few
+# KB, but an exception whose message embeds a request body is not: a binary upload
+# rejected by request validation produced one 2.2 MB line. Keep the head (where the
+# raising frame is) and the tail (where the actual exception type and message are),
+# and say how much was dropped. 0 disables the cap.
+_MAX_EXC_CHARS = _env_int("UNSLOTH_STUDIO_MAX_EXCEPTION_CHARS", 16384)
+_EXC_TAIL_CHARS = 2048
+# The middleware logs the same exception twice: once rendered as a traceback under
+# "exception" and once as str(exc) under "error". Capping only the first still lets an
+# exception whose message embeds the request body through, so bound both.
+_MAX_ERROR_CHARS = 2048
+
+
+def _truncate_middle(text: str, limit: int, tail: int) -> str:
+ """Keep the head and the tail of `text`, saying how much was dropped.
+
+ The head holds the raising frame and the tail the exception type and message, so
+ both ends are worth keeping. `tail` is clamped so a cap smaller than the tail
+ cannot make the head negative and hand back nearly the whole string.
+ """
+ if limit <= 0 or len(text) <= limit:
+ return text
+ tail = max(1, min(tail, limit // 4))
+ head = limit - tail
+ dropped = len(text) - limit
+ return (
+ text[:head] + f"\n... [{dropped} chars omitted; "
+ "raise UNSLOTH_STUDIO_MAX_EXCEPTION_CHARS to see it all] ...\n" + text[-tail:]
+ )
+
+
+def truncate_exception(event_dict: dict) -> dict:
+ """Structlog processor: bound the rendered exception, its message and the event."""
+ if _MAX_EXC_CHARS <= 0:
+ return event_dict
+ text = event_dict.get("exception")
+ if isinstance(text, str):
+ event_dict["exception"] = _truncate_middle(text, _MAX_EXC_CHARS, _EXC_TAIL_CHARS)
+ message_cap = min(_MAX_ERROR_CHARS, _MAX_EXC_CHARS)
+ error = event_dict.get("error")
+ if isinstance(error, str):
+ event_dict["error"] = _truncate_middle(error, message_cap, _EXC_TAIL_CHARS)
+ # f-string call sites interpolate the exception straight into the message
+ # (routes/inference.py: logger.error(f"...: {e}", exc_info = True)), so the event
+ # itself is a third copy that can carry the whole payload.
+ event = event_dict.get("event")
+ if isinstance(event, str):
+ event_dict["event"] = _truncate_middle(event, message_cap, _EXC_TAIL_CHARS)
+ # logger.error("stream error: %s", exc) keeps the exception under positional_args,
+ # and the chain has no PositionalArgumentsFormatter, so the renderer stringifies it
+ # untouched. Render and cap it here instead.
+ args = event_dict.get("positional_args")
+ if isinstance(args, (list, tuple)) and args:
+ event_dict["positional_args"] = [
+ _truncate_middle(a, message_cap, _EXC_TAIL_CHARS)
+ if isinstance(a, str)
+ else _truncate_middle(str(a), message_cap, _EXC_TAIL_CHARS)
+ for a in args
+ ]
+ return event_dict
+
+
+def _truncate_exception_processor(logger, method_name, event_dict):
+ return truncate_exception(event_dict)
+
+
class LogConfig:
"""Structured logging configuration for the application."""
@@ -62,6 +136,10 @@ class LogConfig:
structlog.contextvars.merge_contextvars,
structlog.processors.format_exc_info,
filter_sensitive_data,
+ # After redaction, not before: redact_native_paths replaces exact
+ # strings, so cutting the middle out of a traceback first could leave
+ # half a path behind for it to miss.
+ _truncate_exception_processor,
# Flatten the extra field into the main dict.
lambda logger, method_name, event_dict: {
"timestamp": event_dict.get("timestamp"),
diff --git a/studio/backend/tests/test_exception_log_truncation.py b/studio/backend/tests/test_exception_log_truncation.py
new file mode 100644
index 00000000000..5e23d0ad05e
--- /dev/null
+++ b/studio/backend/tests/test_exception_log_truncation.py
@@ -0,0 +1,109 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""One log record must not be able to grow without bound.
+
+request_failed renders the whole traceback into an "exception" field. That is a
+few KB for a normal failure, but an exception whose message embeds a request body
+is not: a rejected binary upload produced a single 2.2 MB line. The head (raising
+frame) and the tail (exception type and message) are what a reader needs, so the
+middle is dropped with a count of what went missing.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+_BACKEND = Path(__file__).resolve().parent.parent
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+from loggers import config as log_config # noqa: E402
+
+
+def test_short_tracebacks_are_untouched():
+ ev = {"exception": "Traceback...\nValueError: nope"}
+ assert log_config.truncate_exception(dict(ev)) == ev
+
+
+def test_long_traceback_is_capped():
+ text = "HEAD" + ("x" * 4_000_000) + "TAILValueError: nope"
+ out = log_config.truncate_exception({"exception": text})["exception"]
+ assert len(out) < log_config._MAX_EXC_CHARS + 200, len(out)
+
+
+def test_head_and_tail_survive():
+ text = "TRACEBACK_HEAD_MARKER" + ("x" * 4_000_000) + "EXC_TAIL_MARKER"
+ out = log_config.truncate_exception({"exception": text})["exception"]
+ assert out.startswith("TRACEBACK_HEAD_MARKER")
+ assert out.endswith("EXC_TAIL_MARKER")
+ assert "chars omitted" in out
+
+
+def test_the_error_field_is_capped_too():
+ # request_failed logs str(exc) under "error" as well as the rendered traceback,
+ # so capping only the traceback still lets the same payload through.
+ text = "ERR_HEAD" + ("x" * 4_000_000) + "ERR_TAIL"
+ out = log_config.truncate_exception({"error": text})["error"]
+ assert len(out) < log_config._MAX_ERROR_CHARS + 200, len(out)
+ assert out.startswith("ERR_HEAD")
+ assert out.endswith("ERR_TAIL")
+
+
+def test_a_cap_smaller_than_the_tail_is_still_enforced(monkeypatch):
+ # head = cap - tail went negative, so text[:-2048] kept nearly everything.
+ monkeypatch.setattr(log_config, "_MAX_EXC_CHARS", 1024)
+ text = "H" * 4_000_000
+ out = log_config.truncate_exception({"exception": text})["exception"]
+ assert len(out) < 1024 + 200, len(out)
+
+
+def test_non_string_exception_field_is_ignored():
+ ev = {"exception": None}
+ assert log_config.truncate_exception(dict(ev)) == ev
+ ev2 = {"event": "no exception here"}
+ assert log_config.truncate_exception(dict(ev2)) == ev2
+
+
+def test_cap_can_be_disabled(monkeypatch):
+ monkeypatch.setattr(log_config, "_MAX_EXC_CHARS", 0)
+ text = "y" * 100_000
+ assert log_config.truncate_exception({"exception": text})["exception"] == text
+
+
+def test_processor_signature_matches_structlog():
+ text = "z" * 100_000
+ out = log_config._truncate_exception_processor(None, "error", {"exception": text})
+ assert len(out["exception"]) < len(text)
+
+
+def test_redaction_runs_before_truncation():
+ # redact_native_paths replaces exact strings, so truncating first could leave a
+ # half path behind for it to miss.
+ text = (_BACKEND / "loggers/config.py").read_text(encoding = "utf-8")
+ order = text.index("filter_sensitive_data,\n"), text.index("_truncate_exception_processor,\n")
+ assert order[0] < order[1], "filter_sensitive_data must come first in the chain"
+
+
+def test_the_event_field_is_capped_too():
+ # logger.error(f"failed: {e}", exc_info = True) puts the whole exception text in
+ # the event, a third copy the first two caps never saw.
+ text = "failed: " + ("q" * 4_000_000)
+ out = log_config.truncate_exception({"event": text})["event"]
+ assert len(out) < log_config._MAX_ERROR_CHARS + 200, len(out)
+ assert out.startswith("failed: ")
+
+
+def test_a_normal_event_name_is_untouched():
+ ev = {"event": "request_failed", "error": "boom"}
+ assert log_config.truncate_exception(dict(ev)) == ev
+
+
+def test_positional_arguments_are_capped():
+ # logger.error("stream error: %s", exc) keeps the exception under positional_args,
+ # which the renderer stringifies with nothing in the chain to bound it.
+ out = log_config.truncate_exception(
+ {"event": "stream error: %s", "positional_args": (Exception("x" * 4_000_000),)}
+ )
+ assert len(str(out["positional_args"][0])) < log_config._MAX_ERROR_CHARS + 200
diff --git a/studio/backend/tests/test_validation_error_binary_body.py b/studio/backend/tests/test_validation_error_binary_body.py
new file mode 100644
index 00000000000..0c52789537c
--- /dev/null
+++ b/studio/backend/tests/test_validation_error_binary_body.py
@@ -0,0 +1,229 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A binary body on a JSON route must yield 422, not 500 plus a megabyte of log.
+
+POSTing a multipart WAV upload to /api/inference/audio/transcribe (which takes a
+JSON body with base64 audio) failed request validation. The handler then ran
+jsonable_encoder over exc.errors(), whose "input" was the whole raw body, and
+FastAPI encodes bytes with o.decode(): UnicodeDecodeError. The 422 became a 500
+whose traceback embedded the escaped payload, so one 531 KB upload wrote a single
+2.2 MB line into the server log.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+_BACKEND = Path(__file__).resolve().parent.parent
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+import pytest # noqa: E402
+from fastapi import FastAPI # noqa: E402
+from fastapi.encoders import jsonable_encoder # noqa: E402
+from fastapi.testclient import TestClient # noqa: E402
+from pydantic import BaseModel # noqa: E402
+
+from utils.api_errors import ( # noqa: E402
+ install_api_error_handlers,
+ safe_validation_errors,
+)
+
+# Non-UTF-8: 0x80 is an invalid start byte, exactly like a RIFF/WAV payload.
+_BINARY = b"RIFF\x00\x00\x80\xff\xfe\xfd" * 64
+
+
+class _Body(BaseModel):
+ audio: str
+
+
+def _client() -> TestClient:
+ app = FastAPI()
+ install_api_error_handlers(app)
+
+ @app.post("/api/thing")
+ async def _thing(payload: _Body): # pragma: no cover - never reached here
+ return {"ok": True}
+
+ return TestClient(app)
+
+
+def _post_multipart_binary(client: TestClient):
+ # A multipart upload to a JSON-body route: the shape that produced the 500.
+ # FastAPI reads the body, fails to coerce it to the model, and puts the raw
+ # bytes in the error's "input".
+ return client.post("/api/thing", files = {"file": ("audio.wav", _BINARY, "audio/wav")})
+
+
+def test_binary_body_returns_422_not_500():
+ resp = _post_multipart_binary(_client())
+ assert resp.status_code == 422, resp.text
+
+
+def test_response_does_not_echo_the_body():
+ resp = _post_multipart_binary(_client())
+ # The response stays small: the payload is summarized, never echoed back.
+ assert len(resp.text) < 2000, len(resp.text)
+ assert "RIFF" not in resp.text
+
+
+def test_valid_body_still_passes():
+ resp = _client().post("/api/thing", json = {"audio": "abc"})
+ assert resp.status_code == 200
+ assert resp.json() == {"ok": True}
+
+
+def test_a_normal_validation_error_still_names_the_field():
+ resp = _client().post("/api/thing", json = {"wrong": 1})
+ assert resp.status_code == 422
+ body = resp.json()
+ detail = body["detail"]
+ assert any("audio" in str(item.get("loc", "")) for item in detail), detail
+
+
+ "value, expected_fragment",
+ [
+ (b"\x80\xff", "2 bytes of binary data"),
+ (bytearray(b"\x00" * 5), "5 bytes of binary data"),
+ ("x" * 5000, "truncated, 5000 chars"),
+ ],
+)
+def test_summarizer_makes_inputs_encodable(value, expected_fragment):
+ errors = [{"type": "x", "loc": ("body",), "msg": "bad", "input": value}]
+ safe = safe_validation_errors(errors)
+ assert expected_fragment in str(safe[0]["input"])
+ jsonable_encoder(safe) # must not raise
+
+
+def test_short_inputs_are_left_alone():
+ errors = [{"type": "x", "loc": ("body",), "msg": "bad", "input": {"a": 1}}]
+ assert safe_validation_errors(errors)[0]["input"] == {"a": 1}
+
+
+def test_nested_binary_inside_a_dict_is_summarized():
+ errors = [{"type": "x", "loc": ("body",), "msg": "bad", "input": {"f": b"\x80\x81"}}]
+ safe = safe_validation_errors(errors)
+ jsonable_encoder(safe)
+ assert "2 bytes of binary data" in str(safe[0]["input"]["f"])
+
+
+def test_a_huge_array_of_small_values_is_bounded():
+ # 200k integers are individually tiny but the list was copied whole.
+ errors = [{"type": "x", "loc": ("body",), "msg": "bad", "input": list(range(200_000))}]
+ safe = safe_validation_errors(errors)
+ out = safe[0]["input"]
+ assert len(out) <= 21, len(out)
+ assert "more items" in str(out[-1])
+ assert len(str(safe)) < 2000, len(str(safe))
+
+
+def test_a_huge_object_of_small_values_is_bounded():
+ errors = [
+ {"type": "x", "loc": ("body",), "msg": "bad", "input": {str(i): i for i in range(50_000)}}
+ ]
+ out = safe_validation_errors(errors)[0]["input"]
+ assert len(out) <= 21, len(out)
+ assert "more keys" in str(out["..."])
+
+
+def test_deep_nesting_does_not_explode():
+ value = payload = {}
+ for _ in range(20):
+ payload["next"] = {}
+ payload = payload["next"]
+ out = safe_validation_errors([{"type": "x", "loc": ("body",), "msg": "bad", "input": value}])[
+ 0
+ ]["input"]
+ assert "dict with" in str(out)
+
+
+def test_a_validator_message_quoting_the_value_is_bounded():
+ # models/training.py::_parse_lr raises f"... (got {v!r})".
+ msg = "learning_rate must be parseable as float (got '" + "9" * 500_000 + "')"
+ safe = safe_validation_errors([{"type": "x", "loc": ("body",), "msg": msg, "input": "x"}])
+ assert len(safe[0]["msg"]) < 300, len(safe[0]["msg"])
+ assert safe[0]["msg"].startswith("learning_rate must be parseable")
+
+
+def test_a_ctx_error_quoting_the_value_is_bounded():
+ exc = ValueError("got '" + "9" * 500_000 + "'")
+ safe = safe_validation_errors(
+ [{"type": "x", "loc": ("body",), "msg": "bad", "input": "x", "ctx": {"error": exc}}]
+ )
+ assert len(str(safe[0]["ctx"]["error"])) < 300
+ jsonable_encoder(safe)
+
+
+def test_a_long_dictionary_key_is_truncated():
+ errors = [{"type": "x", "loc": ("body",), "msg": "bad", "input": {"k" * 100_000: 1}}]
+ out = safe_validation_errors(errors)[0]["input"]
+ assert all(len(k) < 300 for k in out), [len(k) for k in out]
+
+
+def test_non_finite_numbers_do_not_break_json():
+ # Starlette's JSONResponse dumps with allow_nan = False, so an echoed NaN or
+ # Infinity turns the intended 422 into a 500.
+ import json
+
+ errors = [
+ {"type": "x", "loc": ("body", "max_grad_norm"), "msg": "bad", "input": float("nan")},
+ {"type": "x", "loc": ("body", "lr"), "msg": "bad", "input": float("inf")},
+ ]
+ safe = safe_validation_errors(errors)
+ json.dumps(jsonable_encoder(safe), allow_nan = False)
+
+
+def test_the_number_of_errors_is_capped():
+ errors = [
+ {"type": "x", "loc": ("body", "messages", i, "role"), "msg": "bad", "input": "z"}
+ for i in range(5000)
+ ]
+ safe = safe_validation_errors(errors)
+ assert len(safe) == 21, len(safe)
+ assert "4980 more validation errors omitted" in safe[-1]["msg"]
+
+
+def test_the_v1_surface_gets_the_same_message_cap():
+ from utils.api_errors import _summarize_validation_errors, safe_validation_errors as sve
+
+ msg = "Unsupported content block type " + "q" * 500_000
+ summary, _ = _summarize_validation_errors(
+ sve([{"type": "x", "loc": ("body", "messages"), "msg": msg, "input": "x"}])
+ )
+ assert len(summary) < 400, len(summary)
+
+
+def test_a_long_loc_element_is_truncated():
+ # A typed mapping copies the offending key into loc, so it is user-controlled.
+ errors = [{"type": "x", "loc": ("body", "budgets", "k" * 2_000_000), "msg": "bad", "input": 1}]
+ out = safe_validation_errors(errors)[0]["loc"]
+ assert all(not isinstance(p, str) or len(p) < 300 for p in out), [len(str(p)) for p in out]
+
+
+def test_an_enormous_integer_is_summarized():
+ # str() on an int past sys.get_int_max_str_digits() raises, and json.dumps would
+ # otherwise emit every digit.
+ import json
+
+ errors = [{"type": "x", "loc": ("body", "audio"), "msg": "bad", "input": 10**20_000}]
+ safe = safe_validation_errors(errors)
+ assert "integer with about" in str(safe[0]["input"])
+ json.dumps(jsonable_encoder(safe))
+
+
+def test_an_ordinary_integer_is_left_alone():
+ errors = [{"type": "x", "loc": ("body", "batch_size"), "msg": "bad", "input": 4096}]
+ assert safe_validation_errors(errors)[0]["input"] == 4096
+
+
+def test_a_lone_surrogate_can_still_be_encoded():
+ # Starlette encodes the response as UTF-8 with ensure_ascii = False, and a lone
+ # surrogate survives JSON parsing but cannot be encoded.
+ errors = [{"type": "x", "loc": ("body", "batch_size"), "msg": "bad", "input": "\ud800bad"}]
+ safe = safe_validation_errors(errors)
+ import json
+
+ json.dumps(jsonable_encoder(safe), ensure_ascii = False).encode("utf-8")
diff --git a/studio/backend/utils/api_errors.py b/studio/backend/utils/api_errors.py
index a3686c3a268..5f2480e65e6 100644
--- a/studio/backend/utils/api_errors.py
+++ b/studio/backend/utils/api_errors.py
@@ -33,6 +33,10 @@ Public contract (other modules depend on these):
- ``install_api_error_handlers(app)``
"""
+import math
+import re
+from itertools import islice
+
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse, Response
from fastapi.exceptions import RequestValidationError
@@ -186,6 +190,131 @@ def _summarize_validation_errors(errors) -> tuple:
return summary, param
+# A validation error carries the offending value under "input". For a JSON-body route
+# handed a non-JSON body (a multipart upload posted to /api/inference/audio/transcribe
+# is the case that surfaced this) that value is the whole raw payload, and
+# jsonable_encoder renders bytes with ``o.decode()``, which raises UnicodeDecodeError on
+# any binary. The handler then failed, turning a 422 into a 500 whose traceback embedded
+# the escaped payload: one 531 KB upload produced a single 2.2 MB log line.
+#
+# Clients only need loc/msg/type, so the input is summarized rather than echoed. That
+# also stops a large but perfectly decodable body from being mirrored back and logged.
+_MAX_ECHOED_INPUT_CHARS = 200
+# A body that is a huge container of small values is just as unbounded as one huge
+# string: a JSON route handed an array of 200k integers would otherwise have every
+# element copied into the 422 body. Keep enough to identify the payload, drop the rest.
+_MAX_ECHOED_ITEMS = 20
+_MAX_ECHOED_DEPTH = 4
+
+
+def _truncate_text(value: str) -> str:
+ if len(value) > _MAX_ECHOED_INPUT_CHARS:
+ value = value[:_MAX_ECHOED_INPUT_CHARS] + f"... (truncated, {len(value)} chars)"
+ # A JSON body may legally contain a lone surrogate ("\ud800"), which survives
+ # parsing but cannot be UTF-8 encoded; Starlette's JSONResponse encodes with
+ # ensure_ascii = False, so echoing one turns the 422 back into a 500.
+ if _LONE_SURROGATE_RE.search(value):
+ value = _LONE_SURROGATE_RE.sub(lambda m: f"\\u{ord(m.group()):04x}", value)
+ return value
+
+
+# Digits, not characters: str() on a very large int raises above sys.get_int_max_str_digits(),
+# and json.dumps would emit every digit otherwise.
+_MAX_ECHOED_INT_DIGITS = 100
+_LONE_SURROGATE_RE = re.compile(r"[\ud800-\udfff]")
+
+
+def _summarize_int(value: int) -> object:
+ if -(10**_MAX_ECHOED_INT_DIGITS) < value < 10**_MAX_ECHOED_INT_DIGITS:
+ return value
+ # bit_length, not str(): str() is what raises above the digit limit.
+ return f"<integer with about {value.bit_length() * 3 // 10} digits>"
+
+
+def _summarize_error_input(value, depth: int = 0):
+ """Return a JSON-safe, size-bounded stand-in for an error's ``input`` value."""
+ if isinstance(value, (bytes, bytearray, memoryview)):
+ return f"<{len(bytes(value))} bytes of binary data>"
+ if isinstance(value, str):
+ return _truncate_text(value)
+ if isinstance(value, int) and not isinstance(value, bool):
+ return _summarize_int(value)
+ if isinstance(value, float) and not math.isfinite(value):
+ # NaN and Infinity survive jsonable_encoder but Starlette's JSONResponse
+ # dumps with allow_nan = False, so echoing one turns the 422 into a 500.
+ return repr(value)
+ if isinstance(value, dict):
+ if depth >= _MAX_ECHOED_DEPTH:
+ return f"<dict with {len(value)} keys>"
+ # islice, not a slice of items(): a 10 MB object should not be materialized
+ # into a list just to keep the first 20 entries. A key can be arbitrarily
+ # long too, so it gets the same budget as a value.
+ out = {
+ _truncate_text(k) if isinstance(k, str) else k: _summarize_error_input(v, depth + 1)
+ for k, v in islice(value.items(), _MAX_ECHOED_ITEMS)
+ }
+ if len(value) > _MAX_ECHOED_ITEMS:
+ out["..."] = f"({len(value) - _MAX_ECHOED_ITEMS} more keys)"
+ return out
+ if isinstance(value, (list, tuple)):
+ if depth >= _MAX_ECHOED_DEPTH:
+ return f"<sequence of {len(value)} items>"
+ out = [_summarize_error_input(v, depth + 1) for v in islice(value, _MAX_ECHOED_ITEMS)]
+ if len(value) > _MAX_ECHOED_ITEMS:
+ out.append(f"... ({len(value) - _MAX_ECHOED_ITEMS} more items)")
+ return out
+ return value
+
+
+# One error dictionary per rejected array element is normal for a route that validates
+# each item, so the count itself is unbounded even when every entry is tiny.
+_MAX_ECHOED_ERRORS = 20
+
+
+def safe_validation_errors(errors) -> list:
+ """FastAPI's ``exc.errors()`` with every ``input`` made JSON-encodable."""
+ safe = []
+ total = len(errors) if hasattr(errors, "__len__") else None
+ for err in islice(errors, _MAX_ECHOED_ERRORS):
+ if not isinstance(err, dict):
+ safe.append(err)
+ continue
+ cleaned = dict(err)
+ # A typed mapping puts the offending key straight into loc (CreateResearchRun
+ # has budgets: dict[str, int]), so loc is user-controlled and unbounded too.
+ loc = cleaned.get("loc")
+ if isinstance(loc, (list, tuple)):
+ cleaned["loc"] = [
+ _truncate_text(part) if isinstance(part, str) else part
+ for part in islice(loc, _MAX_ECHOED_ITEMS)
+ ]
+ if "input" in cleaned:
+ cleaned["input"] = _summarize_error_input(cleaned["input"])
+ # A validator that quotes the submitted value reaches "msg" too: models/
+ # training.py's _parse_lr raises f"... (got {v!r})", so a megabyte-long
+ # learning_rate would come back in full even with "input" summarized.
+ if isinstance(cleaned.get("msg"), str):
+ cleaned["msg"] = _truncate_text(cleaned["msg"])
+ # ctx can carry the triggering exception object, which is not JSON either,
+ # and whose str() quotes the same value.
+ ctx = cleaned.get("ctx")
+ if isinstance(ctx, dict):
+ cleaned["ctx"] = {
+ k: (v if isinstance(v, (int, float, bool, type(None))) else _truncate_text(str(v)))
+ for k, v in ctx.items()
+ }
+ safe.append(cleaned)
+ if total is not None and total > _MAX_ECHOED_ERRORS:
+ safe.append(
+ {
+ "type": "too_many_errors",
+ "loc": [],
+ "msg": f"... ({total - _MAX_ECHOED_ERRORS} more validation errors omitted)",
+ }
+ )
+ return safe
+
+
def install_api_error_handlers(app) -> None:
"""Register validation + HTTPException handlers that emit ``/v1/*`` envelopes.
@@ -199,15 +328,19 @@ def install_api_error_handlers(app) -> None:
async def _handle_validation_error(request, exc):
path = request.url.path
if wants_api_error_envelope(path):
- summary, param = _summarize_validation_errors(exc.errors())
+ # Same sanitizing as the 422 branch: /v1 builds its message from msg,
+ # and a validator that quotes the submitted value (models/inference.py
+ # embeds an unsupported block's type with btype!r) makes msg unbounded.
+ summary, param = _summarize_validation_errors(safe_validation_errors(exc.errors()))
return JSONResponse(
status_code = 400,
content = error_body_for_path(path, summary, status = 400, param = param),
)
- # Default FastAPI behavior for every other path.
+ # Default FastAPI behavior for every other path, minus the raw input echo
+ # (see safe_validation_errors: encoding it raised and turned 422 into 500).
return JSONResponse(
status_code = 422,
- content = {"detail": jsonable_encoder(exc.errors())},
+ content = {"detail": jsonable_encoder(safe_validation_errors(exc.errors()))},
)
@app.exception_handler(StarletteHTTPException)