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(insights): harden schema migrations and cover missed upgrade paths (#69926)

Thomas Obermüllere161da7a7014
diff --git a/posthog/schema_migrations/README.md b/posthog/schema_migrations/README.md
new file mode 100644
index 000000000000..6c0cfc7c4973
--- /dev/null
+++ b/posthog/schema_migrations/README.md
@@ -0,0 +1,36 @@
+# Query schema migrations
+
+Versioned migrations for the JSON query schema (`TrendsQuery`, `RetentionQuery`, ...), analogous to Django migrations but for query nodes stored as JSON: in insights, endpoints, cohorts, notebooks, URLs, and templates.
+
+## How it works
+
+- Every query node has an optional `version` field. **A missing or `null` version means version 1.**
+- A migration file (`NNNN_description.py`) declares `targets = {"<NodeKind>": <version>}` and a `transform(query: dict) -> dict` that converts a node from that version to the next. The version bump happens in the base class, not in `transform`.
+- `upgrade(query)` (`upgrade.py`) walks a query dict recursively (any nesting: `InsightVizNode.source`, series arrays, ...) and replays migrations on every node whose `version` is below `LATEST_VERSIONS[kind]`.
+- `upgrade_query(insight)` (`upgrade_manager.py`) additionally converts legacy filters-based insights to query-based ones first. Note: it mutates `insight.query` in memory and does not restore it on exit.
+- Discovery (`__init__.py`) is lazy and validated: duplicate `(kind, version)` targets raise, and `validate.py` (exercised in CI by `test_validate.py::test_linear`) rejects gaps and non-linear versions.
+
+## Where upgrades happen
+
+Read/execute-time (always-on):
+
+- `/api/.../query` and `process_query_dict` upgrade before pydantic validation.
+- `POST /api/environments/:id/query/upgrade` is called by the frontend for untrusted queries (URL-embedded, notebook nodes).
+- Insight serializers upgrade on read; caching, alerts, exports, and subscriptions go through `upgrade_query`.
+- Endpoints upgrade their immutable `EndpointVersion.query` snapshots at execution/materialization time; cohorts upgrade their saved `query` when compiling.
+
+Write-time (backfill): a Temporal schedule (`upgrade-queries-schedule`, every 6 hours, see `posthog/temporal/product_analytics/`) rewrites stored **insights** whose queries are below the latest versions. Other stores (endpoint snapshots, notebook content, dashboard templates, cohort queries) are _not_ rewritten and rely on read-time upgrades forever.
+
+## Adding a migration
+
+1. Create `NNNN_description.py` (next free number, must match `^\d{4}[a-zA-Z_]*\.py$`) with a `Migration(SchemaMigration)` class. Target the _current_ latest version of each kind (see `LATEST_VERSIONS` or `frontend/src/queries/latest-versions.json`).
+2. Add a test in `test/` covering the transform, including the no-op cases below.
+3. Regenerate the frontend versions file: `python bin/build-schema-latest-versions.py` (part of `hogli build:schema` / `pnpm run schema:build`) and commit `frontend/src/queries/latest-versions.json` **in the same PR**, otherwise `test_discovery.py::test_frontend_latest_versions_file_in_sync` fails. A stale file makes the frontend stamp outdated versions on new queries, which double-applies your migration to already-new-shape queries.
+4. Keep the schema backward compatible: leave the old field in `frontend/src/queries/schema/*.ts` (and thus `posthog/schema.py`) until the backfill has completed and no writer emits it anymore. Removing it immediately breaks validation of not-yet-upgraded JSON everywhere.
+
+## Invariants for `transform`
+
+- **Must be a safe no-op on queries already in the new shape.** All unversioned queries are treated as version 1, and plenty of new-shape queries are created without a version stamp (`filter_to_query` conversions, dashboard templates, hand-written API payloads). Guard on the presence of the old field, like the existing migrations do.
+- **Must tolerate missing/None fields.** Stored JSON is not validated before `transform` runs; a `KeyError` here fails query processing for that insight (and marks it failed in the backfill workflow).
+- **Must not change `kind`**: the version bump reads `targets[query["kind"]]` after the transform.
+- Two migrations must not target the same `(kind, version)`: discovery raises. If you race another PR, rebase and bump your target version.
diff --git a/posthog/schema_migrations/__init__.py b/posthog/schema_migrations/__init__.py
index bb5b0f377f91..15c646e72fa1 100644
--- a/posthog/schema_migrations/__init__.py
+++ b/posthog/schema_migrations/__init__.py
@@ -1,6 +1,7 @@
import os
import re
import importlib
+import threading
import structlog
@@ -11,13 +12,31 @@ logger = structlog.get_logger(__name__)
LATEST_VERSIONS: dict[str, int] = {}
MIGRATIONS: dict[str, dict[int, SchemaMigration]] = {}
_migrations_discovered: bool = False
+_discovery_lock = threading.Lock()
def _discover_migrations():
+ if _migrations_discovered:
+ return
+
+ # Serialize discovery: concurrent first calls would otherwise interleave the clear/rebuild
+ # below, tripping the duplicate-target check on valid migrations or exposing partial state
+ with _discovery_lock:
+ _discover_migrations_locked()
+
+
+# Separate function so the double-checked read of the flag isn't narrowed by mypy
+# (which would flag the second check as unreachable)
+def _discover_migrations_locked():
global _migrations_discovered
if _migrations_discovered:
return
+ # Clear in place (both dicts are imported by reference elsewhere), so a retry
+ # after a failed discovery doesn't see partial state as duplicate targets
+ LATEST_VERSIONS.clear()
+ MIGRATIONS.clear()
+
migration_dir = os.path.dirname(__file__)
migration_files = [f for f in os.listdir(migration_dir) if re.match(r"^\d{4}[a-zA-Z_]*\.py$", f)]
@@ -29,11 +48,19 @@ def _discover_migrations():
for kind, version in migration.targets.items():
if kind not in MIGRATIONS:
MIGRATIONS[kind] = {}
+ if version in MIGRATIONS[kind]:
+ # Overwriting would silently drop one of the two transforms at runtime
+ raise ValueError(
+ f"Duplicate schema migration target: {module_name} targets {kind} version {version}, "
+ f"which is already targeted by another migration. Bump one of them to the next version."
+ )
MIGRATIONS[kind][version] = migration
old_version = LATEST_VERSIONS.get(kind, 1)
new_version = max(old_version, version + 1)
LATEST_VERSIONS[kind] = new_version
+ # Set only after the registry is fully built, so the unlocked fast path in
+ # _discover_migrations never observes a partially populated registry
_migrations_discovered = True
logger.debug("migrations_discovered", latest_versions={str(k): v for k, v in LATEST_VERSIONS.items()})
diff --git a/posthog/schema_migrations/test/test_discovery.py b/posthog/schema_migrations/test/test_discovery.py
index 5517c5fe6566..74108115b2b4 100644
--- a/posthog/schema_migrations/test/test_discovery.py
+++ b/posthog/schema_migrations/test/test_discovery.py
@@ -1,48 +1,91 @@
+import json
+from pathlib import Path
+
+import pytest
from unittest.mock import MagicMock, patch
from posthog.schema import NodeKind
import posthog.schema_migrations as schema_migrations_module
from posthog.schema_migrations import LATEST_VERSIONS, MIGRATIONS, _discover_migrations
+from posthog.utils import to_json
-def test_discover_migrations():
+def _discover_with_mocks(files: list[str], modules: list[MagicMock]) -> None:
with (
patch("posthog.schema_migrations.os.listdir") as mock_listdir,
patch("posthog.schema_migrations.importlib.import_module") as mock_import,
):
- # Mock migration files
- mock_listdir.return_value = ["0001_test.py", "0002_another.py", "not_a_migration.py"]
+ mock_listdir.return_value = files
+ mock_import.side_effect = modules
+ schema_migrations_module._migrations_discovered = False
+ _discover_migrations()
- # Mock migration modules
- mock_module1 = MagicMock()
- mock_module1.Migration.return_value.targets = {NodeKind.TRENDS_QUERY: 1}
- mock_module2 = MagicMock()
- mock_module2.Migration.return_value.targets = {NodeKind.TRENDS_QUERY: 2, NodeKind.FUNNELS_QUERY: 1}
[email protected](autouse=True)
+def _reset_migration_state():
+ # Restore pristine state so tests running later in the process re-discover the real migrations
+ yield
+ LATEST_VERSIONS.clear()
+ MIGRATIONS.clear()
+ schema_migrations_module._migrations_discovered = False
- mock_import.side_effect = [mock_module1, mock_module2]
- # Reset state before test
- LATEST_VERSIONS.clear()
- MIGRATIONS.clear()
- schema_migrations_module._migrations_discovered = False
+def test_discover_migrations():
+ mock_module1 = MagicMock()
+ mock_module1.Migration.return_value.targets = {NodeKind.TRENDS_QUERY: 1}
- # Run discovery
- _discover_migrations()
+ mock_module2 = MagicMock()
+ mock_module2.Migration.return_value.targets = {NodeKind.TRENDS_QUERY: 2, NodeKind.FUNNELS_QUERY: 1}
+
+ _discover_with_mocks(["0001_test.py", "0002_another.py", "not_a_migration.py"], [mock_module1, mock_module2])
+
+ assert LATEST_VERSIONS[NodeKind.TRENDS_QUERY] == 3 # Max version + 1
+ assert LATEST_VERSIONS[NodeKind.FUNNELS_QUERY] == 2 # Version + 1
+
+ assert MIGRATIONS[NodeKind.TRENDS_QUERY][1] == mock_module1.Migration.return_value
+ assert MIGRATIONS[NodeKind.TRENDS_QUERY][2] == mock_module2.Migration.return_value
+ assert MIGRATIONS[NodeKind.FUNNELS_QUERY][1] == mock_module2.Migration.return_value
+
+
+def test_discover_migrations_rejects_duplicate_targets():
+ mock_module1 = MagicMock()
+ mock_module1.Migration.return_value.targets = {NodeKind.TRENDS_QUERY: 1}
+
+ mock_module2 = MagicMock()
+ mock_module2.Migration.return_value.targets = {NodeKind.TRENDS_QUERY: 1}
+
+ with pytest.raises(ValueError, match="Duplicate schema migration target"):
+ _discover_with_mocks(["0001_test.py", "0002_another.py"], [mock_module1, mock_module2])
+
+
+def test_discover_migrations_recovers_after_failed_discovery():
+ bad_module = MagicMock()
+ bad_module.Migration.side_effect = RuntimeError("broken migration module")
+
+ with pytest.raises(RuntimeError):
+ _discover_with_mocks(["0001_test.py"], [bad_module])
+
+ good_module = MagicMock()
+ good_module.Migration.return_value.targets = {NodeKind.TRENDS_QUERY: 1}
+
+ _discover_with_mocks(["0001_test.py"], [good_module])
+
+ assert LATEST_VERSIONS[NodeKind.TRENDS_QUERY] == 2
+
+
+def test_frontend_latest_versions_file_in_sync():
+ _discover_migrations()
+
+ path = Path(__file__).parents[3] / "frontend" / "src" / "queries" / "latest-versions.json"
+ committed = json.loads(path.read_text())
+ committed.pop("//", None)
+
+ # Serialize the same way bin/build-schema-latest-versions.py does
+ expected = json.loads(to_json(LATEST_VERSIONS))
- # Verify correct files were imported
- assert mock_import.call_count == 2
- mock_import.assert_any_call("posthog.schema_migrations.0001_test")
- mock_import.assert_any_call("posthog.schema_migrations.0002_another")
-
- # Verify versions were updated correctly
- assert LATEST_VERSIONS[NodeKind.TRENDS_QUERY] == 3 # Max version + 1
- assert LATEST_VERSIONS[NodeKind.FUNNELS_QUERY] == 2 # Version + 1
-
- # Verify migrations were stored correctly
- assert NodeKind.TRENDS_QUERY in MIGRATIONS
- assert NodeKind.FUNNELS_QUERY in MIGRATIONS
- assert MIGRATIONS[NodeKind.TRENDS_QUERY][1] == mock_module1.Migration.return_value
- assert MIGRATIONS[NodeKind.TRENDS_QUERY][2] == mock_module2.Migration.return_value
- assert MIGRATIONS[NodeKind.FUNNELS_QUERY][1] == mock_module2.Migration.return_value
+ assert committed == expected, (
+ "frontend/src/queries/latest-versions.json is out of sync with posthog/schema_migrations. "
+ "Run `python bin/build-schema-latest-versions.py` (part of `pnpm run schema:build` / `hogli build:schema`) "
+ "and commit the result."
+ )
diff --git a/posthog/schema_migrations/test/test_upgrade.py b/posthog/schema_migrations/test/test_upgrade.py
index bddf3b92b641..07ea8833f9cd 100644
--- a/posthog/schema_migrations/test/test_upgrade.py
+++ b/posthog/schema_migrations/test/test_upgrade.py
@@ -2,6 +2,7 @@ import pytest
from posthog.schema import NodeKind
+import posthog.schema_migrations as schema_migrations_module
from posthog.schema_migrations import LATEST_VERSIONS, MIGRATIONS, SchemaMigration
from posthog.schema_migrations.upgrade import upgrade
@@ -32,9 +33,15 @@ def setup_migrations():
MIGRATIONS[NodeKind.EVENTS_NODE] = {1: EventsNodeMigration()}
LATEST_VERSIONS[NodeKind.TRENDS_QUERY] = 2
LATEST_VERSIONS[NodeKind.EVENTS_NODE] = 2
+ # Mark as discovered so upgrade() doesn't replace the stubs with the real migrations
+ schema_migrations_module._migrations_discovered = True
yield
+ LATEST_VERSIONS.clear()
+ MIGRATIONS.clear()
+ schema_migrations_module._migrations_discovered = False
+
def test_simple_migration():
query = {"kind": NodeKind.TRENDS_QUERY, "version": 1, "flag": True}
diff --git a/posthog/schema_migrations/test/test_upgrade_manager.py b/posthog/schema_migrations/test/test_upgrade_manager.py
index 4e85ff23e91d..e56976ec5393 100644
--- a/posthog/schema_migrations/test/test_upgrade_manager.py
+++ b/posthog/schema_migrations/test/test_upgrade_manager.py
@@ -5,6 +5,7 @@ from unittest.mock import Mock
from posthog.schema import NodeKind
+import posthog.schema_migrations as schema_migrations_module
from posthog.schema_migrations import LATEST_VERSIONS, MIGRATIONS, SchemaMigration
from posthog.schema_migrations.upgrade_manager import upgrade_insight, upgrade_query
@@ -24,9 +25,15 @@ def setup_migrations():
MIGRATIONS[NodeKind.TRENDS_QUERY] = {1: SampleMigration()}
LATEST_VERSIONS[NodeKind.TRENDS_QUERY] = 2
+ # Mark as discovered so upgrade() doesn't replace the stub with the real migrations
+ schema_migrations_module._migrations_discovered = True
yield
+ LATEST_VERSIONS.clear()
+ MIGRATIONS.clear()
+ schema_migrations_module._migrations_discovered = False
+
def test_upgrade_insight_context_manager():
mock_insight = Mock()
diff --git a/posthog/schema_migrations/test/test_validate.py b/posthog/schema_migrations/test/test_validate.py
index dc29555e1b27..7ccd16559bb0 100644
--- a/posthog/schema_migrations/test/test_validate.py
+++ b/posthog/schema_migrations/test/test_validate.py
@@ -3,10 +3,19 @@ from unittest.mock import MagicMock
from posthog.schema import NodeKind
-from posthog.schema_migrations import MIGRATIONS
+import posthog.schema_migrations as schema_migrations_module
+from posthog.schema_migrations import LATEST_VERSIONS, MIGRATIONS
from posthog.schema_migrations.validate import validate_migrations
[email protected](autouse=True)
+def _reset_migration_state():
+ yield
+ LATEST_VERSIONS.clear()
+ MIGRATIONS.clear()
+ schema_migrations_module._migrations_discovered = False
+
+
def test_linear():
"""Validation of the actual migrations."""
validate_migrations()
@@ -16,6 +25,8 @@ def test_validate_migrations():
MIGRATIONS.clear()
MIGRATIONS[NodeKind.TRENDS_QUERY] = {1: MagicMock()}
MIGRATIONS[NodeKind.EVENTS_NODE] = {1: MagicMock()}
+ # Mark as discovered so validate_migrations() doesn't replace the stubs with the real migrations
+ schema_migrations_module._migrations_discovered = True
# Should not raise
validate_migrations()
diff --git a/posthog/temporal/product_analytics/upgrade_queries_activities.py b/posthog/temporal/product_analytics/upgrade_queries_activities.py
index 28521176a687..778463e6829f 100644
--- a/posthog/temporal/product_analytics/upgrade_queries_activities.py
+++ b/posthog/temporal/product_analytics/upgrade_queries_activities.py
@@ -7,6 +7,7 @@ from django.db import connection
from structlog import get_logger
from temporalio import activity
+from posthog.exceptions_capture import capture_exception
from posthog.schema_migrations import LATEST_VERSIONS, _discover_migrations
from posthog.schema_migrations.upgrade import upgrade
@@ -85,9 +86,12 @@ def migrate_insights_batch(inputs: MigrateInsightsBatchActivityInputs) -> list[i
for insight in insights:
try:
insight.query = upgrade(cast(dict[Any, Any], insight.query))
- insight.save()
+ # Narrow write: a full save would clobber concurrent user edits to other fields with
+ # the stale values read above. Insight.save() appends query_metadata when regenerated.
+ insight.save(update_fields=["query"])
except Exception as e:
logger.exception(f"Error migrating insight {insight.id}: {str(e)}")
+ capture_exception(e, {"insight_id": insight.id, "team_id": insight.team_id})
failed.append(insight.id)
return failed
diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.py
index ea545063fe7a..cd7062605b5d 100644
--- a/posthog/test/activity_logging/test_activity_logging.py
+++ b/posthog/test/activity_logging/test_activity_logging.py
@@ -1,5 +1,6 @@
import pytest
from posthog.test.base import BaseTest
+from unittest.mock import patch
from django.db.utils import IntegrityError
@@ -190,7 +191,10 @@ class TestActivityLogModel(BaseTest):
)
def test_does_not_throw_if_cannot_log_activity(self) -> None:
- with self.assertLogs(level="WARN") as log:
+ # Assert on the module logger directly instead of assertLogs: the root logger sits at
+ # ERROR under test settings, so whether the warning reaches a root handler depends on
+ # global logging state other tests may have touched
+ with patch("posthog.models.activity_logging.activity_log.logger") as mock_logger:
with self.settings(TEST=False): # Enable production-level silencing
try:
log_activity(
@@ -208,16 +212,13 @@ class TestActivityLogModel(BaseTest):
except Exception as e:
raise pytest.fail(f"Should not have raised exception: {e}")
- logged_warning = log.records[0].__dict__
- self.assertEqual(logged_warning["levelname"], "WARNING")
- self.assertEqual(
- logged_warning["msg"]["event"],
- "activity_log.failed_to_write_to_activity_log",
- )
- self.assertEqual(logged_warning["msg"]["scope"], "testing throwing exceptions on create")
- self.assertEqual(logged_warning["msg"]["team"], 1)
- self.assertEqual(logged_warning["msg"]["activity"], "does not explode")
- self.assertIsInstance(logged_warning["msg"]["exception"], ValueError)
+ warning = mock_logger.warn.call_args
+ self.assertIsNotNone(warning)
+ self.assertEqual(warning.args[0], "activity_log.failed_to_write_to_activity_log")
+ self.assertEqual(warning.kwargs["scope"], "testing throwing exceptions on create")
+ self.assertEqual(warning.kwargs["team"], 1)
+ self.assertEqual(warning.kwargs["activity"], "does not explode")
+ self.assertIsInstance(warning.kwargs["exception"], ValueError)
class TestActivityLogVisibilityManager(BaseTest):
diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.py
index a6522534bba3..aaefd7bf118e 100644
--- a/products/cohorts/backend/models/util.py
+++ b/products/cohorts/backend/models/util.py
@@ -44,6 +44,7 @@ from posthog.models.person.sql import (
)
from posthog.models.property import Property, PropertyGroup
from posthog.schema_enums import PersonsOnEventsMode, ProductKey
+from posthog.schema_migrations.upgrade import upgrade
from products.actions.backend.models.action import Action
from products.actions.backend.models.util import format_action_filter
@@ -328,7 +329,8 @@ def print_cohort_hogql_query(cohort: Cohort, hogql_context: HogQLContext, *, tea
if not cohort.query:
raise ValueError("Cohort has no query")
- query_dict = _sanitize_query_for_cohort(cast(dict, cohort.query))
+ # The stored query (and any insight query nested in its source) may predate the current schema
+ query_dict = upgrade(_sanitize_query_for_cohort(cast(dict, cohort.query)))
query = get_query_runner(query_dict, team=team, limit_context=LimitContext.COHORT_CALCULATION).to_query()
diff --git a/products/endpoints/backend/logic/ducklake_shadow.py b/products/endpoints/backend/logic/ducklake_shadow.py
index f6dffc65adf1..351b0b7dd7d9 100644
--- a/products/endpoints/backend/logic/ducklake_shadow.py
+++ b/products/endpoints/backend/logic/ducklake_shadow.py
@@ -9,6 +9,7 @@ from posthog.ducklake.client import execute_ducklake_query
from posthog.ducklake.common import get_duckgres_server_for_organization, is_dev_mode
from posthog.models import Team
from posthog.ph_client import ph_scoped_capture
+from posthog.schema_migrations.upgrade import upgrade
from products.endpoints.backend.logic.strategies import strategy_for
from products.endpoints.backend.models import Endpoint, EndpointVersion
@@ -37,7 +38,7 @@ def build_ducklake_hogql_query(
"""Build the HogQL an endpoint would run against DuckLake, matching the inline path's
variable overrides and pagination so the shadow mirrors what ClickHouse executed."""
strategy = strategy_for(endpoint, version, team)
- query = strategy.prepare_inline_query(version.query.copy())
+ query = strategy.prepare_inline_query(upgrade(version.query.copy()))
if limit is not None:
query, _ = strategy.apply_pagination(query, limit, offset or 0)
plan = strategy.build_inline_plan(query, data)
diff --git a/products/endpoints/backend/logic/execution.py b/products/endpoints/backend/logic/execution.py
index ed1c869d6326..ad5b98b63636 100644
--- a/products/endpoints/backend/logic/execution.py
+++ b/products/endpoints/backend/logic/execution.py
@@ -65,6 +65,7 @@ from posthog.exceptions import (
from posthog.exceptions_capture import capture_exception
from posthog.models import Team, User
from posthog.permissions import is_authenticated_via_project_secret_api_key
+from posthog.schema_migrations.upgrade import upgrade
from posthog.synthetic_user import SyntheticUser
from products.data_modeling.backend.facade.api import saved_query_materialized_at
@@ -888,6 +889,8 @@ class EndpointExecutionService(PydanticModelMixin):
try:
strategy = strategy_for(endpoint, version, self.team)
+ # Stored snapshots may predate the current query schema
+ query = upgrade(query)
query = strategy.prepare_inline_query(query)
pagination: EndpointPagination | None = None
diff --git a/products/endpoints/backend/logic/strategies.py b/products/endpoints/backend/logic/strategies.py
index 6fadb159e305..669c00cf1fca 100644
--- a/products/endpoints/backend/logic/strategies.py
+++ b/products/endpoints/backend/logic/strategies.py
@@ -34,6 +34,7 @@ from posthog.clickhouse.query_tagging import Product
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL
from posthog.models.team import Team
+from posthog.schema_migrations.upgrade import upgrade
from products.endpoints.backend.insight_transformers import transform_materialized_insight_response
from products.endpoints.backend.logic.pagination import EndpointPagination
@@ -313,7 +314,8 @@ class EndpointQueryStrategy(abc.ABC):
self.endpoint = endpoint
self.version = version
self.team = team
- self.query: dict = version.query
+ # Stored snapshots are immutable and may predate the current query schema
+ self.query: dict = upgrade(version.query)
@property
def query_kind(self) -> str | None:
diff --git a/products/endpoints/backend/materialization_transforms.py b/products/endpoints/backend/materialization_transforms.py
index 95bd02027688..b830a254713e 100644
--- a/products/endpoints/backend/materialization_transforms.py
+++ b/products/endpoints/backend/materialization_transforms.py
@@ -20,6 +20,7 @@ from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_NULL_STRIN
from posthog.hogql_queries.query_runner import get_query_runner
from posthog.models import User
from posthog.models.team import Team
+from posthog.schema_migrations.upgrade import upgrade
ENDPOINT_BREAKDOWN_LIMIT = 10_000
@@ -97,6 +98,9 @@ def convert_insight_query_to_hogql(
if query_kind == "HogQLQuery":
return query
+ # Stored endpoint snapshots may predate the current query schema
+ query = upgrade(query)
+
query_runner = get_query_runner(
query=query,
team=team,
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index 0b9e2b1bcfcf..41e89450413b 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -1006,7 +1006,9 @@ class InsightSerializer(InsightBasicSerializer):
tile_filters_override = tile_filters_override_requested_by_client(request, dashboard_tile) if request else {}
if instance.query is not None or instance.query_from_filters is not None:
- query = instance.query or instance.query_from_filters
+ # Upgrade before applying dashboard filters: the stored query may predate the current
+ # schema, and apply_dashboard_filters_to_dict validates against the latest one
+ query = upgrade(instance.query or instance.query_from_filters)
if (
dashboard is not None
or dashboard_filters_override is not None