Skip to content

feat: opt-in message privacy for diagnostic logs - #48882

Closed
moe-berri wants to merge 9 commits into
mainfrom
litellm_debug_message_privacy
Closed

moe-berri wants to merge 9 commits into
mainfrom
litellm_debug_message_privacy

Conversation

@moe-berri

@moe-berri moe-berri commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Operators can enable detailed diagnostics while keeping prompts, replies, and exception text out of LiteLLM-owned diagnostics. The new setting is off by default and leaves provider requests, client responses, and the existing logging-integration setting unchanged

Details

TLDR

Problem this solves:

  • Detailed diagnostics can expose request and response content

How it solves it:

  • Opt-in suppression at built-in diagnostic output boundaries
  • Skip expensive payload formatting on hot logging paths
  • Keep numeric request, retry, fallback, and timing events

Intentional product change: opting in removes free-form diagnostic text, model names, base URLs, raw exceptions, correlation identifiers, and custom extras; selected operational events remain available

User Flow

Before: detailed logging exposes content even with logging-integration message suppression enabled

  1. The operator enables detailed logging and disables logging-integration message content
  2. The client sends a prompt to POST https://example.com/v1/chat/completions (also POST https://example.com/v1/responses and POST https://example.com/v1/messages)
  3. The client receives HTTP 200 with the response, while diagnostic logs include its content

After: the operator can keep detailed logging without content in built-in diagnostics

  1. The operator also enables redact_messages_in_debug_logs: true and restarts the proxy
  2. The client sends the same prompt to POST https://example.com/v1/chat/completions (also POST https://example.com/v1/responses and POST https://example.com/v1/messages)
  3. The client receives HTTP 200 with the response, while diagnostics show a redaction marker and selected operational events

Relevant issues

Fixes #42896

Pre-Submission checklist

  • I have added meaningful tests
  • The mapped local suites have known baseline failures; comparisons are recorded below
  • My PR passes all required CI/CD checks
  • My PR's scope is as isolated as possible; it only solves one specific problem
  • Every automated review on the latest commit has finished and findings are addressed

Validation

Current tip 98cbd9af71ef0a23c4d643609d6294297d65f773 fixes Bugbot's DeepEval retry finding. The original exception chooses the diagnostic branch; only the logged text is redacted. Missing and null exceptions continue to produce the ordinary retry message with privacy enabled. The two regression cases failed before the fix. pytest tests/unit/integrations/test_deepeval.py -q --tb=short now reports 8 passed, covering missing, null and real exceptions with privacy off and on. Full make check passes

The earlier c3ed358c merge includes main 60601ca9950 and preserves both sets of tests from the request-processing conflict. Its config-warning fix passed 924 tests with two skipped after two before-fix failures. The current branch also merges cleanly with main 89ca8d83f89, verified locally after push

Greptile's updated review gives 5/5 to c3ed358c. Both Bugbot follow-up findings are fixed and their threads resolved. CI and bot results for the current tip are pending. The prior Codecov result at 9cc438c was 91.84% against the 89.25% target

The upstream OpenTelemetry test fix #49129 is included. The previous Rust beta-header failure reproduced on clean main and remains outside this PR's scope. The additional real-database retry probe was inconclusive because the pre-fix checkout's Prisma engine connection failed before exercising the regression. Its disposable databases were stopped and removed. No new live-database or provider proof is claimed for these follow-ups

Screenshots / Proof of Fix

E2E exception at 98cbd9af71ef0a23c4d643609d6294297d65f773: the latest follow-up restores the existing DeepEval diagnostic branch without changing requests, responses or retries. There are no internal callers of this helper. The focused tests exercise the real logger across all three exception cases with privacy off and on: two failures before the fix, eight passes after. Full make check passes

The live-provider proof below was recorded at 9cc438c. Subsequent main merges, the config-warning retry fix and the DeepEval diagnostic fix are validated separately above. These historical results are not presented as a live run of the current tip

Both legs use two proxy workers, the same 241 installed package versions and locked Python dependencies and real chatgpt/gpt-6.1-sol calls. This uses an explicitly authorized existing subscription, with no token refresh or auth-file writes. Chat Completions and Messages exercise bridges; this is not native Anthropic or metered OpenAI API proof

