Skip to content

fix(decisions): log non-UTF-8 bytes as base64 so the request reaches validation and gets a 400 - #47564

Merged
klu-berri merged 1 commit into
mainfrom
litellm_decisions_non_utf8_bytes_400
Oct 20, 2026
Merged

klu-berri merged 1 commit into
mainfrom
litellm_decisions_non_utf8_bytes_400

Conversation

@klu-berri

@klu-berri klu-berri commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

How it solves it:

  • _logged_request_message calls to_jsonable_python(..., bytes_mode="base64"), so bytes serialize losslessly
  • The request then reaches validation as before and gets the same BadRequestError (400)
  • No new helper, the existing pydantic_core.to_jsonable_python option does it

User Flow

Before: an SDK caller who passes raw bytes in a decisions field gets a Python crash instead of the 400 they got before v1.107.0-dev.3

  1. They call litellm.decisions(model="openai/gpt-6-luna", input=b"\xff\xfe not utf-8", questions=[{"type": "predicate", "instructions": "Is this about a billing problem?"}])
  2. The call raises UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0 with no status_code
  3. Their failure callback receives messages of default-message-value, so nothing about the request is logged

After: the same call fails with a 400 that names the invalid field, and the request is logged

  1. They call litellm.decisions(...) with the same bytes input
  2. The call raises litellm.BadRequestError (status_code=400) saying Invalid Decisions request: ... input.str Input should be a valid string
  3. Their failure callback receives messages carrying the full request, with the bytes as base64 ("input": "__4gbm90IHV0Zi04")

Relevant issues

Fixes a regression from #47183, which added the pre-validation request logging that raised on non-UTF-8 bytes

Affected release

