Skip to content

feat(alerts): add email labels, bulk actions and threshold editing - #52139

Merged
moe-berri merged 2 commits into
mainfrom
litellm_alerts_user_email
Nov 16, 2026
Merged

moe-berri merged 2 commits into
mainfrom
litellm_alerts_user_email

Conversation

@moe-berri

@moe-berri moe-berri commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

use email as user identifier in alerts and let enterprise users edit alert thresholds

Details

TLDR

Problem this solves:

  • User alerts show UUIDs instead of recognizable email addresses.
  • Clearing alerts requires updating each row.
  • Performance thresholds cannot be inspected or adjusted.

How it solves it:

  • Prefer email, then alias, while keeping UUID-based activity links.
  • Resolve or dismiss every open alert in the selected category.
  • Enterprise admins can edit existing multipliers and minimum increases.

Intentional product change: Manage alerts shows the four existing rules and explains both conditions. Enterprise admins can edit their thresholds. Users cannot create new rules, and the existing baseline and sample-size safeguards remain fixed.

User Flow

Before, an admin cannot identify users by email or manage these limits from Alerts.

  1. Open http://127.0.0.1:3019/ui/alerts with the four synthetic user alerts.
  2. User alerts display the UUID. Each row must be resolved or dismissed separately.
  3. Open Manage alerts. Monitoring toggles are available, but threshold settings are absent.

After, an admin can identify the user, clear a category, and adjust existing thresholds with Enterprise.

  1. Open http://127.0.0.1:3019/ui/alerts with the same four synthetic user alerts.
  2. Alerts display alex@example.com. Resolve all and Dismiss all include unloaded matching open alerts.
  3. Open Manage alerts, then Edit thresholds. Change the multiplier and minimum increase, then save.
  4. Reopen the editor. A saved 3.5-point error-rate increase remains exactly 3.5.

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally
  • My PR passes all required CI/CD checks
  • My PR's scope is as isolated as possible
  • Every automated review on my PR's latest commit has finished and findings are addressed

The new tests pass. The broader database alert suite has one pre-existing gateway-history failure, reproduced on unchanged main. CI and automated reviews are running on the latest commit.

Screenshots / Proof of Fix

Before and after screenshots were captured at the same local URL using identical synthetic data. Attachment upload is pending. Before is 7363ffd0326e; the after screenshots were captured with the changes in 5219bd6a82c. Current tip 6bdbf92f909 includes main through 8c12b992163 and preserves this view for the same four metric alerts. After main added prompt-cache advisories, bulk All alerts was updated to cover them too. The updated UI and real-database tests cover this integration. The final validation fix accepts multipliers such as 1.005 and rejects 1 before submission. The 39 UI tests pass with this case and fractional percentage round-tripping.

Both live proxies used two workers, a dedicated PostgreSQL 16 database, and dedicated shared Redis through the repository's owned-proxy harness. No provider calls are involved. The baseline frontend used a wider Turbopack root to resolve shared dependencies and allowed the loopback development origin. Neither development-only setting is in this PR.

Enterprise entitlement was simulated through the QA dependency hook below. Authentication, HTTP routes, persistence, and bulk writes were real. Community threshold writes returned HTTP 403 without simulated entitlement. License validation itself was not exercised.

Before

  1. Open the Alerts URL and inspect a user alert. It shows 11111111-2222-4333-8444-555555555555.
  2. Open Manage alerts. There is no threshold editor or list of limits.
  3. Inspect the inbox toolbar. Bulk actions are absent. The baseline browser showed only per-row actions.

After

  1. Open the same Alerts URL. The user is alex@example.com; View user activity still links by UUID.
  2. In Manage alerts, edit spend to 4 and 75, traffic to 12 and 1500, latency to 4 and 750, and error rate to 4 and 3.5.
  3. Save and reopen. Values persist. The error-rate summary reads “At least 4× the usual error rate and 3.5 percentage points higher.”
  4. Choose Resolve all and confirm. Open becomes empty and all four alerts appear under Resolved.
  5. Reopen one alert, choose Dismiss all, and confirm. That alert appears under Dismissed.
  6. Disable the QA Enterprise marker and reload. The editor disappears. The Community API rejects a threshold write with HTTP 403.

The built-in defaults are unchanged.

Rule Times usual Minimum increase
Spend 3 $50
Traffic 10 1,000 requests
Latency 3 500 ms
Error rate 3 2 percentage points

The prior seven days remain the baseline. Four active baseline days, 100 timed requests for latency, and 500 requests for error rate remain fixed. Changes apply to future checks.

Automated validation

uv run --no-sync pytest tests/unit/models/test_performance_alert.py tests/unit/proxy/alerting_endpoints/test_alerts.py tests/unit/repositories/test_performance_alert_repository.py tests/unit/proxy/spend_tracking/test_performance_alerts.py -q passed 158 tests.

npx vitest run src/components/Alerts/Alerts.integration.test.tsx src/components/Alerts/alertPresentation.test.ts passed 39 tests, including filtered bulk writes, combined retirement/performance/prompt-cache writes, retry, permissions, and fractional percentage round-tripping.

