: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(llma): handle null hog eval comparisons (#66771)
Radu Raicea6dfc67615e72
diff --git a/common/hogvm/python/execute.py b/common/hogvm/python/execute.pyindex f0c1d582d7ab..87823efb2df8 100644--- a/common/hogvm/python/execute.py+++ b/common/hogvm/python/execute.py@@ -1,4 +1,5 @@import time+import operatorfrom collections.abc import Callablefrom copy import deepcopyfrom dataclasses import dataclass@@ -47,6 +48,13 @@ class BytecodeResult:stdout: list[str]+def _compare_values(left: Any, right: Any, comparison: Callable[[Any, Any], bool]) -> bool:+ try:+ return comparison(left, right)+ except TypeError as e:+ raise HogVMException(str(e)) from e++def execute_bytecode(input: list[Any] | dict,globals: Optional[dict[str, Any]] = None,@@ -253,16 +261,16 @@ def execute_bytecode(push_stack(var1 != var2)case Operation.GT:var1, var2 = unify_comparison_types(pop_stack(), pop_stack())- push_stack(var1 > var2)+ push_stack(_compare_values(var1, var2, operator.gt))case Operation.GT_EQ:var1, var2 = unify_comparison_types(pop_stack(), pop_stack())- push_stack(var1 >= var2)+ push_stack(_compare_values(var1, var2, operator.ge))case Operation.LT:var1, var2 = unify_comparison_types(pop_stack(), pop_stack())- push_stack(var1 < var2)+ push_stack(_compare_values(var1, var2, operator.lt))case Operation.LT_EQ:var1, var2 = unify_comparison_types(pop_stack(), pop_stack())- push_stack(var1 <= var2)+ push_stack(_compare_values(var1, var2, operator.le))case Operation.LIKE:push_stack(like(pop_stack(), pop_stack()))case Operation.ILIKE:diff --git a/common/hogvm/python/test/test_execute.py b/common/hogvm/python/test/test_execute.pyindex 8ac10fc70db9..1f37eeb2e0a1 100644--- a/common/hogvm/python/test/test_execute.py+++ b/common/hogvm/python/test/test_execute.py@@ -104,6 +104,10 @@ class TestBytecodeExecute:assert self._run("1 == null") is Falseassert self._run("1 != null") is True+ def test_ordering_comparison_type_error_raises_hogvm_exception(self):+ with pytest.raises(HogVMException, match="'<=' not supported between instances of 'NoneType' and 'float'"):+ self._run("properties.missing <= 1.0")+def test_nested_value(self):my_dict = {"properties": {diff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.pyindex 7dcf376782dc..681cf5a8ef67 100644--- a/posthog/cdp/validation.py+++ b/posthog/cdp/validation.py@@ -584,7 +584,12 @@ def topological_sort(nodes: list[str], edges: dict[str, list[str]]) -> list[str]return sorted_list-def compile_hog(hog: str, hog_type: str, in_repl: Optional[bool] = False) -> list[Any]:+def compile_hog(+ hog: str,+ hog_type: str,+ in_repl: Optional[bool] = False,+ null_safe_comparisons: bool = False,+) -> list[Any]:# Attempt to compile the hogtry:program = parse_program(hog)@@ -604,7 +609,12 @@ def compile_hog(hog: str, hog_type: str, in_repl: Optional[bool] = False) -> lis# Stated explicitly so a future refactor can't silently widen the surface.supported_functions = set()- return create_bytecode(program, supported_functions=supported_functions, in_repl=in_repl).bytecode+ return create_bytecode(+ program,+ supported_functions=supported_functions,+ in_repl=in_repl,+ null_safe_comparisons=null_safe_comparisons,+ ).bytecodeexcept serializers.ValidationError:raiseexcept Exception as e:diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 1c254b105e7a..29bca74d94d4 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -1424,6 +1424,31 @@ class TestExecuteHogEvalActivity:assert "TypeError" not in result["reasoning"]assert "NoneType" not in result["reasoning"]+ @pytest.mark.asyncio+ async def test_hog_eval_comparison_type_error_returns_skipped(self):+ from posthog.cdp.validation import compile_hog++ bytecode = compile_hog("return properties.missing <= 1.0", "destination")+ evaluation = {+ "id": "eval-id",+ "name": "Hog Eval",+ "evaluation_type": "hog",+ "evaluation_config": {"source": "return properties.missing <= 1.0", "bytecode": bytecode},+ "output_type": "boolean",+ "output_config": {},+ "team_id": 1,+ }++ result = await execute_hog_eval_activity(evaluation, create_mock_event_data(1))++ assert result["skipped"] is True+ assert result["skip_reason"] == "hog_error"+ assert result["terminal_user_error"] is True+ assert result["status_reason"] == "hog_error"+ assert result["verdict"] is False+ assert "Runtime error: '<=' not supported between instances of 'NoneType' and 'float'" in result["reasoning"]+ assert "Unexpected error during evaluation" not in result["reasoning"]+@pytest.mark.asyncioasync def test_hog_eval_unexpected_error_raises(self):from posthog.cdp.validation import compile_hogdiff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.pyindex 1395d197e764..0ec69c60f921 100644--- a/products/ai_observability/backend/api/evaluations.py+++ b/products/ai_observability/backend/api/evaluations.py@@ -26,6 +26,7 @@ from posthog.temporal.ai_observability.message_utils import extract_text_from_mefrom posthog.temporal.ai_observability.run_evaluation import extract_event_io, run_hog_evalfrom ..feature_flags import is_sentiment_evaluations_enabled+from ..hog import compile_ai_observability_hogfrom ..models.evaluation_config import EvaluationConfigfrom ..models.evaluation_configs import (EvaluationType,@@ -781,12 +782,11 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbifrom posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_query- from posthog.cdp.validation import compile_hogfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.models.team import Teamtry:- bytecode = compile_hog(source, "destination")+ bytecode = compile_ai_observability_hog(source, "destination")except serializers.ValidationError as e:return Response({"error": f"Compilation error: {e.detail}"}, status=400)except Exception:diff --git a/products/ai_observability/backend/api/taggers.py b/products/ai_observability/backend/api/taggers.pyindex 913da74edc0f..d9e6a19b995c 100644--- a/products/ai_observability/backend/api/taggers.py+++ b/products/ai_observability/backend/api/taggers.py@@ -23,7 +23,6 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.monitoring import Feature, monitorfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer-from posthog.cdp.validation import compile_hogfrom posthog.clickhouse.query_tagging import (Feature as QueryFeature,Product,@@ -36,6 +35,7 @@ from posthog.temporal.ai_observability.message_utils import extract_text_from_mefrom posthog.temporal.ai_observability.run_evaluation import extract_event_iofrom posthog.temporal.ai_observability.run_tagger import run_hog_tagger+from ..hog import compile_ai_observability_hogfrom ..models.model_configuration import LLMModelConfigurationfrom ..models.provider_keys import LLMProvider, LLMProviderKeyfrom ..models.taggers import Tagger, TaggerType, validate_tagger_config@@ -549,7 +549,7 @@ class TaggerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDestry:# Use "tagger" kind so we don't expose PRODUCT_ASYNC_FUNCTIONS (fetch, posthogCapture, …) —# taggers should only classify, never perform side effects.- bytecode = compile_hog(source, "tagger")+ bytecode = compile_ai_observability_hog(source, "tagger")except (ValueError, SyntaxError):logger.exception("Compilation error in Hog source")return Response({"error": "Invalid Hog source provided"}, status=400)diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.pyindex 37427b045a5f..752bcdd22660 100644--- a/products/ai_observability/backend/api/test/test_evaluations.py+++ b/products/ai_observability/backend/api/test/test_evaluations.py@@ -759,6 +759,21 @@ class TestTestHogEndpoint(APIBaseTest):self.assertIsNone(results[0]["result"])self.assertIn("Must return boolean", results[0]["error"])+ @patch("posthog.hogql.query.execute_hogql_query")+ def test_test_hog_uses_null_safe_comparisons(self, mock_query):+ mock_query.return_value = self._mock_hogql_response(1)++ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/test_hog/",+ {"source": "return properties.missing <= 1.0"},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ results = response.json()["results"]+ self.assertEqual(len(results), 1)+ self.assertFalse(results[0]["result"])+ self.assertIsNone(results[0]["error"])+class TestEnableBlockingWhenTrialExhausted(APIBaseTest):def _create_trial_eval(self, enabled=False):diff --git a/products/ai_observability/backend/hog.py b/products/ai_observability/backend/hog.pynew file mode 100644index 000000000000..a565a334c7b3--- /dev/null+++ b/products/ai_observability/backend/hog.py@@ -0,0 +1,9 @@+from typing import Any, Literal++from posthog.cdp.validation import compile_hog++AIObservabilityHogType = Literal["destination", "tagger"]+++def compile_ai_observability_hog(source: str, hog_type: AIObservabilityHogType) -> list[Any]:+ return compile_hog(source, hog_type, null_safe_comparisons=True)diff --git a/products/ai_observability/backend/models/evaluations.py b/products/ai_observability/backend/models/evaluations.pyindex b3148a3ce44d..141993c979ce 100644--- a/products/ai_observability/backend/models/evaluations.py+++ b/products/ai_observability/backend/models/evaluations.py@@ -170,7 +170,8 @@ class Evaluation(ModelActivityMixin, UUIDTModel):def save(self, *args, **kwargs):from posthog.cdp.filters import compile_filters_bytecode- from posthog.cdp.validation import compile_hog++ from ..hog import compile_ai_observability_hog # noqa: PLC0415 - keeps Hog compiler off model import path# Coerce status and enabled into a consistent pair. status is authoritative, but we accept writes to# either field — typically `enabled` from user PATCHes, `status` from system transitions.@@ -198,7 +199,7 @@ class Evaluation(ModelActivityMixin, UUIDTModel):# Compile Hog source to bytecodeif self.evaluation_type == EvaluationType.HOG and self.evaluation_config.get("source"):try:- bytecode = compile_hog(self.evaluation_config["source"], "destination")+ bytecode = compile_ai_observability_hog(self.evaluation_config["source"], "destination")self.evaluation_config["bytecode"] = bytecodeexcept Exception as e:raise ValidationError({"evaluation_config": f"Failed to compile Hog code: {e}"})diff --git a/products/ai_observability/backend/models/taggers.py b/products/ai_observability/backend/models/taggers.pyindex dc7b6d063148..23c1764af0a8 100644--- a/products/ai_observability/backend/models/taggers.py+++ b/products/ai_observability/backend/models/taggers.py@@ -148,7 +148,8 @@ class Tagger(UUIDTModel):def save(self, *args, **kwargs):from posthog.cdp.filters import compile_filters_bytecode- from posthog.cdp.validation import compile_hog++ from ..hog import compile_ai_observability_hog # noqa: PLC0415 - keeps Hog compiler off model import path# Validate tagger config based on typeif self.tagger_config:@@ -162,7 +163,7 @@ class Tagger(UUIDTModel):try:# Use "tagger" kind so we don't expose PRODUCT_ASYNC_FUNCTIONS (fetch, posthogCapture, …) —# taggers should only classify, never perform side effects.- bytecode = compile_hog(self.tagger_config["source"], "tagger")+ bytecode = compile_ai_observability_hog(self.tagger_config["source"], "tagger")self.tagger_config["bytecode"] = bytecodeexcept Exception as e:raise ValidationError({"tagger_config": f"Failed to compile Hog code: {e}"})diff --git a/products/ai_observability/backend/models/test/test_evaluations.py b/products/ai_observability/backend/models/test/test_evaluations.pyindex 628d1ab04e33..a534f40cd2ab 100644--- a/products/ai_observability/backend/models/test/test_evaluations.py+++ b/products/ai_observability/backend/models/test/test_evaluations.py@@ -200,6 +200,34 @@ class TestEvaluationModel(BaseTest):self.assertIsInstance(evaluation.evaluation_config["bytecode"], list)self.assertTrue(len(evaluation.evaluation_config["bytecode"]) > 0)+ def test_hog_evaluation_compiles_null_safe_comparisons(self):+ from posthog.temporal.ai_observability.run_evaluation import run_hog_eval++ evaluation = Evaluation.objects.create(+ team=self.team,+ name="Hog Eval",+ evaluation_type="hog",+ evaluation_config={"source": "return properties.missing <= 1.0"},+ output_type="boolean",+ output_config={},+ enabled=True,+ created_by=self.user,+ conditions=[{"id": "cond-1", "rollout_percentage": 100, "properties": []}],+ )++ result = run_hog_eval(+ evaluation.evaluation_config["bytecode"],+ {+ "uuid": "event-id",+ "event": "$ai_generation",+ "properties": {},+ "distinct_id": "user-1",+ },+ )++ self.assertFalse(result["verdict"])+ self.assertIsNone(result["error"])+def test_hog_evaluation_invalid_source_raises_validation_error(self):with self.assertRaises(ValidationError):Evaluation.objects.create(diff --git a/products/ai_observability/backend/models/test/test_taggers.py b/products/ai_observability/backend/models/test/test_taggers.pyindex fc611b4ad956..3092bae7aba8 100644--- a/products/ai_observability/backend/models/test/test_taggers.py+++ b/products/ai_observability/backend/models/test/test_taggers.py@@ -3,6 +3,9 @@ from unittest.mock import patchfrom django.core.exceptions import ValidationError+from posthog.models.utils import UUIDTModel+from posthog.temporal.ai_observability.run_tagger import run_hog_tagger+from products.ai_observability.backend.models.taggers import LLMTaggerConfig, TagDefinition, Tagger@@ -80,6 +83,38 @@ class TestLLMTaggerConfig(BaseTest):assert config.max_tags is None+class TestHogTaggerCompilation:+ def test_hog_tagger_compiles_null_safe_comparisons(self):+ tagger = Tagger(+ team_id=1,+ name="Hog Tagger",+ tagger_type="hog",+ tagger_config={+ "source": "if (properties.missing <= 1.0) { return ['billing'] } return []",+ "tags": [{"name": "billing"}],+ },+ enabled=True,+ conditions=[],+ )++ with patch.object(UUIDTModel, "save", return_value=None):+ tagger.save()++ result = run_hog_tagger(+ tagger.tagger_config["bytecode"],+ {+ "uuid": "event-id",+ "event": "$ai_generation",+ "properties": {},+ "distinct_id": "user-1",+ },+ valid_tag_names={"billing"},+ )++ assert result["tags"] == []+ assert result["error"] is None++class TestTaggerModel(BaseTest):def _make_tagger_config(self, **overrides):defaults = {diff --git a/products/ai_observability/backend/tools/run_hog_eval.py b/products/ai_observability/backend/tools/run_hog_eval.pyindex fa05a934f464..1585e35351b3 100644--- a/products/ai_observability/backend/tools/run_hog_eval.py+++ b/products/ai_observability/backend/tools/run_hog_eval.py@@ -10,6 +10,8 @@ from posthog.hogql_queries.ai.ai_table_resolver import query_ai_eventsfrom posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, merge_heavy_propertiesfrom posthog.sync import database_sync_to_async+from products.ai_observability.backend.hog import compile_ai_observability_hog+from ee.hogai.tool import MaxToolTOOL_DESCRIPTION = """Test Hog evaluation code against sample events from the last 7 days.@@ -46,12 +48,11 @@ class RunHogEvalTestTool(MaxTool):return [("llm_analytics", "viewer")]async def _arun_impl(self, source: str, sample_count: int = 3) -> tuple[str, Any]:- from posthog.cdp.validation import compile_hogfrom posthog.temporal.ai_observability.message_utils import extract_text_from_messagesfrom posthog.temporal.ai_observability.run_evaluation import run_hog_evaltry:- bytecode = compile_hog(source, "destination")+ bytecode = compile_ai_observability_hog(source, "destination")except Exception as e:return (f"Compilation error: {e}", None)