:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(dmat): part 2: batched backfill workflow (#58251)
Sandy Spicerb28091694e7a
diff --git a/posthog/api/test/test_materialized_column_activity_logging.py b/posthog/api/test/test_materialized_column_activity_logging.pynew file mode 100644index 000000000000..e90f83808050--- /dev/null+++ b/posthog/api/test/test_materialized_column_activity_logging.py@@ -0,0 +1,219 @@+"""Tests for materialized column slot activity logging."""++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from temporalio.testing import ActivityEnvironment++from posthog.models import ActivityLog, MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition+from posthog.temporal.backfill_materialized_property.activities import (+ ActivateSlotsInputs,+ FailSlotsInputs,+ activate_slots,+ fail_slots,+)++from products.event_definitions.backend.models.property_definition import PropertyType+++class TestMaterializedColumnActivityLogging(APIBaseTest):+ """Activity logging contract for the PENDING-flow materialized column slot lifecycle."""++ def setUp(self):+ super().setUp()+ self.user.is_staff = True+ self.user.save()++ def test_activity_log_on_slot_creation(self):+ """assign_slot creates a slot and logs `materialized_column_created`."""+ 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,+ 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_retry(self):+ """retry_backfill puts the slot back into PENDING and logs the transition."""+ 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,+ 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++ 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"++ 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"] == "PENDING"++ assert log.user == self.user++ @patch("posthog.api.materialized_column_slot.is_impersonated_session")+ def test_activity_log_includes_impersonation_flag(self, mock_is_impersonated):+ mock_is_impersonated.return_value = True++ 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++ 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++ def test_activate_slots_logs_completion(self):+ """The new batched workflow's activate_slots activity logs a completion entry per slot."""+ activity_environment = ActivityEnvironment()+ prop_def = PropertyDefinition.objects.create(+ team=self.team,+ name="batched_prop",+ property_type=PropertyType.String,+ type=PropertyDefinition.Type.EVENT,+ )+ slot = MaterializedColumnSlot.objects.create(+ team=self.team,+ property_definition=prop_def,+ slot_index=7,+ state=MaterializedColumnSlotState.BACKFILL,+ )++ activity_environment.run(activate_slots, ActivateSlotsInputs(slot_ids=[str(slot.id)]))++ slot.refresh_from_db()+ assert slot.state == MaterializedColumnSlotState.READY++ 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 and log.detail is not None+ assert log.detail["name"] == "batched_prop"++ def test_fail_slots_logs_failure(self):+ """fail_slots transitions slots to ERROR and logs `materialized_column_backfill_failed`."""+ activity_environment = ActivityEnvironment()+ prop_def = PropertyDefinition.objects.create(+ team=self.team,+ name="batched_prop",+ property_type=PropertyType.String,+ type=PropertyDefinition.Type.EVENT,+ )+ slot = MaterializedColumnSlot.objects.create(+ team=self.team,+ property_definition=prop_def,+ slot_index=7,+ state=MaterializedColumnSlotState.BACKFILL,+ )++ activity_environment.run(+ fail_slots,+ FailSlotsInputs(slot_ids=[str(slot.id)], error_message="ClickHouse OOM"),+ )++ slot.refresh_from_db()+ assert slot.state == MaterializedColumnSlotState.ERROR+ assert slot.error_message == "ClickHouse OOM"++ activity_logs = ActivityLog.objects.filter(+ team_id=self.team.id,+ scope="DataManagement",+ activity="materialized_column_backfill_failed",+ )+ assert activity_logs.count() == 1diff --git a/posthog/hogql/transforms/test/test_property_types_dmat.py b/posthog/hogql/transforms/test/test_property_types_dmat.pynew file mode 100644index 000000000000..23fcdafa9a7d--- /dev/null+++ b/posthog/hogql/transforms/test/test_property_types_dmat.py@@ -0,0 +1,264 @@+"""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.hogql.query import execute_hogql_query++from posthog.clickhouse.client import sync_execute+from posthog.models import MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition+from posthog.temporal.backfill_materialized_property.activities import _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_string_column_when_slot_ready_for_numeric_property(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,+ 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_string_3" in query, f"Expected dmat_string_3 in query but got: {query}"+ assert "JSONExtractRaw" not in query+ assert "accurateCastOrNull(events.dmat_string_3" in query, (+ f"Expected accurateCastOrNull wrapper around dmat_string_3 but got: {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,+ 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_string_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+++# Capped at 10 to fit the dmat slot pool (slot_index range 0..9 per the+# valid_slot_index check constraint). Picked to cover one representative case+# per type plus the trickier coercion paths for each.+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=""),+ # Numeric edge cases+ PropertyTestCase(name="num_int", type=PropertyType.Numeric, input_value=42),+ PropertyTestCase(name="num_negative", type=PropertyType.Numeric, input_value=-100),+ PropertyTestCase(name="num_invalid", type=PropertyType.Numeric, input_value="not a number"),+ # Boolean edge cases+ PropertyTestCase(name="bool_true_str", type=PropertyType.Boolean, input_value="true"),+ 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_invalid", type=PropertyType.Datetime, input_value="not a date"),+]+++class TestDmatExtractionConsistency(ClickhouseTestMixin, APIBaseTest):+ """Test that dmat column extraction matches JSON extraction behavior."""++ @pytest.mark.django_db(transaction=True)+ def test_dmat_string_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).+ """+ # Build test data+ event_properties = {tc.name: tc.input_value for tc in TEST_CASES}+ slot_indexes = {tc.name: i for i, tc in enumerate(TEST_CASES)}++ # 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+ extraction_sql = _generate_property_extraction_sql()+ dmat_columns = [f"dmat_string_{slot_indexes[tc.name]}" for tc in TEST_CASES]+ dmat_values = [extraction_sql.replace("%(property_name)s", f"'{tc.name}'") for tc in TEST_CASES]++ 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],+ slot_index=slot_indexes[tc.name],+ 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: dmat_string_{slot_indexes[tc.name]}"+ )++ raise AssertionError(+ f"dmat extraction differs from JSON extraction!\n\nMismatches:\n" + "\n".join(failures)+ )diff --git a/posthog/temporal/backfill_materialized_property/__init__.py b/posthog/temporal/backfill_materialized_property/__init__.pyindex c293cfb2c24b..b7985b9acb4a 100644--- a/posthog/temporal/backfill_materialized_property/__init__.py+++ b/posthog/temporal/backfill_materialized_property/__init__.py@@ -1,27 +1,51 @@-"""Temporal workflow for backfilling materialized property columns."""+"""Temporal workflow for backfilling materialized property columns.++A single weekly batched workflow fills every PENDING slot in one dict-backed+ALTER TABLE UPDATE per cycle. Per-team slot allocation means slot reuse happens+in place; there is no separate compaction step.+"""from posthog.temporal.backfill_materialized_property.activities import (- BackfillMaterializedColumnInputs,- UpdateSlotStateInputs,- backfill_materialized_column,- update_slot_state,+ ActivateSlotsInputs,+ AssignPendingColumnsInputs,+ AssignPendingColumnsResult,+ FailSlotsInputs,+ PopulateSlotAssignmentsInputs,+ PopulateSlotAssignmentsResult,+ RunBatchedMutationInputs,+ activate_slots,+ assign_pending_columns,+ fail_slots,+ populate_slot_assignments,+ run_batched_mutation,)from posthog.temporal.backfill_materialized_property.workflows import (- BackfillMaterializedPropertyInputs,- BackfillMaterializedPropertyWorkflow,+ BackfillMaterializedPropertiesBatchInputs,+ BackfillMaterializedPropertiesBatchWorkflow,)ACTIVITIES = [- backfill_materialized_column,- update_slot_state,+ assign_pending_columns,+ populate_slot_assignments,+ run_batched_mutation,+ activate_slots,+ fail_slots,]__all__ = [- "BackfillMaterializedPropertyWorkflow",- "BackfillMaterializedPropertyInputs",+ "BackfillMaterializedPropertiesBatchWorkflow",+ "BackfillMaterializedPropertiesBatchInputs","ACTIVITIES",- "backfill_materialized_column",- "BackfillMaterializedColumnInputs",- "update_slot_state",- "UpdateSlotStateInputs",+ "assign_pending_columns",+ "AssignPendingColumnsInputs",+ "AssignPendingColumnsResult",+ "populate_slot_assignments",+ "PopulateSlotAssignmentsInputs",+ "PopulateSlotAssignmentsResult",+ "run_batched_mutation",+ "RunBatchedMutationInputs",+ "activate_slots",+ "ActivateSlotsInputs",+ "fail_slots",+ "FailSlotsInputs",]diff --git a/posthog/temporal/backfill_materialized_property/activities.py b/posthog/temporal/backfill_materialized_property/activities.pyindex c3025f5c85e2..a0b4e8a2054f 100644--- a/posthog/temporal/backfill_materialized_property/activities.py+++ b/posthog/temporal/backfill_materialized_property/activities.py@@ -1,224 +1,534 @@"""Activities for materialized property backfill workflow."""+import time+import hashlibimport dataclasses-from typing import Optional++from django.conf import settings+from django.db import transactionimport structlog+import posthoganalyticsfrom temporalio import activity-from posthog.clickhouse.cluster import get_cluster+from posthog.clickhouse.cluster import AlterTableMutationRunner, get_cluster+from posthog.clickhouse.kafka_engine import json_extract_trim_quotesfrom posthog.models import MaterializedColumnSlotfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activity--from products.event_definitions.backend.models.property_definition import PropertyType+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,+)+from posthog.models.event.sql import DMAT_STRING_COLUMN_COUNT+from posthog.models.materialized_column_slots import MaterializedColumnSlotState+from posthog.temporal.common.heartbeat_sync import HeartbeaterSync+from posthog.temporal.common.utils import close_db_connectionslogger = structlog.get_logger(__name__)-PROPERTY_TYPE_TO_COLUMN_NAME: dict[str, str] = {- str(PropertyType.String): "string",- str(PropertyType.Numeric): "numeric",- str(PropertyType.Boolean): "bool",- str(PropertyType.Datetime): "datetime",-}+DMAT_STRING_COLUMN_NAME_PREFIX = "dmat_string_"-MATERIALIZABLE_PROPERTY_TYPES: set[str] = set(PROPERTY_TYPE_TO_COLUMN_NAME.keys())+def _generate_property_extraction_sql(property_name_param: str = "property_name") -> str:+ """SQL fragment that extracts one property out of `properties` as a string."""+ return json_extract_trim_quotes("properties", f"%({property_name_param})s")++[email protected](order=True)+class _SlotBranch:+ """One team's property mapped to a dmat column."""-class BackfillMaterializedColumnInputs:team_id: intproperty_name: str- property_type: str- mat_column_name: str- partition_id: Optional[str] = None+ slot_id: str@dataclasses.dataclass-class UpdateSlotStateInputs:- slot_id: str- state: str- error_message: Optional[str] = None+class _ColumnAssignment:+ """Plan for a single dmat_string column: which (team_id, property_name) pairs land in it."""++ column_index: int+ branches: list[_SlotBranch]+++class AssignPendingColumnsInputs:+ run_id: str-def _generate_property_extraction_sql(property_type: str) -> str:+class AssignPendingColumnsResult:+ assignments: list[_ColumnAssignment]+ assigned_slot_ids: list[str]+++def _plan_column_assignments(+ pending_slots: list[MaterializedColumnSlot],+ used_indexes_by_team: dict[int, set[int]],+) -> list[_ColumnAssignment]:+ """+ Pack PENDING slots into the smallest available column index per team.++ Slot indices are shared across teams — `dmat_string_3` carries team A's "browser_name"+ and team B's "page_url" simultaneously, and the dmat dictionary resolves+ (team_id, column_index) → property_name per row. Per-team uniqueness on the column+ index is the only invariant.++ The greedy algorithm walks pending slots in deterministic order (team_id ASC, slot+ UUID ASC) and places each into the smallest column index that:+ - is not already used by that team in any other slot (PENDING/BACKFILL/READY), and+ - has not yet been assigned to that team during this run."""- Generate SQL expression to extract property value from JSON properties column.+ # Sort for deterministic packing — important for idempotent retries.+ pending_sorted = sorted(pending_slots, key=lambda s: (s.team_id, str(s.id)))++ plan_by_column: dict[int, _ColumnAssignment] = {}+ # Track which columns each team has already been placed into during this run.+ team_columns_in_plan: dict[int, set[int]] = {}++ for slot in pending_sorted:+ team_used = used_indexes_by_team.get(slot.team_id, set()) | team_columns_in_plan.get(slot.team_id, set())+ # Find the smallest column index not used by this team.+ chosen: int | None = None+ for col_idx in range(DMAT_STRING_COLUMN_COUNT):+ if col_idx not in team_used:+ chosen = col_idx+ break+ if chosen is None:+ raise RuntimeError(+ f"No free column index available for team {slot.team_id} (uses {sorted(team_used)}). "+ f"Team has saturated all {DMAT_STRING_COLUMN_COUNT} dmat columns."+ )+ plan_by_column.setdefault(chosen, _ColumnAssignment(column_index=chosen, branches=[]))+ plan_by_column[chosen].branches.append(+ _SlotBranch(team_id=slot.team_id, property_name=slot.property_definition.name, slot_id=str(slot.id))+ )+ team_columns_in_plan.setdefault(slot.team_id, set()).add(chosen)++ # Return assignments sorted by column index for stable SQL.+ return [plan_by_column[idx] for idx in sorted(plan_by_column)]+++@close_db_connections+def assign_pending_columns(inputs: AssignPendingColumnsInputs) -> AssignPendingColumnsResult:+ """Atomically allocate columns for PENDING slots and transition them to BACKFILL.- Uses %(property_name)s placeholder for safe parameterization (matching HogQL pattern).- Caller must pass property_name in the query params dict.+ Also reclaims any BACKFILL slots already stamped with THIS run_id — they're a retry of+ a previous attempt that committed the slot transition but didn't record activity+ completion. Reclaimed slots keep their existing `slot_index` (re-packing would risk+ re-running a finished mutation against a different column).- Mimics the HogQL property type wrappers (toFloat, toBool, toDateTime) applied- to JSON-extracted values to ensure identical behavior.+ Stranded BACKFILL slots from OTHER runs are logged + alerted but not auto-recovered —+ we can't tell if their mutation completed."""- # Base JSON extraction with quote trimming and nullIf handling (same as HogQL printer)- # HogQL pattern: replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(...), ''), 'null'), '^"|"$', '')- base_extract = (- "replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, %(property_name)s), ''), 'null'), '^\"|\"$', '')"+ logger.info("Assigning pending slots to columns", run_id=inputs.run_id)++ with transaction.atomic():+ # Lock everything we'll inspect for collision avoidance — single shared pool, no+ # per-type filter (all dmat columns are `Nullable(String)`, HogQL casts at read).+ all_string_slots = list(+ MaterializedColumnSlot.objects.select_for_update()+ .select_related("property_definition", "team")+ .order_by("team_id", "id")+ )++ pending = [s for s in all_string_slots if s.state == MaterializedColumnSlotState.PENDING]++ # Detect slots already claimed by this workflow_run_id (activity retry case).+ # Their slot_index is already assigned and their column may have already been backfilled+ # by a prior run-batched-mutation invocation — we re-include them in the assignments so+ # the mutation runs idempotently (AlterTableMutationRunner is itself idempotent).+ reclaimed_from_this_run = [+ s+ for s in all_string_slots+ if s.state == MaterializedColumnSlotState.BACKFILL+ and s.backfill_temporal_run_id == inputs.run_id+ and s.slot_index is not None+ ]+ if reclaimed_from_this_run:+ logger.info(+ "Reclaiming BACKFILL slots from a previous attempt of this workflow run",+ run_id=inputs.run_id,+ count=len(reclaimed_from_this_run),+ slot_ids=[str(s.id) for s in reclaimed_from_this_run],+ )++ # Stranded slots from OTHER runs — we don't auto-recover, but we make them visible.+ # An operator can manually transition them back to PENDING via the API's retry endpoint.+ stranded = [+ s+ for s in all_string_slots+ if s.state == MaterializedColumnSlotState.BACKFILL+ and s.backfill_temporal_run_id is not None+ and s.backfill_temporal_run_id != inputs.run_id+ ]+ if stranded:+ stale_run_ids = sorted(+ {s.backfill_temporal_run_id for s in stranded if s.backfill_temporal_run_id is not None}+ )+ stranded_slot_ids = [str(s.id) for s in stranded]+ logger.warning(+ "Stranded BACKFILL slots from a prior workflow run — operator action required to retry",+ current_run_id=inputs.run_id,+ count=len(stranded),+ slot_ids=stranded_slot_ids,+ stale_run_ids=stale_run_ids,+ )+ # Surface to Sentry — the workflow doesn't fail (HogQL falls back to JSON for+ # state != READY) but stranded slots hold a column index until an operator resets+ # them to PENDING.+ posthoganalytics.capture_exception(+ Exception("dmat: stranded BACKFILL slots require operator action"),+ properties={+ "current_run_id": inputs.run_id,+ "stranded_slot_ids": stranded_slot_ids,+ "stale_run_ids": stale_run_ids,+ },+ )++ if not pending and not reclaimed_from_this_run:+ logger.info(+ "Nothing to do — no PENDING slots and nothing reclaimed",+ run_id=inputs.run_id,+ )+ return AssignPendingColumnsResult(assignments=[], assigned_slot_ids=[])++ # PENDING-slot assignment: per-team free pool. Each team picks freely from+ # 0..DMAT_STRING_COLUMN_COUNT-1 — different teams can share the same column index for+ # different properties, the dmat dict resolves (team_id, slot_index) → property_name+ # per row.+ used_indexes_by_team: dict[int, set[int]] = {}+ for slot in all_string_slots:+ if slot.slot_index is not None:+ used_indexes_by_team.setdefault(slot.team_id, set()).add(slot.slot_index)++ pending_assignments = _plan_column_assignments(pending, used_indexes_by_team) if pending else []++ # Apply PENDING assignments.+ slot_index_by_id: dict[str, int] = {}+ for assignment in pending_assignments:+ for branch in assignment.branches:+ slot_index_by_id[branch.slot_id] = assignment.column_index++ assigned_slot_ids: list[str] = []+ for slot in pending:+ slot.slot_index = slot_index_by_id[str(slot.id)]+ slot.state = MaterializedColumnSlotState.BACKFILL+ slot.backfill_temporal_run_id = inputs.run_id+ slot.error_message = None+ slot.save(+ update_fields=[+ "slot_index",+ "state",+ "backfill_temporal_run_id",+ "error_message",+ "updated_at",+ ]+ )+ assigned_slot_ids.append(str(slot.id))++ # Re-include reclaimed slots in the assignment plan so the mutation runs against+ # them too (idempotent — the mutation runner attaches to an existing mutation if one+ # for the same command is already in flight or done).+ reclaimed_assignments_by_column: dict[int, _ColumnAssignment] = {}+ for slot in reclaimed_from_this_run:+ assert slot.slot_index is not None # filtered above+ reclaimed_assignments_by_column.setdefault(+ slot.slot_index, _ColumnAssignment(column_index=slot.slot_index, branches=[])+ )+ reclaimed_assignments_by_column[slot.slot_index].branches.append(+ _SlotBranch(team_id=slot.team_id, property_name=slot.property_definition.name, slot_id=str(slot.id))+ )+ assigned_slot_ids.append(str(slot.id))++ all_assignments = pending_assignments + [+ reclaimed_assignments_by_column[idx] for idx in sorted(reclaimed_assignments_by_column)+ ]++ logger.info(+ "Assigned PENDING slots",+ run_id=inputs.run_id,+ assigned_count=len(assigned_slot_ids),+ reclaimed_count=len(reclaimed_from_this_run),+ column_count=len(all_assignments),)- if property_type == PropertyType.String:- return base_extract+ return AssignPendingColumnsResult(+ assignments=all_assignments,+ assigned_slot_ids=assigned_slot_ids,+ )- elif property_type == PropertyType.Numeric:- # Match HogQL's toFloat() - no whitespace trimming, just direct conversion- return f"toFloat64OrNull({base_extract})"- elif property_type == PropertyType.Boolean:- # Match HogQL's toBool(transform(toString(...), ["true", "false"], [1, 0], None))- # Need to use toString() wrapper to match HogQL behavior- return f"transform(toString({base_extract}), ['true', 'false'], [1, 0], NULL)"+class PopulateSlotAssignmentsInputs:+ pass- elif property_type == PropertyType.Datetime:- # Match HogQL's toDateTime() -> parseDateTime64BestEffortOrNull with precision 6- # See posthog/hogql/printer.py L1391-1392 and posthog/hogql/functions/clickhouse/conversions.py L112-127- # Timezone param omitted - uses server default (UTC). Most datetime strings have explicit- # timezone info anyway, and for ambiguous strings UTC is a reasonable default.- return f"parseDateTime64BestEffortOrNull({base_extract}, 6)"- else:- raise ValueError(f"Unsupported property type for materialization: {property_type}")+class PopulateSlotAssignmentsResult:+ rows_written: int@activity.defn-def backfill_materialized_column(inputs: BackfillMaterializedColumnInputs) -> int:+@close_db_connections+def populate_slot_assignments(inputs: PopulateSlotAssignmentsInputs) -> PopulateSlotAssignmentsResult:+ """Sync slot assignments from Postgres to `dmat_slot_assignments` on every host, then+ reload `dmat_slot_assignments_dict` everywhere.++ Two-phase: TRUNCATE+INSERT on every host, then RELOAD on every host. If any host+ fails the populate, the reload never runs — the next mutation won't see a partially-+ populated cluster."""- Backfill a materialized column by running ALTER TABLE UPDATE on historical events.+ rows: list[tuple[int, int, str]] = []+ for slot in (+ MaterializedColumnSlot.objects.select_related("property_definition")+ .filter(state__in=[MaterializedColumnSlotState.READY, MaterializedColumnSlotState.BACKFILL])+ .order_by("team_id", "id")+ ):+ if slot.slot_index is not None:+ rows.append((slot.team_id, int(slot.slot_index), slot.property_definition.name))++ truncate_sql = TRUNCATE_DMAT_SLOT_ASSIGNMENTS_SQL()+ insert_sql = INSERT_DMAT_SLOT_ASSIGNMENTS_SQL()+ reload_sql = RELOAD_DMAT_SLOT_ASSIGNMENTS_DICTIONARY_SQL()++ def populate(client) -> int:+ client.execute(truncate_sql)+ if rows:+ client.execute(insert_sql, rows)+ return len(rows)++ def reload(client) -> None:+ client.execute(reload_sql)++ cluster = get_cluster()+ populate_results = cluster.map_all_hosts(populate).result()+ cluster.map_all_hosts(reload).result()++ rows_written = next(iter(populate_results.values()), 0)+ logger.info(+ "Populated dmat_slot_assignments and reloaded dictionary on all hosts",+ host_count=len(populate_results),+ rows_per_host=rows_written,+ )+ return PopulateSlotAssignmentsResult(rows_written=rows_written)- Runs the mutation on all shards since sharded_events is a sharded table.- Uses mutations_sync=1 to block until each shard's mutation completes.- Returns 0 (row count not tracked).- """- extraction_sql = _generate_property_extraction_sql(inputs.property_type)-- partition_clause = "IN PARTITION %(partition_id)s" if inputs.partition_id else ""- query = f"""- ALTER TABLE sharded_events- UPDATE {inputs.mat_column_name} = {extraction_sql}- {partition_clause}- WHERE team_id = %(team_id)s- """+class RunBatchedMutationInputs:+ assignments: list[_ColumnAssignment]+ # See `compute_cycle_marker_int` — embedded in the mutation WHERE so SQL text differs+ # across cycles, defeating AlterTableMutationRunner's cross-cycle dedup.+ cycle_marker_int: int- params: dict[str, str | int] = {- "team_id": inputs.team_id,- "property_name": inputs.property_name,- }- if inputs.partition_id:- params["partition_id"] = inputs.partition_id- logger.info(- "Starting backfill for materialized column",- team_id=inputs.team_id,- property_name=inputs.property_name,- property_type=inputs.property_type,- mat_column_name=inputs.mat_column_name,- partition_id=inputs.partition_id,- )+def compute_cycle_marker_int(workflow_run_id: str) -> int:+ """Stable 32-bit unsigned int from `workflow_run_id` — same across activity retries+ within one cycle, different across cycles. Hash is non-cryptographic (just an+ identity bucket), so SHA-256 over a sliced 4-byte prefix is fine here."""+ return int.from_bytes(hashlib.sha256(workflow_run_id.encode()).digest()[:4], "big")- try:- cluster = get_cluster()- # Execute mutation on one host per shard with mutations_sync=1- # This blocks until the mutation completes on each shard- def run_mutation(client):- client.execute(query, params, settings={"mutations_sync": 1})+def _build_dict_backed_update_command(+ assignments: list[_ColumnAssignment], cycle_marker_int: int+) -> tuple[str, dict[str, str]]:+ """Build a single ALTER TABLE UPDATE that populates the given dmat_string columns by+ reading (team_id, column_index) → property_name out of `dmat_slot_assignments_dict`.++ Each column gets `col = if(dictHas(...), <extract>, col)`. The `<extract>` wraps+ `JSONExtractRaw` in the same shape as `_generate_property_extraction_sql` so the+ coercion contract pinned by `coercion_fixtures.json` is preserved.- cluster.map_one_host_per_shard(run_mutation).result()+ The WHERE uses `team_id IN (SELECT DISTINCT team_id FROM dmat_slot_assignments)` so+ the SQL is constant-size regardless of team count, and ClickHouse can prune sharded_events+ parts that don't contain any of those teams.- logger.info(- "Backfill mutation completed on all shards",- team_id=inputs.team_id,- property_name=inputs.property_name,- mat_column_name=inputs.mat_column_name,+ Returns `(command, {})` — property names live in the dict, not in query parameters.+ """+ if not assignments:+ raise ValueError("Cannot build mutation command with no assignments")++ # Fully-qualified identifiers — ClickHouse normalizes bare references when storing+ # `system.mutations.command`, and a bare-vs-qualified mismatch defeats the byte-equality+ # dedup join in `AlterTableMutationRunner.find_existing_mutations`.+ qualified_dict = f"{settings.CLICKHOUSE_DATABASE}.{DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME}"+ qualified_assignments_table = f"{settings.CLICKHOUSE_DATABASE}.dmat_slot_assignments"+ set_clauses: list[str] = []+ for assignment in assignments:+ idx = int(assignment.column_index)+ col_name = f"{DMAT_STRING_COLUMN_NAME_PREFIX}{idx}"+ property_name_expr = f"dictGetString('{qualified_dict}', 'property_name', (team_id, {idx}))"+ extract_sql = (+ f"replaceRegexpAll("+ f"nullIf(nullIf("+ f"JSONExtractRaw(properties, {property_name_expr})"+ f", ''), 'null')"+ f", '^\"|\"$', '')")+ dispatch_sql = f"if(dictHas('{qualified_dict}', (team_id, {idx})), {extract_sql}, {col_name})"+ set_clauses.append(f"{col_name} = {dispatch_sql}")- return 0+ where_clause = (+ f"team_id IN (SELECT DISTINCT team_id FROM {qualified_assignments_table}) "+ f"AND {int(cycle_marker_int)} = {int(cycle_marker_int)}"+ )+ command = f"UPDATE {', '.join(set_clauses)} WHERE {where_clause}"+ return command, {}+++def run_batched_mutation(inputs: RunBatchedMutationInputs) -> None:+ """Submit (or attach to) the batched ALTER TABLE UPDATE and block until done on every+ shard. Reads property names from `dmat_slot_assignments_dict`, which+ `populate_slot_assignments` must have synced and reloaded first.+ """+ if not inputs.assignments:+ logger.info("No assignments to backfill — skipping mutation")+ return++ column_indexes = sorted({a.column_index for a in inputs.assignments})+ logger.info(+ "Submitting dict-backed dmat backfill mutation",+ column_count=len(inputs.assignments),+ column_indexes=column_indexes,+ cycle_marker_int=inputs.cycle_marker_int,+ )++ command, params = _build_dict_backed_update_command(inputs.assignments, inputs.cycle_marker_int)- except Exception as e:- logger.exception(- "Backfill failed",- team_id=inputs.team_id,- property_name=inputs.property_name,- mat_column_name=inputs.mat_column_name,- error=str(e),+ # The mutation can run for hours; HeartbeaterSync keeps Temporal from killing the+ # activity at `heartbeat_timeout`.+ t0 = time.monotonic()+ with HeartbeaterSync(logger=logger):+ cluster = get_cluster()+ runner = AlterTableMutationRunner(+ table="sharded_events",+ commands={command},+ parameters=params,)- raise+ runner.run_on_shards(cluster)+ duration_seconds = time.monotonic() - t0++ logger.info(+ "Dict-backed dmat backfill mutation complete",+ column_count=len(inputs.assignments),+ duration_seconds=round(duration_seconds, 1),+ )+ posthoganalytics.capture(+ "dmat_mutation_completed",+ distinct_id="dmat-system",+ properties={+ "column_count": len(inputs.assignments),+ "column_indexes": column_indexes,+ "cycle_marker_int": inputs.cycle_marker_int,+ "duration_seconds": round(duration_seconds, 1),+ },+ )+++class ActivateSlotsInputs:+ slot_ids: list[str]@activity.defn-def update_slot_state(inputs: UpdateSlotStateInputs) -> bool:+@close_db_connections+def activate_slots(inputs: ActivateSlotsInputs) -> int:"""- Update the state of a materialized column slot with activity logging.+ Transition the given slot IDs from BACKFILL → READY in a single bulk update.- Returns True if update succeeded.+ Logs an audit entry per slot to keep parity with the legacy per-slot workflow."""- try:- slot = MaterializedColumnSlot.objects.select_related("team", "property_definition").get(id=inputs.slot_id)- old_state = slot.state-- slot.state = inputs.state-- # Store or clear error message- if inputs.error_message:- slot.error_message = inputs.error_message- logger.error(- "Slot state update with error",- slot_id=inputs.slot_id,- old_state=old_state,- new_state=inputs.state,- error_message=inputs.error_message,- )- elif inputs.state == "BACKFILL":- # Clear error message when transitioning to BACKFILL (e.g., on retry)- slot.error_message = None+ if not inputs.slot_ids:+ return 0- slot.save()+ activated = 0+ for slot in MaterializedColumnSlot.objects.select_related("team", "property_definition").filter(+ id__in=inputs.slot_ids,+ state=MaterializedColumnSlotState.BACKFILL,+ ):+ old_state = slot.state+ slot.state = MaterializedColumnSlotState.READY+ slot.error_message = None+ slot.save(update_fields=["state", "error_message"])+ activated += 1- logger.info(- "Updated slot state",- slot_id=inputs.slot_id,+ log_activity(+ organization_id=slot.team.organization_id,team_id=slot.team_id,- old_state=old_state,- new_state=inputs.state,+ user=None,+ was_impersonated=False,+ item_id=str(slot.id),+ scope="DataManagement",+ activity="materialized_column_backfill_completed",+ detail=Detail(+ name=slot.property_definition.name,+ changes=[+ Change(+ type="MaterializedColumnSlot",+ action="changed",+ field="state",+ before=old_state,+ after=str(MaterializedColumnSlotState.READY),+ ),+ ],+ ),)- # Log activity for state transitions to READY or ERROR- if inputs.state in ["READY", "ERROR"]:- property_name = slot.property_definition.name if slot.property_definition else "Unknown"+ logger.info("Activated slots", count=activated, requested=len(inputs.slot_ids))+ return activated- activity_name = (- "materialized_column_backfill_completed"- if inputs.state == "READY"- else "materialized_column_backfill_failed"- )- log_activity(- organization_id=slot.team.organization_id,- team_id=slot.team_id,- user=None, # System user for workflow-triggered updates- was_impersonated=False,- item_id=str(slot.id),- scope="DataManagement",- activity=activity_name,- detail=Detail(- name=property_name,- changes=[- Change(- type="MaterializedColumnSlot",- action="changed",- field="state",- before=old_state,- after=inputs.state,- ),- ],- ),- )+class FailSlotsInputs:+ slot_ids: list[str]+ error_message: str+- return True+@close_db_connections+def fail_slots(inputs: FailSlotsInputs) -> int:+ """+ Transition the given slot IDs to ERROR with the supplied error_message. Used when the+ batched mutation fails — operators can later transition them back to PENDING for retry.+ """+ if not inputs.slot_ids:+ return 0++ failed = 0+ for slot in MaterializedColumnSlot.objects.select_related("team", "property_definition").filter(+ id__in=inputs.slot_ids,+ state=MaterializedColumnSlotState.BACKFILL,+ ):+ old_state = slot.state+ slot.state = MaterializedColumnSlotState.ERROR+ slot.error_message = inputs.error_message+ slot.save(update_fields=["state", "error_message"])+ failed += 1++ log_activity(+ organization_id=slot.team.organization_id,+ team_id=slot.team_id,+ user=None,+ was_impersonated=False,+ item_id=str(slot.id),+ scope="DataManagement",+ activity="materialized_column_backfill_failed",+ detail=Detail(+ name=slot.property_definition.name,+ changes=[+ Change(+ type="MaterializedColumnSlot",+ action="changed",+ field="state",+ before=old_state,+ after=str(MaterializedColumnSlotState.ERROR),+ ),+ ],+ ),+ )- except MaterializedColumnSlot.DoesNotExist:- logger.warning("Slot not found for state update", slot_id=inputs.slot_id)- return False- except Exception as e:- logger.exception("Failed to update slot state", slot_id=inputs.slot_id, error=str(e))- raise+ return faileddiff --git a/posthog/temporal/backfill_materialized_property/coercion_fixtures.json b/posthog/temporal/backfill_materialized_property/coercion_fixtures.jsonnew file mode 100644index 000000000000..5df840d1e29e--- /dev/null+++ b/posthog/temporal/backfill_materialized_property/coercion_fixtures.json@@ -0,0 +1,19 @@+{+ "_comment": "Single source of truth for dmat coercion parity. Both the Python-side ClickHouse extraction tests and the TypeScript-side plugin-server tests load this file and assert their respective code path produces `expected_output` for `input`. Per the dmat RFC, every dmat column is `Nullable(String)` — HogQL applies type wrappers (toFloat/toBool/toDateTime) at read time the same way it does for normal mat_* columns. So this fixture only covers the string extraction; type-cast parity is covered at the HogQL layer in test_property_types_dmat.py.",+ "string_cases": [+ { "name": "plain ascii string", "input": "Chrome", "expected_output": "Chrome" },+ { "name": "empty string", "input": "", "expected_output": "" },+ { "name": "whitespace string", "input": " ", "expected_output": " " },+ { "name": "string with internal escaped quotes", "input": "a \"b\" c", "expected_output": "a \\\"b\\\" c" },+ { "name": "string of digits", "input": "123", "expected_output": "123" },+ { "name": "the literal string 'null'", "input": "null", "expected_output": "null" },+ { "name": "JSON object", "input": { "a": 1 }, "expected_output": "{\"a\":1}" },+ { "name": "JSON array of numbers", "input": [1, 2, 3], "expected_output": "[1,2,3]" },+ { "name": "JSON array of strings", "input": ["a", "b"], "expected_output": "[\"a\",\"b\"]" },+ { "name": "number type (integer)", "input": 42, "expected_output": "42" },+ { "name": "number type (float)", "input": 3.14, "expected_output": "3.14" },+ { "name": "boolean true", "input": true, "expected_output": "true" },+ { "name": "boolean false", "input": false, "expected_output": "false" },+ { "name": "string wrapped in double quotes", "input": "\"hello\"", "expected_output": "\\\"hello\\\"" }+ ]+}diff --git a/posthog/temporal/backfill_materialized_property/schedule.py b/posthog/temporal/backfill_materialized_property/schedule.pynew file mode 100644index 000000000000..79f671f1e37e--- /dev/null+++ b/posthog/temporal/backfill_materialized_property/schedule.py@@ -0,0 +1,61 @@+"""Cron schedule registration for the weekly batched dmat workflow.++``weekly-dmat-backfill`` fires the PENDING-allocation workflow Sunday 00:00 UTC. It+picks up any PENDING slots, allocates fresh column indexes (per-team), runs the+single dict-backed mutation, and activates them. There is no separate compaction+schedule — per-team slot allocation means slot reuse happens in place, handled by+the same mutation that fills new PENDING slots.++Register or refresh the schedule by calling+``create_or_update_weekly_dmat_backfill_schedule`` from a management command or+initialization hook. Idempotent — running it twice is safe.+"""++import datetime as dt++from django.conf import settings++from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleOverlapPolicy,+ SchedulePolicy,+ ScheduleSpec,+)++from posthog.temporal.backfill_materialized_property.workflows import (+ BackfillMaterializedPropertiesBatchInputs,+ BackfillMaterializedPropertiesBatchWorkflow,+)+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule++# Sunday at 00:00 UTC — picked to be off-peak across regions and to coincide with the+# existing weekly maintenance window. The exact minute matters less than the day.+WEEKLY_DMAT_BACKFILL_CRON = "0 0 * * 0"+BACKFILL_SCHEDULE_ID = "weekly-dmat-backfill"+++async def create_or_update_weekly_dmat_backfill_schedule(client: Client) -> None:+ """Create or update the weekly PENDING-allocation cron schedule.++ Uses ScheduleOverlapPolicy.SKIP so a long-running mutation does not get a duplicate+ scheduled alongside it — the next firing is dropped instead of queued. The next+ week's cycle then picks up any slots still PENDING.+ """+ schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ BackfillMaterializedPropertiesBatchWorkflow.run,+ BackfillMaterializedPropertiesBatchInputs(),+ id=f"{BACKFILL_SCHEDULE_ID}-execution",+ task_queue=settings.TEMPORAL_TASK_QUEUE,+ execution_timeout=dt.timedelta(hours=24),+ ),+ spec=ScheduleSpec(cron_expressions=[WEEKLY_DMAT_BACKFILL_CRON]),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )++ if await a_schedule_exists(client, BACKFILL_SCHEDULE_ID):+ await a_update_schedule(client, BACKFILL_SCHEDULE_ID, schedule)+ else:+ await a_create_schedule(client, BACKFILL_SCHEDULE_ID, schedule, trigger_immediately=False)diff --git a/posthog/temporal/backfill_materialized_property/workflows.py b/posthog/temporal/backfill_materialized_property/workflows.pyindex d8fea81d7f13..79ee087e2ec7 100644--- a/posthog/temporal/backfill_materialized_property/workflows.py+++ b/posthog/temporal/backfill_materialized_property/workflows.py@@ -1,4 +1,10 @@-"""Workflow for backfilling materialized property columns."""+"""Workflow for backfilling materialized property columns.++``BackfillMaterializedPropertiesBatchWorkflow`` is the single weekly workflow: it+materializes every PENDING slot in one dict-backed ALTER TABLE UPDATE per cycle.+Per-team slot allocation means there is no compaction step — slots are reused in+place as properties are dropped and re-added.+"""import jsonimport datetime as dt@@ -9,130 +15,163 @@ from temporalio import workflowfrom temporalio.common import RetryPolicyfrom posthog.temporal.backfill_materialized_property.activities import (- BackfillMaterializedColumnInputs,- UpdateSlotStateInputs,- backfill_materialized_column,- update_slot_state,+ ActivateSlotsInputs,+ AssignPendingColumnsInputs,+ AssignPendingColumnsResult,+ FailSlotsInputs,+ PopulateSlotAssignmentsInputs,+ RunBatchedMutationInputs,+ activate_slots,+ assign_pending_columns,+ compute_cycle_marker_int,+ fail_slots,+ populate_slot_assignments,+ run_batched_mutation,)from posthog.temporal.common.base import PostHogWorkflow@dataclasses.dataclass-class BackfillMaterializedPropertyInputs:- """Inputs for the backfill materialized property workflow."""-- team_id: int- slot_id: str- property_name: str- property_type: str- mat_column_name: str- # Wait time for ingestion cache refresh (default 180s, can be 0 for tests)+class BackfillMaterializedPropertiesBatchInputs:+ """Inputs for the weekly batched dmat PENDING-allocation workflow."""++ # Wait time between assigning slots and submitting the mutation, so plugin-server+ # TeamManager caches refresh and start populating the new columns for fresh events+ # before the historical backfill mutation runs. Default 180s; tests can pass 0.cache_refresh_wait_seconds: int = 180- # Retry interval for state updates (default 10s, can be shorter for tests)- state_update_retry_interval_seconds: int = 10[email protected](name="backfill-materialized-property")-class BackfillMaterializedPropertyWorkflow(PostHogWorkflow):[email protected](name="backfill-materialized-properties-batch")+class BackfillMaterializedPropertiesBatchWorkflow(PostHogWorkflow):"""- Workflow to backfill a materialized property column.+ Weekly batched workflow that materializes all PENDING slots in one mutation.Flow:- 1. Wait 3 minutes for plugin-server ingestion cache to refresh- (ensures no gap between backfill and future new events being materialized)- 2. Run ClickHouse ALTER TABLE UPDATE to backfill historical events- 3. Update slot state to READY (or ERROR if failed)+ 1. Atomically assign each PENDING slot to a free column index for its team and+ transition it to BACKFILL.+ 2. Sync the current (team_id, column_index) → property_name mapping to the+ ClickHouse-side ``dmat_slot_assignments`` table on every host and reload the+ ``dmat_slot_assignments_dict`` dictionary on every host. The mutation in+ step 4 reads from this dictionary at runtime.+ 3. Sleep ~3 minutes so the plugin-server ingestion cache picks up the new+ (slot_index, property) mappings before the historical backfill runs.+ 4. Submit a single ALTER TABLE UPDATE whose SET clauses dispatch via+ ``dictGet`` against the dictionary and whose WHERE prunes on+ ``team_id IN (SELECT DISTINCT team_id FROM dmat_slot_assignments)``. The+ mutation also embeds a per-cycle marker (``AND <hash> = <hash>``) so+ AlterTableMutationRunner's SQL-text dedup distinguishes cycles. Block until+ the mutation completes on every shard.+ 5. Transition the assigned slots to READY. HogQL immediately starts using the+ materialized columns once the slots are READY.++ On any failure between steps 1 and 5, the affected slots are transitioned to ERROR+ so an operator can investigate and reset them to PENDING for the next cycle."""@classmethod- def parse_inputs(cls, inputs: list[str]) -> BackfillMaterializedPropertyInputs:- """Parse inputs from the management command CLI."""- loaded = json.loads(inputs[0])- return BackfillMaterializedPropertyInputs(**loaded)+ def parse_inputs(cls, inputs: list[str]) -> BackfillMaterializedPropertiesBatchInputs:+ loaded = json.loads(inputs[0]) if inputs else {}+ return BackfillMaterializedPropertiesBatchInputs(**loaded)@workflow.run- async def run(self, inputs: BackfillMaterializedPropertyInputs) -> None:- """Execute the backfill workflow."""- logger = structlog.get_logger("backfill_materialized_property")+ async def run(self, inputs: BackfillMaterializedPropertiesBatchInputs) -> None:+ logger = structlog.get_logger("backfill_materialized_properties_batch")+ # run_id (not workflow_id) — the weekly schedule reuses one workflow_id, so run_id+ # is what makes the assign activity idempotent across retries within one firing.+ run_id = workflow.info().run_id+ # Mixed into the mutation's WHERE so SQL text differs across cycles — otherwise+ # AlterTableMutationRunner's SQL-text dedup would reattach to last week's mutation.+ cycle_marker_int = compute_cycle_marker_int(run_id)++ assignment: AssignPendingColumnsResult = await workflow.execute_activity(+ assign_pending_columns,+ AssignPendingColumnsInputs(run_id=run_id),+ start_to_close_timeout=dt.timedelta(minutes=5),+ retry_policy=RetryPolicy(+ initial_interval=dt.timedelta(seconds=10),+ maximum_interval=dt.timedelta(minutes=1),+ maximum_attempts=3,+ ),+ )++ if not assignment.assigned_slot_ids:+ logger.info("Nothing to do — no PENDING slots", run_id=run_id)+ returntry:- # Wait for plugin-server TeamManager cache to refresh- # IMPORTANT: plugin-server/src/utils/team-manager.ts has refreshAgeMs=2min + refreshJitterMs=30s- # We wait 3 minutes to account for max refresh time (2.5min) + buffer- # This prevents a gap where new events come in after backfill completes- # but before the ingestion server knows about the new materialized column+ await workflow.execute_activity(+ populate_slot_assignments,+ PopulateSlotAssignmentsInputs(),+ start_to_close_timeout=dt.timedelta(minutes=10),+ retry_policy=RetryPolicy(+ initial_interval=dt.timedelta(seconds=10),+ maximum_interval=dt.timedelta(minutes=1),+ maximum_attempts=3,+ ),+ )+if inputs.cache_refresh_wait_seconds > 0:logger.info("Waiting for ingestion cache refresh",- team_id=inputs.team_id,- slot_id=inputs.slot_id,wait_seconds=inputs.cache_refresh_wait_seconds,+ pending_count=len(assignment.assigned_slot_ids),)await workflow.sleep(dt.timedelta(seconds=inputs.cache_refresh_wait_seconds))- # Run backfill- logger.info(- "Starting backfill",- team_id=inputs.team_id,- property_name=inputs.property_name,- mat_column_name=inputs.mat_column_name,- )- await workflow.execute_activity(- backfill_materialized_column,- BackfillMaterializedColumnInputs(- team_id=inputs.team_id,- property_name=inputs.property_name,- property_type=inputs.property_type,- mat_column_name=inputs.mat_column_name,- ),- start_to_close_timeout=dt.timedelta(hours=2),- retry_policy=RetryPolicy(- initial_interval=dt.timedelta(minutes=1),- maximum_interval=dt.timedelta(minutes=10),- maximum_attempts=3,- ),- )+ if assignment.assignments:+ await workflow.execute_activity(+ run_batched_mutation,+ RunBatchedMutationInputs(+ assignments=assignment.assignments,+ cycle_marker_int=cycle_marker_int,+ ),+ # The activity polls system.mutations, so this bounds wall-clock duration,+ # not connection life — sharded_events mutations can run for hours.+ start_to_close_timeout=dt.timedelta(hours=12),+ heartbeat_timeout=dt.timedelta(minutes=5),+ retry_policy=RetryPolicy(+ initial_interval=dt.timedelta(minutes=2),+ maximum_interval=dt.timedelta(minutes=10),+ maximum_attempts=3,+ ),+ )- # Update state to READY- logger.info("Backfill complete, updating state to READY", slot_id=inputs.slot_id)await workflow.execute_activity(- update_slot_state,- UpdateSlotStateInputs(slot_id=inputs.slot_id, state="READY"),- start_to_close_timeout=dt.timedelta(minutes=5),+ activate_slots,+ ActivateSlotsInputs(slot_ids=assignment.assigned_slot_ids),+ start_to_close_timeout=dt.timedelta(minutes=10),retry_policy=RetryPolicy(- initial_interval=dt.timedelta(seconds=inputs.state_update_retry_interval_seconds),+ initial_interval=dt.timedelta(seconds=10),maximum_interval=dt.timedelta(minutes=1),- maximum_attempts=5, # State update is important, retry more+ maximum_attempts=5,),)-- logger.info("Workflow completed successfully", slot_id=inputs.slot_id)-except Exception as e:- # Update state to ERROR- logger.exception("Workflow failed", slot_id=inputs.slot_id)-+ logger.exception("Backfill failed after slot assignment; marking slots as ERROR", run_id=run_id)try:await workflow.execute_activity(- update_slot_state,- UpdateSlotStateInputs(- slot_id=inputs.slot_id,- state="ERROR",+ fail_slots,+ FailSlotsInputs(+ slot_ids=assignment.assigned_slot_ids,error_message=str(e),),start_to_close_timeout=dt.timedelta(minutes=5),retry_policy=RetryPolicy(- initial_interval=dt.timedelta(seconds=inputs.state_update_retry_interval_seconds),+ initial_interval=dt.timedelta(seconds=10),maximum_interval=dt.timedelta(minutes=1),maximum_attempts=5,),)except Exception:logger.exception(- "Failed to update state to ERROR",- slot_id=inputs.slot_id,- original_error=str(e),+ "Failed to mark slots as ERROR after backfill failure",+ run_id=run_id,)-- # Re-raise the original exceptionraise++ logger.info(+ "Batched dmat PENDING workflow completed",+ run_id=run_id,+ pending_count=len(assignment.assigned_slot_ids),+ column_count=len(assignment.assignments),+ )diff --git a/posthog/temporal/product_analytics/__init__.py b/posthog/temporal/product_analytics/__init__.pyindex 23030124c790..784b72d5af65 100644--- a/posthog/temporal/product_analytics/__init__.py+++ b/posthog/temporal/product_analytics/__init__.py@@ -1,6 +1,6 @@from posthog.temporal.backfill_materialized_property import (ACTIVITIES as BACKFILL_ACTIVITIES,- BackfillMaterializedPropertyWorkflow,+ BackfillMaterializedPropertiesBatchWorkflow,)from .upgrade_queries_activities import get_insights_to_migrate, migrate_insights_batch@@ -8,7 +8,7 @@ from .upgrade_queries_workflow import UpgradeQueriesWorkflowWORKFLOWS = [UpgradeQueriesWorkflow,- BackfillMaterializedPropertyWorkflow,+ BackfillMaterializedPropertiesBatchWorkflow,]ACTIVITIES = [get_insights_to_migrate,diff --git a/posthog/temporal/tests/backfill_materialized_property/test_batched_activities.py b/posthog/temporal/tests/backfill_materialized_property/test_batched_activities.pynew file mode 100644index 000000000000..5f2a4efe04f8--- /dev/null+++ b/posthog/temporal/tests/backfill_materialized_property/test_batched_activities.py@@ -0,0 +1,606 @@+"""Tests for the weekly batched dmat backfill activities (PENDING flow)."""++import pytest+from unittest.mock import MagicMock, patch++from django.conf import settings++from posthog.models import MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition+from posthog.temporal.backfill_materialized_property.activities import (+ ActivateSlotsInputs,+ AssignPendingColumnsInputs,+ FailSlotsInputs,+ PopulateSlotAssignmentsInputs,+ RunBatchedMutationInputs,+ _build_dict_backed_update_command,+ _ColumnAssignment,+ _plan_column_assignments,+ _SlotBranch,+ activate_slots,+ assign_pending_columns,+ compute_cycle_marker_int,+ fail_slots,+ populate_slot_assignments,+ run_batched_mutation,+)++from products.event_definitions.backend.models.property_definition import PropertyType+++def _make_pending_slot(team, name: str) -> MaterializedColumnSlot:+ prop_def = PropertyDefinition.objects.create(+ team=team,+ name=name,+ property_type=PropertyType.String,+ type=PropertyDefinition.Type.EVENT,+ )+ return MaterializedColumnSlot.objects.create(+ team=team,+ property_definition=prop_def,+ slot_index=None,+ state=MaterializedColumnSlotState.PENDING,+ )++[email protected]_db(transaction=True)+class TestPlanColumnAssignments:+ def test_packs_two_teams_into_a_single_column(self, team, organization):+ from posthog.models import Team++ team_a = team+ team_b = Team.objects.create(organization=organization, name="Team B")+ slot_a = _make_pending_slot(team_a, "browser")+ slot_b = _make_pending_slot(team_b, "plan")++ plan = _plan_column_assignments([slot_a, slot_b], used_indexes_by_team={})++ assert len(plan) == 1+ assert plan[0].column_index == 0+ team_ids = {b.team_id for b in plan[0].branches}+ assert team_ids == {team_a.id, team_b.id}++ def test_same_team_with_two_pending_uses_two_columns(self, team):+ slot_one = _make_pending_slot(team, "browser")+ slot_two = _make_pending_slot(team, "utm_source")++ plan = _plan_column_assignments([slot_one, slot_two], used_indexes_by_team={})++ assert {a.column_index for a in plan} == {0, 1}+ # Each column has exactly one branch for this team.+ for assignment in plan:+ assert len(assignment.branches) == 1+ assert assignment.branches[0].team_id == team.id++ def test_skips_columns_already_used_by_team(self, team):+ slot = _make_pending_slot(team, "browser")++ plan = _plan_column_assignments(+ [slot],+ used_indexes_by_team={team.id: {0, 1, 2}},+ )++ assert len(plan) == 1+ assert plan[0].column_index == 3++ def test_assignment_is_deterministic_across_calls(self, team, organization):+ from posthog.models import Team++ team_b = Team.objects.create(organization=organization, name="Team B")+ slots = [+ _make_pending_slot(team_b, "z_prop"),+ _make_pending_slot(team, "a_prop"),+ _make_pending_slot(team, "b_prop"),+ ]++ plan1 = _plan_column_assignments(slots, used_indexes_by_team={})+ plan2 = _plan_column_assignments(slots, used_indexes_by_team={})++ assert [(a.column_index, sorted(a.branches)) for a in plan1] == [+ (a.column_index, sorted(a.branches)) for a in plan2+ ]+++class TestBuildDictBackedUpdateCommand:+ def test_emits_one_set_clause_per_column_with_dict_dispatch(self):+ # Branches list is unused by the dict-backed builder but stays on _ColumnAssignment+ # because the assign_* activities still populate it (vestigial — see plan).+ assignments = [+ _ColumnAssignment(column_index=12, branches=[]),+ _ColumnAssignment(column_index=13, branches=[]),+ ]+ command, params = _build_dict_backed_update_command(assignments, cycle_marker_int=12345)++ # One SET per column, dispatched via dictHas+dictGetString. The trailing dmat_string_<idx>+ # branch is the no-op fallback when the dict has no entry for (team_id, idx).+ assert "dmat_string_12 = if(dictHas(" in command+ assert "dmat_string_13 = if(dictHas(" in command+ # The dictionary key includes column_index so different (team, idx) pairs lookup independently.+ assert "(team_id, 12)" in command+ assert "(team_id, 13)" in command+ assert f"dictGetString('{settings.CLICKHOUSE_DATABASE}.dmat_slot_assignments_dict', 'property_name'," in command+ # Extract wrapper must stay byte-identical to `_generate_property_extraction_sql`.+ assert "replaceRegexpAll(" in command+ assert "JSONExtractRaw(properties," in command++ def test_where_clause_uses_in_subselect_against_dict_table(self):+ assignments = [_ColumnAssignment(column_index=7, branches=[])]+ command, _params = _build_dict_backed_update_command(assignments, cycle_marker_int=99999)++ # The WHERE prunes parts via primary-key team_id IN list, sourced from the dict-source+ # CH table (constant-size SQL regardless of how many teams are in the dict).+ assert (+ f"WHERE team_id IN (SELECT DISTINCT team_id FROM {settings.CLICKHOUSE_DATABASE}.dmat_slot_assignments)"+ in command+ )++ def test_cycle_marker_appears_as_no_op_where_conjunct(self):+ assignments = [_ColumnAssignment(column_index=7, branches=[])]+ command, _params = _build_dict_backed_update_command(assignments, cycle_marker_int=12345)++ # Marker terminates the WHERE so MutationRunner's formatted-SQL dedup distinguishes cycles.+ assert command.endswith("AND 12345 = 12345"), command++ def test_different_cycle_markers_produce_different_sql(self):+ assignments = [_ColumnAssignment(column_index=3, branches=[])]+ command_a, _ = _build_dict_backed_update_command(assignments, cycle_marker_int=1)+ command_b, _ = _build_dict_backed_update_command(assignments, cycle_marker_int=2)+ assert command_a != command_b++ def test_same_cycle_marker_produces_identical_sql(self):+ # Within a cycle, retries must produce byte-identical SQL so MutationRunner reattaches.+ assignments = [_ColumnAssignment(column_index=3, branches=[])]+ command_a, params_a = _build_dict_backed_update_command(assignments, cycle_marker_int=42)+ command_b, params_b = _build_dict_backed_update_command(assignments, cycle_marker_int=42)+ assert command_a == command_b+ assert params_a == params_b++ def test_sql_size_is_independent_of_team_count(self):+ # The point of the dict-based design: SQL stays constant size regardless of adoption.+ # We verify by changing the (vestigial) branches list across runs and asserting size.+ few_teams = [_ColumnAssignment(column_index=3, branches=[_SlotBranch(1, "p", "x")])]+ many_teams = [+ _ColumnAssignment(column_index=3, branches=[_SlotBranch(t, f"prop_{t}", f"slot-{t}") for t in range(1000)])+ ]+ cmd_few, _ = _build_dict_backed_update_command(few_teams, cycle_marker_int=42)+ cmd_many, _ = _build_dict_backed_update_command(many_teams, cycle_marker_int=42)+ assert cmd_few == cmd_many, "dict-backed SQL must not depend on per-column branch count"++ def test_returns_empty_params_dict(self):+ # Property names live in the dict at runtime, not as query parameters.+ assignments = [_ColumnAssignment(column_index=0, branches=[])]+ _command, params = _build_dict_backed_update_command(assignments, cycle_marker_int=1)+ assert params == {}++ def test_empty_assignments_raise(self):+ with pytest.raises(ValueError, match="no assignments"):+ _build_dict_backed_update_command([], cycle_marker_int=1)+++class TestCycleMarkerEmbedding:+ def test_same_workflow_run_id_yields_same_int(self):+ run_id = "01234567-89ab-cdef-0123-456789abcdef"+ assert compute_cycle_marker_int(run_id) == compute_cycle_marker_int(run_id)++ def test_different_workflow_run_ids_yield_different_ints(self):+ a = compute_cycle_marker_int("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")+ b = compute_cycle_marker_int("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")+ assert a != b++ def test_marker_fits_in_32_bits(self):+ marker = compute_cycle_marker_int("any-run-id-here")+ # Embedded as a literal in WHERE — must be a positive 32-bit-ish int so the formatted+ # SQL stays compact and CH treats it as a UInt32 constant.+ assert 0 <= marker < 2**32++[email protected]_db(transaction=True)+class TestAssignPendingColumns:+ def test_transitions_pending_slots_to_backfill_with_indexes(self, team, activity_environment):+ slot_a = _make_pending_slot(team, "browser")+ slot_b = _make_pending_slot(team, "utm_source")++ result = activity_environment.run(+ assign_pending_columns,+ AssignPendingColumnsInputs(run_id="wf-test"),+ )++ assert sorted(result.assigned_slot_ids) == sorted([str(slot_a.id), str(slot_b.id)])+ slot_a.refresh_from_db()+ slot_b.refresh_from_db()+ assert slot_a.state == MaterializedColumnSlotState.BACKFILL+ assert slot_b.state == MaterializedColumnSlotState.BACKFILL+ assert slot_a.slot_index is not None+ assert slot_b.slot_index is not None+ assert slot_a.slot_index != slot_b.slot_index+ assert slot_a.backfill_temporal_run_id == "wf-test"++ def test_no_pending_slots_returns_empty_plan(self, team, activity_environment):+ result = activity_environment.run(+ assign_pending_columns,+ AssignPendingColumnsInputs(run_id="wf-test"),+ )++ assert result.assigned_slot_ids == []+ assert result.assignments == []++ def test_reclaims_backfill_slots_from_the_same_workflow_run(self, team, activity_environment):+ """Activity-retry case: PENDING→BACKFILL committed, but Temporal didn't record completion.+ Re-running the activity must pick up the already-claimed slots and include them in the+ assignment plan so the mutation step still runs against them."""+ prop_def = PropertyDefinition.objects.create(+ team=team,+ name="reclaimable",+ type=PropertyDefinition.Type.EVENT,+ )+ existing = MaterializedColumnSlot.objects.create(+ team=team,+ property_definition=prop_def,+ slot_index=7,+ state=MaterializedColumnSlotState.BACKFILL,+ backfill_temporal_run_id="run-abc",+ )++ result = activity_environment.run(+ assign_pending_columns,+ AssignPendingColumnsInputs(run_id="run-abc"),+ )++ # The reclaimed slot should be in assigned_slot_ids and a column 7 assignment should+ # exist so the mutation runs against the slot's existing column.+ assert str(existing.id) in result.assigned_slot_ids+ assert any(a.column_index == 7 for a in result.assignments), "missing reclaim assignment for column 7"++ def test_does_not_reclaim_backfill_slots_from_a_different_run(self, team, activity_environment):+ """Stranded BACKFILL slots from a previous run are NOT auto-reclaimed — the activity+ logs a warning and an operator handles the recovery via the API. Otherwise we'd risk+ re-running a mutation that may have already completed against a column an operator+ re-purposed."""+ prop_def = PropertyDefinition.objects.create(+ team=team,+ name="stranded",+ type=PropertyDefinition.Type.EVENT,+ )+ stranded = MaterializedColumnSlot.objects.create(+ team=team,+ property_definition=prop_def,+ slot_index=7,+ state=MaterializedColumnSlotState.BACKFILL,+ backfill_temporal_run_id="run-OLD",+ )++ result = activity_environment.run(+ assign_pending_columns,+ AssignPendingColumnsInputs(run_id="run-NEW"),+ )++ assert str(stranded.id) not in result.assigned_slot_ids+ # And the slot stays in BACKFILL with its old run_id intact — operator must intervene.+ stranded.refresh_from_db()+ assert stranded.state == MaterializedColumnSlotState.BACKFILL+ assert stranded.backfill_temporal_run_id == "run-OLD"++ def test_avoids_collisions_with_existing_ready_slot_indexes(self, team, activity_environment):+ # Pre-existing READY slot at index 0 means the new pending slot must land elsewhere.+ existing_prop = PropertyDefinition.objects.create(+ team=team,+ name="existing",+ type=PropertyDefinition.Type.EVENT,+ )+ MaterializedColumnSlot.objects.create(+ team=team,+ property_definition=existing_prop,+ slot_index=0,+ state=MaterializedColumnSlotState.READY,+ )++ new_slot = _make_pending_slot(team, "new_prop")++ activity_environment.run(+ assign_pending_columns,+ AssignPendingColumnsInputs(run_id="wf-test"),+ )++ new_slot.refresh_from_db()+ assert new_slot.slot_index == 1++ def test_reclaimed_slots_pass_through(self, organization, activity_environment):+ """Slots already past the allocation point (BACKFILL with this run's run_id) flow+ through normally so the mutation step re-runs idempotently against them."""+ from posthog.models import Team++ # Reclaimed slot — already in BACKFILL with run_id matching this run.+ reclaim_team = Team.objects.create(organization=organization, name="reclaim_team")+ reclaim_prop = PropertyDefinition.objects.create(+ team=reclaim_team,+ name="reclaimed",+ type=PropertyDefinition.Type.EVENT,+ )+ reclaimed = MaterializedColumnSlot.objects.create(+ team=reclaim_team,+ property_definition=reclaim_prop,+ slot_index=3,+ state=MaterializedColumnSlotState.BACKFILL,+ backfill_temporal_run_id="wf-test",+ )++ result = activity_environment.run(+ assign_pending_columns,+ AssignPendingColumnsInputs(run_id="wf-test"),+ )++ # Reclaimed slot makes it into the assignment plan (mutation will re-run idempotently).+ assert str(reclaimed.id) in result.assigned_slot_ids+ assert any(a.column_index == 3 for a in result.assignments)++[email protected]_db(transaction=True)+class TestActivateAndFailSlots:+ def test_activate_slots_transitions_backfill_to_ready(self, team, activity_environment):+ prop = PropertyDefinition.objects.create(+ team=team,+ name="p",+ type=PropertyDefinition.Type.EVENT,+ )+ slot = MaterializedColumnSlot.objects.create(+ team=team,+ property_definition=prop,+ slot_index=3,+ state=MaterializedColumnSlotState.BACKFILL,+ )++ activated = activity_environment.run(activate_slots, ActivateSlotsInputs(slot_ids=[str(slot.id)]))++ assert activated == 1+ slot.refresh_from_db()+ assert slot.state == MaterializedColumnSlotState.READY++ def test_activate_slots_skips_non_backfill_slots(self, team, activity_environment):+ prop = PropertyDefinition.objects.create(+ team=team,+ name="p",+ type=PropertyDefinition.Type.EVENT,+ )+ # ERROR slot should not be transitioned to READY by activate_slots.+ slot = MaterializedColumnSlot.objects.create(+ team=team,+ property_definition=prop,+ slot_index=3,+ state=MaterializedColumnSlotState.ERROR,+ )++ activated = activity_environment.run(activate_slots, ActivateSlotsInputs(slot_ids=[str(slot.id)]))++ assert activated == 0+ slot.refresh_from_db()+ assert slot.state == MaterializedColumnSlotState.ERROR++ def test_fail_slots_records_error_message(self, team, activity_environment):+ prop = PropertyDefinition.objects.create(+ team=team,+ name="p",+ type=PropertyDefinition.Type.EVENT,+ )+ slot = MaterializedColumnSlot.objects.create(+ team=team,+ property_definition=prop,+ slot_index=4,+ state=MaterializedColumnSlotState.BACKFILL,+ )++ failed = activity_environment.run(+ fail_slots,+ FailSlotsInputs(slot_ids=[str(slot.id)], error_message="ClickHouse OOM"),+ )++ assert failed == 1+ slot.refresh_from_db()+ assert slot.state == MaterializedColumnSlotState.ERROR+ assert slot.error_message == "ClickHouse OOM"++[email protected]_db(transaction=True)+class TestRunBatchedMutation:+ @patch("posthog.temporal.backfill_materialized_property.activities.AlterTableMutationRunner")+ @patch("posthog.temporal.backfill_materialized_property.activities.get_cluster")+ def test_no_op_when_no_assignments(self, mock_get_cluster, mock_runner_cls, activity_environment):+ activity_environment.run(+ run_batched_mutation,+ RunBatchedMutationInputs(assignments=[], cycle_marker_int=1),+ )+ mock_get_cluster.assert_not_called()+ mock_runner_cls.assert_not_called()++ @patch("posthog.temporal.backfill_materialized_property.activities.AlterTableMutationRunner")+ @patch("posthog.temporal.backfill_materialized_property.activities.get_cluster")+ def test_invokes_alter_table_runner_with_dict_backed_command(+ self,+ mock_get_cluster,+ mock_runner_cls,+ activity_environment,+ ):+ assignments = [_ColumnAssignment(column_index=7, branches=[])]+ runner_instance = mock_runner_cls.return_value++ activity_environment.run(+ run_batched_mutation,+ RunBatchedMutationInputs(assignments=assignments, cycle_marker_int=42),+ )++ mock_runner_cls.assert_called_once()+ call_kwargs = mock_runner_cls.call_args.kwargs+ assert call_kwargs["table"] == "sharded_events"+ commands = call_kwargs["commands"]+ assert len(commands) == 1+ (command,) = commands+ # Dict-backed dispatch over the column.+ assert "dmat_string_7 = if(dictHas(" in command+ # Cycle marker appended for cross-cycle dedup.+ assert command.endswith("AND 42 = 42")+ # Empty params: property names live in the dict, not the query.+ assert call_kwargs["parameters"] == {}++ runner_instance.run_on_shards.assert_called_once_with(mock_get_cluster.return_value)++[email protected]_db(transaction=True)+class TestPopulateSlotAssignments:+ """The activity reads READY+BACKFILL slots from Postgres and pushes them as a CH-side+ table that the dmat_slot_assignments_dict reads from. The PENDING-allocation+ workflow calls it after `assign_pending_columns`."""++ def _fake_cluster_with_hosts(self, host_count: int = 3, fail_on_host: int | None = None) -> MagicMock:+ """Build a MagicMock ClickhouseCluster whose `map_all_hosts(fn)` invokes `fn` once per+ synthetic host. If `fail_on_host` is set, that host's call raises, and the FuturesMap's+ .result() raises ExceptionGroup like the real cluster does."""+ cluster = MagicMock()++ def map_all_hosts(fn):+ results: dict[str, object] = {}+ errors: dict[str, Exception] = {}+ for host_idx in range(host_count):+ client = MagicMock()+ try:+ if fail_on_host is not None and host_idx == fail_on_host:+ raise RuntimeError(f"populate failed on host {host_idx}")+ results[f"host-{host_idx}"] = fn(client)+ except Exception as e:+ errors[f"host-{host_idx}"] = e++ futures_map = MagicMock()++ def result():+ if errors:+ raise ExceptionGroup("simulated cluster failure", list(errors.values()))+ return results++ futures_map.result = result+ futures_map.values = lambda: results.values()+ return futures_map++ cluster.map_all_hosts = MagicMock(side_effect=map_all_hosts)+ return cluster++ @patch("posthog.temporal.backfill_materialized_property.activities.get_cluster")+ def test_truncates_inserts_and_reloads_on_every_host(self, mock_get_cluster, team, activity_environment):+ prop_a = PropertyDefinition.objects.create(team=team, name="browser", type=PropertyDefinition.Type.EVENT)+ prop_b = PropertyDefinition.objects.create(team=team, name="plan", type=PropertyDefinition.Type.EVENT)+ MaterializedColumnSlot.objects.create(+ team=team,+ property_definition=prop_a,+ slot_index=3,+ state=MaterializedColumnSlotState.READY,+ )+ MaterializedColumnSlot.objects.create(+ team=team,+ property_definition=prop_b,+ slot_index=7,+ state=MaterializedColumnSlotState.READY,+ )++ # Capture every SQL string each "host" sees so we can assert the order: TRUNCATE, INSERT, RELOAD.+ all_executed: list[list] = []++ def map_all_hosts(fn):+ futures_map = MagicMock()++ def run_per_host():+ results = {}+ for host_idx in range(3):+ executed_per_host: list = []+ client = MagicMock()+ client.execute = lambda sql, *args, _log=executed_per_host: _log.append((sql, args))+ results[f"host-{host_idx}"] = fn(client)+ all_executed.append(executed_per_host)+ return results++ stored = run_per_host()+ futures_map.result = lambda: stored+ futures_map.values = stored.values+ return futures_map++ cluster = MagicMock()+ cluster.map_all_hosts = MagicMock(side_effect=map_all_hosts)+ mock_get_cluster.return_value = cluster++ result = activity_environment.run(populate_slot_assignments, PopulateSlotAssignmentsInputs())++ # Two rows: (team, slot_index=3, browser), (team, slot_index=7, plan).+ assert result.rows_written == 2++ # 3 hosts populated + 3 hosts reloaded → 6 host-fn invocations total.+ # Each populate host sees [TRUNCATE, INSERT]; each reload host sees [RELOAD].+ truncate_count = sum(1 for batch in all_executed for sql, _ in batch if "TRUNCATE TABLE" in sql)+ insert_count = sum(1 for batch in all_executed for sql, _ in batch if "INSERT INTO" in sql)+ reload_count = sum(1 for batch in all_executed for sql, _ in batch if "SYSTEM RELOAD DICTIONARY" in sql)+ assert truncate_count == 3+ assert insert_count == 3+ assert reload_count == 3++ # Within each populate host, TRUNCATE precedes INSERT.+ for batch in all_executed:+ sql_seq = [s for s, _ in batch]+ if any("TRUNCATE TABLE" in s for s in sql_seq):+ truncate_idx = next(i for i, s in enumerate(sql_seq) if "TRUNCATE TABLE" in s)+ insert_idx = next(i for i, s in enumerate(sql_seq) if "INSERT INTO" in s)+ assert truncate_idx < insert_idx++ @patch("posthog.temporal.backfill_materialized_property.activities.get_cluster")+ def test_aborts_before_reload_when_a_host_populate_fails(self, mock_get_cluster, team, activity_environment):+ prop = PropertyDefinition.objects.create(team=team, name="browser", type=PropertyDefinition.Type.EVENT)+ MaterializedColumnSlot.objects.create(+ team=team,+ property_definition=prop,+ slot_index=3,+ state=MaterializedColumnSlotState.READY,+ )++ # First map_all_hosts call (populate) fails on host 1; second call (reload) must never happen.+ call_count = {"map_all_hosts": 0}++ def map_all_hosts(fn):+ call_count["map_all_hosts"] += 1+ futures_map = MagicMock()+ if call_count["map_all_hosts"] == 1:+ # Populate raises on the second host.+ def result():+ raise ExceptionGroup("populate failed", [RuntimeError("host 1 down")])++ futures_map.result = result+ else:+ # Reload should never reach here.+ futures_map.result = MagicMock(return_value={})+ return futures_map++ cluster = MagicMock()+ cluster.map_all_hosts = MagicMock(side_effect=map_all_hosts)+ mock_get_cluster.return_value = cluster++ with pytest.raises(BaseException) as excinfo:+ activity_environment.run(populate_slot_assignments, PopulateSlotAssignmentsInputs())++ # Either the ExceptionGroup itself or the activity's wrapping raises — what matters+ # is that the second map_all_hosts call (reload) never happened.+ assert "populate failed" in str(excinfo.value) or "host 1 down" in str(excinfo.value)+ assert call_count["map_all_hosts"] == 1, "reload must not be issued when populate fails on any host"++ @patch("posthog.temporal.backfill_materialized_property.activities.get_cluster")+ def test_idempotent_under_retry(self, mock_get_cluster, team, activity_environment):+ """Running the activity twice in a row with no Postgres state changes between+ produces the same end state on every host. TRUNCATE+INSERT is end-state idempotent."""+ prop = PropertyDefinition.objects.create(team=team, name="browser", type=PropertyDefinition.Type.EVENT)+ MaterializedColumnSlot.objects.create(+ team=team,+ property_definition=prop,+ slot_index=3,+ state=MaterializedColumnSlotState.READY,+ )++ cluster = self._fake_cluster_with_hosts(host_count=2)+ mock_get_cluster.return_value = cluster++ first = activity_environment.run(populate_slot_assignments, PopulateSlotAssignmentsInputs())+ second = activity_environment.run(populate_slot_assignments, PopulateSlotAssignmentsInputs())++ assert first.rows_written == second.rows_written+ # Two activity invocations × (1 populate + 1 reload) per invocation × per-host execution+ # — what matters is each call dispatched the same operations.diff --git a/posthog/temporal/tests/backfill_materialized_property/test_batched_workflow.py b/posthog/temporal/tests/backfill_materialized_property/test_batched_workflow.pynew file mode 100644index 000000000000..2d34500fdc39--- /dev/null+++ b/posthog/temporal/tests/backfill_materialized_property/test_batched_workflow.py@@ -0,0 +1,221 @@+"""Tests for the dmat batched workflows. Each test stubs every activity by registering+mocks under the real activity's `@activity.defn(name=...)` — renaming a real activity+therefore requires renaming its mock here too.+"""++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 (+ ActivateSlotsInputs,+ AssignPendingColumnsInputs,+ AssignPendingColumnsResult,+ FailSlotsInputs,+ PopulateSlotAssignmentsInputs,+ PopulateSlotAssignmentsResult,+ RunBatchedMutationInputs,+ _ColumnAssignment,+ _SlotBranch,+ compute_cycle_marker_int,+)+from posthog.temporal.backfill_materialized_property.workflows import (+ BackfillMaterializedPropertiesBatchInputs,+ BackfillMaterializedPropertiesBatchWorkflow,+)+++class TestBackfillMaterializedPropertiesBatchWorkflow:+ async def test_happy_path_assigns_runs_mutation_and_activates(self):+ recorded: dict[str, list] = {+ "assign": [],+ "populate": [],+ "mutation": [],+ "activate": [],+ "fail": [],+ }++ sample_assignments = [+ _ColumnAssignment(+ column_index=10,+ branches=[_SlotBranch(1, "browser", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")],+ )+ ]++ @activity.defn(name="assign_pending_columns")+ async def mock_assign(inputs: AssignPendingColumnsInputs) -> AssignPendingColumnsResult:+ recorded["assign"].append(inputs.run_id)+ return AssignPendingColumnsResult(+ assignments=sample_assignments,+ assigned_slot_ids=["aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"],+ )++ @activity.defn(name="populate_slot_assignments")+ async def mock_populate(inputs: PopulateSlotAssignmentsInputs) -> PopulateSlotAssignmentsResult:+ recorded["populate"].append(True)+ return PopulateSlotAssignmentsResult(rows_written=1)++ @activity.defn(name="run_batched_mutation")+ async def mock_run(inputs: RunBatchedMutationInputs) -> None:+ recorded["mutation"].append(+ {+ "assignments": inputs.assignments,+ "cycle_marker_int": inputs.cycle_marker_int,+ }+ )++ @activity.defn(name="activate_slots")+ async def mock_activate(inputs: ActivateSlotsInputs) -> int:+ recorded["activate"].append(inputs.slot_ids)+ return len(inputs.slot_ids)++ @activity.defn(name="fail_slots")+ async def mock_fail(inputs: FailSlotsInputs) -> int:+ recorded["fail"].append(inputs.slot_ids)+ return len(inputs.slot_ids)++ workflow_id = str(uuid.uuid4())+ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[BackfillMaterializedPropertiesBatchWorkflow],+ activities=[mock_assign, mock_populate, mock_run, mock_activate, mock_fail],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ handle = await env.client.start_workflow(+ BackfillMaterializedPropertiesBatchWorkflow.run,+ BackfillMaterializedPropertiesBatchInputs(cache_refresh_wait_seconds=0),+ id=workflow_id,+ task_queue=task_queue,+ )+ await handle.result()+ description = await handle.describe()+ run_id = description.run_id++ assert recorded["assign"], "assign activity should run"+ assert recorded["populate"] == [True], "populate activity should run between assign and mutation"+ assert len(recorded["mutation"]) == 1+ # cycle_marker_int passed through from run_id (NOT workflow_id).+ assert recorded["mutation"][0]["cycle_marker_int"] == compute_cycle_marker_int(run_id)+ assert recorded["mutation"][0]["assignments"] == [+ _ColumnAssignment(+ column_index=10,+ branches=[_SlotBranch(1, "browser", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")],+ )+ ]+ assert recorded["activate"] == [["aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"]]+ assert recorded["fail"] == []++ async def test_no_pending_slots_skips_mutation_and_activation(self):+ recorded: dict[str, list] = {"populate": [], "mutation": [], "activate": []}++ @activity.defn(name="assign_pending_columns")+ async def mock_assign(inputs: AssignPendingColumnsInputs) -> AssignPendingColumnsResult:+ return AssignPendingColumnsResult(assignments=[], assigned_slot_ids=[])++ @activity.defn(name="populate_slot_assignments")+ async def mock_populate(inputs: PopulateSlotAssignmentsInputs) -> PopulateSlotAssignmentsResult:+ recorded["populate"].append(True)+ return PopulateSlotAssignmentsResult(rows_written=0)++ @activity.defn(name="run_batched_mutation")+ async def mock_run(inputs: RunBatchedMutationInputs) -> None:+ recorded["mutation"].append(True)++ @activity.defn(name="activate_slots")+ async def mock_activate(inputs: ActivateSlotsInputs) -> int:+ recorded["activate"].append(True)+ return 0++ @activity.defn(name="fail_slots")+ async def mock_fail(inputs: FailSlotsInputs) -> int:+ return 0++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[BackfillMaterializedPropertiesBatchWorkflow],+ activities=[mock_assign, mock_populate, mock_run, mock_activate, mock_fail],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ await env.client.execute_workflow(+ BackfillMaterializedPropertiesBatchWorkflow.run,+ BackfillMaterializedPropertiesBatchInputs(cache_refresh_wait_seconds=0),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ # Workflow short-circuits before populate / mutation / activate when no PENDING slots.+ assert recorded["populate"] == []+ assert recorded["mutation"] == []+ assert recorded["activate"] == []++ async def test_mutation_failure_marks_slots_as_error(self):+ recorded: dict[str, list] = {"populate": [], "activate": [], "fail": []}++ sample_assignments = [+ _ColumnAssignment(+ column_index=10,+ branches=[_SlotBranch(1, "browser", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")],+ )+ ]++ @activity.defn(name="assign_pending_columns")+ async def mock_assign(inputs: AssignPendingColumnsInputs) -> AssignPendingColumnsResult:+ return AssignPendingColumnsResult(+ assignments=sample_assignments,+ assigned_slot_ids=["aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"],+ )++ @activity.defn(name="populate_slot_assignments")+ async def mock_populate(inputs: PopulateSlotAssignmentsInputs) -> PopulateSlotAssignmentsResult:+ recorded["populate"].append(True)+ return PopulateSlotAssignmentsResult(rows_written=1)++ @activity.defn(name="run_batched_mutation")+ async def mock_run(inputs: RunBatchedMutationInputs) -> None:+ raise ApplicationError("ClickHouse mutation timed out", non_retryable=True)++ @activity.defn(name="activate_slots")+ async def mock_activate(inputs: ActivateSlotsInputs) -> int:+ recorded["activate"].append(inputs.slot_ids)+ return len(inputs.slot_ids)++ @activity.defn(name="fail_slots")+ async def mock_fail(inputs: FailSlotsInputs) -> int:+ recorded["fail"].append((inputs.slot_ids, inputs.error_message))+ return len(inputs.slot_ids)++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[BackfillMaterializedPropertiesBatchWorkflow],+ activities=[mock_assign, mock_populate, mock_run, mock_activate, mock_fail],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ with pytest.raises(Exception):+ await env.client.execute_workflow(+ BackfillMaterializedPropertiesBatchWorkflow.run,+ BackfillMaterializedPropertiesBatchInputs(cache_refresh_wait_seconds=0),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ # Populate ran (it precedes the mutation); failed slots got recorded; activate did NOT run.+ assert recorded["populate"] == [True]+ assert recorded["fail"], "fail_slots should have run"+ assert recorded["fail"][0][0] == ["aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"]+ assert recorded["activate"] == []diff --git a/posthog/temporal/tests/backfill_materialized_property/test_coercion_parity.py b/posthog/temporal/tests/backfill_materialized_property/test_coercion_parity.pynew file mode 100644index 000000000000..a7e5f4102fb4--- /dev/null+++ b/posthog/temporal/tests/backfill_materialized_property/test_coercion_parity.py@@ -0,0 +1,188 @@+"""SQL-side parity tests for the dmat string extraction.++The same fixture file (`coercion_fixtures.json` in the activities package) drives both this+test and the TypeScript-side `create-event.dmat.test.ts`. For each case the SQL extraction+must produce the value listed under `expected_output` — that's the value plugin-server+produces for live ingest, and it's also the value HogQL falls back to for queries on+properties without a materialized slot. Three paths, one fixture, byte-for-byte agreement.++Per the dmat RFC every dmat column is `Nullable(String)`, so this fixture only covers the+string extraction. Type-cast parity (toFloat / toBool / toDateTime applied at HogQL read+time) is covered separately in `test_property_types_dmat.py::TestDmatExtractionConsistency`.++Tests run actual ClickHouse SQL against an inserted row, so any drift between the SQL we+generate and the SQL ClickHouse actually evaluates surfaces here.++Two test classes:++- ``TestCoercionParity`` exercises the bare ``_generate_property_extraction_sql`` shape+ with the property name passed as a query parameter — the same path used by HogQL's+ JSON fallback and by the legacy multiIf-based mutation. Pins the inner-extract+ contract.++- ``TestDictBackedDispatchCoercion`` exercises the full+ ``if(dictHas(...), JSONExtractRaw(properties, dictGetString(...)), col)`` dispatch+ used by the dict-backed mutation introduced for the dictionary-keyed backfill.+ Property name is sourced from the dict at runtime instead of a query parameter, so+ the SQL strings are NOT byte-identical to the bare-extract path — but the runtime+ output must match for every fixture case.+"""++import json+import uuid+from pathlib import Path++import pytest+from posthog.test.base import _create_event, flush_persons_and_events++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,+)+from posthog.temporal.backfill_materialized_property.activities import _generate_property_extraction_sql++FIXTURES_PATH = (+ Path(__file__).resolve().parents[3] / "temporal" / "backfill_materialized_property" / "coercion_fixtures.json"+)+FIXTURES = json.loads(FIXTURES_PATH.read_text())+++def _string_cases():+ for case in FIXTURES["string_cases"]:+ if case.get("_skip_reason"):+ continue+ yield pytest.param(case, id=f"string_cases::{case['name']}")++[email protected]_db(transaction=True)+class TestCoercionParity:+ @pytest.mark.parametrize("case", list(_string_cases()))+ def test_extraction_sql_matches_fixture(self, team, case):+ # Inserts one event per case into `sharded_events`, runs the extraction SELECT,+ # and asserts byte equality with the shared fixture. Slow-ish but the only way to+ # catch SQL-level drift (e.g. a ClickHouse upgrade that changes how `JSONExtractRaw`+ # quotes its output).+ property_name = f"prop_{uuid.uuid4().hex[:8]}"+ _create_event(+ team=team,+ distinct_id="user1",+ event="$test",+ properties={property_name: case["input"]},+ )+ flush_persons_and_events()++ sql = _generate_property_extraction_sql()+ result = sync_execute(+ f"SELECT {sql} FROM sharded_events WHERE team_id = %(team_id)s AND properties LIKE %(prop_marker)s LIMIT 1",+ {+ "team_id": team.id,+ "property_name": property_name,+ "prop_marker": f"%{property_name}%",+ },+ )+ actual = result[0][0] if result else None++ if case["expected_output"] is None:+ assert actual is None, f"Expected NULL, got {actual!r}"+ else:+ assert actual == case["expected_output"], (+ f"SQL output {actual!r} does not match fixture expected {case['expected_output']!r} "+ f"for input {case['input']!r}"+ )+++def _populate_dict(team_id: int, column_index: int, property_name: str) -> None:+ """Replace the dict's contents with a single (team_id, column_index, property_name)+ row, then reload so the next dictGet/dictHas sees the new state. Using TRUNCATE+INSERT+ matches what the populate_slot_assignments activity does in production."""+ sync_execute(TRUNCATE_DMAT_SLOT_ASSIGNMENTS_SQL())+ sync_execute(+ INSERT_DMAT_SLOT_ASSIGNMENTS_SQL(),+ [(team_id, column_index, property_name)],+ )+ sync_execute(RELOAD_DMAT_SLOT_ASSIGNMENTS_DICTIONARY_SQL())+++def _dict_backed_dispatch_sql(column_index: int, fallback_value: str = "NULL") -> str:+ """The full dispatch shape used by the dict-backed mutation. Mirrors+ `_build_dict_backed_update_command` in activities.py; kept inline here so the test+ fails loudly if either side drifts."""+ property_name_expr = (+ f"dictGetString('{DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME}', 'property_name', (team_id, {column_index}))"+ )+ extract_sql = (+ f"replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, {property_name_expr}), ''), 'null'), '^\"|\"$', '')"+ )+ return (+ f"if(dictHas('{DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME}', (team_id, {column_index})), "+ f"{extract_sql}, "+ f"{fallback_value})"+ )++[email protected]_db(transaction=True)+class TestDictBackedDispatchCoercion:+ """The dict-based mutation reads property names out of `dmat_slot_assignments_dict`+ via `dictGetString` instead of a query parameter. Same wrapper, different way of+ sourcing the property name — runtime output must match the bare-extract path for+ every fixture case so plugin-server / HogQL JSON fallback / dict-based backfill+ agree byte-for-byte.+ """++ @pytest.mark.parametrize("case", list(_string_cases()))+ def test_dispatch_extraction_matches_fixture(self, team, case):+ property_name = f"prop_{uuid.uuid4().hex[:8]}"+ column_index = 0+ _create_event(+ team=team,+ distinct_id="user1",+ event="$test",+ properties={property_name: case["input"]},+ )+ flush_persons_and_events()+ _populate_dict(team.id, column_index, property_name)++ dispatch_sql = _dict_backed_dispatch_sql(column_index)+ result = sync_execute(+ f"SELECT {dispatch_sql} FROM sharded_events "+ "WHERE team_id = %(team_id)s AND properties LIKE %(prop_marker)s LIMIT 1",+ {"team_id": team.id, "prop_marker": f"%{property_name}%"},+ )+ actual = result[0][0] if result else None++ if case["expected_output"] is None:+ assert actual is None, f"Expected NULL, got {actual!r}"+ else:+ assert actual == case["expected_output"], (+ f"Dispatch SQL output {actual!r} does not match fixture expected "+ f"{case['expected_output']!r} for input {case['input']!r}"+ )++ def test_empty_dict_falls_through_to_column_value(self, team):+ """When the dict has no entry for (team_id, column_index), the dispatch must+ return the fallback (the column itself in the production builder, NULL here so+ we can assert via SELECT). Confirms the no-op path that protects unrelated+ teams' rows from being clobbered when the mutation runs."""+ sync_execute(TRUNCATE_DMAT_SLOT_ASSIGNMENTS_SQL())+ sync_execute(RELOAD_DMAT_SLOT_ASSIGNMENTS_DICTIONARY_SQL())++ property_name = f"prop_{uuid.uuid4().hex[:8]}"+ _create_event(+ team=team,+ distinct_id="user1",+ event="$test",+ properties={property_name: "should-not-be-extracted"},+ )+ flush_persons_and_events()++ dispatch_sql = _dict_backed_dispatch_sql(column_index=0, fallback_value="NULL")+ result = sync_execute(+ f"SELECT {dispatch_sql} FROM sharded_events "+ "WHERE team_id = %(team_id)s AND properties LIKE %(prop_marker)s LIMIT 1",+ {"team_id": team.id, "prop_marker": f"%{property_name}%"},+ )+ actual = result[0][0] if result else None+ assert actual is None, f"Expected NULL fallback when dict is empty, got {actual!r}"