The real-database run of tests/integration/database/test_alerts.py plus test_enterprise_thresholds_persist_and_change_detection_but_free_uses_defaults passed 40 tests. The existing test_daily_history_matches_scope_and_weighted_metrics[gateway] failed on both branch and baseline (baseline result 27 passed, 1 failed). The two email-present regression cases failed on the baseline, while all four fallback cases passed.

The full make check and production typecheck passed before the final main integration. Both are being rerun on the rebased tip. Gitleaks found no secrets in the outgoing diff or commit message.

Reproduce the local browser fixtures

Use a disposable PostgreSQL 16 instance and Redis available to the integration harness. Set DATABASE_URL to the disposable database, LITELLM_MASTER_KEY, UI_USERNAME, and UI_PASSWORD to local test values. Keep these runtime-only. Save the following launcher outside the checkout and set ALERTS_QA_REPO to the checkout and ALERTS_QA_WORK to an empty scratch directory. This is the launcher used for both versions, with machine-specific paths replaced by environment variables.

import asyncio
import getpass
import os
from pathlib import Path
import signal
import sys
import time
from datetime import datetime, timedelta, timezone
import httpx

repo = Path(os.environ['ALERTS_QA_REPO'])
work = Path(os.environ['ALERTS_QA_WORK'])
os.chdir(repo)
sys.path.insert(0, str(repo))
os.environ.update({
    'PYTHON_DOTENV_DISABLED': '1',
    'LITELLM_LOCAL_MODEL_COST_MAP': 'True',
    'PYTHONPATH': os.pathsep.join((str(work), str(repo / 'tests'), str(repo))),
    'LITELLM_WORKER_STARTUP_HOOKS': 'qa_alert_hooks:configure',
})
from tests.integration._support.workers import worker_services
from tests.integration._support.process import owned_proxy_process, OwnedState
from tests.integration._support.client import Gateway
from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
from litellm.proxy.utils import PrismaClient, ProxyLogging
from litellm.repositories.alert_repository import AlertRepository
from litellm.models.alert import AlertDetection

config = work / 'qa-config.yaml'
config.write_text('''model_list: []
litellm_settings:
  cache: true
  cache_params:
    type: redis
    host: os.environ/REDIS_HOST
    port: os.environ/REDIS_PORT
router_settings:
  redis_host: os.environ/REDIS_HOST
  redis_port: os.environ/REDIS_PORT
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL
  coordination_redis:
    host: os.environ/REDIS_HOST
    port: os.environ/REDIS_PORT
''')

async def seed(database):
    os.environ['DATABASE_URL'] = database
    import psycopg
    with psycopg.connect(database) as db:
        db.execute('INSERT INTO "LiteLLM_UserTable" (user_id,user_email) VALUES (%s,%s)', ('11111111-2222-4333-8444-555555555555', 'alex@example.com'))
    client = PrismaClient(database, ProxyLogging(UserApiKeyCache()))
    await client.connect()
    try:
        repository = AlertRepository(client)
        day = datetime(2026, 11, 15, tzinfo=timezone.utc)
        for kind, value, baseline, unit in [('spend',180,40,'usd'),('traffic',15000,1000,'requests'),('latency',2200,600,'milliseconds'),('reliability',0.1,0.02,'ratio')]:
            await repository.record(AlertDetection.model_validate({'type':kind,'resource_type':'user','resource_id':'11111111-2222-4333-8444-555555555555','window_start':day,'window_end':day+timedelta(days=1),'evidence':{'value':value,'baseline':baseline,'unit':unit,'sample_size':15000}}))
    finally:
        await client.disconnect()

with worker_services(work / 'browser-runtime') as services, httpx.Client(base_url='http://127.0.0.1:1') as client:
    with owned_proxy_process(Gateway(client, os.environ['LITELLM_MASTER_KEY'], 'http://127.0.0.1:1'), work / 'browser-runtime', services, config=config, workers=2, state=OwnedState.SHARED_WITH_WORKER) as proxy:
        asyncio.run(seed(services['DATABASE_URL']))
        (work / 'qa-port').write_text(str(proxy.gateway.client.base_url.port))
        print('Two-worker local QA proxy ready', flush=True)
        while not (work / 'stop-browser-qa').exists():
            time.sleep(1)

Save this hook as qa_alert_hooks.py in the scratch directory. Add or remove an empty enterprise-mode file there to simulate the entitlement for UI checks.

from pathlib import Path
from litellm.proxy.deps.database import DatabaseDep
from litellm.repositories.performance_alert_repository import PerformanceAlertRepository

async def monitoring_repository(database: DatabaseDep):
    return None if database is None else PerformanceAlertRepository(database.prisma, enterprise=(Path(__file__).parent / 'enterprise-mode').exists())

def configure():
    from litellm.proxy.proxy_server import app
    from litellm.proxy.deps.repositories import get_alert_monitoring_repository
    app.dependency_overrides[get_alert_monitoring_repository] = monitoring_repository

Run the launcher with the checkout's Python environment. It starts the owned two-worker proxy and writes its port to qa-port. The underlying command is python -m integration._support.proxy --config <generated-config> --host 127.0.0.1 --num_workers 2 --timeout_worker_healthcheck <harness-default> --use_prisma_db_push --port <allocated-port>. The harness applies the schema before serving. Reload is omitted so both worker processes remain active.

