: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(data-modeling): run jev calls inside materializations (#111722)
Jovan Sakovica8918ac556e4
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex 7edb62c91be8..709e12cd07c9 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -59,7 +59,7 @@ from posthog.hogql.parser import parse_select, sanitize_client_parser_modefrom posthog.hogql.placeholders import find_placeholders, replace_placeholdersfrom posthog.hogql.printer import prepare_ast_for_printing, print_prepared_astfrom posthog.hogql.printer.access_control import build_access_control_warning-from posthog.hogql.resolver import Resolver+from posthog.hogql.resolver import Resolver, ResolverFactory, resolve_typesfrom posthog.hogql.resolver_utils import extract_base_table_types, extract_lazy_table_types, extract_select_queriesfrom posthog.hogql.timings import HogQLTimingsfrom posthog.hogql.transforms.preaggregated_table_transformation import do_preaggregated_table_transforms@@ -136,6 +136,7 @@ class HogQLQueryExecutor:user: Optional[User] = Nonebypass_warehouse_access_control: bool = Falseuser_access_control: Optional[UserAccessControl] = None+ resolver_factory: Optional[ResolverFactory] = None__uninitialized_context: ClassVar[HogQLContext] = HogQLContext()@@ -746,8 +747,9 @@ class HogQLQueryExecutor:validate_prompt_jev_access(self.team)PromptJevBudget().visit(self.select_query)# The resolver types jev calls without model output, so an invalid query fails before any model call.- Resolver(- context=dataclasses.replace(+ resolve_types(+ clone_expr(self.select_query, True),+ dataclasses.replace(self.context,team_id=self.team.pk,team=self.team,@@ -768,8 +770,9 @@ class HogQLQueryExecutor:notices=[],errors=[],),- dialect="clickhouse",- ).visit(clone_expr(self.select_query, True))+ "clickhouse",+ resolver_factory=self.resolver_factory,+ )self._prompt_jev_tables = []runner = PromptJevRunner(team_id=self.team.pk, distinct_id=self.user.distinct_id if self.user else None)@@ -795,6 +798,18 @@ class HogQLQueryExecutor:if PromptJevFinder.contains(self.select_query):raise QueryError("Use jev in a named SELECT column and filter its results in an outer query.")+ def plan_prompt_jev(self) -> "tuple[ast.SelectQuery | ast.SelectSetQuery, list[PromptJevTable]]":+ """Run every jev call in the query and return the query rewritten to read the results.++ For callers that print and run the query themselves, such as a materialization. They must+ register the returned tables on their context and send them with the query.+ """+ self._parse_query()+ self._process_variables()+ self._process_placeholders()+ self._evaluate_prompt_jev()+ return self.select_query, self._prompt_jev_tables+def _prepare_execution(self, *, embedded_select: bool = False) -> _PreparedExecution:self.context.referenced_saved_query_ids.clear()self._parse_query()diff --git a/posthog/temporal/common/clickhouse.py b/posthog/temporal/common/clickhouse.pyindex 1654309d0e1b..7f9e515bfde2 100644--- a/posthog/temporal/common/clickhouse.py+++ b/posthog/temporal/common/clickhouse.py@@ -20,12 +20,17 @@ import pyarrow as pafrom structlog import get_loggerfrom temporalio import activity+from posthog.hogql.escape_sql import backquote_clickhouse_identifier+import posthog.temporal.common.asyncpa as asyncpafrom posthog.clickhouse import query_taggingfrom posthog.clickhouse.client.connection import MAX_QUERY_SIZE_BYTES, ClickHouseCredentialsfrom posthog.clickhouse.query_tagging import QueryTags, TemporalTags, get_query_tagsfrom posthog.security.outbound_proxy import internal_requests_session+if typing.TYPE_CHECKING:+ from posthog.clickhouse.client.execute import ClickHouseExternalTable+LOGGER = get_logger(__name__)@@ -94,6 +99,42 @@ def encode_clickhouse_data(data: typing.Any, quote_char="'") -> bytes:return f"{quote_char}{str_data}{quote_char}".encode()+def _encode_external_value(value: typing.Any) -> typing.Any:+ # Epoch strings parse into DateTime and DateTime64 columns in any timezone; a formatted+ # datetime would be read in the column's timezone instead of the value's.+ if isinstance(value, dt.datetime):+ if value.tzinfo is None:+ value = value.replace(tzinfo=dt.UTC)+ return f"{value.timestamp():.6f}"+ if isinstance(value, dt.date):+ return value.isoformat()+ return str(value)+++def _external_tables_form(+ query: str, external_tables: collections.abc.Sequence["ClickHouseExternalTable"]+) -> aiohttp.FormData:+ """Build the multipart body that carries query-scoped tables over the HTTP interface.++ The query goes in the form rather than the URL, so its length is not bound by URL limits.+ """+ form = aiohttp.FormData()+ form.add_field("query", query)+ for table in external_tables:+ name = table["name"]+ form.add_field(+ f"{name}_structure",+ ", ".join(+ f"{backquote_clickhouse_identifier(column)} {clickhouse_type}"+ for column, clickhouse_type in table["structure"]+ ),+ )+ form.add_field(f"{name}_format", "JSONEachRow")+ rows = b"\n".join(json.dumps(row, default=_encode_external_value).encode() for row in table["data"])+ form.add_field(name, rows, filename=name, content_type="application/octet-stream")+ return form++class ClickHouseQueryStatus(enum.StrEnum):FINISHED = "Finished"RUNNING = "Running"@@ -483,6 +524,7 @@ class ClickHouseClient:query_id,timeout: float | None = None,settings: dict[str, str] | None = None,+ external_tables: collections.abc.Sequence["ClickHouseExternalTable"] | None = None,) -> collections.abc.AsyncIterator[aiohttp.ClientResponse]:"""POST a query to the ClickHouse HTTP interface.@@ -497,14 +539,20 @@ class ClickHouseClient:query_parameters: Parameters to be formatted in the query.query_id: A query ID to pass to ClickHouse.settings: Extra ClickHouse HTTP-interface settings to include as query-string parameters.+ external_tables: Query-scoped tables the query reads, sent in the request body.Returns:The response received from the ClickHouse HTTP interface."""if self.session is None:raise ClickHouseClientNotConnected()+ if external_tables and data:+ raise ValueError("A query cannot send both external tables and request data.")params = {**self.params}+ if external_tables:+ # Named tuples, such as a jev choice, are encoded as JSON arrays.+ params["input_format_json_named_tuples_as_objects"] = "0"if settings is not None:params.update(settings)if query_id is not None:@@ -528,12 +576,15 @@ class ClickHouseClient:params[f"param_{key}"] = str(value)add_log_comment_param(params)- request_data = self.prepare_request_data(data)-- if request_data:- params["query"] = query+ request_data: bytes | aiohttp.FormData | None+ if external_tables:+ request_data = _external_tables_form(query, external_tables)else:- request_data = query.encode("utf-8")+ request_data = self.prepare_request_data(data)+ if request_data:+ params["query"] = query+ else:+ request_data = query.encode("utf-8")if timeout:client_timeout = aiohttp.ClientTimeout(total=timeout)@@ -929,12 +980,15 @@ class ClickHouseClient:query_parameters=None,query_id: str | None = None,on_schema: collections.abc.Callable[[pa.Schema], None] | None = None,+ external_tables: collections.abc.Sequence["ClickHouseExternalTable"] | None = None,) -> typing.AsyncGenerator[pa.RecordBatch]:"""Execute the given query in ClickHouse and stream back the response as Arrow record batches.This method makes sense when running with FORMAT ArrowStream, although we currently do not enforce this."""- async with self.apost_query(query, *data, query_parameters=query_parameters, query_id=query_id) as response:+ async with self.apost_query(+ query, *data, query_parameters=query_parameters, query_id=query_id, external_tables=external_tables+ ) as response:reader = asyncpa.AsyncRecordBatchReader(ChunkBytesAsyncStreamIterator(response.content))if on_schema is not None:on_schema(await reader.get_schema())diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.pyindex de2b027cbd92..4a924dc2b96a 100644--- a/posthog/temporal/data_modeling/activities/materialize_view.py+++ b/posthog/temporal/data_modeling/activities/materialize_view.py@@ -15,15 +15,19 @@ from structlog.types import FilteringBoundLoggerfrom temporalio import activityfrom posthog.hogql import ast-from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.constants import HogQLGlobalSettings, LimitContextfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.errors import ParsingError+from posthog.hogql.functions.prompt_jev import PromptJevFinderfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast+from posthog.hogql.query import HogQLQueryExecutor+from posthog.hogql.resolver import ResolverFactoryfrom posthog.hogql.visitor import CloningVisitor+from posthog.clickhouse.client.execute import ClickHouseExternalTablefrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exception@@ -123,8 +127,35 @@ class _DescribedColumn:ch_type: str+def _plan_prompt_jev(+ query_node: ast.SelectQuery | ast.SelectSetQuery,+ team: Team,+ context: HogQLContext,+ resolver_factory: ResolverFactory,+) -> ast.SelectQuery | ast.SelectSetQuery:+ """Run the model's jev calls up front, so the query that materializes reads their results+ from external tables registered on ``context``. The printer refuses a jev call it meets.++ Planning types the query before any model call, so it resolves the view tree too and needs+ the same cycle, depth and deadline bounds the printing pass gets."""+ planned, tables = HogQLQueryExecutor(+ query=query_node,+ team=team,+ context=context,+ modifiers=context.modifiers,+ limit_context=LimitContext.SAVED_QUERY,+ resolver_factory=resolver_factory,+ ).plan_prompt_jev()+ for table in tables:+ table.register(context)+ return planned++async def _describe_columns(- printed: str, query_parameters: dict[str, typing.Any], query_settings: dict[str, str] | None+ printed: str,+ query_parameters: dict[str, typing.Any],+ query_settings: dict[str, str] | None,+ external_tables: list[ClickHouseExternalTable],) -> list[_DescribedColumn]:"""A select list is ordered and may repeat a name, so the probe returns a list, not a mapping.`_reject_duplicate_output_columns` is what turns a repeat into a readable error."""@@ -134,6 +165,7 @@ async def _describe_columns(query_parameters=query_parameters,query_id=str(uuid.uuid4()),settings=query_settings,+ external_tables=external_tables,) as ch_response:table_describe_response = await ch_response.content.read()columns: list[_DescribedColumn] = []@@ -666,6 +698,13 @@ async def hogql_table(allowed_system_tables=DATA_MODELING_ALLOWED_SYSTEM_TABLES,)+ if PromptJevFinder.contains(query_node):+ # A factory of its own: the deadline is wall clock, and the jev calls between the two+ # passes would otherwise spend the printing pass's budget.+ query_node = await database_sync_to_async_pool(_plan_prompt_jev)(+ query_node, team, context, bounded_resolver_factory_for_view(view_name)+ )+factory = bounded_resolver_factory_for_view(view_name)prepared_hogql_query = await database_sync_to_async_pool(prepare_ast_for_printing)(query_node,@@ -705,7 +744,9 @@ async def hogql_table()try:- described_columns = await _describe_columns(printed, context.values, DESCRIBE_QUERY_SETTINGS)+ described_columns = await _describe_columns(+ printed, context.values, DESCRIBE_QUERY_SETTINGS, list(context.external_tables.values())+ )except ClickHouseError as error:# ClickHouse cannot plan some shapes once GLOBAL is gone, such as an IN subquery inside an# aggregate function. The untouched query is the one that runs, so it always describes.@@ -713,7 +754,9 @@ async def hogql_table("DESCRIBE with local subqueries failed, retrying with the untouched query", error=str(error))untouched = await database_sync_to_async_pool(_print_untouched)(prepared_hogql_query, context, settings)- described_columns = await _describe_columns(untouched, context.values, None)+ described_columns = await _describe_columns(+ untouched, context.values, None, list(context.external_tables.values())+ )_reject_duplicate_output_columns(described_columns)@@ -786,6 +829,7 @@ async def hogql_table(arrow_printed,query_parameters=context.values,on_schema=capture_arrow_schema,+ external_tables=list(context.external_tables.values()),):batches_size = batches_size + batch.nbytesbatches.append(batch)diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex d3e6b5a71c24..b2967e8d3b3e 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -13,6 +13,7 @@ import unittest.mockfrom django.conf import settingsfrom django.test import override_settings+import httpximport pyarrow as paimport deltalakeimport pyarrow.parquet as pq@@ -55,7 +56,7 @@ from posthog.temporal.data_modeling.activities.notify_materialization_failure imfrom products.customer_analytics.backend.facade.temporal import stage_warehouse_account_property_files_activityfrom products.customer_analytics.backend.facade.temporal_contracts import StageAccountPropertySyncInputfrom products.data_modeling.backend.facade.api import compute_enrichment_hash-from products.data_modeling.backend.facade.modeling import bounded_resolver_factory_for_view+from products.data_modeling.backend.facade.modeling import ResolutionCycleError, bounded_resolver_factory_for_viewfrom products.data_modeling.backend.facade.models import (DataModelingJob,DataModelingJobEngine,@@ -1695,6 +1696,7 @@ class _EmptyArrowClient:query_parameters: dict[str, Any] | None = None,query_id: str | None = None,on_schema: Callable[[pa.Schema], None] | None = None,+ external_tables: list[Any] | None = None,) -> AsyncIterator[pa.RecordBatch]:self.arrow_query_calls += 1self.arrow_query = query@@ -1711,6 +1713,7 @@ class _EmptyArrowClient:query_parameters: dict[str, Any] | None = None,query_id: str | None = None,settings: dict[str, str] | None = None,+ external_tables: list[Any] | None = None,) -> AsyncIterator[Any]:if query.startswith("DESCRIBE TABLE"):self.describe_calls.append((query, settings))@@ -1814,6 +1817,85 @@ class TestHogqlTableModifiers:assert client.arrow_query is not None+def _jev_gateway_response(_url: str, *, json: dict, headers: dict) -> httpx.Response:+ answers: dict[str, dict[str, Any]] = {}+ for name, question in json["questions"].items():+ refund = "refund" in json["state"][name]+ if question["type"] == "noul":+ answers[name] = {"type": "noul", "noul": 0.9 if refund else 0.1}+ else:+ choice = "billing" if refund else "other"+ answers[name] = {+ "type": "choice",+ "choice": choice,+ "confidence": 0.9,+ "probabilities": {label: 0.9 if label == choice else 0.1 for label in question["criteria"]},+ }+ return httpx.Response(200, json={"model": "jevk5-0.2", "answers": answers, "usage": {"input_tokens": 10}})+++class TestMaterializeViewPromptJev:+ async def test_materializes_jev_results_to_delta(+ self, activity_environment, ateam, anode, asaved_query, ajob, bucket_name, adag+ ):+ asaved_query.query = {+ "kind": "HogQLQuery",+ "query": (+ "SELECT text, is_refund, routed.choice AS team FROM ("+ "SELECT text, jev(text, 'Is this a refund request?') AS is_refund, "+ "jev(text, 'Which team should answer?', choice := ['billing', 'other']) AS routed "+ "FROM (SELECT arrayJoin(['please refund me', 'hello there']) AS text) LIMIT 10)"+ ),+ }+ await database_sync_to_async(asaved_query.save)()++ with (+ override_settings(+ BUCKET_URL=f"s3://{bucket_name}",+ DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,+ DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,+ DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",+ AI_GATEWAY_URL="https://gateway.example.com/v1",+ AI_GATEWAY_API_KEY="test-key",+ ),+ unittest.mock.patch("posthog.hogql.transforms.prompt_jev.feature_enabled_or_false", return_value=True),+ unittest.mock.patch("httpx.AsyncClient.post", side_effect=_jev_gateway_response),+ ):+ inputs = MaterializeViewInputs(+ team_id=ateam.pk, dag_id=str(adag.id), node_id=str(anode.id), job_id=str(ajob.id)+ )+ result = await activity_environment.run(materialize_view_activity, inputs)+ materialized = await asyncio.to_thread(+ lambda: deltalake.DeltaTable(+ result.table_uri, storage_options=get_aws_storage_options()+ ).to_pyarrow_table()+ )++ rows = sorted(materialized.to_pylist(), key=lambda row: row["text"])+ assert rows == [+ {"text": "hello there", "is_refund": pytest.approx(0.1), "team": "other"},+ {"text": "please refund me", "is_refund": pytest.approx(0.9), "team": "billing"},+ ]++ async def test_a_self_referencing_model_hits_the_resolution_bounds(self, ateam, auser):+ # planning types the query before any model call, so a cycle must raise there instead of+ # recursing until the worker's stack runs out+ query = "SELECT jev(text, 'Is this a refund request?') AS is_refund FROM jev_cycle"+ await database_sync_to_async(DataWarehouseSavedQuery.objects.create)(+ team=ateam,+ name="jev_cycle",+ query={"kind": "HogQLQuery", "query": query},+ created_by=auser,+ )++ with (+ override_settings(AI_GATEWAY_URL="https://gateway.example.com/v1", AI_GATEWAY_API_KEY="test-key"),+ unittest.mock.patch("posthog.hogql.transforms.prompt_jev.feature_enabled_or_false", return_value=True),+ pytest.raises(ResolutionCycleError),+ ):+ [batch async for batch in hogql_table(query, ateam, LOGGER.bind(), view_name="jev_cycle")]++class TestHogqlTableEmptyResults:async def test_zero_row_query_uses_the_initial_stream_schema(self, ateam):client = _EmptyArrowClient(pa.schema([pa.field("id", pa.int64())]))@@ -1937,10 +2019,16 @@ class _SlowDescribeClient(_EmptyArrowClient):query_parameters: dict[str, Any] | None = None,query_id: str | None = None,settings: dict[str, str] | None = None,+ external_tables: list[Any] | None = None,) -> AsyncIterator[Any]:await asyncio.sleep(self.describe_seconds)async with super().apost_query(- query, *data, query_parameters=query_parameters, query_id=query_id, settings=settings+ query,+ *data,+ query_parameters=query_parameters,+ query_id=query_id,+ settings=settings,+ external_tables=external_tables,) as response:yield responsediff --git a/posthog/temporal/tests/test_clickhouse.py b/posthog/temporal/tests/test_clickhouse.pyindex f74a558422a1..e7cdc3520532 100644--- a/posthog/temporal/tests/test_clickhouse.py+++ b/posthog/temporal/tests/test_clickhouse.py@@ -1,3 +1,4 @@+import jsonimport uuidimport asyncioimport datetime as dt@@ -557,3 +558,36 @@ async def test_stream_query_as_jsonl_handles_whitespace_only_lines(clickhouse_classert results[0] == {"id": 1}assert results[1] == {"id": 2}assert results[2] == {"id": 3}+++async def test_apost_query_sends_external_tables(clickhouse_client, django_db_setup):+ table = {+ "name": "_jev_result",+ "structure": [+ ("my `text`", "String"),+ ("at", "DateTime64(6, 'America/New_York')"),+ (+ "decision",+ "Tuple(choice Nullable(String), probabilities Array(Tuple(value String, probability Float64)), "+ "confidence Nullable(Float64))",+ ),+ ],+ "data": [+ {+ "my `text`": 'say "refund"',+ "at": dt.datetime(2026, 1, 2, 3, 4, 5, 123456, tzinfo=dt.UTC),+ "decision": ["billing", [["billing", 0.9], ["other", 0.1]], 0.9],+ }+ ],+ }+ query = (+ "SELECT `my \\`text\\`` AS text, toString(toTimeZone(at, 'UTC')) AS at, decision.choice AS choice, "+ "decision.probabilities[1].probability AS p FROM _jev_result FORMAT JSONEachRow"+ )++ async with clickhouse_client.apost_query(+ query, query_parameters={}, query_id=str(uuid.uuid4()), external_tables=[table]+ ) as response:+ row = json.loads(await response.content.read())++ assert row == {"text": 'say "refund"', "at": "2026-01-02 03:04:05.123456", "choice": "billing", "p": 0.9}