Shared setup uses environment credentials, turn_off_message_logging: true, redact_messages_in_debug_logs: true, and --detailed_debug --num_workers 2. $PORT identifies the isolated leg and $QA_MASTER_KEY its temporary master key. Each payload asks for a synthetic marker. No real user content is used

Case Before After
Three APIs, nonstream + stream 200, content intact, marker logged 200, content intact, marker absent
Tool arguments on all three APIs 200, argument intact, marker logged 200, argument intact, marker absent
Request-debug WARNING, JSON and legacy stdout 200, marker logged 200, marker absent
Unsupported-model provider error 400, marker in response and logs 400, marker in response only
Failed deployment with real fallback 200 after provider error, marker logged 200 after provider error, marker absent
Shared configuration, response projection and exact headline request payloads

project_headline.py

import argparse
import json
from pathlib import Path
p=argparse.ArgumentParser();p.add_argument('response');a=p.parse_args()
d=json.loads(Path(a.response).read_text())
if 'choices' in d:text=d['choices'][0].get('message',{}).get('content')
elif 'output' in d:text=''.join(c.get('text','') for item in d['output'] for c in item.get('content',[]))
else:text=''.join(c.get('text','') for c in d.get('content',[]))
usage={k:v for k,v in d.get('usage',{}).items() if k in ('input_tokens','output_tokens','prompt_tokens','completion_tokens','total_tokens')}
print(json.dumps({'text':text,'usage':usage},indent=2))
model_list:
  - model_name: qa-model
    litellm_params:
      model: chatgpt/gpt-6.1-sol
      api_key: os.environ/QA_CHATGPT_ACCESS_TOKEN
litellm_settings:
  turn_off_message_logging: true
  redact_messages_in_debug_logs: true
  json_logs: false
  telemetry: false

Set LITELLM_MASTER_KEY to the temporary key used by the curl header, then start the isolated proxy with the configuration above. The access token is supplied through QA_CHATGPT_ACCESS_TOKEN in the process environment

python litellm/proxy/proxy_cli.py --config config.yaml --host 127.0.0.1 --port "$PORT" --num_workers 2 --detailed_debug

chat_completions_False_0.request.json

{
  "model": "qa-model",
  "stream": false,
  "messages": [
    {
      "role": "user",
      "content": "Reply with exactly this text and no other words: SYNTHETIC_PRIVATE_42896_chat_False_0"
    }
  ]
}

responses_False_0.request.json

{
  "model": "qa-model",
  "stream": false,
  "input": "Reply with exactly this text and no other words: SYNTHETIC_PRIVATE_42896_responses_False_0"
}

messages_False_0.request.json

{
  "model": "qa-model",
  "stream": false,
  "messages": [
    {
      "role": "user",
      "content": "Reply with exactly this text and no other words: SYNTHETIC_PRIVATE_42896_messages_False_0"
    }
  ],
  "max_tokens": 128000
}

The displayed response projections use python3 project_headline.py RESPONSE_FILE, which selects only returned text and core input/output token counts. They exclude response IDs and usage attribution objects

The operator checks the complete captured log with:

grep -c 'SYNTHETIC_PRIVATE_42896_chat_False_0' proxy.log

Before (83d6779)

Chat Completions

  1. Send the captured synthetic payload using curl
printf 'header = "Authorization: Bearer %s"\nheader = "Content-Type: application/json"\n' "$QA_MASTER_KEY" |
  curl --silent --show-error --request POST --config - \
  --data-binary @chat_completions_False_0.request.json \
  --write-out '\nQA_STATUS:%{http_code}\n' \
  "http://127.0.0.1:$PORT/v1/chat/completions"
  1. Observe HTTP200 and the returned text (response projected to text and usage below). The operator's complete captured logs contain the marker (grep -c returns 10 for the Chat Completions marker)
{
  "text": "SYNTHETIC_PRIVATE_42896_chat_False_0",
  "usage": {
    "completion_tokens": 18,
    "prompt_tokens": 1653,
    "total_tokens": 1671
  }
}

Responses

  1. Run the same curl command with @responses_False_0.request.json and /v1/responses
  2. Observe HTTP200 and the returned text; logs contain the marker
{
  "text": "SYNTHETIC_PRIVATE_42896_responses_False_0",
  "usage": {
    "input_tokens": 1654,
    "output_tokens": 19,
    "total_tokens": 1673
  }
}