Start the dashboard from litellm/ui/litellm-dashboard with LENS_DEV_PROXY_URL=http://127.0.0.1:<qa-port> NEXT_PUBLIC_USE_REWRITES=true ../../scripts/with_dashboard_node.sh npm run dev -- --port 3019. Sign in with the local test credentials and follow the steps above. Creating stop-browser-qa in the scratch directory closes the owned proxy and services.

Type

New Feature and Bug Fix

Caveats

Low

  • Enterprise QA simulates entitlement, not license validation.
  • Existing gateway-history fixture failure also reproduces on main.
  • OSV flags the unchanged Next.js dependency, advisory GHSA-mfr8-8qww-v76h.

Final Attestation

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

Note

Medium Risk
Changes alert detection thresholds, bulk SQL status updates, and admin-only Enterprise gating—incorrect thresholds or filters could miss or mislabel alerts at scale.

Overview
Adds bulk resolve/dismiss for saved alerts via PATCH /alerts, including open rows that are not on the current page, with optional filtering by alert type. The dashboard exposes Resolve all / Dismiss all (with confirmation), coordinates model-deprecation updates when viewing all types, and hides bulk controls for read-only admins.

User-facing alert labels prefer trimmed email over alias when enriching user-scoped alerts, while keeping UUID-based activity links.

Enterprise admins can inspect and persist performance alert thresholds (multiplier + minimum increase per spend/traffic/latency/reliability) through PATCH /alerts/monitoring; detection and sweeps use the configured values instead of fixed constants, with validation and 403 for non-Enterprise. Free tiers still see read-only defaults in Manage alerts.

Detection tweaks require traffic and reliability increases to exceed baseline (not only meet multiplier floors). UI, OpenAPI schema, and integration/unit tests cover bulk writes, threshold persistence, permissions, and email fallback.

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

@moe-berri
moe-berri force-pushed the litellm_alerts_user_email branch from 5219bd6 to bd06973 Compare November 16, 2026 23:09
@moe-berri
moe-berri marked this pull request as ready for review November 16, 2026 23:09
@moe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai @veria-ai

@moe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@veria-ai

veria-ai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@greptile-apps

greptile-apps Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The changes affect alert management and future performance checks within a deployment.

Attach the required before/after screenshots before merging.

Findings

  1. P2 Required screenshots are missing ▶

Summary

Adds email-first user labels, category-wide alert actions, and Enterprise threshold editing.

  • User alerts show an email when one is available.
  • Admins can resolve or dismiss open alerts by category.
  • Enterprise admins can change the four performance alert thresholds.

Reviews (2) · Last reviewed commit: "fix(alerts): accept fractional multiplie..." · Reviewed by Greptile

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@moe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai @veria-ai

@moe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

Comment on lines +132 to +138
<AlertThresholds
thresholds={data.thresholds}
enterprise={data.alert_limit === null}
readOnly={readOnly}
pending={mutation.isPending}
save={(thresholds) => mutation.mutateAsync({ thresholds })}
/>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Required screenshots are missing

The new threshold editor lacks embedded before/after screenshots. Upload is pending. The repository’s UI QA requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@codecov

codecov Bot commented Nov 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.37931% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/repositories/alert_repository.py 25.00% 3 Missing ⚠️
litellm/proxy/alerting_endpoints/alerts.py 88.88% 1 Missing ⚠️
...tellm/repositories/performance_alert_repository.py 90.90% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Bugbot reviewed your changes and found no new issues!

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

Reviewed by Cursor Bugbot for commit 6bdbf92. Configure here.

@codspeed

codspeed Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 2 benchmarks are dominated by system calls

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

Learn more about system calls

See affected benchmarks

✅ 45 untouched benchmarks


Comparing litellm_alerts_user_email (6bdbf92) with main (4af6fb7)1

Open in CodSpeed

Footnotes

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

@moe-berri
moe-berri merged commit ea448a8 into main Nov 16, 2026
99 of 100 checks passed
@moe-berri
moe-berri deleted the litellm_alerts_user_email branch November 16, 2026 23:32
yuneng-berri added a commit that referenced this pull request Nov 23, 2026
…ges (#53940)

Brings nine tests in line with behavior that intentionally changed:

- SSO client removal: /sso/key/generate without SSO now redirects to /ui/login (#53205)
- budget partial update: /budget/info returns the app relation keys (#52477, #52787, #53232)
- performance alerts opt-out: /alerts/monitoring returns thresholds (#52139)
- cost margin rejection: the error names 'customer' as a valid key (#52406)
- regional two-image generation: Gemini gets n single-image requests (#52103)
- customer app budget key rotation: the rotated key's cleanup tolerates /key/regenerate
- DeepSeek 401: the upstream error type is relayed (#53217)
- vLLM rejected predicate: the plain upstream message is relayed (#53217). The case still
  fails on the non-OpenAI error type that #51809 fixes
- /callbacks/list e2e: the Rust spend logger is listed as spend_log (#52182)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants