Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(llma): stop provider-key assign attaching model configs to non-judge evals (#67289)

Carlos Marchalb80688bd176d
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index 2208dd3cfa79..c600d82a1f27 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -518,10 +518,13 @@ class EvaluationSerializer(serializers.ModelSerializer):
return super().create(validated_data)
def update(self, instance, validated_data):
+ # An explicit `model_configuration: null` detaches the config; a PATCH that omits the field must
+ # leave it untouched. pop()'s default can't tell the two apart, so check membership explicitly.
+ model_config_provided = "model_configuration" in validated_data
model_config_data = validated_data.pop("model_configuration", None)
old_config = None
- if model_config_data is not None:
+ if model_config_provided:
# Defer the cascade until after super().update(): SET_NULL would otherwise null
# Evaluation.model_configuration_id before ModelActivityMixin.save() snapshots
# before_update from the DB, producing a `null -> new` diff instead of `old -> new`.
diff --git a/products/ai_observability/backend/api/provider_keys.py b/products/ai_observability/backend/api/provider_keys.py
index 77b4f08d42af..59ebb48e470d 100644
--- a/products/ai_observability/backend/api/provider_keys.py
+++ b/products/ai_observability/backend/api/provider_keys.py
@@ -29,7 +29,6 @@ from ..llm.providers.azure_openai import (
is_allowed_azure_endpoint,
)
from ..models.evaluation_config import EvaluationConfig
-from ..models.evaluation_configs import EvaluationType
from ..models.evaluations import Evaluation
from ..models.model_configuration import LLMModelConfiguration
from ..models.provider_keys import LLMProvider, LLMProviderKey
@@ -440,11 +439,12 @@ class LLMProviderKeyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, v
if provider == "openai":
trial_filter |= Q(model_configuration__isnull=True)
- # Only LLM-as-a-judge evaluations use a provider key — Hog and Sentiment never do, so the
- # legacy "no model_configuration" clause above would otherwise sweep them in.
- trial_evals = Evaluation.objects.filter(
- trial_filter, team_id=self.team_id, deleted=False, evaluation_type=EvaluationType.LLM_JUDGE
- ).values("id", "name", "enabled")[:50]
+ # The legacy "no model_configuration" clause above would otherwise include Hog/Sentiment evals.
+ trial_evals = (
+ Evaluation.objects.filter(trial_filter, team_id=self.team_id, deleted=False)
+ .using_provider_keys()
+ .values("id", "name", "enabled")[:50]
+ )
return Response({"evaluations": list(trial_evals)})
@@ -479,14 +479,15 @@ class LLMProviderKeyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, v
_reload_model_config_dependents_on_commit(self.team_id, model_config_ids)
# Handle legacy evaluations (no model_configuration) — these are always
- # OpenAI, so only create a config if the key matches.
+ # OpenAI, so only create a config if the key matches. Exclude Hog/Sentiment: minting a
+ # config for them locks the eval out of all future edits.
if instance.provider == "openai":
legacy_evals = Evaluation.objects.filter(
id__in=evaluation_ids,
team_id=self.team_id,
model_configuration__isnull=True,
deleted=False,
- )
+ ).using_provider_keys()
for eval_obj in legacy_evals:
mc = LLMModelConfiguration.objects.create(
team_id=self.team_id,
@@ -502,14 +503,14 @@ class LLMProviderKeyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, v
# dependent evals — the cause no longer applies once they're attached to a live key.
for eval_obj in Evaluation.objects.filter(
id__in=evaluation_ids, team_id=self.team_id, deleted=False, status="error"
- ):
+ ).using_provider_keys():
eval_obj.set_status("paused")
evals_enabled = 0
if enable:
for eval_obj in Evaluation.objects.filter(
id__in=evaluation_ids, team_id=self.team_id, deleted=False, enabled=False
- ):
+ ).using_provider_keys():
eval_obj.set_status("active")
evals_enabled += 1
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index 5d8d9b11eaf4..f5fd8d6a5ab2 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -3,6 +3,8 @@ from uuid import uuid4
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from django.db import IntegrityError, transaction
+
from parameterized import parameterized
from rest_framework import status
@@ -378,6 +380,51 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data["attr"], "model_configuration")
+ def test_clearing_model_configuration_with_explicit_null(self):
+ mc = LLMModelConfiguration.objects.create(team=self.team, provider="openai", model="gpt-5-mini")
+ eval_obj = Evaluation.objects.create(
+ team=self.team,
+ name="Judge",
+ evaluation_type="llm_judge",
+ evaluation_config={"prompt": "Test"},
+ output_type="boolean",
+ model_configuration=mc,
+ created_by=self.user,
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",
+ {"name": "Renamed"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ eval_obj.refresh_from_db()
+ self.assertEqual(eval_obj.model_configuration_id, mc.id)
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",
+ {"model_configuration": None},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ eval_obj.refresh_from_db()
+ self.assertIsNone(eval_obj.model_configuration)
+ self.assertFalse(LLMModelConfiguration.objects.filter(id=mc.id).exists())
+
+ def test_db_constraint_blocks_model_config_on_non_judge_eval(self):
+ # QuerySet.update() bypasses Evaluation.save(), so this exercises the DB constraint itself.
+ mc = LLMModelConfiguration.objects.create(team=self.team, provider="openai", model="gpt-5-mini")
+ hog_eval = Evaluation.objects.create(
+ team=self.team,
+ name="Hog",
+ evaluation_type="hog",
+ output_type="boolean",
+ model_configuration=None,
+ )
+
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ Evaluation.objects.filter(id=hog_eval.id).update(model_configuration=mc)
+
@parameterized.expand(
[
("sentiment_boolean", "sentiment", "boolean", {}, {}),
diff --git a/products/ai_observability/backend/api/test/test_provider_keys.py b/products/ai_observability/backend/api/test/test_provider_keys.py
index 2d7824158028..8237c0769103 100644
--- a/products/ai_observability/backend/api/test/test_provider_keys.py
+++ b/products/ai_observability/backend/api/test/test_provider_keys.py
@@ -1399,3 +1399,34 @@ class TestAssignKeyEndpoint(APIBaseTest):
format="json",
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_does_not_create_config_for_hog_eval(self):
+ key = LLMProviderKey.objects.create(
+ team=self.team,
+ provider="openai",
+ name="Key",
+ state=LLMProviderKey.State.OK,
+ encrypted_config={"api_key": "sk-test"},
+ created_by=self.user,
+ )
+ hog_eval = Evaluation.objects.create(
+ team=self.team,
+ name="Hog eval",
+ evaluation_type="hog",
+ output_type="boolean",
+ model_configuration=None,
+ enabled=False,
+ )
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/llm_analytics/provider_keys/{key.id}/assign/",
+ {"evaluation_ids": [str(hog_eval.id)], "enable": True},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.data["evals_enabled"], 0)
+
+ hog_eval.refresh_from_db()
+ self.assertIsNone(hog_eval.model_configuration)
+ self.assertFalse(hog_eval.enabled)
+ self.assertEqual(LLMModelConfiguration.objects.filter(team=self.team).count(), 0)
diff --git a/products/ai_observability/backend/migrations/0012_clear_model_config_from_non_judge_evals.py b/products/ai_observability/backend/migrations/0012_clear_model_config_from_non_judge_evals.py
new file mode 100644
index 000000000000..324cd90e8717
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0012_clear_model_config_from_non_judge_evals.py
@@ -0,0 +1,55 @@
+from django.conf import settings
+from django.db import migrations
+
+# "llm_judge" is EvaluationType.LLM_JUDGE.value. Use the literal here: historical models from
+# apps.get_model() don't carry the Python enum, and Django serializes the enum to this string anyway.
+LLM_JUDGE = "llm_judge"
+
+
+def clear_model_config_from_non_judge_evals(apps, schema_editor):
+ """Detach model_configuration from evals that should never have one, then delete the orphans.
+
+ Only llm_judge evals use a model_configuration / BYOK provider key. Hog and sentiment evals
+ acquired one through the provider-key `assign` endpoint, whose legacy-eval branch created a
+ config for every passed eval without filtering on type. The save() guard added afterwards then
+ rejected every write to those evals, locking them out of all edits. This clears the bad state so
+ the CHECK constraint (added in the next migration) can validate, and unblocks the affected evals.
+
+ Validated against production (2026-06-30) before writing, both regions:
+ - Violating rows (evaluation_type <> 'llm_judge' AND model_configuration_id IS NOT NULL):
+ US: 45 (33 live + 12 deleted), all evaluation_type='hog'
+ EU: 11 (all live), all evaluation_type='hog'
+ 0 sentiment rows in either region.
+ - Distinct configs referenced by those evals: US 45, EU 11 (1:1 with the evals).
+ - Configs also referenced by a legitimate llm_judge eval: 0 in both regions — so every
+ detached config becomes a true orphan and is safe to delete. The evaluations__isnull and
+ taggers__isnull guards below still protect any config shared with an eval or a tagger
+ (Tagger also FKs LLMModelConfiguration), so a config is deleted only when nothing else
+ references it. No llm_judge eval is touched: exclude() filters them out entirely.
+ ~56 rows updated + ~56 deleted total; a single UPDATE and DELETE hold locks only momentarily,
+ matching the "tiny affected set" reasoning in 0007_retire_reports_for_deleted_evaluations.
+
+ The migration is atomic (default), so a retry (bin/migrate re-runs the whole migration on
+ failure) redoes detach+delete together rather than leaving detached-but-undeleted configs behind.
+ """
+ Evaluation = apps.get_model("ai_observability", "Evaluation")
+ LLMModelConfiguration = apps.get_model("ai_observability", "LLMModelConfiguration")
+
+ violating = Evaluation.objects.exclude(evaluation_type=LLM_JUDGE).filter(model_configuration__isnull=False)
+ orphaned_config_ids = list(violating.values_list("model_configuration_id", flat=True))
+ violating.update(model_configuration=None)
+ LLMModelConfiguration.objects.filter(
+ id__in=orphaned_config_ids, evaluations__isnull=True, taggers__isnull=True
+ ).delete()
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0011_evaluation_target"),
+ ("posthog", "1245_duckgres_sink_schema_state"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.RunPython(clear_model_config_from_non_judge_evals, migrations.RunPython.noop),
+ ]
diff --git a/products/ai_observability/backend/migrations/0013_add_model_config_only_on_llm_judge.py b/products/ai_observability/backend/migrations/0013_add_model_config_only_on_llm_judge.py
new file mode 100644
index 000000000000..13fedfc5a671
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0013_add_model_config_only_on_llm_judge.py
@@ -0,0 +1,29 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import AddConstraintNotValid
+
+# "llm_judge" is EvaluationType.LLM_JUDGE.value; see 0012 for why the literal is used here.
+LLM_JUDGE = "llm_judge"
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0012_clear_model_config_from_non_judge_evals"),
+ ]
+
+ operations = [
+ # Enforce going forward: model_configuration may only be set on llm_judge evals. NOT VALID
+ # skips the existing-row scan (0012 already cleaned it) but enforces on every new write
+ # immediately. ValidateConstraint in 0014 scans the existing rows without blocking traffic.
+ AddConstraintNotValid(
+ model_name="evaluation",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ ("model_configuration__isnull", True),
+ ("evaluation_type", LLM_JUDGE),
+ _connector="OR",
+ ),
+ name="model_config_only_on_llm_judge",
+ ),
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/0014_validate_model_config_only_on_llm_judge.py b/products/ai_observability/backend/migrations/0014_validate_model_config_only_on_llm_judge.py
new file mode 100644
index 000000000000..5fae638aa5e6
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0014_validate_model_config_only_on_llm_judge.py
@@ -0,0 +1,14 @@
+from django.db import migrations
+
+from posthog.migration_helpers import ValidateConstraint
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0013_add_model_config_only_on_llm_judge"),
+ ]
+
+ operations = [
+ # Validate the cleaned existing rows under SHARE UPDATE EXCLUSIVE (does not block traffic).
+ ValidateConstraint(model_name="evaluation", name="model_config_only_on_llm_judge"),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index 226fd029ba8a..d53db48043c3 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_evaluation_target
+0014_validate_model_config_only_on_llm_judge
diff --git a/products/ai_observability/backend/models/evaluations.py b/products/ai_observability/backend/models/evaluations.py
index 0ebe3d6d0a2a..1759bbcedbd7 100644
--- a/products/ai_observability/backend/models/evaluations.py
+++ b/products/ai_observability/backend/models/evaluations.py
@@ -43,6 +43,11 @@ class EvaluationStatusReason(models.TextChoices):
HOG_ERROR = "hog_error", "Hog evaluation code failed"
+class EvaluationQuerySet(models.QuerySet):
+ def using_provider_keys(self) -> "EvaluationQuerySet":
+ return self.filter(evaluation_type=EvaluationType.LLM_JUDGE)
+
+
class EvaluationTarget(models.TextChoices):
GENERATION = "generation", "Generation"
TRACE = "trace", "Trace"
@@ -57,6 +62,15 @@ class Evaluation(ModelActivityMixin, UUIDTModel):
models.Index(fields=["team", "enabled"]),
models.Index(fields=["model_configuration"], name="llm_analyti_model_c_idx"),
]
+ constraints = [
+ models.CheckConstraint(
+ name="model_config_only_on_llm_judge",
+ condition=models.Q(model_configuration__isnull=True)
+ | models.Q(evaluation_type=EvaluationType.LLM_JUDGE),
+ ),
+ ]
+
+ objects = EvaluationQuerySet.as_manager()
# Core fields
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)