Messages

  1. Run the same curl command with @messages_False_0.request.json and /v1/messages. The required output limit uses the model's documented native maximum
  2. Observe HTTP200 and the returned text; logs contain the marker
{
  "text": "SYNTHETIC_PRIVATE_42896_messages_False_0",
  "usage": {
    "input_tokens": 245,
    "output_tokens": 18
  }
}

After (9cc438c)

Chat Completions

  1. Repeat the same payload and curl command against the after proxy
  2. Observe HTTP200 with the original returned text. The complete logs contain no marker (grep -c returns 0 for the Chat Completions marker)
{
  "text": "SYNTHETIC_PRIVATE_42896_chat_False_0",
  "usage": {
    "completion_tokens": 18,
    "prompt_tokens": 1653,
    "total_tokens": 1671
  }
}

Responses

  1. Repeat the same Responses payload and curl command
  2. Observe HTTP200 with the original returned text, with no marker in logs
{
  "text": "SYNTHETIC_PRIVATE_42896_responses_False_0",
  "usage": {
    "input_tokens": 1654,
    "output_tokens": 19,
    "total_tokens": 1673
  }
}

Messages

  1. Repeat the same Messages payload and curl command
  2. Observe HTTP200 with the original returned text, with no marker in logs
{
  "text": "SYNTHETIC_PRIVATE_42896_messages_False_0",
  "usage": {
    "input_tokens": 245,
    "output_tokens": 18
  }
}
Extended API cases and observed results
Case Before HTTP / log occurrences After HTTP / log occurrences
core/chat_completions_False_0 200 / 10 200 / 0
core/chat_completions_True_0 200 / 13 200 / 0
core/responses_False_0 200 / 8 200 / 0
core/responses_True_0 200 / 7 200 / 0
core/messages_False_0 200 / 11 200 / 0
core/messages_True_0 200 / 15 200 / 0
extended/tool_chat 200 / 28 200 / 0
extended/tool_responses 200 / 16 200 / 0
extended/tool_messages 200 / 33 200 / 0
extended/request_debug 200 / 15 200 / 0
extended/provider_error 400 / 43 400 / 0
extended/fallback 200 / 23 200 / 0
curl/chat_completions_False_0 200 / 10 200 / 0
curl/responses_False_0 200 / 8 200 / 0
curl/messages_False_0 200 / 11 200 / 0

These cases use the actual stdlib HTTP runner rather than claim additional curl runs. The runner only sends HTTP and observes client responses and the operator's logs; it does not substitute provider responses

  1. Stream each API and join text deltas. Before returns the marker and logs it; After returns the same marker without logging it
  2. Define record_marker, put a marker in its description, and require the model to call it with that marker. All three APIs return the exact argument Before and After; only Before logs the marker
  3. Send litellm_request_debug: true with JSON logging and legacy verbose enabled. Before and After return200; only Before logs the prompt
  4. Call a configured deployment whose unsupported upstream model contains the synthetic error marker. Before and After return400 invalid_request_error with the marker in the client error; only Before logs it
  5. Configure that failed deployment to fall back to the real model. Both legs fall back after the provider rejects the first deployment and return200; only Before logs the prompt

With two workers, startup-only INFO on current main logs qa-model twice with either flag value. The updated PR logs it twice with privacy off and zero times with privacy on. Startup probes make no provider requests. The real provider400 failure logs at ERROR. All temporary proxies stopped

The after log retains these observed operational fields (projected from its safe diagnostic messages):

event=response_ready status=200 elapsed_seconds=1.9625910410031793
event=request_failed status=400
event=fallback attempt=1

Actual extended runner commands, with the authorized credential supplied only in the process environment:

python3 live_probe.py --tree "$BASE_TREE" --revision 83d67791584fde196c3fbd8258df9e248fcb2e96 --name refresh-base-extended --redact --extended --json-logs --legacy-verbose
python3 live_probe.py --tree "$HEAD_TREE" --revision 9cc438c228c1fb8d03dbee107b0ad2e53684296e --name final-head-extended --redact --extended --json-logs --legacy-verbose

All 15 paired request bodies are identical. The actual returned tool calls and parsed arguments match on all three APIs. Complete opt-in logs have zero synthetic markers, configured model names, formatter errors or tracebacks

DB-only configuration regression, previous PR versus final tip

