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.

feat(dmat): part 1: postgres migration + django backend (#58079)

Sandy Spicer8e2798c88372
diff --git a/posthog/api/materialized_column_slot.py b/posthog/api/materialized_column_slot.py
index bb2421a955e7..2c167ed98c10 100644
--- a/posthog/api/materialized_column_slot.py
+++ b/posthog/api/materialized_column_slot.py
@@ -1,8 +1,6 @@
-from django.conf import settings
-from django.db import IntegrityError, models, transaction
+from django.db import IntegrityError, transaction
import structlog
-from asgiref.sync import async_to_sync
from loginas.utils import is_impersonated_session
from rest_framework import (
response,
@@ -11,19 +9,13 @@ from rest_framework import (
viewsets,
)
from rest_framework.decorators import action
-from temporalio.common import RetryPolicy
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.models import MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition
+from posthog.models import MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition, Team
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
+from posthog.models.materialized_column_slots import MAX_SLOTS_PER_TEAM
from posthog.permissions import IsStaffUserOrImpersonating
from posthog.settings import EE_AVAILABLE
-from posthog.temporal.backfill_materialized_property.activities import (
- MATERIALIZABLE_PROPERTY_TYPES,
- PROPERTY_TYPE_TO_COLUMN_NAME,
-)
-from posthog.temporal.backfill_materialized_property.workflows import BackfillMaterializedPropertyInputs
-from posthog.temporal.common.client import async_connect
if EE_AVAILABLE:
from ee.clickhouse.materialized_columns.columns import get_materialized_columns
@@ -61,10 +53,9 @@ class MaterializedColumnSlotSerializer(serializers.ModelSerializer):
"team",
"property_definition",
"property_definition_details",
- "property_type",
"slot_index",
"state",
- "backfill_temporal_workflow_id",
+ "backfill_temporal_run_id",
"error_message",
"created_at",
"updated_at",
@@ -83,27 +74,24 @@ class MaterializedColumnSlotViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSe
serializer_class = MaterializedColumnSlotSerializer
def safely_get_queryset(self, queryset):
- return queryset.filter(team_id=self.team_id).order_by("property_type", "slot_index")
+ return queryset.filter(team_id=self.team_id).order_by("slot_index")
@action(methods=["GET"], detail=False)
def slot_usage(self, request, **kwargs):
- """Get slot usage summary for a team."""
- counts = {
- row["property_type"]: row["count"]
- for row in MaterializedColumnSlot.objects.filter(team_id=self.team_id)
- .values("property_type")
- .annotate(count=models.Count("id"))
- }
- usage = {}
- for prop_type in MATERIALIZABLE_PROPERTY_TYPES:
- used = counts.get(prop_type, 0)
- usage[prop_type] = {"used": used, "total": 10, "available": 10 - used}
+ """Per-team materialized column slot usage.
+ The cap is MAX_SLOTS_PER_TEAM across all properties — there is no per-type
+ breakdown because dmat is string-only (HogQL casts at read time).
+ """
+ used_total = MaterializedColumnSlot.objects.filter(team_id=self.team_id).count()
+ available = max(0, MAX_SLOTS_PER_TEAM - used_total)
return response.Response(
{
"team_id": self.team_id,
"team_name": self.team.name,
- "usage": usage,
+ "max_slots_per_team": MAX_SLOTS_PER_TEAM,
+ "used_total": used_total,
+ "available": available,
}
)
@@ -123,7 +111,6 @@ class MaterializedColumnSlotViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSe
PropertyDefinition.objects.filter(
team_id=self.team_id,
property_type__isnull=False,
- property_type__in=MATERIALIZABLE_PROPERTY_TYPES,
type=PropertyDefinition.Type.EVENT,
)
.exclude(id__in=already_materialized)
@@ -187,79 +174,16 @@ class MaterializedColumnSlotViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSe
"""Returns error message if property cannot be materialized, None if valid."""
if not property_definition.property_type:
return "Property must have a type set to be materialized"
- if property_definition.property_type not in MATERIALIZABLE_PROPERTY_TYPES:
- return f"Property type '{property_definition.property_type}' cannot be materialized"
if property_definition.name.startswith("$") and not property_definition.name.startswith("$feature/"):
return "PostHog system properties cannot be materialized"
if property_definition.name in auto_materialized_names:
return f"Property '{property_definition.name}' is already auto-materialized by PostHog"
if any(slot.property_definition_id == property_definition.id for slot in existing_slots):
return "Property is already materialized"
+ if len(existing_slots) >= MAX_SLOTS_PER_TEAM:
+ return f"Team has reached the maximum of {MAX_SLOTS_PER_TEAM} materialized column slots"
return None
- def _find_available_slot_index(
- self, property_type: str, existing_slots: list[MaterializedColumnSlot]
- ) -> int | None:
- """Find the next available slot index for a property type."""
- used_indices = {slot.slot_index for slot in existing_slots if slot.property_type == property_type}
- for i in range(10):
- if i not in used_indices:
- return i
- return None
-
- def _get_mat_column_name(self, property_type: str, slot_index: int) -> str:
- """Generate the materialized column name for a slot."""
- type_name = PROPERTY_TYPE_TO_COLUMN_NAME[property_type]
- return f"dmat_{type_name}_{slot_index}"
-
- def _start_backfill_workflow(
- self,
- slot: MaterializedColumnSlot,
- property_name: str,
- property_type: str,
- workflow_id_suffix: str = "",
- ) -> str | None:
- """Start the Temporal backfill workflow. Returns error message on failure, None on success."""
- mat_column_name = self._get_mat_column_name(property_type, slot.slot_index)
-
- async def _start():
- client = await async_connect()
- workflow_id = f"backfill-mat-prop-{slot.id}{workflow_id_suffix}"
- handle = await client.start_workflow(
- "backfill-materialized-property",
- BackfillMaterializedPropertyInputs(
- team_id=slot.team_id,
- slot_id=str(slot.id),
- property_name=property_name,
- property_type=property_type,
- mat_column_name=mat_column_name,
- ),
- id=workflow_id,
- task_queue=settings.TEMPORAL_TASK_QUEUE,
- retry_policy=RetryPolicy(maximum_attempts=3),
- )
- return handle.id
-
- try:
- workflow_id = async_to_sync(_start)()
- slot.backfill_temporal_workflow_id = workflow_id
- slot.save()
- logger.info(
- "Started backfill workflow",
- slot_id=slot.id,
- team_id=slot.team_id,
- workflow_id=workflow_id,
- )
- return None
- except Exception as e:
- logger.exception(
- "Failed to start backfill workflow",
- slot_id=slot.id,
- team_id=slot.team_id,
- error=str(e),
- )
- return "Failed to start backfill workflow due to an internal error."
-
def _log_slot_created(self, slot: MaterializedColumnSlot, request) -> None:
"""Log activity for slot creation."""
log_activity(
@@ -275,20 +199,25 @@ class MaterializedColumnSlotViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSe
@action(methods=["POST"], detail=False)
def assign_slot(self, request, **kwargs):
- """Assign a property to an available slot."""
+ """Queue a property for materialization.
+
+ The slot is created in PENDING state with no slot_index assigned. The weekly
+ batched workflow assigns a column index, runs the historical backfill, and
+ transitions the slot to READY. Until then HogQL falls back to JSON extraction
+ for this property.
+ """
property_definition_id = request.data.get("property_definition_id")
if not property_definition_id:
return response.Response({"error": "property_definition_id is required"}, status=400)
- # Fetch auto-materialized names outside transaction (ClickHouse query)
auto_materialized_names = get_auto_materialized_property_names()
try:
with transaction.atomic():
- # Fetch all data we need upfront
- property_definition = PropertyDefinition.objects.select_for_update().get(
- id=property_definition_id, team_id=self.team_id
- )
+ # Serialize concurrent assign_slot calls per team so the MAX_SLOTS_PER_TEAM
+ # check below can't be raced past by two requests both reading 4 existing slots.
+ Team.objects.select_for_update().get(id=self.team_id)
+ property_definition = PropertyDefinition.objects.get(id=property_definition_id, team_id=self.team_id)
existing_slots = list(MaterializedColumnSlot.objects.filter(team_id=self.team_id))
validation_error = self._validate_property_for_materialization(
@@ -297,23 +226,11 @@ class MaterializedColumnSlotViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSe
if validation_error:
return response.Response({"error": validation_error}, status=400)
- # Validation ensures property_type is set
- property_type = property_definition.property_type
- assert property_type is not None
-
- slot_index = self._find_available_slot_index(property_type, existing_slots)
- if slot_index is None:
- return response.Response(
- {"error": f"No available slots for property type {property_type}"},
- status=400,
- )
-
slot = MaterializedColumnSlot.objects.create(
team=self.team,
property_definition=property_definition,
- property_type=property_type,
- slot_index=slot_index,
- state=MaterializedColumnSlotState.BACKFILL,
+ slot_index=None,
+ state=MaterializedColumnSlotState.PENDING,
created_by=request.user,
)
@@ -325,15 +242,6 @@ class MaterializedColumnSlotViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSe
status=http_status.HTTP_409_CONFLICT,
)
- # Start workflow outside transaction (idempotent, slot already committed)
- workflow_error = self._start_backfill_workflow(
- slot,
- property_name=property_definition.name,
- property_type=property_type,
- )
- if workflow_error:
- return response.Response({"error": workflow_error}, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)
-
self._log_slot_created(slot, request)
return response.Response(MaterializedColumnSlotSerializer(slot).data, status=http_status.HTTP_201_CREATED)
@@ -341,7 +249,9 @@ class MaterializedColumnSlotViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSe
"""Delete a materialized column slot with activity logging."""
slot = self.get_object()
- # Prevent deletion during active backfill
+ # PENDING slots can be safely cancelled (no column has been assigned yet).
+ # READY/ERROR slots can be deleted at any time. BACKFILL slots have an in-flight
+ # mutation populating their column — wait for it to finish.
if slot.state == MaterializedColumnSlotState.BACKFILL:
return response.Response(
{"error": "Cannot delete slot while backfill is in progress. Wait for completion or failure."},
@@ -375,7 +285,12 @@ class MaterializedColumnSlotViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSe
@action(methods=["POST"], detail=True)
def retry_backfill(self, request, pk=None, **kwargs):
- """Retry backfill for a slot in ERROR state."""
+ """Re-queue a failed slot for the next weekly backfill cycle.
+
+ Resets the slot to PENDING and clears the previously assigned slot_index so the
+ weekly workflow can pack it into the freshest available column. The error_message
+ is cleared so the UI no longer flags it as failed.
+ """
slot = self.get_object()
if slot.state != MaterializedColumnSlotState.ERROR:
@@ -385,27 +300,21 @@ class MaterializedColumnSlotViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSe
)
property_name = slot.property_definition.name
- property_type = slot.property_type
- # Update state back to BACKFILL and clear error message
- slot.state = MaterializedColumnSlotState.BACKFILL
+ slot.state = MaterializedColumnSlotState.PENDING
+ slot.slot_index = None
slot.error_message = None
- slot.save()
-
- workflow_error = self._start_backfill_workflow(
- slot,
- property_name=property_name,
- property_type=property_type,
- workflow_id_suffix=f"-retry-{slot.updated_at.timestamp()}",
+ slot.backfill_temporal_run_id = None
+ slot.save(
+ update_fields=[
+ "state",
+ "slot_index",
+ "error_message",
+ "backfill_temporal_run_id",
+ "updated_at",
+ ]
)
- if workflow_error:
- # Revert state and record the new error
- slot.state = MaterializedColumnSlotState.ERROR
- slot.error_message = workflow_error
- slot.save()
- return response.Response({"error": workflow_error}, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)
-
- # Log activity
+
log_activity(
organization_id=slot.team.organization_id,
team_id=slot.team_id,
@@ -422,7 +331,7 @@ class MaterializedColumnSlotViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSe
action="changed",
field="state",
before="ERROR",
- after="BACKFILL",
+ after="PENDING",
),
],
),
diff --git a/posthog/api/test/test_materialized_column_activity_logging.py b/posthog/api/test/test_materialized_column_activity_logging.py
deleted file mode 100644
index 2d120a98b641..000000000000
--- a/posthog/api/test/test_materialized_column_activity_logging.py
+++ /dev/null
@@ -1,289 +0,0 @@
-"""Tests for materialized column slot activity logging."""
-
-from posthog.test.base import APIBaseTest
-from unittest.mock import MagicMock, patch
-
-from temporalio.testing import ActivityEnvironment
-
-from posthog.models import ActivityLog, MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition
-from posthog.temporal.backfill_materialized_property.activities import UpdateSlotStateInputs, update_slot_state
-
-from products.event_definitions.backend.models.property_definition import PropertyType
-
-
-class TestMaterializedColumnActivityLogging(APIBaseTest):
- """Test that all state changes are properly logged."""
-
- def setUp(self):
- super().setUp()
- self.user.is_staff = True
- self.user.save()
-
- @patch("posthog.api.materialized_column_slot.async_to_sync")
- def test_activity_log_on_slot_creation(self, mock_async_to_sync):
- """Test activity log created when slot assigned."""
- mock_async_to_sync.return_value = MagicMock(return_value="workflow-id-123")
-
- prop_def = PropertyDefinition.objects.create(
- team=self.team,
- name="test_prop",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/materialized_column_slots/assign_slot/",
- {"property_definition_id": prop_def.id},
- )
-
- assert response.status_code == 201
-
- # Verify activity log was created
- activity_logs = ActivityLog.objects.filter(
- team_id=self.team.id,
- scope="DataManagement",
- activity="materialized_column_created",
- )
-
- assert activity_logs.count() == 1
- log = activity_logs.first()
- assert log is not None
- assert log.detail is not None
- assert log.detail["name"] == "test_prop"
- assert log.user == self.user
-
- def test_activity_log_on_slot_deletion(self):
- """Test activity log created when slot deleted."""
- prop_def = PropertyDefinition.objects.create(
- team=self.team,
- name="test_prop",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
- slot = MaterializedColumnSlot.objects.create(
- team=self.team,
- property_definition=prop_def,
- property_type=PropertyType.String,
- slot_index=5,
- state=MaterializedColumnSlotState.READY,
- )
-
- response = self.client.delete(f"/api/environments/{self.team.id}/materialized_column_slots/{slot.id}/")
-
- assert response.status_code == 204
-
- activity_logs = ActivityLog.objects.filter(
- team_id=self.team.id,
- scope="DataManagement",
- activity="materialized_column_deleted",
- )
-
- assert activity_logs.count() == 1
- log = activity_logs.first()
- assert log is not None
- assert log.detail is not None
- assert log.detail["name"] == "test_prop"
-
- def test_activity_log_on_backfill_completed(self):
- """Test activity log created when workflow completes successfully."""
- activity_environment = ActivityEnvironment()
- prop_def = PropertyDefinition.objects.create(
- team=self.team,
- name="test_prop",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
- slot = MaterializedColumnSlot.objects.create(
- team=self.team,
- property_definition=prop_def,
- property_type=PropertyType.String,
- slot_index=0,
- state=MaterializedColumnSlotState.BACKFILL,
- )
-
- # Call update_slot_state activity with READY
- activity_environment.run(
- update_slot_state,
- UpdateSlotStateInputs(slot_id=str(slot.id), state="READY"),
- )
-
- # Verify activity log was created
- activity_logs = ActivityLog.objects.filter(
- team_id=self.team.id,
- scope="DataManagement",
- activity="materialized_column_backfill_completed",
- )
-
- assert activity_logs.count() == 1
- log = activity_logs.first()
- assert log is not None
- assert log.detail is not None
-
- assert log.detail["name"] == "test_prop"
-
- # Verify state change is logged
- state_changes = [c for c in log.detail["changes"] if c["field"] == "state"]
- assert len(state_changes) == 1
- assert state_changes[0]["before"] == "BACKFILL"
- assert state_changes[0]["after"] == "READY"
-
- # User should be None (system user for workflow-triggered updates)
- assert log.user is None
-
- def test_activity_log_on_backfill_failed(self):
- """Test activity log created when workflow fails."""
- activity_environment = ActivityEnvironment()
- prop_def = PropertyDefinition.objects.create(
- team=self.team,
- name="test_prop",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
- slot = MaterializedColumnSlot.objects.create(
- team=self.team,
- property_definition=prop_def,
- property_type=PropertyType.String,
- slot_index=0,
- state=MaterializedColumnSlotState.BACKFILL,
- )
-
- # Call update_slot_state activity with ERROR
- activity_environment.run(
- update_slot_state,
- UpdateSlotStateInputs(
- slot_id=str(slot.id),
- state="ERROR",
- error_message="ClickHouse mutation failed",
- ),
- )
-
- # Verify activity log was created
- activity_logs = ActivityLog.objects.filter(
- team_id=self.team.id,
- scope="DataManagement",
- activity="materialized_column_backfill_failed",
- )
-
- assert activity_logs.count() == 1
- log = activity_logs.first()
- assert log is not None
- assert log.detail is not None
-
- assert log.detail["name"] == "test_prop"
-
- # Verify state change is logged
- state_changes = [c for c in log.detail["changes"] if c["field"] == "state"]
- assert len(state_changes) == 1
- assert state_changes[0]["before"] == "BACKFILL"
- assert state_changes[0]["after"] == "ERROR"
-
- def test_activity_log_no_log_for_backfill_state(self):
- """Test that transitioning to BACKFILL doesn't create activity log."""
- activity_environment = ActivityEnvironment()
- prop_def = PropertyDefinition.objects.create(
- team=self.team,
- name="test_prop",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
- slot = MaterializedColumnSlot.objects.create(
- team=self.team,
- property_definition=prop_def,
- property_type=PropertyType.String,
- slot_index=0,
- state=MaterializedColumnSlotState.ERROR,
- )
-
- initial_count = ActivityLog.objects.filter(team_id=self.team.id).count()
-
- # Call update_slot_state activity with BACKFILL
- activity_environment.run(
- update_slot_state,
- UpdateSlotStateInputs(slot_id=str(slot.id), state="BACKFILL"),
- )
-
- # Verify NO new activity log was created (only ERROR→READY and BACKFILL→ERROR/READY are logged)
- assert ActivityLog.objects.filter(team_id=self.team.id).count() == initial_count
-
- @patch("posthog.api.materialized_column_slot.async_to_sync")
- def test_activity_log_on_retry(self, mock_async_to_sync):
- """Test activity log created when backfill retried."""
- mock_async_to_sync.return_value = MagicMock(return_value="workflow-id-retry-123")
-
- prop_def = PropertyDefinition.objects.create(
- team=self.team,
- name="test_prop",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
- slot = MaterializedColumnSlot.objects.create(
- team=self.team,
- property_definition=prop_def,
- property_type=PropertyType.String,
- slot_index=0,
- state=MaterializedColumnSlotState.ERROR,
- error_message="Previous error",
- )
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/materialized_column_slots/{slot.id}/retry_backfill/"
- )
-
- assert response.status_code == 200
-
- # Verify activity log was created
- activity_logs = ActivityLog.objects.filter(
- team_id=self.team.id,
- scope="DataManagement",
- activity="materialized_column_retried",
- )
-
- assert activity_logs.count() == 1
- log = activity_logs.first()
- assert log is not None
- assert log.detail is not None
-
- assert log.detail["name"] == "test_prop"
-
- # Verify state change from ERROR to BACKFILL
- state_changes = [c for c in log.detail["changes"] if c["field"] == "state"]
- assert len(state_changes) == 1
- assert state_changes[0]["before"] == "ERROR"
- assert state_changes[0]["after"] == "BACKFILL"
-
- # User should be set (user initiated retry)
- assert log.user == self.user
-
- @patch("posthog.api.materialized_column_slot.is_impersonated_session")
- @patch("posthog.api.materialized_column_slot.async_to_sync")
- def test_activity_log_includes_impersonation_flag(self, mock_async_to_sync, mock_is_impersonated):
- """Test that is_impersonated_session is captured."""
- mock_is_impersonated.return_value = True
- mock_async_to_sync.return_value = MagicMock(return_value="workflow-id-123")
-
- prop_def = PropertyDefinition.objects.create(
- team=self.team,
- name="test_prop",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/materialized_column_slots/assign_slot/",
- {"property_definition_id": prop_def.id},
- )
-
- assert response.status_code == 201
-
- # Verify activity log has was_impersonated=True
- activity_logs = ActivityLog.objects.filter(
- team_id=self.team.id,
- scope="DataManagement",
- activity="materialized_column_created",
- )
-
- assert activity_logs.count() == 1
- log = activity_logs.first()
- assert log is not None
-
- assert log.was_impersonated is True
diff --git a/posthog/api/test/test_materialized_column_slot.py b/posthog/api/test/test_materialized_column_slot.py
index 42b59686fbf2..8fddf34f3cbf 100644
--- a/posthog/api/test/test_materialized_column_slot.py
+++ b/posthog/api/test/test_materialized_column_slot.py
@@ -7,6 +7,7 @@ from parameterized import parameterized
from rest_framework import status
from posthog.models import MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition
+from posthog.models.materialized_column_slots import MAX_SLOTS_PER_TEAM
from products.event_definitions.backend.models.property_definition import PropertyType
@@ -31,7 +32,6 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
MaterializedColumnSlot.objects.create(
team=self.team,
property_definition=prop_def,
- property_type=PropertyType.String,
slot_index=0,
state=MaterializedColumnSlotState.READY,
)
@@ -40,7 +40,6 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert len(response.json()["results"]) == 1
- assert response.json()["results"][0]["property_type"] == "String"
def test_list_slots_filtered_by_team(self):
"""Test that team_id query param filters correctly."""
@@ -54,7 +53,6 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
MaterializedColumnSlot.objects.create(
team=other_team,
property_definition=prop_def,
- property_type=PropertyType.String,
slot_index=0,
state=MaterializedColumnSlotState.READY,
)
@@ -64,57 +62,42 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert len(response.json()["results"]) == 0
- @parameterized.expand(
- [
- # No slots used
- (
- [],
- {
- "String": {"used": 0, "total": 10, "available": 10},
- "Numeric": {"used": 0, "total": 10, "available": 10},
- "Boolean": {"used": 0, "total": 10, "available": 10},
- "DateTime": {"used": 0, "total": 10, "available": 10},
- },
- ),
- # Some slots used
- (
- [("String", 0), ("String", 1), ("Numeric", 0)],
- {
- "String": {"used": 2, "total": 10, "available": 8},
- "Numeric": {"used": 1, "total": 10, "available": 9},
- "Boolean": {"used": 0, "total": 10, "available": 10},
- "DateTime": {"used": 0, "total": 10, "available": 10},
- },
- ),
- ]
- )
- def test_slot_usage_summary(self, slots_config, expected_usage):
- """Test slot usage calculation."""
- # Create slots based on config
- for i, (prop_type, slot_index) in enumerate(slots_config):
+ def test_slot_usage_empty(self):
+ """Test slot usage when no slots are assigned."""
+ response = self.client.get(f"/api/environments/{self.team.id}/materialized_column_slots/slot_usage/")
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["max_slots_per_team"] == MAX_SLOTS_PER_TEAM
+ assert body["used_total"] == 0
+ assert body["available"] == MAX_SLOTS_PER_TEAM
+
+ def test_slot_usage_partially_filled(self):
+ """Test slot usage with a mix of PENDING and READY slots."""
+ for i in range(3):
prop_def = PropertyDefinition.objects.create(
team=self.team,
name=f"prop_{i}",
- property_type=prop_type,
+ property_type=PropertyType.String,
type=PropertyDefinition.Type.EVENT,
)
MaterializedColumnSlot.objects.create(
team=self.team,
property_definition=prop_def,
- property_type=prop_type,
- slot_index=slot_index,
- state=MaterializedColumnSlotState.READY,
+ slot_index=i if i == 2 else None,
+ state=MaterializedColumnSlotState.READY if i == 2 else MaterializedColumnSlotState.PENDING,
)
response = self.client.get(f"/api/environments/{self.team.id}/materialized_column_slots/slot_usage/")
assert response.status_code == status.HTTP_200_OK
- assert response.json()["usage"] == expected_usage
+ body = response.json()
+ assert body["used_total"] == 3
+ assert body["available"] == MAX_SLOTS_PER_TEAM - 3
def test_slot_usage_all_slots_full(self):
- """Test slot usage when all slots for a type are full."""
- # Create 10 String slots
- for i in range(10):
+ """Test slot usage when all slots are full."""
+ for i in range(MAX_SLOTS_PER_TEAM):
prop_def = PropertyDefinition.objects.create(
team=self.team,
name=f"prop_{i}",
@@ -124,7 +107,6 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
MaterializedColumnSlot.objects.create(
team=self.team,
property_definition=prop_def,
- property_type=PropertyType.String,
slot_index=i,
state=MaterializedColumnSlotState.READY,
)
@@ -132,7 +114,9 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
response = self.client.get(f"/api/environments/{self.team.id}/materialized_column_slots/slot_usage/")
assert response.status_code == status.HTTP_200_OK
- assert response.json()["usage"]["String"] == {"used": 10, "total": 10, "available": 0}
+ body = response.json()
+ assert body["used_total"] == MAX_SLOTS_PER_TEAM
+ assert body["available"] == 0
def test_available_properties_filters_correctly(self):
"""Test that available_properties excludes the right properties."""
@@ -170,7 +154,6 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
MaterializedColumnSlot.objects.create(
team=self.team,
property_definition=already_materialized,
- property_type=PropertyType.String,
slot_index=0,
state=MaterializedColumnSlotState.READY,
)
@@ -252,11 +235,8 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response.json() == []
- @patch("posthog.api.materialized_column_slot.async_to_sync")
- def test_assign_slot_success(self, mock_async_to_sync):
- """Test successfully assigning a property to a slot."""
- mock_async_to_sync.return_value = MagicMock(return_value="workflow-id-123")
-
+ def test_assign_slot_success(self):
+ """Test successfully queueing a property as PENDING."""
prop_def = PropertyDefinition.objects.create(
team=self.team,
name="test_prop",
@@ -270,55 +250,16 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_201_CREATED
- assert response.json()["slot_index"] == 0
- assert response.json()["state"] == "BACKFILL"
- assert response.json()["property_type"] == "String"
-
- # Verify workflow was started
- assert mock_async_to_sync.called
-
- @patch("posthog.api.materialized_column_slot.async_to_sync")
- def test_assign_slot_finds_next_available_slot(self, mock_async_to_sync):
- """Test that slot assignment skips used slots."""
- mock_async_to_sync.return_value = MagicMock(return_value="workflow-id-123")
-
- # Create slots at indices 0, 1, 3
- for slot_index in [0, 1, 3]:
- prop_def = PropertyDefinition.objects.create(
- team=self.team,
- name=f"prop_{slot_index}",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
- MaterializedColumnSlot.objects.create(
- team=self.team,
- property_definition=prop_def,
- property_type=PropertyType.String,
- slot_index=slot_index,
- state=MaterializedColumnSlotState.READY,
- )
-
- # Assign new property - should get slot_index=2
- new_prop = PropertyDefinition.objects.create(
- team=self.team,
- name="new_prop",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/materialized_column_slots/assign_slot/",
- {"property_definition_id": new_prop.id},
- )
+ body = response.json()
+ assert body["state"] == "PENDING"
+ assert body["slot_index"] is None
- assert response.status_code == status.HTTP_201_CREATED
- assert response.json()["slot_index"] == 2
+ slot = MaterializedColumnSlot.objects.get(property_definition=prop_def)
+ assert slot.backfill_temporal_run_id is None
- @patch("posthog.api.materialized_column_slot.async_to_sync")
- def test_assign_slot_returns_error_when_all_slots_used(self, mock_async_to_sync):
- """Test error when all 10 slots are used."""
- # Create 10 String slots
- for i in range(10):
+ def test_assign_slot_returns_error_when_all_slots_used(self):
+ """Test error when team has reached MAX_SLOTS_PER_TEAM."""
+ for i in range(MAX_SLOTS_PER_TEAM):
prop_def = PropertyDefinition.objects.create(
team=self.team,
name=f"prop_{i}",
@@ -328,12 +269,10 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
MaterializedColumnSlot.objects.create(
team=self.team,
property_definition=prop_def,
- property_type=PropertyType.String,
slot_index=i,
state=MaterializedColumnSlotState.READY,
)
- # Try to assign another String property
new_prop = PropertyDefinition.objects.create(
team=self.team,
name="new_prop",
@@ -347,7 +286,7 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "No available slots" in response.json()["error"]
+ assert f"maximum of {MAX_SLOTS_PER_TEAM}" in response.json()["error"]
def test_assign_slot_no_property_type(self):
"""Test error when property has no type set."""
@@ -366,12 +305,21 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "Property must have a type set" in response.json()["error"]
- def test_assign_slot_duration_type(self):
- """Test error when trying to materialize Duration property."""
+ @parameterized.expand(
+ [
+ [PropertyType.Numeric],
+ [PropertyType.Boolean],
+ [PropertyType.Datetime],
+ [PropertyType.Duration],
+ [PropertyType.String],
+ ]
+ )
+ def test_assign_slot_accepts_all_typed_properties(self, prop_type):
+ """All PropertyTypes are materializable — storage is `Nullable(String)`, HogQL casts at read time."""
prop_def = PropertyDefinition.objects.create(
team=self.team,
- name="duration_prop",
- property_type=PropertyType.Duration,
+ name=f"{prop_type}_prop",
+ property_type=prop_type,
type=PropertyDefinition.Type.EVENT,
)
@@ -380,8 +328,7 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
{"property_definition_id": prop_def.id},
)
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "cannot be materialized" in response.json()["error"]
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
def test_assign_slot_system_property(self):
"""Test error when trying to materialize PostHog system property."""
@@ -400,11 +347,8 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "PostHog system properties cannot be materialized" in response.json()["error"]
- @patch("posthog.api.materialized_column_slot.async_to_sync")
- def test_assign_slot_allows_feature_flags(self, mock_async_to_sync):
+ def test_assign_slot_allows_feature_flags(self):
"""Test that feature flag properties CAN be materialized."""
- mock_async_to_sync.return_value = MagicMock(return_value="workflow-id-123")
-
prop_def = PropertyDefinition.objects.create(
team=self.team,
name="$feature/my_flag",
@@ -439,8 +383,7 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "already auto-materialized by PostHog" in response.json()["error"]
- @patch("posthog.api.materialized_column_slot.async_to_sync")
- def test_assign_slot_already_materialized(self, mock_async_to_sync):
+ def test_assign_slot_already_materialized(self):
"""Test error when property is already materialized."""
prop_def = PropertyDefinition.objects.create(
team=self.team,
@@ -451,7 +394,6 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
MaterializedColumnSlot.objects.create(
team=self.team,
property_definition=prop_def,
- property_type=PropertyType.String,
slot_index=0,
state=MaterializedColumnSlotState.READY,
)
@@ -464,35 +406,8 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "Property is already materialized" in response.json()["error"]
- @patch("posthog.api.materialized_column_slot.async_to_sync")
- def test_assign_slot_workflow_start_failure(self, mock_async_to_sync):
- """Test that workflow start failure doesn't delete slot."""
- mock_async_to_sync.side_effect = Exception("Temporal connection failed")
-
- prop_def = PropertyDefinition.objects.create(
- team=self.team,
- name="test_prop",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/materialized_column_slots/assign_slot/",
- {"property_definition_id": prop_def.id},
- )
-
- assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
- assert "Failed to start backfill workflow" in response.json()["error"]
-
- # Slot should still exist in BACKFILL state
- slot = MaterializedColumnSlot.objects.get(property_definition=prop_def)
- assert slot.state == MaterializedColumnSlotState.BACKFILL
-
- @patch("posthog.api.materialized_column_slot.async_to_sync")
- def test_retry_backfill_success(self, mock_async_to_sync):
- """Test retrying a failed backfill."""
- mock_async_to_sync.return_value = MagicMock(return_value="workflow-id-retry-123")
-
+ def test_retry_backfill_success(self):
+ """Test retrying a failed backfill resets slot to PENDING."""
prop_def = PropertyDefinition.objects.create(
team=self.team,
name="test_prop",
@@ -502,10 +417,10 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
slot = MaterializedColumnSlot.objects.create(
team=self.team,
property_definition=prop_def,
- property_type=PropertyType.String,
slot_index=0,
state=MaterializedColumnSlotState.ERROR,
error_message="Previous error",
+ backfill_temporal_run_id="failed-wf-1",
)
response = self.client.post(
@@ -513,14 +428,15 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_200_OK
- assert response.json()["state"] == "BACKFILL"
+ assert response.json()["state"] == "PENDING"
- # Verify state changed and error cleared
slot.refresh_from_db()
- assert slot.state == MaterializedColumnSlotState.BACKFILL
+ assert slot.state == MaterializedColumnSlotState.PENDING
+ assert slot.slot_index is None
assert slot.error_message is None
+ assert slot.backfill_temporal_run_id is None
- @parameterized.expand([["BACKFILL"], ["READY"]])
+ @parameterized.expand([["PENDING"], ["BACKFILL"], ["READY"]])
def test_retry_backfill_rejects_non_error_states(self, current_state):
"""Test that retry only works on ERROR state."""
prop_def = PropertyDefinition.objects.create(
@@ -532,8 +448,7 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
slot = MaterializedColumnSlot.objects.create(
team=self.team,
property_definition=prop_def,
- property_type=PropertyType.String,
- slot_index=0,
+ slot_index=None if current_state == "PENDING" else 0,
state=current_state,
)
@@ -555,7 +470,6 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
slot = MaterializedColumnSlot.objects.create(
team=self.team,
property_definition=prop_def,
- property_type=PropertyType.String,
slot_index=0,
state=MaterializedColumnSlotState.READY,
)
@@ -578,7 +492,6 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
slot = MaterializedColumnSlot.objects.create(
team=self.team,
property_definition=prop_def,
- property_type=PropertyType.String,
slot_index=0,
state=MaterializedColumnSlotState.BACKFILL, # In progress!
)
@@ -591,42 +504,27 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
# Verify slot still exists
assert MaterializedColumnSlot.objects.filter(id=slot.id).exists()
- def test_delete_slot_allowed_in_ready_state(self):
- """Test that deletion works when slot is in READY state."""
- prop_def = PropertyDefinition.objects.create(
- team=self.team,
- name="test_prop_ready",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
- slot = MaterializedColumnSlot.objects.create(
- team=self.team,
- property_definition=prop_def,
- property_type=PropertyType.String,
- slot_index=1,
- state=MaterializedColumnSlotState.READY,
- )
-
- response = self.client.delete(f"/api/environments/{self.team.id}/materialized_column_slots/{slot.id}/")
-
- assert response.status_code == status.HTTP_204_NO_CONTENT
- assert not MaterializedColumnSlot.objects.filter(id=slot.id).exists()
-
- def test_delete_slot_allowed_in_error_state(self):
- """Test that deletion works when slot is in ERROR state."""
+ @parameterized.expand(
+ [
+ ["PENDING", None],
+ ["READY", 1],
+ ["ERROR", 2],
+ ]
+ )
+ def test_delete_slot_allowed_in_non_backfill_states(self, state, slot_index):
prop_def = PropertyDefinition.objects.create(
team=self.team,
- name="test_prop_error",
+ name=f"test_prop_{state.lower()}",
property_type=PropertyType.String,
type=PropertyDefinition.Type.EVENT,
)
+ kwargs = {"error_message": "Previous failure"} if state == "ERROR" else {}
slot = MaterializedColumnSlot.objects.create(
team=self.team,
property_definition=prop_def,
- property_type=PropertyType.String,
- slot_index=2,
- state=MaterializedColumnSlotState.ERROR,
- error_message="Previous failure",
+ slot_index=slot_index,
+ state=state,
+ **kwargs,
)
response = self.client.delete(f"/api/environments/{self.team.id}/materialized_column_slots/{slot.id}/")
@@ -652,11 +550,9 @@ class TestMaterializedColumnSlotAPI(APIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN
@patch("posthog.permissions.is_impersonated_session")
- @patch("posthog.api.materialized_column_slot.async_to_sync")
- def test_endpoints_allow_impersonated_sessions(self, mock_async_to_sync, mock_is_impersonated):
+ def test_endpoints_allow_impersonated_sessions(self, mock_is_impersonated):
"""Test that impersonated sessions can access endpoints."""
mock_is_impersonated.return_value = True
- mock_async_to_sync.return_value = MagicMock(return_value="workflow-id-123")
# Make user non-staff
self.user.is_staff = False
diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.py
index 186d2efc8f66..231cb5876440 100644
--- a/posthog/clickhouse/cluster.py
+++ b/posthog/clickhouse/cluster.py
@@ -707,6 +707,14 @@ class MutationRunner(abc.ABC):
# we match commands by position, so require a stable ordering - this is because this class is provided the
# command template without parameter values, while the record in the mutation log will have the values inlined
command_list = [*commands]
+ # `formatQuerySingleLine` + collapse-whitespace + trim on both sides of the join so
+ # cosmetic spacing differences between our formatting and what
+ # `system.mutations.command` stored don't break the byte-equality match.
+ # Callers must pass fully-qualified identifiers (`db.table` / `db.dictionary`) —
+ # ClickHouse normalizes bare references against the connection database when
+ # storing the mutation, and a bare-vs-qualified mismatch defeats the join.
+ alter_prefix = f"ALTER TABLE {settings.CLICKHOUSE_DATABASE}.{self.table} "
+ per_command_alters = ", ".join(f"$__sql${alter_prefix}{cmd}$__sql$" for cmd in command_list)
mutations = client.execute(
f"""
SELECT mutation_id
@@ -715,11 +723,13 @@ class MutationRunner(abc.ABC):
(arrayJoin(
arrayZip(
arrayMap(
- command -> extract(command, '^\\s*(.*?)(?:,)?\\s*$'), -- strip leading/trailing whitespace and optional trailing comma
- arraySlice( -- drop "ALTER TABLE" preamble line
- splitByChar('\n', formatQuery($__sql$ALTER TABLE {settings.CLICKHOUSE_DATABASE}.{self.table} {", ".join(command_list)}$__sql$)),
- 2
- )
+ alter -> trim(BOTH ' ' FROM
+ replaceRegexpAll(
+ replaceOne(formatQuerySingleLine(alter), %(__alter_prefix)s, ''),
+ '[ \\t\\n]+', ' '
+ )
+ ),
+ [{per_command_alters}]
) as commands,
arrayEnumerate(commands)
)
@@ -728,7 +738,7 @@ class MutationRunner(abc.ABC):
) commands
LEFT OUTER JOIN (
SELECT
- command,
+ trim(BOTH ' ' FROM replaceRegexpAll(command, '[ \\t\\n]+', ' ')) as command,
argMax(mutation_id, create_time) as mutation_id -- Get the most recent mutation for each command
FROM system.mutations
WHERE
@@ -743,6 +753,7 @@ class MutationRunner(abc.ABC):
{
f"__database": settings.CLICKHOUSE_DATABASE,
f"__table": self.table,
+ f"__alter_prefix": alter_prefix,
**self.parameters,
},
)
diff --git a/posthog/clickhouse/kafka_engine.py b/posthog/clickhouse/kafka_engine.py
index 171f0c2988d0..b15bb8f7626a 100644
--- a/posthog/clickhouse/kafka_engine.py
+++ b/posthog/clickhouse/kafka_engine.py
@@ -121,3 +121,21 @@ def ttl_period(field: str = "created_at", amount: int = 3, unit: Literal["DAY",
def trim_quotes_expr(expr: str) -> str:
return f"replaceRegexpAll({expr}, '^\"|\"$', '')"
+
+
+def json_extract_trim_quotes(*args: str) -> str:
+ """Build a ClickHouse SQL expression that extracts a JSON value as a trimmed string.
+
+ Takes the same arguments as JSONExtractRaw (field, key1, key2, ...) and wraps the
+ result to: strip surrounding quotes, convert empty string and literal 'null' to NULL.
+
+ Three code paths must produce byte-identical output for the same input:
+ - HogQL printer's JSON fallback (``_unsafe_json_extract_trim_quotes``)
+ - SQL backfill mutation (``_generate_property_extraction_sql``)
+ - Plugin-server live ingest (``jsonExtractRawAndTrimQuotes`` in create-event.ts)
+
+ This function is the single source of truth for the SQL shape so the Python
+ paths can't drift from each other. The TypeScript path is covered by the
+ shared coercion fixture in ``coercion_fixtures.json``.
+ """
+ return f"replaceRegexpAll(nullIf(nullIf(JSONExtractRaw({', '.join(args)}), ''), 'null'), '^\"|\"$', '')"
diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.py
index 57b19a68ed2d..71bcfdd5fc6f 100644
--- a/posthog/clickhouse/schema.py
+++ b/posthog/clickhouse/schema.py
@@ -105,6 +105,10 @@ from posthog.models.distinct_id_usage.sql import (
KAFKA_DISTINCT_ID_USAGE_TABLE_SQL,
WRITABLE_DISTINCT_ID_USAGE_TABLE_SQL,
)
+from posthog.models.dmat_slot_assignments.sql import (
+ DMAT_SLOT_ASSIGNMENTS_DICTIONARY_SQL,
+ DMAT_SLOT_ASSIGNMENTS_TABLE_SQL,
+)
from posthog.models.event.sql import (
DISTRIBUTED_EVENTS_RECENT_TABLE_SQL,
DISTRIBUTED_EVENTS_TABLE_SQL,
@@ -298,6 +302,7 @@ CREATE_MERGETREE_TABLE_QUERIES = (
TOPHOG_DATA_TABLE_SQL,
AI_EVENTS_DATA_TABLE_SQL,
PROPERTY_VALUES_TABLE_SQL,
+ DMAT_SLOT_ASSIGNMENTS_TABLE_SQL,
)
CREATE_DISTRIBUTED_TABLE_QUERIES = (
WRITABLE_EVENTS_TABLE_SQL,
@@ -436,6 +441,7 @@ CREATE_DICTIONARY_QUERIES = (
PERSON_OVERRIDES_CREATE_DICTIONARY_SQL,
CHANNEL_DEFINITION_DICTIONARY_SQL,
EXCHANGE_RATE_DICTIONARY_SQL,
+ DMAT_SLOT_ASSIGNMENTS_DICTIONARY_SQL,
)
diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
index 63e5cf163303..7ff3b4ff1596 100644
--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr
+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
@@ -37,36 +37,6 @@
, `dmat_string_7` Nullable(String)
, `dmat_string_8` Nullable(String)
, `dmat_string_9` Nullable(String)
- , `dmat_numeric_0` Nullable(Float64)
- , `dmat_numeric_1` Nullable(Float64)
- , `dmat_numeric_2` Nullable(Float64)
- , `dmat_numeric_3` Nullable(Float64)
- , `dmat_numeric_4` Nullable(Float64)
- , `dmat_numeric_5` Nullable(Float64)
- , `dmat_numeric_6` Nullable(Float64)
- , `dmat_numeric_7` Nullable(Float64)
- , `dmat_numeric_8` Nullable(Float64)
- , `dmat_numeric_9` Nullable(Float64)
- , `dmat_bool_0` Nullable(UInt8)
- , `dmat_bool_1` Nullable(UInt8)
- , `dmat_bool_2` Nullable(UInt8)
- , `dmat_bool_3` Nullable(UInt8)
- , `dmat_bool_4` Nullable(UInt8)
- , `dmat_bool_5` Nullable(UInt8)
- , `dmat_bool_6` Nullable(UInt8)
- , `dmat_bool_7` Nullable(UInt8)
- , `dmat_bool_8` Nullable(UInt8)
- , `dmat_bool_9` Nullable(UInt8)
- , `dmat_datetime_0` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_1` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_2` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_3` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_4` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_5` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_6` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_7` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_8` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_9` Nullable(DateTime64(6, 'UTC'))
@@ -263,36 +233,6 @@
, `dmat_string_7` Nullable(String)
, `dmat_string_8` Nullable(String)
, `dmat_string_9` Nullable(String)
- , `dmat_numeric_0` Nullable(Float64)
- , `dmat_numeric_1` Nullable(Float64)
- , `dmat_numeric_2` Nullable(Float64)
- , `dmat_numeric_3` Nullable(Float64)
- , `dmat_numeric_4` Nullable(Float64)
- , `dmat_numeric_5` Nullable(Float64)
- , `dmat_numeric_6` Nullable(Float64)
- , `dmat_numeric_7` Nullable(Float64)
- , `dmat_numeric_8` Nullable(Float64)
- , `dmat_numeric_9` Nullable(Float64)
- , `dmat_bool_0` Nullable(UInt8)
- , `dmat_bool_1` Nullable(UInt8)
- , `dmat_bool_2` Nullable(UInt8)
- , `dmat_bool_3` Nullable(UInt8)
- , `dmat_bool_4` Nullable(UInt8)
- , `dmat_bool_5` Nullable(UInt8)
- , `dmat_bool_6` Nullable(UInt8)
- , `dmat_bool_7` Nullable(UInt8)
- , `dmat_bool_8` Nullable(UInt8)
- , `dmat_bool_9` Nullable(UInt8)
- , `dmat_datetime_0` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_1` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_2` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_3` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_4` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_5` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_6` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_7` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_8` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_9` Nullable(DateTime64(6, 'UTC'))
@@ -1223,6 +1163,19 @@
'''
# ---
+# name: test_create_table_query[dmat_slot_assignments]
+ '''
+
+ CREATE TABLE IF NOT EXISTS `dmat_slot_assignments` (
+ team_id UInt64,
+ column_index UInt8,
+ property_name String,
+ version UInt32 DEFAULT toUnixTimestamp(now())
+ ) ENGINE = ReplacingMergeTree(version)
+ ORDER BY (team_id, column_index);
+
+ '''
+# ---
# name: test_create_table_query[error_tracking_fingerprint_issue_state]
'''
@@ -1354,36 +1307,6 @@
, `dmat_string_7` Nullable(String)
, `dmat_string_8` Nullable(String)
, `dmat_string_9` Nullable(String)
- , `dmat_numeric_0` Nullable(Float64)
- , `dmat_numeric_1` Nullable(Float64)
- , `dmat_numeric_2` Nullable(Float64)
- , `dmat_numeric_3` Nullable(Float64)
- , `dmat_numeric_4` Nullable(Float64)
- , `dmat_numeric_5` Nullable(Float64)
- , `dmat_numeric_6` Nullable(Float64)
- , `dmat_numeric_7` Nullable(Float64)
- , `dmat_numeric_8` Nullable(Float64)
- , `dmat_numeric_9` Nullable(Float64)
- , `dmat_bool_0` Nullable(UInt8)
- , `dmat_bool_1` Nullable(UInt8)
- , `dmat_bool_2` Nullable(UInt8)
- , `dmat_bool_3` Nullable(UInt8)
- , `dmat_bool_4` Nullable(UInt8)
- , `dmat_bool_5` Nullable(UInt8)
- , `dmat_bool_6` Nullable(UInt8)
- , `dmat_bool_7` Nullable(UInt8)
- , `dmat_bool_8` Nullable(UInt8)
- , `dmat_bool_9` Nullable(UInt8)
- , `dmat_datetime_0` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_1` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_2` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_3` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_4` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_5` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_6` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_7` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_8` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_9` Nullable(DateTime64(6, 'UTC'))
, $group_0 VARCHAR COMMENT 'column_materializer::$group_0'
, $group_1 VARCHAR COMMENT 'column_materializer::$group_1'
@@ -1510,36 +1433,6 @@
dmat_string_7,
dmat_string_8,
dmat_string_9,
- dmat_numeric_0,
- dmat_numeric_1,
- dmat_numeric_2,
- dmat_numeric_3,
- dmat_numeric_4,
- dmat_numeric_5,
- dmat_numeric_6,
- dmat_numeric_7,
- dmat_numeric_8,
- dmat_numeric_9,
- dmat_bool_0,
- dmat_bool_1,
- dmat_bool_2,
- dmat_bool_3,
- dmat_bool_4,
- dmat_bool_5,
- dmat_bool_6,
- dmat_bool_7,
- dmat_bool_8,
- dmat_bool_9,
- dmat_datetime_0,
- dmat_datetime_1,
- dmat_datetime_2,
- dmat_datetime_3,
- dmat_datetime_4,
- dmat_datetime_5,
- dmat_datetime_6,
- dmat_datetime_7,
- dmat_datetime_8,
- dmat_datetime_9,
_timestamp,
_offset,
arrayMap(
@@ -2015,36 +1908,6 @@
, `dmat_string_7` Nullable(String)
, `dmat_string_8` Nullable(String)
, `dmat_string_9` Nullable(String)
- , `dmat_numeric_0` Nullable(Float64)
- , `dmat_numeric_1` Nullable(Float64)
- , `dmat_numeric_2` Nullable(Float64)
- , `dmat_numeric_3` Nullable(Float64)
- , `dmat_numeric_4` Nullable(Float64)
- , `dmat_numeric_5` Nullable(Float64)
- , `dmat_numeric_6` Nullable(Float64)
- , `dmat_numeric_7` Nullable(Float64)
- , `dmat_numeric_8` Nullable(Float64)
- , `dmat_numeric_9` Nullable(Float64)
- , `dmat_bool_0` Nullable(UInt8)
- , `dmat_bool_1` Nullable(UInt8)
- , `dmat_bool_2` Nullable(UInt8)
- , `dmat_bool_3` Nullable(UInt8)
- , `dmat_bool_4` Nullable(UInt8)
- , `dmat_bool_5` Nullable(UInt8)
- , `dmat_bool_6` Nullable(UInt8)
- , `dmat_bool_7` Nullable(UInt8)
- , `dmat_bool_8` Nullable(UInt8)
- , `dmat_bool_9` Nullable(UInt8)
- , `dmat_datetime_0` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_1` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_2` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_3` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_4` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_5` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_6` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_7` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_8` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_9` Nullable(DateTime64(6, 'UTC'))
@@ -5176,36 +5039,6 @@
, `dmat_string_7` Nullable(String)
, `dmat_string_8` Nullable(String)
, `dmat_string_9` Nullable(String)
- , `dmat_numeric_0` Nullable(Float64)
- , `dmat_numeric_1` Nullable(Float64)
- , `dmat_numeric_2` Nullable(Float64)
- , `dmat_numeric_3` Nullable(Float64)
- , `dmat_numeric_4` Nullable(Float64)
- , `dmat_numeric_5` Nullable(Float64)
- , `dmat_numeric_6` Nullable(Float64)
- , `dmat_numeric_7` Nullable(Float64)
- , `dmat_numeric_8` Nullable(Float64)
- , `dmat_numeric_9` Nullable(Float64)
- , `dmat_bool_0` Nullable(UInt8)
- , `dmat_bool_1` Nullable(UInt8)
- , `dmat_bool_2` Nullable(UInt8)
- , `dmat_bool_3` Nullable(UInt8)
- , `dmat_bool_4` Nullable(UInt8)
- , `dmat_bool_5` Nullable(UInt8)
- , `dmat_bool_6` Nullable(UInt8)
- , `dmat_bool_7` Nullable(UInt8)
- , `dmat_bool_8` Nullable(UInt8)
- , `dmat_bool_9` Nullable(UInt8)
- , `dmat_datetime_0` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_1` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_2` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_3` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_4` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_5` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_6` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_7` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_8` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_9` Nullable(DateTime64(6, 'UTC'))
, $group_0 VARCHAR MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_0'), '^"|"$', '') COMMENT 'column_materializer::$group_0'
, $group_1 VARCHAR MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_1'), '^"|"$', '') COMMENT 'column_materializer::$group_1'
@@ -6458,36 +6291,6 @@
, `dmat_string_7` Nullable(String)
, `dmat_string_8` Nullable(String)
, `dmat_string_9` Nullable(String)
- , `dmat_numeric_0` Nullable(Float64)
- , `dmat_numeric_1` Nullable(Float64)
- , `dmat_numeric_2` Nullable(Float64)
- , `dmat_numeric_3` Nullable(Float64)
- , `dmat_numeric_4` Nullable(Float64)
- , `dmat_numeric_5` Nullable(Float64)
- , `dmat_numeric_6` Nullable(Float64)
- , `dmat_numeric_7` Nullable(Float64)
- , `dmat_numeric_8` Nullable(Float64)
- , `dmat_numeric_9` Nullable(Float64)
- , `dmat_bool_0` Nullable(UInt8)
- , `dmat_bool_1` Nullable(UInt8)
- , `dmat_bool_2` Nullable(UInt8)
- , `dmat_bool_3` Nullable(UInt8)
- , `dmat_bool_4` Nullable(UInt8)
- , `dmat_bool_5` Nullable(UInt8)
- , `dmat_bool_6` Nullable(UInt8)
- , `dmat_bool_7` Nullable(UInt8)
- , `dmat_bool_8` Nullable(UInt8)
- , `dmat_bool_9` Nullable(UInt8)
- , `dmat_datetime_0` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_1` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_2` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_3` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_4` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_5` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_6` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_7` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_8` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_9` Nullable(DateTime64(6, 'UTC'))
, _timestamp DateTime
@@ -7344,6 +7147,19 @@
Order By (team_id, cohort_id, person_id, version)
+ '''
+# ---
+# name: test_create_table_query_replicated_and_storage[dmat_slot_assignments]
+ '''
+
+ CREATE TABLE IF NOT EXISTS `dmat_slot_assignments` (
+ team_id UInt64,
+ column_index UInt8,
+ property_name String,
+ version UInt32 DEFAULT toUnixTimestamp(now())
+ ) ENGINE = ReplacingMergeTree(version)
+ ORDER BY (team_id, column_index);
+
'''
# ---
# name: test_create_table_query_replicated_and_storage[error_tracking_issue_fingerprint_overrides]
@@ -8393,36 +8209,6 @@
, `dmat_string_7` Nullable(String)
, `dmat_string_8` Nullable(String)
, `dmat_string_9` Nullable(String)
- , `dmat_numeric_0` Nullable(Float64)
- , `dmat_numeric_1` Nullable(Float64)
- , `dmat_numeric_2` Nullable(Float64)
- , `dmat_numeric_3` Nullable(Float64)
- , `dmat_numeric_4` Nullable(Float64)
- , `dmat_numeric_5` Nullable(Float64)
- , `dmat_numeric_6` Nullable(Float64)
- , `dmat_numeric_7` Nullable(Float64)
- , `dmat_numeric_8` Nullable(Float64)
- , `dmat_numeric_9` Nullable(Float64)
- , `dmat_bool_0` Nullable(UInt8)
- , `dmat_bool_1` Nullable(UInt8)
- , `dmat_bool_2` Nullable(UInt8)
- , `dmat_bool_3` Nullable(UInt8)
- , `dmat_bool_4` Nullable(UInt8)
- , `dmat_bool_5` Nullable(UInt8)
- , `dmat_bool_6` Nullable(UInt8)
- , `dmat_bool_7` Nullable(UInt8)
- , `dmat_bool_8` Nullable(UInt8)
- , `dmat_bool_9` Nullable(UInt8)
- , `dmat_datetime_0` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_1` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_2` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_3` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_4` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_5` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_6` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_7` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_8` Nullable(DateTime64(6, 'UTC'))
- , `dmat_datetime_9` Nullable(DateTime64(6, 'UTC'))
, $group_0 VARCHAR MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_0'), '^"|"$', '') COMMENT 'column_materializer::$group_0'
, $group_1 VARCHAR MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_1'), '^"|"$', '') COMMENT 'column_materializer::$group_1'
diff --git a/posthog/clickhouse/test/test_cluster.py b/posthog/clickhouse/test/test_cluster.py
index cf5a1728f3c5..9cffa52f876f 100644
--- a/posthog/clickhouse/test/test_cluster.py
+++ b/posthog/clickhouse/test/test_cluster.py
@@ -183,6 +183,120 @@ def test_alter_mutation_single_command(cluster: ClickhouseCluster) -> None:
assert cluster.any_host(MutationWaiter("x", {"y"}).is_done).result()
+def test_cycle_marker_survives_format_query(cluster: ClickhouseCluster) -> None:
+ """Pins the load-bearing assumption: ClickHouse's `formatQuery` preserves the
+ `AND <int> = <int>` conjunct verbatim, so same int → dedup hits, different int →
+ dedup misses. Without that, the dict-backed mutation's SQL would be byte-identical
+ across cycles and a fresh cycle would falsely reattach to last week's completed run.
+ """
+ table = EVENTS_DATA_TABLE()
+ count = 100
+
+ cluster.map_one_host_per_shard(Query(f"INSERT INTO {table} SELECT * FROM generateRandom() LIMIT {count}")).result()
+
+ sentinel_uuid_a = uuid.uuid1()
+ sentinel_uuid_b = uuid.uuid1()
+ # Per-run unique cycle markers so prior test runs' mutations in `system.mutations` don't
+ # collide with this run's expected-empty state.
+ cycle_a = int(sentinel_uuid_a.int % 2_000_000_000)
+ cycle_b = int(sentinel_uuid_b.int % 2_000_000_000)
+ assert cycle_a != cycle_b, "uuid collision — re-run the test"
+
+ def _runner(uuid_param, cycle_int: int) -> AlterTableMutationRunner:
+ return AlterTableMutationRunner(
+ table=table,
+ commands={
+ f"""
+ UPDATE person_id = %(uuid)s
+ WHERE 1 = 1 AND {cycle_int} = {cycle_int}
+ """
+ },
+ parameters={"uuid": uuid_param},
+ )
+
+ runner_a = _runner(sentinel_uuid_a, cycle_a)
+ runner_a_again = _runner(sentinel_uuid_a, cycle_a) # Same cycle marker → must dedup against runner_a.
+ runner_b = _runner(sentinel_uuid_b, cycle_b) # Different marker → must NOT dedup against runner_a.
+
+ # Initially no existing mutation for any of them.
+ for runner in (runner_a, runner_b):
+ existing = cluster.map_all_hosts(runner.find_existing_mutations).result()
+ assert all(not mutations for mutations in existing.values()), (
+ f"unexpected pre-existing mutation for cycle {runner.commands}"
+ )
+
+ # Submit runner_a, wait for completion.
+ shard_mutations_a = cluster.map_one_host_per_shard(runner_a).result()
+ wait_and_check_mutations_on_shards(cluster, shard_mutations_a)
+
+ # Same cycle marker → identical formatted SQL → re-submission attaches to runner_a's mutation.
+ shard_mutations_a_again = cluster.map_one_host_per_shard(runner_a_again).result()
+ assert shard_mutations_a == shard_mutations_a_again, "same cycle marker must reattach to the existing mutation"
+
+ # Different cycle marker → different formatted SQL → fresh mutation, NOT a reattach.
+ shard_mutations_b = cluster.map_one_host_per_shard(runner_b).result()
+ for host_info, waiter_a in shard_mutations_a.items():
+ waiter_b = shard_mutations_b[host_info]
+ assert waiter_a.mutation_ids != waiter_b.mutation_ids, (
+ f"cycle markers {cycle_a} and {cycle_b} produced colliding mutation_ids — "
+ "formatQuery may have folded the marker, breaking cross-cycle isolation"
+ )
+
+ wait_and_check_mutations_on_shards(cluster, shard_mutations_b)
+
+
+def test_find_existing_mutations_handles_multiline_formatted_command(cluster: ClickhouseCluster) -> None:
+ """Regression test: ClickHouse's `formatQuery` wraps long/nested commands across multiple
+ lines. `find_existing_mutations` must still treat that as a single command — pre-fix the
+ helper formatted one batched ALTER and split by '\n', so a wrapped command produced more
+ rows than `command_list` had entries and the assert at the bottom of the function blew up.
+ """
+ table = EVENTS_DATA_TABLE()
+ count = 100
+
+ cluster.map_one_host_per_shard(Query(f"INSERT INTO {table} SELECT * FROM generateRandom() LIMIT {count}")).result()
+
+ sentinel_uuid = uuid.uuid1()
+ # Marker keeps this run's mutation isolated from prior runs in system.mutations.
+ cycle_int = int(sentinel_uuid.int % 2_000_000_000)
+
+ # Deeply nested no-op UPDATE on `properties`. The shape mirrors the dmat dict-backed
+ # mutation closely enough that formatQuery wraps it across multiple lines — that is the
+ # condition that pre-fix tripped the assertion in find_existing_mutations. The leaf is
+ # wrapped in `ifNull(..., properties)` because `replaceRegexpAll(nullIf(...))` returns
+ # NULL when the JSON key is absent, and `properties` is non-Nullable — without the guard
+ # the mutation fails on every row with CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN.
+ long_command = (
+ "UPDATE properties = if(1 = 1, "
+ "if(1 = 1, "
+ "if(1 = 1, "
+ "ifNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, 'a_long_property_name_to_force_wrapping'), ''), 'null'), '^\"|\"$', ''), properties), "
+ "properties), "
+ "properties), "
+ "properties) "
+ f"WHERE 1 = 1 AND {cycle_int} = {cycle_int}"
+ )
+ runner = AlterTableMutationRunner(table=table, commands={long_command})
+
+ # Pre-fix, this call alone raised AssertionError because formatQuery wraps the command.
+ existing = cluster.map_all_hosts(runner.find_existing_mutations).result()
+ assert all(not mutations for mutations in existing.values()), "expected no pre-existing mutation for this cycle"
+
+ shard_mutations = cluster.map_one_host_per_shard(runner).result()
+ wait_and_check_mutations_on_shards(cluster, shard_mutations)
+
+ # After completion, the command must round-trip — i.e. the formatted-command join still
+ # matches what ClickHouse stored in system.mutations.command, multi-line text and all.
+ existing = cluster.map_all_hosts(runner.find_existing_mutations).result()
+ assert all(mutations.keys() == runner.commands for mutations in existing.values()), (
+ "find_existing_mutations failed to reattach to a wrapped multi-line formatted command"
+ )
+
+ # Idempotent re-submission: must reattach, not enqueue a duplicate.
+ duplicate = cluster.map_one_host_per_shard(runner).result()
+ assert shard_mutations == duplicate
+
+
def test_alter_mutation_multiple_commands(cluster: ClickhouseCluster) -> None:
table = EVENTS_DATA_TABLE()
count = 100
diff --git a/posthog/clickhouse/test/test_dmat_dictionary.py b/posthog/clickhouse/test/test_dmat_dictionary.py
new file mode 100644
index 000000000000..fa1716f6b02a
--- /dev/null
+++ b/posthog/clickhouse/test/test_dmat_dictionary.py
@@ -0,0 +1,109 @@
+"""Real-ClickHouse integration tests for the dmat slot-assignments dictionary.
+
+These tests pin the dict mechanics that the dmat backfill mutation depends on:
+- `dictHas` returns true for known `(team_id, column_index)` keys, false otherwise.
+- `dictGetString` returns the inserted property name for known keys.
+- Reload picks up new rows after TRUNCATE+INSERT.
+
+The end-to-end coercion parity is covered by
+`posthog/temporal/tests/backfill_materialized_property/test_coercion_parity.py::TestDictBackedDispatchCoercion`.
+This file is the focused unit-style equivalent: no event rows, no extraction, just the
+dict round-trip the mutation builder relies on.
+"""
+
+import uuid
+
+from posthog.clickhouse.client import sync_execute
+from posthog.models.dmat_slot_assignments.sql import (
+ DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME,
+ INSERT_DMAT_SLOT_ASSIGNMENTS_SQL,
+ RELOAD_DMAT_SLOT_ASSIGNMENTS_DICTIONARY_SQL,
+ TRUNCATE_DMAT_SLOT_ASSIGNMENTS_SQL,
+)
+
+
+def _populate(rows: list[tuple[int, int, str]]) -> None:
+ sync_execute(TRUNCATE_DMAT_SLOT_ASSIGNMENTS_SQL())
+ if rows:
+ sync_execute(INSERT_DMAT_SLOT_ASSIGNMENTS_SQL(), rows)
+ sync_execute(RELOAD_DMAT_SLOT_ASSIGNMENTS_DICTIONARY_SQL())
+
+
+def test_dict_has_returns_true_for_known_keys() -> None:
+ team_id = 1_000_001
+ column_index = 5
+ property_name = f"prop_{uuid.uuid4().hex[:8]}"
+ _populate([(team_id, column_index, property_name)])
+
+ result = sync_execute(
+ f"SELECT dictHas('{DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME}', (toUInt64(%(team)s), toUInt8(%(idx)s)))",
+ {"team": team_id, "idx": column_index},
+ )
+ assert result == [(1,)]
+
+
+def test_dict_has_returns_false_for_unknown_keys() -> None:
+ _populate([]) # empty dict
+
+ result = sync_execute(
+ f"SELECT dictHas('{DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME}', (toUInt64(%(team)s), toUInt8(%(idx)s)))",
+ {"team": 999_999, "idx": 0},
+ )
+ assert result == [(0,)]
+
+
+def test_dict_get_string_round_trips_property_name() -> None:
+ team_id = 2_000_002
+ column_index = 8
+ property_name = f"my prop with spaces {uuid.uuid4().hex[:6]}"
+ _populate([(team_id, column_index, property_name)])
+
+ result = sync_execute(
+ f"SELECT dictGetString('{DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME}', 'property_name', "
+ "(toUInt64(%(team)s), toUInt8(%(idx)s)))",
+ {"team": team_id, "idx": column_index},
+ )
+ assert result == [(property_name,)]
+
+
+def test_truncate_then_reload_clears_dict() -> None:
+ team_id = 3_000_003
+ column_index = 7
+ _populate([(team_id, column_index, "browser")])
+
+ # Round trip on the populated state.
+ has_before = sync_execute(
+ f"SELECT dictHas('{DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME}', (toUInt64(%(team)s), toUInt8(%(idx)s)))",
+ {"team": team_id, "idx": column_index},
+ )
+ assert has_before == [(1,)]
+
+ # Truncate and reload — the populate activity uses this exact pattern every cycle.
+ _populate([])
+
+ has_after = sync_execute(
+ f"SELECT dictHas('{DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME}', (toUInt64(%(team)s), toUInt8(%(idx)s)))",
+ {"team": team_id, "idx": column_index},
+ )
+ assert has_after == [(0,)], "dict must drop the entry after TRUNCATE+RELOAD"
+
+
+def test_distinct_team_ids_lookup_via_in_subselect() -> None:
+ """The mutation's WHERE uses `team_id IN (SELECT DISTINCT team_id FROM dmat_slot_assignments)`.
+ Confirms the subselect actually returns the right team set so the mutation prunes
+ parts correctly.
+ """
+ team_a = 4_000_001
+ team_b = 4_000_002
+ team_c = 4_000_003
+ _populate(
+ [
+ (team_a, 0, "p1"),
+ (team_a, 1, "p2"), # team_a appears twice — DISTINCT must collapse it.
+ (team_b, 3, "p3"),
+ (team_c, 5, "p4"),
+ ]
+ )
+
+ result = sync_execute("SELECT DISTINCT team_id FROM dmat_slot_assignments ORDER BY team_id")
+ assert result == [(team_a,), (team_b,), (team_c,)]
diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.py
index 6f7bf58ddbb0..3653828c56df 100644
--- a/posthog/hogql/printer/base.py
+++ b/posthog/hogql/printer/base.py
@@ -39,6 +39,7 @@ from posthog.hogql.resolver import resolve_types
from posthog.hogql.resolver_utils import lookup_field_by_name
from posthog.hogql.visitor import Visitor, clone_expr
+from posthog.clickhouse.kafka_engine import json_extract_trim_quotes
from posthog.clickhouse.materialized_columns import (
MaterializedColumn,
TablesWithMaterializedColumns,
@@ -1551,7 +1552,7 @@ class BasePrinter(Visitor[str]):
return escape_hogql_string(name, timezone=self._get_timezone())
def _unsafe_json_extract_trim_quotes(self, unsafe_field: str, unsafe_args: list[str]) -> str:
- return f"replaceRegexpAll(nullIf(nullIf(JSONExtractRaw({', '.join([unsafe_field, *unsafe_args])}), ''), 'null'), '^\"|\"$', '')"
+ return json_extract_trim_quotes(unsafe_field, *unsafe_args)
def _json_property_args(self, chain: Iterable[Any]) -> list[str]:
return [self.context.add_value(name) for name in chain]
@@ -1567,7 +1568,7 @@ class BasePrinter(Visitor[str]):
"""
Get the dmat column name for a property if available.
- Returns the column name (e.g., 'dmat_numeric_3') if a materialized slot exists,
+ Returns the column name (e.g., 'dmat_string_3') if a materialized slot exists,
otherwise None.
"""
if self.context.property_swapper is None:
diff --git a/posthog/hogql/transforms/property_types.py b/posthog/hogql/transforms/property_types.py
index 586e04a18d28..a1bacd30eee8 100644
--- a/posthog/hogql/transforms/property_types.py
+++ b/posthog/hogql/transforms/property_types.py
@@ -30,14 +30,6 @@ from posthog.clickhouse.materialized_columns import (
from posthog.models import Team
from posthog.models.property import PropertyName, TableColumn
-# Mapping from PropertyType enum values to column name suffixes for dynamic materialized columns
-PROPERTY_TYPE_TO_COLUMN_NAME: dict[str, str] = {
- "String": "string",
- "Numeric": "numeric",
- "Boolean": "bool",
- "DateTime": "datetime",
-}
-
def build_property_swapper(node: ast.AST, context: HogQLContext) -> None:
from posthog.models import PropertyDefinition
@@ -86,9 +78,7 @@ def build_property_swapper(node: ast.AST, context: HogQLContext) -> None:
prop_info: dict[str, str | None] = {"type": prop_def.property_type}
slot = prop_def.materialized_column_slots.first()
if slot:
- type_name = PROPERTY_TYPE_TO_COLUMN_NAME.get(slot.property_type)
- if type_name:
- prop_info["dmat"] = f"dmat_{type_name}_{slot.slot_index}"
+ prop_info["dmat"] = f"dmat_string_{slot.slot_index}"
event_properties[prop_def.name] = prop_info
@@ -562,11 +552,9 @@ class PropertySwapper(CloningVisitor):
# Add notice about the property type and materialization status
self._add_property_notice(node, property_type, field_type, prop_info.get("dmat"))
- if "dmat" in prop_info:
- # Don't rewrite the AST - let the printer substitute the dmat column
- # The printer will check context.property_swapper and use the dmat column
- return node
-
+ # Both paths fall through to the wrapper: dmat columns are `Nullable(String)` (the
+ # printer swaps the field to `dmat_string_<idx>`), so they need the same cast as
+ # the JSON fallback.
return self._field_type_to_property_call(node, field_type)
def _field_type_to_property_call(self, node: ast.Field, field_type: str):
diff --git a/posthog/hogql/transforms/test/test_property_types_dmat.py b/posthog/hogql/transforms/test/test_property_types_dmat.py
deleted file mode 100644
index d47e1769aa03..000000000000
--- a/posthog/hogql/transforms/test/test_property_types_dmat.py
+++ /dev/null
@@ -1,299 +0,0 @@
-"""Tests for dmat (dynamic materialized columns) integration in property type resolution."""
-
-import json
-import uuid
-from dataclasses import dataclass
-from typing import Any
-
-import pytest
-from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
-
-from posthog.hogql.context import HogQLContext
-from posthog.hogql.parser import parse_select
-from posthog.hogql.printer import prepare_and_print_ast
-
-from posthog.clickhouse.client import sync_execute
-from posthog.models import MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition
-from posthog.temporal.backfill_materialized_property.activities import (
- PROPERTY_TYPE_TO_COLUMN_NAME,
- _generate_property_extraction_sql,
-)
-
-from products.event_definitions.backend.models.property_definition import PropertyType
-
-
-class TestDmatIntegration(BaseTest):
- """Test that HogQL queries use dmat columns when available."""
-
- def test_uses_dmat_column_when_slot_ready(self):
- """Test that property access uses dmat column when slot is READY."""
- prop_def = PropertyDefinition.objects.create(
- team=self.team,
- project_id=self.team.project_id,
- name="revenue",
- property_type=PropertyType.Numeric,
- type=PropertyDefinition.Type.EVENT,
- )
- MaterializedColumnSlot.objects.create(
- team=self.team,
- property_definition=prop_def,
- property_type=PropertyType.Numeric,
- slot_index=3,
- state=MaterializedColumnSlotState.READY,
- )
-
- expr = parse_select("SELECT properties.revenue FROM events")
- query, _ = prepare_and_print_ast(
- expr,
- HogQLContext(team_id=self.team.pk, team=self.team, enable_select_queries=True),
- "clickhouse",
- )
-
- # Should use dmat column
- assert "dmat_numeric_3" in query, f"Expected dmat_numeric_3 in query but got: {query}"
- assert "JSONExtractRaw" not in query
-
- def test_falls_back_to_json_when_no_slot(self):
- """Test that property access falls back to JSON extraction when no slot exists."""
- PropertyDefinition.objects.create(
- team=self.team,
- name="custom_prop",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
-
- expr = parse_select("SELECT properties.custom_prop FROM events")
- query, _ = prepare_and_print_ast(
- expr,
- HogQLContext(team_id=self.team.pk, team=self.team, enable_select_queries=True),
- "clickhouse",
- )
-
- # Should use JSON extraction (no dmat)
- assert "properties" in query or "JSONExtractRaw" in query
- assert "dmat_" not in query
-
- def test_ignores_slot_in_backfill_state(self):
- """Test that slots in BACKFILL state are not used."""
- prop_def = PropertyDefinition.objects.create(
- team=self.team,
- name="user_score",
- property_type=PropertyType.Numeric,
- type=PropertyDefinition.Type.EVENT,
- )
- MaterializedColumnSlot.objects.create(
- team=self.team,
- property_definition=prop_def,
- property_type=PropertyType.Numeric,
- slot_index=0,
- state=MaterializedColumnSlotState.BACKFILL,
- )
-
- expr = parse_select("SELECT properties.user_score FROM events")
- query, _ = prepare_and_print_ast(
- expr,
- HogQLContext(team_id=self.team.pk, team=self.team, enable_select_queries=True),
- "clickhouse",
- )
-
- # Should NOT use dmat (slot is in BACKFILL state)
- assert "dmat_numeric_0" not in query
- # Should use JSON extraction or properties access
- assert "properties" in query or "JSONExtractRaw" in query
-
-
-@dataclass
-class PropertyTestCase:
- """Single property edge case test."""
-
- name: str # Property name (unique identifier)
- type: PropertyType # Property type
- input_value: Any # Value stored in JSON properties
-
-
-TEST_CASES = [
- # String edge cases
- PropertyTestCase(name="str_normal", type=PropertyType.String, input_value="hello world"),
- PropertyTestCase(name="str_empty", type=PropertyType.String, input_value=""),
- PropertyTestCase(name="str_whitespace", type=PropertyType.String, input_value=" "),
- # Numeric edge cases
- PropertyTestCase(name="num_int", type=PropertyType.Numeric, input_value=42),
- PropertyTestCase(name="num_zero", type=PropertyType.Numeric, input_value=0),
- PropertyTestCase(name="num_negative", type=PropertyType.Numeric, input_value=-100),
- PropertyTestCase(name="num_float", type=PropertyType.Numeric, input_value=3.14159),
- PropertyTestCase(name="num_invalid", type=PropertyType.Numeric, input_value="not a number"),
- PropertyTestCase(name="num_whitespace", type=PropertyType.Numeric, input_value=" 123 "),
- # Boolean edge cases
- PropertyTestCase(name="bool_true_str", type=PropertyType.Boolean, input_value="true"),
- PropertyTestCase(name="bool_false_str", type=PropertyType.Boolean, input_value="false"),
- PropertyTestCase(name="bool_true_int", type=PropertyType.Boolean, input_value="1"),
- PropertyTestCase(name="bool_false_int", type=PropertyType.Boolean, input_value="0"),
- PropertyTestCase(name="bool_invalid", type=PropertyType.Boolean, input_value="maybe"),
- # DateTime edge cases
- PropertyTestCase(name="dt_iso_full", type=PropertyType.Datetime, input_value="2024-01-15T10:30:00Z"),
- PropertyTestCase(name="dt_date_only", type=PropertyType.Datetime, input_value="2024-01-15"),
- PropertyTestCase(name="dt_invalid", type=PropertyType.Datetime, input_value="not a date"),
-]
-
-
-class TestDmatExtractionConsistency(ClickhouseTestMixin, APIBaseTest):
- """Test that dmat column extraction matches JSON extraction behavior."""
-
- def _build_slot_mapping(self):
- """Build mapping of test cases to dmat column names and slot indices.
-
- Returns dict: {test_case_name: {"col_name": str, "slot_idx": int}}
- """
- slot_counters = {
- PropertyType.String: 0,
- PropertyType.Numeric: 0,
- PropertyType.Boolean: 0,
- PropertyType.Datetime: 0,
- }
-
- mapping = {}
- for tc in TEST_CASES:
- slot_idx = slot_counters[tc.type]
- slot_counters[tc.type] += 1
-
- mapping[tc.name] = {
- "col_name": f"dmat_{PROPERTY_TYPE_TO_COLUMN_NAME[tc.type]}_{slot_idx}",
- "slot_idx": slot_idx,
- }
-
- return mapping
-
- @pytest.mark.django_db(transaction=True)
- def test_dmat_extraction_matches_json_for_all_property_types(self):
- """
- Verify dmat columns produce identical results to JSON extraction.
-
- This test does NOT test the backfill mutation process (for speed).
- Instead it:
- 1. Inserts an event with JSON properties and queries it (baseline)
- 2. Inserts an event with pre-filled dmat columns using the extraction SQL
- 3. Creates MaterializedColumnSlot records so PropertySwapper detects them
- 4. Queries the dmat event and verifies results match JSON results
-
- This ensures _generate_property_extraction_sql() produces the same output
- as HogQL's property type wrappers (toFloat, toBool, toDateTime).
- """
- from posthog.hogql.query import execute_hogql_query
-
- # Build test data
- event_properties = {tc.name: tc.input_value for tc in TEST_CASES}
- slot_mapping = self._build_slot_mapping()
-
- # Create PropertyDefinitions (needed for MaterializedColumnSlot foreign key)
- prop_defs = {}
- for tc in TEST_CASES:
- prop_defs[tc.name] = PropertyDefinition.objects.create(
- team=self.team,
- name=tc.name,
- property_type=tc.type,
- type=PropertyDefinition.Type.EVENT,
- )
-
- # ============================================================
- # PHASE 1: Establish baseline using JSON extraction
- # ============================================================
- _create_event(
- team=self.team,
- distinct_id="user1",
- event="json_event",
- properties=event_properties,
- )
- flush_persons_and_events()
-
- select_fields = ", ".join([f"properties.{tc.name}" for tc in TEST_CASES])
- result_json = execute_hogql_query(
- f"SELECT {select_fields} FROM events WHERE event = 'json_event'",
- team=self.team,
- )
-
- # Verify no dmat columns used (sanity check)
- assert result_json.clickhouse is not None and "dmat_" not in result_json.clickhouse, (
- "Should use JSON extraction, not dmat"
- )
- json_results = result_json.results[0]
-
- # ============================================================
- # PHASE 2: Insert event with pre-filled dmat columns
- # ============================================================
- # Build INSERT statement with dmat columns computed via extraction SQL
- dmat_columns = []
- dmat_values = []
- for tc in TEST_CASES:
- dmat_columns.append(slot_mapping[tc.name]["col_name"])
- extraction_sql = _generate_property_extraction_sql(tc.type).replace("%(property_name)s", f"'{tc.name}'")
- dmat_values.append(extraction_sql)
-
- sync_execute(
- f"""
- INSERT INTO sharded_events (
- uuid, team_id, event, distinct_id, timestamp, properties,
- {", ".join(dmat_columns)}
- )
- SELECT
- %(uuid)s,
- %(team_id)s,
- 'dmat_event',
- 'user1',
- now(),
- %(properties)s,
- {", ".join(dmat_values)}
- FROM (SELECT %(properties)s as properties)
- """,
- {
- "team_id": self.team.pk,
- "properties": json.dumps(event_properties),
- "uuid": str(uuid.uuid4()),
- },
- flush=False,
- )
-
- # ============================================================
- # PHASE 3: Create slots and query with dmat columns
- # ============================================================
- # Create MaterializedColumnSlot records so PropertySwapper detects dmat columns
- for tc in TEST_CASES:
- MaterializedColumnSlot.objects.create(
- team=self.team,
- property_definition=prop_defs[tc.name],
- property_type=tc.type,
- slot_index=slot_mapping[tc.name]["slot_idx"],
- state=MaterializedColumnSlotState.READY,
- )
-
- result_dmat = execute_hogql_query(
- f"SELECT {select_fields} FROM events WHERE event = 'dmat_event'",
- team=self.team,
- )
-
- # Verify dmat columns ARE used
- assert result_dmat.clickhouse is not None and "dmat_" in result_dmat.clickhouse, (
- f"Should use dmat columns. SQL: {result_dmat.clickhouse}"
- )
- dmat_results = result_dmat.results[0]
-
- # ============================================================
- # VERIFICATION: Results must be identical
- # ============================================================
- if json_results != dmat_results:
- # Provide detailed comparison on failure
- failures = []
- for i, tc in enumerate(TEST_CASES):
- json_val = json_results[i]
- dmat_val = dmat_results[i]
- if json_val != dmat_val:
- failures.append(
- f" {tc.name} ({tc.type}):\n"
- f" Input: {tc.input_value!r}\n"
- f" JSON result: {json_val!r}\n"
- f" dmat result: {dmat_val!r}\n"
- f" dmat column: {slot_mapping[tc.name]['col_name']}"
- )
-
- raise AssertionError(
- f"dmat extraction differs from JSON extraction!\n\nMismatches:\n" + "\n".join(failures)
- )
diff --git a/posthog/migrations/1157_materializedcolumnslot_pending_and_expand_index.py b/posthog/migrations/1157_materializedcolumnslot_pending_and_expand_index.py
new file mode 100644
index 000000000000..47430be6219c
--- /dev/null
+++ b/posthog/migrations/1157_materializedcolumnslot_pending_and_expand_index.py
@@ -0,0 +1,130 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("posthog", "1156_cohort_team_filters_help_text")]
+
+ # Bundles two pre-shipping changes for MaterializedColumnSlot:
+ # 1) slot_index becomes nullable + range allows 0–9 + uniqueness becomes partial
+ # so multiple PENDING slots per team can coexist with no slot_index assigned.
+ # Slots are allocated per-team — every team picks freely from 0..9, and the dmat
+ # dictionary resolves (team_id, slot_index) → property_name at write/read time.
+ # 2) Drop property_type from Django state only — every dmat column is `Nullable(String)`;
+ # HogQL casts at read using prop_def.property_type instead. The DB column is left in
+ # place per safe-django-migrations.md (multi-phase column drop). A future migration
+ # can drop the column once all running code no longer references it.
+ #
+ # Companion migrations:
+ # - 1154_drop_property_type_not_null: DROP NOT NULL on the legacy `property_type`
+ # column so new code (which no longer sends it in INSERTs) doesn't violate the
+ # constraint. Split out of this migration because mixing RunSQL DDL with Django
+ # schema ops violates POSTHOG_POLICIES (RunSQL DDL and Django schema operations
+ # should be in separate migrations).
+ # - 1155_*_concurrent_index: AddIndexConcurrently for `(team, slot_index)`. Split
+ # out because mixing CONCURRENTLY with regular DDL also violates POSTHOG_POLICIES.
+ #
+ # Multi-phase rename of `backfill_temporal_workflow_id` → `backfill_temporal_run_id`:
+ # Phase 1 (this migration): add the new column, drop the old column's index, and remove the
+ # old field from Django state (column kept physically — Django no longer reads/writes it).
+ # Phase 2 (1156_*_concurrent): add the index on the new column via AddIndexConcurrently.
+ # Phase 3 (future migration): DROP COLUMN backfill_temporal_workflow_id once this PR has
+ # propagated through a full deployment cycle.
+ # dmat hasn't shipped yet so there's no in-flight data to copy between the old and new
+ # columns. We avoid `RenameField` because the migration risk analyzer hard-blocks it
+ # (score 4 BLOCKED, no override), while AddField + state-only RemoveField is Safe (score 1).
+
+ operations = [
+ migrations.RemoveConstraint(
+ model_name="materializedcolumnslot",
+ name="valid_slot_index",
+ ),
+ migrations.RemoveConstraint(
+ model_name="materializedcolumnslot",
+ name="unique_team_property_type_slot_index",
+ ),
+ migrations.RemoveIndex(
+ model_name="materializedcolumnslot",
+ name="posthog_mat_team_ty_idx",
+ ),
+ # Drop property_type from Django state only — column stays in DB so old code that
+ # still references it during the deployment cycle keeps working. The companion
+ # migration 1154_drop_property_type_not_null then removes the NOT NULL constraint
+ # so new code's INSERTs (which no longer include `property_type`) are accepted.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RemoveField(
+ model_name="materializedcolumnslot",
+ name="property_type",
+ ),
+ ],
+ database_operations=[],
+ ),
+ # Slot index becomes nullable for PENDING and ranges 0–9.
+ migrations.AlterField(
+ model_name="materializedcolumnslot",
+ name="slot_index",
+ field=models.PositiveSmallIntegerField(null=True, blank=True),
+ ),
+ migrations.AlterField(
+ model_name="materializedcolumnslot",
+ name="state",
+ field=models.CharField(
+ max_length=20,
+ choices=[
+ ("PENDING", "Pending"),
+ ("BACKFILL", "Backfill"),
+ ("READY", "Ready"),
+ ("ERROR", "Error"),
+ ],
+ default="PENDING",
+ ),
+ ),
+ # Re-add constraints in the new (property_type-free) shape.
+ migrations.AddConstraint(
+ model_name="materializedcolumnslot",
+ constraint=models.UniqueConstraint(
+ fields=("team", "slot_index"),
+ name="unique_team_slot_index",
+ condition=models.Q(slot_index__isnull=False),
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="materializedcolumnslot",
+ constraint=models.CheckConstraint(
+ name="valid_slot_index",
+ condition=models.Q(slot_index__isnull=True)
+ | (models.Q(slot_index__gte=0) & models.Q(slot_index__lte=9)),
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="materializedcolumnslot",
+ constraint=models.CheckConstraint(
+ name="slot_index_required_when_assigned",
+ condition=models.Q(state="PENDING") | models.Q(state="ERROR") | models.Q(slot_index__isnull=False),
+ ),
+ ),
+ # Add the new column. Old column kept in DB until a follow-up migration drops it
+ # (multi-phase column drop — RemoveField score-5 needs its own migration after deploy).
+ migrations.AddField(
+ model_name="materializedcolumnslot",
+ name="backfill_temporal_run_id",
+ field=models.CharField(max_length=400, null=True, blank=True),
+ ),
+ # Drop the index that covered the old column. No code reads or writes the old column
+ # after this migration so there's no benefit to keeping its index around.
+ migrations.RemoveIndex(
+ model_name="materializedcolumnslot",
+ name="posthog_mat_backfi_idx",
+ ),
+ # Remove the old field from Django state only. The physical column stays in Postgres
+ # so a future migration can DROP it without a cross-deploy compat hazard.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RemoveField(
+ model_name="materializedcolumnslot",
+ name="backfill_temporal_workflow_id",
+ ),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/posthog/migrations/1158_drop_property_type_not_null.py b/posthog/migrations/1158_drop_property_type_not_null.py
new file mode 100644
index 000000000000..3f872e0f957e
--- /dev/null
+++ b/posthog/migrations/1158_drop_property_type_not_null.py
@@ -0,0 +1,25 @@
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ # Companion to 1157, which removed `property_type` from Django model state. New code
+ # no longer sends `property_type` in INSERTs into `posthog_materializedcolumnslot`,
+ # but the underlying DB column was created with NOT NULL. Drop the constraint so
+ # those INSERTs succeed.
+ #
+ # Lives in its own migration per POSTHOG_POLICIES — RunSQL DDL and Django schema
+ # operations should not share a migration.
+ #
+ # The column itself remains so old code (still running between deploy phases) can
+ # continue writing to it. A future migration can DROP the column entirely once a
+ # full deployment cycle has elapsed (the analyzer recognises the prior 1157
+ # SeparateDatabaseAndState as a properly-staged state removal at that point).
+
+ dependencies = [("posthog", "1157_materializedcolumnslot_pending_and_expand_index")]
+
+ operations = [
+ migrations.RunSQL(
+ sql='ALTER TABLE "posthog_materializedcolumnslot" ALTER COLUMN "property_type" DROP NOT NULL',
+ reverse_sql='ALTER TABLE "posthog_materializedcolumnslot" ALTER COLUMN "property_type" SET NOT NULL',
+ ),
+ ]
diff --git a/posthog/migrations/1159_materializedcolumnslot_team_slot_index_concurrent.py b/posthog/migrations/1159_materializedcolumnslot_team_slot_index_concurrent.py
new file mode 100644
index 000000000000..6f6a8fc6386a
--- /dev/null
+++ b/posthog/migrations/1159_materializedcolumnslot_team_slot_index_concurrent.py
@@ -0,0 +1,16 @@
+from django.contrib.postgres.operations import AddIndexConcurrently
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ # `AddIndexConcurrently` requires atomic=False. Lives in its own migration per
+ # PostHog policy (don't mix CONCURRENTLY operations with regular DDL).
+ atomic = False
+ dependencies = [("posthog", "1158_drop_property_type_not_null")]
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="materializedcolumnslot",
+ index=models.Index(fields=["team", "slot_index"], name="posthog_mat_team_sl_idx"),
+ ),
+ ]
diff --git a/posthog/migrations/1160_materializedcolumnslot_run_id_concurrent_idx.py b/posthog/migrations/1160_materializedcolumnslot_run_id_concurrent_idx.py
new file mode 100644
index 000000000000..a25178b53533
--- /dev/null
+++ b/posthog/migrations/1160_materializedcolumnslot_run_id_concurrent_idx.py
@@ -0,0 +1,16 @@
+from django.contrib.postgres.operations import AddIndexConcurrently
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ # `AddIndexConcurrently` requires atomic=False. Lives in its own migration per
+ # PostHog policy (don't mix CONCURRENTLY operations with regular DDL).
+ atomic = False
+ dependencies = [("posthog", "1159_materializedcolumnslot_team_slot_index_concurrent")]
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="materializedcolumnslot",
+ index=models.Index(fields=["backfill_temporal_run_id"], name="posthog_mat_run_id_idx"),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 5eb0a9f7bbcb..c49c2a02c024 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1156_cohort_team_filters_help_text
+1160_materializedcolumnslot_run_id_concurrent_idx
diff --git a/posthog/models/dmat_slot_assignments/sql.py b/posthog/models/dmat_slot_assignments/sql.py
new file mode 100644
index 000000000000..aa6a39077ad5
--- /dev/null
+++ b/posthog/models/dmat_slot_assignments/sql.py
@@ -0,0 +1,108 @@
+"""ClickHouse schema for the dmat slot-assignments dictionary.
+
+The weekly dmat backfill workflow writes the current `(team_id, column_index) →
+property_name` mapping into `dmat_slot_assignments` and then reloads the
+`dmat_slot_assignments_dict` dictionary on every host. The mutation that
+follows reads the mapping via `dictGetString` / `dictHas`, which keeps the
+mutation SQL constant-size regardless of how many teams have adopted dmat.
+
+Pattern mirrors `posthog/models/web_preaggregated/team_selection.py` —
+ReplacingMergeTree backing table + CLICKHOUSE-source dictionary, created
+per-host via `run_sql_with_exceptions`. Differs from that pattern in one
+place: we use TRUNCATE+INSERT every
+cycle rather than append-only, because dmat slots can be deleted or reset
+and append-only would leave stale rows in the dict that silently overwrite
+columns no longer assigned to that (team, slot_index).
+"""
+
+from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE
+from posthog.clickhouse.table_engines import ReplacingMergeTree, ReplicationScheme
+from posthog.settings.data_stores import CLICKHOUSE_DATABASE, CLICKHOUSE_PASSWORD, CLICKHOUSE_USER
+
+DMAT_SLOT_ASSIGNMENTS_TABLE_NAME = "dmat_slot_assignments"
+DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME = "dmat_slot_assignments_dict"
+
+
+def DMAT_SLOT_ASSIGNMENTS_TABLE_SQL(on_cluster: bool = False) -> str:
+ # NOT_SHARDED → plain `ReplacingMergeTree` (no ZK/replication), so each host
+ # gets a truly independent local table. This is what makes the per-host
+ # TRUNCATE+INSERT pattern in `populate_slot_assignments` correct: writes on
+ # host A don't replicate to hosts B/C/D, so concurrent populates don't race.
+ return """
+CREATE TABLE IF NOT EXISTS {table_name} {on_cluster_clause} (
+ team_id UInt64,
+ column_index UInt8,
+ property_name String,
+ version UInt32 DEFAULT toUnixTimestamp(now())
+) ENGINE = {engine}
+ORDER BY (team_id, column_index);
+""".format(
+ on_cluster_clause=ON_CLUSTER_CLAUSE(on_cluster),
+ table_name=f"`{DMAT_SLOT_ASSIGNMENTS_TABLE_NAME}`",
+ engine=ReplacingMergeTree(
+ DMAT_SLOT_ASSIGNMENTS_TABLE_NAME,
+ replication_scheme=ReplicationScheme.NOT_SHARDED,
+ ver="version",
+ ),
+ )
+
+
+def DMAT_SLOT_ASSIGNMENTS_DICTIONARY_QUERY() -> str:
+ # FINAL collapses ReplacingMergeTree versions; the populate activity uses
+ # TRUNCATE+INSERT so there is normally only one version per (team_id,
+ # column_index) per cycle, but FINAL is still required during the brief
+ # window where merges have not yet caught up to a fresh insert.
+ return f"""
+SELECT
+ team_id,
+ column_index,
+ property_name
+FROM
+ `{CLICKHOUSE_DATABASE}`.`{DMAT_SLOT_ASSIGNMENTS_TABLE_NAME}`
+FINAL
+""".replace("\n", " ").strip()
+
+
+def DMAT_SLOT_ASSIGNMENTS_DICTIONARY_SQL(on_cluster: bool = False) -> str:
+ return """
+CREATE DICTIONARY IF NOT EXISTS {dictionary_name} {on_cluster_clause} (
+ team_id UInt64,
+ column_index UInt8,
+ property_name String
+)
+PRIMARY KEY team_id, column_index
+SOURCE(CLICKHOUSE(QUERY '{query}' USER '{clickhouse_user}' PASSWORD '{clickhouse_password}'))
+LIFETIME(MIN 600 MAX 1200)
+LAYOUT(COMPLEX_KEY_HASHED())""".format(
+ dictionary_name=f"`{DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME}`",
+ on_cluster_clause=ON_CLUSTER_CLAUSE(on_cluster),
+ query=DMAT_SLOT_ASSIGNMENTS_DICTIONARY_QUERY(),
+ clickhouse_user=CLICKHOUSE_USER,
+ clickhouse_password=CLICKHOUSE_PASSWORD,
+ )
+
+
+def DROP_DMAT_SLOT_ASSIGNMENTS_DICTIONARY_SQL(on_cluster: bool = False) -> str:
+ return (
+ f"DROP DICTIONARY IF EXISTS `{DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME}` {ON_CLUSTER_CLAUSE(on_cluster)}".strip()
+ )
+
+
+def DROP_DMAT_SLOT_ASSIGNMENTS_TABLE_SQL(on_cluster: bool = False) -> str:
+ return f"DROP TABLE IF EXISTS `{DMAT_SLOT_ASSIGNMENTS_TABLE_NAME}` {ON_CLUSTER_CLAUSE(on_cluster)}".strip()
+
+
+def TRUNCATE_DMAT_SLOT_ASSIGNMENTS_SQL() -> str:
+ # No ON CLUSTER — the populate activity calls TRUNCATE on every host via
+ # `cluster.map_all_hosts(...)`, which gives each host a deterministic local
+ # truncation. Adding ON CLUSTER would have every host issue a cluster-wide
+ # TRUNCATE, multiplying ZK chatter for no benefit.
+ return f"TRUNCATE TABLE `{DMAT_SLOT_ASSIGNMENTS_TABLE_NAME}`"
+
+
+def INSERT_DMAT_SLOT_ASSIGNMENTS_SQL() -> str:
+ return f"INSERT INTO `{DMAT_SLOT_ASSIGNMENTS_TABLE_NAME}` (team_id, column_index, property_name) VALUES"
+
+
+def RELOAD_DMAT_SLOT_ASSIGNMENTS_DICTIONARY_SQL() -> str:
+ return f"SYSTEM RELOAD DICTIONARY `{DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME}`"
diff --git a/posthog/models/event/sql.py b/posthog/models/event/sql.py
index 1ed0870797db..579206b98e3c 100644
--- a/posthog/models/event/sql.py
+++ b/posthog/models/event/sql.py
@@ -72,62 +72,29 @@ CREATE TABLE IF NOT EXISTS {table_name} {on_cluster_clause}
"""
-def EVENTS_TABLE_DYNAMICALLY_MATERIALIZED_COLUMNS() -> str:
- s = []
-
- # Add string columns (0-9)
- for i in range(10):
- s.append(f"`dmat_string_{i}` Nullable(String)")
-
- # Add numeric columns (0-9)
- for i in range(10):
- s.append(f"`dmat_numeric_{i}` Nullable(Float64)")
-
- # Add bool columns (0-9)
- for i in range(10):
- s.append(f"`dmat_bool_{i}` Nullable(UInt8)")
+# Shared per-team allocation: each team picks its slots independently from this range, and
+# (team_id, slot_index) → property_name is resolved at write/read time via the dmat dictionary.
+# Cap matches MAX_SLOTS_PER_TEAM so every team can fully saturate its slots.
+DMAT_STRING_COLUMN_COUNT = 10
- # Add datetime columns (0-9)
- for i in range(10):
- s.append(f"`dmat_datetime_{i}` Nullable(DateTime64(6, 'UTC'))")
+def EVENTS_TABLE_DYNAMICALLY_MATERIALIZED_COLUMNS() -> str:
+ s = [f"`dmat_string_{i}` Nullable(String)" for i in range(DMAT_STRING_COLUMN_COUNT)]
return f" , {'\n , '.join(s)}"
def ALTER_TABLE_ADD_DYNAMICALLY_MATERIALIZED_COLUMNS(table: str) -> str:
- s = []
-
- # Add string columns (0-9)
- for i in range(10):
- s.append(f"ADD COLUMN IF NOT EXISTS `dmat_string_{i}` Nullable(String)")
-
- # Add numeric columns (0-9)
- for i in range(10):
- s.append(f"ADD COLUMN IF NOT EXISTS `dmat_numeric_{i}` Nullable(Float64)")
-
- # Add bool columns (0-9)
- for i in range(10):
- s.append(f"ADD COLUMN IF NOT EXISTS `dmat_bool_{i}` Nullable(UInt8)")
+ return ALTER_TABLE_ADD_DMAT_STRING_COLUMNS(table, 0, DMAT_STRING_COLUMN_COUNT)
- # Add datetime columns (0-9)
- for i in range(10):
- s.append(f"ADD COLUMN IF NOT EXISTS `dmat_datetime_{i}` Nullable(DateTime64(6, 'UTC'))")
- separator = ",\n"
- return f"ALTER TABLE {table} \n {separator.join(s)}"
+def ALTER_TABLE_ADD_DMAT_STRING_COLUMNS(table: str, start: int, end_exclusive: int) -> str:
+ """ALTER TABLE statement adding dmat_string columns in a half-open index range."""
+ pieces = [f"ADD COLUMN IF NOT EXISTS `dmat_string_{i}` Nullable(String)" for i in range(start, end_exclusive)]
+ return f"ALTER TABLE {table} \n {',\n'.join(pieces)}"
def MV_DYNAMICALLY_MATERIALIZED_COLUMNS() -> str:
- s = []
- for i in range(10):
- s.append(f"dmat_string_{i}")
- for i in range(10):
- s.append(f"dmat_numeric_{i}")
- for i in range(10):
- s.append(f"dmat_bool_{i}")
- for i in range(10):
- s.append(f"dmat_datetime_{i}")
- return ",\n".join(s)
+ return ",\n".join(f"dmat_string_{i}" for i in range(DMAT_STRING_COLUMN_COUNT))
EVENTS_TABLE_MATERIALIZED_COLUMNS = f"""
diff --git a/posthog/models/materialized_column_slots.py b/posthog/models/materialized_column_slots.py
index 4d2d70d4cc3d..9aa6c6bf4b89 100644
--- a/posthog/models/materialized_column_slots.py
+++ b/posthog/models/materialized_column_slots.py
@@ -1,17 +1,27 @@
-from django.core.exceptions import ValidationError
from django.db import models
-from django.db.models.signals import pre_save
-from django.dispatch import receiver
+from posthog.models.event.sql import DMAT_STRING_COLUMN_COUNT
from posthog.models.team import Team
from posthog.models.utils import UUIDTModel
-from products.event_definitions.backend.models import PropertyDefinition, PropertyType
+from products.event_definitions.backend.models import PropertyDefinition
+
+# Single source of truth is the physical dmat_string pool size in event/sql.py. Per-team
+# cap equals pool size because slots are allocated per-team and indices are shared across
+# teams (the dmat dict resolves (team_id, slot_index) -> property_name at write/read time).
+MAX_SLOTS_PER_TEAM = DMAT_STRING_COLUMN_COUNT
+MAX_SLOT_INDEX = MAX_SLOTS_PER_TEAM - 1
class MaterializedColumnSlotState(models.TextChoices):
+ # PENDING: queued for the next weekly backfill cycle. No ingestion writes, no query reads.
+ PENDING = "PENDING", "Pending"
+ # BACKFILL: assigned a slot_index; ingestion writes new events but historical backfill is in flight.
+ # Query reads still use JSON until READY to avoid serving partial data.
BACKFILL = "BACKFILL", "Backfill"
+ # READY: backfill complete; HogQL serves reads from the dmat column.
READY = "READY", "Ready"
+ # ERROR: backfill failed; can be retried by transitioning back to PENDING.
ERROR = "ERROR", "Error"
@@ -31,15 +41,23 @@ class MaterializedColumnSlot(UUIDTModel):
related_name="materialized_column_slots",
related_query_name="materialized_column_slot",
)
- # Denormalized from PropertyDefinition for efficient constraints and queries
- property_type = models.CharField(max_length=50, choices=PropertyType)
- slot_index = models.PositiveSmallIntegerField()
+ # Null while in PENDING — assigned by the weekly backfill workflow when the slot transitions
+ # to BACKFILL. The unique constraint on (team, slot_index) only applies to rows with a
+ # non-null slot_index, so multiple PENDING slots can coexist without conflict.
+ slot_index = models.PositiveSmallIntegerField(null=True, blank=True)
state = models.CharField(
max_length=20,
choices=MaterializedColumnSlotState,
- default=MaterializedColumnSlotState.BACKFILL,
+ default=MaterializedColumnSlotState.PENDING,
+ )
+ # Temporal run_id of the workflow execution that owns this slot's current BACKFILL transition.
+ # The weekly schedule reuses one workflow_id, so run_id (unique per execution, stable across
+ # activity retries) is what the assign activity uses for idempotency and stranded-slot detection.
+ backfill_temporal_run_id = models.CharField(
+ max_length=400,
+ null=True,
+ blank=True,
)
- backfill_temporal_workflow_id = models.CharField(max_length=400, null=True, blank=True)
error_message = models.TextField(null=True, blank=True)
class Meta:
@@ -48,48 +66,35 @@ class MaterializedColumnSlot(UUIDTModel):
fields=["team", "property_definition"],
name="unique_team_property_definition",
),
+ # Per-team uniqueness on the assigned column index. The dmat_string_<idx> columns
+ # are shared across teams (one column physically; the dmat dict resolves
+ # (team_id, slot_index) → property_name per row), but within a team each slot
+ # must own a distinct index.
models.UniqueConstraint(
- fields=["team", "property_type", "slot_index"],
- name="unique_team_property_type_slot_index",
+ fields=["team", "slot_index"],
+ name="unique_team_slot_index",
+ condition=models.Q(slot_index__isnull=False),
),
models.CheckConstraint(
name="valid_slot_index",
- condition=models.Q(slot_index__gte=0) & models.Q(slot_index__lte=9),
+ condition=models.Q(slot_index__isnull=True)
+ | (models.Q(slot_index__gte=0) & models.Q(slot_index__lte=MAX_SLOT_INDEX)),
+ ),
+ models.CheckConstraint(
+ name="slot_index_required_when_assigned",
+ condition=(
+ models.Q(state=MaterializedColumnSlotState.PENDING)
+ | models.Q(state=MaterializedColumnSlotState.ERROR)
+ | models.Q(slot_index__isnull=False)
+ ),
),
]
indexes = [
models.Index(fields=["team", "state"], name="posthog_mat_team_st_idx"),
models.Index(fields=["team", "property_definition"], name="posthog_mat_team_pr_idx"),
- models.Index(fields=["team", "property_type", "slot_index"], name="posthog_mat_team_ty_idx"),
- models.Index(fields=["backfill_temporal_workflow_id"], name="posthog_mat_backfi_idx"),
+ models.Index(fields=["team", "slot_index"], name="posthog_mat_team_sl_idx"),
+ models.Index(fields=["backfill_temporal_run_id"], name="posthog_mat_run_id_idx"),
]
- def save(self, *args, **kwargs):
- # Sync property_type from property_definition on save
- if self.property_definition_id and not self.property_type:
- self.property_type = self.property_definition.property_type # type: ignore[assignment]
- super().save(*args, **kwargs)
-
def __str__(self) -> str:
- return f"{self.property_definition.name} ({self.property_type}) -> slot {self.slot_index} ({self.state})"
-
-
-@receiver(pre_save, sender=PropertyDefinition)
-def prevent_property_type_changes_with_materialized_slots(sender, instance, **kwargs):
- """
- Prevent changing property_type on a PropertyDefinition if it has any
- MaterializedColumnSlot records, since the property_type is part of the
- slot allocation constraint.
- """
- if instance.pk: # Only for updates, not creates
- try:
- old_instance = PropertyDefinition.objects.get(pk=instance.pk)
- if old_instance.property_type != instance.property_type:
- # Check if this property has any materialized slots
- if MaterializedColumnSlot.objects.filter(property_definition=instance).exists():
- raise ValidationError(
- f"Cannot change property_type for '{instance.name}' because it has materialized column slots. "
- "Delete the materialized slots first."
- )
- except PropertyDefinition.DoesNotExist:
- pass
+ return f"{self.property_definition.name} -> slot {self.slot_index} ({self.state})"
diff --git a/posthog/temporal/tests/backfill_materialized_property/conftest.py b/posthog/temporal/tests/backfill_materialized_property/conftest.py
deleted file mode 100644
index 82cc7bd83c30..000000000000
--- a/posthog/temporal/tests/backfill_materialized_property/conftest.py
+++ /dev/null
@@ -1,127 +0,0 @@
-"""Fixtures for materialized property backfill tests."""
-
-import random
-
-import pytest
-
-import pytest_asyncio
-from asgiref.sync import sync_to_async
-
-from posthog.models import MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition
-
-from products.event_definitions.backend.models.property_definition import PropertyType
-
-
-def property_definition(team):
- """Create a test property definition."""
- return PropertyDefinition.objects.create(
- team=team,
- name=f"test_property_{random.randint(1, 99999)}",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
-
-
-def string_property_definition(team):
- """Create a String type property definition."""
- return PropertyDefinition.objects.create(
- team=team,
- name=f"string_prop_{random.randint(1, 99999)}",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
-
-
-def numeric_property_definition(team):
- """Create a Numeric type property definition."""
- return PropertyDefinition.objects.create(
- team=team,
- name=f"numeric_prop_{random.randint(1, 99999)}",
- property_type=PropertyType.Numeric,
- type=PropertyDefinition.Type.EVENT,
- )
-
-
-def boolean_property_definition(team):
- """Create a Boolean type property definition."""
- return PropertyDefinition.objects.create(
- team=team,
- name=f"bool_prop_{random.randint(1, 99999)}",
- property_type=PropertyType.Boolean,
- type=PropertyDefinition.Type.EVENT,
- )
-
-
-def datetime_property_definition(team):
- """Create a DateTime type property definition."""
- return PropertyDefinition.objects.create(
- team=team,
- name=f"datetime_prop_{random.randint(1, 99999)}",
- property_type=PropertyType.Datetime,
- type=PropertyDefinition.Type.EVENT,
- )
-
-
-def materialized_slot(team, property_definition):
- """Create a test materialized column slot in BACKFILL state."""
- return MaterializedColumnSlot.objects.create(
- team=team,
- property_definition=property_definition,
- property_type=property_definition.property_type,
- slot_index=0,
- state=MaterializedColumnSlotState.BACKFILL,
- )
-
-
-def materialized_slot_ready(team, property_definition):
- """Create a test materialized column slot in READY state."""
- return MaterializedColumnSlot.objects.create(
- team=team,
- property_definition=property_definition,
- property_type=property_definition.property_type,
- slot_index=0,
- state=MaterializedColumnSlotState.READY,
- )
-
-
-def materialized_slot_error(team, property_definition):
- """Create a test materialized column slot in ERROR state."""
- return MaterializedColumnSlot.objects.create(
- team=team,
- property_definition=property_definition,
- property_type=property_definition.property_type,
- slot_index=0,
- state=MaterializedColumnSlotState.ERROR,
- error_message="Test error message",
- )
-
-
-@pytest_asyncio.fixture
-async def aproperty_definition(ateam):
- """Create a test property definition (async)."""
- return await sync_to_async(PropertyDefinition.objects.create)(
- team=ateam,
- name=f"test_property_{random.randint(1, 99999)}",
- property_type=PropertyType.String,
- type=PropertyDefinition.Type.EVENT,
- )
-
-
-@pytest_asyncio.fixture
-async def amaterialized_slot(ateam, aproperty_definition):
- """Create a test materialized column slot (async)."""
- return await sync_to_async(MaterializedColumnSlot.objects.create)(
- team=ateam,
- property_definition=aproperty_definition,
- property_type=aproperty_definition.property_type,
- slot_index=0,
- state=MaterializedColumnSlotState.BACKFILL,
- )
diff --git a/posthog/temporal/tests/backfill_materialized_property/test_activities.py b/posthog/temporal/tests/backfill_materialized_property/test_activities.py
deleted file mode 100644
index 54815ce5913d..000000000000
--- a/posthog/temporal/tests/backfill_materialized_property/test_activities.py
+++ /dev/null
@@ -1,372 +0,0 @@
-"""Tests for backfill materialized property activities."""
-
-import uuid
-
-import pytest
-from posthog.test.base import _create_event, flush_persons_and_events
-from unittest.mock import patch
-
-from posthog.clickhouse.client import sync_execute
-from posthog.models import MaterializedColumnSlotState
-from posthog.temporal.backfill_materialized_property.activities import (
- BackfillMaterializedColumnInputs,
- UpdateSlotStateInputs,
- _generate_property_extraction_sql,
- backfill_materialized_column,
- update_slot_state,
-)
-
-from products.event_definitions.backend.models.property_definition import PropertyType
-
-
[email protected]_db(transaction=True)
-class TestPropertyExtractionSQL:
- """Test SQL generation for extracting properties."""
-
- @pytest.mark.parametrize(
- "property_type,expected_fragments",
- [
- # String type uses base extraction with nullIf handling (HogQL pattern)
- ("String", ["replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, %(property_name)s)", "'null')"]),
- ("Numeric", ["toFloat64OrNull("]),
- ("Boolean", ["transform(toString(", "['true', 'false'], [1, 0], NULL)"]),
- ("DateTime", ["parseDateTime64BestEffortOrNull(", ", 6)"]),
- ],
- )
- def test_property_extraction_sql_generation(
- self,
- property_type,
- expected_fragments,
- ):
- """Test that SQL uses parameterized placeholder for property_name."""
- sql = _generate_property_extraction_sql(property_type)
- for fragment in expected_fragments:
- assert fragment in sql, f"Expected '{fragment}' in SQL: {sql}"
- # All types should use the parameterized placeholder
- assert "%(property_name)s" in sql, f"Expected parameterized property_name in SQL: {sql}"
-
- def test_property_extraction_unsupported_type(self):
- """Test that unsupported property types raise error."""
- with pytest.raises(ValueError, match="Unsupported property type"):
- _generate_property_extraction_sql("UnsupportedType")
-
-
[email protected]_db(transaction=True)
-class TestBackfillMaterializedColumn:
- """Test backfill_materialized_column activity."""
-
- @pytest.mark.parametrize(
- "property_name",
- [
- "test'prop", # Single quote - would break unparameterized SQL
- 'test"prop', # Double quote
- "test\\prop", # Backslash
- "$feature/my-flag", # Feature flag format with special chars
- "prop'); DROP TABLE events; --", # SQL injection attempt
- ],
- )
- @patch("posthog.temporal.backfill_materialized_property.activities.get_cluster")
- def test_property_name_is_parameterized_not_interpolated(
- self, mock_get_cluster, activity_environment, property_name
- ):
- """Test that property names are parameterized, preventing SQL injection."""
- from unittest.mock import MagicMock
-
- mock_cluster = mock_get_cluster.return_value
- mock_cluster.map_one_host_per_shard.return_value.result.return_value = {}
-
- activity_environment.run(
- backfill_materialized_column,
- BackfillMaterializedColumnInputs(
- team_id=123,
- property_name=property_name,
- property_type="String",
- mat_column_name="dmat_string_0",
- ),
- )
-
- # Get the function passed to map_one_host_per_shard and call it with a mock client
- run_mutation_fn = mock_cluster.map_one_host_per_shard.call_args[0][0]
- mock_client = MagicMock()
- run_mutation_fn(mock_client)
-
- # Check what client.execute was called with
- call_args = mock_client.execute.call_args
- query = call_args[0][0]
- params = call_args[0][1]
-
- # Property name should NEVER be in the SQL query directly
- assert property_name not in query, f"Property name '{property_name}' should not be in SQL: {query}"
- # It should use a parameterized placeholder
- assert "%(property_name)s" in query
- # And the actual value should be in params
- assert params["property_name"] == property_name
- # Should use mutations_sync=1
- assert call_args[1]["settings"]["mutations_sync"] == 1
-
-
[email protected]_db(transaction=True)
-class TestUpdateSlotState:
- """Test update_slot_state activity."""
-
- @pytest.mark.parametrize(
- "new_state,error_message",
- [
- ("READY", None),
- ("ERROR", "Something went wrong"),
- ("BACKFILL", None),
- ],
- )
- def test_update_slot_state(
- self,
- materialized_slot,
- activity_environment,
- new_state,
- error_message,
- ):
- """Test updating slot state."""
- result = activity_environment.run(
- update_slot_state,
- UpdateSlotStateInputs(
- slot_id=str(materialized_slot.id),
- state=new_state,
- error_message=error_message,
- ),
- )
-
- assert result is True
-
- # Verify state was updated
- materialized_slot.refresh_from_db()
- assert materialized_slot.state == new_state
-
- if error_message:
- assert materialized_slot.error_message == error_message
-
- def test_update_slot_state_clears_error_on_backfill(self, materialized_slot_error, activity_environment):
- """Test that transitioning to BACKFILL clears error_message."""
- assert materialized_slot_error.error_message is not None
-
- activity_environment.run(
- update_slot_state,
- UpdateSlotStateInputs(
- slot_id=str(materialized_slot_error.id),
- state="BACKFILL",
- ),
- )
-
- materialized_slot_error.refresh_from_db()
- assert materialized_slot_error.state == MaterializedColumnSlotState.BACKFILL
- assert materialized_slot_error.error_message is None
-
- def test_update_slot_state_not_found(self, activity_environment):
- """Test that activity returns False when slot not found."""
- result = activity_environment.run(
- update_slot_state,
- UpdateSlotStateInputs(
- slot_id="00000000-0000-0000-0000-000000000000",
- state="READY",
- ),
- )
-
- assert result is False
-
-
[email protected]_db(transaction=True)
-class TestBackfillMaterializedColumnClickHouse:
- """Integration tests that run against real ClickHouse."""
-
- @pytest.mark.parametrize(
- "property_type,property_value,mat_column,expected_value",
- [
- (PropertyType.String, "hello_world", "dmat_string_0", "hello_world"),
- (PropertyType.Numeric, "42.5", "dmat_numeric_0", 42.5),
- (PropertyType.Boolean, "true", "dmat_bool_0", 1),
- (PropertyType.Boolean, "false", "dmat_bool_0", 0),
- ],
- )
- def test_backfill_populates_materialized_column(
- self,
- team,
- activity_environment,
- property_type,
- property_value,
- mat_column,
- expected_value,
- ):
- """
- Test that backfill activity actually populates dmat columns in ClickHouse.
-
- 1. Insert event with property (dmat column will be empty)
- 2. Run backfill activity
- 3. Verify dmat column is now populated
- """
- property_name = f"test_prop_{uuid.uuid4().hex[:8]}"
- event_uuid = _create_event(
- team=team,
- event="$test_event",
- distinct_id="test_user",
- properties={property_name: property_value},
- )
- flush_persons_and_events()
-
- # Verify dmat column is empty before backfill
- result_before = sync_execute(
- f"SELECT {mat_column} FROM sharded_events WHERE uuid = %(uuid)s AND team_id = %(team_id)s",
- {"uuid": event_uuid, "team_id": team.id},
- )
- # Empty string for String, 0 for Numeric, 0 for Bool
- assert result_before[0][0] in ("", 0, None), f"{mat_column} should be empty before backfill"
-
- # Run backfill
- activity_environment.run(
- backfill_materialized_column,
- BackfillMaterializedColumnInputs(
- team_id=team.id,
- property_name=property_name,
- property_type=str(property_type),
- mat_column_name=mat_column,
- ),
- )
-
- # Verify dmat column is now populated
- result_after = sync_execute(
- f"SELECT {mat_column} FROM sharded_events WHERE uuid = %(uuid)s AND team_id = %(team_id)s",
- {"uuid": event_uuid, "team_id": team.id},
- )
- assert result_after[0][0] == expected_value, (
- f"{mat_column} should be {expected_value}, got {result_after[0][0]}"
- )
-
- @pytest.mark.parametrize(
- "property_name",
- [
- "test'prop", # Single quote
- 'test"prop', # Double quote
- "test\\prop", # Backslash
- "$feature/my-flag", # Feature flag format
- "prop with spaces", # Spaces
- "emoji_🎉_prop", # Unicode
- ],
- )
- def test_backfill_handles_special_characters_in_property_name(self, team, activity_environment, property_name):
- """Test that property names with special characters work correctly in ClickHouse."""
- expected_value = "test_value"
- event_uuid = _create_event(
- team=team,
- event="$test_event",
- distinct_id="test_user",
- properties={property_name: expected_value},
- )
- flush_persons_and_events()
-
- # Run backfill
- activity_environment.run(
- backfill_materialized_column,
- BackfillMaterializedColumnInputs(
- team_id=team.id,
- property_name=property_name,
- property_type=str(PropertyType.String),
- mat_column_name="dmat_string_0",
- ),
- )
-
- # Verify backfill worked
- result = sync_execute(
- "SELECT dmat_string_0 FROM sharded_events WHERE uuid = %(uuid)s AND team_id = %(team_id)s",
- {"uuid": event_uuid, "team_id": team.id},
- )
- assert result[0][0] == expected_value, f"Backfill should work for property name: {property_name}"
-
- def test_backfill_handles_missing_property(self, team, activity_environment):
- """Test that backfill leaves dmat column empty when property doesn't exist on event."""
- property_name = f"nonexistent_prop_{uuid.uuid4().hex[:8]}"
-
- # Insert event WITHOUT the property
- event_uuid = _create_event(
- team=team,
- event="$test_event",
- distinct_id="test_user",
- properties={"other_prop": "value"},
- )
- flush_persons_and_events()
-
- # Run backfill for a property that doesn't exist on this event
- activity_environment.run(
- backfill_materialized_column,
- BackfillMaterializedColumnInputs(
- team_id=team.id,
- property_name=property_name,
- property_type=str(PropertyType.String),
- mat_column_name="dmat_string_0",
- ),
- )
-
- # Verify dmat column is NULL (extraction SQL returns NULL for missing properties)
- result = sync_execute(
- "SELECT dmat_string_0 FROM sharded_events WHERE uuid = %(uuid)s AND team_id = %(team_id)s",
- {"uuid": event_uuid, "team_id": team.id},
- )
- assert result[0][0] is None, "dmat_string_0 should be NULL for missing property"
-
- def test_backfill_only_affects_team_events(self, team, organization, activity_environment):
- """Test that backfill only updates events for the specified team."""
- from posthog.models import Team
-
- # Create a second team
- other_team = Team.objects.create(organization=organization, name="Other Team")
-
- property_name = f"test_prop_{uuid.uuid4().hex[:8]}"
-
- # Insert events for both teams
- event_uuid_team1 = _create_event(
- team=team,
- event="$test_event",
- distinct_id="test_user",
- properties={property_name: "test_value"},
- )
- event_uuid_team2 = _create_event(
- team=other_team,
- event="$test_event",
- distinct_id="test_user",
- properties={property_name: "test_value"},
- )
- flush_persons_and_events()
-
- # Run backfill only for team1
- activity_environment.run(
- backfill_materialized_column,
- BackfillMaterializedColumnInputs(
- team_id=team.id,
- property_name=property_name,
- property_type=str(PropertyType.String),
- mat_column_name="dmat_string_0",
- ),
- )
-
- # Verify team1's event was backfilled
- result_team1 = sync_execute(
- "SELECT dmat_string_0 FROM sharded_events WHERE uuid = %(uuid)s AND team_id = %(team_id)s",
- {"uuid": event_uuid_team1, "team_id": team.id},
- )
- assert result_team1[0][0] == "test_value", "team1 event should be backfilled"
-
- # Verify team2's event was NOT backfilled (column stays at default NULL)
- result_team2 = sync_execute(
- "SELECT dmat_string_0 FROM sharded_events WHERE uuid = %(uuid)s AND team_id = %(team_id)s",
- {"uuid": event_uuid_team2, "team_id": other_team.id},
- )
- assert result_team2[0][0] is None, "team2 event should NOT be backfilled"
-
- def test_backfill_invalid_property_type_raises_error(self, team, activity_environment):
- """Test that an invalid property type raises an error."""
- with pytest.raises(ValueError, match="Unsupported property type"):
- activity_environment.run(
- backfill_materialized_column,
- BackfillMaterializedColumnInputs(
- team_id=team.id,
- property_name="test_prop",
- property_type="InvalidType",
- mat_column_name="dmat_string_0",
- ),
- )
diff --git a/posthog/temporal/tests/backfill_materialized_property/test_workflow.py b/posthog/temporal/tests/backfill_materialized_property/test_workflow.py
deleted file mode 100644
index 2fe8e9197ee5..000000000000
--- a/posthog/temporal/tests/backfill_materialized_property/test_workflow.py
+++ /dev/null
@@ -1,221 +0,0 @@
-"""Tests for backfill materialized property workflow."""
-
-import uuid
-
-import pytest
-
-import temporalio.worker
-from temporalio import activity
-from temporalio.exceptions import ApplicationError
-from temporalio.testing import WorkflowEnvironment
-from temporalio.worker import Worker
-
-from posthog.temporal.backfill_materialized_property.activities import (
- BackfillMaterializedColumnInputs,
- UpdateSlotStateInputs,
-)
-from posthog.temporal.backfill_materialized_property.workflows import (
- BackfillMaterializedPropertyInputs,
- BackfillMaterializedPropertyWorkflow,
-)
-
-
[email protected]_db(transaction=True)
-class TestBackfillMaterializedPropertyWorkflow:
- """Test the backfill workflow state machine with mocked activities."""
-
- async def test_workflow_happy_path(self, amaterialized_slot):
- """Test successful workflow: BACKFILL → READY."""
- slot_id = str(amaterialized_slot.id)
- team_id = amaterialized_slot.team_id
-
- state_updates = []
-
- @activity.defn(name="backfill_materialized_column")
- async def mock_backfill(inputs: BackfillMaterializedColumnInputs) -> int:
- return 0
-
- @activity.defn(name="update_slot_state")
- async def mock_update_state(inputs: UpdateSlotStateInputs) -> bool:
- state_updates.append({"state": inputs.state, "error_message": inputs.error_message})
- return True
-
- task_queue = str(uuid.uuid4())
- async with await WorkflowEnvironment.start_time_skipping() as env:
- async with Worker(
- env.client,
- task_queue=task_queue,
- workflows=[BackfillMaterializedPropertyWorkflow],
- activities=[mock_backfill, mock_update_state],
- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
- ):
- await env.client.execute_workflow(
- BackfillMaterializedPropertyWorkflow.run,
- BackfillMaterializedPropertyInputs(
- team_id=team_id,
- slot_id=slot_id,
- property_name="test_property",
- property_type="String",
- mat_column_name="dmat_string_0",
- cache_refresh_wait_seconds=0,
- state_update_retry_interval_seconds=1,
- ),
- id=str(uuid.uuid4()),
- task_queue=task_queue,
- )
-
- assert len(state_updates) == 1
- assert state_updates[0]["state"] == "READY"
- assert state_updates[0]["error_message"] is None
-
- async def test_workflow_backfill_fails(self, amaterialized_slot):
- """Test workflow failure when backfill fails: BACKFILL → ERROR."""
- slot_id = str(amaterialized_slot.id)
- team_id = amaterialized_slot.team_id
-
- state_updates = []
-
- @activity.defn(name="backfill_materialized_column")
- async def mock_backfill(inputs: BackfillMaterializedColumnInputs) -> int:
- raise ApplicationError("ClickHouse mutation failed", non_retryable=True)
-
- @activity.defn(name="update_slot_state")
- async def mock_update_state(inputs: UpdateSlotStateInputs) -> bool:
- state_updates.append({"state": inputs.state, "error_message": inputs.error_message})
- return True
-
- task_queue = str(uuid.uuid4())
- async with await WorkflowEnvironment.start_time_skipping() as env:
- async with Worker(
- env.client,
- task_queue=task_queue,
- workflows=[BackfillMaterializedPropertyWorkflow],
- activities=[mock_backfill, mock_update_state],
- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
- ):
- with pytest.raises(Exception):
- await env.client.execute_workflow(
- BackfillMaterializedPropertyWorkflow.run,
- BackfillMaterializedPropertyInputs(
- team_id=team_id,
- slot_id=slot_id,
- property_name="test_property",
- property_type="String",
- mat_column_name="dmat_string_0",
- cache_refresh_wait_seconds=0,
- state_update_retry_interval_seconds=1,
- ),
- id=str(uuid.uuid4()),
- task_queue=task_queue,
- )
-
- assert len(state_updates) == 1
- assert state_updates[0]["state"] == "ERROR"
- assert state_updates[0]["error_message"] is not None
- assert "Activity task failed" in state_updates[0]["error_message"]
-
- async def test_workflow_update_state_to_error_fails(self, amaterialized_slot):
- """Test that workflow still raises original error if update_slot_state to ERROR fails."""
- slot_id = str(amaterialized_slot.id)
- team_id = amaterialized_slot.team_id
-
- @activity.defn(name="backfill_materialized_column")
- async def mock_backfill(inputs: BackfillMaterializedColumnInputs) -> int:
- raise ApplicationError("Original error: backfill failed", non_retryable=True)
-
- @activity.defn(name="update_slot_state")
- async def mock_update_state(inputs: UpdateSlotStateInputs) -> bool:
- # Always fail when trying to update to ERROR
- if inputs.state == "ERROR":
- raise ApplicationError("DB connection lost", non_retryable=True)
- return True
-
- task_queue = str(uuid.uuid4())
- async with await WorkflowEnvironment.start_time_skipping() as env:
- async with Worker(
- env.client,
- task_queue=task_queue,
- workflows=[BackfillMaterializedPropertyWorkflow],
- activities=[mock_backfill, mock_update_state],
- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
- ):
- with pytest.raises(Exception) as exc_info:
- await env.client.execute_workflow(
- BackfillMaterializedPropertyWorkflow.run,
- BackfillMaterializedPropertyInputs(
- team_id=team_id,
- slot_id=slot_id,
- property_name="test_property",
- property_type="String",
- mat_column_name="dmat_string_0",
- cache_refresh_wait_seconds=0,
- state_update_retry_interval_seconds=1,
- ),
- id=str(uuid.uuid4()),
- task_queue=task_queue,
- )
-
- # Verify the workflow re-raises the ORIGINAL backfill error (not the state update error)
- # Temporal wraps errors, so we need to check the cause chain
- error = exc_info.value
- error_str = str(error)
-
- # Check if the error has a cause attribute (WorkflowFailureError)
- if hasattr(error, "cause"):
- cause_str = str(error.cause) if error.cause else ""
- full_error = f"{error_str} | cause: {cause_str}"
- else:
- full_error = error_str
-
- # The original "backfill failed" error should be in the error chain
- assert "backfill failed" in full_error or "Activity task failed" in full_error, (
- f"Expected original backfill error in chain, got: {full_error}"
- )
-
- async def test_workflow_update_state_to_ready_retries(self, amaterialized_slot):
- """Test that update_slot_state to READY retries on transient failures."""
- slot_id = str(amaterialized_slot.id)
- team_id = amaterialized_slot.team_id
-
- # Track how many times update_slot_state is called
- call_count = {"count": 0}
-
- @activity.defn(name="backfill_materialized_column")
- async def mock_backfill(inputs: BackfillMaterializedColumnInputs) -> int:
- return 0
-
- @activity.defn(name="update_slot_state")
- async def mock_update_state(inputs: UpdateSlotStateInputs) -> bool:
- call_count["count"] += 1
- # Fail first 2 attempts, succeed on 3rd
- if call_count["count"] < 3:
- raise RuntimeError("Transient database error")
- return True
-
- task_queue = str(uuid.uuid4())
- async with await WorkflowEnvironment.start_time_skipping() as env:
- async with Worker(
- env.client,
- task_queue=task_queue,
- workflows=[BackfillMaterializedPropertyWorkflow],
- activities=[mock_backfill, mock_update_state],
- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
- ):
- await env.client.execute_workflow(
- BackfillMaterializedPropertyWorkflow.run,
- BackfillMaterializedPropertyInputs(
- team_id=team_id,
- slot_id=slot_id,
- property_name="test_property",
- property_type="String",
- mat_column_name="dmat_string_0",
- cache_refresh_wait_seconds=0,
- state_update_retry_interval_seconds=1,
- ),
- id=str(uuid.uuid4()),
- task_queue=task_queue,
- )
-
- # Verify state update was retried and eventually succeeded
- assert call_count["count"] >= 3
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 726aba6fe956..322d93c7bb82 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20514,7 +20514,8 @@ export namespace Schemas {
}
/**
- * * `BACKFILL` - Backfill
+ * * `PENDING` - Pending
+ * `BACKFILL` - Backfill
* `READY` - Ready
* `ERROR` - Error
*/
@@ -20522,6 +20523,7 @@ export namespace Schemas {
export const MaterializedColumnSlotStateEnum = {
+ Pending: 'PENDING',
Backfill: 'BACKFILL',
Ready: 'READY',
Error: 'ERROR',
@@ -20532,18 +20534,18 @@ export namespace Schemas {
team: number;
property_definition: string;
readonly property_definition_details: PropertyDefinition;
- property_type: PropertyDefinitionTypeEnum;
/**
* @minimum 0
* @maximum 32767
+ * @nullable
*/
- slot_index: number;
+ slot_index?: number | null;
state?: MaterializedColumnSlotStateEnum;
/**
* @maxLength 400
* @nullable
*/
- backfill_temporal_workflow_id?: string | null;
+ backfill_temporal_run_id?: string | null;
/** @nullable */
error_message?: string | null;
readonly created_at: string;
@@ -27591,18 +27593,18 @@ export namespace Schemas {
team?: number;
property_definition?: string;
readonly property_definition_details?: PropertyDefinition;
- property_type?: PropertyDefinitionTypeEnum;
/**
* @minimum 0
* @maximum 32767
+ * @nullable
*/
- slot_index?: number;
+ slot_index?: number | null;
state?: MaterializedColumnSlotStateEnum;
/**
* @maxLength 400
* @nullable
*/
- backfill_temporal_workflow_id?: string | null;
+ backfill_temporal_run_id?: string | null;
/** @nullable */
error_message?: string | null;
readonly created_at?: string;