Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(policy_engine): restore config policy immediately when its DB override is removed and keep same-named DB drafts reachable in the UI

mateo-berri35f770f43e10
diff --git a/litellm/proxy/policy_engine/policy_registry.py b/litellm/proxy/policy_engine/policy_registry.py
index 9456afaa1b9..7d2b439270a 100644
--- a/litellm/proxy/policy_engine/policy_registry.py
+++ b/litellm/proxy/policy_engine/policy_registry.py
@@ -340,7 +340,8 @@ class PolicyRegistry:
def remove_policy(self, policy_name: str) -> bool:
"""
- Remove a policy by name.
+ Remove a policy by name. If a config-defined policy shares the name,
+ it is restored immediately instead of waiting for the next DB sync.
Args:
policy_name: Name of the policy to remove
@@ -348,12 +349,18 @@ class PolicyRegistry:
Returns:
True if policy was removed, False if it didn't exist
"""
- if policy_name in self._policies:
- del self._policies[policy_name]
- self._sources = {name: source for name, source in self._sources.items() if name != policy_name}
- verbose_proxy_logger.debug(f"Removed policy: {policy_name}")
+ if policy_name not in self._policies:
+ return False
+ config_fallback = self._config_policies.get(policy_name)
+ if config_fallback is not None:
+ self._policies[policy_name] = config_fallback
+ self._sources = {**self._sources, policy_name: "config"}
+ verbose_proxy_logger.debug(f"Removed policy: {policy_name}; restored config-defined version")
return True
- return False
+ del self._policies[policy_name]
+ self._sources = {name: source for name, source in self._sources.items() if name != policy_name}
+ verbose_proxy_logger.debug(f"Removed policy: {policy_name}")
+ return True
# ─────────────────────────────────────────────────────────────────────────
# Database CRUD Methods
@@ -527,10 +534,15 @@ class PolicyRegistry:
# Remove from in-memory registry only if this was the production version
if version_status == "production":
self.remove_policy(policy_name)
- result["warning"] = (
- "Production version was deleted. No other version was promoted. "
- "Promote another version to production if this policy should remain active."
- )
+ if self.get_source(policy_name) == "config":
+ result["warning"] = (
+ "Production version was deleted. The config-defined policy with the same name is active again."
+ )
+ else:
+ result["warning"] = (
+ "Production version was deleted. No other version was promoted. "
+ "Promote another version to production if this policy should remain active."
+ )
return result
except Exception as e:
diff --git a/tests/test_litellm/proxy/policy_engine/test_policy_versioning.py b/tests/test_litellm/proxy/policy_engine/test_policy_versioning.py
index ae80373ee23..41d856e7baf 100644
--- a/tests/test_litellm/proxy/policy_engine/test_policy_versioning.py
+++ b/tests/test_litellm/proxy/policy_engine/test_policy_versioning.py
@@ -556,3 +556,66 @@ class TestConfigPoliciesPreservedAcrossDbSync:
assert not registry.has_policy("config-policy")
assert registry.get_source("config-policy") is None
+
+
+class TestRemovePolicyRestoresConfigFallback:
+ """Deleting a same-named DB override must re-activate the config policy immediately, not at the next sync."""
+
+ def test_remove_policy_restores_config_version_immediately(self):
+ registry = PolicyRegistry()
+ registry.load_policies({"shared-name": {"guardrails": {"add": ["config-guard"]}}})
+ registry.add_policy("shared-name", Policy(guardrails=PolicyGuardrails(add=["db-guard"])), source="db")
+
+ assert registry.remove_policy("shared-name") is True
+
+ policy = registry.get_policy("shared-name")
+ assert policy is not None
+ assert policy.guardrails.add == ["config-guard"]
+ assert registry.get_source("shared-name") == "config"
+
+ def test_remove_policy_without_config_fallback_removes_entirely(self):
+ registry = PolicyRegistry()
+ registry.add_policy("db-only", Policy(guardrails=PolicyGuardrails(add=["db-guard"])))
+
+ assert registry.remove_policy("db-only") is True
+
+ assert not registry.has_policy("db-only")
+ assert registry.get_source("db-only") is None
+
+ def test_remove_missing_policy_returns_false(self):
+ registry = PolicyRegistry()
+
+ assert registry.remove_policy("missing") is False
+
+ @pytest.mark.asyncio
+ async def test_delete_production_override_reactivates_config_policy_and_says_so(self):
+ registry = PolicyRegistry()
+ registry.load_policies({"shared-name": {"guardrails": {"add": ["config-guard"]}}})
+ registry.add_policy("shared-name", Policy(guardrails=PolicyGuardrails(add=["db-guard"])), source="db")
+ prisma = MagicMock()
+ prod_row = _make_row(policy_id="prod-1", policy_name="shared-name", version_status="production")
+ prisma.db.litellm_policytable.find_unique = AsyncMock(return_value=prod_row)
+ prisma.db.litellm_policytable.delete = AsyncMock()
+
+ result = await registry.delete_policy_from_db(policy_id="prod-1", prisma_client=prisma)
+
+ assert "config" in result["warning"]
+ policy = registry.get_policy("shared-name")
+ assert policy is not None
+ assert policy.guardrails.add == ["config-guard"]
+ assert registry.get_source("shared-name") == "config"
+
+ @pytest.mark.asyncio
+ async def test_delete_all_versions_reactivates_config_policy(self):
+ registry = PolicyRegistry()
+ registry.load_policies({"shared-name": {"guardrails": {"add": ["config-guard"]}}})
+ registry.add_policy("shared-name", Policy(guardrails=PolicyGuardrails(add=["db-guard"])), source="db")
+ prisma = MagicMock()
+ prisma.db.litellm_policytable.delete_many = AsyncMock()
+
+ await registry.delete_all_versions(policy_name="shared-name", prisma_client=prisma)
+
+ assert registry.get_source("shared-name") == "config"
+ policy = registry.get_policy("shared-name")
+ assert policy is not None
+ assert policy.guardrails.add == ["config-guard"]
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/PolicyTable.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/PolicyTable.test.tsx
index 06c939aa151..9be1bd60ec8 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/PolicyTable.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/PolicyTable.test.tsx
@@ -145,4 +145,34 @@ describe("PolicyTable", () => {
await user.click(screen.getByRole("button", { name: /grouped/ }));
expect(defaultProps.onViewClick).toHaveBeenCalledWith("prod-id");
});
+
+ const sameNamedDbDraft: Partial<Policy> = {
+ policy_name: "config-policy",
+ policy_id: "db-draft-id",
+ version_status: "draft",
+ version_number: 2,
+ };
+ const configTwin: Partial<Policy> = {
+ policy_name: "config-policy",
+ policy_id: "config-policy",
+ version_status: "production",
+ definition_location: "config",
+ };
+
+ it("should render a config policy and a same-named DB draft as separate rows", () => {
+ const policies = [makePolicy(sameNamedDbDraft), makePolicy(configTwin)];
+ renderWithProviders(<PolicyTable {...defaultProps} policies={policies} />);
+ expect(screen.getAllByText("config-policy")).toHaveLength(2);
+ expect(screen.getByText("Config")).toBeInTheDocument();
+ });
+
+ it("should keep a same-named DB draft reachable next to a config policy", async () => {
+ const user = userEvent.setup();
+ const policies = [makePolicy(sameNamedDbDraft), makePolicy(configTwin)];
+ renderWithProviders(<PolicyTable {...defaultProps} policies={policies} />);
+ await user.click(screen.getByRole("button", { name: "config-policy" }));
+ expect(defaultProps.onViewClick).toHaveBeenCalledWith("db-draft-id");
+ await user.click(screen.getByTestId("policy-actions-db-draft-id"));
+ expect(await screen.findByTestId("policy-action-edit")).not.toHaveAttribute("data-disabled");
+ });
});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/PolicyTable.tsx b/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/PolicyTable.tsx
index d6e841c2119..3405ac6b6bb 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/PolicyTable.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/policies/_components/PolicyTable.tsx
@@ -9,16 +9,21 @@ import { Policy } from "@/components/policies/types";
import { getPolicyTableColumns, PolicyRow } from "./PolicyTableColumns";
-/** One row per policy name; primaryPolicy is used for display and for Edit (FlowBuilder loads all versions) */
+/** One row per DB policy name plus one row per config policy, so a config policy never hides same-named DB versions; primaryPolicy is used for display and for Edit (FlowBuilder loads all versions) */
function groupPoliciesByName(policies: Policy[]): PolicyRow[] {
- const names = Array.from(new Set(policies.map((policy) => policy.policy_name || "(unnamed)")));
- return names.map((policyName) => {
- const versions = policies.filter((policy) => (policy.policy_name || "(unnamed)") === policyName);
+ const dbPolicies = policies.filter((policy) => policy.definition_location !== "config");
+ const names = Array.from(new Set(dbPolicies.map((policy) => policy.policy_name || "(unnamed)")));
+ const dbRows = names.map((policyName) => {
+ const versions = dbPolicies.filter((policy) => (policy.policy_name || "(unnamed)") === policyName);
const primary =
versions.find((version) => version.version_status === "production") ??
[...versions].sort((a, b) => (b.version_number ?? 0) - (a.version_number ?? 0))[0];
return { policy_name: policyName, primaryPolicy: primary, versionCount: versions.length };
});
+ const configRows = policies
+ .filter((policy) => policy.definition_location === "config")
+ .map((policy) => ({ policy_name: policy.policy_name || "(unnamed)", primaryPolicy: policy, versionCount: 1 }));
+ return [...dbRows, ...configRows];
}
interface PolicyTableProps {
@@ -67,7 +72,7 @@ const PolicyTable: React.FC<PolicyTableProps> = ({
<DataTable
data={rows}
columns={columns}
- getRowId={(row) => row.policy_name}
+ getRowId={(row) => `${row.primaryPolicy.definition_location ?? "db"}:${row.policy_name}`}
sortingMode="client"
sorting={sorting}
onSortingChange={setSorting}