: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(llma): deprecate trial evals behind a grandfathering window (#68234)
Carlos Marchal82d6bcae9701
diff --git a/nodejs/src/ai-observability/types.ts b/nodejs/src/ai-observability/types.tsindex 8ff3b87dcd56..6f821d42fb3b 100644--- a/nodejs/src/ai-observability/types.ts+++ b/nodejs/src/ai-observability/types.ts@@ -2,7 +2,19 @@ import { HogBytecode } from '../cdp/types'import { PropertyFilter } from '../types'export type EvaluationStatus = 'active' | 'paused' | 'error'-export type EvaluationStatusReason = 'trial_limit_reached' | 'model_not_allowed' | 'provider_key_deleted'+// Keep in sync with EvaluationStatusReason in products/ai_observability/backend/models/evaluations.py+export type EvaluationStatusReason =+ | 'provider_key_required'+ | 'trial_limit_reached'+ | 'model_not_allowed'+ | 'provider_key_deleted'+ | 'no_default_model'+ | 'provider_key_invalid'+ | 'provider_key_permission_denied'+ | 'provider_key_quota_exceeded'+ | 'provider_key_rate_limited'+ | 'model_not_found'+ | 'hog_error'export type EvaluationTarget = 'generation' | 'trace'export interface Evaluation {diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.pyindex 94e009ac8b6c..6915e6de784d 100644--- a/posthog/settings/base_variables.py+++ b/posthog/settings/base_variables.py@@ -1,5 +1,6 @@import osimport sys+from datetime import datetimeimport structlog@@ -67,6 +68,14 @@ GITHUB_SECRET_ALERT_RELAY_URL: str | None = get_from_env("GITHUB_SECRET_ALERT_RE# Override in tests via @override_settings to point at a per-test team.LLM_ANALYTICS_INTERNAL_TEAM_ID: int = 2+# Override for the AI observability trial-eval deprecation cutoff+AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE: str | None = get_from_env(+ "AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE", optional=True+)+if AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE:+ # Fail at boot on a malformed value rather than 500ing requests and temporal runs later.+ datetime.fromisoformat(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE)+# Duckgres - URL, internal secret, and PG endpoint for the managed warehouse serviceDUCKGRES_API_URL: str | None = get_from_env("DUCKGRES_API_URL", optional=True)DUCKGRES_INTERNAL_SECRET: str | None = get_from_env("DUCKGRES_INTERNAL_SECRET", optional=True)diff --git a/posthog/temporal/ai_observability/evaluation_errors.py b/posthog/temporal/ai_observability/evaluation_errors.pyindex 0715fbff1acd..9ddb1cf2efe8 100644--- a/posthog/temporal/ai_observability/evaluation_errors.py+++ b/posthog/temporal/ai_observability/evaluation_errors.py@@ -31,6 +31,13 @@ class EvaluationErrorSpec:USER_ERROR_SPECS: dict[str, EvaluationErrorSpec] = {+ "provider_key_required": EvaluationErrorSpec(+ error_type="provider_key_required",+ owner="user",+ safe_message="Add a provider API key to run this evaluation.",+ status_reason=EvaluationStatusReason.PROVIDER_KEY_REQUIRED,+ disables_evaluation=True,+ ),"trial_limit_reached": EvaluationErrorSpec(error_type="trial_limit_reached",owner="user",diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.pyindex 1eaf6bd2252e..df1a528c6dbc 100644--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py@@ -139,7 +139,7 @@ async def disable_evaluation_activity("""def _disable() -> bool:- reason = status_reason or "trial_limit_reached"+ reason = status_reason or "provider_key_required"with transaction.atomic():evaluation = Evaluation.objects.select_for_update().filter(id=evaluation_id, team_id=team_id).first()if evaluation is None:@@ -185,6 +185,12 @@ async def send_trial_usage_email_activity(inputs: SendTrialUsageEmailInputs) ->if not config:return+ # provider_key_required disables also route here with threshold 100, but they can fire for+ # teams cut off mid-trial at the deprecation date or that never started — for those, "used+ # up" would be false, so only send when the trial was actually exhausted.+ if inputs.threshold_pct >= 100 and config.trial_evals_used < config.trial_eval_limit:+ return+max_listed = 20affected_qs = Evaluation.objects.filter(team_id=inputs.team_id,@@ -248,6 +254,7 @@ class SendEvaluationDisabledEmailInputs:_STATUS_REASON_SUBJECTS = {+ "provider_key_required": "Your AI observability evaluation was disabled because it has no provider API key","model_not_allowed": "Your AI observability evaluation was disabled because its model isn't supported on the trial plan","no_default_model": "Your AI observability evaluation was disabled because no default model is configured","provider_key_deleted": "Your AI observability evaluation was disabled because its provider API key was removed",diff --git a/posthog/temporal/ai_observability/model_resolution.py b/posthog/temporal/ai_observability/model_resolution.pyindex 34879559d989..4321b08d19f1 100644--- a/posthog/temporal/ai_observability/model_resolution.py+++ b/posthog/temporal/ai_observability/model_resolution.py@@ -2,9 +2,10 @@`model_configuration` is optional on both `Evaluation` and `Tagger`. A null value is not"unconfigured" — it means "defer to the team's active key, falling back to PostHog trial-credits". `model_spec()` turns the (possibly null) serialized config into a `ModelSpec`-whose `resolve()` produces a concrete `ResolvedModel`, so judge and tagger share one-definition of what null means instead of each re-deriving it.+credits while the team is still grandfathered into the trial (see `is_trial_grandfathered`)".+`model_spec()` turns the (possibly null) serialized config into a `ModelSpec` whose `resolve()`+produces a concrete `ResolvedModel`, so judge and tagger share one definition of what null+means instead of each re-deriving it.Lives in the temporal layer because `resolve()` raises Temporal `ApplicationError`s whose`error_type` details the workflows pattern-match on (disable, key-state updates, emails).@@ -59,6 +60,7 @@ class ExplicitModelSpec:if fallback is not None:return ResolvedModel(self.provider, self.model, _ensure_usable(fallback))+ _assert_funded_inference_allowed(config)if self.model not in TRIAL_MODEL_IDS:raise ApplicationError(f"Model '{self.model}' is not available on the trial plan. "@@ -66,19 +68,18 @@ class ExplicitModelSpec:{"error_type": "model_not_allowed", "model": self.model},non_retryable=True,)- _assert_trial_quota(config)return ResolvedModel(self.provider, self.model, None)@dataclass(frozen=True)class DefaultModelSpec:- """Null config: defer to the team's active BYOK key, else PostHog trial credits."""+ """Null config: defer to the team's active BYOK key, else PostHog trial credits while grandfathered."""def resolve(self, team_id: int) -> ResolvedModel:config = _eval_config(team_id)key = config.active_provider_keyif key is None:- _assert_trial_quota(config)+ _assert_funded_inference_allowed(config)return ResolvedModel(TRIAL_DEFAULT_PROVIDER, DEFAULT_MODEL_BY_PROVIDER[TRIAL_DEFAULT_PROVIDER], None)model = DEFAULT_MODEL_BY_PROVIDER.get(key.provider)@@ -112,11 +113,11 @@ def _eval_config(team_id: int) -> EvaluationConfig:return config-def _assert_trial_quota(config: EvaluationConfig) -> None:- if config.trial_evals_used >= config.trial_eval_limit:+def _assert_funded_inference_allowed(config: EvaluationConfig) -> None:+ if not config.is_trial_grandfathered:raise ApplicationError(- f"Trial evaluation limit ({config.trial_eval_limit}) reached. Add your own API key to continue.",- {"error_type": "trial_limit_reached", "trial_eval_limit": config.trial_eval_limit},+ "Add a provider API key to run this evaluation.",+ {"error_type": "provider_key_required"},non_retryable=True,)diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.pyindex e8353f2e7455..8fda4281aef3 100644--- a/posthog/temporal/ai_observability/run_tagger.py+++ b/posthog/temporal/ai_observability/run_tagger.py@@ -617,13 +617,19 @@ class RunTaggerWorkflow(PostHogWorkflow):error_type = details.get("error_type")if error_type in (+ "provider_key_required","trial_limit_reached","key_invalid","parse_error","model_not_allowed","no_default_model",):- if error_type in ("trial_limit_reached", "model_not_allowed", "no_default_model"):+ if error_type in (+ "provider_key_required",+ "trial_limit_reached",+ "model_not_allowed",+ "no_default_model",+ ):await temporalio.workflow.execute_activity(disable_tagger_activity,args=[tagger["id"], tagger["team_id"]],@@ -631,6 +637,7 @@ class RunTaggerWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=2),)if error_type in (+ "provider_key_required","trial_limit_reached","model_not_allowed",) and temporalio.workflow.patched("trial-usage-email"):diff --git a/posthog/temporal/ai_observability/test_model_resolution.py b/posthog/temporal/ai_observability/test_model_resolution.pyindex 7e4ceb11b2c0..5748724a137a 100644--- a/posthog/temporal/ai_observability/test_model_resolution.py+++ b/posthog/temporal/ai_observability/test_model_resolution.py@@ -12,6 +12,13 @@ from products.ai_observability.backend.models.evaluation_config import Evaluatiofrom products.ai_observability.backend.models.provider_keys import LLMProviderKey[email protected](autouse=True)+def _future_deprecation_date(settings):+ # Pin the trial cutoff far in the future so grandfathering (0 < used < limit) is deterministic+ # regardless of the wall clock the suite runs on. Cutoff-specific tests override this locally.+ settings.AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE = "2999-12-31T00:00:00+00:00"++@pytest.fixturedef team():organization = Organization.objects.create(name="Test Org")@@ -28,6 +35,10 @@ def _key(team, provider, state=LLMProviderKey.State.OK):)+def _grandfathered_config(team, **kwargs):+ return EvaluationConfig.objects.create(team=team, trial_eval_limit=100, trial_evals_used=50, **kwargs)++def _error_type(exc_info):return exc_info.value.details[0]["error_type"]@@ -65,21 +76,35 @@ class TestExplicitModelSpec:ExplicitModelSpec("openai", "gpt-5", str(key.id)).resolve(team.id)assert _error_type(exc_info) == "key_invalid"- def test_trial_allowlisted_model_resolves_without_key(self, team):+ def test_grandfathered_trial_allowlisted_model_resolves_without_key(self, team):+ _grandfathered_config(team)resolved = ExplicitModelSpec("openai", "gpt-5-mini", None).resolve(team.id)assert resolved.provider_key is Noneassert not resolved.is_byok- def test_trial_non_allowlisted_model_raises_model_not_allowed(self, team):+ def test_grandfathered_non_allowlisted_model_raises_model_not_allowed(self, team):+ _grandfathered_config(team)with pytest.raises(ApplicationError) as exc_info:ExplicitModelSpec("openai", "gpt-5", None).resolve(team.id)assert _error_type(exc_info) == "model_not_allowed"- def test_trial_quota_exhausted_raises_trial_limit_reached(self, team):+ def test_no_trial_usage_requires_provider_key(self, team):+ with pytest.raises(ApplicationError) as exc_info:+ ExplicitModelSpec("openai", "gpt-5-mini", None).resolve(team.id)+ assert _error_type(exc_info) == "provider_key_required"++ def test_exhausted_trial_requires_provider_key(self, team):EvaluationConfig.objects.create(team=team, trial_eval_limit=100, trial_evals_used=100)with pytest.raises(ApplicationError) as exc_info:ExplicitModelSpec("openai", "gpt-5-mini", None).resolve(team.id)- assert _error_type(exc_info) == "trial_limit_reached"+ assert _error_type(exc_info) == "provider_key_required"++ def test_past_cutoff_requires_provider_key(self, team, settings):+ settings.AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE = "2000-01-01T00:00:00+00:00"+ _grandfathered_config(team)+ with pytest.raises(ApplicationError) as exc_info:+ ExplicitModelSpec("openai", "gpt-5-mini", None).resolve(team.id)+ assert _error_type(exc_info) == "provider_key_required"def test_null_key_falls_back_to_matching_active_key_despite_exhausted_quota(self, team):# Regression: an eval whose model config pinned a model but no key was blocked with@@ -94,7 +119,7 @@ class TestExplicitModelSpec:def test_null_key_ignores_active_key_of_a_different_provider(self, team):key = _key(team, "anthropic")- EvaluationConfig.objects.create(team=team, active_provider_key=key)+ _grandfathered_config(team, active_provider_key=key)resolved = ExplicitModelSpec("openai", "gpt-5-mini", None).resolve(team.id)@@ -104,18 +129,24 @@ class TestExplicitModelSpec:@pytest.mark.django_dbclass TestDefaultModelSpec:- def test_no_active_key_falls_back_to_posthog_trial(self, team):+ def test_grandfathered_no_active_key_falls_back_to_posthog_trial(self, team):+ _grandfathered_config(team)resolved = DefaultModelSpec().resolve(team.id)assert resolved.provider == "openai"assert resolved.model == DEFAULT_MODEL_BY_PROVIDER["openai"]assert resolved.provider_key is Noneassert not resolved.is_byok- def test_no_active_key_with_exhausted_quota_raises_trial_limit_reached(self, team):+ def test_no_active_key_no_trial_usage_requires_provider_key(self, team):+ with pytest.raises(ApplicationError) as exc_info:+ DefaultModelSpec().resolve(team.id)+ assert _error_type(exc_info) == "provider_key_required"++ def test_no_active_key_exhausted_requires_provider_key(self, team):EvaluationConfig.objects.create(team=team, trial_eval_limit=100, trial_evals_used=100)with pytest.raises(ApplicationError) as exc_info:DefaultModelSpec().resolve(team.id)- assert _error_type(exc_info) == "trial_limit_reached"+ assert _error_type(exc_info) == "provider_key_required"def test_anthropic_active_key_resolves_to_anthropic_default(self, team):# Regression: a null config with an Anthropic active key used to resolve to openai/gpt-5-minidiff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 1acae3d9a05b..13b685a4305c 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -128,6 +128,13 @@ def setup_data():return {"organization": organization, "team": team, "evaluation": evaluation}+def grandfathered(setup_data, settings):+ # A team mid-trial before the cutoff keeps PostHog-funded inference, so trial/keyless judges run.+ settings.AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE = "2999-12-31T00:00:00+00:00"+ EvaluationConfig.objects.create(team=setup_data["team"], trial_eval_limit=100, trial_evals_used=50)++class TestRunEvaluationWorkflow:@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)@@ -164,7 +171,7 @@ class TestRunEvaluationWorkflow:assert result["output_config"] == {"allows_na": False}@pytest.mark.django_db(transaction=True)- def test_execute_llm_judge_activity(self, setup_data):+ def test_execute_llm_judge_activity(self, setup_data, grandfathered):"""Test LLM judge execution with realistic message array format"""evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -216,7 +223,7 @@ class TestRunEvaluationWorkflow:],)@pytest.mark.django_db(transaction=True)- def test_execute_llm_judge_activity_bounds_oversized_input(self, oversized_input, setup_data):+ def test_execute_llm_judge_activity_bounds_oversized_input(self, oversized_input, setup_data, grandfathered):team = setup_data["team"]evaluation_obj = setup_data["evaluation"]@@ -611,7 +618,7 @@ class TestRunEvaluationWorkflow:assert result["skip_reason"] == "hog_error"@pytest.mark.django_db(transaction=True)- def test_execute_llm_judge_activity_allows_na_applicable(self, setup_data):+ def test_execute_llm_judge_activity_allows_na_applicable(self, setup_data, grandfathered):"""Test LLM judge execution with allows_na=True when applicable"""evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -653,7 +660,7 @@ class TestRunEvaluationWorkflow:assert result["allows_na"] is True@pytest.mark.django_db(transaction=True)- def test_execute_llm_judge_activity_allows_na_not_applicable(self, setup_data):+ def test_execute_llm_judge_activity_allows_na_not_applicable(self, setup_data, grandfathered):"""Test LLM judge execution with allows_na=True when not applicable"""evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -792,7 +799,9 @@ class TestRunEvaluationWorkflow:],)@pytest.mark.django_db(transaction=True)- def test_execute_llm_judge_activity_does_not_skip_when_not_errored(self, error_props: dict[str, Any], setup_data):+ def test_execute_llm_judge_activity_does_not_skip_when_not_errored(+ self, error_props: dict[str, Any], setup_data, grandfathered+ ):"""Sanity check: traces without `$ai_is_error=true` still flow through to the LLM judge."""evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -1067,7 +1076,7 @@ class TestRunEvaluationWorkflow:)@pytest.mark.django_db(transaction=True)def test_execute_llm_judge_activity_unhandled_exception_uses_class_name(- self, raised_exception: Exception, expected_label: str, setup_data+ self, raised_exception: Exception, expected_label: str, setup_data, grandfathered):evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -1097,8 +1106,11 @@ class TestRunEvaluationWorkflow:mock_increment_errors.assert_called_once_with(expected_label, provider="openai")@pytest.mark.django_db(transaction=True)- def test_execute_llm_judge_activity_rejects_non_trial_model_on_posthog_key(self, setup_data):+ def test_execute_llm_judge_activity_rejects_non_trial_model_on_posthog_key(self, setup_data, settings):team = setup_data["team"]+ # Only a grandfathered team gets past the funded gate to the model-allowlist check.+ settings.AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE = "2999-12-31T00:00:00+00:00"+ EvaluationConfig.objects.create(team=team, trial_eval_limit=100, trial_evals_used=50)evaluation = {"id": str(setup_data["evaluation"].id),@@ -1133,6 +1145,43 @@ class TestRunEvaluationWorkflow:assert result["status_reason"] == "model_not_allowed"assert result["verdict"] is None+ @pytest.mark.django_db(transaction=True)+ def test_execute_llm_judge_activity_terminal_team_requires_provider_key(self, setup_data):+ team = setup_data["team"]++ evaluation = {+ "id": str(setup_data["evaluation"].id),+ "name": "Test Evaluation",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Is this accurate?"},+ "output_type": "boolean",+ "output_config": {},+ "team_id": team.id,+ "model_configuration": {+ "provider": "openai",+ "model": "gpt-5-mini",+ "provider_key_id": None,+ },+ }++ event_data = create_mock_event_data(team.id)++ with (+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class,+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.increment_user_errors") as mock_user_errors,+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.increment_errors") as mock_errors,+ ):+ result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))++ mock_client_class.assert_not_called()+ mock_user_errors.assert_called_once_with("provider_key_required", provider=None)+ mock_errors.assert_not_called()+ assert result["terminal_user_error"] is True+ assert result["skipped"] is True+ assert result["skip_reason"] == "provider_key_required"+ assert result["status_reason"] == "provider_key_required"+ assert result["verdict"] is None+@pytest.mark.parametrize("raised_exception, skip_reason, status_reason, provider_key_state",[@@ -1907,7 +1956,7 @@ class TestSendTrialUsageEmailActivity:)async def test_sends_correct_template_for_threshold(self, setup_data, threshold_pct, expected_template):team = setup_data["team"]- await sync_to_async(EvaluationConfig.objects.get_or_create)(team_id=team.id)+ await sync_to_async(EvaluationConfig.objects.get_or_create)(team_id=team.id, defaults={"trial_evals_used": 100})with (patch("posthog.email.is_email_available", return_value=True),@@ -1925,6 +1974,22 @@ class TestSendTrialUsageEmailActivity:assert call_kwargs["template_name"] == expected_templatemock_message.send.assert_called_once()+ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_skips_exhausted_email_when_trial_not_actually_exhausted(self, setup_data):+ # provider_key_required disables route here with threshold 100 for teams cut off mid-trial+ # at the deprecation date or that never started — "used up" would be false for them.+ team = setup_data["team"]+ await sync_to_async(EvaluationConfig.objects.get_or_create)(team_id=team.id, defaults={"trial_evals_used": 50})++ with (+ patch("posthog.email.is_email_available", return_value=True),+ patch("posthog.email.EmailMessage") as mock_email_class,+ ):+ await send_trial_usage_email_activity(SendTrialUsageEmailInputs(team_id=team.id, threshold_pct=100))++ mock_email_class.assert_not_called()+@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)async def test_skips_when_email_not_available(self, setup_data):@@ -1944,7 +2009,7 @@ class TestSendTrialUsageEmailActivity:@pytest.mark.parametrize("threshold_pct", [50, 75, 100], ids=["50pct", "75pct", "100pct"])async def test_campaign_key_includes_threshold_and_team(self, setup_data, threshold_pct):team = setup_data["team"]- await sync_to_async(EvaluationConfig.objects.get_or_create)(team_id=team.id)+ await sync_to_async(EvaluationConfig.objects.get_or_create)(team_id=team.id, defaults={"trial_evals_used": 100})with (patch("posthog.email.is_email_available", return_value=True),diff --git a/posthog/temporal/ai_observability/test_run_tagger.py b/posthog/temporal/ai_observability/test_run_tagger.pyindex 1af893e90ea9..f6097ee6e9e3 100644--- a/posthog/temporal/ai_observability/test_run_tagger.py+++ b/posthog/temporal/ai_observability/test_run_tagger.py@@ -181,8 +181,8 @@ class TestRunTaggerWorkflow:with patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config:mock_config = MagicMock()mock_config.active_provider_key = None- mock_config.trial_evals_used = 0- mock_config.trial_eval_limit = 100+ # A bare MagicMock auto-returns a truthy child for the real @property — pin it explicitly.+ mock_config.is_trial_grandfathered = Truemock_eval_config.objects.get_or_create.return_value = (mock_config, False)result = await execute_tagger_activity(ExecuteTaggerInputs(tagger=tagger, event_data=event_data))@@ -223,8 +223,7 @@ class TestRunTaggerWorkflow:with patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config:mock_config = MagicMock()mock_config.active_provider_key = None- mock_config.trial_evals_used = 0- mock_config.trial_eval_limit = 100+ mock_config.is_trial_grandfathered = Truemock_eval_config.objects.get_or_create.return_value = (mock_config, False)result = await execute_tagger_activity(ExecuteTaggerInputs(tagger=tagger, event_data=event_data))@@ -266,8 +265,7 @@ class TestRunTaggerWorkflow:with patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config:mock_config = MagicMock()mock_config.active_provider_key = None- mock_config.trial_evals_used = 0- mock_config.trial_eval_limit = 100+ mock_config.is_trial_grandfathered = Truemock_eval_config.objects.get_or_create.return_value = (mock_config, False)result = await execute_tagger_activity(ExecuteTaggerInputs(tagger=tagger, event_data=event_data))@@ -277,7 +275,7 @@ class TestRunTaggerWorkflow:@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)- async def test_execute_tagger_trial_limit_reached(self, setup_data):+ async def test_execute_tagger_terminal_team_requires_provider_key(self, setup_data):tagger_obj = setup_data["tagger"]team = setup_data["team"]@@ -293,13 +291,15 @@ class TestRunTaggerWorkflow:with patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config:mock_config = MagicMock()mock_config.active_provider_key = None- mock_config.trial_evals_used = 100- mock_config.trial_eval_limit = 100+ # A bare MagicMock would return a truthy child and silently pass the funded gate.+ mock_config.is_trial_grandfathered = Falsemock_eval_config.objects.get_or_create.return_value = (mock_config, False)- with pytest.raises(ApplicationError, match="Trial evaluation limit"):+ with pytest.raises(ApplicationError) as exc_info:await execute_tagger_activity(ExecuteTaggerInputs(tagger=tagger, event_data=event_data))+ assert exc_info.value.details[0]["error_type"] == "provider_key_required"+@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)async def test_execute_tagger_missing_prompt(self, setup_data):diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.pyindex 4ec3aac83c11..1c9be99c311f 100644--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py@@ -11,6 +11,7 @@ from posthog.schema import LLMTrace, LLMTraceEventfrom posthog.cdp.validation import compile_hogfrom posthog.models import Organization, Team+from products.ai_observability.backend.models.evaluation_config import EvaluationConfigfrom products.ai_observability.backend.models.evaluations import Evaluationfrom .evaluation_llm_judge import BooleanEvalResult@@ -72,6 +73,13 @@ def setup_data():return {"organization": organization, "team": team, "evaluation": evaluation}+def grandfathered(setup_data, settings):+ # A team mid-trial before the cutoff keeps PostHog-funded inference, so trial/keyless judges run.+ settings.AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE = "2999-12-31T00:00:00+00:00"+ EvaluationConfig.objects.create(team=setup_data["team"], trial_eval_limit=100, trial_evals_used=50)++def evaluation_dict(setup_data: dict, **overrides: Any) -> dict[str, Any]:defaults = {"id": str(setup_data["evaluation"].id),@@ -250,7 +258,7 @@ class TestFetchTraceForEvaluation:class TestExecuteTraceLLMJudgeActivity:@pytest.mark.django_db(transaction=True)- def test_judges_full_trace_transcript(self, setup_data):+ def test_judges_full_trace_transcript(self, setup_data, grandfathered):trace = create_trace([create_trace_event("$ai_generation", **{"$ai_input": "What is 2+2?", "$ai_output": "4"}),diff --git a/posthog/test/activity_logging/test_evaluation_activity_logging.py b/posthog/test/activity_logging/test_evaluation_activity_logging.pyindex e039646d77b7..e5a50489cb4e 100644--- a/posthog/test/activity_logging/test_evaluation_activity_logging.py+++ b/posthog/test/activity_logging/test_evaluation_activity_logging.py@@ -1,9 +1,12 @@from typing import Any+from django.test import override_settings+from rest_framework import statusfrom posthog.test.activity_log_utils import ActivityLogTestHelper+from products.ai_observability.backend.models.evaluation_config import EvaluationConfigfrom products.ai_observability.backend.models.evaluations import Evaluationfrom products.ai_observability.backend.models.model_configuration import LLMModelConfigurationfrom products.ai_observability.backend.models.provider_keys import LLMProviderKey@@ -26,7 +29,14 @@ def _create_evaluation_payload(**overrides: Any) -> dict[str, Any]:return payload+# The create payloads are keyless llm_judge with enabled=True, which only validates for a+# grandfathered team.+@override_settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00")class TestEvaluationActivityLogging(ActivityLogTestHelper):+ def setUp(self) -> None:+ super().setUp()+ EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)+def _create_evaluation(self, **overrides: Any) -> dict[str, Any]:response = self.client.post(f"/api/environments/{self.team.id}/evaluations/",diff --git a/products/ai_observability/backend/api/evaluation_config.py b/products/ai_observability/backend/api/evaluation_config.pyindex 95a7272b3e9d..76f671c3024a 100644--- a/products/ai_observability/backend/api/evaluation_config.py+++ b/products/ai_observability/backend/api/evaluation_config.py@@ -1,4 +1,7 @@-from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_serializer+from datetime import datetime++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field, extend_schema_serializerfrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.permissions import IsAuthenticated@@ -12,6 +15,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.event_usage import report_user_actionfrom posthog.permissions import AccessControlPermission+from ..constants import trial_eval_deprecation_datefrom ..models.evaluation_config import EvaluationConfigfrom ..models.provider_keys import LLMProviderKeyfrom .metrics import llma_track_latency@@ -24,18 +28,32 @@ class EvaluationConfigSerializer(serializers.ModelSerializer):read_only=True,help_text="Trial runs remaining — a getting-started affordance only; evals should use the team's own provider key.",)+ trial_grandfathered = serializers.BooleanField(+ source="is_trial_grandfathered",+ read_only=True,+ help_text="True while this team keeps PostHog-funded trial inference during the deprecation window (i.e. it is mid-trial and the cutoff has not passed). False means the team must use its own provider key.",+ )+ trial_deprecation_date = serializers.SerializerMethodField(+ help_text="Timestamp after which trial evaluations are fully removed and every team must use its own provider key.",+ )active_provider_key = LLMProviderKeySerializer(read_only=True,allow_null=True,help_text="Provider key used to run llm_judge evals; null if none configured yet.",)+ @extend_schema_field(OpenApiTypes.DATETIME)+ def get_trial_deprecation_date(self, _obj: EvaluationConfig) -> datetime:+ return trial_eval_deprecation_date()+class Meta:model = EvaluationConfigfields = ["trial_eval_limit","trial_evals_used","trial_evals_remaining",+ "trial_grandfathered",+ "trial_deprecation_date","active_provider_key","created_at","updated_at",@@ -44,6 +62,7 @@ class EvaluationConfigSerializer(serializers.ModelSerializer):"trial_eval_limit","trial_evals_used","trial_evals_remaining",+ "trial_grandfathered","active_provider_key","created_at","updated_at",diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.pyindex c3171a5c3ac5..6fe34baed88a 100644--- a/products/ai_observability/backend/api/evaluations.py+++ b/products/ai_observability/backend/api/evaluations.py@@ -28,6 +28,7 @@ from posthog.temporal.ai_observability.run_evaluation import extract_event_io, rfrom ..feature_flags import is_sentiment_evaluations_enabledfrom ..hog import compile_ai_observability_hog+from ..llm import DEFAULT_MODEL_BY_PROVIDER, TRIAL_MODEL_IDSfrom ..models.evaluation_config import EvaluationConfigfrom ..models.evaluation_configs import (TRACE_EVAL_DEFAULT_WINDOW_SECONDS,@@ -42,7 +43,7 @@ from ..models.evaluation_configs import (validate_target_config,)from ..models.evaluation_reports import EvaluationReport-from ..models.evaluations import Evaluation, EvaluationStatusReason, EvaluationTarget+from ..models.evaluations import Evaluation, EvaluationTargetfrom ..models.model_configuration import LLMModelConfigurationfrom ..models.provider_keys import LLMProvider, LLMProviderKeyfrom .metrics import llma_track_latency@@ -50,15 +51,6 @@ from .metrics import llma_track_latencylogger = structlog.get_logger(__name__)-PROVIDER_KEY_ERROR_STATUS_REASONS = {- EvaluationStatusReason.PROVIDER_KEY_DELETED,- EvaluationStatusReason.PROVIDER_KEY_INVALID,- EvaluationStatusReason.PROVIDER_KEY_PERMISSION_DENIED,- EvaluationStatusReason.PROVIDER_KEY_QUOTA_EXCEEDED,- EvaluationStatusReason.PROVIDER_KEY_RATE_LIMITED,-}--@extend_schema_field({"oneOf": [@@ -352,12 +344,11 @@ class EvaluationSerializer(serializers.ModelSerializer):except ValueError as e:raise serializers.ValidationError({"target_config": str(e)})- # Guard re-enable transitions: if the eval is currently disabled and the caller is flipping- # `enabled=True`, make sure whatever caused the disabled state has actually been resolved.- # Without this check, a caller (UI, API, MCP, agent) can flip enabled=True, see a 200, and- # then watch the next Temporal run silently re-disable the eval for the same reason.- if data.get("enabled") and self.instance and not self.instance.enabled:- self._validate_re_enable(data)+ if data.get("enabled"):+ if self.instance is None:+ self._validate_can_run(data)+ elif not self.instance.enabled:+ self._validate_re_enable(data)return data@@ -389,60 +380,34 @@ class EvaluationSerializer(serializers.ModelSerializer):self.context["get_team"](),)- def _validate_re_enable(self, data: dict) -> None:- provider_key = self._effective_provider_key(data)- has_byok = provider_key is not None- has_usable_byok = provider_key is not None and provider_key.state == LLMProviderKey.State.OK- status_reason = getattr(self.instance, "status_reason", None)+ def _validate_can_run(self, data: dict) -> None:+ """An eval being turned on — created enabled or re-enabled — must be able to resolve a+ model at runtime; otherwise the caller gets a 200/201 and the first Temporal run silently+ disables it again."""evaluation_type = data.get("evaluation_type") or getattr(self.instance, "evaluation_type", None)- # Non-model evals never call an LLM provider, consume trial quota, or need a BYOK key.- # The trial-limit / model-allowlist / provider-key-deleted gates below assume an- # LLM-judge call path, so skip them entirely.if not evaluation_uses_model_configuration(evaluation_type):return- if has_byok and not has_usable_byok:- raise serializers.ValidationError(- {"enabled": "Attach a working provider API key before re-enabling this evaluation."}- )-- # Trial limit: can only re-enable if they've attached a BYOK key (which bypasses trial quota).- if status_reason == "trial_limit_reached" or not status_reason:- team = self.context["get_team"]()- config = EvaluationConfig.objects.filter(team=team).first()- if config and config.trial_limit_reached and not has_usable_byok:+ provider_key = self._effective_provider_key(data)+ if provider_key is not None:+ if provider_key.state != LLMProviderKey.State.OK:raise serializers.ValidationError(- {"enabled": "Trial evaluation limit reached. Add a provider API key to re-enable this evaluation."}+ {"enabled": "Attach a working provider API key to enable this evaluation."})+ return- # Model-not-allowed: the eval's current model must now be on the trial allowlist, or they- # must have attached a BYOK key (BYOK bypasses the allowlist entirely).- if status_reason == "model_not_allowed" and not has_usable_byok:- from products.ai_observability.backend.llm import TRIAL_MODEL_IDS+ self._validate_keyless_resolution(data)- model_config_data = data.get("model_configuration")- if model_config_data is not None:- model = model_config_data.get("model")- elif self.instance and self.instance.model_configuration:- model = self.instance.model_configuration.model- else:- model = None- if model and model not in TRIAL_MODEL_IDS:- raise serializers.ValidationError(- {- "enabled": (- f"Model '{model}' is not available on the trial plan. "- "Either choose a supported trial model or add a provider API key."- )- }- )+ def _validate_re_enable(self, data: dict) -> None:+ evaluation_type = data.get("evaluation_type") or getattr(self.instance, "evaluation_type", None)+ if not evaluation_uses_model_configuration(evaluation_type):+ return- # Provider key failures: the eval must now point at a usable provider key.- if status_reason in PROVIDER_KEY_ERROR_STATUS_REASONS:- if not has_usable_byok:- raise serializers.ValidationError(- {"enabled": "Attach a working provider API key before re-enabling this evaluation."}- )+ # _validate_can_run mirrors runtime resolution, so it already rejects a re-enable whose key is+ # missing/unhealthy or whose keyless config can't resolve — no separate provider-key gate needed.+ self._validate_can_run(data)++ status_reason = getattr(self.instance, "status_reason", None)if status_reason == "model_not_found" and not self._has_model_configuration_after_update(data):raise serializers.ValidationError(@@ -459,24 +424,85 @@ class EvaluationSerializer(serializers.ModelSerializer):})+ def _validate_keyless_resolution(self, data: dict) -> None:+ """Mirror the runtime model resolution for evals with no usable provider key (see+ `posthog/temporal/ai_observability/model_resolution.py`). A pinned key, or an explicit+ config's active-key fallback, is already handled by `_validate_can_run`; this covers what+ is left: a null config resolves via the team's active key, else PostHog-funded trial+ inference while the team is still grandfathered; an explicit config that reached here has+ no active-key fallback, so it resolves via funded inference only, and only for models on+ the trial allowlist."""+ add_key_message = "Add a provider API key to enable this evaluation."+ team = self.context["get_team"]()+ config = EvaluationConfig.objects.filter(team=team).first()+ is_grandfathered = config is not None and config.is_trial_grandfathered++ explicit_config = self._effective_model_configuration(data)+ if explicit_config is None:+ active_key = config.active_provider_key if config else None+ if active_key is not None:+ # DefaultModelSpec never falls back to funded inference when an active key exists,+ # so an unhealthy key blocks the enable regardless of grandfathering.+ if active_key.state != LLMProviderKey.State.OK:+ raise serializers.ValidationError(+ {"enabled": "Attach a working provider API key to enable this evaluation."}+ )+ if DEFAULT_MODEL_BY_PROVIDER.get(active_key.provider) is None:+ raise serializers.ValidationError(+ {+ "enabled": "This evaluation's provider has no default model. Set a model on the evaluation before enabling it."+ }+ )+ return+ if is_grandfathered:+ return+ raise serializers.ValidationError({"enabled": add_key_message})++ if not is_grandfathered:+ raise serializers.ValidationError({"enabled": add_key_message})++ model = explicit_config.get("model")+ if model and model not in TRIAL_MODEL_IDS:+ raise serializers.ValidationError(+ {+ "enabled": (+ f"Model '{model}' is not available on the trial plan. "+ "Either choose a supported trial model or add a provider API key."+ )+ }+ )++ def _effective_model_configuration(self, data: dict) -> dict[str, Any] | None:+ """The explicit model configuration the evaluation will have after this update, or None+ when it defers to the team default (null config). An explicit `model_configuration: null`+ detaches the stored config (see update()), so payload presence wins — membership, not+ truthiness."""+ if "model_configuration" in data:+ return data["model_configuration"]+ if self.instance is not None and self.instance.model_configuration is not None:+ mc = self.instance.model_configuration+ return {+ "provider": mc.provider,+ "model": mc.model,+ "provider_key_id": str(mc.provider_key_id) if mc.provider_key_id else None,+ }+ return None+def _has_model_configuration_after_update(self, data: dict) -> bool:return bool(data.get("model_configuration")) or bool(self.instance and self.instance.model_configuration_id)def _effective_provider_key(self, data: dict) -> LLMProviderKey | None:- """Return the provider key the evaluation will use after this update."""+ """The provider key the evaluation will use after this update. With no pinned key, an+ explicit config falls back to the team's active key for the same provider, mirroring+ `active_key_fallback` in model_resolution.py."""team = self.context["get_team"]()- model_config_data = data.get("model_configuration")- if model_config_data is not None:- provider_key_id = model_config_data.get("provider_key_id")- provider = model_config_data.get("provider")- elif self.instance and self.instance.model_configuration:- provider_key_id = self.instance.model_configuration.provider_key_id- provider = self.instance.model_configuration.provider- else:+ model_config = self._effective_model_configuration(data)+ if not model_config:return None-+ provider_key_id = model_config.get("provider_key_id")if provider_key_id:return LLMProviderKey.objects.filter(id=provider_key_id, team=team).first()+ provider = model_config.get("provider")config = EvaluationConfig.objects.filter(team=team).first()return active_key_fallback(config, provider) if config and provider else Nonediff --git a/products/ai_observability/backend/api/models.py b/products/ai_observability/backend/api/models.pyindex ef9c5f3ef6a9..12f881bb8c79 100644--- a/products/ai_observability/backend/api/models.py+++ b/products/ai_observability/backend/api/models.py@@ -11,6 +11,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.permissions import AccessControlPermissionfrom ..llm import TRIAL_MODELS_BY_PROVIDER+from ..models.evaluation_config import EvaluationConfigfrom ..models.model_configuration import LLMModelConfigurationfrom ..models.provider_keys import LLMProvider, LLMProviderKeyfrom .metrics import llma_track_latency@@ -21,7 +22,7 @@ class LLMModelInfoSerializer(serializers.Serializer):help_text="Provider-specific model identifier (e.g. 'gpt-4o-mini', 'claude-3-5-sonnet-20241022').")posthog_available = serializers.BooleanField(- help_text="True if the model can run without a provider key — for getting-started testing only; real evals should use the team's own key."+ help_text="True if the model can run without a provider key on PostHog-funded trial credits. Only true for teams still grandfathered into the deprecating trial; every other team must use its own key.")@@ -103,7 +104,11 @@ class LLMModelsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):team_id=self.team_id,)available = config.get_available_models()- posthog_allowed = TRIAL_MODELS_BY_PROVIDER.get(provider, [])++ # A team with no config row was never mid-trial, so a read-only lookup suffices.+ eval_config = EvaluationConfig.objects.filter(team_id=self.team_id).first()+ is_grandfathered = eval_config is not None and eval_config.is_trial_grandfathered+ posthog_allowed = TRIAL_MODELS_BY_PROVIDER.get(provider, []) if is_grandfathered else []return Response({"models": [{"id": model, "posthog_available": model in posthog_allowed} for model in available]}diff --git a/products/ai_observability/backend/api/test/test_evaluation_config.py b/products/ai_observability/backend/api/test/test_evaluation_config.pyindex 6efeb270b504..7b53866f04bb 100644--- a/products/ai_observability/backend/api/test/test_evaluation_config.py+++ b/products/ai_observability/backend/api/test/test_evaluation_config.py@@ -50,6 +50,11 @@ class TestEvaluationConfigViewSet(APIBaseTest):self.assertEqual(response.data["trial_evals_used"], 0)self.assertEqual(response.data["trial_evals_remaining"], 100)self.assertIsNone(response.data["active_provider_key"])+ # The frontend gates the terminal/grandfathered UI on these two fields.+ self.assertIn("trial_grandfathered", response.data)+ self.assertFalse(response.data["trial_grandfathered"])+ self.assertIn("trial_deprecation_date", response.data)+ self.assertIsNotNone(response.data["trial_deprecation_date"])def test_get_creates_config_if_missing(self):self.assertEqual(EvaluationConfig.objects.filter(team=self.team).count(), 0)@@ -67,6 +72,16 @@ class TestEvaluationConfigViewSet(APIBaseTest):self.assertEqual(response.data["trial_evals_used"], 50)self.assertEqual(response.data["trial_evals_remaining"], 50)+ def test_trial_grandfathered_field_reflects_is_trial_grandfathered_property(self):+ # The field must track the model property; pin the cutoff for wall-clock determinism.+ with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):+ EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)++ response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/evaluation_config/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertTrue(response.data["trial_grandfathered"])+def test_can_set_active_key(self):key = LLMProviderKey.objects.create(team=self.team,diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.pyindex f5fd8d6a5ab2..3e4a8a71cc4a 100644--- a/products/ai_observability/backend/api/test/test_evaluations.py+++ b/products/ai_observability/backend/api/test/test_evaluations.py@@ -46,19 +46,22 @@ class TestEvaluationConfigsApi(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)def test_can_create_evaluation_config(self):- response = self.client.post(- f"/api/environments/{self.team.id}/evaluations/",- {- "name": "Test Evaluation",- "description": "Test Description",- "enabled": True,- "evaluation_type": "llm_judge",- "evaluation_config": {"prompt": "Test prompt"},- "output_type": "boolean",- "output_config": {},- "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],- },- )+ # Creating enabled+keyless only validates for a grandfathered team; pin the cutoff for determinism.+ with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):+ EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)+ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/",+ {+ "name": "Test Evaluation",+ "description": "Test Description",+ "enabled": True,+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Test prompt"},+ "output_type": "boolean",+ "output_config": {},+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],+ },+ )self.assertEqual(response.status_code, status.HTTP_201_CREATED)self.assertEqual(Evaluation.objects.count(), 1)@@ -228,7 +231,6 @@ class TestEvaluationConfigsApi(APIBaseTest):f"/api/environments/{self.team.id}/evaluations/",{"name": "Will Rollback",- "enabled": True,"evaluation_type": "llm_judge","evaluation_config": {"prompt": "Test prompt"},"output_type": "boolean",@@ -967,43 +969,160 @@ class TestTestHogEndpoint(APIBaseTest):self.assertIsNone(results[0]["error"])-class TestEnableBlockingWhenTrialExhausted(APIBaseTest):- def _create_trial_eval(self, enabled=False):- mc = LLMModelConfiguration.objects.create(team=self.team, provider="openai", model="gpt-5-mini")+class TestEnableBlockingWhenKeyRequired(APIBaseTest):+ """Enabling a keyless llm_judge eval must mirror the runtime funded-inference gate: a config+ with no pinned key falls back to the team's active key for the same provider, else only+ grandfathered (mid-trial, pre-cutoff) teams may run it via funded inference. Anything the+ serializer lets through here would just flap back to disabled on the next Temporal run."""++ def _create_keyless_eval(self, model_configuration=...):+ if model_configuration is ...:+ model_configuration = LLMModelConfiguration.objects.create(+ team=self.team, provider="openai", model="gpt-5-mini"+ )return Evaluation.objects.create(team=self.team,- name="Trial Eval",+ name="Keyless Eval",evaluation_type="llm_judge",evaluation_config={"prompt": "test"},output_type="boolean",- model_configuration=mc,- enabled=enabled,+ model_configuration=model_configuration,+ enabled=False,)- def test_blocks_enabling_trial_eval_when_limit_reached(self):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=100)- eval_obj = self._create_trial_eval(enabled=False)+ def _create_active_key(self):+ key = LLMProviderKey.objects.create(+ team=self.team,+ provider="openai",+ name="Active Key",+ state=LLMProviderKey.State.OK,+ encrypted_config={"api_key": "sk-test"},+ created_by=self.user,+ )+ return key- response = self.client.patch(+ def _enable(self, eval_obj):+ return self.client.patch(f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",{"enabled": True},format="json",)++ @parameterized.expand(+ [+ ("trial_exhausted_explicit_config", 100, True),+ ("trial_never_started_explicit_config", 0, True),+ ("trial_never_started_null_config", 0, False),+ ]+ )+ def test_blocks_enabling_keyless_eval_when_not_grandfathered(self, _name, trial_evals_used, explicit_config):+ EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=trial_evals_used)+ eval_obj = (+ self._create_keyless_eval() if explicit_config else self._create_keyless_eval(model_configuration=None)+ )++ response = self._enable(eval_obj)+self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("Trial evaluation limit reached", str(response.data))+ self.assertIn("Add a provider API key", str(response.data))+ eval_obj.refresh_from_db()+ self.assertFalse(eval_obj.enabled)++ def test_allows_enabling_keyless_eval_while_grandfathered(self):+ with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):+ EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)+ eval_obj = self._create_keyless_eval()++ response = self._enable(eval_obj)- def test_allows_enabling_trial_eval_when_limit_not_reached(self):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)- eval_obj = self._create_trial_eval(enabled=False)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ eval_obj.refresh_from_db()+ self.assertTrue(eval_obj.enabled)++ def test_active_team_key_enables_explicit_keyless_eval(self):+ # An explicit config with no pinned key falls back to the team's active key for the same+ # provider, so it enables even with the trial exhausted (mirrors runtime resolution).+ key = self._create_active_key()+ EvaluationConfig.objects.create(+ team=self.team, trial_eval_limit=100, trial_evals_used=100, active_provider_key=key+ )+ eval_obj = self._create_keyless_eval()++ response = self._enable(eval_obj)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ eval_obj.refresh_from_db()+ self.assertTrue(eval_obj.enabled)++ def test_active_team_key_enables_null_config_eval(self):+ # Null configs resolve via the active key at runtime — the gate must not over-block them.+ key = self._create_active_key()+ EvaluationConfig.objects.create(+ team=self.team, trial_eval_limit=100, trial_evals_used=100, active_provider_key=key+ )+ eval_obj = self._create_keyless_eval(model_configuration=None)++ response = self._enable(eval_obj)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ eval_obj.refresh_from_db()+ self.assertTrue(eval_obj.enabled)++ def test_unhealthy_active_key_blocks_null_config_eval_even_while_grandfathered(self):+ # Runtime never falls back to funded inference when an active key exists, even unhealthy.+ key = self._create_active_key()+ key.state = LLMProviderKey.State.INVALID+ key.save()+ with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):+ EvaluationConfig.objects.create(+ team=self.team, trial_eval_limit=100, trial_evals_used=50, active_provider_key=key+ )+ eval_obj = self._create_keyless_eval(model_configuration=None)++ response = self._enable(eval_obj)++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("working provider API key", str(response.data))+ eval_obj.refresh_from_db()+ self.assertFalse(eval_obj.enabled)++ def test_detaching_model_configuration_enables_via_active_key(self):+ # The gate must validate the post-detach state, not the stored config.+ key = self._create_active_key()+ EvaluationConfig.objects.create(+ team=self.team, trial_eval_limit=100, trial_evals_used=100, active_provider_key=key+ )+ eval_obj = self._create_keyless_eval()response = self.client.patch(f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",- {"enabled": True},+ {"enabled": True, "model_configuration": None},format="json",)+self.assertEqual(response.status_code, status.HTTP_200_OK)eval_obj.refresh_from_db()self.assertTrue(eval_obj.enabled)+ self.assertIsNone(eval_obj.model_configuration)++ def test_blocks_creating_enabled_keyless_eval_when_not_grandfathered(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/",+ {+ "name": "Doomed Eval",+ "enabled": True,+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "test"},+ "output_type": "boolean",+ "output_config": {},+ "conditions": [{"id": "cond-1", "rollout_percentage": 100, "properties": []}],+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("Add a provider API key", str(response.data))+ self.assertEqual(Evaluation.objects.filter(name="Doomed Eval").count(), 0)def test_allows_enabling_hog_eval_when_limit_reached(self):EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=100)@@ -1123,13 +1242,16 @@ class TestReEnableValidatesRootCauseResolved(APIBaseTest):return eval_objdef test_rejects_re_enable_when_model_still_not_allowed(self):- eval_obj = self._create_errored_eval(status_reason="model_not_allowed", model="gpt-9")+ # Only a grandfathered team gets past the funded gate to the model-allowlist message.+ with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):+ EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)+ eval_obj = self._create_errored_eval(status_reason="model_not_allowed", model="gpt-9")- response = self.client.patch(- f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",- {"enabled": True},- format="json",- )+ response = self.client.patch(+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",+ {"enabled": True},+ format="json",+ )self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertIn("not available on the trial plan", str(response.data))@@ -1177,6 +1299,40 @@ class TestReEnableValidatesRootCauseResolved(APIBaseTest):eval_obj.refresh_from_db()self.assertFalse(eval_obj.enabled)+ def test_rejects_re_enable_when_provider_key_required_and_no_key(self):+ eval_obj = self._create_errored_eval(status_reason="provider_key_required")++ response = self.client.patch(+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",+ {"enabled": True},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("provider API key", str(response.data))+ eval_obj.refresh_from_db()+ self.assertFalse(eval_obj.enabled)++ def test_allows_re_enable_when_provider_key_required_and_byok_key_attached(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,+ )+ eval_obj = self._create_errored_eval(status_reason="provider_key_required", provider_key=key)++ response = self.client.patch(+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",+ {"enabled": True},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ eval_obj.refresh_from_db()+ self.assertTrue(eval_obj.enabled)+ self.assertIsNone(eval_obj.status_reason)+@parameterized.expand([("provider_key_deleted",),@@ -1226,13 +1382,16 @@ class TestReEnableValidatesRootCauseResolved(APIBaseTest):self.assertIn("working provider API key", str(response.data))def test_allows_re_enable_when_model_not_found_with_existing_model_config(self):- eval_obj = self._create_errored_eval(status_reason="model_not_found")+ # Grandfather the team so the funded gate passes — this test is about the model_not_found rule.+ with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):+ EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)+ eval_obj = self._create_errored_eval(status_reason="model_not_found")- response = self.client.patch(- f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",- {"enabled": True},- format="json",- )+ response = self.client.patch(+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",+ {"enabled": True},+ format="json",+ )self.assertEqual(response.status_code, status.HTTP_200_OK)eval_obj.refresh_from_db()@@ -1240,20 +1399,22 @@ class TestReEnableValidatesRootCauseResolved(APIBaseTest):self.assertIsNone(eval_obj.status_reason)def test_allows_re_enable_when_model_not_found_with_new_model(self):- eval_obj = self._create_errored_eval(status_reason="model_not_found", model="missing-model")+ with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):+ EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)+ eval_obj = self._create_errored_eval(status_reason="model_not_found", model="missing-model")- response = self.client.patch(- f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",- {- "enabled": True,- "model_configuration": {- "provider": "openai",- "model": "gpt-5-mini",- "provider_key_id": None,+ response = self.client.patch(+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",+ {+ "enabled": True,+ "model_configuration": {+ "provider": "openai",+ "model": "gpt-5-mini",+ "provider_key_id": None,+ },},- },- format="json",- )+ format="json",+ )self.assertEqual(response.status_code, status.HTTP_200_OK)eval_obj.refresh_from_db()diff --git a/products/ai_observability/backend/api/test/test_models.py b/products/ai_observability/backend/api/test/test_models.pyindex 74cbe749e418..656df510e23c 100644--- a/products/ai_observability/backend/api/test/test_models.py+++ b/products/ai_observability/backend/api/test/test_models.py@@ -3,9 +3,12 @@ from unittest.mock import patchfrom django.test import SimpleTestCase+from parameterized import parameterizedfrom rest_framework import statusfrom products.ai_observability.backend.api.models import LLMModelInfoSerializer, LLMModelsListResponseSerializer+from products.ai_observability.backend.llm import TRIAL_MODELS_BY_PROVIDER+from products.ai_observability.backend.models.evaluation_config import EvaluationConfigclass TestLLMModelInfoSerializer(SimpleTestCase):@@ -61,6 +64,26 @@ class TestLLMModelsViewSet(APIBaseTest):for entry in response.data["models"]:self.assertIn("posthog_available", entry)+ @parameterized.expand(+ [+ ("grandfathered", 50, True),+ ("terminal", 100, False),+ ]+ )+ @patch("products.ai_observability.backend.api.models.LLMModelConfiguration")+ def test_posthog_available_requires_grandfathering(self, _name, trial_evals_used, expected, mock_config_cls):+ # This flag feeds the MCP judge-models tool — a regression silently re-offers+ # PostHog-funded models to terminal teams via agents.+ trial_model = TRIAL_MODELS_BY_PROVIDER["openai"][0]+ mock_config_cls.return_value.get_available_models.return_value = [trial_model]+ with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):+ EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=trial_evals_used)++ response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/models/?provider=openai")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.data["models"][0]["posthog_available"], expected)+def test_unauthenticated_user_cannot_list_models(self):self.client.logout()response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/models/?provider=openai")diff --git a/products/ai_observability/backend/constants.py b/products/ai_observability/backend/constants.pynew file mode 100644index 000000000000..119a2d14c3cf--- /dev/null+++ b/products/ai_observability/backend/constants.py@@ -0,0 +1,15 @@+from datetime import UTC, datetime++from django.conf import settings++# Cutoff for the trial-eval deprecation: grandfathered teams keep PostHog-funded inference until+# this date. Extendable without a deploy via the env var (see posthog/settings/base_variables.py).+DEFAULT_TRIAL_EVAL_DEPRECATION_DATE = datetime(2026, 7, 17, tzinfo=UTC)+++def trial_eval_deprecation_date() -> datetime:+ override = settings.AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE+ if override:+ parsed = datetime.fromisoformat(override)+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)+ return DEFAULT_TRIAL_EVAL_DEPRECATION_DATEdiff --git a/products/ai_observability/backend/migrations/0016_deprecate_trial_evaluations.py b/products/ai_observability/backend/migrations/0016_deprecate_trial_evaluations.pynew file mode 100644index 000000000000..0a4b277c6760--- /dev/null+++ b/products/ai_observability/backend/migrations/0016_deprecate_trial_evaluations.py@@ -0,0 +1,36 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("ai_observability", "0015_llmprompt_version_description")]++ operations = [+ migrations.AlterField(+ model_name="evaluation",+ name="status_reason",+ field=models.CharField(+ blank=True,+ choices=[+ ("provider_key_required", "No provider API key configured"),+ ("trial_limit_reached", "Trial evaluation limit reached"),+ ("model_not_allowed", "Model not available on the trial plan"),+ ("provider_key_deleted", "Provider API key was deleted"),+ (+ "no_default_model",+ "No default model available for the selected provider",+ ),+ ("provider_key_invalid", "Provider API key is invalid"),+ (+ "provider_key_permission_denied",+ "Provider API key lacks model access",+ ),+ ("provider_key_quota_exceeded", "Provider API key quota exceeded"),+ ("provider_key_rate_limited", "Provider API key is rate limited"),+ ("model_not_found", "Model not found"),+ ("hog_error", "Hog evaluation code failed"),+ ],+ max_length=50,+ null=True,+ ),+ ),+ ]diff --git a/products/ai_observability/backend/migrations/0017_relabel_terminal_status_reasons.py b/products/ai_observability/backend/migrations/0017_relabel_terminal_status_reasons.pynew file mode 100644index 000000000000..4992fdbbd612--- /dev/null+++ b/products/ai_observability/backend/migrations/0017_relabel_terminal_status_reasons.py@@ -0,0 +1,31 @@+from django.db import migrations, models+++def backfill_terminal_status_reasons(apps, schema_editor):+ """Terminal teams — never started (used == 0, or no config row) or already exhausted the+ trial — should see evaluations as if trials never existed, so relabel their trial-flavored+ disable reasons to `provider_key_required`. Only mid-trial (grandfathered) teams keep their+ existing, still-accurate labels. The grandfathered set deliberately omits the deprecation+ cutoff: this runs at deploy time, before the cutoff; a self-hosted instance migrating after+ it just keeps a few stale-but-blocked labels."""+ Evaluation = apps.get_model("ai_observability", "Evaluation")+ EvaluationConfig = apps.get_model("ai_observability", "EvaluationConfig")++ grandfathered_team_ids = EvaluationConfig.objects.filter(+ trial_evals_used__gt=0, trial_evals_used__lt=models.F("trial_eval_limit")+ ).values_list("team_id", flat=True)++ Evaluation.objects.filter(+ status_reason__in=["trial_limit_reached", "model_not_allowed"],+ ).exclude(team_id__in=list(grandfathered_team_ids)).update(+ status_reason="provider_key_required", status_reason_detail=None+ )+++class Migration(migrations.Migration):+ dependencies = [("ai_observability", "0016_deprecate_trial_evaluations")]++ operations = [+ # Lossy relabel (several trial reasons collapse into one); reverse is a no-op.+ migrations.RunPython(backfill_terminal_status_reasons, migrations.RunPython.noop),+ ]diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txtindex 6e9dbdb0d51f..154ae8dad143 100644--- a/products/ai_observability/backend/migrations/max_migration.txt+++ b/products/ai_observability/backend/migrations/max_migration.txt@@ -1 +1 @@-0015_llmprompt_version_description+0017_relabel_terminal_status_reasonsdiff --git a/products/ai_observability/backend/models/evaluation_config.py b/products/ai_observability/backend/models/evaluation_config.pyindex adf16e091565..4bbade6c7a5a 100644--- a/products/ai_observability/backend/models/evaluation_config.py+++ b/products/ai_observability/backend/models/evaluation_config.py@@ -1,4 +1,7 @@from django.db import models+from django.utils import timezone++from products.ai_observability.backend.constants import trial_eval_deprecation_dateclass EvaluationConfig(models.Model):@@ -38,5 +41,9 @@ class EvaluationConfig(models.Model):return max(0, self.trial_eval_limit - self.trial_evals_used)@property- def trial_limit_reached(self) -> bool:- return self.trial_evals_used >= self.trial_eval_limit+ def is_trial_grandfathered(self) -> bool:+ """Only teams already mid-trial keep PostHog-funded inference, and only until the cutoff.+ Teams that never started (used == 0) or exhausted (used >= limit) the trial are terminal+ and must bring their own provider key — as are all teams once the deprecation date passes.+ """+ return 0 < self.trial_evals_used < self.trial_eval_limit and timezone.now() < trial_eval_deprecation_date()diff --git a/products/ai_observability/backend/models/evaluations.py b/products/ai_observability/backend/models/evaluations.pyindex 1759bbcedbd7..18615b5a16ee 100644--- a/products/ai_observability/backend/models/evaluations.py+++ b/products/ai_observability/backend/models/evaluations.py@@ -31,6 +31,8 @@ class EvaluationStatus(models.TextChoices):class EvaluationStatusReason(models.TextChoices):+ PROVIDER_KEY_REQUIRED = "provider_key_required", "No provider API key configured"+ # Trial reasons — retained while mid-trial teams are grandfathered; removed once the trial is fully deprecated.TRIAL_LIMIT_REACHED = "trial_limit_reached", "Trial evaluation limit reached"MODEL_NOT_ALLOWED = "model_not_allowed", "Model not available on the trial plan"PROVIDER_KEY_DELETED = "provider_key_deleted", "Provider API key was deleted"diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsxindex 443c42e5bdc2..01572e0a2e85 100644--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx@@ -657,13 +657,14 @@ function EvaluationModelPicker(): JSX.Element {trialModelsLoading,providerKeysLoading,} = useValues(modelPickerLogic)- const { selectedModel, selectedPickerProviderKeyId } = useValues(llmEvaluationLogic)+ const { selectedModel, selectedPickerProviderKeyId, requiresProviderKey } = useValues(llmEvaluationLogic)const { selectModelFromPicker } = useActions(llmEvaluationLogic)- const allModels = hasByokKeys ? byokModels : trialModels+ const showTrialModels = !hasByokKeys && !requiresProviderKey+ const allModels = showTrialModels ? trialModels : byokModelsconst selectedModelName = allModels.find((m) => m.id === selectedModel)?.name- const groups = hasByokKeys ? providerModelGroups : trialProviderModelGroups- const loading = hasByokKeys ? byokModelsLoading || providerKeysLoading : trialModelsLoading+ const groups = showTrialModels ? trialProviderModelGroups : providerModelGroups+ const loading = showTrialModels ? trialModelsLoading : byokModelsLoading || providerKeysLoadingconst footerLink = getModelPickerFooterLink(hasByokKeys)diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsxindex 7f0ae5632137..4c6fce7daf44 100644--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx@@ -197,7 +197,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {const isBlocked = !canEnable && !evaluation.enabledconst blockedReason = !canUseEvaluationType? 'Sentiment evaluations are not available for this project.'- : 'Trial evaluation limit reached. Add a provider API key to re-enable.'+ : 'Add a provider API key to enable this evaluation.'return (<div className="flex items-center gap-2"><AccessControlAction@@ -375,7 +375,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {return (<div className="space-y-4">- <TrialUsageMeter showSettingsLink={false} />+ <TrialUsageMeter showSettingsLink />{unhealthyProviderKeysUsedByEvaluations.length > 0 && (<LemonBanner type="warning">diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.tsindex f10573cb2dd4..df99df905d20 100644--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts@@ -29,6 +29,25 @@ export function evaluationTypeUsesProviderKey(evaluationType: EvaluationType | nreturn evaluationTypeUsesModelConfiguration(evaluationType)}+export function evaluationCanResolveModel(+ evaluation: Pick<EvaluationConfig, 'evaluation_type' | 'model_configuration'>,+ requiresProviderKey: boolean,+ isTrialGrandfathered: boolean+): boolean {+ if (!evaluationTypeUsesProviderKey(evaluation.evaluation_type)) {+ return true+ }+ if (evaluation.model_configuration?.provider_key_id) {+ return true+ }+ // An explicit keyless config never falls back to the team's active key at runtime —+ // it only resolves via PostHog-funded inference while the team is still grandfathered.+ if (evaluation.model_configuration) {+ return isTrialGrandfathered+ }+ return !requiresProviderKey+}+export function evaluationTypeDefaultsToBooleanOutput(evaluationType: EvaluationType | null | undefined): boolean {return evaluationType === 'llm_judge' || evaluationType === 'hog'}diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.tsindex e05c4b36824c..a083df879842 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts@@ -211,6 +211,8 @@ describe('llmEvaluationLogic', () => {trial_eval_limit: 100,trial_evals_used: 0,trial_evals_remaining: 100,+ trial_grandfathered: false,+ trial_deprecation_date: '2026-07-15T00:00:00Z',active_provider_key: null,created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',@@ -505,6 +507,18 @@ describe('llmEvaluationLogic', () => {describe('async flows', () => {describe('loadEvaluation', () => {it('initializes new evaluation with default values', async () => {+ // Pin the team to a non-terminal state before mounting so the draft's enabled+ // default doesn't depend on config-fetch timing.+ keysLogic.actions.loadEvaluationConfigSuccess({+ trial_eval_limit: 100,+ trial_evals_used: 50,+ trial_evals_remaining: 50,+ trial_grandfathered: true,+ trial_deprecation_date: '2026-07-17T00:00:00Z',+ active_provider_key: null,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ })logic = llmEvaluationLogic({ evaluationId: 'new' })logic.mount()@@ -522,6 +536,65 @@ describe('llmEvaluationLogic', () => {})})+ it('initializes new evaluation disabled for terminal teams that require a provider key', async () => {+ keysLogic.actions.loadEvaluationConfigSuccess({+ trial_eval_limit: 100,+ trial_evals_used: 100,+ trial_evals_remaining: 0,+ trial_grandfathered: false,+ trial_deprecation_date: '2026-07-17T00:00:00Z',+ active_provider_key: null,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ })+ logic = llmEvaluationLogic({ evaluationId: 'new' })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])++ await expectLogic(logic).toMatchValues({+ isNewEvaluation: true,+ evaluation: expect.objectContaining({ enabled: false }),+ })+ })++ it('disables an enabled new draft when a late config load says the team requires a key', async () => {+ // The draft's enabled default is read before the config fetch resolves — the+ // listener must correct it when the config arrives late.+ keysLogic.actions.loadEvaluationConfigSuccess({+ trial_eval_limit: 100,+ trial_evals_used: 50,+ trial_evals_remaining: 50,+ trial_grandfathered: true,+ trial_deprecation_date: '2026-07-17T00:00:00Z',+ active_provider_key: null,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ })+ logic = llmEvaluationLogic({ evaluationId: 'new' })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])+ await expectLogic(logic).toMatchValues({+ evaluation: expect.objectContaining({ enabled: true }),+ })++ keysLogic.actions.loadEvaluationConfigSuccess({+ trial_eval_limit: 100,+ trial_evals_used: 100,+ trial_evals_remaining: 0,+ trial_grandfathered: false,+ trial_deprecation_date: '2026-07-17T00:00:00Z',+ active_provider_key: null,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ })++ await expectLogic(logic).toMatchValues({+ evaluation: expect.objectContaining({ enabled: false }),+ })+ })+it('loads existing evaluation', async () => {logic = llmEvaluationLogic({ evaluationId: 'eval-123' })logic.mount()@@ -1095,6 +1168,8 @@ describe('llmEvaluationLogic', () => {trial_eval_limit: 100,trial_evals_used: 100,trial_evals_remaining: 0,+ trial_grandfathered: false,+ trial_deprecation_date: '2026-07-15T00:00:00Z',active_provider_key: null,created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.tsindex bed3b8175e1c..751406001876 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts@@ -20,9 +20,9 @@ import { queryEvaluationRuns } from '../utils'import { evaluationErrorMessage } from './apiErrors'import { EVALUATION_SUMMARY_MAX_RUNS } from './constants'import {+ evaluationCanResolveModel,evaluationSupportsReports,evaluationTypeDefaultsToBooleanOutput,- evaluationTypeUsesProviderKey,isBooleanEvaluationOutput,isLLMJudgeEvaluation,} from './evaluationCapabilities'@@ -141,13 +141,13 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([connect(() => ({values: [llmProviderKeysLogic,- ['providerKeys', 'providerKeysLoading', 'isTrialLimitReached'],+ ['providerKeys', 'providerKeysLoading', 'requiresProviderKey', 'isTrialGrandfathered'],signalSourcesLogic,['sourceConfigs', 'sourceConfigsLoading'],],actions: [llmProviderKeysLogic,- ['loadProviderKeys'],+ ['loadProviderKeys', 'loadEvaluationConfigSuccess'],signalSourcesLogic,['loadSourceConfigs',@@ -496,6 +496,18 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([}),listeners(({ actions, values, props }) => ({+ loadEvaluationConfigSuccess: () => {+ // The new-eval draft's enabled default is read before the team's evaluation config has+ // loaded — correct it once we know the draft can't actually resolve a model.+ if (+ props.evaluationId === 'new' &&+ values.evaluation?.enabled &&+ !evaluationCanResolveModel(values.evaluation, values.requiresProviderKey, values.isTrialGrandfathered)+ ) {+ actions.setEvaluationEnabled(false)+ }+ },+loadEvaluation: async () => {if (props.evaluationId && props.evaluationId !== 'new') {try {@@ -522,7 +534,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([id: '',name: template?.name || '',description: template?.description || '',- enabled: true,+ // Starting a keyless draft enabled would 400 on save for teams that require a key.+ enabled: !values.requiresProviderKey,status: 'active' as const,status_reason: null,status_reason_detail: null,@@ -619,7 +632,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([id: '',name: '',description: '',- enabled: true,+ enabled: !values.requiresProviderKey,status: 'active',status_reason: null,status_reason_detail: null,@@ -797,16 +810,16 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([],canEnable: [- (s) => [s.evaluation, s.isTrialLimitReached],- (evaluation: EvaluationConfig | null, isTrialLimitReached: boolean): boolean => {- if (!evaluation || !isTrialLimitReached) {- return true- }- if (!evaluationTypeUsesProviderKey(evaluation.evaluation_type)) {+ (s) => [s.evaluation, s.requiresProviderKey, s.isTrialGrandfathered],+ (+ evaluation: EvaluationConfig | null,+ requiresProviderKey: boolean,+ isTrialGrandfathered: boolean+ ): boolean => {+ if (!evaluation) {return true}- // Can enable if the evaluation has a BYOK key- return !!evaluation.model_configuration?.provider_key_id+ return evaluationCanResolveModel(evaluation, requiresProviderKey, isTrialGrandfathered)},],@@ -816,7 +829,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([if (canEnable) {return null}- return 'Trial evaluation limit reached. Add a provider API key to re-enable this evaluation.'+ return 'Add a provider API key to enable this evaluation.'},],diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.tsindex d24f1b558488..b0289c8330de 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts@@ -107,6 +107,8 @@ describe('llmEvaluationsLogic', () => {trial_eval_limit: 100,trial_evals_used: 0,trial_evals_remaining: 100,+ trial_grandfathered: false,+ trial_deprecation_date: '2026-07-15T00:00:00Z',active_provider_key: null,created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',@@ -145,6 +147,8 @@ describe('llmEvaluationsLogic', () => {trial_eval_limit: 100,trial_evals_used: 100,trial_evals_remaining: 0,+ trial_grandfathered: false,+ trial_deprecation_date: '2026-07-15T00:00:00Z',active_provider_key: null,created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',@@ -155,6 +159,28 @@ describe('llmEvaluationsLogic', () => {expect(logic.values.canEnableEvaluation(evaluationWithKey('llm-default', null))).toBe(false)})+ it('an active team key only unlocks null-config evaluations, never explicit keyless ones', async () => {+ // Runtime resolution uses the active key only for null configs — explicit keyless+ // configs never fall back to it, so they stay blocked.+ keysLogic.actions.loadEvaluationConfigSuccess({+ trial_eval_limit: 100,+ trial_evals_used: 100,+ trial_evals_remaining: 0,+ trial_grandfathered: false,+ trial_deprecation_date: '2026-07-17T00:00:00Z',+ active_provider_key: mockProviderKeys[0],+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ })++ const explicitKeyless: LLMJudgeEvaluation = {+ ...evaluationWithKey('llm-explicit', null),+ model_configuration: { provider: 'openai', model: 'gpt-5-mini', provider_key_id: null },+ }+ expect(logic.values.canEnableEvaluation(explicitKeyless)).toBe(false)+ expect(logic.values.canEnableEvaluation(evaluationWithKey('llm-default', null))).toBe(true)+ })+it('returns unhealthy keys used by evaluations without duplicates', async () => {logic.actions.loadEvaluations()keysLogic.actions.loadProviderKeys()diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.tsindex 3895a08305c4..e5300e19a0ae 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts@@ -15,7 +15,7 @@ import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-generaimport { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'import { getUnhealthyProviderKey } from '../settings/providerKeyStateUtils'import { evaluationErrorMessage } from './apiErrors'-import { evaluationTypeCanBeCreated, evaluationTypeUsesProviderKey } from './evaluationCapabilities'+import { evaluationCanResolveModel, evaluationTypeCanBeCreated } from './evaluationCapabilities'import type { llmEvaluationsLogicType } from './llmEvaluationsLogicType'import { EvaluationConfig } from './types'@@ -40,7 +40,12 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([path(['products', 'ai_observability', 'evaluations', 'llmEvaluationsLogic']),props({} as LLMEvaluationsLogicProps),connect(() => ({- values: [featureFlagLogic, ['featureFlags'], llmProviderKeysLogic, ['providerKeys', 'isTrialLimitReached']],+ values: [+ featureFlagLogic,+ ['featureFlags'],+ llmProviderKeysLogic,+ ['providerKeys', 'requiresProviderKey', 'isTrialGrandfathered'],+ ],actions: [teamLogic, ['addProductIntent'], llmProviderKeysLogic, ['loadProviderKeys']],})),@@ -262,17 +267,10 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([},],canEnableEvaluation: [- (s) => [s.isTrialLimitReached],- (isTrialLimitReached: boolean) => {- return (evaluation: EvaluationConfig): boolean => {- if (!isTrialLimitReached) {- return true- }- if (!evaluationTypeUsesProviderKey(evaluation.evaluation_type)) {- return true- }- return !!evaluation.model_configuration?.provider_key_id- }+ (s) => [s.requiresProviderKey, s.isTrialGrandfathered],+ (requiresProviderKey: boolean, isTrialGrandfathered: boolean) => {+ return (evaluation: EvaluationConfig): boolean =>+ evaluationCanResolveModel(evaluation, requiresProviderKey, isTrialGrandfathered)},],diff --git a/products/ai_observability/frontend/evaluations/statusDisplay.test.ts b/products/ai_observability/frontend/evaluations/statusDisplay.test.tsindex 550223fa350a..fcf3c194907c 100644--- a/products/ai_observability/frontend/evaluations/statusDisplay.test.ts+++ b/products/ai_observability/frontend/evaluations/statusDisplay.test.ts@@ -3,6 +3,7 @@ import { statusReasonLabel, statusReasonRecoveryLabel } from './statusDisplay'describe('statusDisplay', () => {describe('statusReasonLabel', () => {it.each([+ ['provider_key_required' as const, 'No provider API key configured'],['trial_limit_reached' as const, 'Trial evaluation limit reached'],['model_not_allowed' as const, 'Model not available on the trial plan'],['provider_key_deleted' as const, 'Provider API key was deleted'],@@ -25,6 +26,10 @@ describe('statusDisplay', () => {describe('statusReasonRecoveryLabel', () => {it.each([+ [+ 'provider_key_required' as const,+ 'Add a provider API key in settings, then re-enable the evaluation to resume running.',+ ],['trial_limit_reached' as const,'Add a provider API key in settings, then re-enable the evaluation to resume running.',diff --git a/products/ai_observability/frontend/evaluations/statusDisplay.ts b/products/ai_observability/frontend/evaluations/statusDisplay.tsindex 86de3c897130..64f8dd863e6b 100644--- a/products/ai_observability/frontend/evaluations/statusDisplay.ts+++ b/products/ai_observability/frontend/evaluations/statusDisplay.ts@@ -1,6 +1,7 @@import { EvaluationStatusReason } from './types'const REASON_LABELS: Record<EvaluationStatusReason, string> = {+ provider_key_required: 'No provider API key configured',trial_limit_reached: 'Trial evaluation limit reached',model_not_allowed: 'Model not available on the trial plan',provider_key_deleted: 'Provider API key was deleted',@@ -29,7 +30,7 @@ export function statusReasonLabel(reason: EvaluationStatusReason | null | undefi}export function statusReasonRecoveryLabel(reason: EvaluationStatusReason | null | undefined): string {- if (reason === 'trial_limit_reached') {+ if (reason === 'provider_key_required' || reason === 'trial_limit_reached') {return 'Add a provider API key in settings, then re-enable the evaluation to resume running.'}if (reason === 'model_not_allowed') {diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.tsindex 0060a285d7f9..666cb51e610a 100644--- a/products/ai_observability/frontend/evaluations/types.ts+++ b/products/ai_observability/frontend/evaluations/types.ts@@ -7,6 +7,7 @@ export type EvaluationTarget = 'generation' | 'trace'export type EvaluationOutputType = 'boolean' | 'sentiment'export type EvaluationStatus = 'active' | 'paused' | 'error'export type EvaluationStatusReason =+ | 'provider_key_required'| 'trial_limit_reached'| 'model_not_allowed'| 'provider_key_deleted'diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex 545d7b05cb24..d35ce8d96a5f 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -344,6 +344,7 @@ export const EvaluationStatusEnumApi = {} as const/**+ * * `provider_key_required` - No provider API key configured* * `trial_limit_reached` - Trial evaluation limit reached* * `model_not_allowed` - Model not available on the trial plan* * `provider_key_deleted` - Provider API key was deleted@@ -358,6 +359,7 @@ export const EvaluationStatusEnumApi = {export type StatusReasonEnumApi = (typeof StatusReasonEnumApi)[keyof typeof StatusReasonEnumApi]export const StatusReasonEnumApi = {+ ProviderKeyRequired: 'provider_key_required',TrialLimitReached: 'trial_limit_reached',ModelNotAllowed: 'model_not_allowed',ProviderKeyDeleted: 'provider_key_deleted',@@ -965,6 +967,10 @@ export interface EvaluationConfigApi {readonly trial_evals_used: number/** Trial runs remaining — a getting-started affordance only; evals should use the team's own provider key. */readonly trial_evals_remaining: number+ /** True while this team keeps PostHog-funded trial inference during the deprecation window (i.e. it is mid-trial and the cutoff has not passed). False means the team must use its own provider key. */+ readonly trial_grandfathered: boolean+ /** Timestamp after which trial evaluations are fully removed and every team must use its own provider key. */+ readonly trial_deprecation_date: string/** Provider key used to run llm_judge evals; null if none configured yet. */readonly active_provider_key: LLMProviderKeyApi | null/** Timestamp when the evaluation config row was created. */@@ -1237,7 +1243,7 @@ export interface EvaluationSummaryResponseApi {export interface LLMModelInfoApi {/** Provider-specific model identifier (e.g. 'gpt-4o-mini', 'claude-3-5-sonnet-20241022'). */id: string- /** True if the model can run without a provider key — for getting-started testing only; real evals should use the team's own key. */+ /** True if the model can run without a provider key on PostHog-funded trial credits. Only true for teams still grandfathered into the deprecating trial; every other team must use its own key. */posthog_available: boolean}diff --git a/products/ai_observability/frontend/settings/LLMProviderKeysSettings.tsx b/products/ai_observability/frontend/settings/LLMProviderKeysSettings.tsxindex 50ac33d08a67..bd481a6c372e 100644--- a/products/ai_observability/frontend/settings/LLMProviderKeysSettings.tsx+++ b/products/ai_observability/frontend/settings/LLMProviderKeysSettings.tsx@@ -36,7 +36,7 @@ import {llmProviderKeysLogic,sortProviderKeys,} from './llmProviderKeysLogic'-import { TrialUsageMeterDisplay } from './TrialUsageMeter'+import { TrialUsageMeter } from './TrialUsageMeter'function StateTag({ state, errorMessage }: { state: LLMProviderKeyState; errorMessage: string | null }): JSX.Element {const tagProps: { type: 'success' | 'danger' | 'warning' | 'default'; children: string } = {@@ -752,7 +752,6 @@ export function LLMProviderKeysSettings(): JSX.Element {const {providerKeys,providerKeysLoading,- evaluationConfig,evaluationConfigLoading,editingKey,validatingKeyId,@@ -882,9 +881,7 @@ export function LLMProviderKeysSettings(): JSX.Element {</LemonButton></div>- {evaluationConfig && !evaluationConfig.active_provider_key && (- <TrialUsageMeterDisplay evaluationConfig={evaluationConfig} />- )}+ <TrialUsageMeter showSettingsLink={false} />{providerKeys.length === 0 ? (<div className="border rounded-lg p-8 flex flex-col items-center">diff --git a/products/ai_observability/frontend/settings/TrialUsageMeter.tsx b/products/ai_observability/frontend/settings/TrialUsageMeter.tsxindex 0615ee5d0316..2b1250be6a70 100644--- a/products/ai_observability/frontend/settings/TrialUsageMeter.tsx+++ b/products/ai_observability/frontend/settings/TrialUsageMeter.tsx@@ -1,10 +1,35 @@import { useValues } from 'kea'-import { Link } from '@posthog/lemon-ui'+import { LemonBanner, Link } from '@posthog/lemon-ui'+import { dayjs } from 'lib/dayjs'import { urls } from 'scenes/urls'-import { EvaluationConfig, llmProviderKeysLogic } from './llmProviderKeysLogic'+import { EvaluationTrialConfig, llmProviderKeysLogic } from './llmProviderKeysLogic'++function TrialDeprecationBanner({+ deprecationDate,+ showSettingsLink,+ noun,+}: {+ deprecationDate: string+ showSettingsLink: boolean+ noun: string+}): JSX.Element {+ const endDate = dayjs.utc(deprecationDate).format('MMMM D, YYYY')++ return (+ <LemonBanner type="warning">+ Trial {noun} are being phased out and will be removed on {endDate}.{' '}+ {showSettingsLink ? (+ <Link to={urls.settings('project-ai-observability', 'ai-observability-byok')}>Add a provider key</Link>+ ) : (+ 'Add a provider key'+ )}{' '}+ to keep {noun} working without interruption.+ </LemonBanner>+ )+}export function TrialUsageMeter({showSettingsLink = false,@@ -15,68 +40,65 @@ export function TrialUsageMeter({}): JSX.Element | null {const { evaluationConfig } = useValues(llmProviderKeysLogic)- if (!evaluationConfig || evaluationConfig.active_provider_key) {+ // Terminal teams get no trial UI at all — post-deprecation the trial should look like it never existed.+ if (!evaluationConfig || !evaluationConfig.trial_grandfathered || evaluationConfig.active_provider_key) {return null}return (- <TrialUsageMeterDisplay evaluationConfig={evaluationConfig} showSettingsLink={showSettingsLink} noun={noun} />+ <div className="space-y-3">+ <TrialDeprecationBanner+ deprecationDate={evaluationConfig.trial_deprecation_date}+ showSettingsLink={showSettingsLink}+ noun={noun}+ />+ <TrialUsageMeterDisplay+ evaluationConfig={evaluationConfig}+ showSettingsLink={showSettingsLink}+ noun={noun}+ />+ </div>)}-export function TrialUsageMeterDisplay({+function TrialUsageMeterDisplay({evaluationConfig,showSettingsLink = false,noun = 'evaluations',}: {- evaluationConfig: EvaluationConfig+ evaluationConfig: EvaluationTrialConfigshowSettingsLink?: booleannoun?: string}): JSX.Element {const { trial_eval_limit, trial_evals_remaining } = evaluationConfigconst percentUsed = Math.min(((trial_eval_limit - trial_evals_remaining) / trial_eval_limit) * 100, 100)- const isExhausted = trial_evals_remaining <= 0return (<div className="rounded-lg p-4 space-y-3 border"><div className="flex justify-between items-center"><span className="font-medium">Trial {noun}</span>- <span className={`text-sm ${isExhausted ? 'font-medium' : 'text-muted'}`}>+ <span className="text-sm text-muted">{trial_evals_remaining} of {trial_eval_limit} remaining</span></div><div className="h-2 bg-border rounded-full overflow-hidden"><div- className={`h-full transition-all ${isExhausted ? 'bg-danger' : 'bg-success'}`}+ className="h-full transition-all bg-success"// eslint-disable-next-line react/forbid-dom-propsstyle={{ width: `${percentUsed}%` }}/></div>- {isExhausted ? (- <p className="text-sm">- Trial {noun} exhausted.{' '}- {showSettingsLink ? (- <Link to={urls.settings('project-ai-observability', 'ai-observability-byok')}>- Add your API key- </Link>- ) : (- 'Add your API key'- )}{' '}- to continue.- </p>- ) : (- <p className="text-sm text-muted">- You have {trial_evals_remaining} {noun} to try things out before{' '}- {showSettingsLink ? (- <Link to={urls.settings('project-ai-observability', 'ai-observability-byok')}>- adding your own key- </Link>- ) : (- 'adding your own key'- )}- .- </p>- )}+ <p className="text-sm text-muted">+ You have {trial_evals_remaining} {noun} to try things out before{' '}+ {showSettingsLink ? (+ <Link to={urls.settings('project-ai-observability', 'ai-observability-byok')}>+ adding your own key+ </Link>+ ) : (+ 'adding your own key'+ )}+ .+ </p></div>)}diff --git a/products/ai_observability/frontend/settings/llmProviderKeysLogic.ts b/products/ai_observability/frontend/settings/llmProviderKeysLogic.tsindex 49948f91ebf2..9205e890207b 100644--- a/products/ai_observability/frontend/settings/llmProviderKeysLogic.ts+++ b/products/ai_observability/frontend/settings/llmProviderKeysLogic.ts@@ -135,10 +135,12 @@ export function firstUsableProviderKeyIdForProvider(return sortProviderKeys(keys).find((key) => key.state === 'ok' && key.provider === normalizedProvider)?.id ?? null}-export interface EvaluationConfig {+export interface EvaluationTrialConfig {trial_eval_limit: numbertrial_evals_used: numbertrial_evals_remaining: number+ trial_grandfathered: boolean+ trial_deprecation_date: stringactive_provider_key: LLMProviderKey | nullcreated_at: stringupdated_at: string@@ -335,9 +337,9 @@ export const llmProviderKeysLogic = kea<llmProviderKeysLogicType>([},],evaluationConfig: [- null as EvaluationConfig | null,+ null as EvaluationTrialConfig | null,{- loadEvaluationConfig: async (): Promise<EvaluationConfig | null> => {+ loadEvaluationConfig: async (): Promise<EvaluationTrialConfig | null> => {const teamId = teamLogic.values.currentTeamIdif (!teamId) {return null@@ -445,22 +447,27 @@ export const llmProviderKeysLogic = kea<llmProviderKeysLogicType>([selectors({trialEvalsUsed: [(s) => [s.evaluationConfig],- (evaluationConfig: EvaluationConfig | null) => evaluationConfig?.trial_evals_used ?? 0,+ (evaluationConfig: EvaluationTrialConfig | null) => evaluationConfig?.trial_evals_used ?? 0,],trialEvalLimit: [(s) => [s.evaluationConfig],- (evaluationConfig: EvaluationConfig | null) => evaluationConfig?.trial_eval_limit ?? 100,+ (evaluationConfig: EvaluationTrialConfig | null) => evaluationConfig?.trial_eval_limit ?? 100,],trialEvalsRemaining: [(s) => [s.evaluationConfig],- (evaluationConfig: EvaluationConfig | null) => evaluationConfig?.trial_evals_remaining ?? 0,+ (evaluationConfig: EvaluationTrialConfig | null) => evaluationConfig?.trial_evals_remaining ?? 0,],- isTrialLimitReached: [+ isTrialGrandfathered: [(s) => [s.evaluationConfig],- (evaluationConfig: EvaluationConfig | null) =>+ (evaluationConfig: EvaluationTrialConfig | null) => evaluationConfig?.trial_grandfathered ?? false,+ ],+ // Terminal state: no active key and not grandfathered — the team must bring its own provider key.+ requiresProviderKey: [+ (s) => [s.evaluationConfig],+ (evaluationConfig: EvaluationTrialConfig | null) =>evaluationConfig !== null &&evaluationConfig.active_provider_key === null &&- evaluationConfig.trial_evals_remaining <= 0,+ !evaluationConfig.trial_grandfathered,],}),diff --git a/products/ai_observability/frontend/tags/AIObservabilityTag.tsx b/products/ai_observability/frontend/tags/AIObservabilityTag.tsxindex be40689189df..d6b62fc02958 100644--- a/products/ai_observability/frontend/tags/AIObservabilityTag.tsx+++ b/products/ai_observability/frontend/tags/AIObservabilityTag.tsx@@ -33,7 +33,7 @@ import { InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-geimport { getModelPickerFooterLink, ModelPicker } from '../ModelPicker'import { modelPickerLogic } from '../modelPickerLogic'-import { LLMProviderKey } from '../settings/llmProviderKeysLogic'+import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'import {getUnhealthyProviderKey,providerKeyStateIssueDescription,@@ -121,11 +121,13 @@ function TaggerModelPicker({ id }: { id: string }): JSX.Element {} = useValues(modelPickerLogic)const { selectedModel, selectedPickerProviderKeyId } = useValues(llmTaggerLogic({ id }))const { selectModelFromPicker } = useActions(llmTaggerLogic({ id }))+ const { requiresProviderKey } = useValues(llmProviderKeysLogic)- const allModels = hasByokKeys ? byokModels : trialModels+ const showTrialModels = !hasByokKeys && !requiresProviderKey+ const allModels = showTrialModels ? trialModels : byokModelsconst selectedModelName = allModels.find((m) => m.id === selectedModel)?.name- const groups = hasByokKeys ? providerModelGroups : trialProviderModelGroups- const loading = hasByokKeys ? byokModelsLoading || providerKeysLoading : trialModelsLoading+ const groups = showTrialModels ? trialProviderModelGroups : providerModelGroups+ const loading = showTrialModels ? trialModelsLoading : byokModelsLoading || providerKeysLoadingconst footerLink = getModelPickerFooterLink(hasByokKeys)diff --git a/products/ai_observability/frontend/tags/AIObservabilityTagsScene.tsx b/products/ai_observability/frontend/tags/AIObservabilityTagsScene.tsxindex a78e66ed47e6..e2cc7cbfde4d 100644--- a/products/ai_observability/frontend/tags/AIObservabilityTagsScene.tsx+++ b/products/ai_observability/frontend/tags/AIObservabilityTagsScene.tsx@@ -277,7 +277,7 @@ function AIObservabilityTagsContent(): JSX.Element {return (<div className="space-y-4">- <TrialUsageMeter showSettingsLink={false} noun="runs" />+ <TrialUsageMeter showSettingsLink noun="runs" /><DateFilter dateFrom={dateFilter.dateFrom} dateTo={dateFilter.dateTo} onChange={setDates} />diff --git a/products/ai_observability/frontend/tags/llmTaggersLogic.test.ts b/products/ai_observability/frontend/tags/llmTaggersLogic.test.tsindex a4f0b2dd4725..fb20dcc84c7e 100644--- a/products/ai_observability/frontend/tags/llmTaggersLogic.test.ts+++ b/products/ai_observability/frontend/tags/llmTaggersLogic.test.ts@@ -56,6 +56,8 @@ const providerKeyMocks = {trial_eval_limit: 100,trial_evals_used: 0,trial_evals_remaining: 100,+ trial_grandfathered: false,+ trial_deprecation_date: '2026-07-15T00:00:00Z',},}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 15c17330c153..d330ed3f329d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -21094,6 +21094,7 @@ export namespace Schemas {} as const;/**+ * * `provider_key_required` - No provider API key configured* * `trial_limit_reached` - Trial evaluation limit reached* * `model_not_allowed` - Model not available on the trial plan* * `provider_key_deleted` - Provider API key was deleted@@ -21109,6 +21110,7 @@ export namespace Schemas {export const StatusReasonEnum = {+ ProviderKeyRequired: 'provider_key_required',TrialLimitReached: 'trial_limit_reached',ModelNotAllowed: 'model_not_allowed',ProviderKeyDeleted: 'provider_key_deleted',@@ -21327,6 +21329,10 @@ export namespace Schemas {readonly trial_evals_used: number;/** Trial runs remaining — a getting-started affordance only; evals should use the team's own provider key. */readonly trial_evals_remaining: number;+ /** True while this team keeps PostHog-funded trial inference during the deprecation window (i.e. it is mid-trial and the cutoff has not passed). False means the team must use its own provider key. */+ readonly trial_grandfathered: boolean;+ /** Timestamp after which trial evaluations are fully removed and every team must use its own provider key. */+ readonly trial_deprecation_date: string;/** Provider key used to run llm_judge evals; null if none configured yet. */readonly active_provider_key: LLMProviderKey | null;/** Timestamp when the evaluation config row was created. */@@ -29006,7 +29012,7 @@ export namespace Schemas {export interface LLMModelInfo {/** Provider-specific model identifier (e.g. 'gpt-4o-mini', 'claude-3-5-sonnet-20241022'). */id: string;- /** True if the model can run without a provider key — for getting-started testing only; real evals should use the team's own key. */+ /** True if the model can run without a provider key on PostHog-funded trial credits. Only true for teams still grandfathered into the deprecating trial; every other team must use its own key. */posthog_available: boolean;}