regression since v1.107.0-dev.3 (the only tag that carries #47183, no rc or stable has it)

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Screenshots / Proof of Fix

Raw bytes cannot reach /v1/decisions or /v1/systemone through the proxy: the route parses the body with validate_json, which 400s invalid UTF-8 before any litellm code runs. The proxy run below shows that on both sides, and the SDK call is the surface where the finding reproduces, so the before/after is an SDK call with a failure callback printing the logged messages. Validation rejects bytes before any provider call, so neither leg reaches OpenAI. The valid request on the same rig did, to show the proxy and model are real.

Shared setup: python -m litellm.proxy.proxy_cli --config config.yaml --port <port> --num_workers 1 --detailed_debug with local Postgres, main at port 4000 and this branch at 4001

model_list:
  - model_name: luna
    litellm_params:
      model: openai/gpt-6-luna
      api_key: os.environ/OPENAI_API_KEY
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
# sdk_bytes.py
import litellm
from litellm.integrations.custom_logger import CustomLogger


class PrintLoggedMessages(CustomLogger):
    def log_failure_event(self, kwargs, response_obj, start_time, end_time):
        print("logged messages:", kwargs["messages"])


litellm.failure_callback = [PrintLoggedMessages()]
try:
    litellm.decisions(
        model="openai/gpt-6-luna",
        input=b"\xff\xfe not utf-8",
        questions=[{"type": "predicate", "instructions": "Is this about a billing problem?"}],
    )
except Exception as error:
    print("caller sees:", type(error).__name__, "status_code=", getattr(error, "status_code", None))
    print(str(error).splitlines()[0][:160])

Before (5145250)

SDK call with non-UTF-8 bytes in input

  1. python sdk_bytes.py
  2. Output
logged messages: [{'role': 'user', 'content': 'default-message-value'}]
caller sees: UnicodeDecodeError status_code= None
'utf-8' codec can't decode byte 0xff in position 0: invalid utf-8

Proxy: raw 0xFF 0xFE bytes inside the JSON body (unchanged by this PR)

  1. printf '{"model":"luna","input":"\xff\xfe not utf-8","questions":[{"type":"predicate","instructions":"Is this about a billing problem?"}]}' > bad_utf8_body.bin
  2. curl -s -w '\nHTTP %{http_code}\n' localhost:4000/v1/decisions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' --data-binary @bad_utf8_body.bin
  3. Output
{"error":{"message":"litellm.BadRequestError: Invalid Decisions request: 1 validation error for dict[str,any]\n  Invalid JSON: invalid unicode code point at line 1 column 27 [type=json_invalid, ...
HTTP 400

After (05a1ba3)

SDK call with non-UTF-8 bytes in input

  1. python sdk_bytes.py
  2. Output
logged messages: [{'role': 'user', 'content': '{"input": "__4gbm90IHV0Zi04", "questions": [{"type": "predicate", "instructions": "Is this about a billing problem?"}]}'}]
caller sees: BadRequestError status_code= 400
litellm.BadRequestError: Invalid Decisions request: 2 validation errors for OpenAIDecisionRequestBody

Proxy: raw 0xFF 0xFE bytes inside the JSON body (unchanged by this PR)

  1. same curl against localhost:4001/v1/decisions
  2. Output
{"error":{"message":"litellm.BadRequestError: Invalid Decisions request: 1 validation error for dict[str,any]\n  Invalid JSON: invalid unicode code point at line 1 column 27 [type=json_invalid, ...
HTTP 400

Proxy: valid request on the same rig (real OpenAI call)

  1. curl -s -w '\nHTTP %{http_code}\n' localhost:4001/v1/decisions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"luna","input":"My card was charged twice.","questions":[{"type":"predicate","instructions":"Is this about a billing problem?"}]}'
  2. Output
{"model":"gpt-6-luna","answers":[{"type":"predicate","name":null,"probability":1.0}],"usage":{"input_tokens":161,"input_tokens_details":{"cached_tokens":0,"cache_write_tokens":0},"output_tokens":0,"output_tokens_details":{"reasoning_tokens":0},"total_tokens":161}}
HTTP 200

Regression test tests/unit/decisions/test_call.py::test_non_utf8_bytes_in_the_request_are_logged_and_rejected_with_a_400 on main (5145250) with only the test applied:

E       UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid utf-8
litellm/decisions/call.py:430: UnicodeDecodeError
1 failed, 4 deselected in 0.52s

Type

🐛 Bug Fix

Caveats (if any)

Low

  • bytes_mode="base64" is pydantic's URL-safe alphabet (-_), not the +/ the data_base64 fields take
  • Valid UTF-8 bytes now log as base64 too, where before they logged as the decoded text (validation 400s both)

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Link to Devin session: https://app.devin.ai/sessions/8458846cc699483291f33927c4e4f383
Open in Devin Desktop: https://app.devin.ai/desktop/session/8458846cc699483291f33927c4e4f383?variant=devin
Requested by: @kerrylu-berri


Note

Low Risk
Narrow change to decisions pre-validation logging serialization; behavior for invalid byte input improves (400 instead of crash) with a small logging format shift for all byte fields.

Overview
Fixes a decisions SDK regression where pre-validation request logging crashed on bytes fields that are not valid UTF-8, instead of letting validation return a 400.

_logged_request_message now serializes caller fields with to_jsonable_python(..., bytes_mode="base64"), so non-UTF-8 input (and other byte values) are logged losslessly as URL-safe base64 and the call still fails with litellm.BadRequestError as before. A unit test asserts the logged payload round-trips the raw bytes and that validation still rejects the request.

Reviewed by Cursor Bugbot for commit 05a1ba3. Bugbot is set up for automated code reviews on this repo. Configure here.

@devin-ai-integration

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@codspeed

codspeed Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing litellm_decisions_non_utf8_bytes_400 (05a1ba3) with main (5145250)

Open in CodSpeed

@codecov

codecov Bot commented Oct 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@klu-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

kerry-berri commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

litellm-stampbot: risk low

Approved at 05a1ba3.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Cursor Bugbot: Low Risk at 05a1ba3. Narrow change to decisions pre-validation logging serialization; behavior for invalid byte input improves (400 instead of crash) with a small logging format shift for all byte fields. Bugbot run requested, finished in 3 min.
Bugbot Low is low, Medium and High are high. The judge model was not called.

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 05a1ba3. Configure here.

@kerry-berri kerry-berri added the risk:low Small, isolated, low-risk change label Oct 20, 2026

@kerry-berri kerry-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Low risk by rule and by judgement at 05a1ba3

@klu-berri
klu-berri merged commit ce63f48 into main Oct 20, 2026
90 of 91 checks passed
@klu-berri
klu-berri deleted the litellm_decisions_non_utf8_bytes_400 branch October 20, 2026 15:22
Cartofante pushed a commit to CartoDB/litellm that referenced this pull request Oct 26, 2026
…validation and gets a 400 (BerriAI#47564)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>

Backport of BerriAI#47564 to stable/1.106.x
Cherry-picked from ce63f48 (main)
yuneng-berri pushed a commit that referenced this pull request Oct 28, 2026
…validation and gets a 400 (#47564)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit ce63f48)
haowang1013 pushed a commit to directivegames/litellm that referenced this pull request Nov 3, 2026
…validation and gets a 400 (BerriAI#47564)

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>

Backport of BerriAI#47564 to stable/1.105.x.
Cherry-picked from ce63f48 (main).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Small, isolated, low-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants