Skip to content

: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.

fix(batch-exports): drop unknown hogql modifiers from api responses (#114023)

Ross1f1a2f43ba92
diff --git a/products/batch_exports/backend/facade/api.py b/products/batch_exports/backend/facade/api.py
index 52c2f136f42c..9160a9a60637 100644
--- a/products/batch_exports/backend/facade/api.py
+++ b/products/batch_exports/backend/facade/api.py
@@ -21,7 +21,7 @@ those may be imported from here.
import datetime as dt
from collections.abc import Mapping, Sequence
from types import ModuleType
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from uuid import UUID
from django.db import transaction
@@ -59,6 +59,7 @@ __all__ = [
"delete_batch_export",
"delete_batch_exports_for_teams",
"describe_destination_test",
+ "drop_unknown_hogql_modifiers",
"get_batch_export_by_name",
"get_latest_completed_run",
"get_latest_run",
@@ -464,3 +465,12 @@ def run_destination_test_step(
destination_test.configure(**test_configuration)
return _to_destination_test_step(destination_test.run_step(step))
+
+
+def drop_unknown_hogql_modifiers(stored: Mapping[str, Any]) -> dict[str, Any]:
+ """Return stored HogQL modifiers without keys that the HogQL schema no longer defines."""
+ from products.batch_exports.backend.hogql_source import ( # noqa: PLC0415 — keeps the HogQL parser and printer off the django.setup() path
+ drop_unknown_hogql_modifiers as drop_unknown,
+ )
+
+ return drop_unknown(dict(stored))
diff --git a/products/batch_exports/backend/hogql_source.py b/products/batch_exports/backend/hogql_source.py
index 97dc4f4ba9c1..dc66f0fd7aa9 100644
--- a/products/batch_exports/backend/hogql_source.py
+++ b/products/batch_exports/backend/hogql_source.py
@@ -238,12 +238,18 @@ def validate_hogql_query_for_batch_export(
raise UnsupportedHogQLQueryError(f"Invalid HogQL query: {e}") from e
-def load_hogql_modifiers(stored: dict[str, typing.Any] | None) -> HogQLQueryModifiers | None:
- """Load the HogQL modifiers a batch export stored, dropping keys that no longer exist.
+def drop_unknown_hogql_modifiers(stored: dict[str, typing.Any]) -> dict[str, typing.Any]:
+ """Return the stored HogQL modifiers without keys that `HogQLQueryModifiers` no longer has.
`HogQLQueryModifiers` forbids unknown keys, so a modifier removed from the schema after
- an export stored it would fail every run. No code reads a removed modifier anymore, so
+ an export stored it would fail validation. No code reads a removed modifier anymore, so
dropping it keeps the output the same.
+ """
+ return {key: value for key, value in stored.items() if key in HogQLQueryModifiers.model_fields}
+
+
+def load_hogql_modifiers(stored: dict[str, typing.Any] | None) -> HogQLQueryModifiers | None:
+ """Load the HogQL modifiers a batch export stored, dropping keys that no longer exist.
Raises:
UnsupportedHogQLQueryError: If a stored modifier has a value that is not valid.
@@ -251,7 +257,7 @@ def load_hogql_modifiers(stored: dict[str, typing.Any] | None) -> HogQLQueryModi
if stored is None:
return None
- known = {key: value for key, value in stored.items() if key in HogQLQueryModifiers.model_fields}
+ known = drop_unknown_hogql_modifiers(stored)
if unknown := sorted(stored.keys() - known.keys()):
LOGGER.warning("Dropping unknown HogQL modifiers", modifiers=unknown)
diff --git a/products/batch_exports/backend/presentation/views/utils.py b/products/batch_exports/backend/presentation/views/utils.py
index f046c71ff4e1..49189101ac0d 100644
--- a/products/batch_exports/backend/presentation/views/utils.py
+++ b/products/batch_exports/backend/presentation/views/utils.py
@@ -10,6 +10,8 @@ from posthog.schema import HogQLQueryModifiers
from posthog.models import Team
+from products.batch_exports.backend.facade.api import drop_unknown_hogql_modifiers
+
HOGQL_MODIFIERS_HELP_TEXT = (
"HogQL modifiers to use when the query runs, as an object keyed by modifier name, for example "
"{\"convertToProjectTimezone\": true}. Only supported when 'model' is 'hogql'. Each modifier set here "
@@ -73,3 +75,10 @@ class HogQLModifiersField(serializers.JSONField):
else:
self.loaded = modifiers
return modifiers.model_dump(mode="json", exclude_none=True)
+
+ def to_representation(self, value: typing.Any) -> typing.Any:
+ # Runs drop modifiers removed from the schema, so responses drop them too: a client that sends back
+ # what it read must not fail validation on a key it never set.
+ if isinstance(value, dict):
+ value = drop_unknown_hogql_modifiers(value)
+ return super().to_representation(value)
diff --git a/products/batch_exports/backend/tests/api/test_update.py b/products/batch_exports/backend/tests/api/test_update.py
index d5bb3a99818d..c2dd3f99fac2 100644
--- a/products/batch_exports/backend/tests/api/test_update.py
+++ b/products/batch_exports/backend/tests/api/test_update.py
@@ -877,6 +877,18 @@ def test_patch_hogql_model_batch_export(
assert args["batch_export_model"]["hogql_query"] == new_hogql_query
assert args["batch_export_model"]["hogql_modifiers"] == hogql_modifiers
+ # A modifier removed from the schema after the export stored it is not returned, so sending back what was read
+ # still saves.
+ source = BatchExport.objects.get(id=batch_export["id"]).source
+ assert source is not None
+ source.hogql_modifiers = {"convertToProjectTimezone": False, "removedModifier": True}
+ source.save()
+
+ read_modifiers = get_batch_export_ok(client, team.pk, batch_export["id"])["hogql_modifiers"]
+ assert read_modifiers == {"convertToProjectTimezone": False}
+ response = patch_batch_export(client, team.pk, batch_export["id"], {"hogql_modifiers": read_modifiers})
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
@pytest.mark.usefixtures("hogql_batch_exports_enabled")
@pytest.mark.parametrize("access_level,include_query", [("viewer", False), ("none", False), ("none", True)])