This additional regression compares the previous PR at 56372ea04f955ad8f2caf602bc2f9a636395c76c with 9cc438c228c1fb8d03dbee107b0ad2e53684296e. Both boot two workers against the same disposable PostgreSQL16 database and call the real provider on all three API routes

The saved litellm_settings contains redact_messages_in_debug_logs: true and model_alias_map: {SYNTHETIC_PRIVATE_DB_ALIAS_42896: qa-model}. A saved general_settings.custom_auth contains the deliberately rejected synthetic value s3://example-bucket/SYNTHETIC_PRIVATE_DB_CONFIG.py. YAML omits the privacy flag and enables store_model_in_db. The database URL is supplied only through the environment

  1. Start each frozen proxy with --detailed_debug --num_workers 2
  2. Run the shared literal curl requests for Chat Completions, Responses and Messages. All six requests return HTTP200. Each before/after pair has identical returned text and token counts
  3. Inspect each complete operator log after shutdown
grep -c 'SYNTHETIC_PRIVATE_DB_ALIAS_42896' proxy.log
grep -c 'SYNTHETIC_PRIVATE_DB_CONFIG.py' proxy.log

Previous PR output

2
2

Final tip output

0
0

The previous PR exposes the alias key in a DEBUG config row and the rejected path in a WARNING before applying DB-only privacy. The final tip omits both. The rejected remote auth value remains rejected, and requests still succeed. Both final log marker counts are zero, with no formatter errors or tracebacks

The disposable database was stopped and removed after verification. No persistent service was used

Functional and performance comparisons

A fresh component ABBA comparison at base 83d67791584 and pre-follow-up head 56372ea04f9, with 241 identical package versions and 20 samples per payload size, measures default-off INFO overhead of 24–32 ns per provider diagnostic helper call and an unchanged 64-byte temporary peak. At 8 MiB, opt-in DEBUG formatting falls from 26.81 ms to 0.037 ms and 25.17 MB to 8.5 KB temporary allocation. These are component measurements, not HTTP latency or total RSS. The final follow-up adds configuration-only diagnostic deferral and skips a streaming diagnostic

Performance measurements below are from 8d9bd9045a3d9fa13492fcd000266344add13fb0; live functional proof above was repeated on 9cc438c228c1fb8d03dbee107b0ad2e53684296e.

Measurement Baseline → head
Fixed-seed INFO/opt-out, 1 KiB nonstream p50/p95 3.11/6.32 → 3.05/3.91 ms
Fixed-seed INFO/opt-out, 1 MiB nonstream p50/p95 5.77/7.09 → 6.03/7.26 ms
Fixed-seed INFO/opt-out, 1 MiB stream p50/p95 11.77/13.02 → 11.94/13.21 ms
DEBUG opt-in, 1 MiB nonstream/stream p50 42.2/51.8 → 8.6/16.2 ms
Disabled diagnostic helper, CPU/temporary peak 89 → 116 ns; 64 → 64 bytes
Opt-in DEBUG provider helper, 8 MiB CPU/temporary peak 23.8 → 0.04 ms; 25.2 MB → 8.5 KB

Synthetic HTTP: 24/24 response-semantic comparisons match; 16/16 canceled streams disconnect upstream within 70–75 ms. INFO opt-out log bytes match. ABBA uses two workers and 100 warm requests/case for the focused repeat. First-use 1 KiB nonstream ranges: baseline 96–98 ms, head 76–95 ms.

Initial random-seed runs showed 7–13% higher head medians on several INFO cases. Fixed-seed 1 MiB nonstream retained +4.5% and +0.20 ms CPU/request; identical-baseline control itself showed +3.6% and +0.20 ms. Profiling found constant microsecond guards, no added payload-scaled work. No attributable payload-scaled regression was found; zero overhead is not claimed. Process-tree RSS varied substantially across identical boots (roughly 1.6–2.1 GiB); these samples cannot establish zero RSS overhead.

Synthetic upstream HTTP measurements are separate from real-provider proof. They hold response content constant and compare first/warm p50/p95 latency, streaming delay, response semantics, cancellation propagation and process RSS. Diagnostic component measurements use the real logger/filter stack and compare CPU time and temporary allocations. No provider-latency speedup or universal zero-overhead guarantee is inferred

## Type

🆕 New Feature

Caveats

Severe

  • Opt-in sacrifices free-form diagnostics, exceptions, and caller-supplied identifiers
  • Custom formatters requiring extras must supply defaults before enabling

