: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
feat(aio): run local evals in one temporal activity (#93215)
Bernat Torresc8f9a5fdc358
diff --git a/posthog/temporal/ai_observability/__init__.py b/posthog/temporal/ai_observability/__init__.pyindex b9c80bdd115d..c2e826ff9252 100644--- a/posthog/temporal/ai_observability/__init__.py+++ b/posthog/temporal/ai_observability/__init__.py@@ -38,6 +38,7 @@ from posthog.temporal.ai_observability.evaluation_workflow_activities import (emit_evaluation_event_activity,emit_internal_telemetry_activity,fetch_evaluation_activity,+ run_local_evaluation_activity,send_evaluation_disabled_email_activity,update_key_state_activity,)@@ -97,6 +98,7 @@ EVAL_WORKFLOWS = [EVAL_ACTIVITIES = [fetch_evaluation_activity,+ run_local_evaluation_activity,disable_evaluation_activity,send_evaluation_disabled_email_activity,update_key_state_activity,@@ -181,6 +183,7 @@ ACTIVITIES = [emit_evaluation_cluster_events_activity,# Keep eval activities registered here temporarily so orphaned workflows on general-purpose queue can completefetch_evaluation_activity,+ run_local_evaluation_activity,disable_evaluation_activity,send_evaluation_disabled_email_activity,update_key_state_activity,diff --git a/posthog/temporal/ai_observability/evaluation_hog.py b/posthog/temporal/ai_observability/evaluation_hog.pyindex 4b78c92f5751..0feb23848ef1 100644--- a/posthog/temporal/ai_observability/evaluation_hog.py+++ b/posthog/temporal/ai_observability/evaluation_hog.py@@ -335,8 +335,7 @@ def run_hog_eval(bytecode: list, event_data: dict[str, Any], allows_na: bool = Freturn execute_hog_eval_bytecode(bytecode, globals_dict, allows_na=allows_na)-async def execute_hog_eval_activity(evaluation: dict[str, Any], event_data: dict[str, Any]) -> EvaluationActivityResult:+async def run_hog_eval_for_event(evaluation: dict[str, Any], event_data: dict[str, Any]) -> EvaluationActivityResult:"""Execute Hog code to evaluate the target event."""if evaluation["evaluation_type"] != "hog":raise ApplicationError(@@ -358,3 +357,9 @@ async def execute_hog_eval_activity(evaluation: dict[str, Any], event_data: dictresult = await database_sync_to_async(_execute, thread_sensitive=False)()return finalize_hog_eval_result(result, evaluation=evaluation, allows_na=allows_na, unit_label=None)+++async def execute_hog_eval_activity(evaluation: dict[str, Any], event_data: dict[str, Any]) -> EvaluationActivityResult:+ """Execute Hog code to evaluate the target event."""+ return await run_hog_eval_for_event(evaluation, event_data)diff --git a/posthog/temporal/ai_observability/evaluation_sentiment.py b/posthog/temporal/ai_observability/evaluation_sentiment.pyindex 5a91a0ac6a4e..80a0a5b1f7e8 100644--- a/posthog/temporal/ai_observability/evaluation_sentiment.py+++ b/posthog/temporal/ai_observability/evaluation_sentiment.py@@ -60,10 +60,7 @@ def _build_sentiment_activity_result(}-async def execute_sentiment_eval_activity(- evaluation: dict[str, Any], event_data: dict[str, Any]-) -> EvaluationActivityResult:+async def run_sentiment_eval(evaluation: dict[str, Any], event_data: dict[str, Any]) -> EvaluationActivityResult:"""Classify sentiment for the target event's user messages."""if evaluation["evaluation_type"] != "sentiment":raise ApplicationError(@@ -105,3 +102,11 @@ async def execute_sentiment_eval_activity(classification_results = await asyncio.to_thread(classify, texts)return _build_sentiment_activity_result(event_uuid, trace_id, user_messages, classification_results)+++async def execute_sentiment_eval_activity(+ evaluation: dict[str, Any], event_data: dict[str, Any]+) -> EvaluationActivityResult:+ """Classify sentiment for the target event's user messages."""+ return await run_sentiment_eval(evaluation, event_data)diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.pyindex c6d5d7945da1..c44ebefea8f7 100644--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py@@ -1,6 +1,7 @@import json+import uuidfrom dataclasses import dataclass-from datetime import UTC, datetime+from datetime import datetimefrom typing import Anyfrom django.conf import settings@@ -9,11 +10,16 @@ from django.db import transactionimport structlogimport temporaliofrom structlog.contextvars import bind_contextvars+from temporalio.exceptions import ApplicationErrorfrom posthog.api.capture import CaptureInternalError+from posthog.dataclasses import frozenfrom posthog.models.team import Team-from posthog.sync import database_sync_to_async+from posthog.sync import database_sync_to_async, database_sync_to_async_pool+from posthog.temporal.ai_observability.evaluation_errors import is_terminal_user_error_result+from posthog.temporal.ai_observability.evaluation_hog import run_hog_eval_for_eventfrom posthog.temporal.ai_observability.evaluation_llm_judge import DEFAULT_JUDGE_MODEL+from posthog.temporal.ai_observability.evaluation_sentiment import run_sentiment_evalfrom posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResultfrom posthog.temporal.ai_observability.metrics import increment_emit_event_outcomefrom posthog.temporal.ai_observability.team_capture import capture_internal_for_team@@ -25,6 +31,8 @@ logger = structlog.get_logger(__name__)SOURCE_AI_PROPERTIES_TO_COPY = ("$ai_prompt_name", "$ai_prompt_version")+EMIT_EVALUATION_EVENT_FAILED_ERROR_TYPE = "EmitEvaluationEventFailed"+@dataclassclass RunEvaluationInputs:@@ -39,44 +47,45 @@ class RunEvaluationInputs:}+def fetch_evaluation(evaluation_id: str, team_id: int) -> dict[str, Any]:+ """Fetch evaluation config from Postgres."""+ try:+ evaluation = Evaluation.objects.select_related(+ "model_configuration",+ "model_configuration__provider_key",+ ).get(id=evaluation_id, team_id=team_id)++ model_configuration = None+ if evaluation.model_configuration:+ mc = evaluation.model_configuration+ model_configuration = {+ "provider": mc.provider,+ "model": mc.model,+ "provider_key_id": str(mc.provider_key_id) if mc.provider_key_id else None,+ }++ return {+ "id": str(evaluation.id),+ "name": evaluation.name,+ "evaluation_type": evaluation.evaluation_type,+ "evaluation_config": evaluation.evaluation_config,+ "output_type": evaluation.output_type,+ "output_config": evaluation.output_config,+ "team_id": evaluation.team_id,+ "model_configuration": model_configuration,+ "enabled": evaluation.enabled,+ "deleted": evaluation.deleted,+ }+ except Evaluation.DoesNotExist:+ logger.exception("Evaluation not found", evaluation_id=evaluation_id)+ raise ValueError(f"Evaluation {evaluation_id} not found")++@temporalio.activity.defnasync def fetch_evaluation_activity(inputs: RunEvaluationInputs) -> dict[str, Any]:"""Fetch evaluation config from Postgres."""bind_contextvars(team_id=inputs.event_data.get("team_id"), evaluation_id=inputs.evaluation_id)-- def _fetch() -> dict[str, Any]:- try:- evaluation = Evaluation.objects.select_related(- "model_configuration",- "model_configuration__provider_key",- ).get(id=inputs.evaluation_id, team_id=inputs.event_data["team_id"])-- model_configuration = None- if evaluation.model_configuration:- mc = evaluation.model_configuration- model_configuration = {- "provider": mc.provider,- "model": mc.model,- "provider_key_id": str(mc.provider_key_id) if mc.provider_key_id else None,- }-- return {- "id": str(evaluation.id),- "name": evaluation.name,- "evaluation_type": evaluation.evaluation_type,- "evaluation_config": evaluation.evaluation_config,- "output_type": evaluation.output_type,- "output_config": evaluation.output_config,- "team_id": evaluation.team_id,- "model_configuration": model_configuration,- "enabled": evaluation.enabled,- "deleted": evaluation.deleted,- }- except Evaluation.DoesNotExist:- logger.exception("Evaluation not found", evaluation_id=inputs.evaluation_id)- raise ValueError(f"Evaluation {inputs.evaluation_id} not found")-- return await database_sync_to_async(_fetch)()+ return await database_sync_to_async(fetch_evaluation)(inputs.evaluation_id, inputs.event_data["team_id"])@temporalio.activity.defn@@ -273,9 +282,22 @@ def build_evaluation_event_properties(return properties-async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> None:- """Emit $ai_evaluation event via capture_internal so it routes through the ingestion pipeline for cost calculation."""+def _evaluation_event_uuid() -> str | None:+ """One workflow emits one $ai_evaluation, so its uuid derives from the workflow id, which+ survives activity retries and workflow-level retries alike. A manual re-run mints a new+ workflow id (it embeds a ms timestamp), so re-runs still get distinct events."""+ if not temporalio.activity.in_activity():+ return None+ workflow_id = temporalio.activity.info().workflow_id+ return str(uuid.uuid5(uuid.NAMESPACE_URL, f"posthog://ai-evaluation/{workflow_id}"))+++async def emit_generation_evaluation_event(inputs: EmitEvaluationEventInputs) -> None:+ """Emit the $ai_evaluation event via capture_internal so it routes through the ingestion+ pipeline for cost calculation. A billing-limited capture drops the event without failing+ the caller. The event timestamp is the workflow start time, not emit time: ingestion dedup+ keys on (timestamp, event, distinct_id, token), so only a stable timestamp lets a retried+ emit collapse into the original."""evaluation = inputs.evaluationevent_data = inputs.event_dataresult = inputs.result@@ -309,8 +331,9 @@ async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> Nevent_name="$ai_evaluation",event_source="llm_analytics_evaluation",distinct_id=event_data["distinct_id"],- timestamp=datetime.now(UTC),+ timestamp=start_time,properties=properties,+ event_uuid=_evaluation_event_uuid(),)try:@@ -328,6 +351,12 @@ async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> Nraise+async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> None:+ """Emit $ai_evaluation event via capture_internal so it routes through the ingestion pipeline for cost calculation."""+ await emit_generation_evaluation_event(inputs)++@dataclassclass EmitInternalTelemetryInputs:evaluation: dict[str, Any]@@ -373,3 +402,69 @@ async def emit_internal_telemetry_activity(inputs: EmitInternalTelemetryInputs)ph_client.flush()await database_sync_to_async(_emit_telemetry, thread_sensitive=False)()+++@frozen+class RunLocalEvaluationInputs:+ evaluation_id: str+ event_data: dict[str, Any]+ start_time: datetime++ @property+ def properties_to_log(self) -> dict[str, Any]:+ return {+ "evaluation_id": self.evaluation_id,+ "team_id": self.event_data.get("team_id"),+ }+++@frozen+class LocalEvaluationOutcome:+ """What `run_local_evaluation_activity` handled.++ `result` is None when the evaluation runs on an LLM judge: the activity only fetched the+ config, and the workflow must run the judge with its own timeout and retry policy. `emitted`+ says whether the $ai_evaluation event was sent here, so the workflow never emits a second one.+ """++ evaluation: dict[str, Any]+ result: EvaluationActivityResult | None+ emitted: bool+++async def run_local_evaluation_activity(inputs: RunLocalEvaluationInputs) -> LocalEvaluationOutcome:+ """Fetch the evaluation and, for hog and sentiment, execute it and emit its event in one+ activity. These runtimes make no external call, so one activity replaces three Temporal+ Cloud actions. llm_judge returns after the fetch: the judge needs its own activity and+ retry policy. Terminal user errors skip the emit; the workflow owns disable and notify.+ """+ bind_contextvars(team_id=inputs.event_data.get("team_id"), evaluation_id=inputs.evaluation_id)+ evaluation = await database_sync_to_async_pool(fetch_evaluation)(inputs.evaluation_id, inputs.event_data["team_id"])++ evaluation_type = evaluation.get("evaluation_type", "llm_judge")+ if evaluation_type == "hog":+ result = await run_hog_eval_for_event(evaluation, inputs.event_data)+ elif evaluation_type == "sentiment":+ result = await run_sentiment_eval(evaluation, inputs.event_data)+ else:+ return LocalEvaluationOutcome(evaluation=evaluation, result=None, emitted=False)++ emitted = False+ if not is_terminal_user_error_result(result):+ try:+ await emit_generation_evaluation_event(+ EmitEvaluationEventInputs(+ evaluation=evaluation,+ event_data=inputs.event_data,+ result=result,+ start_time=inputs.start_time,+ )+ )+ except Exception as error:+ # Typed so the workflow counts one emit failure per run, after retries end.+ raise ApplicationError(+ "Failed to emit $ai_evaluation", type=EMIT_EVALUATION_EVENT_FAILED_ERROR_TYPE+ ) from error+ emitted = True+ return LocalEvaluationOutcome(evaluation=evaluation, result=result, emitted=emitted)diff --git a/posthog/temporal/ai_observability/metrics.py b/posthog/temporal/ai_observability/metrics.pyindex 831d60b58595..55978abaa762 100644--- a/posthog/temporal/ai_observability/metrics.py+++ b/posthog/temporal/ai_observability/metrics.py@@ -25,6 +25,7 @@ LOGGER = get_write_only_logger(__name__)EVAL_ACTIVITY_TYPES = {"fetch_evaluation_activity",+ "run_local_evaluation_activity","execute_llm_judge_activity","execute_hog_eval_activity","execute_sentiment_eval_activity",@@ -143,10 +144,10 @@ def increment_tokens(token_type: str, count: int) -> None:def increment_emit_event_outcome(outcome: str) -> None:"""Track $ai_evaluation event emission outcomes (success/failed/dropped_billing_limited).- Distinguishes Activity 4 failures from other workflow failures so we can- measure and alert on dropped eval events specifically. `dropped_billing_limited`- is an expected billing condition, not a system failure, so it's kept out of- the `failed` bucket the error-rate alert watches.+ Distinguishes emit failures from other workflow failures so we can measure dropped+ eval events specifically, and the LLMAEvalsHighErrorRate alert divides llma_eval_errors+ by this counter's total. `dropped_billing_limited` is an expected billing condition,+ not a system failure, so it's kept out of the `failed` bucket."""if not activity.in_activity() and not workflow.in_workflow():returndiff --git a/posthog/temporal/ai_observability/run_evaluation.py b/posthog/temporal/ai_observability/run_evaluation.pyindex 1e89c6744821..ce7bba85f823 100644--- a/posthog/temporal/ai_observability/run_evaluation.py+++ b/posthog/temporal/ai_observability/run_evaluation.py@@ -31,14 +31,17 @@ from posthog.temporal.ai_observability.evaluation_llm_judge import (from posthog.temporal.ai_observability.evaluation_sentiment import execute_sentiment_eval_activityfrom posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResultfrom posthog.temporal.ai_observability.evaluation_workflow_activities import (+ EMIT_EVALUATION_EVENT_FAILED_ERROR_TYPE,EmitEvaluationEventInputs,EmitInternalTelemetryInputs,RunEvaluationInputs,+ RunLocalEvaluationInputs,SendEvaluationDisabledEmailInputs,disable_evaluation_activity,emit_evaluation_event_activity,emit_internal_telemetry_activity,fetch_evaluation_activity,+ run_local_evaluation_activity,send_evaluation_disabled_email_activity,update_key_state_activity,)@@ -64,6 +67,7 @@ __all__ = ["EvaluationActivityResult","RunEvaluationInputs","RunEvaluationWorkflow",+ "RunLocalEvaluationInputs","SendEvaluationDisabledEmailInputs","WorkflowResult","build_system_prompt",@@ -80,6 +84,7 @@ __all__ = ["handle_llm_judge_activity_error","handle_terminal_user_error_result","run_hog_eval",+ "run_local_evaluation_activity","send_evaluation_disabled_email_activity","update_key_state_activity",]@@ -254,45 +259,87 @@ class RunEvaluationWorkflow(PostHogWorkflow):temporalio.workflow.deprecate_patch("remove-trial-evals")start_time = temporalio.workflow.now()- evaluation = await temporalio.workflow.execute_activity(- fetch_evaluation_activity,- inputs,- schedule_to_close_timeout=timedelta(seconds=30),- retry_policy=RetryPolicy(maximum_attempts=3),- )-- evaluation_type = evaluation.get("evaluation_type", "llm_judge")- if evaluation_type == "hog":- result = await temporalio.workflow.execute_activity(- execute_hog_eval_activity,- args=[evaluation, inputs.event_data],- schedule_to_close_timeout=timedelta(seconds=30),- retry_policy=RetryPolicy(maximum_attempts=1),- )- elif evaluation_type == "sentiment":- result = await temporalio.workflow.execute_activity(- execute_sentiment_eval_activity,- args=[evaluation, inputs.event_data],- schedule_to_close_timeout=timedelta(seconds=120),- retry_policy=RetryPolicy(maximum_attempts=1),- )- elif evaluation_type == "llm_judge":+ # One activity fetches the evaluation and, for hog and sentiment, also executes it and+ # emits its event, so three Temporal Cloud actions become one for these local evaluation+ # types, which are the large majority of volume.+ # Pre-patch histories replay the separate fetch/execute/emit commands below.+ result: EvaluationActivityResult | None = None+ emitted_in_activity = False+ if temporalio.workflow.patched("merge-local-eval-activities-2026-09"):try:- result = await temporalio.workflow.execute_activity(- execute_llm_judge_activity,- ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=inputs.event_data),- schedule_to_close_timeout=timedelta(minutes=6),- retry_policy=LLM_JUDGE_RETRY_POLICY,+ outcome = await temporalio.workflow.execute_activity(+ run_local_evaluation_activity,+ RunLocalEvaluationInputs(+ evaluation_id=inputs.evaluation_id,+ event_data=inputs.event_data,+ start_time=start_time,+ ),+ start_to_close_timeout=timedelta(seconds=120),+ # Total deadline including queue wait: without it a task stuck in the queue+ # keeps the workflow RUNNING forever, and USE_EXISTING then blocks every later+ # trigger for this (evaluation, event) pair.+ schedule_to_close_timeout=timedelta(minutes=8),+ retry_policy=RetryPolicy(maximum_attempts=3),)except temporalio.exceptions.ActivityError as e:- handled = await handle_llm_judge_activity_error(e, evaluation, evaluation_type)- if handled is not None:- return handled+ if isinstance(e.cause, ApplicationError) and e.cause.type == EMIT_EVALUATION_EVENT_FAILED_ERROR_TYPE:+ # Feeds llma_eval_errors, the LLMAEvalsHighErrorRate numerator — once per+ # workflow after retries end, matching the legacy emit path below.+ increment_errors("emit_evaluation_event_failed")raise+ evaluation = outcome.evaluation+ result = outcome.result+ emitted_in_activity = outcome.emittedelse:+ evaluation = await temporalio.workflow.execute_activity(+ fetch_evaluation_activity,+ inputs,+ schedule_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )++ evaluation_type = evaluation.get("evaluation_type", "llm_judge")++ if result is None:+ if evaluation_type == "hog":+ result = await temporalio.workflow.execute_activity(+ execute_hog_eval_activity,+ args=[evaluation, inputs.event_data],+ schedule_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ elif evaluation_type == "sentiment":+ result = await temporalio.workflow.execute_activity(+ execute_sentiment_eval_activity,+ args=[evaluation, inputs.event_data],+ schedule_to_close_timeout=timedelta(seconds=120),+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ elif evaluation_type == "llm_judge":+ try:+ result = await temporalio.workflow.execute_activity(+ execute_llm_judge_activity,+ ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=inputs.event_data),+ schedule_to_close_timeout=timedelta(minutes=6),+ retry_policy=LLM_JUDGE_RETRY_POLICY,+ )+ except temporalio.exceptions.ActivityError as e:+ handled = await handle_llm_judge_activity_error(e, evaluation, evaluation_type)+ if handled is not None:+ return handled+ raise+ else:+ raise ApplicationError(+ f"Unsupported evaluation type: {evaluation_type}",+ non_retryable=True,+ )++ if result is None:+ # Unreachable: every dispatch branch above assigns, returns, or raises. An assert+ # would wedge the workflow task in an infinite retry; this fails the run instead.raise ApplicationError(- f"Unsupported evaluation type: {evaluation_type}",+ f"No evaluation result for type: {evaluation_type}",non_retryable=True,)@@ -303,32 +350,42 @@ class RunEvaluationWorkflow(PostHogWorkflow):result=result,)- try:- await temporalio.workflow.execute_activity(- emit_evaluation_event_activity,- EmitEvaluationEventInputs(- evaluation=evaluation,- event_data=inputs.event_data,- result=result,- start_time=start_time,- ),- schedule_to_close_timeout=timedelta(seconds=30),- retry_policy=RetryPolicy(maximum_attempts=3),- )- except Exception:- increment_errors("emit_evaluation_event_failed", provider=result.get("provider"))- raise+ if not emitted_in_activity:+ try:+ await temporalio.workflow.execute_activity(+ emit_evaluation_event_activity,+ EmitEvaluationEventInputs(+ evaluation=evaluation,+ event_data=inputs.event_data,+ result=result,+ start_time=start_time,+ ),+ schedule_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ except Exception:+ increment_errors("emit_evaluation_event_failed", provider=result.get("provider"))+ raiseif evaluation_type == "llm_judge" and not result.get("skipped"):- await temporalio.workflow.execute_activity(- emit_internal_telemetry_activity,- EmitInternalTelemetryInputs(- evaluation=evaluation,+ try:+ await temporalio.workflow.execute_activity(+ emit_internal_telemetry_activity,+ EmitInternalTelemetryInputs(+ evaluation=evaluation,+ team_id=evaluation["team_id"],+ result=result,+ ),+ schedule_to_close_timeout=timedelta(seconds=30),+ )+ except Exception:+ # Internal telemetry must not fail a workflow whose $ai_evaluation already+ # emitted: the workflow-level retry would re-emit it.+ logger.exception(+ "Failed to emit internal telemetry",+ evaluation_id=evaluation["id"],team_id=evaluation["team_id"],- result=result,- ),- schedule_to_close_timeout=timedelta(seconds=30),- )+ )# Old histories must still issue their recorded activity or child-workflow command during replay.replay_legacy_eval_signal = not temporalio.workflow.patched("remove-per-evaluation-signal-2026-08")diff --git a/posthog/temporal/ai_observability/team_capture.py b/posthog/temporal/ai_observability/team_capture.pyindex e47d5e4f83bd..ae46688eb511 100644--- a/posthog/temporal/ai_observability/team_capture.py+++ b/posthog/temporal/ai_observability/team_capture.py@@ -75,6 +75,7 @@ def capture_internal_for_team(timestamp: datetime,properties: dict[str, Any],process_person_profile: bool = True,+ event_uuid: str | None = None,) -> None:"""Capture one event for a team, raising on a non-2xx capture response."""token = get_team_api_token(team_id)@@ -87,6 +88,7 @@ def capture_internal_for_team(timestamp=timestamp,properties=properties,process_person_profile=process_person_profile,+ event_uuid=event_uuid,)result.raise_for_status()except CaptureInternalError as e:diff --git a/posthog/temporal/ai_observability/test_metrics.py b/posthog/temporal/ai_observability/test_metrics.pyindex e17f29879148..2237757f8113 100644--- a/posthog/temporal/ai_observability/test_metrics.py+++ b/posthog/temporal/ai_observability/test_metrics.py@@ -119,6 +119,7 @@ class TestActivityTypes:"""Test that EVAL_ACTIVITY_TYPES contains the expected activities"""expected = {"fetch_evaluation_activity",+ "run_local_evaluation_activity","execute_llm_judge_activity","execute_hog_eval_activity","execute_sentiment_eval_activity",diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex c1e9e54b4e0b..a75044f1ec06 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -41,6 +41,7 @@ from .evaluation_errors import (terminal_user_error_result_from_application_error,)from .evaluation_llm_judge import JUDGE_EVENT_MAX_CHARS+from .evaluation_workflow_activities import LocalEvaluationOutcomefrom .run_evaluation import (BooleanEvalResult,BooleanWithNAEvalResult,@@ -50,6 +51,7 @@ from .run_evaluation import (ExecuteLLMJudgeInputs,RunEvaluationInputs,RunEvaluationWorkflow,+ RunLocalEvaluationInputs,SendEvaluationDisabledEmailInputs,WorkflowResult,disable_evaluation_activity,@@ -60,6 +62,7 @@ from .run_evaluation import (extract_event_tools,fetch_evaluation_activity,run_hog_eval,+ run_local_evaluation_activity,send_evaluation_disabled_email_activity,)@@ -184,10 +187,28 @@ class TestRunEvaluationWorkflow:async def mock_emit_internal_telemetry(_: EmitInternalTelemetryInputs) -> None:return+ @activity.defn(name="run_local_evaluation_activity")+ async def mock_run_local_evaluation(inputs: RunLocalEvaluationInputs) -> LocalEvaluationOutcome:+ return LocalEvaluationOutcome(+ evaluation={+ "id": inputs.evaluation_id,+ "name": "Boolean evaluation",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Is the answer grounded?"},+ "output_type": "boolean",+ "output_config": {},+ "team_id": 1,+ },+ result=None,+ emitted=False,+ )+original_patched = run_evaluation_module.temporalio.workflow.patched+ # The legacy run predates both patches, so its history records the separate+ # fetch/execute/emit activities and the per-evaluation signal child workflow.def legacy_patched(patch_id: str) -> bool:- if patch_id == "remove-per-evaluation-signal-2026-08":+ if patch_id in ("remove-per-evaluation-signal-2026-08", "merge-local-eval-activities-2026-09"):return Falsereturn original_patched(patch_id)@@ -202,6 +223,7 @@ class TestRunEvaluationWorkflow:mock_execute_llm_judge,mock_emit_evaluation_event,mock_emit_internal_telemetry,+ mock_run_local_evaluation,],workflow_runner=UnsandboxedWorkflowRunner(),):@@ -687,34 +709,31 @@ class TestRunEvaluationWorkflow:async def test_terminal_user_error_disables_emails_without_emitting_evaluation_event(self):calls: list[str] = []- @activity.defn(name="fetch_evaluation_activity")- async def mock_fetch_evaluation(inputs: RunEvaluationInputs) -> dict[str, Any]:- calls.append("fetch")- return {- "id": inputs.evaluation_id,- "name": "Hog eval",- "evaluation_type": "hog",- "evaluation_config": {},- "output_type": "boolean",- "output_config": {},- "team_id": 1,- }-- @activity.defn(name="execute_hog_eval_activity")- async def mock_execute_hog_eval(- evaluation: dict[str, Any], event_data: dict[str, Any]- ) -> EvaluationActivityResult:- calls.append("execute_hog")- return {- "result_type": "boolean",- "verdict": False,- "reasoning": "Must return boolean, got int: 42",- "allows_na": False,- "skipped": True,- "skip_reason": "hog_error",- "terminal_user_error": True,- "status_reason": "hog_error",- }+ @activity.defn(name="run_local_evaluation_activity")+ async def mock_run_local_evaluation(inputs: RunLocalEvaluationInputs) -> LocalEvaluationOutcome:+ calls.append("local_eval")+ return LocalEvaluationOutcome(+ evaluation={+ "id": inputs.evaluation_id,+ "name": "Hog eval",+ "evaluation_type": "hog",+ "evaluation_config": {},+ "output_type": "boolean",+ "output_config": {},+ "team_id": 1,+ },+ result={+ "result_type": "boolean",+ "verdict": False,+ "reasoning": "Must return boolean, got int: 42",+ "allows_na": False,+ "skipped": True,+ "skip_reason": "hog_error",+ "terminal_user_error": True,+ "status_reason": "hog_error",+ },+ emitted=False,+ )@activity.defn(name="disable_evaluation_activity")async def mock_disable_evaluation(@@ -740,8 +759,7 @@ class TestRunEvaluationWorkflow:task_queue=task_queue,workflows=[RunEvaluationWorkflow],activities=[- mock_fetch_evaluation,- mock_execute_hog_eval,+ mock_run_local_evaluation,mock_disable_evaluation,mock_send_evaluation_disabled_email,mock_emit_evaluation_event,@@ -759,8 +777,7 @@ class TestRunEvaluationWorkflow:)assert calls == [- "fetch",- "execute_hog",+ "local_eval",f"disable:{evaluation_id}:1:hog_error:Must return boolean, got int: 42",(f"email:{evaluation_id}:hog_error:"@@ -774,12 +791,77 @@ class TestRunEvaluationWorkflow:assert result["message"] == "Must return boolean, got int: 42"@pytest.mark.asyncio- async def test_terminal_user_error_does_not_email_when_evaluation_was_already_disabled(self):- calls: list[str] = []+ async def test_telemetry_failure_does_not_fail_an_emitted_judge_run(self):+ # The emit already happened; failing the workflow here would re-run it on a manual+ # retry and emit the evaluation a second time.+ emits: list[str] = []++ @activity.defn(name="run_local_evaluation_activity")+ async def mock_run_local_evaluation(inputs: RunLocalEvaluationInputs) -> LocalEvaluationOutcome:+ return LocalEvaluationOutcome(+ evaluation={+ "id": inputs.evaluation_id,+ "name": "Boolean evaluation",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Is the answer grounded?"},+ "output_type": "boolean",+ "output_config": {},+ "team_id": 1,+ },+ result=None,+ emitted=False,+ )++ @activity.defn(name="execute_llm_judge_activity")+ async def mock_execute_llm_judge(_: ExecuteLLMJudgeInputs) -> EvaluationActivityResult:+ return {+ "result_type": "boolean",+ "verdict": True,+ "reasoning": "ok",+ "allows_na": False,+ "model": "gpt-4.1-mini",+ "provider": "openai",+ }++ @activity.defn(name="emit_evaluation_event_activity")+ async def mock_emit_evaluation_event(_: EmitEvaluationEventInputs) -> None:+ emits.append("emit")++ @activity.defn(name="emit_internal_telemetry_activity")+ async def mock_emit_internal_telemetry(_: EmitInternalTelemetryInputs) -> None:+ raise ApplicationError("telemetry down", non_retryable=True)++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[RunEvaluationWorkflow],+ activities=[+ mock_run_local_evaluation,+ mock_execute_llm_judge,+ mock_emit_evaluation_event,+ mock_emit_internal_telemetry,+ ],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ result: WorkflowResult = await env.client.execute_workflow(+ RunEvaluationWorkflow.run,+ RunEvaluationInputs(+ evaluation_id=str(uuid.uuid4()),+ event_data=create_mock_event_data(team_id=1),+ ),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )+ assert result["verdict"] is True+ assert emits == ["emit"]++ @pytest.mark.asyncio+ async def test_pre_patch_hog_history_replays_against_new_code(self, monkeypatch):@activity.defn(name="fetch_evaluation_activity")async def mock_fetch_evaluation(inputs: RunEvaluationInputs) -> dict[str, Any]:- calls.append("fetch")return {"id": inputs.evaluation_id,"name": "Hog eval",@@ -794,18 +876,136 @@ class TestRunEvaluationWorkflow:async def mock_execute_hog_eval(evaluation: dict[str, Any], event_data: dict[str, Any]) -> EvaluationActivityResult:- calls.append("execute_hog")return {"result_type": "boolean",- "verdict": False,- "reasoning": "Must return boolean, got int: 42",+ "verdict": True,+ "reasoning": "","allows_na": False,- "skipped": True,- "skip_reason": "hog_error",- "terminal_user_error": True,- "status_reason": "hog_error",}+ @activity.defn(name="emit_evaluation_event_activity")+ async def mock_emit_evaluation_event(_: EmitEvaluationEventInputs) -> None:+ return++ original_patched = run_evaluation_module.temporalio.workflow.patched++ def pre_patch(patch_id: str) -> bool:+ if patch_id in ("remove-per-evaluation-signal-2026-08", "merge-local-eval-activities-2026-09"):+ return False+ return original_patched(patch_id)++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[RunEvaluationWorkflow],+ activities=[mock_fetch_evaluation, mock_execute_hog_eval, mock_emit_evaluation_event],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ monkeypatch.setattr(run_evaluation_module.temporalio.workflow, "patched", pre_patch)+ try:+ handle = await env.client.start_workflow(+ RunEvaluationWorkflow.run,+ RunEvaluationInputs(+ evaluation_id="pre-patch-hog-evaluation",+ event_data=create_mock_event_data(team_id=1),+ ),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )+ result: WorkflowResult = await handle.result()+ history = await handle.fetch_history()+ finally:+ monkeypatch.setattr(run_evaluation_module.temporalio.workflow, "patched", original_patched)++ assert result["verdict"] is True++ # A pre-patch hog run recorded fetch/execute/emit commands; the new code must replay them.+ await Replayer(+ workflows=[RunEvaluationWorkflow],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ).replay_workflow(history)++ @pytest.mark.asyncio+ async def test_merged_local_eval_result_is_not_emitted_again_by_the_workflow(self):+ @activity.defn(name="run_local_evaluation_activity")+ async def mock_run_local_evaluation(inputs: RunLocalEvaluationInputs) -> LocalEvaluationOutcome:+ return LocalEvaluationOutcome(+ evaluation={+ "id": inputs.evaluation_id,+ "name": "Hog eval",+ "evaluation_type": "hog",+ "evaluation_config": {},+ "output_type": "boolean",+ "output_config": {},+ "team_id": 1,+ },+ result={+ "result_type": "boolean",+ "verdict": True,+ "reasoning": "",+ "allows_na": False,+ },+ emitted=True,+ )++ @activity.defn(name="emit_evaluation_event_activity")+ async def mock_emit_evaluation_event(inputs: EmitEvaluationEventInputs) -> None:+ raise AssertionError("the merged activity already emitted; the workflow must not emit again")++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[RunEvaluationWorkflow],+ activities=[mock_run_local_evaluation, mock_emit_evaluation_event],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ result: WorkflowResult = await env.client.execute_workflow(+ RunEvaluationWorkflow.run,+ RunEvaluationInputs(+ evaluation_id=str(uuid.uuid4()),+ event_data=create_mock_event_data(team_id=1),+ ),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert result["verdict"] is True+ assert result["skipped"] is False++ @pytest.mark.asyncio+ async def test_terminal_user_error_does_not_email_when_evaluation_was_already_disabled(self):+ calls: list[str] = []++ @activity.defn(name="run_local_evaluation_activity")+ async def mock_run_local_evaluation(inputs: RunLocalEvaluationInputs) -> LocalEvaluationOutcome:+ calls.append("local_eval")+ return LocalEvaluationOutcome(+ evaluation={+ "id": inputs.evaluation_id,+ "name": "Hog eval",+ "evaluation_type": "hog",+ "evaluation_config": {},+ "output_type": "boolean",+ "output_config": {},+ "team_id": 1,+ },+ result={+ "result_type": "boolean",+ "verdict": False,+ "reasoning": "Must return boolean, got int: 42",+ "allows_na": False,+ "skipped": True,+ "skip_reason": "hog_error",+ "terminal_user_error": True,+ "status_reason": "hog_error",+ },+ emitted=False,+ )+@activity.defn(name="disable_evaluation_activity")async def mock_disable_evaluation(evaluation_id: str, team_id: int, reason: str, reason_detail: str | None = None@@ -826,8 +1026,7 @@ class TestRunEvaluationWorkflow:task_queue=task_queue,workflows=[RunEvaluationWorkflow],activities=[- mock_fetch_evaluation,- mock_execute_hog_eval,+ mock_run_local_evaluation,mock_disable_evaluation,mock_send_evaluation_disabled_email,],@@ -844,8 +1043,7 @@ class TestRunEvaluationWorkflow:)assert calls == [- "fetch",- "execute_hog",+ "local_eval",f"disable:{evaluation_id}:1:hog_error:Must return boolean, got int: 42",]assert result["evaluation_id"] == evaluation_id@@ -2322,3 +2520,160 @@ class TestJudgePromptAssembly:assert "Tools available:" not in user_promptassert "Input:" in user_promptassert "Output:" in user_prompt+++class TestRunLocalEvaluationActivity:+ # A fixed workflow start time: the activity only threads it through to the emitted event.+ START_TIME = datetime(2026, 1, 1, tzinfo=UTC)++ def _create_hog_evaluation(self, team, source: str):+ from posthog.cdp.validation import compile_hog++ return Evaluation.objects.create(+ team=team,+ name="Hog eval",+ evaluation_type="hog",+ evaluation_config={"source": source, "bytecode": compile_hog(source, "destination")},+ output_type="boolean",+ output_config={},+ enabled=True,+ )++ def _inputs(self, evaluation, team, start_time: datetime) -> RunLocalEvaluationInputs:+ return RunLocalEvaluationInputs(+ evaluation_id=str(evaluation.id),+ event_data=create_mock_event_data(team.id),+ start_time=start_time,+ )++ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_hog_eval_executes_and_emits_in_one_activity(self, setup_data):+ team = setup_data["team"]+ evaluation = await sync_to_async(self._create_hog_evaluation)(team, "return true")+ start_time = self.START_TIME++ with patch(+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ ) as mock_capture:+ outcome = await run_local_evaluation_activity(self._inputs(evaluation, team, start_time))++ assert outcome.evaluation["id"] == str(evaluation.id)+ assert outcome.result is not None+ assert outcome.result["verdict"] is True+ mock_capture.assert_called_once()+ capture_kwargs = mock_capture.call_args.kwargs+ assert capture_kwargs["event_name"] == "$ai_evaluation"+ assert capture_kwargs["properties"]["$ai_evaluation_result"] is True+ # A retried emit only deduplicates when the timestamp is stable across attempts.+ assert capture_kwargs["timestamp"] == start_time++ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_terminal_hog_error_returns_without_emitting(self, setup_data):+ team = setup_data["team"]+ evaluation = await sync_to_async(self._create_hog_evaluation)(team, "return 42")++ with patch(+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ ) as mock_capture:+ outcome = await run_local_evaluation_activity(self._inputs(evaluation, team, self.START_TIME))++ assert outcome.result is not None+ assert outcome.result["terminal_user_error"] is True+ assert outcome.result["skip_reason"] == "hog_error"+ mock_capture.assert_not_called()++ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_llm_judge_returns_fetch_only(self, setup_data):+ evaluation = setup_data["evaluation"]+ team = setup_data["team"]++ with patch(+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ ) as mock_capture:+ outcome = await run_local_evaluation_activity(self._inputs(evaluation, team, self.START_TIME))++ assert outcome.result is None+ assert outcome.evaluation["evaluation_type"] == "llm_judge"+ mock_capture.assert_not_called()++ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_sentiment_without_user_messages_emits_skipped_event(self, setup_data):+ team = setup_data["team"]++ def _create_sentiment_evaluation():+ return Evaluation.objects.create(+ team=team,+ name="Sentiment eval",+ evaluation_type="sentiment",+ evaluation_config={"source": "user_messages"},+ output_type="sentiment",+ output_config={},+ enabled=True,+ )++ evaluation = await sync_to_async(_create_sentiment_evaluation)()+ inputs = RunLocalEvaluationInputs(+ evaluation_id=str(evaluation.id),+ event_data=create_mock_event_data(+ team.id,+ properties={"$ai_input": [{"role": "assistant", "content": "no user turn"}]},+ ),+ start_time=self.START_TIME,+ )++ with patch(+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ ) as mock_capture:+ outcome = await run_local_evaluation_activity(inputs)++ assert outcome.result is not None+ assert outcome.result["skipped"] is True+ assert outcome.result["skip_reason"] == "no_user_messages"+ mock_capture.assert_called_once()+ assert mock_capture.call_args.kwargs["properties"]["$ai_evaluation_skipped"] is True++ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_emit_failure_raises_the_typed_error(self, setup_data):+ # The workflow keys its once-per-run alert counter on this type; an untyped raise+ # would silently drop hog/sentiment emit failures from llma_eval_errors.+ from posthog.temporal.ai_observability.evaluation_workflow_activities import (+ EMIT_EVALUATION_EVENT_FAILED_ERROR_TYPE,+ )++ team = setup_data["team"]+ evaluation = await sync_to_async(self._create_hog_evaluation)(team, "return true")++ with patch(+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ ) as mock_capture:+ mock_capture.side_effect = Exception("capture down")+ with pytest.raises(ApplicationError) as exc_info:+ await run_local_evaluation_activity(self._inputs(evaluation, team, self.START_TIME))++ assert exc_info.value.type == EMIT_EVALUATION_EVENT_FAILED_ERROR_TYPE++ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_emit_event_uuid_is_stable_across_activity_attempts(self, setup_data):+ from temporalio.testing import ActivityEnvironment++ team = setup_data["team"]+ evaluation = await sync_to_async(self._create_hog_evaluation)(team, "return true")+ inputs = self._inputs(evaluation, team, self.START_TIME)++ env = ActivityEnvironment()+ with patch(+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_for_team"+ ) as mock_capture:+ await env.run(run_local_evaluation_activity, inputs)+ await env.run(run_local_evaluation_activity, inputs)++ first_uuid = mock_capture.call_args_list[0].kwargs["event_uuid"]+ second_uuid = mock_capture.call_args_list[1].kwargs["event_uuid"]+ assert first_uuid is not None+ assert first_uuid == second_uuiddiff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex c1e6057fd35d..088572d62d92 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -240,6 +240,7 @@ class TestAIObservabilityModuleIntegrity:"compute_evaluation_cluster_aggregates_activity","emit_evaluation_cluster_events_activity","fetch_evaluation_activity",+ "run_local_evaluation_activity","disable_evaluation_activity","send_evaluation_disabled_email_activity","update_key_state_activity",