mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-29 01:03:17 +00:00
* feat(model-catalog): add Rust registry validation (#43136) * doc * feat(model-catalog): add Rust registry validation * test(model-catalog): ignore integration tests * docs(model-catalog): fix validation note grammar --------- Co-authored-by: Yujong Lee <yujong@berri.ai> (cherry picked from commitc289d5d6fb) * test(rust): reorganize core crate tests and split cache and OCR suites (#43177) * test(rust): group cache tests under cache/ and fold test_ocr.py into ocr/ The two failure cases in test_ocr.py duplicated the upstream-500 and timeout rows of PUBLIC_FAILURES, so only the file-input encoding case moves to ocr/test_requests.py Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(rust): split the response cache suite into one file per backend test_response_cache.py grew to 2400 lines. Each backend now has its own file, shared fixtures live in cache/conftest.py and shared helpers in support/cache.py. The helpers alias the private native test handles once, dropping the per-call reportPrivateUsage hits Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * split tokenizer test * test(core): consolidate route integration tests under tests/ with rstest and wiremock Moves the public-API OCR route tests out of src/ocr/route.rs and document.rs into tests/ocr/, split per provider plus lifecycle, machine, and document tests, merging the duplicated pairs. Messages, audio transcription, and chat completions share one wiremock-based upstream and recording secret source in tests/support, and gain table-driven cases for auth, routing, upstream errors, streaming, and declines. Tests of litellm-llms items move to that crate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(messages): keep the stream relay test independent of the stream head contents The stream head carries no headers on main, so the relay test asserts the open-then-deliver order and the relayed body instead of header hand-off. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit10413796c6) * feat(rust): hand upstream response headers to the native Messages stream (#43178) * ci: drop the ocr_testing job now that tests/ocr_tests is gone Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(ocr): restore the live OCR matrix and the ocr_testing job The public litellm.ocr / aocr / Router interface is unchanged by the Rust migration, so the live provider matrix still applies. Drops the stale VCR skip list for the deleted test_rust_bridge.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(messages): show streamed upstream headers never reach the native stream The Python handler puts the upstream response headers on the stream's _hidden_params before the first chunk so the proxy can forward them as llm_provider-* headers. The native route drops them, and this test fails on the Rust path while passing on Python. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(messages): hand upstream response headers to the native stream before its first chunk The Messages route fills MessagesStreamHead from the upstream response and yields it on Open. The Python driver converts it through the protocol host and hands it to Stream and SyncStream as their _hidden_params, so a streamed native call carries additional_headers the same way the Python handler does and the proxy can forward them as llm_provider-* headers. The relay contract lives in the core crate test, the hand-off in the host-python driver test, and the header projection in the route host test, so the recording-server test that showed the gap is dropped. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * wip --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit081f73f021) * feat(testkit): agent clients for Claude Code, Codex and opencode (#43181) * feat(testkit): install and configure Claude Code, Codex and opencode against a gateway Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * refactor(testkit): derive targets from target-lexicon and split agents behind a trait Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * refactor(testkit): group sources into agent and install folders Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(testkit): split agents into install, configure and drive with semver-aware launch Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * style(testkit): drop a needless borrow Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> (cherry picked from commit9c10e0f985) * ci: run migrated unit selections on every event in legacy GHA shards (#43182) * ci: run the unit_selection.sh shard files on every event instead of only fork pull requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: rename fork-flag to unit-flag now that it applies on every event --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit694783ebbe) * test: move tests/test_litellm root and small trees into tests/unit (#43186) * ci: run the unit_selection.sh shard files on every event instead of only fork pull requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: rename fork-flag to unit-flag now that it applies on every event * test: move tests/test_litellm root and small trees into tests/unit Pure renames, no content changes. Follow-up commits in this PR fix references, merge the three files that already existed in tests/unit, keep live-provider tests in tests/test_litellm and wire CI. * test: carry tests/test_litellm conftest isolation into tests/unit Callback lists, routing fallbacks, cached HTTP clients, logger state, AWS, proxy-URL and keychain env, and session-end client cleanup now reset for unit tests too. The environment isolation owns its MonkeyPatch so a test's own monkeypatch is undone before the model-cost teardown runs. * test: merge, split and prune the moved root and small-tree tests Merge batches/test_batch_utils.py and the chat_completions and messages dispatch tests into the files that already existed in tests/unit. Keep the live Gemini interactions tests, the async image-fetch format test and the OpenAI embedding scorer test in tests/test_litellm since they need real network or keys. Put test_router.py under tests/unit/test_router so the existing package no longer shadows it. Delete eight tests the audit found superseded by stronger ones kept in this move. * ci: run the moved root and small-tree tests under their legacy flags Add the misc and responses-caching-types flags to unit_selection.sh and CircleCI, extend enterprise-routing and mcp-integration, and point the legacy GHA shards, Makefile, redis-compat workflow, merge smoke manifest and change classifier at the new paths. * test: make the new tests/unit directories packages tests/unit/test_package_layout.py requires every directory to carry an __init__.py, and without one the moved and retained test_litellm_responses_bridge.py modules collide on import. * test: scope the unit socket block to tests/unit in shared sessions The GHA shards collect the legacy test-path and the unit selection in one pytest session. The unit conftest's loopback-only block leaked into legacy modules that reach the network at import. The legacy conftest now lifts the restriction at collect and setup time, and the unit conftest re-applies it when collecting its own modules. * test: give the shard-script tests their own GITHUB_OUTPUT They only passed where the runner set it. The CircleCI unit job's env allowlist drops it, so the script's redirect failed there. * test: point the router and module-deletion checks at tests/unit router_code_coverage and code_qa_check_tests only searched tests/test_litellm, so the moved router tests no longer counted. The two silent-experiment tests the audit deleted were the only direct callers of those methods; they are replaced with tests that assert the forwarded shadow request and the recursion guard. --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commitf6882246d4) * refactor(framer): replace Framer trait with tokio-util codecs (#43193) * refactor(framer): replace Framer trait with tokio-util codecs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(framer): port SSE and AWS event stream framing to codecs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(rust): drop clone on Copy capabilities in messages request test Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(rust): use field init shorthand in messages request test Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit3c93ea1697) * test: move tests/test_litellm/llms into tests/unit/llms (#43191) * ci: run the unit_selection.sh shard files on every event instead of only fork pull requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: rename fork-flag to unit-flag now that it applies on every event * test: move tests/test_litellm root and small trees into tests/unit Pure renames, no content changes. Follow-up commits in this PR fix references, merge the three files that already existed in tests/unit, keep live-provider tests in tests/test_litellm and wire CI. * test: carry tests/test_litellm conftest isolation into tests/unit Callback lists, routing fallbacks, cached HTTP clients, logger state, AWS, proxy-URL and keychain env, and session-end client cleanup now reset for unit tests too. The environment isolation owns its MonkeyPatch so a test's own monkeypatch is undone before the model-cost teardown runs. * test: merge, split and prune the moved root and small-tree tests Merge batches/test_batch_utils.py and the chat_completions and messages dispatch tests into the files that already existed in tests/unit. Keep the live Gemini interactions tests, the async image-fetch format test and the OpenAI embedding scorer test in tests/test_litellm since they need real network or keys. Put test_router.py under tests/unit/test_router so the existing package no longer shadows it. Delete eight tests the audit found superseded by stronger ones kept in this move. * ci: run the moved root and small-tree tests under their legacy flags Add the misc and responses-caching-types flags to unit_selection.sh and CircleCI, extend enterprise-routing and mcp-integration, and point the legacy GHA shards, Makefile, redis-compat workflow, merge smoke manifest and change classifier at the new paths. * test: make the new tests/unit directories packages tests/unit/test_package_layout.py requires every directory to carry an __init__.py, and without one the moved and retained test_litellm_responses_bridge.py modules collide on import. * test: scope the unit socket block to tests/unit in shared sessions The GHA shards collect the legacy test-path and the unit selection in one pytest session. The unit conftest's loopback-only block leaked into legacy modules that reach the network at import. The legacy conftest now lifts the restriction at collect and setup time, and the unit conftest re-applies it when collecting its own modules. * test: move tests/test_litellm/llms into tests/unit/llms Rename-only. Moves the provider tests and the fine-tuning fixtures they load, mirroring the old paths. Follow-up commits merge, split and wire them. * test: merge, split and prune the moved llms tests Merges the Databricks chat transformation tests into the existing unit file, keeps the tests that need real keys or the network in tests/test_litellm, deletes the audited tests a stronger unit test already covers, and points imports at tests.unit.llms. * ci: run the moved llms tests under their legacy flags The Vertex AI and All Other Providers shards keep their legacy test-path for the retained files and add the llm-vertex-ai and llm-other-providers unit selections. CircleCI gets matching unit jobs. * test: make the tests/unit/llms directories packages Adds __init__.py to the moved dirs and drops the legacy ones whose directories no longer hold tests. * test: drop script runners and path hacks the llms split left dangling The __main__ runners in the split openai_like files and the Databricks e2e runner called tests that now live in the other half of the split or were deleted. The retained legacy halves also no longer need sys.path edits. * test: give the shard-script tests their own GITHUB_OUTPUT They only passed where the runner set it. The CircleCI unit job's env allowlist drops it, so the script's redirect failed there. * test: point the router and module-deletion checks at tests/unit router_code_coverage and code_qa_check_tests only searched tests/test_litellm, so the moved router tests no longer counted. The two silent-experiment tests the audit deleted were the only direct callers of those methods; they are replaced with tests that assert the forwarded shadow request and the recursion guard. * test: keep the Databricks manual e2e runner and fix the SageMaker Nova run path The Databricks e2e file is a manual script whose main() calls the tests that were pruned, so pruning them broke the documented run. It is back to its main version. The SageMaker Nova docstring now points at the file's real location in tests/local_testing. * test: keep the job's UNIT_FLAG out of the shard-script tests --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit5e6dc89ba1) * test: move tests/test_litellm integrations and secret_managers into tests/unit (#43194) * ci: run the unit_selection.sh shard files on every event instead of only fork pull requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: rename fork-flag to unit-flag now that it applies on every event * test: move tests/test_litellm root and small trees into tests/unit Pure renames, no content changes. Follow-up commits in this PR fix references, merge the three files that already existed in tests/unit, keep live-provider tests in tests/test_litellm and wire CI. * test: carry tests/test_litellm conftest isolation into tests/unit Callback lists, routing fallbacks, cached HTTP clients, logger state, AWS, proxy-URL and keychain env, and session-end client cleanup now reset for unit tests too. The environment isolation owns its MonkeyPatch so a test's own monkeypatch is undone before the model-cost teardown runs. * test: merge, split and prune the moved root and small-tree tests Merge batches/test_batch_utils.py and the chat_completions and messages dispatch tests into the files that already existed in tests/unit. Keep the live Gemini interactions tests, the async image-fetch format test and the OpenAI embedding scorer test in tests/test_litellm since they need real network or keys. Put test_router.py under tests/unit/test_router so the existing package no longer shadows it. Delete eight tests the audit found superseded by stronger ones kept in this move. * ci: run the moved root and small-tree tests under their legacy flags Add the misc and responses-caching-types flags to unit_selection.sh and CircleCI, extend enterprise-routing and mcp-integration, and point the legacy GHA shards, Makefile, redis-compat workflow, merge smoke manifest and change classifier at the new paths. * test: make the new tests/unit directories packages tests/unit/test_package_layout.py requires every directory to carry an __init__.py, and without one the moved and retained test_litellm_responses_bridge.py modules collide on import. * test: scope the unit socket block to tests/unit in shared sessions The GHA shards collect the legacy test-path and the unit selection in one pytest session. The unit conftest's loopback-only block leaked into legacy modules that reach the network at import. The legacy conftest now lifts the restriction at collect and setup time, and the unit conftest re-applies it when collecting its own modules. * test: move tests/test_litellm/llms into tests/unit/llms Rename-only. Moves the provider tests and the fine-tuning fixtures they load, mirroring the old paths. Follow-up commits merge, split and wire them. * test: merge, split and prune the moved llms tests Merges the Databricks chat transformation tests into the existing unit file, keeps the tests that need real keys or the network in tests/test_litellm, deletes the audited tests a stronger unit test already covers, and points imports at tests.unit.llms. * ci: run the moved llms tests under their legacy flags The Vertex AI and All Other Providers shards keep their legacy test-path for the retained files and add the llm-vertex-ai and llm-other-providers unit selections. CircleCI gets matching unit jobs. * test: make the tests/unit/llms directories packages Adds __init__.py to the moved dirs and drops the legacy ones whose directories no longer hold tests. * test: drop script runners and path hacks the llms split left dangling The __main__ runners in the split openai_like files and the Databricks e2e runner called tests that now live in the other half of the split or were deleted. The retained legacy halves also no longer need sys.path edits. * test: give the shard-script tests their own GITHUB_OUTPUT They only passed where the runner set it. The CircleCI unit job's env allowlist drops it, so the script's redirect failed there. * test: point the router and module-deletion checks at tests/unit router_code_coverage and code_qa_check_tests only searched tests/test_litellm, so the moved router tests no longer counted. The two silent-experiment tests the audit deleted were the only direct callers of those methods; they are replaced with tests that assert the forwarded shadow request and the recursion guard. * test: move tests/test_litellm integrations and secret_managers into tests/unit Rename-only. Mirrors the old paths, including the directory conftests and the prompt and JSON fixtures. Follow-up commits prune and wire them. * test: prune and repoint the moved integrations tests Deletes the 7 audited tests a stronger test in the same tree already covers, imports the TLS sink helpers from their new conftest path, and restores os.environ after each integrations test. Some presets write OTEL_EXPORTER_OTLP_HEADERS straight into os.environ, and without the legacy tree's test ordering that header leaked into the AgentOps tests. * ci: run the moved integrations tests under their legacy flag The integrations GHA shard and a new CircleCI job run the integrations unit selection. secret_managers joins the misc selection. * docs: point integrations and secret_managers references at tests/unit * test: make the moved integrations directories packages * test: keep the Databricks manual e2e runner and fix the SageMaker Nova run path The Databricks e2e file is a manual script whose main() calls the tests that were pruned, so pruning them broke the documented run. It is back to its main version. The SageMaker Nova docstring now points at the file's real location in tests/local_testing. * test: keep the job's UNIT_FLAG out of the shard-script tests --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commitcf491d1df9) * fix(tests): drop the repeated UNIT_FLAG key in test_unit_shard_missing_paths (#43212) Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com> (cherry picked from commit25de1ab2b0) * fix(jwt): let x-litellm-team-id select DB membership teams when the token also carries a team claim (#43206) * fix(jwt): let x-litellm-team-id select DB membership teams when the token also carries a team claim Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * docs(jwt): describe header team selection under fallback_to_db_teams Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: yassin <yassin@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit7b4fd47c6e) * test: move tests/test_litellm core utils, routing, responses, caching and rust_bridge into tests/unit (#43199) * ci: run the unit_selection.sh shard files on every event instead of only fork pull requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci: rename fork-flag to unit-flag now that it applies on every event * test: move tests/test_litellm root and small trees into tests/unit Pure renames, no content changes. Follow-up commits in this PR fix references, merge the three files that already existed in tests/unit, keep live-provider tests in tests/test_litellm and wire CI. * test: carry tests/test_litellm conftest isolation into tests/unit Callback lists, routing fallbacks, cached HTTP clients, logger state, AWS, proxy-URL and keychain env, and session-end client cleanup now reset for unit tests too. The environment isolation owns its MonkeyPatch so a test's own monkeypatch is undone before the model-cost teardown runs. * test: merge, split and prune the moved root and small-tree tests Merge batches/test_batch_utils.py and the chat_completions and messages dispatch tests into the files that already existed in tests/unit. Keep the live Gemini interactions tests, the async image-fetch format test and the OpenAI embedding scorer test in tests/test_litellm since they need real network or keys. Put test_router.py under tests/unit/test_router so the existing package no longer shadows it. Delete eight tests the audit found superseded by stronger ones kept in this move. * ci: run the moved root and small-tree tests under their legacy flags Add the misc and responses-caching-types flags to unit_selection.sh and CircleCI, extend enterprise-routing and mcp-integration, and point the legacy GHA shards, Makefile, redis-compat workflow, merge smoke manifest and change classifier at the new paths. * test: make the new tests/unit directories packages tests/unit/test_package_layout.py requires every directory to carry an __init__.py, and without one the moved and retained test_litellm_responses_bridge.py modules collide on import. * test: scope the unit socket block to tests/unit in shared sessions The GHA shards collect the legacy test-path and the unit selection in one pytest session. The unit conftest's loopback-only block leaked into legacy modules that reach the network at import. The legacy conftest now lifts the restriction at collect and setup time, and the unit conftest re-applies it when collecting its own modules. * test: move tests/test_litellm/llms into tests/unit/llms Rename-only. Moves the provider tests and the fine-tuning fixtures they load, mirroring the old paths. Follow-up commits merge, split and wire them. * test: merge, split and prune the moved llms tests Merges the Databricks chat transformation tests into the existing unit file, keeps the tests that need real keys or the network in tests/test_litellm, deletes the audited tests a stronger unit test already covers, and points imports at tests.unit.llms. * ci: run the moved llms tests under their legacy flags The Vertex AI and All Other Providers shards keep their legacy test-path for the retained files and add the llm-vertex-ai and llm-other-providers unit selections. CircleCI gets matching unit jobs. * test: make the tests/unit/llms directories packages Adds __init__.py to the moved dirs and drops the legacy ones whose directories no longer hold tests. * test: drop script runners and path hacks the llms split left dangling The __main__ runners in the split openai_like files and the Databricks e2e runner called tests that now live in the other half of the split or were deleted. The retained legacy halves also no longer need sys.path edits. * test: give the shard-script tests their own GITHUB_OUTPUT They only passed where the runner set it. The CircleCI unit job's env allowlist drops it, so the script's redirect failed there. * test: point the router and module-deletion checks at tests/unit router_code_coverage and code_qa_check_tests only searched tests/test_litellm, so the moved router tests no longer counted. The two silent-experiment tests the audit deleted were the only direct callers of those methods; they are replaced with tests that assert the forwarded shadow request and the recursion guard. * test: move tests/test_litellm integrations and secret_managers into tests/unit Rename-only. Mirrors the old paths, including the directory conftests and the prompt and JSON fixtures. Follow-up commits prune and wire them. * test: prune and repoint the moved integrations tests Deletes the 7 audited tests a stronger test in the same tree already covers, imports the TLS sink helpers from their new conftest path, and restores os.environ after each integrations test. Some presets write OTEL_EXPORTER_OTLP_HEADERS straight into os.environ, and without the legacy tree's test ordering that header leaked into the AgentOps tests. * ci: run the moved integrations tests under their legacy flag The integrations GHA shard and a new CircleCI job run the integrations unit selection. secret_managers joins the misc selection. * docs: point integrations and secret_managers references at tests/unit * test: make the moved integrations directories packages * test: keep the Databricks manual e2e runner and fix the SageMaker Nova run path The Databricks e2e file is a manual script whose main() calls the tests that were pruned, so pruning them broke the documented run. It is back to its main version. The SageMaker Nova docstring now points at the file's real location in tests/local_testing. * test: move tests/test_litellm core utils, routing, responses, caching and rust_bridge into tests/unit Rename-only. Mirrors the old paths, including fixtures, the stubtest config and the native-route wheel script. Two files that collide with existing unit files are merged in a follow-up commit. * test: merge, prune and repoint the moved core, routing, responses, caching and rust_bridge tests Merges the two files that collided with existing unit files, folding the legacy extra case into test_is_chat_completion_cached_dict, and deletes the 9 audited tests a stronger test in the same file already covers. Keeps what needs the network in tests/test_litellm: test_tokenizers pulls a tokenizer from the Hugging Face hub, and the gpt2 and r50k_base tokenizer cases download their BPE files. The unit core_utils conftest points TIKTOKEN_CACHE_DIR at litellm's bundled encodings so the rest never depend on import order to stay offline, and FakeSecretVault moves to a shared module so both trees can build it. * ci: run the moved core, routing, responses, caching and rust_bridge tests under their flags core_utils gets a core-utils flag and CircleCI job, and its GHA shard keeps the legacy path for the retained network tests. router_utils and router_strategy join enterprise-routing, responses joins responses-caching-types (minus responses/mcp, which mcp-integration owns), caching joins caching-local and rust_bridge joins misc. The redis-compat, test-rust, stubtest and merge-smoke paths follow the move. * docs: point the Rust crate references at tests/unit * test: make the moved core, routing and rust_bridge directories packages * test: keep the no-loop DualCache batch_get_cache regression test It runs the sync path outside any event loop, which the inside-loop test cannot, so a change that picks the Redis client by loop state would only show up there. * test: keep the job's UNIT_FLAG out of the shard-script tests * fix(url_utils): block 192.0.0.0/24 on every Python patch release * test: move the new budget limiter tests into tests/unit/router_strategy * test: move the new sentry scrubbing tests into tests/unit/litellm_core_utils * test: move the new zerobus tests into tests/unit/integrations * test: make tests/unit/integrations/zerobus a package * test: load litellm's own tiktoken cache setup once instead of resetting it per test --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commita11a93f44a) * refactor(rust): move credential inheritance and the SDK limits out of the legacy callback crate into a driver preflight (#43259) The legacy callback crate carried two rewrites that have nothing to do with the Logging contract: litellm_credential_name inheritance and the max_budget and num_retries_per_request checks. Any later callback host would need them unchanged, which is the smell the crate's AGENTS.md now names. They are now a Preflight the driver in litellm-host-python runs on the keyword view begin returned, before the host projects from it, supplied by python-bridge and passed through run_legacy_call. The call order is unchanged (setup, deployment hook, credentials, limits) and a rejection still fails the call as a host failure, so the failure callbacks run as before. The preflight rewrites the adapter's own copy in place, so no extra dict copy and no new lifecycle method Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> (cherry picked from commite9491d31b5) * refactor(http): hand out an owned Client and route all providers through the pool (#43245) * refactor(messages): take the provider client from the injected HTTP pool The messages route kept its own process-wide reqwest client, so it ignored ssl_verify, CA bundles, client certs, proxies and every other setting that litellm-http resolves. The machine now takes the HttpClientPool and the call's HttpClientConfig, as OCR does, and the bridge passes its shared pool. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(http): hand out an owned Client and move chat, audio and OIDC onto the pool HttpClientPool now returns litellm_http::Client, a newtype only crates/http can build, so every provider client carries the resolved TLS, proxy and timeout settings. Chat completions and audio transcription drop their process-wide reqwest clients and take the pool and call config like messages; their 600s ceiling moves to the request. OidcResolver takes its client instead of building one, and the bridge hands it the pooled one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(secrets): build Google, Azure and CyberArk manager clients from the pool The native secret managers built bare reqwest clients, so they ignored the host's TLS and proxy settings. load_native_manager now takes the pool and the host config and hands each manager a pooled client. CyberArk's CYBERARK_SSL_VERIFY and CYBERARK_CLIENT_CERT/KEY become an override on the host config instead of a hand-built client. To express a certificate and key in separate files, HttpClientConfig::client_certificate is now a ClientIdentity that is either one PEM or a split pair. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(clippy): only crates/http may build a reqwest client Fence reqwest::Client, ClientBuilder and the TLS builder methods with disallowed-types and disallowed-methods so new code takes a litellm_http::Client from the pool. crates/http is exempt as the one place clients are built, and testkit as a dev-only installer. Tests move to litellm_http::Client::plain_for_test or a pooled client. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(secrets-cyberark): keep verifying certificates when the host disables it Python hands CyberArk its own ssl_verify, which wins over the global setting, so CYBERARK_SSL_VERIFY unset or true still verifies even when the host sets ssl_verify false. The pooled client copied the host's Disabled and would send the API key unverified; fall back to the built-in roots instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(python-bridge): treat a missing litellm package as no host HTTP settings Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit1a58162630) * refactor(rust): promote anthropic messages out of experimental_pass_through (#43269) Co-authored-by: Yujong Lee <yujong@berri.ai> (cherry picked from commit2ef3250ec3) * test: stop CI tests from downloading tokenizer files and images (#43257) * test: load the embedding base image from a committed 100x100 PNG instead of downloading it * test: move the volcengine embedding test into tests/unit * test: check gpt2 and r50k_base tokenizer parity against committed tiktoken reference files * test: check hub tokenizer selection against an in-memory Hugging Face hub * test: serve image URLs from respx in the gemini tool-result and format-param tests * ci: drop the emptied legacy core-utils test path * test: cover the cohere and anthropic tokenizer paths in the hub tokenizer test * test: fetch every format-param image through respx and check its bytes reach the request * test: drop the gpt2 and r50k_base parity tests, which no litellm path uses * test: drop comments that restate assertions in the format-param test (cherry picked from commit2530255624) * fix(rust): preserve nested optional import failures (#43265) * fix(rust): preserve nested optional import failures Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(rust): restore Python modules after settings tests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commite1a9378093) * fix(callbacks-legacy-python): traverse and release the retained headers dict (#43274) * fix(callbacks-legacy-python): traverse and release the retained headers dict LegacyLogging keeps the headers dict it hands to pre_call and post_call, but its traverse never reported that edge to the collector and close never dropped it. A cycle a callback builds through that dict could not be collected, and a closed call kept the dict alive until the driver dropped the whole adapter. Visit and clear headers like body, with regression tests for both * refactor(callbacks-legacy-python): move the test support module into its own file --------- Co-authored-by: Yujong Lee <yujong@berri.ai> (cherry picked from commit4eb340abe0) * test(integration): port langfuse callbacks-in-db coverage to the local harness (#43282) * test(integration): port langfuse callbacks-in-db coverage to the local harness Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): assert the langfuse db rows after the exported span Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: yuneng <yuneng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commite11c3f5815) * test: finish the non-proxy half of tests/test_litellm (#43281) * test: move key-gated tests/test_litellm SDK tests into tests/llm_translation and drop empty folders * test: make token counter and health check unit tests run offline * ci: point unit shards, rust path filter, Makefile and docs at tests/unit * docs: fix stale test_litellm run paths in moved llm_translation tests * fix: correct databricks e2e sys.path depth and contributing example path --------- Co-authored-by: yuneng <yuneng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit99655b6f86) * refactor(rust): prepare inference and auth foundations for the gateway (#43287) * refactor(rust): prepare inference and auth foundations * fix(rust): keep textract operations parsing from kebab-case model names Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit7ae721bf79) * feat(rust): add config router and gateway crates (#43289) Co-authored-by: Yujong Lee <yujong@berri.ai> (cherry picked from commitaffb547525) * test(integration): run the Langfuse DB-callback test on its own scratch database (#43288) * test(integration): run the Langfuse DB-callback test on its own scratch database The test from #43282 wrote success_callback=langfuse and the LANGFUSE_* env into the shared integration LiteLLM_Config. The suite's long-running gateway reloads that table and only ever adds callbacks, so it kept exporting to the test's closed Langfuse fake for the rest of the shard even after the rows were restored. The owned proxy now gets a scratch database, which also removes the snapshot/restore code. scratch_database moves into _support/database.py so test_cache_and_quota and this test share one copy, and the stock-config guard now checks the callback settings instead of the raw YAML text. * test(integration): include failure_callback in the stock-config Langfuse guard (cherry picked from commitdd63637322) * refactor(rust): expand logging and test coverage across gateway and Anthropic messages (#43295) * refactor(rust): prepare inference and auth foundations * fix(rust): keep textract operations parsing from kebab-case model names Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * done * refactor(types): derive Anthropic beta string conversions with Strum * fix(anthropic): report missing max_tokens as a missing field * refactor(rust): type Anthropic messages headers and auth after the Python layout Delete anthropic/messages/headers.rs. Its OAuth handling, credential ladder and beta merging move to anthropic/common_utils.rs where Python keeps them (optionally_handle_anthropic_oauth, get_auth_header, _merge_beta_headers), and the feature beta injection becomes update_headers_with_anthropic_beta on the messages config, as in Python. The BaseAnthropicMessagesConfig impl is unchanged apart from the bodies of validate_environment and request_headers Beta values are now the AnthropicBeta enum and BetaSet, which sort, dedupe and comma-join by construction. Request params gain typed speed, tools and context_management through Recognized, so the beta logic matches on enums instead of string-comparing JSON. OauthToken parses the sk-ant-oat token once and the chat config shares that detection instead of its own copy Case-insensitive header helpers move next to has_header in litellm-http. One deliberate divergence: a Bearer-prefixed OAuth key configured through api_key or ANTHROPIC_API_KEY is sent with a single Bearer scheme, where Python would emit "Bearer Bearer" Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * done * fix(rust): repair test compilation and clippy failures resolve auth before building the outbound request in prepare tests, give the host hook tests their own error type, and drop the disallowed reqwest client and err().expect() from core tests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> (cherry picked from commit90873c46de) * test(proxy_behavior): scope the management proxy fixture to its package so its spend monitor cannot race the spend tests (#43302) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit115668f43e) * fix(ci): stop stale CI reds, keep unit tests off the host env, retry CyberArk policy conflicts (#43294) * fix(ci): stop five stale or flaky CI reds and retry CyberArk policy-load conflicts The Langfuse redaction unit test exports to a local OTLP capture instead of polling Langfuse Cloud through a recorded lookup. The passthrough worker-kill test only requires spend rows for requests the surviving worker served. The spend-routes sweep treats the intentional /spend/capture_rate 503 as expected. CyberArk retries a 409 policy load in Python, Rust and the e2e Conjur helper instead of reading it as "variable exists". The integration egress guard now matches the script's own cgroup, so it no longer blocks the CircleCI agent, which runs as the same user. * fix(ci): keep the policy-load backoff typed as float * fix(ci): retry CyberArk policy loads without blocking the event loop and tighten the worker-kill and Langfuse tests * fix(secrets): load CyberArk policy one request at a time per manager * test(secrets): pin that non-conflict CyberArk policy failures are not retried * test(unit): run tests/unit with only an allowlisted host environment CircleCI's unit job inherits every project env var, so real provider keys, REDIS_HOST, DATABASE_URL and AWS or Azure credentials reached tests that assume none are set. Locally, litellm's import-time load_dotenv did the same from any .env up the tree. The unit conftest now drops every variable outside a small allowlist and disables dotenv before litellm is imported. * test(e2e): name a failed search and the stuck batch status instead of misattributing them The websearch session test read an empty web_search_tool_result_error block as a successful search, so a failing search tool surfaced as a session billing bug. The batch cancellation timeout now reports the last status the proxy returned. * fix(ci): scrub the host environment per unit test instead of for the whole pytest process GHA shards run tests/unit next to other suites in one process, so the import-time scrub deleted MCP_TEST_PEER_PYTHON before tests/mcp_tests read it and the MCP upstream fell back to the SDK2 interpreter. The two websearch tests that called OpenAI and Perplexity live are removed: tests/unit no longer sees their keys. * fix(ci): scrub only the host variables present before litellm is imported The per-test scrub also deleted TIKTOKEN_CACHE_DIR, which litellm sets at import to its bundled encodings, so tokenizer paths tried to download them and hit the socket guard. The prisma setup test now passes its own database URL instead of reading one another test leaked into the process environment. * fix(ci): stop the order-dependent unit reds and settle logging tasks on their own queue LoggingWorker marked a task done on whichever queue was current when the callback finished, so a callback that outlived an event-loop change raised "task_done() called too many times" or undercounted the new loop's queue. It now settles the queue the task came from. The rest are test isolation fixes for failures that only appeared when another file ran first on the same xdist worker: a replaced user_api_key_cache, breaker metrics unregistered by prometheus tests, semantic_router's health-check filter on uvicorn.access, logging tasks carried over from bedrock tests, a Router-written model_cost entry, and a stray post captured by the langflow test. The token counter check now asserts bounded chunking instead of wall-clock time. * test(e2e/ui): wait for the logout redirect before visiting a protected page Logout revokes the session server-side before clearing cookies and navigating, so an immediate page.goto either ran with the cookie still set or was aborted by the logout redirect (net::ERR_ABORTED). * test(unit): restore the prometheus metrics config per test and settle logs carried from earlier tests in the a2a cost tests * test(router): pin the router clock in the usage counter tests so a minute rollover cannot empty the read * test(e2e/ui): wait for logout to clear the token cookie instead of for a login redirect * test(integration/mcp): answer the model-info probe another test's proxy sends to the model double (cherry picked from commit14f4c34c61) * test(e2e): assert only litellm-owned batch behavior and move the blank S3 env pin to an integration test (#43321) (cherry picked from commite53e67ede5) * ci: drop main and litellm_* branch filters from the CircleCI litellm-main workflows (#43272) Co-authored-by: yuneng <yuneng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commitc822c7fffa) * test(e2e): accept the otel cost write as a linked root trace (#42931) * test(e2e): accept the otel cost write as a linked root trace Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(e2e): window and fail-closed the linked otel trace read-back Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(e2e): poll the otel read-back without recursion Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: yuneng <yuneng@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit3ebf6a1fd8) * refactor(rust): exclude gateway and config crates from rc backport * refactor(rust): exclude router crate from rc backport --------- Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Co-authored-by: yassin <yassin@berri.ai>
1951 lines
73 KiB
Python
1951 lines
73 KiB
Python
"""
|
|
Tests for the Rubrik LiteLLM plugin.
|
|
|
|
Covers initialization, apply_guardrail (prompt moderation + response/tool
|
|
blocking), batch logging, and Anthropic format handling.
|
|
"""
|
|
|
|
import os
|
|
from typing import Any, Dict
|
|
from unittest.mock import AsyncMock, Mock, patch
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
from litellm.integrations.custom_guardrail import ModifyResponseException
|
|
from litellm.integrations.rubrik import (
|
|
RubrikLogger,
|
|
_MalformedToolBlockingResponseError,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
from tests.unit.integrations.rubrik_test_helpers import (
|
|
make_inputs_with_tools,
|
|
make_tool_call_dict,
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_env():
|
|
"""Set up environment variables for testing."""
|
|
with patch.dict(
|
|
os.environ,
|
|
{
|
|
"RUBRIK_WEBHOOK_URL": "http://localhost:8080",
|
|
"RUBRIK_API_KEY": "test-api-key",
|
|
},
|
|
):
|
|
yield
|
|
|
|
|
|
@pytest.fixture
|
|
def handler(mock_env):
|
|
"""Create a RubrikLogger instance for testing."""
|
|
with patch("asyncio.create_task", Mock()):
|
|
return RubrikLogger()
|
|
|
|
|
|
@pytest.fixture
|
|
def user_api_key_dict():
|
|
"""The authenticated caller the proxy hands to async_post_call_failure_hook."""
|
|
return UserAPIKeyAuth(
|
|
api_key="sk-block-attribution-test",
|
|
key_alias="rubrik-probe-key",
|
|
user_id="probe-user-1",
|
|
team_id="probe-team-1",
|
|
org_id="probe-org-1",
|
|
)
|
|
|
|
|
|
# -- Initialization -----------------------------------------------------------
|
|
|
|
|
|
class TestInitialization:
|
|
def test_init_success(self, mock_env):
|
|
with patch("asyncio.create_task", Mock()):
|
|
handler = RubrikLogger()
|
|
assert (
|
|
handler.response_moderation_endpoint
|
|
== "http://localhost:8080/v1/after_completion/openai/v1"
|
|
)
|
|
assert handler.logging_endpoint == "http://localhost:8080/v1/litellm/batch"
|
|
assert handler.key == "test-api-key"
|
|
assert handler.moderation_client is not None
|
|
|
|
def test_init_with_constructor_params(self):
|
|
with patch("asyncio.create_task", Mock()):
|
|
handler = RubrikLogger(api_key="ctor-key", api_base="http://ctor-host:9090")
|
|
assert handler.key == "ctor-key"
|
|
assert (
|
|
handler.response_moderation_endpoint
|
|
== "http://ctor-host:9090/v1/after_completion/openai/v1"
|
|
)
|
|
|
|
def test_init_without_url(self):
|
|
with patch.dict(os.environ, {}, clear=True):
|
|
with pytest.raises(ValueError, match="Rubrik webhook URL not configured"):
|
|
RubrikLogger()
|
|
|
|
def test_init_without_api_key(self):
|
|
with patch.dict(
|
|
os.environ, {"RUBRIK_WEBHOOK_URL": "http://localhost:8080"}, clear=True
|
|
):
|
|
with patch("asyncio.create_task", Mock()):
|
|
assert RubrikLogger().key is None
|
|
|
|
def test_trailing_slash_removed(self):
|
|
with patch.dict(os.environ, {"RUBRIK_WEBHOOK_URL": "http://localhost:8080/"}):
|
|
with patch("asyncio.create_task", Mock()):
|
|
assert (
|
|
RubrikLogger().response_moderation_endpoint
|
|
== "http://localhost:8080/v1/after_completion/openai/v1"
|
|
)
|
|
|
|
def test_v1_suffix_stripped_as_substring_not_charset(self):
|
|
with patch("asyncio.create_task", Mock()):
|
|
with patch.dict(os.environ, {"RUBRIK_WEBHOOK_URL": "http://host/v1"}):
|
|
assert (
|
|
RubrikLogger().response_moderation_endpoint
|
|
== "http://host/v1/after_completion/openai/v1"
|
|
)
|
|
|
|
with patch.dict(os.environ, {"RUBRIK_WEBHOOK_URL": "http://host/v11"}):
|
|
assert (
|
|
RubrikLogger().response_moderation_endpoint
|
|
== "http://host/v11/v1/after_completion/openai/v1"
|
|
)
|
|
|
|
def test_sampling_rate_fractional(self):
|
|
with patch("asyncio.create_task", Mock()):
|
|
with patch.dict(
|
|
os.environ,
|
|
{"RUBRIK_WEBHOOK_URL": "http://host", "RUBRIK_SAMPLING_RATE": "0.5"},
|
|
):
|
|
assert RubrikLogger().sampling_rate == 0.5
|
|
|
|
def test_sampling_rate_invalid_ignored(self):
|
|
with patch("asyncio.create_task", Mock()):
|
|
with patch.dict(
|
|
os.environ,
|
|
{"RUBRIK_WEBHOOK_URL": "http://host", "RUBRIK_SAMPLING_RATE": "abc"},
|
|
):
|
|
assert RubrikLogger().sampling_rate == 1.0
|
|
|
|
def test_sampling_rate_clamped(self):
|
|
with patch("asyncio.create_task", Mock()):
|
|
with patch.dict(
|
|
os.environ,
|
|
{"RUBRIK_WEBHOOK_URL": "http://host", "RUBRIK_SAMPLING_RATE": "2.0"},
|
|
):
|
|
assert RubrikLogger().sampling_rate == 1.0
|
|
with patch.dict(
|
|
os.environ,
|
|
{"RUBRIK_WEBHOOK_URL": "http://host", "RUBRIK_SAMPLING_RATE": "-0.5"},
|
|
):
|
|
assert RubrikLogger().sampling_rate == 0.0
|
|
|
|
def test_batch_size_invalid_ignored(self):
|
|
with patch("asyncio.create_task", Mock()):
|
|
with patch.dict(
|
|
os.environ,
|
|
{"RUBRIK_WEBHOOK_URL": "http://host", "RUBRIK_BATCH_SIZE": "abc"},
|
|
):
|
|
# Should use default without crashing
|
|
assert isinstance(RubrikLogger().batch_size, int)
|
|
|
|
def test_batch_size_valid(self):
|
|
with patch("asyncio.create_task", Mock()):
|
|
with patch.dict(
|
|
os.environ,
|
|
{"RUBRIK_WEBHOOK_URL": "http://host", "RUBRIK_BATCH_SIZE": "256"},
|
|
):
|
|
assert RubrikLogger().batch_size == 256
|
|
|
|
def test_init_outside_event_loop_does_not_raise(self):
|
|
"""Instantiation without a running event loop must not raise RuntimeError."""
|
|
with patch.dict(
|
|
os.environ,
|
|
{"RUBRIK_WEBHOOK_URL": "http://localhost:8080", "RUBRIK_API_KEY": "k"},
|
|
):
|
|
# Do NOT patch asyncio.create_task — the real call should be
|
|
# guarded and fall back gracefully when there is no event loop.
|
|
handler = RubrikLogger()
|
|
assert handler.response_moderation_endpoint.startswith("http://localhost:8080")
|
|
# Without a running loop at init, the periodic flush task should be
|
|
# deferred so batches still get drained once a log event arrives.
|
|
assert handler._periodic_flush_task is None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_periodic_flush_task_started_lazily_on_first_log(self, mock_env):
|
|
"""Loggers instantiated outside an event loop must still start the
|
|
periodic flush task on first use to drain low-traffic batches."""
|
|
# Simulate sync-init by hiding the running loop from the constructor.
|
|
with patch(
|
|
"litellm.integrations.rubrik.asyncio.get_running_loop",
|
|
side_effect=RuntimeError("no running loop"),
|
|
):
|
|
handler = RubrikLogger()
|
|
assert handler._periodic_flush_task is None
|
|
|
|
kwargs = {
|
|
"standard_logging_object": {
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"id": "litellm-id",
|
|
},
|
|
"litellm_call_id": "litellm-id",
|
|
"litellm_params": {},
|
|
}
|
|
with patch.object(handler, "_log_batch_to_rubrik", AsyncMock()):
|
|
await handler.async_log_success_event(kwargs, None, None, None)
|
|
|
|
assert handler._periodic_flush_task is not None
|
|
handler._periodic_flush_task.cancel()
|
|
|
|
def test_event_hook_defaults_to_post_call_when_none_passed(self, mock_env):
|
|
"""`initialize_guardrail` always passes ``event_hook=litellm_params.mode``
|
|
(which is ``None`` when the user omits ``mode``). The logger must coerce
|
|
a None ``event_hook`` to ``post_call`` rather than leaving it as None,
|
|
which would otherwise cause the guardrail to run on every event hook."""
|
|
from litellm.types.guardrails import GuardrailEventHooks
|
|
|
|
with patch("asyncio.create_task", Mock()):
|
|
handler = RubrikLogger(event_hook=None)
|
|
assert handler.event_hook == GuardrailEventHooks.post_call
|
|
|
|
def test_explicit_event_hook_preserved(self, mock_env):
|
|
from litellm.types.guardrails import GuardrailEventHooks
|
|
|
|
with patch("asyncio.create_task", Mock()):
|
|
handler = RubrikLogger(event_hook=GuardrailEventHooks.pre_call)
|
|
assert handler.event_hook == GuardrailEventHooks.pre_call
|
|
|
|
def test_default_on_defaults_to_false_when_none_passed(self, mock_env):
|
|
"""Follows the standard litellm pattern: omitted ``default_on`` resolves
|
|
to ``False`` (off by default). Users must explicitly set
|
|
``default_on: true`` to enable the guardrail for all requests."""
|
|
with patch("asyncio.create_task", Mock()):
|
|
handler = RubrikLogger(default_on=None)
|
|
assert handler.default_on is False
|
|
|
|
def test_explicit_default_on_false_preserved(self, mock_env):
|
|
"""A user explicitly setting ``default_on: false`` in their guardrail
|
|
config must NOT be silently overridden to True."""
|
|
with patch("asyncio.create_task", Mock()):
|
|
handler = RubrikLogger(default_on=False)
|
|
assert handler.default_on is False
|
|
|
|
def test_explicit_default_on_true_preserved(self, mock_env):
|
|
with patch("asyncio.create_task", Mock()):
|
|
handler = RubrikLogger(default_on=True)
|
|
assert handler.default_on is True
|
|
|
|
def test_headers_with_api_key(self, handler):
|
|
assert handler._headers["Authorization"] == "Bearer test-api-key"
|
|
assert handler._headers["Content-Type"] == "application/json"
|
|
|
|
def test_headers_without_api_key(self):
|
|
with patch.dict(os.environ, {"RUBRIK_WEBHOOK_URL": "http://host"}, clear=True):
|
|
with patch("asyncio.create_task", Mock()):
|
|
h = RubrikLogger()
|
|
assert "Authorization" not in h._headers
|
|
|
|
|
|
# -- Batch Logging ------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
class TestBatchLogging:
|
|
async def test_log_success_event_appends_to_queue(self, handler):
|
|
kwargs = {
|
|
"standard_logging_object": {
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"response": "hello",
|
|
},
|
|
}
|
|
await handler.async_log_success_event(
|
|
kwargs=kwargs, response_obj=None, start_time=None, end_time=None
|
|
)
|
|
assert len(handler.log_queue) == 1
|
|
|
|
async def test_log_failure_event_appends_to_queue(self, handler):
|
|
kwargs = {
|
|
"standard_logging_object": {
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"response": "error",
|
|
},
|
|
}
|
|
await handler.async_log_failure_event(
|
|
kwargs=kwargs, response_obj=None, start_time=None, end_time=None
|
|
)
|
|
assert len(handler.log_queue) == 1
|
|
|
|
async def test_log_success_event_sampling_skips(self, handler):
|
|
handler.sampling_rate = 0.0
|
|
kwargs = {
|
|
"standard_logging_object": {
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"response": "hello",
|
|
},
|
|
}
|
|
await handler.async_log_success_event(
|
|
kwargs=kwargs, response_obj=None, start_time=None, end_time=None
|
|
)
|
|
assert len(handler.log_queue) == 0
|
|
|
|
async def test_flush_queue_sends_batch(self, handler):
|
|
handler.log_queue = [{"msg": "a"}, {"msg": "b"}]
|
|
mock_response = Mock()
|
|
mock_response.status_code = 200
|
|
handler.async_httpx_client = AsyncMock()
|
|
handler.async_httpx_client.post = AsyncMock(return_value=mock_response)
|
|
await handler.flush_queue()
|
|
handler.async_httpx_client.post.assert_called_once()
|
|
assert len(handler.log_queue) == 0
|
|
|
|
async def test_flush_queue_preserves_events_added_during_send(self, handler):
|
|
handler.log_queue = [{"msg": "a"}, {"msg": "b"}]
|
|
|
|
async def mock_post(*_args, **_kwargs):
|
|
handler.log_queue.append({"msg": "c"})
|
|
mock_response = Mock()
|
|
mock_response.raise_for_status = Mock()
|
|
return mock_response
|
|
|
|
handler.async_httpx_client = AsyncMock()
|
|
handler.async_httpx_client.post = mock_post
|
|
|
|
await handler.flush_queue()
|
|
|
|
assert handler.log_queue == [{"msg": "c"}]
|
|
|
|
async def test_async_send_batch_does_not_drain_events(self, handler):
|
|
handler.log_queue = [{"msg": "a"}, {"msg": "b"}]
|
|
|
|
async def mock_post(*_args, **_kwargs):
|
|
handler.log_queue.append({"msg": "c"})
|
|
mock_response = Mock()
|
|
mock_response.raise_for_status = Mock()
|
|
return mock_response
|
|
|
|
handler.async_httpx_client = AsyncMock()
|
|
handler.async_httpx_client.post = mock_post
|
|
|
|
await handler.async_send_batch()
|
|
|
|
assert handler.log_queue == [{"msg": "a"}, {"msg": "b"}, {"msg": "c"}]
|
|
|
|
async def test_log_batch_error_does_not_crash_and_preserves_events(self, handler):
|
|
"""A failed batch send must not crash the caller AND must preserve the
|
|
original events in the queue so they can be retried on the next flush.
|
|
Previously the events were silently dropped on HTTP 5xx / network errors.
|
|
"""
|
|
handler.log_queue = [{"msg": "a"}]
|
|
mock_response = Mock()
|
|
mock_response.status_code = 500
|
|
mock_response.text = "Internal Server Error"
|
|
mock_response.raise_for_status = Mock(
|
|
side_effect=httpx.HTTPStatusError(
|
|
"err", request=Mock(), response=mock_response
|
|
)
|
|
)
|
|
handler.async_httpx_client = AsyncMock()
|
|
handler.async_httpx_client.post = AsyncMock(return_value=mock_response)
|
|
await handler.flush_queue()
|
|
assert handler.log_queue == [{"msg": "a"}]
|
|
|
|
async def test_log_batch_network_error_preserves_events(self, handler):
|
|
"""Network/timeout errors must also preserve the in-flight events."""
|
|
handler.log_queue = [{"msg": "a"}, {"msg": "b"}]
|
|
handler.async_httpx_client = AsyncMock()
|
|
handler.async_httpx_client.post = AsyncMock(
|
|
side_effect=httpx.TimeoutException("timeout")
|
|
)
|
|
await handler.flush_queue()
|
|
assert handler.log_queue == [{"msg": "a"}, {"msg": "b"}]
|
|
|
|
async def test_enqueue_drops_oldest_when_queue_exceeds_max_size(self, handler):
|
|
"""A sustained Rubrik webhook outage must not let the in-memory retry
|
|
queue grow without bound. Once max_queue_size is exceeded, the oldest
|
|
events are dropped to make room for new ones."""
|
|
handler.max_queue_size = 3
|
|
handler.batch_size = 10**6 # disable size-triggered flush
|
|
handler.flush_queue = AsyncMock()
|
|
for i in range(5):
|
|
await handler._enqueue_log_event(
|
|
kwargs={
|
|
"standard_logging_object": {
|
|
"messages": [{"role": "user", "content": f"hi-{i}"}],
|
|
"response": "hello",
|
|
},
|
|
},
|
|
event_type="success",
|
|
)
|
|
assert len(handler.log_queue) == 3
|
|
retained = [item["messages"][0]["content"] for item in handler.log_queue]
|
|
assert retained == ["hi-2", "hi-3", "hi-4"]
|
|
|
|
async def test_log_batch_failure_preserves_events_added_during_send(self, handler):
|
|
"""Failure must preserve both the snapshot AND events appended mid-flush."""
|
|
handler.log_queue = [{"msg": "a"}, {"msg": "b"}]
|
|
|
|
async def mock_post(*_args, **_kwargs):
|
|
handler.log_queue.append({"msg": "c"})
|
|
mock_response = Mock()
|
|
mock_response.status_code = 500
|
|
mock_response.text = "boom"
|
|
mock_response.raise_for_status = Mock(
|
|
side_effect=httpx.HTTPStatusError(
|
|
"err", request=Mock(), response=mock_response
|
|
)
|
|
)
|
|
return mock_response
|
|
|
|
handler.async_httpx_client = AsyncMock()
|
|
handler.async_httpx_client.post = mock_post
|
|
|
|
await handler.flush_queue()
|
|
assert handler.log_queue == [{"msg": "a"}, {"msg": "b"}, {"msg": "c"}]
|
|
|
|
async def test_system_prompt_prepended_to_messages(self, handler):
|
|
kwargs = {
|
|
"standard_logging_object": {
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"response": "hello",
|
|
},
|
|
"system": "You are a helpful assistant.",
|
|
}
|
|
await handler.async_log_success_event(
|
|
kwargs=kwargs, response_obj=None, start_time=None, end_time=None
|
|
)
|
|
assert len(handler.log_queue) == 1
|
|
msgs = handler.log_queue[0]["messages"]
|
|
assert msgs[0]["role"] == "system"
|
|
assert msgs[0]["content"] == "You are a helpful assistant."
|
|
|
|
async def test_system_prompt_with_dict_messages(self, handler):
|
|
kwargs = {
|
|
"standard_logging_object": {
|
|
"messages": {"role": "user", "content": "hi"},
|
|
"response": "hello",
|
|
},
|
|
"system": "Be concise.",
|
|
}
|
|
await handler.async_log_success_event(
|
|
kwargs=kwargs, response_obj=None, start_time=None, end_time=None
|
|
)
|
|
assert len(handler.log_queue) == 1
|
|
msgs = handler.log_queue[0]["messages"]
|
|
assert isinstance(msgs, tuple)
|
|
assert msgs[0]["role"] == "system"
|
|
assert msgs[1] == {"role": "user", "content": "hi"}
|
|
|
|
async def test_anthropic_id_normalization(self, handler):
|
|
kwargs = {
|
|
"standard_logging_object": {
|
|
"id": "chatcmpl-original",
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"response": "hello",
|
|
},
|
|
"litellm_params": {
|
|
"proxy_server_request": {
|
|
"url": "http://proxy/v1/messages",
|
|
},
|
|
},
|
|
"litellm_call_id": "litellm-call-123",
|
|
}
|
|
await handler.async_log_success_event(
|
|
kwargs=kwargs, response_obj=None, start_time=None, end_time=None
|
|
)
|
|
assert handler.log_queue[0]["id"] == "litellm-call-123"
|
|
|
|
async def test_litellm_call_id_always_used_as_correlation_key(self, handler):
|
|
"""The merged plugin always uses litellm_call_id as the log ID for all
|
|
providers (not just Anthropic) so that logs correlate with the
|
|
moderation (_blocking) and failure logs for the same request."""
|
|
kwargs = {
|
|
"standard_logging_object": {
|
|
"id": "chatcmpl-original",
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"response": "hello",
|
|
},
|
|
"litellm_params": {
|
|
"proxy_server_request": {
|
|
"url": "http://proxy/v1/chat/completions",
|
|
},
|
|
},
|
|
"litellm_call_id": "litellm-call-123",
|
|
}
|
|
await handler.async_log_success_event(
|
|
kwargs=kwargs, response_obj=None, start_time=None, end_time=None
|
|
)
|
|
assert handler.log_queue[0]["id"] == "litellm-call-123"
|
|
|
|
async def test_payload_deep_copied_not_mutated(self, handler):
|
|
"""Verify the shared standard_logging_object is not mutated."""
|
|
original_payload = {
|
|
"id": "original-id",
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"response": "hello",
|
|
}
|
|
kwargs = {
|
|
"standard_logging_object": original_payload,
|
|
"system": "System prompt.",
|
|
}
|
|
await handler.async_log_success_event(
|
|
kwargs=kwargs, response_obj=None, start_time=None, end_time=None
|
|
)
|
|
# Original payload should NOT have been mutated
|
|
assert original_payload["id"] == "original-id"
|
|
assert len(original_payload["messages"]) == 1
|
|
|
|
|
|
# -- Tool Blocking (apply_guardrail) ------------------------------------------
|
|
|
|
|
|
def _mock_service_response(response_json):
|
|
"""Create a mock tool blocking client that returns the given JSON."""
|
|
|
|
async def mock_post(*_args, **kwargs):
|
|
mock_resp = Mock()
|
|
mock_resp.json.return_value = response_json
|
|
mock_resp.raise_for_status = Mock()
|
|
return mock_resp
|
|
|
|
mock_client = AsyncMock()
|
|
mock_client.post = mock_post
|
|
return mock_client
|
|
|
|
|
|
def _echo_service():
|
|
"""Create a mock tool blocking client that echoes the payload back."""
|
|
|
|
async def mock_post(*_args, **kwargs):
|
|
mock_resp = Mock()
|
|
mock_resp.json.return_value = kwargs.get("json", {}).get("response", {})
|
|
mock_resp.raise_for_status = Mock()
|
|
return mock_resp
|
|
|
|
mock_client = AsyncMock()
|
|
mock_client.post = mock_post
|
|
return mock_client
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
class TestApplyGuardrail:
|
|
async def test_skips_requests(self, handler):
|
|
inputs = make_inputs_with_tools([make_tool_call_dict("call_1", "test_tool")])
|
|
result = await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="request"
|
|
)
|
|
assert result is inputs
|
|
|
|
async def test_no_tool_calls(self, handler):
|
|
from litellm.types.utils import GenericGuardrailAPIInputs
|
|
|
|
inputs = GenericGuardrailAPIInputs(texts=["hello"])
|
|
result = await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="response"
|
|
)
|
|
assert result is inputs
|
|
|
|
async def test_all_allowed(self, handler):
|
|
tc1 = make_tool_call_dict("call_1", "get_weather")
|
|
tc2 = make_tool_call_dict("call_2", "get_time")
|
|
inputs = make_inputs_with_tools([tc1, tc2])
|
|
|
|
handler.moderation_client = _echo_service()
|
|
|
|
result = await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="response"
|
|
)
|
|
assert result is inputs
|
|
|
|
async def test_all_blocked(self, handler):
|
|
tc1 = make_tool_call_dict("call_1", "delete_table")
|
|
tc2 = make_tool_call_dict("call_2", "drop_database")
|
|
inputs = make_inputs_with_tools([tc1, tc2])
|
|
|
|
handler.moderation_client = _mock_service_response(
|
|
{
|
|
"choices": [
|
|
{
|
|
"message": {
|
|
"role": "assistant",
|
|
"content": "Tool blocked by policy",
|
|
"tool_calls": [],
|
|
}
|
|
}
|
|
],
|
|
}
|
|
)
|
|
|
|
with pytest.raises(ModifyResponseException) as exc_info:
|
|
await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="response"
|
|
)
|
|
assert "Tool blocked by policy" in exc_info.value.message
|
|
|
|
async def test_partial_blocking(self, handler):
|
|
tc_blocked = make_tool_call_dict("call_A", "blocked_tool")
|
|
tc_allowed = make_tool_call_dict("call_B", "allowed_tool")
|
|
inputs = make_inputs_with_tools([tc_blocked, tc_allowed])
|
|
|
|
async def mock_post(*_args, **kwargs):
|
|
payload = kwargs.get("json", {}).get("response", {})
|
|
all_tcs = payload["choices"][0]["message"]["tool_calls"]
|
|
allowed = [tc for tc in all_tcs if tc.get("id") == "call_B"]
|
|
mock_resp = Mock()
|
|
mock_resp.json.return_value = {
|
|
"choices": [
|
|
{
|
|
"message": {
|
|
"role": "assistant",
|
|
"content": "blocked",
|
|
"tool_calls": allowed,
|
|
}
|
|
}
|
|
],
|
|
}
|
|
mock_resp.raise_for_status = Mock()
|
|
return mock_resp
|
|
|
|
mock_client = AsyncMock()
|
|
mock_client.post = mock_post
|
|
handler.moderation_client = mock_client
|
|
|
|
with pytest.raises(ModifyResponseException):
|
|
await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="response"
|
|
)
|
|
|
|
async def test_service_failure_fail_open(self, handler):
|
|
tc1 = make_tool_call_dict("call_1", "test_tool")
|
|
inputs = make_inputs_with_tools([tc1])
|
|
|
|
mock_client = AsyncMock()
|
|
mock_client.post = AsyncMock(side_effect=httpx.TimeoutException("Timeout"))
|
|
handler.moderation_client = mock_client
|
|
|
|
result = await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="response"
|
|
)
|
|
assert result is inputs
|
|
|
|
async def test_service_empty_choices_fail_open(self, handler):
|
|
tc1 = make_tool_call_dict("call_1", "test_tool")
|
|
inputs = make_inputs_with_tools([tc1])
|
|
|
|
handler.moderation_client = _mock_service_response({"choices": []})
|
|
|
|
result = await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="response"
|
|
)
|
|
assert result is inputs
|
|
|
|
async def test_blocking_service_payload_format(self, handler):
|
|
tc1 = make_tool_call_dict("call_1", "get_weather", '{"location": "SF"}')
|
|
tc2 = make_tool_call_dict("call_2", "send_email", '{"to": "user@example.com"}')
|
|
inputs = make_inputs_with_tools([tc1, tc2])
|
|
|
|
captured_payload: Dict[str, Any] = {}
|
|
|
|
async def mock_post(*_args, **kwargs):
|
|
captured_payload.update(kwargs.get("json", {}))
|
|
mock_resp = Mock()
|
|
mock_resp.json.return_value = captured_payload.get("response", {})
|
|
mock_resp.raise_for_status = Mock()
|
|
return mock_resp
|
|
|
|
mock_client = AsyncMock()
|
|
mock_client.post = mock_post
|
|
handler.moderation_client = mock_client
|
|
|
|
await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="response"
|
|
)
|
|
|
|
# Verify envelope structure
|
|
assert "request" in captured_payload
|
|
assert "response" in captured_payload
|
|
|
|
response_data = captured_payload["response"]
|
|
message = response_data["choices"][0]["message"]
|
|
assert message["role"] == "assistant"
|
|
assert len(message["tool_calls"]) == 2
|
|
assert message["tool_calls"][0]["id"] == "call_1"
|
|
assert message["tool_calls"][0]["function"]["name"] == "get_weather"
|
|
assert message["tool_calls"][1]["id"] == "call_2"
|
|
assert message["tool_calls"][1]["function"]["name"] == "send_email"
|
|
|
|
async def test_request_data_included_in_envelope(self, handler):
|
|
tc = make_tool_call_dict("call_1", "test_tool")
|
|
inputs = make_inputs_with_tools([tc])
|
|
|
|
captured_payload: Dict[str, Any] = {}
|
|
|
|
async def mock_post(*_args, **kwargs):
|
|
captured_payload.update(kwargs.get("json", {}))
|
|
mock_resp = Mock()
|
|
mock_resp.json.return_value = captured_payload.get("response", {})
|
|
mock_resp.raise_for_status = Mock()
|
|
return mock_resp
|
|
|
|
mock_client = AsyncMock()
|
|
mock_client.post = mock_post
|
|
handler.moderation_client = mock_client
|
|
|
|
logging_obj = Mock()
|
|
logging_obj.model_call_details = {
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"model": "gpt-4",
|
|
"litellm_params": {
|
|
"proxy_server_request": {"url": "/chat/completions"},
|
|
},
|
|
}
|
|
|
|
await handler.apply_guardrail(
|
|
inputs=inputs,
|
|
request_data={},
|
|
input_type="response",
|
|
logging_obj=logging_obj,
|
|
)
|
|
|
|
req = captured_payload["request"]
|
|
assert req["model"] == "gpt-4"
|
|
assert req["messages"] == [{"role": "user", "content": "hi"}]
|
|
|
|
async def test_proxy_server_request_not_forwarded(self, handler):
|
|
"""proxy_server_request is intentionally NOT included in the request
|
|
envelope: in litellm >=1.83 its ``body`` carries a UserAPIKeyAuth
|
|
instance that breaks json.dumps, silently fail-opening the guardrail."""
|
|
tc = make_tool_call_dict("call_1", "test_tool")
|
|
inputs = make_inputs_with_tools([tc])
|
|
|
|
captured_payload: Dict[str, Any] = {}
|
|
|
|
async def mock_post(*_args, **kwargs):
|
|
captured_payload.update(kwargs.get("json", {}))
|
|
mock_resp = Mock()
|
|
mock_resp.json.return_value = captured_payload.get("response", {})
|
|
mock_resp.raise_for_status = Mock()
|
|
return mock_resp
|
|
|
|
mock_client = AsyncMock()
|
|
mock_client.post = mock_post
|
|
handler.moderation_client = mock_client
|
|
|
|
logging_obj = Mock()
|
|
logging_obj.model_call_details = {
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"model": "gpt-4",
|
|
"litellm_params": {
|
|
"proxy_server_request": {
|
|
"url": "/chat/completions",
|
|
"method": "POST",
|
|
"headers": {
|
|
"authorization": "Bearer sk-litellm-secret",
|
|
"cookie": "session=abc",
|
|
"x-api-key": "leaked-key",
|
|
},
|
|
"body": {"api_key": "sk-upstream-secret"},
|
|
},
|
|
},
|
|
}
|
|
|
|
await handler.apply_guardrail(
|
|
inputs=inputs,
|
|
request_data={},
|
|
input_type="response",
|
|
logging_obj=logging_obj,
|
|
)
|
|
|
|
# proxy_server_request is deliberately excluded from the forwarded envelope
|
|
assert "proxy_server_request" not in captured_payload["request"]
|
|
|
|
|
|
# -- Anthropic format ----------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
class TestApplyGuardrailAnthropicFormat:
|
|
"""Verify blocking works correctly regardless of original provider format.
|
|
|
|
The framework converts Anthropic tool_use blocks to OpenAI-format
|
|
tool_calls before calling apply_guardrail.
|
|
"""
|
|
|
|
async def test_single_tool_allowed(self, handler):
|
|
tc = make_tool_call_dict(
|
|
"toolu_123", "get_weather", '{"location": "Portland, OR"}'
|
|
)
|
|
inputs = make_inputs_with_tools([tc], texts=["I'll check the weather."])
|
|
|
|
handler.moderation_client = _echo_service()
|
|
|
|
result = await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="response"
|
|
)
|
|
assert result is inputs
|
|
|
|
async def test_single_tool_blocked(self, handler):
|
|
tc = make_tool_call_dict("toolu_123", "dangerous_tool", '{"arg": "value"}')
|
|
inputs = make_inputs_with_tools([tc])
|
|
|
|
handler.moderation_client = _mock_service_response(
|
|
{
|
|
"choices": [
|
|
{
|
|
"message": {
|
|
"role": "assistant",
|
|
"content": "blocked",
|
|
"tool_calls": [],
|
|
}
|
|
}
|
|
],
|
|
}
|
|
)
|
|
|
|
with pytest.raises(ModifyResponseException):
|
|
await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="response"
|
|
)
|
|
|
|
async def test_text_only_response_sent_to_moderation(self, handler):
|
|
"""Text-only responses (no tool calls) are sent to the response
|
|
moderation service to check the assistant's text content."""
|
|
from litellm.types.utils import GenericGuardrailAPIInputs
|
|
|
|
inputs = GenericGuardrailAPIInputs(texts=["Hello! I'm Claude."])
|
|
|
|
# Service allows the response (returns the content unchanged)
|
|
handler.moderation_client = _echo_service()
|
|
|
|
result = await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="response"
|
|
)
|
|
|
|
assert result is inputs
|
|
|
|
async def test_service_failure_preserves_tools(self, handler):
|
|
tc = make_tool_call_dict("toolu_123", "get_weather", '{"location": "SF"}')
|
|
inputs = make_inputs_with_tools([tc])
|
|
|
|
mock_client = AsyncMock()
|
|
mock_client.post = AsyncMock(side_effect=httpx.TimeoutException("Timeout"))
|
|
handler.moderation_client = mock_client
|
|
|
|
result = await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="response"
|
|
)
|
|
assert result is inputs
|
|
|
|
|
|
# -- Normalize tool calls ------------------------------------------------------
|
|
|
|
|
|
class TestNormalizeToolCalls:
|
|
def test_dict_input(self):
|
|
tc = make_tool_call_dict("call_1", "test", '{"a": 1}')
|
|
result = RubrikLogger._normalize_tool_calls([tc])
|
|
assert len(result) == 1
|
|
assert result[0].id == "call_1"
|
|
assert result[0].function.name == "test"
|
|
assert result[0].function.arguments == '{"a": 1}'
|
|
|
|
def test_typed_object_input(self):
|
|
from litellm.types.utils import ChatCompletionMessageToolCall, Function
|
|
|
|
tc = ChatCompletionMessageToolCall(
|
|
id="call_2",
|
|
type="function",
|
|
function=Function(name="fn", arguments="{}"),
|
|
)
|
|
result = RubrikLogger._normalize_tool_calls([tc])
|
|
assert len(result) == 1
|
|
assert result[0].id == "call_2"
|
|
assert result[0].function.name == "fn"
|
|
|
|
def test_unsupported_type_raises(self):
|
|
with pytest.raises(TypeError, match="Cannot normalize"):
|
|
RubrikLogger._normalize_tool_calls(["not_a_tool_call"])
|
|
|
|
|
|
# -- Extract response block ----------------------------------------------------
|
|
|
|
|
|
class TestExtractResponseBlock:
|
|
"""Tests for _extract_response_block, which replaces the upstream
|
|
_extract_blocked_tools and handles both text blocks and tool blocks."""
|
|
|
|
def test_all_allowed_returns_none(self):
|
|
from litellm.types.utils import ChatCompletionMessageToolCall, Function
|
|
|
|
tc = ChatCompletionMessageToolCall(
|
|
id="call_1", type="function", function=Function(name="fn", arguments="{}")
|
|
)
|
|
service_resp = {
|
|
"choices": [
|
|
{
|
|
"message": {
|
|
"tool_calls": [{"id": "call_1"}],
|
|
"content": "",
|
|
}
|
|
}
|
|
]
|
|
}
|
|
result = RubrikLogger._extract_response_block(service_resp, [tc], "")
|
|
assert result is None
|
|
|
|
def test_some_blocked_returns_explanation(self):
|
|
from litellm.types.utils import ChatCompletionMessageToolCall, Function
|
|
|
|
tc1 = ChatCompletionMessageToolCall(
|
|
id="call_1",
|
|
type="function",
|
|
function=Function(name="fn1", arguments="{}"),
|
|
)
|
|
tc2 = ChatCompletionMessageToolCall(
|
|
id="call_2",
|
|
type="function",
|
|
function=Function(name="fn2", arguments="{}"),
|
|
)
|
|
service_resp = {
|
|
"choices": [
|
|
{
|
|
"message": {
|
|
"tool_calls": [{"id": "call_1"}],
|
|
"content": "blocked fn2",
|
|
}
|
|
}
|
|
]
|
|
}
|
|
result = RubrikLogger._extract_response_block(service_resp, [tc1, tc2], "")
|
|
assert result is not None
|
|
assert "blocked fn2" in result.explanation
|
|
|
|
def test_empty_choices_raises(self):
|
|
with pytest.raises(_MalformedToolBlockingResponseError):
|
|
RubrikLogger._extract_response_block({"choices": []}, [], "")
|
|
|
|
def test_null_tool_calls_treated_as_all_blocked(self):
|
|
from litellm.types.utils import ChatCompletionMessageToolCall, Function
|
|
|
|
tc = ChatCompletionMessageToolCall(
|
|
id="call_1", type="function", function=Function(name="fn", arguments="{}")
|
|
)
|
|
service_resp = {
|
|
"choices": [
|
|
{
|
|
"message": {
|
|
"tool_calls": None,
|
|
"content": "blocked everything",
|
|
}
|
|
}
|
|
]
|
|
}
|
|
result = RubrikLogger._extract_response_block(service_resp, [tc], "")
|
|
assert result is not None
|
|
assert "blocked everything" in result.explanation
|
|
|
|
def test_text_block_detected(self):
|
|
"""When the service replaces the response text wholesale, it's a text block."""
|
|
from litellm.types.utils import ChatCompletionMessageToolCall, Function
|
|
|
|
service_resp = {
|
|
"choices": [
|
|
{
|
|
"message": {
|
|
"tool_calls": [],
|
|
"content": "This content violates policy.",
|
|
}
|
|
}
|
|
]
|
|
}
|
|
result = RubrikLogger._extract_response_block(
|
|
service_resp, [], "Original assistant text."
|
|
)
|
|
assert result is not None
|
|
assert "violates policy" in result.explanation
|
|
|
|
def test_tool_block_with_appended_explanation(self):
|
|
"""When the service appends an explanation to the original text, only the
|
|
appended part is returned as the explanation."""
|
|
from litellm.types.utils import ChatCompletionMessageToolCall, Function
|
|
|
|
tc = ChatCompletionMessageToolCall(
|
|
id="call_1", type="function", function=Function(name="fn", arguments="{}")
|
|
)
|
|
original_text = "Here is my response."
|
|
appended_explanation = "Tool call was blocked."
|
|
service_resp = {
|
|
"choices": [
|
|
{
|
|
"message": {
|
|
"tool_calls": [],
|
|
"content": original_text + "\n\n" + appended_explanation,
|
|
}
|
|
}
|
|
]
|
|
}
|
|
result = RubrikLogger._extract_response_block(
|
|
service_resp, [tc], original_text
|
|
)
|
|
assert result is not None
|
|
assert appended_explanation in result.explanation
|
|
|
|
|
|
# -- Sanitize proxy server request -------------------------------------------
|
|
|
|
|
|
class TestSanitizeProxyServerRequest:
|
|
def test_drops_headers_and_body(self):
|
|
proxy_request = {
|
|
"url": "/chat/completions",
|
|
"method": "POST",
|
|
"headers": {
|
|
"authorization": "Bearer sk-litellm-secret",
|
|
"cookie": "session=abc",
|
|
"content-type": "application/json",
|
|
},
|
|
"body": {"api_key": "sk-upstream-secret", "model": "gpt-4"},
|
|
}
|
|
result = RubrikLogger._sanitize_proxy_server_request(proxy_request)
|
|
assert result == {"url": "/chat/completions", "method": "POST"}
|
|
|
|
def test_none_passthrough(self):
|
|
assert RubrikLogger._sanitize_proxy_server_request(None) is None
|
|
|
|
def test_non_dict_passthrough(self):
|
|
assert RubrikLogger._sanitize_proxy_server_request("not a dict") == "not a dict"
|
|
|
|
def test_partial_dict(self):
|
|
result = RubrikLogger._sanitize_proxy_server_request({"url": "/v1/messages"})
|
|
assert result == {"url": "/v1/messages"}
|
|
|
|
|
|
# -- Resolve model -------------------------------------------------------------
|
|
|
|
|
|
class TestResolveModel:
|
|
def test_model_from_response(self):
|
|
from unittest.mock import Mock
|
|
|
|
response = Mock()
|
|
response.model = "gpt-4"
|
|
result = RubrikLogger._resolve_model({"response": response}, {})
|
|
assert result == "gpt-4"
|
|
|
|
def test_model_from_call_details(self):
|
|
result = RubrikLogger._resolve_model({}, {"model": "claude-3"})
|
|
assert result == "claude-3"
|
|
|
|
def test_fallback_to_unknown(self):
|
|
result = RubrikLogger._resolve_model({}, {})
|
|
assert result == "unknown"
|
|
|
|
def test_empty_model_on_response_returns_unknown(self):
|
|
from unittest.mock import Mock
|
|
|
|
response = Mock()
|
|
response.model = ""
|
|
result = RubrikLogger._resolve_model(
|
|
{"response": response}, {"model": "fallback"}
|
|
)
|
|
assert result == "unknown"
|
|
|
|
|
|
# -- Additional Initialization edge cases ------------------------------------
|
|
|
|
|
|
class TestInitializationEdgeCases:
|
|
def test_batch_size_zero_uses_default(self):
|
|
"""RUBRIK_BATCH_SIZE=0 must warn and fall back to the default."""
|
|
with patch("asyncio.create_task", Mock()):
|
|
with patch.dict(
|
|
os.environ,
|
|
{"RUBRIK_WEBHOOK_URL": "http://host", "RUBRIK_BATCH_SIZE": "0"},
|
|
):
|
|
h = RubrikLogger()
|
|
# Should use default, not 0
|
|
assert h.batch_size > 0
|
|
|
|
def test_batch_size_negative_uses_default(self):
|
|
"""RUBRIK_BATCH_SIZE=-1 must warn and fall back to the default."""
|
|
with patch("asyncio.create_task", Mock()):
|
|
with patch.dict(
|
|
os.environ,
|
|
{"RUBRIK_WEBHOOK_URL": "http://host", "RUBRIK_BATCH_SIZE": "-5"},
|
|
):
|
|
h = RubrikLogger()
|
|
assert h.batch_size > 0
|
|
|
|
|
|
# -- aclose() -----------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
class TestAclose:
|
|
async def test_aclose_cancels_task_does_not_close_shared_client(self, mock_env):
|
|
"""aclose() cancels the periodic flush task but does NOT close the shared
|
|
moderation_client — closing a shared cached client would break other
|
|
RubrikLogger instances that share the same connection pool."""
|
|
with patch("asyncio.create_task", Mock()):
|
|
handler = RubrikLogger()
|
|
|
|
mock_task = Mock()
|
|
mock_task.cancel = Mock()
|
|
handler._periodic_flush_task = mock_task
|
|
|
|
handler.moderation_client = AsyncMock()
|
|
handler.moderation_client.close = AsyncMock()
|
|
|
|
await handler.aclose()
|
|
|
|
mock_task.cancel.assert_called_once()
|
|
handler.moderation_client.close.assert_not_awaited()
|
|
|
|
async def test_aclose_with_none_task_does_not_close_client(self, mock_env):
|
|
"""aclose() with no flush task still does not close the shared client."""
|
|
with patch("asyncio.create_task", Mock()):
|
|
handler = RubrikLogger()
|
|
|
|
handler._periodic_flush_task = None
|
|
handler.moderation_client = AsyncMock()
|
|
handler.moderation_client.close = AsyncMock()
|
|
|
|
await handler.aclose()
|
|
|
|
handler.moderation_client.close.assert_not_awaited()
|
|
|
|
|
|
# -- apply_guardrail edge cases -----------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
class TestApplyGuardrailEdgeCases:
|
|
async def test_unknown_input_type_returns_inputs_unchanged(self, handler):
|
|
"""When input_type is not 'request' or 'response', inputs are returned as-is."""
|
|
inputs = make_inputs_with_tools([make_tool_call_dict("call_1", "tool")])
|
|
result = await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="unknown"
|
|
)
|
|
assert result is inputs
|
|
|
|
async def test_response_with_no_texts_and_no_tool_calls_returns_inputs(self, handler):
|
|
"""_moderate_response early-returns when both texts and tool_calls are empty."""
|
|
from litellm.types.utils import GenericGuardrailAPIInputs
|
|
|
|
inputs = GenericGuardrailAPIInputs()
|
|
result = await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="response"
|
|
)
|
|
assert result is inputs
|
|
|
|
async def test_moderate_response_empty_call_details_emits_warning(self, handler):
|
|
"""When logging_obj is present but model_call_details is empty, a warning is
|
|
logged and moderation proceeds (fail-open on HTTP error)."""
|
|
tc = make_tool_call_dict("call_1", "test_tool")
|
|
inputs = make_inputs_with_tools([tc])
|
|
|
|
logging_obj = Mock()
|
|
logging_obj.model_call_details = {}
|
|
|
|
handler.moderation_client = _echo_service()
|
|
|
|
result = await handler.apply_guardrail(
|
|
inputs=inputs,
|
|
request_data={},
|
|
input_type="response",
|
|
logging_obj=logging_obj,
|
|
)
|
|
assert result is inputs
|
|
|
|
|
|
# -- Prompt moderation --------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
class TestPromptModeration:
|
|
async def test_prompt_moderation_passthrough(self, handler):
|
|
"""Webhook returns {} (empty dict) → inputs returned unchanged."""
|
|
inputs = {"structured_messages": [{"role": "user", "content": "Hello"}]}
|
|
|
|
handler.moderation_client = _mock_service_response({})
|
|
|
|
result = await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="request"
|
|
)
|
|
assert result is inputs
|
|
|
|
async def test_prompt_moderation_blocked_raises(self, handler):
|
|
"""Webhook returns synthetic chat.completion → raises ModifyResponseException."""
|
|
inputs = {
|
|
"structured_messages": [{"role": "user", "content": "Harmful prompt"}],
|
|
"model": "gpt-4",
|
|
}
|
|
|
|
handler.moderation_client = _mock_service_response(
|
|
{
|
|
"choices": [
|
|
{
|
|
"message": {
|
|
"role": "assistant",
|
|
"content": "This request violates our policy.",
|
|
}
|
|
}
|
|
]
|
|
}
|
|
)
|
|
|
|
with pytest.raises(ModifyResponseException) as exc_info:
|
|
await handler.apply_guardrail(
|
|
inputs=inputs, request_data={"model": "gpt-4"}, input_type="request"
|
|
)
|
|
assert "violates our policy" in exc_info.value.message
|
|
|
|
async def test_prompt_moderation_no_messages_skips_moderation(self, handler):
|
|
"""When structured_messages is absent/empty, moderation is skipped."""
|
|
inputs = {"model": "gpt-4"}
|
|
|
|
result = await handler.apply_guardrail(
|
|
inputs=inputs, request_data={}, input_type="request"
|
|
)
|
|
assert result is inputs
|
|
|
|
async def test_prompt_moderation_stashes_logging_obj_on_block(self, handler):
|
|
"""On a prompt block, _stash_block_context must set the blocked flag."""
|
|
inputs = {
|
|
"structured_messages": [{"role": "user", "content": "bad prompt"}],
|
|
}
|
|
|
|
handler.moderation_client = _mock_service_response(
|
|
{
|
|
"choices": [
|
|
{"message": {"role": "assistant", "content": "Blocked."}}
|
|
]
|
|
}
|
|
)
|
|
|
|
logging_obj = Mock()
|
|
logging_obj.model_call_details = {}
|
|
request_data: dict = {}
|
|
|
|
with pytest.raises(ModifyResponseException):
|
|
await handler.apply_guardrail(
|
|
inputs=inputs,
|
|
request_data=request_data,
|
|
input_type="request",
|
|
logging_obj=logging_obj,
|
|
)
|
|
|
|
assert logging_obj.model_call_details.get("_rubrik_blocked") is True
|
|
assert request_data.get("_rubrik_logging_obj") is logging_obj
|
|
|
|
|
|
# -- _stash_block_context -----------------------------------------------------
|
|
|
|
|
|
class TestStashBlockContext:
|
|
def test_with_non_none_logging_obj_sets_flag_and_stashes(self):
|
|
"""Sets _rubrik_blocked flag and stores logging_obj on request_data."""
|
|
logging_obj = Mock()
|
|
logging_obj.model_call_details = {}
|
|
request_data: dict = {}
|
|
|
|
RubrikLogger._stash_block_context(logging_obj, request_data)
|
|
|
|
assert logging_obj.model_call_details["_rubrik_blocked"] is True
|
|
assert request_data["_rubrik_logging_obj"] is logging_obj
|
|
|
|
def test_with_none_logging_obj_stores_none_on_request_data(self):
|
|
"""When logging_obj is None, stores None on request_data (logged as error)."""
|
|
request_data: dict = {"litellm_call_id": "test-id"}
|
|
|
|
RubrikLogger._stash_block_context(None, request_data)
|
|
|
|
assert request_data["_rubrik_logging_obj"] is None
|
|
|
|
|
|
# -- _normalize_tool_calls duck-typed -----------------------------------------
|
|
|
|
|
|
class TestNormalizeToolCallsDuckTyped:
|
|
def test_duck_typed_object_with_id_and_function_attrs(self):
|
|
"""Objects that have .id and .function attrs but are not
|
|
ChatCompletionMessageToolCall are handled by the third branch."""
|
|
from litellm.types.utils import Function
|
|
|
|
tc = Mock()
|
|
tc.id = "call_duck"
|
|
tc.type = "function"
|
|
tc.function = Function(name="duck_tool", arguments='{"x": 1}')
|
|
# Make isinstance(..., ChatCompletionMessageToolCall) return False
|
|
# by using a plain Mock (not a ChatCompletionMessageToolCall subclass)
|
|
|
|
result = RubrikLogger._normalize_tool_calls([tc])
|
|
assert len(result) == 1
|
|
assert result[0].id == "call_duck"
|
|
assert result[0].function.name == "duck_tool"
|
|
|
|
def test_duck_typed_without_type_defaults_to_function(self):
|
|
"""getattr(tc, "type", None) falls back to "function" when absent."""
|
|
from litellm.types.utils import Function
|
|
|
|
tc = Mock(spec=["id", "function"]) # no .type attr
|
|
tc.id = "call_no_type"
|
|
tc.function = Function(name="fn", arguments="{}")
|
|
|
|
result = RubrikLogger._normalize_tool_calls([tc])
|
|
assert result[0].type == "function"
|
|
|
|
|
|
# -- _flatten_messages_for_moderation -----------------------------------------
|
|
|
|
|
|
class TestFlattenMessagesForModeration:
|
|
def test_plain_string_content_preserved(self):
|
|
messages = [{"role": "user", "content": "Hello world"}]
|
|
result = RubrikLogger._flatten_messages_for_moderation(messages)
|
|
assert len(result) == 1
|
|
assert result[0]["role"] == "user"
|
|
assert result[0]["content"] == "Hello world"
|
|
|
|
def test_content_list_flattened_to_string(self):
|
|
"""Content as a list of parts (e.g. Anthropic multi-part) is flattened."""
|
|
messages = [
|
|
{
|
|
"role": "user",
|
|
"content": [
|
|
{"type": "text", "text": "Hello from parts"},
|
|
],
|
|
}
|
|
]
|
|
result = RubrikLogger._flatten_messages_for_moderation(messages)
|
|
assert len(result) == 1
|
|
assert result[0]["role"] == "user"
|
|
assert "Hello from parts" in result[0]["content"]
|
|
|
|
def test_non_dict_messages_skipped(self):
|
|
"""Non-dict entries in the messages list are silently skipped."""
|
|
messages = [
|
|
"raw string message",
|
|
{"role": "user", "content": "valid"},
|
|
]
|
|
result = RubrikLogger._flatten_messages_for_moderation(messages)
|
|
assert len(result) == 1
|
|
assert result[0]["content"] == "valid"
|
|
|
|
def test_none_messages_returns_empty(self):
|
|
result = RubrikLogger._flatten_messages_for_moderation(None)
|
|
assert result == ()
|
|
|
|
def test_multiple_messages_preserved_in_order(self):
|
|
messages = [
|
|
{"role": "system", "content": "You are helpful."},
|
|
{"role": "user", "content": "Question?"},
|
|
]
|
|
result = RubrikLogger._flatten_messages_for_moderation(messages)
|
|
assert len(result) == 2
|
|
assert result[0]["role"] == "system"
|
|
assert result[1]["role"] == "user"
|
|
|
|
|
|
# -- _build_prompt_moderation_payload -----------------------------------------
|
|
|
|
|
|
class TestBuildPromptModerationPayload:
|
|
def test_payload_includes_tools_when_present(self):
|
|
inputs = {
|
|
"model": "gpt-4",
|
|
"structured_messages": [{"role": "user", "content": "hi"}],
|
|
"tools": [{"type": "function", "function": {"name": "fn"}}],
|
|
}
|
|
payload = RubrikLogger._build_prompt_moderation_payload(inputs, {})
|
|
assert payload["tools"] == [{"type": "function", "function": {"name": "fn"}}]
|
|
|
|
def test_payload_includes_user_when_present(self):
|
|
inputs = {
|
|
"structured_messages": [{"role": "user", "content": "hi"}],
|
|
}
|
|
request_data = {"user": "alice"}
|
|
payload = RubrikLogger._build_prompt_moderation_payload(inputs, request_data)
|
|
assert payload["user"] == "alice"
|
|
|
|
def test_payload_uses_explicit_correlation_key(self):
|
|
inputs = {"structured_messages": [{"role": "user", "content": "hi"}]}
|
|
request_data = {
|
|
"correlation_key": "corr-123",
|
|
"litellm_call_id": "litellm-456",
|
|
}
|
|
payload = RubrikLogger._build_prompt_moderation_payload(inputs, request_data)
|
|
assert payload["correlation_key"] == "corr-123"
|
|
|
|
def test_payload_falls_back_to_litellm_call_id(self):
|
|
"""When correlation_key is absent, litellm_call_id is used."""
|
|
inputs = {"structured_messages": [{"role": "user", "content": "hi"}]}
|
|
request_data = {"litellm_call_id": "litellm-789"}
|
|
payload = RubrikLogger._build_prompt_moderation_payload(inputs, request_data)
|
|
assert payload["correlation_key"] == "litellm-789"
|
|
|
|
def test_payload_omits_optional_fields_when_absent(self):
|
|
inputs = {"structured_messages": [{"role": "user", "content": "hi"}]}
|
|
payload = RubrikLogger._build_prompt_moderation_payload(inputs, {})
|
|
assert "tools" not in payload
|
|
assert "user" not in payload
|
|
assert "correlation_key" not in payload
|
|
|
|
|
|
# -- _extract_request_data tools preference -----------------------------------
|
|
|
|
|
|
class TestExtractRequestDataToolsPreference:
|
|
def test_prefers_tools_from_request_data_over_optional_params(self):
|
|
"""When 'tools' key exists in request_data, it wins over optional_params."""
|
|
call_details = {
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"model": "gpt-4",
|
|
"optional_params": {
|
|
"tools": [{"type": "function", "function": {"name": "from_optional"}}]
|
|
},
|
|
}
|
|
request_data = {
|
|
"tools": [{"type": "function", "function": {"name": "from_request"}}]
|
|
}
|
|
result = RubrikLogger._extract_request_data(call_details, request_data)
|
|
assert result["tools"] == [
|
|
{"type": "function", "function": {"name": "from_request"}}
|
|
]
|
|
|
|
def test_falls_back_to_optional_params_when_not_in_request_data(self):
|
|
call_details = {
|
|
"optional_params": {
|
|
"tools": [{"type": "function", "function": {"name": "from_optional"}}]
|
|
}
|
|
}
|
|
result = RubrikLogger._extract_request_data(call_details, {})
|
|
assert result["tools"] == [
|
|
{"type": "function", "function": {"name": "from_optional"}}
|
|
]
|
|
|
|
def test_explicit_empty_list_in_request_data_is_forwarded(self):
|
|
"""An explicit empty tools list signals 'no tools' to the moderation service."""
|
|
call_details = {
|
|
"optional_params": {
|
|
"tools": [{"type": "function", "function": {"name": "from_optional"}}]
|
|
}
|
|
}
|
|
request_data = {"tools": []}
|
|
result = RubrikLogger._extract_request_data(call_details, request_data)
|
|
assert result["tools"] == []
|
|
|
|
|
|
# -- _extract_prompt_refusal --------------------------------------------------
|
|
|
|
|
|
class TestExtractPromptRefusal:
|
|
def test_passthrough_response_returns_none(self):
|
|
"""Empty dict (passthrough) → None."""
|
|
assert RubrikLogger._extract_prompt_refusal({}) is None
|
|
|
|
def test_no_choices_returns_none(self):
|
|
assert RubrikLogger._extract_prompt_refusal({"choices": []}) is None
|
|
|
|
def test_block_response_returns_content(self):
|
|
service_response = {
|
|
"choices": [{"message": {"content": "Request blocked by Rubrik."}}]
|
|
}
|
|
result = RubrikLogger._extract_prompt_refusal(service_response)
|
|
assert result == "Request blocked by Rubrik."
|
|
|
|
def test_empty_content_falls_back_to_default_message(self):
|
|
"""When content is empty string or falsy, falls back to default refusal."""
|
|
service_response = {"choices": [{"message": {"content": ""}}]}
|
|
result = RubrikLogger._extract_prompt_refusal(service_response)
|
|
assert result == "Request blocked by policy."
|
|
|
|
def test_none_content_falls_back_to_default_message(self):
|
|
service_response = {"choices": [{"message": {"content": None}}]}
|
|
result = RubrikLogger._extract_prompt_refusal(service_response)
|
|
assert result == "Request blocked by policy."
|
|
|
|
|
|
# -- _prepend_system_prompt exception path ------------------------------------
|
|
|
|
|
|
class TestPrependSystemPromptException:
|
|
def test_exception_during_unpack_is_caught_and_logged(self):
|
|
"""When an exception is raised inside _prepend_system_prompt, it is swallowed."""
|
|
|
|
class ExplodingList(list):
|
|
def __iter__(self):
|
|
raise RuntimeError("iteration error!")
|
|
|
|
payload = {"messages": ExplodingList()}
|
|
source = {"system": "You are an assistant."}
|
|
|
|
# Must not raise
|
|
RubrikLogger._prepend_system_prompt(payload, source)
|
|
|
|
|
|
# -- _append_and_maybe_flush batch trigger ------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
class TestAppendAndMaybeFlush:
|
|
async def test_flush_triggered_when_queue_reaches_batch_size(self, handler):
|
|
"""flush_queue is called when the queue length reaches batch_size."""
|
|
handler.batch_size = 2
|
|
handler.flush_queue = AsyncMock()
|
|
|
|
await handler._append_and_maybe_flush({"msg": "a"})
|
|
handler.flush_queue.assert_not_called()
|
|
|
|
await handler._append_and_maybe_flush({"msg": "b"})
|
|
handler.flush_queue.assert_called_once()
|
|
|
|
async def test_no_flush_before_batch_size(self, handler):
|
|
handler.batch_size = 5
|
|
handler.flush_queue = AsyncMock()
|
|
|
|
for i in range(4):
|
|
await handler._append_and_maybe_flush({"msg": str(i)})
|
|
|
|
handler.flush_queue.assert_not_called()
|
|
|
|
|
|
# -- _enqueue_log_event exception handling ------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
class TestEnqueueLogEventExceptions:
|
|
async def test_exception_from_prepare_log_payload_is_caught(self, handler):
|
|
"""Exceptions raised by _prepare_log_payload are caught and logged."""
|
|
handler._prepare_log_payload = AsyncMock(
|
|
side_effect=RuntimeError("payload error")
|
|
)
|
|
|
|
# Must not raise
|
|
await handler._enqueue_log_event(
|
|
{"standard_logging_object": {"messages": [], "response": ""}}, "test"
|
|
)
|
|
assert len(handler.log_queue) == 0
|
|
|
|
|
|
# -- async_log_success_event skip when _rubrik_blocked ------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
class TestSuccessEventBlockedSkip:
|
|
async def test_skips_enqueue_when_rubrik_blocked_flag_set(self, handler):
|
|
"""When kwargs['_rubrik_blocked'] is True, the event is not enqueued."""
|
|
kwargs = {
|
|
"_rubrik_blocked": True,
|
|
"litellm_call_id": "blocked-call-123",
|
|
"standard_logging_object": {
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"response": "hello",
|
|
},
|
|
}
|
|
await handler.async_log_success_event(
|
|
kwargs=kwargs, response_obj=None, start_time=None, end_time=None
|
|
)
|
|
assert len(handler.log_queue) == 0
|
|
|
|
|
|
# -- async_post_call_failure_hook ---------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
class TestPostCallFailureHook:
|
|
async def test_non_modify_exception_returns_immediately(self, handler, user_api_key_dict):
|
|
"""Non-ModifyResponseException causes a no-op."""
|
|
await handler.async_post_call_failure_hook(
|
|
request_data={"litellm_call_id": "test"},
|
|
original_exception=ValueError("unrelated error"),
|
|
user_api_key_dict=user_api_key_dict,
|
|
)
|
|
assert len(handler.log_queue) == 0
|
|
|
|
async def test_modify_exception_without_stashed_logging_obj_emits_warning(
|
|
self, handler, user_api_key_dict
|
|
):
|
|
"""ModifyResponseException with no _rubrik_logging_obj → warning, no enqueue."""
|
|
request_data = {"litellm_call_id": "test-123", "model": "gpt-4"}
|
|
exc = ModifyResponseException(
|
|
message="blocked",
|
|
model="gpt-4",
|
|
request_data=request_data,
|
|
guardrail_name="rubrik",
|
|
)
|
|
|
|
await handler.async_post_call_failure_hook(
|
|
request_data=request_data,
|
|
original_exception=exc,
|
|
user_api_key_dict=user_api_key_dict,
|
|
)
|
|
assert len(handler.log_queue) == 0
|
|
|
|
async def test_modify_exception_with_valid_logging_obj_enqueues_payload(
|
|
self, handler, user_api_key_dict
|
|
):
|
|
"""ModifyResponseException + stashed logging_obj → builds and enqueues."""
|
|
logging_obj = Mock()
|
|
logging_obj.model_call_details = {
|
|
"litellm_call_id": "call-abc",
|
|
"model": "gpt-4",
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
"standard_logging_object": {
|
|
"id": "chatcmpl-original",
|
|
"model": "gpt-4",
|
|
"response": "original",
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
},
|
|
"metadata": {},
|
|
}
|
|
|
|
request_data = {"_rubrik_logging_obj": logging_obj}
|
|
exc = ModifyResponseException(
|
|
message="blocked by policy",
|
|
model="gpt-4",
|
|
request_data=request_data,
|
|
guardrail_name="rubrik",
|
|
)
|
|
|
|
handler.batch_size = 10**6 # disable auto-flush
|
|
await handler.async_post_call_failure_hook(
|
|
request_data=request_data,
|
|
original_exception=exc,
|
|
user_api_key_dict=user_api_key_dict,
|
|
)
|
|
assert len(handler.log_queue) == 1
|
|
assert "ModifyResponseException" in handler.log_queue[0]["response"]
|
|
|
|
async def test_logging_obj_popped_from_request_data(self, handler, user_api_key_dict):
|
|
"""_rubrik_logging_obj must be popped from request_data so it is not
|
|
forwarded downstream."""
|
|
logging_obj = Mock()
|
|
logging_obj.model_call_details = {
|
|
"litellm_call_id": "call-pop",
|
|
"model": "gpt-4",
|
|
"messages": [],
|
|
"standard_logging_object": {
|
|
"id": "chatcmpl-pop",
|
|
"model": "gpt-4",
|
|
"response": "text",
|
|
"messages": [],
|
|
},
|
|
"metadata": {},
|
|
}
|
|
|
|
request_data = {"_rubrik_logging_obj": logging_obj}
|
|
exc = ModifyResponseException(
|
|
message="popped",
|
|
model="gpt-4",
|
|
request_data=request_data,
|
|
guardrail_name="rubrik",
|
|
)
|
|
|
|
handler.batch_size = 10**6
|
|
await handler.async_post_call_failure_hook(
|
|
request_data=request_data,
|
|
original_exception=exc,
|
|
user_api_key_dict=user_api_key_dict,
|
|
)
|
|
assert "_rubrik_logging_obj" not in request_data
|
|
|
|
async def test_build_and_enqueue_swallows_attribute_error_from_prepare_payload(
|
|
self, handler, user_api_key_dict
|
|
):
|
|
"""When _prepare_block_failure_payload raises AttributeError/KeyError/TypeError,
|
|
the error is logged and the event is silently dropped (lines 806-812)."""
|
|
logging_obj = Mock()
|
|
# Make model_call_details.get() raise TypeError
|
|
logging_obj.model_call_details = None # .get() will raise AttributeError
|
|
|
|
exc = ModifyResponseException(
|
|
message="blocked",
|
|
model="gpt-4",
|
|
request_data={},
|
|
guardrail_name="rubrik",
|
|
)
|
|
|
|
# Must not raise
|
|
await handler._build_and_enqueue_block_event(logging_obj, exc, None, user_api_key_dict)
|
|
assert len(handler.log_queue) == 0
|
|
|
|
async def test_build_and_enqueue_swallows_flush_exception(self, handler, user_api_key_dict):
|
|
"""When _append_and_maybe_flush raises, the error is logged (lines 816-817)."""
|
|
logging_obj = Mock()
|
|
logging_obj.model_call_details = {
|
|
"litellm_call_id": "call-flush-err",
|
|
"model": "gpt-4",
|
|
"messages": [],
|
|
"standard_logging_object": {
|
|
"id": "id-flush-err",
|
|
"model": "gpt-4",
|
|
"response": "text",
|
|
"messages": [],
|
|
},
|
|
"metadata": {},
|
|
}
|
|
|
|
exc = ModifyResponseException(
|
|
message="blocked",
|
|
model="gpt-4",
|
|
request_data={},
|
|
guardrail_name="rubrik",
|
|
)
|
|
|
|
handler._append_and_maybe_flush = AsyncMock(
|
|
side_effect=RuntimeError("flush failed")
|
|
)
|
|
|
|
# Must not raise
|
|
await handler._build_and_enqueue_block_event(logging_obj, exc, None, user_api_key_dict)
|
|
|
|
|
|
# -- _prepare_block_failure_payload and _build_fallback_payload ---------------
|
|
|
|
|
|
class TestPrepareBlockFailurePayload:
|
|
def test_uses_standard_logging_object_when_present(self, handler, user_api_key_dict):
|
|
"""When standard_logging_object is on model_call_details, it is used as base."""
|
|
logging_obj = Mock()
|
|
logging_obj.model_call_details = {
|
|
"litellm_call_id": "call-slo",
|
|
"model": "gpt-4",
|
|
"standard_logging_object": {
|
|
"id": "chatcmpl-original",
|
|
"model": "gpt-4",
|
|
"response": "original response",
|
|
"messages": [{"role": "user", "content": "hi"}],
|
|
},
|
|
"metadata": {},
|
|
}
|
|
exc = ModifyResponseException(
|
|
message="blocked",
|
|
model="gpt-4",
|
|
request_data={},
|
|
guardrail_name="rubrik",
|
|
)
|
|
|
|
payload = handler._prepare_block_failure_payload(logging_obj, exc, user_api_key_dict)
|
|
|
|
assert "ModifyResponseException: blocked" in payload["response"]
|
|
assert payload["id"] == "call-slo"
|
|
|
|
def test_standard_logging_object_identity_is_not_overwritten(self, handler, user_api_key_dict):
|
|
"""A streamed block can arrive with the object populated; it keeps its own identity."""
|
|
logging_obj = Mock()
|
|
logging_obj.model_call_details = {
|
|
"litellm_call_id": "call-slo-identity",
|
|
"model": "gpt-4",
|
|
"standard_logging_object": {
|
|
"id": "chatcmpl-original",
|
|
"model": "gpt-4",
|
|
"response": "original response",
|
|
"messages": [],
|
|
"metadata": {"user_api_key_hash": "hash-from-standard-logging-object"},
|
|
},
|
|
}
|
|
exc = ModifyResponseException(
|
|
message="blocked",
|
|
model="gpt-4",
|
|
request_data={},
|
|
guardrail_name="rubrik",
|
|
)
|
|
|
|
payload = handler._prepare_block_failure_payload(logging_obj, exc, user_api_key_dict)
|
|
|
|
assert payload["metadata"]["user_api_key_hash"] == "hash-from-standard-logging-object"
|
|
|
|
def test_uses_fallback_when_standard_logging_object_absent(self, handler, user_api_key_dict):
|
|
"""When standard_logging_object is absent, _build_fallback_payload is used."""
|
|
from datetime import datetime
|
|
|
|
logging_obj = Mock()
|
|
logging_obj.model_call_details = {
|
|
"litellm_call_id": "call-fallback",
|
|
"model": "claude-3",
|
|
"messages": [{"role": "user", "content": "question"}],
|
|
"optional_params": {"temperature": 0.5},
|
|
"metadata": {"headers": {"host": "127.0.0.1:4000", "user-agent": "curl/8.7.1"}},
|
|
"start_time": datetime(2024, 6, 1),
|
|
}
|
|
exc = ModifyResponseException(
|
|
message="prompt blocked",
|
|
model="claude-3",
|
|
request_data={},
|
|
guardrail_name="rubrik",
|
|
)
|
|
|
|
payload = handler._prepare_block_failure_payload(logging_obj, exc, user_api_key_dict)
|
|
|
|
assert payload["id"] == "call-fallback"
|
|
assert payload["model"] == "claude-3"
|
|
assert payload["model_group"] == "claude-3"
|
|
assert "ModifyResponseException: prompt blocked" in payload["response"]
|
|
assert payload["status"] == "failure"
|
|
|
|
def test_fallback_payload_without_start_time(self, handler, user_api_key_dict):
|
|
"""_build_fallback_payload handles missing start_time gracefully."""
|
|
logging_obj = Mock()
|
|
logging_obj.model_call_details = {
|
|
"litellm_call_id": "call-notime",
|
|
"model": "gpt-4",
|
|
"messages": [],
|
|
"optional_params": {},
|
|
"metadata": {},
|
|
}
|
|
exc = ModifyResponseException(
|
|
message="blocked",
|
|
model="gpt-4",
|
|
request_data={},
|
|
guardrail_name="rubrik",
|
|
)
|
|
|
|
payload = handler._prepare_block_failure_payload(logging_obj, exc, user_api_key_dict)
|
|
assert payload["startTime"] is None
|
|
|
|
|
|
class TestBlockPayloadCallerAttribution:
|
|
"""A block log must identify the caller that triggered it.
|
|
|
|
The enriched litellm metadata lives under
|
|
``model_call_details["litellm_params"]["metadata"]``, never at the top
|
|
level, so sourcing identity from ``call_details["metadata"]`` yielded an
|
|
empty string for every block. Identity comes from the authenticated
|
|
``user_api_key_dict`` the failure hook is handed.
|
|
"""
|
|
|
|
def _blocked_call_details(self):
|
|
return {
|
|
"litellm_call_id": "call-attr",
|
|
"model": "claude-3",
|
|
"messages": [{"role": "user", "content": "question"}],
|
|
"optional_params": {},
|
|
"metadata": {"headers": {"host": "127.0.0.1:4000", "user-agent": "curl/8.7.1"}},
|
|
}
|
|
|
|
def test_fallback_payload_identifies_the_caller(self, handler, user_api_key_dict):
|
|
payload = handler._build_fallback_payload(self._blocked_call_details(), user_api_key_dict)
|
|
|
|
metadata = payload["metadata"]
|
|
assert metadata["user_api_key_hash"] == user_api_key_dict.api_key
|
|
assert metadata["user_api_key_alias"] == "rubrik-probe-key"
|
|
assert metadata["user_api_key_user_id"] == "probe-user-1"
|
|
assert metadata["user_api_key_team_id"] == "probe-team-1"
|
|
assert metadata["user_api_key_org_id"] == "probe-org-1"
|
|
|
|
def test_metadata_covers_the_full_caller_key_set(self, handler, user_api_key_dict):
|
|
"""A block log and a success log agree on the caller key set."""
|
|
from litellm.types.utils import StandardLoggingUserAPIKeyMetadata
|
|
|
|
payload = handler._build_fallback_payload(self._blocked_call_details(), user_api_key_dict)
|
|
|
|
expected = StandardLoggingUserAPIKeyMetadata.__required_keys__ | StandardLoggingUserAPIKeyMetadata.__optional_keys__
|
|
assert set(payload["metadata"]) == set(expected)
|
|
|
|
def test_virtual_key_is_logged_hashed(self, handler):
|
|
"""A virtual key reaches the webhook as its hash, never as the raw token."""
|
|
raw = "sk-block-attribution-test"
|
|
payload = handler._build_fallback_payload(
|
|
self._blocked_call_details(), UserAPIKeyAuth(api_key=raw)
|
|
)
|
|
|
|
assert payload["metadata"]["user_api_key_hash"] not in (raw, "")
|
|
|
|
def test_request_header_metadata_is_not_used_as_identity(self, handler, user_api_key_dict):
|
|
"""The pre-fix source is present and misleading; it must not win."""
|
|
call_details = self._blocked_call_details()
|
|
call_details["metadata"]["user_api_key_hash"] = "stale-hash-from-request-metadata"
|
|
|
|
payload = handler._build_fallback_payload(call_details, user_api_key_dict)
|
|
|
|
assert payload["metadata"]["user_api_key_hash"] == user_api_key_dict.api_key
|
|
|
|
async def test_enqueued_block_event_carries_attribution(self, handler, user_api_key_dict):
|
|
"""End of the real hook chain: what actually lands on the Rubrik queue."""
|
|
logging_obj = Mock()
|
|
logging_obj.model_call_details = self._blocked_call_details()
|
|
request_data = {"litellm_call_id": "call-attr", "_rubrik_logging_obj": logging_obj}
|
|
exc = ModifyResponseException(
|
|
message="prompt blocked",
|
|
model="claude-3",
|
|
request_data=request_data,
|
|
guardrail_name="rubrik",
|
|
)
|
|
|
|
await handler.async_post_call_failure_hook(
|
|
request_data=request_data,
|
|
original_exception=exc,
|
|
user_api_key_dict=user_api_key_dict,
|
|
)
|
|
|
|
assert len(handler.log_queue) == 1
|
|
metadata = handler.log_queue[0]["metadata"]
|
|
assert metadata["user_api_key_hash"] == user_api_key_dict.api_key
|
|
assert metadata["user_api_key_user_id"] == "probe-user-1"
|
|
|
|
|
|
# -- async_send_batch empty queue and flush_queue edge cases ------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
class TestQueueEdgeCases:
|
|
async def test_async_send_batch_returns_early_on_empty_queue(self, handler):
|
|
"""async_send_batch is a no-op when the queue is empty."""
|
|
handler.async_httpx_client = AsyncMock()
|
|
await handler.async_send_batch()
|
|
handler.async_httpx_client.post.assert_not_called()
|
|
|
|
async def test_flush_queue_returns_early_when_flush_lock_is_none(self, handler):
|
|
"""flush_queue is a no-op when flush_lock is None."""
|
|
handler.flush_lock = None
|
|
handler.log_queue = [{"msg": "a"}]
|
|
handler.async_httpx_client = AsyncMock()
|
|
|
|
await handler.flush_queue()
|
|
handler.async_httpx_client.post.assert_not_called()
|
|
|
|
async def test_flush_queue_returns_early_when_queue_empty_inside_lock(self, handler):
|
|
"""flush_queue acquires the lock then no-ops when the queue is empty."""
|
|
handler.log_queue = []
|
|
handler.async_httpx_client = AsyncMock()
|
|
|
|
await handler.flush_queue()
|
|
handler.async_httpx_client.post.assert_not_called()
|
|
|
|
|
|
# -- _post_json non-dict response ---------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
class TestPostJson:
|
|
async def test_raises_type_error_for_list_response(self, handler):
|
|
"""When the service returns a JSON array instead of a dict, TypeError is raised."""
|
|
mock_client = AsyncMock()
|
|
mock_resp = Mock()
|
|
mock_resp.json.return_value = ["not", "a", "dict"]
|
|
mock_resp.raise_for_status = Mock()
|
|
mock_client.post = AsyncMock(return_value=mock_resp)
|
|
handler.moderation_client = mock_client
|
|
|
|
with pytest.raises(TypeError, match="non-dict JSON"):
|
|
await handler._post_json(
|
|
handler.prompt_moderation_endpoint, {}, "Test service"
|
|
)
|
|
|
|
async def test_raises_type_error_for_string_response(self, handler):
|
|
"""A bare string response also raises TypeError."""
|
|
mock_client = AsyncMock()
|
|
mock_resp = Mock()
|
|
mock_resp.json.return_value = "blocked"
|
|
mock_resp.raise_for_status = Mock()
|
|
mock_client.post = AsyncMock(return_value=mock_resp)
|
|
handler.moderation_client = mock_client
|
|
|
|
with pytest.raises(TypeError, match="non-dict JSON"):
|
|
await handler._post_json(
|
|
handler.response_moderation_endpoint, {}, "Test service"
|
|
)
|