Medium

  • Custom application loggers and third-party wire logs need separate controls
  • Standalone Rust gateway is outside this Python setting
  • Live coverage uses one provider; other adapters were source-audited

Low

  • Logging integrations still require turn_off_message_logging
  • Restart after changing the setting

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

Note

Medium Risk
Broad changes to logging filters and proxy config load ordering affect observability and startup diagnostics, but default-off behavior and extensive tests limit production impact.

Overview
Adds litellm_settings.redact_messages_in_debug_logs (default false) so operators can run --detailed_debug without prompts, replies, or exception text appearing in LiteLLM-owned diagnostics. README documents pairing it with existing turn_off_message_logging for logging integrations.

Central logging (_logging.py) wires MessageContentFilter and _redact_diagnostic_record through secret/access/JSON formatters, startup output, and excepthooks: LiteLLM-scoped records become redacted-by-litellm, strip **exc_info/extras, and skip correlation IDs. log_safe_diagnostic emits structured events (request_sent, response_ready, retry, fallback, etc.) when privacy is on. The Rust bridge logger treats privacy mode as “diagnostics disabled” for native emits.

Hot paths skip formatting payloads when enabled: proxy skips DEBUG request payload dumps; litellm_logging short-circuits curl/RAW response debug and redacts optional stdout payload printing; router/proxy stream handlers log safe events instead of chunks. Dozens of print_verbose / legacy stdout call sites gate on the flag; several integration loggers attach MessageContentFilter.

Proxy config applies the flag from YAML/DB at runtime, redacts worker config for startup logs when privacy is on, and defers DB config DEBUG/WARNING lines until after privacy is resolved so DB overlay content is not logged before redaction applies.

Tests cover privacy on/off across streaming, proxy, config load, integrations, and MCP iterators while asserting client/provider behavior and in-memory data stay unchanged.

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

@moe-berri
moe-berri marked this pull request as ready for review October 28, 2026 19:36
@codspeed

codspeed Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 38 untouched benchmarks
🆕 4 new benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
🆕 test_pdf_page_of_drawing_operators_and_no_image N/A 23.3 ms N/A
🆕 test_pdf_page_of_forms_sharing_one_resources_dictionary N/A 19.7 ms N/A
🆕 test_pdf_page_of_parent_forms_sharing_one_child_form N/A 305.8 ms N/A
🆕 test_token_counter_long_unknown_model_name N/A 2.2 ms N/A

Comparing litellm_debug_message_privacy (98cbd9a) with main (24afa12)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (53ce416) during the generation of this report, so 24afa12 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@moe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@moe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@greptile-apps

greptile-apps Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with no new actionable issues found

Summary

Adds opt-in redact_messages_in_debug_logs for built-in Python diagnostics while keeping provider requests, client responses, and logging-integration controls separate

Database diagnostics wait until privacy settings are resolved. Shadow warnings remain available after a failed configuration load

No new actionable issues were found. The earlier startup-output and database-setting findings are addressed in the current code. Historical live-provider results are clearly labeled with their tested commit

  • LiteLLM can hide free-form content in its built-in diagnostic logs.
  • Request, provider, cache, and stream diagnostics honor the privacy setting.
  • Proxy configuration applies diagnostic privacy before it writes configuration details.

Reviews (5) · Last reviewed commit: "fix(logging): preserve deferred config w..." · Reviewed by Greptile

Comment thread litellm/_logging.py Resolved

@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.

Stale Bugbot comment from a previous run.

@moe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@moe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

Comment thread README.md Resolved

@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.

Stale Bugbot comment from a previous run.

@moe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@moe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

Comment thread litellm/proxy/proxy_server.py Resolved

@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.

Stale Bugbot comment from a previous run.

Comment thread litellm/main.py Resolved
@moe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@moe-berri

Copy link
Copy Markdown
Contributor Author

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.

Stale Bugbot comment from a previous run.

Comment thread litellm/proxy/proxy_server.py Resolved
Merge current main and retain both sets of request-processing tests
Emit shadow warnings after runtime validation so retries do not lose them
@moe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@moe-berri

Copy link
Copy Markdown
Contributor Author

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.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit c3ed358. Configure here.

Comment thread litellm/integrations/deepeval/api.py Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Option to keep message content out of debug logs while debug logging is enabled

2 participants