mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-01 01:18:34 +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>
1294 lines
48 KiB
Python
1294 lines
48 KiB
Python
"""
|
|
Test Azure Sentinel logging integration
|
|
"""
|
|
|
|
import asyncio
|
|
import json
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import httpx
|
|
import pytest
|
|
from httpx import Request, Response
|
|
from pydantic import BaseModel, computed_field
|
|
|
|
from litellm.integrations.azure_sentinel.azure_sentinel import AzureSentinelLogger
|
|
from litellm.llms.custom_httpx.http_handler import MaskedHTTPStatusError
|
|
from litellm.types.integrations.azure_sentinel import AZURE_SENTINEL_MAX_PAYLOAD_SIZE_BYTES
|
|
from litellm.types.utils import StandardAuditLogPayload, StandardLoggingPayload
|
|
|
|
|
|
def _close_periodic_flush_task(coro):
|
|
coro.close()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_azure_sentinel_oauth_and_send_batch():
|
|
"""Test that Azure Sentinel logger gets OAuth token and sends batch to API"""
|
|
test_dcr_id = "dcr-test123456789"
|
|
test_endpoint = "https://test-dce.eastus-1.ingest.monitor.azure.com"
|
|
test_tenant_id = "test-tenant-id"
|
|
test_client_id = "test-client-id"
|
|
test_client_secret = "test-client-secret"
|
|
|
|
with patch("asyncio.create_task", side_effect=_close_periodic_flush_task):
|
|
logger = AzureSentinelLogger(
|
|
dcr_immutable_id=test_dcr_id,
|
|
endpoint=test_endpoint,
|
|
tenant_id=test_tenant_id,
|
|
client_id=test_client_id,
|
|
client_secret=test_client_secret,
|
|
)
|
|
|
|
# Create test payload
|
|
standard_payload = StandardLoggingPayload(
|
|
id="test_id",
|
|
call_type="completion",
|
|
model="gpt-3.5-turbo",
|
|
status="success",
|
|
messages=[{"role": "user", "content": "Hello"}],
|
|
response={"choices": [{"message": {"content": "Hi"}}]},
|
|
)
|
|
|
|
# Add to queue
|
|
logger.log_queue.append(standard_payload)
|
|
|
|
mock_token_response = MagicMock()
|
|
mock_token_response.status_code = 200
|
|
mock_token_response.json = MagicMock(
|
|
return_value={
|
|
"access_token": "test-bearer-token",
|
|
"expires_in": 3600,
|
|
}
|
|
)
|
|
mock_token_response.text = "Success"
|
|
|
|
# Mock API response
|
|
mock_api_response = MagicMock()
|
|
mock_api_response.status_code = 204
|
|
mock_api_response.text = "Success"
|
|
|
|
# Mock HTTP client - first call for token, second for API
|
|
async def mock_post(*args, **kwargs):
|
|
if "oauth2/v2.0/token" in kwargs.get("url", ""):
|
|
return mock_token_response
|
|
return mock_api_response
|
|
|
|
logger.async_httpx_client.post = AsyncMock(side_effect=mock_post)
|
|
|
|
# Send batch
|
|
await logger.async_send_batch()
|
|
|
|
# Verify OAuth token request was made
|
|
assert logger.async_httpx_client.post.called
|
|
|
|
# Verify API request was made
|
|
call_count = logger.async_httpx_client.post.call_count
|
|
assert call_count >= 2 # At least token + API call
|
|
|
|
# Get the API call (last call)
|
|
api_call_args = logger.async_httpx_client.post.call_args_list[-1]
|
|
assert test_dcr_id in api_call_args.kwargs["url"]
|
|
assert test_endpoint in api_call_args.kwargs["url"]
|
|
|
|
# Verify headers
|
|
headers = api_call_args.kwargs["headers"]
|
|
assert headers["Content-Type"] == "application/json"
|
|
assert "Authorization" in headers
|
|
assert headers["Authorization"].startswith("Bearer ")
|
|
|
|
# Verify queue is cleared
|
|
assert len(logger.log_queue) == 0
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_azure_sentinel_queues_audit_log_event():
|
|
"""Test that Azure Sentinel supports direct audit log callbacks"""
|
|
with patch("asyncio.create_task", side_effect=_close_periodic_flush_task):
|
|
logger = AzureSentinelLogger(
|
|
dcr_immutable_id="dcr-test123456789",
|
|
endpoint="https://test-dce.eastus-1.ingest.monitor.azure.com",
|
|
tenant_id="test-tenant-id",
|
|
client_id="test-client-id",
|
|
client_secret="test-client-secret",
|
|
)
|
|
|
|
logger.batch_size = 2
|
|
logger.async_send_audit_batch = AsyncMock()
|
|
|
|
audit_log = StandardAuditLogPayload(
|
|
id="audit-123",
|
|
updated_at="2026-05-06T04:39:00+00:00",
|
|
changed_by="user-1",
|
|
changed_by_api_key="sk-test",
|
|
action="created",
|
|
table_name="LiteLLM_TeamTable",
|
|
object_id="team-1",
|
|
before_value=None,
|
|
updated_values='{"team_alias": "sentinel-demo"}',
|
|
)
|
|
|
|
await logger.async_log_audit_log_event(audit_log)
|
|
|
|
assert logger.audit_log_queue == [audit_log]
|
|
logger.async_send_audit_batch.assert_not_called()
|
|
|
|
await logger.async_log_audit_log_event(audit_log)
|
|
|
|
assert logger.audit_log_queue == [audit_log, audit_log]
|
|
logger.async_send_audit_batch.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_azure_sentinel_sends_audit_log_payload_to_ingestion_api():
|
|
"""Test that queued audit logs are sent to Azure Monitor Logs Ingestion"""
|
|
with patch("asyncio.create_task", side_effect=_close_periodic_flush_task):
|
|
logger = AzureSentinelLogger(
|
|
dcr_immutable_id="dcr-test123456789",
|
|
endpoint="https://test-dce.eastus-1.ingest.monitor.azure.com",
|
|
tenant_id="test-tenant-id",
|
|
client_id="test-client-id",
|
|
client_secret="test-client-secret",
|
|
)
|
|
|
|
audit_log = StandardAuditLogPayload(
|
|
id="audit-123",
|
|
updated_at="2026-05-06T04:39:00+00:00",
|
|
changed_by="user-1",
|
|
changed_by_api_key="sk-test",
|
|
action="created",
|
|
table_name="LiteLLM_TeamTable",
|
|
object_id="team-1",
|
|
before_value=None,
|
|
updated_values='{"team_alias": "sentinel-demo"}',
|
|
)
|
|
await logger.async_log_audit_log_event(audit_log)
|
|
|
|
mock_token_response = MagicMock()
|
|
mock_token_response.status_code = 200
|
|
mock_token_response.json = MagicMock(
|
|
return_value={
|
|
"access_token": "test-bearer-token",
|
|
"expires_in": 3600,
|
|
}
|
|
)
|
|
mock_token_response.text = "Success"
|
|
|
|
mock_api_response = MagicMock()
|
|
mock_api_response.status_code = 204
|
|
mock_api_response.text = "Success"
|
|
|
|
async def mock_post(*args, **kwargs):
|
|
if "oauth2/v2.0/token" in kwargs.get("url", ""):
|
|
return mock_token_response
|
|
return mock_api_response
|
|
|
|
logger.async_httpx_client.post = AsyncMock(side_effect=mock_post)
|
|
|
|
await logger.flush_queue()
|
|
|
|
api_call_args = logger.async_httpx_client.post.call_args_list[-1]
|
|
body = json.loads(api_call_args.kwargs["data"].decode("utf-8"))
|
|
assert body == [audit_log]
|
|
assert "dcr-test123456789" in api_call_args.kwargs["url"]
|
|
assert "Custom-LiteLLM" in api_call_args.kwargs["url"]
|
|
assert len(logger.audit_log_queue) == 0
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_azure_sentinel_flushes_standard_and_audit_logs_separately():
|
|
"""Test mixed callback roles do not send schema-mismatched batches."""
|
|
with patch("asyncio.create_task", side_effect=_close_periodic_flush_task):
|
|
logger = AzureSentinelLogger(
|
|
dcr_immutable_id="dcr-test123456789",
|
|
stream_name="Custom-LiteLLM-Standard",
|
|
audit_stream_name="Custom-LiteLLM-Audit",
|
|
endpoint="https://test-dce.eastus-1.ingest.monitor.azure.com",
|
|
tenant_id="test-tenant-id",
|
|
client_id="test-client-id",
|
|
client_secret="test-client-secret",
|
|
)
|
|
|
|
standard_payload = StandardLoggingPayload(
|
|
id="standard-123",
|
|
call_type="completion",
|
|
model="gpt-3.5-turbo",
|
|
status="success",
|
|
messages=[{"role": "user", "content": "Hello"}],
|
|
response={"choices": [{"message": {"content": "Hi"}}]},
|
|
)
|
|
audit_log = StandardAuditLogPayload(
|
|
id="audit-123",
|
|
updated_at="2026-05-06T04:39:00+00:00",
|
|
changed_by="user-1",
|
|
changed_by_api_key="sk-test",
|
|
action="created",
|
|
table_name="LiteLLM_TeamTable",
|
|
object_id="team-1",
|
|
before_value=None,
|
|
updated_values='{"team_alias": "sentinel-demo"}',
|
|
)
|
|
|
|
logger.log_queue.append(standard_payload)
|
|
await logger.async_log_audit_log_event(audit_log)
|
|
|
|
mock_token_response = MagicMock()
|
|
mock_token_response.status_code = 200
|
|
mock_token_response.json = MagicMock(
|
|
return_value={
|
|
"access_token": "test-bearer-token",
|
|
"expires_in": 3600,
|
|
}
|
|
)
|
|
mock_token_response.text = "Success"
|
|
|
|
mock_api_response = MagicMock()
|
|
mock_api_response.status_code = 204
|
|
mock_api_response.text = "Success"
|
|
|
|
async def mock_post(*args, **kwargs):
|
|
if "oauth2/v2.0/token" in kwargs.get("url", ""):
|
|
return mock_token_response
|
|
return mock_api_response
|
|
|
|
logger.async_httpx_client.post = AsyncMock(side_effect=mock_post)
|
|
|
|
await logger.flush_queue()
|
|
|
|
ingestion_calls = [
|
|
call
|
|
for call in logger.async_httpx_client.post.call_args_list
|
|
if "dataCollectionRules" in call.kwargs["url"]
|
|
]
|
|
assert len(ingestion_calls) == 2
|
|
|
|
standard_call, audit_call = ingestion_calls
|
|
assert "Custom-LiteLLM-Standard" in standard_call.kwargs["url"]
|
|
assert json.loads(standard_call.kwargs["data"].decode("utf-8")) == [
|
|
standard_payload
|
|
]
|
|
assert "Custom-LiteLLM-Audit" in audit_call.kwargs["url"]
|
|
assert json.loads(audit_call.kwargs["data"].decode("utf-8")) == [audit_log]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_azure_sentinel_audit_stream_name_from_env_var(monkeypatch):
|
|
"""Audit stream resolves from AZURE_SENTINEL_AUDIT_STREAM_NAME when the string
|
|
callback constructs the logger with no audit_stream_name argument."""
|
|
monkeypatch.setenv("AZURE_SENTINEL_STREAM_NAME", "Custom-LiteLLM-Standard")
|
|
monkeypatch.setenv("AZURE_SENTINEL_AUDIT_STREAM_NAME", "Custom-LiteLLM-Audit")
|
|
|
|
with patch("asyncio.create_task", side_effect=_close_periodic_flush_task):
|
|
logger = AzureSentinelLogger(
|
|
dcr_immutable_id="dcr-test123456789",
|
|
endpoint="https://test-dce.eastus-1.ingest.monitor.azure.com",
|
|
tenant_id="test-tenant-id",
|
|
client_id="test-client-id",
|
|
client_secret="test-client-secret",
|
|
)
|
|
|
|
assert logger.audit_stream_name == "Custom-LiteLLM-Audit"
|
|
assert "streams/Custom-LiteLLM-Audit" in logger.audit_api_endpoint
|
|
assert "streams/Custom-LiteLLM-Standard" in logger.api_endpoint
|
|
|
|
with patch("asyncio.create_task", side_effect=_close_periodic_flush_task):
|
|
explicit_logger = AzureSentinelLogger(
|
|
dcr_immutable_id="dcr-test123456789",
|
|
endpoint="https://test-dce.eastus-1.ingest.monitor.azure.com",
|
|
tenant_id="test-tenant-id",
|
|
client_id="test-client-id",
|
|
client_secret="test-client-secret",
|
|
audit_stream_name="Custom-LiteLLM-Explicit",
|
|
)
|
|
|
|
assert explicit_logger.audit_stream_name == "Custom-LiteLLM-Explicit"
|
|
|
|
|
|
def _build_logger(**overrides):
|
|
kwargs = {
|
|
"dcr_immutable_id": "dcr-test123456789",
|
|
"endpoint": "https://test-dce.eastus-1.ingest.monitor.azure.com",
|
|
"tenant_id": "test-tenant-id",
|
|
"client_id": "test-client-id",
|
|
"client_secret": "test-client-secret",
|
|
**overrides,
|
|
}
|
|
with patch("asyncio.create_task", side_effect=_close_periodic_flush_task):
|
|
return AzureSentinelLogger(**kwargs)
|
|
|
|
|
|
@pytest.fixture
|
|
def _no_authority_host_env(monkeypatch):
|
|
monkeypatch.delenv("AZURE_SENTINEL_AUTHORITY_HOST", raising=False)
|
|
monkeypatch.delenv("AZURE_AUTHORITY_HOST", raising=False)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"authority_host, expected_authority, expected_scope",
|
|
[
|
|
(None, "https://login.microsoftonline.com", "https://monitor.azure.com/.default"),
|
|
("https://login.microsoftonline.us", "https://login.microsoftonline.us", "https://monitor.azure.us/.default"),
|
|
("https://login.microsoftonline.us/", "https://login.microsoftonline.us", "https://monitor.azure.us/.default"),
|
|
("login.microsoftonline.us", "https://login.microsoftonline.us", "https://monitor.azure.us/.default"),
|
|
("https://adfs.contoso.example", "https://adfs.contoso.example", "https://monitor.azure.com/.default"),
|
|
],
|
|
)
|
|
def test_azure_sentinel_resolves_authority_host_and_audience_together(
|
|
_no_authority_host_env, authority_host, expected_authority, expected_scope
|
|
):
|
|
"""Both the Entra authority and the Azure Monitor audience must follow the configured cloud.
|
|
|
|
Moving only the authority leaves a sovereign deployment asking sovereign Entra for the
|
|
commercial audience, which the sovereign ingestion endpoint rejects.
|
|
"""
|
|
logger = _build_logger(**({} if authority_host is None else {"authority_host": authority_host}))
|
|
|
|
assert logger.authority_host == expected_authority
|
|
assert logger.oauth_scope == expected_scope
|
|
|
|
|
|
def test_azure_sentinel_authority_host_from_env_var(_no_authority_host_env, monkeypatch):
|
|
"""AZURE_AUTHORITY_HOST is the documented setting and the string callback constructs the logger
|
|
with no arguments, so the env var alone has to move both values."""
|
|
monkeypatch.setenv("AZURE_AUTHORITY_HOST", "https://login.microsoftonline.us")
|
|
|
|
logger = _build_logger()
|
|
|
|
assert logger.authority_host == "https://login.microsoftonline.us"
|
|
assert logger.oauth_scope == "https://monitor.azure.us/.default"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_azure_sentinel_token_request_uses_sovereign_authority_and_audience(_no_authority_host_env):
|
|
"""The resolved values must reach the wire, not just the instance attributes."""
|
|
logger = _build_logger(authority_host="https://login.microsoftonline.us")
|
|
logger.log_queue.append(
|
|
StandardLoggingPayload(
|
|
id="test_id",
|
|
call_type="completion",
|
|
model="gpt-3.5-turbo",
|
|
status="success",
|
|
messages=[{"role": "user", "content": "Hello"}],
|
|
response={"choices": [{"message": {"content": "Hi"}}]},
|
|
)
|
|
)
|
|
|
|
mock_token_response = MagicMock()
|
|
mock_token_response.status_code = 200
|
|
mock_token_response.json = MagicMock(return_value={"access_token": "test-bearer-token", "expires_in": 3600})
|
|
mock_token_response.text = "Success"
|
|
mock_api_response = MagicMock()
|
|
mock_api_response.status_code = 204
|
|
mock_api_response.text = "Success"
|
|
|
|
async def mock_post(*args, **kwargs):
|
|
if "oauth2/v2.0/token" in kwargs.get("url", ""):
|
|
return mock_token_response
|
|
return mock_api_response
|
|
|
|
logger.async_httpx_client.post = AsyncMock(side_effect=mock_post)
|
|
|
|
await logger.async_send_batch()
|
|
|
|
token_calls = [
|
|
call for call in logger.async_httpx_client.post.call_args_list if "oauth2/v2.0/token" in call.kwargs["url"]
|
|
]
|
|
assert len(token_calls) == 1
|
|
assert token_calls[0].kwargs["url"] == "https://login.microsoftonline.us/test-tenant-id/oauth2/v2.0/token"
|
|
assert token_calls[0].kwargs["data"]["scope"] == "https://monitor.azure.us/.default"
|
|
|
|
|
|
def test_azure_sentinel_authority_host_prefers_the_sentinel_scoped_env_var(_no_authority_host_env, monkeypatch):
|
|
"""AZURE_AUTHORITY_HOST is shared with Azure OpenAI and the azure_storage callback, so a deployment
|
|
whose Sentinel workspace lives in a different cloud than the rest of its Azure resources needs a
|
|
Sentinel-scoped override. This mirrors how tenant, client id and secret already resolve."""
|
|
monkeypatch.setenv("AZURE_AUTHORITY_HOST", "https://login.microsoftonline.com")
|
|
monkeypatch.setenv("AZURE_SENTINEL_AUTHORITY_HOST", "https://login.microsoftonline.us")
|
|
|
|
logger = _build_logger()
|
|
|
|
assert logger.authority_host == "https://login.microsoftonline.us"
|
|
assert logger.oauth_scope == "https://monitor.azure.us/.default"
|
|
|
|
|
|
def test_azure_sentinel_authority_host_argument_outranks_the_scoped_env_var(_no_authority_host_env, monkeypatch):
|
|
"""An explicit constructor argument is the most specific source and has to win, otherwise a
|
|
deployment that exports the scoped variable silently overrides an SDK caller."""
|
|
monkeypatch.setenv("AZURE_SENTINEL_AUTHORITY_HOST", "https://login.microsoftonline.us")
|
|
|
|
logger = _build_logger(authority_host="https://login.microsoftonline.com")
|
|
|
|
assert logger.authority_host == "https://login.microsoftonline.com"
|
|
assert logger.oauth_scope == "https://monitor.azure.com/.default"
|
|
|
|
|
|
def _standard_payloads(count, filler_bytes=0):
|
|
return [
|
|
StandardLoggingPayload(
|
|
id=f"standard-{i}",
|
|
call_type="completion",
|
|
model="gpt-3.5-turbo",
|
|
status="success",
|
|
messages=[{"role": "user", "content": "x" * filler_bytes}],
|
|
response={"choices": [{"message": {"content": "Hi"}}]},
|
|
)
|
|
for i in range(count)
|
|
]
|
|
|
|
|
|
def _audit_payloads(count, filler_bytes=0):
|
|
return [
|
|
StandardAuditLogPayload(
|
|
id=f"audit-{i}",
|
|
updated_at="2026-05-06T04:39:00+00:00",
|
|
changed_by="user-1",
|
|
changed_by_api_key="sk-test",
|
|
action="created",
|
|
table_name="LiteLLM_TeamTable",
|
|
object_id="team-1",
|
|
before_value=None,
|
|
updated_values=json.dumps({"team_alias": "x" * filler_bytes}),
|
|
)
|
|
for i in range(count)
|
|
]
|
|
|
|
|
|
QUEUE_CASES = [
|
|
pytest.param("log_queue", "async_send_batch", _standard_payloads, id="standard"),
|
|
pytest.param("audit_log_queue", "async_send_audit_batch", _audit_payloads, id="audit"),
|
|
]
|
|
|
|
|
|
def _token_response():
|
|
response = MagicMock()
|
|
response.status_code = 200
|
|
response.json = MagicMock(return_value={"access_token": "test-bearer-token", "expires_in": 3600})
|
|
response.text = "Success"
|
|
return response
|
|
|
|
|
|
def _install_ingestion(logger, on_ingest):
|
|
"""Route the OAuth call to a canned token and every ingestion call to `on_ingest(body_bytes)`."""
|
|
|
|
async def _post(*args, **kwargs):
|
|
if "oauth2/v2.0/token" in kwargs.get("url", ""):
|
|
return _token_response()
|
|
return await on_ingest(kwargs["data"])
|
|
|
|
logger.async_httpx_client.post = AsyncMock(side_effect=_post)
|
|
|
|
|
|
def _accepted():
|
|
return Response(204, request=Request("POST", "https://example.com"), text="")
|
|
|
|
|
|
def _too_large(*, raised):
|
|
request = Request("POST", "https://example.com")
|
|
response = Response(413, request=request, text="Payload Too Large")
|
|
if raised:
|
|
raise MaskedHTTPStatusError(httpx.HTTPStatusError("413", request=request, response=response))
|
|
return response
|
|
|
|
|
|
def _rejected(status_code, *, raised):
|
|
"""litellm's http handler calls raise_for_status, so a real rejection arrives raised, not returned."""
|
|
request = Request("POST", "https://example.com")
|
|
response = Response(status_code, request=request, text=f"rejected with {status_code}")
|
|
if raised:
|
|
raise MaskedHTTPStatusError(httpx.HTTPStatusError(str(status_code), request=request, response=response))
|
|
return response
|
|
|
|
|
|
def _awaiting_retry(logger, queue_attr):
|
|
return getattr(logger, "logs_awaiting_retry" if queue_attr == "log_queue" else "audit_logs_awaiting_retry")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_splits_a_batch_that_would_exceed_the_ingestion_cap(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""Azure Monitor rejects a body over 1MB uncompressed, so an oversize batch has to be split
|
|
before it is sent instead of being posted whole and lost."""
|
|
logger = _build_logger()
|
|
records = build_payloads(4, filler_bytes=400_000)
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
sent_bodies = []
|
|
|
|
async def _on_ingest(data):
|
|
sent_bodies.append(data)
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await getattr(logger, send_method)()
|
|
|
|
assert len(sent_bodies) > 1
|
|
assert all(len(body) <= AZURE_SENTINEL_MAX_PAYLOAD_SIZE_BYTES for body in sent_bodies)
|
|
delivered = [record["id"] for body in sent_bodies for record in json.loads(body.decode("utf-8"))]
|
|
assert delivered == [record["id"] for record in records]
|
|
assert getattr(logger, queue_attr) == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("raised", [True, False], ids=["raised", "returned"])
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_halves_the_batch_on_413(queue_attr, send_method, build_payloads, raised):
|
|
"""A 413 the size estimate did not predict must halve the batch and retry, not drop it.
|
|
|
|
litellm's http handler raises MaskedHTTPStatusError on a 4xx, so the raised path is the one
|
|
a real Azure Monitor 413 takes, and both are covered here.
|
|
"""
|
|
logger = _build_logger()
|
|
records = build_payloads(4)
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
delivered = []
|
|
|
|
async def _on_ingest(data):
|
|
body = json.loads(data.decode("utf-8"))
|
|
if len(body) > 1:
|
|
return _too_large(raised=raised)
|
|
delivered.extend(record["id"] for record in body)
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await getattr(logger, send_method)()
|
|
|
|
assert delivered == [record["id"] for record in records]
|
|
assert getattr(logger, queue_attr) == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_drops_only_the_lone_record_that_still_413s(queue_attr, send_method, build_payloads):
|
|
"""One undeliverable record must not take its siblings down with it or wedge the queue."""
|
|
logger = _build_logger()
|
|
records = build_payloads(4)
|
|
poison = records[2]["id"]
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
delivered = []
|
|
|
|
async def _on_ingest(data):
|
|
body = json.loads(data.decode("utf-8"))
|
|
if any(record["id"] == poison for record in body):
|
|
return _too_large(raised=True)
|
|
delivered.extend(record["id"] for record in body)
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await asyncio.wait_for(getattr(logger, send_method)(), timeout=10)
|
|
|
|
assert delivered == [record["id"] for record in records if record["id"] != poison]
|
|
assert getattr(logger, queue_attr) == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_requeues_only_what_a_transient_failure_left_undelivered(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""Records Azure Monitor already accepted must not be sent twice, and the rest must survive
|
|
for the next flush instead of being cleared."""
|
|
logger = _build_logger()
|
|
records = build_payloads(4)
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
delivered = []
|
|
|
|
async def _on_ingest(data):
|
|
body = json.loads(data.decode("utf-8"))
|
|
if len(body) > 2:
|
|
return _too_large(raised=True)
|
|
if any(record["id"] == records[2]["id"] for record in body):
|
|
raise httpx.ConnectError("connection reset")
|
|
delivered.extend(record["id"] for record in body)
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await getattr(logger, send_method)()
|
|
|
|
assert delivered == [records[0]["id"], records[1]["id"]]
|
|
assert getattr(logger, queue_attr) == records[2:]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_requeues_the_batch_on_a_non_success_status(queue_attr, send_method, build_payloads):
|
|
"""A 500 from ingestion is retryable, so the batch has to stay queued."""
|
|
logger = _build_logger()
|
|
records = build_payloads(3)
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
async def _on_ingest(data):
|
|
return Response(500, request=Request("POST", "https://example.com"), text="Internal Server Error")
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await getattr(logger, send_method)()
|
|
|
|
assert getattr(logger, queue_attr) == records
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_requeues_the_batch_when_the_oauth_token_call_fails(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""Losing the token is transient, so the batch must not be dropped on the way to the wire."""
|
|
logger = _build_logger()
|
|
records = build_payloads(2)
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
ingestion_calls = []
|
|
|
|
async def _post(*args, **kwargs):
|
|
if "oauth2/v2.0/token" in kwargs.get("url", ""):
|
|
failed = MagicMock()
|
|
failed.status_code = 401
|
|
failed.text = "Unauthorized"
|
|
return failed
|
|
ingestion_calls.append(kwargs["url"])
|
|
return _accepted()
|
|
|
|
logger.async_httpx_client.post = AsyncMock(side_effect=_post)
|
|
|
|
await getattr(logger, send_method)()
|
|
|
|
assert ingestion_calls == []
|
|
assert getattr(logger, queue_attr) == records
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_caps_the_retry_queue_at_max_queue_size(queue_attr, send_method, build_payloads):
|
|
"""Retrying forever against an unreachable workspace must not grow the queue without bound,
|
|
so the oldest records go once the queue is over its limit."""
|
|
logger = _build_logger(max_queue_size=3)
|
|
records = build_payloads(4)
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
async def _on_ingest(data):
|
|
raise httpx.ConnectError("connection reset")
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await getattr(logger, send_method)()
|
|
|
|
assert getattr(logger, queue_attr) == records[1:]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_keeps_records_queued_during_a_send(queue_attr, send_method, build_payloads):
|
|
"""The queue is detached before sending, so a record logged mid-flush is kept and lands behind
|
|
anything the failed send hands back."""
|
|
logger = _build_logger()
|
|
records = build_payloads(2)
|
|
late_record = build_payloads(1)[0]
|
|
late_record["id"] = "logged-during-send"
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
async def _on_ingest(data):
|
|
getattr(logger, queue_attr).append(late_record)
|
|
raise httpx.ConnectError("connection reset")
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await getattr(logger, send_method)()
|
|
|
|
assert getattr(logger, queue_attr) == [*records, late_record]
|
|
|
|
|
|
def _poison(record):
|
|
"""A mixed-type set makes safe_dumps raise TypeError while sorting it, so the record can never be serialized."""
|
|
field = "messages" if "messages" in record else "updated_values"
|
|
record[field] = {1, "a"}
|
|
return record
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_drops_only_the_record_that_cannot_be_serialized(queue_attr, send_method, build_payloads):
|
|
"""A record that raises during serialization used to escape the send, which killed the periodic
|
|
flush task for good and lost the already-detached batch with it. It has to be isolated and
|
|
dropped alone, with the flush completing normally."""
|
|
logger = _build_logger()
|
|
records = build_payloads(4)
|
|
poison = _poison(records[2])["id"]
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
delivered = []
|
|
|
|
async def _on_ingest(data):
|
|
delivered.extend(record["id"] for record in json.loads(data.decode("utf-8")))
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await asyncio.wait_for(logger.flush_queue(), timeout=10)
|
|
|
|
assert delivered == [record["id"] for record in records if record["id"] != poison]
|
|
assert getattr(logger, queue_attr) == []
|
|
|
|
|
|
async def _log(logger, queue_attr, record):
|
|
if queue_attr == "log_queue":
|
|
await logger.async_log_success_event({"standard_logging_object": record}, None, None, None)
|
|
return
|
|
await logger.async_log_audit_log_event(record)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_retries_on_the_flush_timer_not_on_every_record_while_the_destination_is_down(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""Requeued records keep the queue at or over batch_size, so without a guard every new record
|
|
re-sent the whole growing queue. While a retry is pending only the periodic flush may send, and
|
|
a successful flush hands the trigger back to the batch size."""
|
|
logger = _build_logger(batch_size=3)
|
|
records = build_payloads(11)
|
|
|
|
attempts = []
|
|
destination_down = True
|
|
|
|
async def _on_ingest(data):
|
|
attempts.append([record["id"] for record in json.loads(data.decode("utf-8"))])
|
|
if destination_down:
|
|
raise httpx.ConnectError("connection reset")
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
for record in records[:8]:
|
|
await _log(logger, queue_attr, record)
|
|
|
|
assert attempts == [[record["id"] for record in records[:3]]]
|
|
assert getattr(logger, queue_attr) == records[:8]
|
|
|
|
destination_down = False
|
|
await logger.flush_queue()
|
|
for record in records[8:]:
|
|
await _log(logger, queue_attr, record)
|
|
|
|
assert [record_id for attempt in attempts[1:-1] for record_id in attempt] == [record["id"] for record in records[:8]]
|
|
assert all(len(attempt) <= 3 for attempt in attempts[1:-1])
|
|
assert attempts[-1] == [record["id"] for record in records[8:]]
|
|
assert getattr(logger, queue_attr) == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_threshold_send_waits_for_an_in_flight_timer_flush(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""A batch-size send that overlapped the periodic flush could finish after it and requeue its
|
|
newer records in front of the older ones, so the max_queue_size trim would then drop the
|
|
newest records instead of the oldest. Both paths have to take the flush lock, and a waiter
|
|
that gets the lock after a failed flush stands down instead of resending the whole queue."""
|
|
logger = _build_logger(batch_size=2)
|
|
records = build_payloads(4)
|
|
setattr(logger, queue_attr, list(records[:2]))
|
|
|
|
attempts = []
|
|
timer_send_started = asyncio.Event()
|
|
release_timer_send = asyncio.Event()
|
|
|
|
async def _on_ingest(data):
|
|
attempts.append([record["id"] for record in json.loads(data.decode("utf-8"))])
|
|
if len(attempts) == 1:
|
|
timer_send_started.set()
|
|
await release_timer_send.wait()
|
|
raise httpx.ConnectError("connection reset")
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
timer_flush = asyncio.create_task(logger.flush_queue())
|
|
await asyncio.wait_for(timer_send_started.wait(), timeout=10)
|
|
await _log(logger, queue_attr, records[2])
|
|
threshold_send = asyncio.create_task(_log(logger, queue_attr, records[3]))
|
|
await asyncio.sleep(0)
|
|
release_timer_send.set()
|
|
await asyncio.wait_for(timer_flush, timeout=10)
|
|
await asyncio.wait_for(threshold_send, timeout=10)
|
|
|
|
assert attempts == [[record["id"] for record in records[:2]]]
|
|
assert getattr(logger, queue_attr) == records
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_concurrent_threshold_sends_collapse_into_one_attempt_while_the_destination_is_down(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""Records logged while a threshold send is blocked on the wire all see the retry flag still
|
|
unset and queue up on the flush lock. Each waiter has to recheck under the lock, or every one
|
|
of them resends the growing queue as soon as the first attempt fails."""
|
|
logger = _build_logger(batch_size=2)
|
|
records = build_payloads(6)
|
|
|
|
attempts = []
|
|
first_send_started = asyncio.Event()
|
|
release_first_send = asyncio.Event()
|
|
destination_down = True
|
|
|
|
async def _on_ingest(data):
|
|
attempts.append([record["id"] for record in json.loads(data.decode("utf-8"))])
|
|
if len(attempts) == 1:
|
|
first_send_started.set()
|
|
await release_first_send.wait()
|
|
if destination_down:
|
|
raise httpx.ConnectError("connection reset")
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await _log(logger, queue_attr, records[0])
|
|
first_send = asyncio.create_task(_log(logger, queue_attr, records[1]))
|
|
await asyncio.wait_for(first_send_started.wait(), timeout=10)
|
|
waiters = [asyncio.create_task(_log(logger, queue_attr, record)) for record in records[2:]]
|
|
await asyncio.sleep(0)
|
|
release_first_send.set()
|
|
await asyncio.wait_for(asyncio.gather(first_send, *waiters), timeout=10)
|
|
|
|
assert attempts == [[record["id"] for record in records[:2]]]
|
|
assert getattr(logger, queue_attr) == records
|
|
|
|
destination_down = False
|
|
await logger.flush_queue()
|
|
|
|
assert [record_id for attempt in attempts[1:] for record_id in attempt] == [record["id"] for record in records]
|
|
assert all(len(attempt) <= 2 for attempt in attempts[1:])
|
|
assert getattr(logger, queue_attr) == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_batch_size_bounds_every_request_under_concurrent_events(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""Lowering batch_size is the documented way to stay under the ingestion cap, so no request may
|
|
carry more than batch_size records even when events keep landing while a send is on the wire,
|
|
and every one of those records still has to arrive exactly once."""
|
|
logger = _build_logger(batch_size=5)
|
|
records = build_payloads(40)
|
|
|
|
attempts = []
|
|
first_send_started = asyncio.Event()
|
|
release_first_send = asyncio.Event()
|
|
|
|
async def _on_ingest(data):
|
|
attempts.append([record["id"] for record in json.loads(data.decode("utf-8"))])
|
|
if len(attempts) == 1:
|
|
first_send_started.set()
|
|
await release_first_send.wait()
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
sends = [asyncio.create_task(_log(logger, queue_attr, record)) for record in records]
|
|
await asyncio.wait_for(first_send_started.wait(), timeout=10)
|
|
|
|
assert attempts == [[record["id"] for record in records[:5]]]
|
|
assert getattr(logger, queue_attr) == records[5:]
|
|
|
|
release_first_send.set()
|
|
await asyncio.wait_for(asyncio.gather(*sends), timeout=10)
|
|
await logger.flush_queue()
|
|
|
|
assert max(len(attempt) for attempt in attempts) <= 5
|
|
assert [record_id for attempt in attempts for record_id in attempt] == [record["id"] for record in records]
|
|
assert getattr(logger, queue_attr) == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_requeues_a_cancelled_send(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""Cancellation after detaching a batch must preserve the detached records for a later flush."""
|
|
logger = _build_logger()
|
|
records = build_payloads(2)
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
async def _on_ingest(data):
|
|
raise asyncio.CancelledError
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
with pytest.raises(asyncio.CancelledError) as excinfo:
|
|
await getattr(logger, send_method)()
|
|
|
|
assert type(excinfo.value) is asyncio.CancelledError
|
|
assert getattr(logger, queue_attr) == records
|
|
assert _awaiting_retry(logger, queue_attr)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_requeues_a_send_cancelled_before_it_reached_the_wire(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""Cancellation can land on the token call, before any record was sent, and the detached batch
|
|
has to survive that too."""
|
|
logger = _build_logger()
|
|
records = build_payloads(2)
|
|
setattr(logger, queue_attr, list(records))
|
|
logger.async_httpx_client.post = AsyncMock(side_effect=asyncio.CancelledError)
|
|
|
|
with pytest.raises(asyncio.CancelledError) as excinfo:
|
|
await getattr(logger, send_method)()
|
|
|
|
assert type(excinfo.value) is asyncio.CancelledError
|
|
assert getattr(logger, queue_attr) == records
|
|
assert _awaiting_retry(logger, queue_attr)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_does_not_resend_the_half_delivered_before_a_cancelled_split(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""A batch over the size cap goes out in pieces, so a cancellation partway through must requeue
|
|
only the pieces the destination never accepted, or the accepted ones land in Sentinel twice."""
|
|
logger = _build_logger()
|
|
records = build_payloads(8, filler_bytes=400_000)
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
attempts = []
|
|
cancel_after_the_first_piece = True
|
|
|
|
async def _on_ingest(data):
|
|
attempts.append([record["id"] for record in json.loads(data.decode("utf-8"))])
|
|
if cancel_after_the_first_piece and len(attempts) > 1:
|
|
raise asyncio.CancelledError
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
with pytest.raises(asyncio.CancelledError) as excinfo:
|
|
await getattr(logger, send_method)()
|
|
|
|
assert type(excinfo.value) is asyncio.CancelledError
|
|
assert attempts == [[record["id"] for record in records[:2]], [record["id"] for record in records[2:4]]]
|
|
assert getattr(logger, queue_attr) == records[2:]
|
|
|
|
cancel_after_the_first_piece = False
|
|
await logger.flush_queue()
|
|
|
|
assert [record_id for attempt in attempts[2:] for record_id in attempt] == [record["id"] for record in records[2:]]
|
|
assert getattr(logger, queue_attr) == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_threshold_waiter_does_not_send_a_sub_batch_after_success(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""A successful threshold send can leave one record behind, so a waiter must not send it
|
|
before the next record completes a batch."""
|
|
logger = _build_logger(batch_size=2)
|
|
records = build_payloads(3)
|
|
|
|
attempts = []
|
|
first_send_started = asyncio.Event()
|
|
release_first_send = asyncio.Event()
|
|
|
|
async def _on_ingest(data):
|
|
attempts.append([record["id"] for record in json.loads(data.decode("utf-8"))])
|
|
if len(attempts) == 1:
|
|
first_send_started.set()
|
|
await release_first_send.wait()
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await _log(logger, queue_attr, records[0])
|
|
first_send = asyncio.create_task(_log(logger, queue_attr, records[1]))
|
|
await asyncio.wait_for(first_send_started.wait(), timeout=10)
|
|
waiter = asyncio.create_task(_log(logger, queue_attr, records[2]))
|
|
await asyncio.sleep(0)
|
|
release_first_send.set()
|
|
await asyncio.wait_for(asyncio.gather(first_send, waiter), timeout=10)
|
|
|
|
assert attempts == [[record["id"] for record in records[:2]]]
|
|
assert getattr(logger, queue_attr) == [records[2]]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_azure_sentinel_threshold_send_only_sends_the_queue_that_crossed_the_threshold():
|
|
"""The standard and audit queues retry independently: crossing the audit threshold must not
|
|
resend standard records that are waiting for the periodic flush."""
|
|
logger = _build_logger(batch_size=2)
|
|
standard_records = _standard_payloads(2)
|
|
audit_records = _audit_payloads(2)
|
|
logger.log_queue = list(standard_records)
|
|
logger.logs_awaiting_retry = True
|
|
|
|
attempts = []
|
|
|
|
async def _on_ingest(data):
|
|
attempts.append([record["id"] for record in json.loads(data.decode("utf-8"))])
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
for record in audit_records:
|
|
await logger.async_log_audit_log_event(record)
|
|
|
|
assert attempts == [[record["id"] for record in audit_records]]
|
|
assert logger.audit_log_queue == []
|
|
assert logger.log_queue == standard_records
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("status_code", [408, 429, 500, 503])
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_keeps_the_batch_when_ingestion_raises_a_retryable_status(
|
|
queue_attr, send_method, build_payloads, status_code
|
|
):
|
|
"""A 5xx, a timeout or a throttle can clear on the next flush, so the whole batch stays queued
|
|
and the awaiting-retry flag hands the send back to the timer."""
|
|
logger = _build_logger()
|
|
records = build_payloads(3)
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
async def _on_ingest(data):
|
|
return _rejected(status_code, raised=True)
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await getattr(logger, send_method)()
|
|
|
|
assert getattr(logger, queue_attr) == records
|
|
assert _awaiting_retry(logger, queue_attr)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("raised", [True, False], ids=["raised", "returned"])
|
|
@pytest.mark.parametrize("status_code", [400, 403, 404])
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_drops_the_batch_when_ingestion_rejects_it_for_good(
|
|
queue_attr, send_method, build_payloads, status_code, raised
|
|
):
|
|
"""A permanent 4xx is dropped, the flag is cleared and the next records go out on their own."""
|
|
logger = _build_logger(batch_size=2)
|
|
rejected_records = build_payloads(2)
|
|
later_records = build_payloads(4)[2:]
|
|
setattr(logger, queue_attr, list(rejected_records))
|
|
|
|
delivered = []
|
|
destination_rejects = True
|
|
|
|
async def _on_ingest(data):
|
|
if destination_rejects:
|
|
return _rejected(status_code, raised=raised)
|
|
delivered.extend(record["id"] for record in json.loads(data.decode("utf-8")))
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await getattr(logger, send_method)()
|
|
|
|
assert getattr(logger, queue_attr) == []
|
|
assert not _awaiting_retry(logger, queue_attr)
|
|
|
|
destination_rejects = False
|
|
for record in later_records:
|
|
await _log(logger, queue_attr, record)
|
|
|
|
assert delivered == [record["id"] for record in later_records]
|
|
assert getattr(logger, queue_attr) == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_keeps_the_whole_batch_when_the_first_piece_of_a_split_fails(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""When the first half of a split hits a retryable error the untried second half must be kept
|
|
too, in the original order, instead of being sent ahead of records that are still pending."""
|
|
logger = _build_logger()
|
|
records = build_payloads(4)
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
attempts = []
|
|
|
|
async def _on_ingest(data):
|
|
body = json.loads(data.decode("utf-8"))
|
|
attempts.append([record["id"] for record in body])
|
|
if len(body) > 2:
|
|
return _too_large(raised=True)
|
|
return _rejected(503, raised=True)
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await getattr(logger, send_method)()
|
|
|
|
assert attempts == [[record["id"] for record in records], [record["id"] for record in records[:2]]]
|
|
assert getattr(logger, queue_attr) == records
|
|
assert _awaiting_retry(logger, queue_attr)
|
|
|
|
|
|
class _RaisesWhileDumping(BaseModel):
|
|
@computed_field
|
|
@property
|
|
def rendered(self) -> str:
|
|
raise RuntimeError("this field cannot be rendered")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_drops_only_the_record_whose_serialization_raises_an_unexpected_error(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""Serialization can fail with any exception class, not just TypeError or ValueError, because
|
|
safe_dumps hands pydantic models to model_dump. A record that raises anything has to be isolated
|
|
and dropped alone, or the flush dies with the whole batch."""
|
|
logger = _build_logger()
|
|
records = build_payloads(4)
|
|
poison = records[1]
|
|
poison["messages" if "messages" in poison else "updated_values"] = _RaisesWhileDumping()
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
delivered = []
|
|
|
|
async def _on_ingest(data):
|
|
delivered.extend(record["id"] for record in json.loads(data.decode("utf-8")))
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await asyncio.wait_for(logger.flush_queue(), timeout=10)
|
|
|
|
assert delivered == [record["id"] for record in records if record is not poison]
|
|
assert getattr(logger, queue_attr) == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_send_cancelled_by_a_timeout_surfaces_as_a_timeout(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""The logging worker bounds each flush with asyncio.wait_for, which on Python 3.12 only turns
|
|
an exact CancelledError into TimeoutError. A subclass carrying the undelivered records would
|
|
escape the worker as an unhandled error, so the send must re-raise the plain class."""
|
|
logger = _build_logger()
|
|
records = build_payloads(2)
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
async def _on_ingest(data):
|
|
await asyncio.sleep(60)
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
with pytest.raises(asyncio.TimeoutError):
|
|
await asyncio.wait_for(getattr(logger, send_method)(), timeout=0.05)
|
|
|
|
assert getattr(logger, queue_attr) == records
|
|
assert _awaiting_retry(logger, queue_attr)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_never_sends_more_than_batch_size_records_in_one_request(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""A recovery flush can find far more than batch_size records queued. Splitting on the count
|
|
first keeps each request at the configured size and bounds how much of the queue is serialized
|
|
just to measure it."""
|
|
logger = _build_logger(batch_size=2)
|
|
records = build_payloads(5)
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
attempts = []
|
|
|
|
async def _on_ingest(data):
|
|
attempts.append([record["id"] for record in json.loads(data.decode("utf-8"))])
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await getattr(logger, send_method)()
|
|
|
|
assert attempts == [
|
|
[records[0]["id"], records[1]["id"]],
|
|
[records[2]["id"]],
|
|
[records[3]["id"], records[4]["id"]],
|
|
]
|
|
assert getattr(logger, queue_attr) == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"status_code, expected_queue",
|
|
[pytest.param(503, "kept", id="503-kept"), pytest.param(401, "dropped", id="401-dropped")],
|
|
)
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_oauth_rejection_follows_the_same_retry_rule_as_ingestion(
|
|
queue_attr, send_method, build_payloads, status_code, expected_queue
|
|
):
|
|
"""The token endpoint raises through the same http handler as ingestion. A 5xx there is
|
|
transient and keeps the batch, a 401 means the client secret is wrong and would fail every
|
|
retry, so the batch is dropped instead of wedging the queue."""
|
|
logger = _build_logger()
|
|
records = build_payloads(2)
|
|
setattr(logger, queue_attr, list(records))
|
|
|
|
ingestion_calls = []
|
|
|
|
async def _post(*args, **kwargs):
|
|
if "oauth2/v2.0/token" in kwargs.get("url", ""):
|
|
return _rejected(status_code, raised=True)
|
|
ingestion_calls.append(kwargs["url"])
|
|
return _accepted()
|
|
|
|
logger.async_httpx_client.post = AsyncMock(side_effect=_post)
|
|
|
|
await getattr(logger, send_method)()
|
|
|
|
assert ingestion_calls == []
|
|
assert getattr(logger, queue_attr) == (records if expected_queue == "kept" else [])
|
|
assert _awaiting_retry(logger, queue_attr) is (expected_queue == "kept")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("queue_attr, send_method, build_payloads", QUEUE_CASES)
|
|
async def test_azure_sentinel_does_not_stay_in_retry_mode_when_the_queue_cap_trims_everything(
|
|
queue_attr, send_method, build_payloads
|
|
):
|
|
"""With max_queue_size at 0 the cap drops every requeued record, so there is nothing for the
|
|
timer to retry. The flag must follow the retained queue, or every later threshold send is
|
|
skipped until the timer happens to fire."""
|
|
logger = _build_logger(batch_size=2, max_queue_size=0)
|
|
lost_records = build_payloads(2)
|
|
later_records = build_payloads(4)[2:]
|
|
setattr(logger, queue_attr, list(lost_records))
|
|
|
|
delivered = []
|
|
destination_down = True
|
|
|
|
async def _on_ingest(data):
|
|
if destination_down:
|
|
raise httpx.ConnectError("connection reset")
|
|
delivered.extend(record["id"] for record in json.loads(data.decode("utf-8")))
|
|
return _accepted()
|
|
|
|
_install_ingestion(logger, _on_ingest)
|
|
|
|
await getattr(logger, send_method)()
|
|
|
|
assert getattr(logger, queue_attr) == []
|
|
assert not _awaiting_retry(logger, queue_attr)
|
|
|
|
destination_down = False
|
|
for record in later_records:
|
|
await _log(logger, queue_attr, record)
|
|
|
|
assert delivered == [record["id"] for record in later_records]
|