: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
fix(aio): skip hog evals on unreadable event data instead of failing (#80335)
Carlos Marchalf9ee08bcff6d
diff --git a/posthog/temporal/ai_observability/evaluation_errors.py b/posthog/temporal/ai_observability/evaluation_errors.pyindex 807107ac579d..7b910ab02939 100644--- a/posthog/temporal/ai_observability/evaluation_errors.py+++ b/posthog/temporal/ai_observability/evaluation_errors.py@@ -1,8 +1,9 @@"""Shared taxonomy for evaluation execution errors.-The split between user-actionable and PostHog-owned errors is load-bearing:-user errors disable the evaluation without failing the Temporal activity, while-PostHog-owned errors still raise so Temporal/Grafana stays useful.+The split between user-actionable and PostHog-owned errors is load-bearing: most user errors+disable the evaluation without failing the Temporal activity, while PostHog-owned errors still+raise so Temporal/Grafana stays useful. `hog_input_error` is the one user error that disables+nothing — it describes a single unit, not the evaluation."""from dataclasses import dataclass@@ -104,6 +105,16 @@ USER_ERROR_SPECS: dict[str, EvaluationErrorSpec] = {status_reason=EvaluationStatusReason.HOG_ERROR,disables_evaluation=True,),+ # The one user-actionable spec that neither disables the evaluation nor sets a status reason:+ # a single unit carried data the Hog source could not handle, which says nothing about whether+ # the evaluation works on the next one. What keeps the workflow off `disable_evaluation_activity`+ # is the result omitting `terminal_user_error` (see `is_terminal_user_error_result`); the unset+ # `status_reason` is a second guard behind that.+ "hog_input_error": EvaluationErrorSpec(+ error_type="hog_input_error",+ owner="user",+ safe_message="The evaluation code could not handle the data for this run, so it was skipped.",+ ),}@@ -222,14 +233,20 @@ def terminal_user_error_result_from_application_error()-def status_reason_detail_for_terminal_user_error(spec: EvaluationErrorSpec, message: str | None) -> str | None:- if spec.error_type != "hog_error" or not message:+def truncate_error_detail(message: str | None) -> str | None:+ """Bound a raw execution error before it reaches a status reason or a user-visible result."""+ if not message:return None-if len(message) <= MAX_STATUS_REASON_DETAIL_LENGTH:return messagereturn f"{message[: MAX_STATUS_REASON_DETAIL_LENGTH - 3]}..."+def status_reason_detail_for_terminal_user_error(spec: EvaluationErrorSpec, message: str | None) -> str | None:+ if spec.error_type != "hog_error":+ return None+ return truncate_error_detail(message)++def is_terminal_user_error_result(result: EvaluationActivityResult) -> bool:return result.get("terminal_user_error") is Truediff --git a/posthog/temporal/ai_observability/evaluation_hog.py b/posthog/temporal/ai_observability/evaluation_hog.pyindex 78eeb5acb5ba..38c94a8fa2fb 100644--- a/posthog/temporal/ai_observability/evaluation_hog.py+++ b/posthog/temporal/ai_observability/evaluation_hog.py@@ -11,10 +11,12 @@ from posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.evaluation_errors import (require_user_error_spec,status_reason_detail_for_terminal_user_error,+ truncate_error_detail,)from posthog.temporal.ai_observability.evaluation_event_io import extract_event_iofrom posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResultfrom posthog.temporal.ai_observability.message_utils import extract_text_from_messages+from posthog.temporal.ai_observability.metrics import increment_user_errorsfrom common.hogvm.python.execute import execute_bytecodefrom common.hogvm.python.operation import Operation@@ -22,6 +24,30 @@ from common.hogvm.python.utils import HogVMException, HogVMMemoryExceededExceptilogger = structlog.get_logger(__name__)+# Python-level errors the Hog standard library raises when a unit's data is not the shape the+# evaluation source assumed: `ilike` against a list rather than a string, `jsonParse` on truncated+# model output, a divide by a token count that arrived as zero. The evaluation is not broken and+# neither are we, so these skip the one unit instead of paging us or disabling the evaluation.+#+# Classifying by Python type cannot separate a bad value from a source that always fails the same+# way, so a source hardcoded to raise one of these (`length(5)`) still skips every unit. Closing+# that needs an every-unit-skipped signal, not a narrower list. Two exclusions we can make here:+#+# - `ValueError` at large, with `json.JSONDecodeError` (a subclass) listed instead: our own code+# raises plain ValueError, and skipping on that would hide real bugs.+# - `IndexError`, which no user data reaches: Hog indexing is bounds-safe (`get_nested_value`+# returns null past the end of an array). What does raise it is an STL call compiled with the+# wrong arity, which nothing validates at save time, so a source like `jsonParse()` reaches the+# VM and fails on every unit. Listing it here would skip that source silently and forever, and+# blame the customer's data for it; left out, it stays loud.+HOG_INPUT_ERROR_TYPES: tuple[type[Exception], ...] = (+ TypeError,+ AttributeError,+ KeyError,+ ZeroDivisionError,+ json.JSONDecodeError,+)+def coerce_hog_io_value(value: Any) -> str:"""Coerce an extracted input/output value into a string for Hog globals.@@ -123,8 +149,9 @@ def execute_hog_eval_bytecode(bytecode: list, globals_dict: dict[str, Any], alloShared by the single-event and trace-level Hog activities — only the globals differ.Returns {"verdict": bool | None, "reasoning": str, "error": str | None}, plus "applicable"- when allows_na and a `return null` is treated as N/A, and "unexpected": True when the failure- was a bug in our code rather than in the user's Hog source.+ when allows_na and a `return null` is treated as N/A, "user_input_error": True when this unit's+ data defeated the user's Hog source, and "unexpected": True when the failure was a bug in our+ code rather than in the user's Hog source or its input."""try:response = execute_bytecode(@@ -139,6 +166,13 @@ def execute_hog_eval_bytecode(bytecode: list, globals_dict: dict[str, Any], alloreturn {"verdict": None, "reasoning": "", "error": "Memory limit exceeded"}except HogVMException as e:return {"verdict": None, "reasoning": "", "error": f"Runtime error: {e}"}+ except HOG_INPUT_ERROR_TYPES as e:+ return {+ "verdict": None,+ "reasoning": "",+ "error": f"{type(e).__name__}: {e}",+ "user_input_error": True,+ }except Exception as e:logger.exception("Unexpected error executing Hog eval bytecode")return {@@ -167,24 +201,59 @@ def execute_hog_eval_bytecode(bytecode: list, globals_dict: dict[str, Any], alloreturn result-def finalize_hog_eval_result(result: dict[str, Any], *, allows_na: bool, unit_label: str) -> EvaluationActivityResult:+def finalize_hog_eval_result(+ result: dict[str, Any], *, evaluation: dict[str, Any], allows_na: bool, unit_label: str | None+) -> EvaluationActivityResult:"""Turn raw Hog bytecode output into an activity result.- Shared by the trace and session Hog activities: this is the block that decides whether a- failure is our bug or the customer's, and a drifted copy would mean a broken evaluation- silently retrying against every unit instead of disabling itself. `unit_label`- ("trace" / "session") reaches only the raised our-bug message, so whoever triages the page- can tell which target produced it.+ Shared by the generation, trace, and session Hog activities: this is the block that decides+ whether a failure is our bug, this unit's data, or a broken evaluation, and a drifted copy+ would mean a broken evaluation silently retrying against every unit instead of disabling+ itself. `unit_label` ("trace" / "session") reaches only the raised our-bug message, so whoever+ triages the page can tell which target produced it; the generation path passes None to keep its+ message, and so the error tracking issue it groups into, unchanged."""if result["error"]:if result.get("unexpected"):# A genuine bug in our evaluation code (not the user's Hog). Raise so the Temporal# interceptor reports it to error tracking and we get paged to investigate.+ qualifier = f" ({unit_label})" if unit_label else ""raise ApplicationError(- f"Hog evaluation error ({unit_label}): {result['error']}",+ f"Hog evaluation error{qualifier}: {result['error']}",non_retryable=True,)+ if result.get("user_input_error"):+ # This unit's data was not the shape the Hog source expected. Deliberately not marked+ # terminal: the same evaluation usually reads the next unit fine, so disabling it over+ # one malformed payload would cost the user every later result. Skipping keeps the+ # evaluation running and leaves the run visible as skipped rather than failed.+ input_error_spec = require_user_error_spec("hog_input_error")+ increment_user_errors(input_error_spec.error_type)+ # This path raises nothing and emails nobody, and the counter can't carry ids at this+ # cardinality, so without these fields there is no way to find the offending evaluation.+ logger.warning(+ "Hog eval could not handle unit data",+ team_id=evaluation.get("team_id"),+ evaluation_id=evaluation.get("id"),+ unit=unit_label or "generation",+ error=result["error"],+ )+ detail = truncate_error_detail(result["error"])+ skipped_result: EvaluationActivityResult = {+ "result_type": "boolean",+ "verdict": None if allows_na else False,+ # Leads with the safe message: `detail` is a Python exception repr, which is not a+ # Hog concept, and `reasoning` is the only text the run shows the user.+ "reasoning": f"{input_error_spec.safe_message} ({detail})" if detail else input_error_spec.safe_message,+ "allows_na": allows_na,+ "skipped": True,+ "skip_reason": input_error_spec.error_type,+ }+ if allows_na:+ skipped_result["applicable"] = False+ return skipped_result+# The user's Hog source itself errored — an expected outcome of running customer-authored# code, recorded as a skipped evaluation rather than raised (which would flood error# tracking with one event per unit). Marked terminal so the workflow disables the broken@@ -222,8 +291,10 @@ def run_hog_eval(bytecode: list, event_data: dict[str, Any], allows_na: bool = FUsed by both the Temporal activity and the test endpoint.Returns {"verdict": bool | None, "reasoning": str, "error": str | None}.When allows_na=True, a `return null` is treated as N/A (not an error).- Sets "unexpected": True only when the bytecode raised something other than a- HogVM error — i.e. a bug in our code rather than in the user's Hog source.+ Sets "user_input_error": True when this event's data defeated the user's Hog source, and+ "unexpected": True only when the bytecode raised something other than a HogVM error or one of+ `HOG_INPUT_ERROR_TYPES` — i.e. a bug in our code rather than in the user's Hog source or its+ input."""properties = event_data["properties"]if isinstance(properties, str):@@ -285,42 +356,4 @@ async def execute_hog_eval_activity(evaluation: dict[str, Any], event_data: dictresult = await database_sync_to_async(_execute, thread_sensitive=False)()- if result["error"]:- if result.get("unexpected"):- # A genuine bug in our evaluation code (not the user's Hog). Raise so the Temporal- # interceptor reports it to error tracking and we get paged to investigate.- raise ApplicationError(- f"Hog evaluation error: {result['error']}",- non_retryable=True,- )-- # The user's Hog source itself errored (invalid code, execution timeout, or a- # non-boolean result). That's an expected outcome of running customer-authored code,- # not a system fault — record it as a skipped evaluation the user can see, rather than- # raising (which would flood error tracking with one event per matching generation).- spec = require_user_error_spec("hog_error")- error_detail = status_reason_detail_for_terminal_user_error(spec, result["error"]) or spec.safe_message- errored_result: EvaluationActivityResult = {- "result_type": "boolean",- "verdict": None if allows_na else False,- "reasoning": error_detail,- "allows_na": allows_na,- "skipped": True,- "skip_reason": "hog_error",- "terminal_user_error": True,- "status_reason": spec.status_reason,- }- if allows_na:- errored_result["applicable"] = False- return errored_result-- activity_result: EvaluationActivityResult = {- "result_type": "boolean",- "verdict": result["verdict"],- "reasoning": result["reasoning"],- "allows_na": allows_na,- }- if allows_na:- activity_result["applicable"] = result.get("applicable", True)-- return activity_result+ return finalize_hog_eval_result(result, evaluation=evaluation, allows_na=allows_na, unit_label=None)diff --git a/posthog/temporal/ai_observability/metrics.py b/posthog/temporal/ai_observability/metrics.pyindex 960a6c074af9..33156530113e 100644--- a/posthog/temporal/ai_observability/metrics.py+++ b/posthog/temporal/ai_observability/metrics.py@@ -93,7 +93,12 @@ def increment_errors(error_type: str, *, provider: str | None = None) -> None:def increment_user_errors(error_type: str, *, provider: str | None = None) -> None:- """Track terminal user-actionable eval errors separately from system failures."""+ """Track user-actionable eval errors separately from system failures.++ Filter on `error_type` rather than alerting on this counter's total: most values are terminal+ errors that disable the evaluation and so stay rare, but `hog_input_error` is per-unit and can+ outnumber them by orders of magnitude without anything being broken.+ """if not activity.in_activity() and not workflow.in_workflow():returnattrs: dict[str, str | int | float | bool] = {"error_type": error_type}diff --git a/posthog/temporal/ai_observability/run_session_evaluation.py b/posthog/temporal/ai_observability/run_session_evaluation.pyindex 734faa8e6ae4..9f9ed9b7c1e8 100644--- a/posthog/temporal/ai_observability/run_session_evaluation.py+++ b/posthog/temporal/ai_observability/run_session_evaluation.py@@ -481,7 +481,7 @@ async def execute_session_hog_eval_activity(inputs: ExecuteSessionEvaluationInpuif skip_reason or result is None:return build_session_skip_result(allows_na, skip_reason or "session_not_found")- return finalize_hog_eval_result(result, allows_na=allows_na, unit_label="session")+ return finalize_hog_eval_result(result, evaluation=evaluation, allows_na=allows_na, unit_label="session")@dataclassdiff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.pyindex c9abfbeca37d..4756983df2d9 100644--- a/posthog/temporal/ai_observability/run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py@@ -585,7 +585,7 @@ async def execute_trace_hog_eval_activity(inputs: ExecuteTraceEvaluationInputs)if skip_reason or result is None:return _build_trace_skip_result(allows_na, skip_reason or "trace_not_found")- return finalize_hog_eval_result(result, allows_na=allows_na, unit_label="trace")+ return finalize_hog_eval_result(result, evaluation=evaluation, allows_na=allows_na, unit_label="trace")@dataclassdiff --git a/posthog/temporal/ai_observability/test_evaluation_hog.py b/posthog/temporal/ai_observability/test_evaluation_hog.pynew file mode 100644index 000000000000..e0c621d8e2cb--- /dev/null+++ b/posthog/temporal/ai_observability/test_evaluation_hog.py@@ -0,0 +1,127 @@+import json++import pytest++from parameterized import parameterized+from temporalio.exceptions import ApplicationError++from posthog.temporal.ai_observability.evaluation_errors import is_terminal_user_error_result+from posthog.temporal.ai_observability.evaluation_hog import execute_hog_eval_bytecode, finalize_hog_eval_result++from products.ai_observability.backend.hog import compile_ai_observability_hog++# The failure shape these tests exercise: an operator applied to a property the source assumes is a+# string, against an event where the same property arrived as some other type.+ILIKE_SOURCE = """+if (properties['$ai_output'] ilike '%truncated%') {+ return false+}+return true+"""++JSON_PARSE_SOURCE = """+return jsonParse(properties['$ai_output']) == null+"""++NON_BOOLEAN_SOURCE = """+return 42+"""++# Nothing validates builtin arity at save time, so this compiles and raises IndexError in the STL.+MISSING_ARGUMENT_SOURCE = """+return jsonParse()+"""++EVALUATION = {"id": "01890000-0000-0000-0000-000000000000", "team_id": 1}+++def run_source(source: str, property_value: object = "", *, allows_na: bool = True) -> dict:+ bytecode = compile_ai_observability_hog(source, "destination")+ return execute_hog_eval_bytecode(bytecode, {"properties": {"$ai_output": property_value}}, allows_na=allows_na)+++class TestHogInputErrorClassification:+ @parameterized.expand(+ [+ ("list_against_ilike", ILIKE_SOURCE, ["stop"]),+ ("dict_against_ilike", ILIKE_SOURCE, {"reason": "stop"}),+ ("int_against_ilike", ILIKE_SOURCE, 7),+ ("truncated_json_against_json_parse", JSON_PARSE_SOURCE, '{"ok": tr'),+ ]+ )+ def test_unsupported_property_type_is_an_input_error(self, _name: str, source: str, property_value: object) -> None:+ result = run_source(source, property_value)++ assert result["user_input_error"] is True+ assert "unexpected" not in result++ def test_supported_property_type_still_evaluates(self) -> None:+ result = run_source(ILIKE_SOURCE, json.dumps(["truncated"]))++ assert result["error"] is None+ assert result["verdict"] is False++ # The exclusions from HOG_INPUT_ERROR_TYPES are invisible otherwise: widening the tuple back to+ # Exception leaves every case above classifying identically, so only a case that must NOT be an+ # input error can catch it. A source that fails on every unit has to stay loud, or it skips+ # forever while blaming the customer's data.+ def test_source_that_can_never_run_stays_our_bug(self) -> None:+ result = run_source(MISSING_ARGUMENT_SOURCE)++ assert result["unexpected"] is True+ assert "user_input_error" not in result+++class TestFinalizeHogEvalResult:+ @parameterized.expand([("allows_na", True, None), ("disallows_na", False, False)])+ def test_input_error_skips_the_unit_without_disabling_the_evaluation(+ self, _name: str, allows_na: bool, expected_verdict: bool | None+ ) -> None:+ result = finalize_hog_eval_result(+ run_source(ILIKE_SOURCE, ["stop"], allows_na=allows_na),+ evaluation=EVALUATION,+ allows_na=allows_na,+ unit_label=None,+ )++ assert result["skipped"] is True+ assert result["skip_reason"] == "hog_input_error"+ assert result["verdict"] == expected_verdict+ # Both absent is what keeps the workflow from calling disable_evaluation_activity, so the+ # evaluation survives one unreadable unit and keeps scoring later ones.+ assert is_terminal_user_error_result(result) is False+ assert "status_reason" not in result++ def test_input_error_reasoning_leads_with_the_readable_message(self) -> None:+ result = finalize_hog_eval_result(+ run_source(ILIKE_SOURCE, ["stop"]),+ evaluation=EVALUATION,+ allows_na=True,+ unit_label=None,+ )++ # `reasoning` is the only text the run shows the user, and a bare Python exception repr is+ # not a Hog concept, so the readable sentence has to come first.+ assert result["reasoning"].startswith("The evaluation code could not handle the data for this run")+ assert "TypeError" in result["reasoning"]++ def test_broken_hog_source_still_disables_the_evaluation(self) -> None:+ result = finalize_hog_eval_result(+ run_source(NON_BOOLEAN_SOURCE, allows_na=False),+ evaluation=EVALUATION,+ allows_na=False,+ unit_label=None,+ )++ assert result["skip_reason"] == "hog_error"+ assert is_terminal_user_error_result(result) is True++ @parameterized.expand([("generation", None, r"Hog evaluation error:"), ("trace", "trace", r"error \(trace\):")])+ def test_our_own_bug_still_raises(self, _name: str, unit_label: str | None, expected: str) -> None:+ with pytest.raises(ApplicationError, match=expected):+ finalize_hog_eval_result(+ {"verdict": None, "reasoning": "", "error": "RuntimeError: boom", "unexpected": True},+ evaluation=EVALUATION,+ allows_na=False,+ unit_label=unit_label,+ )